"""附件内容提取服务 - 从上传的文件中提取文本内容供分析""" import os from pathlib import Path def extract_text_from_file(file_path: str) -> str: """根据文件类型提取文本内容 Args: file_path: 本地文件路径 Returns: 提取的文本内容,失败返回空字符串 """ if not file_path or not os.path.exists(file_path): return "" ext = Path(file_path).suffix.lower() if ext == '.txt': return _extract_txt(file_path) elif ext in ['.docx', '.doc']: return _extract_docx(file_path) elif ext == '.pdf': return _extract_pdf(file_path) elif ext in ['.xlsx', '.xls']: return _extract_excel(file_path) elif ext in ['.csv']: return _extract_csv(file_path) else: return f"【无法解析的文件格式:{ext},请将内容复制到正文】" def _extract_txt(file_path: str) -> str: """提取 TXT 文件内容""" try: with open(file_path, 'r', encoding='utf-8') as f: return f.read() except UnicodeDecodeError: try: with open(file_path, 'r', encoding='gbk') as f: return f.read() except Exception: return "" except Exception: return "" def _extract_docx(file_path: str) -> str: """提取 Word 文档内容""" try: from docx import Document doc = Document(file_path) paragraphs = [p.text for p in doc.paragraphs if p.text.strip()] return '\n'.join(paragraphs) except ImportError: return "【需要安装 python-docx 库以解析 Word 文档】" except Exception: return "" def _extract_pdf(file_path: str) -> str: """提取 PDF 文件内容""" try: # 尝试使用 PyPDF2 try: from PyPDF2 import PdfReader reader = PdfReader(file_path) texts = [] for page in reader.pages: text = page.extract_text() if text: texts.append(text) return '\n'.join(texts) except ImportError: pass # 尝试使用 pdfplumber try: import pdfplumber texts = [] with pdfplumber.open(file_path) as pdf: for page in pdf.pages: text = page.extract_text() if text: texts.append(text) return '\n'.join(texts) except ImportError: pass return "【需要安装 PyPDF2 或 pdfplumber 库以解析 PDF 文件】" except Exception: return "" def _extract_excel(file_path: str) -> str: """提取 Excel 文件内容""" try: from openpyxl import load_workbook wb = load_workbook(file_path, data_only=True) texts = [] for sheet in wb.worksheets: texts.append(f"【工作表:{sheet.title}】") for row in sheet.iter_rows(values_only=True): row_text = ' | '.join(str(cell) for cell in row if cell is not None) if row_text.strip(): texts.append(row_text) return '\n'.join(texts) except ImportError: return "【需要安装 openpyxl 库以解析 Excel 文件】" except Exception: return "" def _extract_csv(file_path: str) -> str: """提取 CSV 文件内容""" try: import csv with open(file_path, 'r', encoding='utf-8') as f: reader = csv.reader(f) texts = [] for row in reader: texts.append(' | '.join(row)) return '\n'.join(texts) except UnicodeDecodeError: try: with open(file_path, 'r', encoding='gbk') as f: reader = csv.reader(f) texts = [] for row in reader: texts.append(' | '.join(row)) return '\n'.join(texts) except Exception: return "" except Exception: return "" def extract_from_doc_attachments(doc: dict, download_func) -> str: """从审计资料记录的附件中提取内容 Args: doc: 审计资料记录字典(包含"附件"字段) download_func: 下载附件的函数,签名 download_func(doc_id, file_token, output_dir) -> file_path Returns: 提取的文本内容 """ att_field = doc.get("附件") if not att_field: return "" # 解析附件字段 attachments = [] if isinstance(att_field, list): for a in att_field: if isinstance(a, dict): attachments.append(a) elif isinstance(a, str): attachments.append({"name": a, "file_token": "", "size": 0}) elif isinstance(att_field, str): attachments.append({"name": att_field, "file_token": "", "size": 0}) if not attachments: return "" all_texts = [] for att in attachments: file_token = att.get("file_token", "") name = att.get("name", "未知文件") if not file_token: continue try: # 下载附件 from config import UPLOAD_DIR download_dir = os.path.join(UPLOAD_DIR, "downloads") os.makedirs(download_dir, exist_ok=True) saved_path = download_func(doc["id"], file_token, download_dir) if saved_path and os.path.exists(saved_path): # 提取文本 text = extract_text_from_file(saved_path) if text: all_texts.append(f"### 附件:{name}\n{text}") except Exception as e: print(f"提取附件 {name} 内容失败: {e}") continue return "\n\n---\n\n".join(all_texts) if all_texts else ""