fix(etl & ocr): stabilize scud_export syntax/imports, revert to qwen2.5vl:7b-q8_0
This commit is contained in:
@@ -2,51 +2,117 @@
|
||||
===============================================================================
|
||||
FILE: services/office/word_builder.py
|
||||
PROJECT: SCUD Orion AI (Office Domain)
|
||||
ROLE: Сборка форматированного документа MS Word (.docx) из распознанного текста.
|
||||
ROLE: Фаза 3: Сборка форматированного документа MS Word (.docx):
|
||||
- Поддержка нативных таблиц Word (Table Grid) из Markdown.
|
||||
- Специальное выделение блоков рукописных резолюций.
|
||||
- ГОСТ-оформление (Times New Roman, поля, отступы).
|
||||
===============================================================================
|
||||
"""
|
||||
|
||||
import os
|
||||
from typing import List, Dict, Any
|
||||
from docx import Document
|
||||
from docx.shared import Pt, Inches
|
||||
from docx.shared import Pt, Inches, RGBColor
|
||||
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
||||
from docx.oxml import OxmlElement
|
||||
from docx.oxml.ns import qn
|
||||
|
||||
|
||||
def set_cell_margins(cell, top=100, bottom=100, left=150, right=150):
|
||||
"""Устанавливает внутренние поля ячейки таблицы."""
|
||||
tcPr = cell._tc.get_or_add_tcPr()
|
||||
tcMar = OxmlElement('w:tcMar')
|
||||
for m, val in [('top', top), ('bottom', bottom), ('left', left), ('right', right)]:
|
||||
node = OxmlElement(f'w:{m}')
|
||||
node.set(qn('w:w'), str(val))
|
||||
node.set(qn('w:type'), 'dxa')
|
||||
tcMar.append(node)
|
||||
tcPr.append(tcMar)
|
||||
|
||||
|
||||
def build_docx_from_ocr(pages_data: List[Dict[str, Any]], output_filepath: str, doc_title: str = "Распознанный документ") -> str:
|
||||
"""
|
||||
Создает файл .docx по ГОСТ-стандартам делопроизводства:
|
||||
- Шрифт Times New Roman 12-14pt.
|
||||
- Межстрочный интервал 1.15.
|
||||
- Разделители страниц и колонтитулы.
|
||||
"""
|
||||
doc = Document()
|
||||
|
||||
sections = doc.sections
|
||||
for section in sections:
|
||||
# Поля страницы по ГОСТ (2 см по бокам и сверху, 1.5 см справа)
|
||||
for section in doc.sections:
|
||||
section.top_margin = Inches(0.79)
|
||||
section.bottom_margin = Inches(0.79)
|
||||
section.left_margin = Inches(0.79)
|
||||
section.right_margin = Inches(0.59)
|
||||
|
||||
for p_idx, page in enumerate(pages_data):
|
||||
page_num = page.get("page", p_idx + 1)
|
||||
text_content = page.get("text", "")
|
||||
|
||||
if p_idx > 0:
|
||||
doc.add_page_break()
|
||||
|
||||
lines = text_content.splitlines()
|
||||
table_buffer = []
|
||||
|
||||
def flush_table():
|
||||
nonlocal table_buffer
|
||||
if not table_buffer:
|
||||
return
|
||||
|
||||
parsed_rows = []
|
||||
for t_line in table_buffer:
|
||||
cells = [c.strip() for c in t_line.strip().strip('|').split('|')]
|
||||
# Пропускаем разделительные строки Markdown (|---|---|)
|
||||
if any(cells) and not all(set(c).issubset({'-', ':', ' '}) for c in cells):
|
||||
parsed_rows.append(cells)
|
||||
|
||||
if parsed_rows:
|
||||
num_cols = max(len(r) for r in parsed_rows)
|
||||
tbl = doc.add_table(rows=len(parsed_rows), cols=num_cols)
|
||||
tbl.style = 'Table Grid'
|
||||
|
||||
for r_idx, row_data in enumerate(parsed_rows):
|
||||
for c_idx in range(num_cols):
|
||||
val = row_data[c_idx] if c_idx < len(row_data) else ""
|
||||
cell = tbl.cell(r_idx, c_idx)
|
||||
cell.text = val
|
||||
set_cell_margins(cell)
|
||||
for para in cell.paragraphs:
|
||||
para.paragraph_format.line_spacing = 1.05
|
||||
para.paragraph_format.space_after = Pt(2)
|
||||
for run in para.runs:
|
||||
run.font.name = "Times New Roman"
|
||||
run.font.size = Pt(10)
|
||||
if r_idx == 0:
|
||||
run.font.bold = True
|
||||
|
||||
table_buffer = []
|
||||
|
||||
for line in lines:
|
||||
line_str = line.strip()
|
||||
if not line_str:
|
||||
flush_table()
|
||||
continue
|
||||
|
||||
# Детекция строки Markdown-таблицы
|
||||
if line_str.startswith('|') and line_str.endswith('|'):
|
||||
table_buffer.append(line_str)
|
||||
continue
|
||||
else:
|
||||
flush_table()
|
||||
|
||||
# Обработка блока рукописной резолюции
|
||||
if line_str.startswith('[Резолюция:') or line_str.startswith('Резолюция:'):
|
||||
p = doc.add_paragraph()
|
||||
p.paragraph_format.space_after = Pt(6)
|
||||
p.paragraph_format.line_spacing = 1.15
|
||||
run = p.add_run(f"✍️ {line_str}")
|
||||
run.font.name = "Times New Roman"
|
||||
run.font.size = Pt(11)
|
||||
run.font.italic = True
|
||||
run.font.color.rgb = RGBColor(15, 76, 129) # Классический синий цвет визы
|
||||
continue
|
||||
|
||||
p = doc.add_paragraph()
|
||||
p.paragraph_format.space_after = Pt(3)
|
||||
p.paragraph_format.space_after = Pt(4)
|
||||
p.paragraph_format.line_spacing = 1.15
|
||||
|
||||
if any(h in line_str.upper() for h in ["ПРЕДСЕДАТЕЛЬСТВОВАЛ", "ПРОТОКОЛ", "ПОВЕСТКА", "РЕШИЛИ:", "ОТМЕТИЛИ:"]):
|
||||
# Выравнивание заголовков
|
||||
if any(h in line_str.upper() for h in ["ПРЕДСЕДАТЕЛЬСТВОВАЛ", "ПРОТОКОЛ", "ПОВЕСТКА", "РЕШИЛИ:", "ОТМЕТИЛИ:", "СПИСОК УЧАСТНИКОВ"]):
|
||||
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||
run = p.add_run(line_str)
|
||||
run.font.name = "Times New Roman"
|
||||
@@ -58,6 +124,8 @@ def build_docx_from_ocr(pages_data: List[Dict[str, Any]], output_filepath: str,
|
||||
run.font.name = "Times New Roman"
|
||||
run.font.size = Pt(12)
|
||||
|
||||
flush_table()
|
||||
|
||||
os.makedirs(os.path.dirname(output_filepath), exist_ok=True)
|
||||
doc.save(output_filepath)
|
||||
return output_filepath
|
||||
Reference in New Issue
Block a user