87 lines
3.0 KiB
Python
87 lines
3.0 KiB
Python
"""
|
|
===============================================================================
|
|
FILE: services/office/service.py
|
|
ROLE: Детерминированная сборка Word без галлюцинаций.
|
|
===============================================================================
|
|
"""
|
|
|
|
import os
|
|
import re
|
|
import uuid
|
|
import logging
|
|
from typing import Dict, Any
|
|
|
|
from config import BASE_DIR
|
|
from .document_extractor import process_pdf_full
|
|
from .word_builder import build_docx_from_ocr
|
|
|
|
logger = logging.getLogger("OFFICE_SERVICE")
|
|
|
|
OFFICE_OUTPUT_DIR = os.path.join(BASE_DIR, "output", "web", "office")
|
|
os.makedirs(OFFICE_OUTPUT_DIR, exist_ok=True)
|
|
|
|
|
|
def clean_page_text(text: str, page_num: int) -> str:
|
|
"""Детерминированная очистка страницы от шума и галлюцинаций."""
|
|
lines = text.splitlines()
|
|
cleaned_lines = []
|
|
|
|
for line in lines:
|
|
l = line.strip()
|
|
if not l:
|
|
cleaned_lines.append("")
|
|
continue
|
|
|
|
# 1. Срезаем фантомные резолюции со всех страниц, кроме 1 и 2
|
|
if page_num > 2 and any(k in l.lower() for k in ["резолюция:", "рукописный текст:"]):
|
|
continue
|
|
|
|
# 2. Срезаем приветствия
|
|
if any(l.lower().startswith(g) for g in ["спасибо за", "здравствуйте", "вот текст"]):
|
|
continue
|
|
|
|
# 3. Убираем markdown-обертки ```
|
|
if l.startswith("```"):
|
|
continue
|
|
|
|
cleaned_lines.append(l)
|
|
|
|
return "\n".join(cleaned_lines).strip()
|
|
|
|
|
|
def convert_pdf_to_word_service(file_path: str, original_filename: str) -> Dict[str, Any]:
|
|
session_id = str(uuid.uuid4())[:8]
|
|
base_name = os.path.splitext(os.path.basename(original_filename))[0]
|
|
out_docx_name = f"{base_name}_распознан.docx"
|
|
|
|
target_dir = os.path.join(OFFICE_OUTPUT_DIR, session_id)
|
|
os.makedirs(target_dir, exist_ok=True)
|
|
out_docx_path = os.path.join(target_dir, out_docx_name)
|
|
|
|
# Постраничный честный OCR без фантазий
|
|
raw_pages = process_pdf_full(file_path)
|
|
|
|
sanitized_pages = []
|
|
for p in raw_pages:
|
|
p_num = p.get("page", 1)
|
|
cleaned = clean_page_text(p.get("text", ""), page_num=p_num)
|
|
sanitized_pages.append({
|
|
"page": p_num,
|
|
"text": cleaned
|
|
})
|
|
|
|
# Сборка в Word
|
|
build_docx_from_ocr(sanitized_pages, out_docx_path, doc_title=base_name)
|
|
|
|
preview_sample = sanitized_pages[0]["text"][:600] if sanitized_pages else "Документ распознан."
|
|
download_url = f"/api/v1/files/download/office/{session_id}/{out_docx_name}"
|
|
|
|
return {
|
|
"status": "success",
|
|
"total_pages": len(sanitized_pages),
|
|
"filename": out_docx_name,
|
|
"filepath": out_docx_path,
|
|
"download_url": download_url,
|
|
"preview_text": preview_sample,
|
|
"message": f"Документ точно распознан ({len(sanitized_pages)} стр.) без искажений."
|
|
} |