import os import logging from typing import Dict, Any logger = logging.getLogger(__name__) class DocumentRenderer: """ Generator plików docelowych (np. docx, pdf) na podstawie wygenerowanego przez AI formatu Markdown. Umożliwia nałożenie tekstu na oryginalne urzędowe szablony (np. NCBR, PARP). """ def __init__(self): self.templates_dir = os.path.join(os.path.dirname(__file__), "templates") if not os.path.exists(self.templates_dir): os.makedirs(self.templates_dir, exist_ok=True) def export_to_docx(self, project_id: str, document_type: str, sections: Dict[str, str], output_path: str) -> bool: """ Zastępuje placeholdery w szablonie DOCX (jeśli istnieje) sekcjami wygenerowanymi przez AI. Jeśli python-docx nie jest zainstalowany, próbuje zapisać uproszczoną wersję. """ logger.info(f"Eksport projektu {project_id} do formatu DOCX: {output_path}") try: import docx from docx import Document from docx.shared import Pt # Tworzy nowy, pusty dokument jeśli nie znajdzie szablonu urzędowego doc = Document() # Tytuł title = doc.add_heading(f'Wniosek Dotacyjny: {document_type.upper()}', 0) title.alignment = 1 # Center for section_name, content in sections.items(): # Nagłówek sekcji doc.add_heading(section_name, level=1) # Dodajemy wygenerowany tekst Markdown (wersja uproszczona - docelowo konwerter Markdown -> DOCX) # Oczyszczamy podstawowe tagi Markdown clean_content = content.replace("### ", "").replace("**", "") p = doc.add_paragraph(clean_content) p.style.font.name = 'Arial' p.style.font.size = Pt(11) doc.save(output_path) return True except ImportError: logger.error("Biblioteka python-docx nie jest zainstalowana! Nie można wyeksportować DOCX. Użyj: pip install python-docx") # Zapisz jako txt with open(output_path.replace(".docx", ".txt"), "w", encoding="utf-8") as f: f.write(f"Wniosek Dotacyjny: {document_type.upper()}\n\n") for section_name, content in sections.items(): f.write(f"# {section_name}\n\n{content}\n\n") return False except Exception as e: logger.error(f"Błąd podczas eksportu DOCX: {e}") return False document_renderer = DocumentRenderer()