"""文件解析服务。 Excel/PDF 文件解析 → 文本提取。 """ async def parse_excel(file_bytes: bytes) -> str: """解析 Excel 文件,提取文本内容。""" try: import openpyxl import io wb = openpyxl.load_workbook(io.BytesIO(file_bytes), read_only=True) texts: list[str] = [] for sheet in wb.sheetnames: ws = wb[sheet] for row in ws.iter_rows(values_only=True): row_text = " | ".join(str(c) for c in row if c is not None) if row_text.strip(): texts.append(row_text) return "\n".join(texts) except Exception: return "" async def parse_pdf(file_bytes: bytes) -> str: """解析 PDF 文件,提取文本内容。""" try: import fitz import io doc = fitz.open(stream=io.BytesIO(file_bytes), filetype="pdf") texts: list[str] = [] for page in doc: texts.append(page.get_text()) return "\n".join(texts) except Exception: return "" async def parse_file(file_bytes: bytes, filename: str) -> str: """根据文件类型选择解析器。""" if filename.endswith((".xlsx", ".xls")): return await parse_excel(file_bytes) elif filename.endswith(".pdf"): return await parse_pdf(file_bytes) elif filename.endswith((".txt", ".md", ".csv")): return file_bytes.decode("utf-8", errors="ignore") return ""