initial MVP

This commit is contained in:
Mikan
2025-12-08 16:57:25 +03:00
commit 848eb462b5
20 changed files with 398 additions and 0 deletions

16
src/handlers/__init__.py Normal file
View File

@@ -0,0 +1,16 @@
from typing import Dict, Callable, Any
from docx.document import Document
from pathlib import Path
Handler = Callable[[dict, Document, Path, 'StyleRegistry'], None]
HANDLER_REGISTRY: Dict[str, Handler] = {}
def register_handler(node_type: str):
def decorator(fn: Handler):
HANDLER_REGISTRY[node_type] = fn
return fn
return decorator
def get_handler(node_type: str) -> Handler:
return HANDLER_REGISTRY.get(node_type)

84
src/handlers/builtin.py Normal file
View File

@@ -0,0 +1,84 @@
import logging
logger = logging.getLogger(__name__)
from pathlib import Path
from src.handlers import register_handler
from docx.shared import Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH
@register_handler("heading")
def handle_heading(node: dict, doc, images_dir: Path, style_reg):
level = min(node["level"], 3)
text = node["children"][0]["raw"] if node["children"] else ""
doc.add_heading(text, level=level)
p = doc.paragraphs[-1]
style_reg.apply_style(p.style, f"Heading {level}")
def _render_inline_tokens(p, tokens, doc, images_dir, style_reg):
for token in tokens:
if token["type"] == "text":
p.add_run(token["raw"])
elif token["type"] == "strong":
run = p.add_run()
run.bold = True
run.text = token["children"][0]["raw"] if token["children"] else ""
elif token["type"] == "emphasis":
run = p.add_run()
run.italic = True
run.text = token["children"][0]["raw"] if token["children"] else ""
elif token["type"] == "link":
run = p.add_run()
run.text = token["children"][0]["raw"] if token["children"] else ""
run.font.color.rgb = style_reg.get_color("LinkColor")
elif token["type"] == "image":
# Если image внутри параграфа — вызываем обработчик
handle_image(token, doc, images_dir, style_reg)
@register_handler("paragraph")
def handle_paragraph(node: dict, doc, images_dir: Path, style_reg):
p = doc.add_paragraph()
_render_inline_tokens(p, node["children"], doc, images_dir, style_reg)
style_reg.apply_style(p.style, "Normal")
@register_handler("image")
def handle_image(node: dict, doc, images_dir: Path, style_reg):
src = node["src"]
alt = node.get("alt", "")
img_path = images_dir / src
if img_path.exists():
logger.debug(f"Обработка изображения: {img_path}, exists: {img_path.exists()}")
p = doc.add_paragraph()
run = p.add_run()
logger.debug(f"Добавлен параграф: {len(doc.paragraphs)} до add_picture")
try:
run.add_picture(str(img_path), width=Inches(5))
logger.debug("add_picture успешно выполнен")
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
except Exception as e:
logger.error(f"Ошибка при добавлении изображения {img_path}: {e}")
doc.add_paragraph(f"[Изображение не загружено: {src}]")
return
logger.debug(f"После add_picture: {len(doc.paragraphs)} параграфов")
if alt:
try:
cap_p = doc.add_paragraph(alt, style="Caption")
logger.debug(f"Добавлена подпись: {alt}, всего параграфов: {len(doc.paragraphs)}")
except KeyError:
cap_p = doc.add_paragraph(alt)
style_reg.apply_style(cap_p.style, "Caption")
logger.debug(f"Добавлена подпись без стиля: {alt}")
else:
doc.add_paragraph(f"[Изображение не найдено: {src}]")
@register_handler("list")
def handle_list(node: dict, doc, images_dir: Path, style_reg):
ordered = node.get("ordered", False)
for item in node["children"]:
p = doc.add_paragraph(style="List Number" if ordered else "List Bullet")
for child in item["children"]:
if child["type"] == "text":
p.add_run(child["raw"])