fix(etl & ocr): stabilize scud_export syntax/imports, revert to qwen2.5vl:7b-q8_0
This commit is contained in:
@@ -1,88 +1,127 @@
|
||||
import base64
|
||||
"""
|
||||
===============================================================================
|
||||
FILE: modules/web_api/llm/file_parser.py
|
||||
ROLE: Изолированный сервис извлечения содержимого из PDF, таблиц и сканов.
|
||||
===============================================================================
|
||||
"""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import base64
|
||||
import logging
|
||||
import pandas as pd
|
||||
from typing import Dict, Any, List
|
||||
|
||||
logger = logging.getLogger("FILE_PARSER")
|
||||
|
||||
def extract_text_from_file(file_bytes: bytes, filename: str) -> dict:
|
||||
ext = os.path.splitext(filename)[1].lower()
|
||||
temp_filepath = f"/tmp/upload_{os.getpid()}_{filename}"
|
||||
|
||||
with open(temp_filepath, "wb") as f:
|
||||
f.write(file_bytes)
|
||||
|
||||
def extract_content_from_pdf(file_path: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Извлекает текст из многостраничного PDF.
|
||||
Если текстовый слой присутствует, собирает все страницы без обрезания.
|
||||
Если текст отсутствует (чистый скан), подготавливает страницы для Vision OCR.
|
||||
"""
|
||||
text_pages = []
|
||||
|
||||
# 1. Попытка чтения через pypdf
|
||||
try:
|
||||
# 1. ИЗОБРАЖЕНИЯ (.png, .jpg, .jpeg, .bmp, .webp) -> Кодируем в Base64 для Vision LLM
|
||||
if ext in ['.png', '.jpg', '.jpeg', '.bmp', '.webp']:
|
||||
b64_str = base64.b64encode(file_bytes).decode('utf-8')
|
||||
return {
|
||||
"text": f"[ПРИКРЕПЛЕНО ИЗОБРАЖЕНИЕ: {filename}]",
|
||||
"image_b64": b64_str
|
||||
}
|
||||
|
||||
# 2. PDF ДОКУМЕНТЫ (Конвертируем 1-ю страницу в картинку для Vision LLM)
|
||||
elif ext == '.pdf':
|
||||
cmd = ['pdftotext', temp_filepath, '-']
|
||||
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
pdf_text = res.stdout.strip()
|
||||
|
||||
img_prefix = f"/tmp/pdf_preview_{os.getpid()}"
|
||||
subprocess.run(['pdftoppm', '-png', '-r', '200', '-f', '1', '-l', '1', temp_filepath, img_prefix], check=True)
|
||||
|
||||
page_png = f"{img_prefix}-1.png"
|
||||
b64_str = None
|
||||
if os.path.exists(page_png):
|
||||
with open(page_png, "rb") as pf:
|
||||
b64_str = base64.b64encode(pf.read()).decode('utf-8')
|
||||
os.remove(page_png)
|
||||
|
||||
context_text = f"[ПРИКРЕПЛЕН ДОКУМЕНТ PDF: {filename}]"
|
||||
if pdf_text:
|
||||
context_text += f"\n\n[ЭЛЕКТРОННЫЙ ТЕКСТОВЫЙ СЛОЙ PDF]:\n{pdf_text}"
|
||||
|
||||
return {
|
||||
"text": context_text,
|
||||
"image_b64": b64_str
|
||||
}
|
||||
|
||||
# 3. ЭЛЕКТРОННЫЕ ТАБЛИЦЫ (.xlsx, .xls, .csv)
|
||||
elif ext in ['.xlsx', '.xls', '.csv']:
|
||||
if ext == '.csv':
|
||||
df = pd.read_csv(temp_filepath)
|
||||
else:
|
||||
df = pd.read_excel(temp_filepath)
|
||||
|
||||
total_rows = len(df)
|
||||
df_preview = df.head(100)
|
||||
table_str = df_preview.to_string(index=False)
|
||||
note = f"\n(Показано первых 100 строк из {total_rows})" if total_rows > 100 else ""
|
||||
return {
|
||||
"text": f"[СОДЕРЖИМОЕ ТАБЛИЦЫ {filename}]:\n{table_str}{note}",
|
||||
"image_b64": None
|
||||
}
|
||||
|
||||
# 4. ТЕКСТОВЫЕ ФАЙЛЫ
|
||||
elif ext in ['.txt', '.log', '.json', '.xml', '.md']:
|
||||
with open(temp_filepath, 'r', encoding='utf-8', errors='replace') as tf:
|
||||
return {
|
||||
"text": tf.read().strip(),
|
||||
"image_b64": None
|
||||
}
|
||||
|
||||
else:
|
||||
return {
|
||||
"text": f"[ОШИБКА: Формат {ext} не поддерживается]",
|
||||
"image_b64": None
|
||||
}
|
||||
|
||||
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.error(f"Ошибка при анализе файла {filename}: {e}")
|
||||
logger.warning(f"Ошибка pypdf при чтении {file_path}: {e}")
|
||||
|
||||
full_text = "\n\n".join(text_pages).strip()
|
||||
|
||||
# 2. Если текста достаточно — отдаем чистый извлеченный текст
|
||||
if len(full_text) > 100:
|
||||
return {
|
||||
"text": f"[ОШИБКА ОБРАБОТКИ ФАЙЛА: {str(e)}]",
|
||||
"image_b64": None
|
||||
"has_text": True,
|
||||
"text": full_text,
|
||||
"image_b64": None,
|
||||
"pages_count": len(text_pages)
|
||||
}
|
||||
finally:
|
||||
if os.path.exists(temp_filepath):
|
||||
os.remove(temp_filepath)
|
||||
|
||||
# 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"}
|
||||
Reference in New Issue
Block a user