Files
scud_ai/modules/web_api/llm/file_parser.py

127 lines
4.9 KiB
Python

"""
===============================================================================
FILE: modules/web_api/llm/file_parser.py
ROLE: Изолированный сервис извлечения содержимого из PDF, таблиц и сканов.
===============================================================================
"""
import os
import base64
import logging
from typing import Dict, Any, List
logger = logging.getLogger("FILE_PARSER")
def extract_content_from_pdf(file_path: str) -> Dict[str, Any]:
"""
Извлекает текст из многостраничного PDF.
Если текстовый слой присутствует, собирает все страницы без обрезания.
Если текст отсутствует (чистый скан), подготавливает страницы для Vision OCR.
"""
text_pages = []
# 1. Попытка чтения через pypdf
try:
import pypdf
reader = pypdf.PdfReader(file_path)
for idx, page in enumerate(reader.pages, start=1):
t = page.extract_text() or ""
if t.strip():
text_pages.append(f"--- Страница {idx} ---\n{t.strip()}")
except Exception as e:
logger.warning(f"Ошибка pypdf при чтении {file_path}: {e}")
full_text = "\n\n".join(text_pages).strip()
# 2. Если текста достаточно — отдаем чистый извлеченный текст
if len(full_text) > 100:
return {
"has_text": True,
"text": full_text,
"image_b64": None,
"pages_count": len(text_pages)
}
# 3. Если текста мало или это чистый скан — рендерим первую страницу через PyMuPDF для Vision
image_b64 = None
try:
import fitz # PyMuPDF
doc = fitz.open(file_path)
if len(doc) > 0:
page = doc[0]
pix = page.get_pixmap(dpi=150)
image_b64 = base64.b64encode(pix.tobytes("png")).decode("utf-8")
except Exception as e:
logger.warning(f"Ошибка PyMuPDF при рендеринге страницы: {e}")
return {
"has_text": bool(full_text),
"text": full_text,
"image_b64": image_b64,
"pages_count": len(text_pages) if text_pages else 1
}
def parse_uploaded_file(file_path: str, filename: str) -> Dict[str, Any]:
"""
Главная точка входа разбора входящего файла.
"""
ext = os.path.splitext(filename)[1].lower()
# 1. PDF
if ext == ".pdf":
pdf_res = extract_content_from_pdf(file_path)
return {
"context_text": pdf_res["text"],
"image_b64": pdf_res["image_b64"],
"type": "PDF",
"is_pure_text": pdf_res["has_text"] and not pdf_res["image_b64"]
}
# 2. Изображения (сканы / фотографии)
elif ext in [".png", ".jpg", ".jpeg", ".webp", ".bmp"]:
try:
with open(file_path, "rb") as f:
b64 = base64.b64encode(f.read()).decode("utf-8")
return {
"context_text": f"[Прикреплено изображение: {filename}]",
"image_b64": b64,
"type": "IMAGE",
"is_pure_text": False
}
except Exception as e:
return {"context_text": "", "image_b64": None, "type": "ERROR", "error": str(e)}
# 3. Электронные таблицы Excel / CSV
elif ext in [".xlsx", ".xls", ".csv"]:
try:
import pandas as pd
df = pd.read_csv(file_path) if ext == ".csv" else pd.read_excel(file_path)
rows_cnt = len(df)
preview = df.head(150).to_string(index=False)
note = f"\n(Показано первых 150 строк из {rows_cnt})" if rows_cnt > 150 else ""
return {
"context_text": f"[Таблица {filename}]:\n{preview}{note}",
"image_b64": None,
"type": "SPREADSHEET",
"is_pure_text": True
}
except Exception as e:
return {"context_text": "", "image_b64": None, "type": "ERROR", "error": str(e)}
# 4. Текстовые файлы
elif ext in [".txt", ".log", ".md", ".json", ".xml"]:
try:
with open(file_path, "r", encoding="utf-8", errors="replace") as f:
content = f.read()
return {
"context_text": content,
"image_b64": None,
"type": "TEXT",
"is_pure_text": True
}
except Exception as e:
return {"context_text": "", "image_b64": None, "type": "ERROR", "error": str(e)}
return {"context_text": "", "image_b64": None, "type": "UNKNOWN"}