Restore full pipeline: 3-step summarization, formatting, PDF/DOCX generation
This commit is contained in:
@@ -5,9 +5,9 @@ import logging
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any, List, Tuple
|
||||
from ..core import FileProcessingError
|
||||
from ..config import settings
|
||||
from ..services.ai import ai_provider_factory
|
||||
from core import FileProcessingError
|
||||
from config import settings
|
||||
from services.ai import ai_provider_factory
|
||||
|
||||
|
||||
class DocumentGenerator:
|
||||
@@ -22,8 +22,79 @@ class DocumentGenerator:
|
||||
self.logger.info(f"Generating summary for {base_name}")
|
||||
|
||||
try:
|
||||
# Generate summary
|
||||
summary = self.ai_provider.summarize(text)
|
||||
# Step 1: Generate Bullet Points (Chunking handled by provider or single prompt for now)
|
||||
# Note: We use the main provider (Claude/Zai) for content generation
|
||||
self.logger.info("Generating bullet points...")
|
||||
bullet_prompt = f"""Analiza el siguiente texto y extrae entre 5 y 8 bullet points clave en español.
|
||||
|
||||
REGLAS ESTRICTAS:
|
||||
1. Devuelve ÚNICAMENTE bullet points, cada línea iniciando con "- "
|
||||
2. Cada bullet debe ser conciso (12-20 palabras) y resaltar datos, fechas, conceptos o conclusiones importantes
|
||||
3. NO agregues introducciones, conclusiones ni texto explicativo
|
||||
4. Concéntrate en los puntos más importantes del texto
|
||||
5. Incluye fechas, datos específicos y nombres relevantes si los hay
|
||||
|
||||
Texto:
|
||||
{text[:15000]}""" # Truncate to avoid context limits if necessary, though providers handle it differently
|
||||
|
||||
try:
|
||||
bullet_points = self.ai_provider.generate_text(bullet_prompt)
|
||||
self.logger.info(f"Bullet points generated: {len(bullet_points)}")
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Bullet point generation failed: {e}")
|
||||
bullet_points = "- Puntos clave no disponibles por error en IA"
|
||||
|
||||
# Step 2: Generate Unified Summary
|
||||
self.logger.info("Generating unified summary...")
|
||||
summary_prompt = f"""Eres un profesor universitario experto en historia del siglo XX. Redacta un resumen académico integrado en español usando el texto y los bullet points extraídos.
|
||||
|
||||
REQUISITOS ESTRICTOS:
|
||||
- Extensión entre 500-700 palabras
|
||||
- Usa encabezados Markdown con jerarquía clara (##, ###)
|
||||
- Desarrolla los puntos clave con profundidad y contexto histórico
|
||||
- Mantén un tono académico y analítico
|
||||
- Incluye conclusiones significativas
|
||||
- NO agregues texto fuera del resumen
|
||||
- Devuelve únicamente el resumen en formato Markdown
|
||||
|
||||
Contenido a resumir:
|
||||
{text[:20000]}
|
||||
|
||||
Puntos clave a incluir obligatoriamente:
|
||||
{bullet_points}"""
|
||||
|
||||
try:
|
||||
raw_summary = self.ai_provider.generate_text(summary_prompt)
|
||||
except Exception as e:
|
||||
self.logger.error(f"Raw summary generation failed: {e}")
|
||||
raise e
|
||||
|
||||
# Step 3: Format with Gemini (using GeminiProvider explicitly)
|
||||
self.logger.info("Formatting summary with Gemini...")
|
||||
format_prompt = f"""Revisa y mejora el siguiente resumen en Markdown para que sea perfectamente legible:
|
||||
|
||||
{raw_summary}
|
||||
|
||||
Instrucciones:
|
||||
- Corrige cualquier error de formato
|
||||
- Asegúrate de que los encabezados estén bien espaciados
|
||||
- Verifica que las viñetas usen "- " correctamente
|
||||
- Mantén exactamente el contenido existente
|
||||
- Devuelve únicamente el resumen formateado sin texto adicional"""
|
||||
|
||||
# Use generic Gemini provider for formatting as requested
|
||||
from services.ai.gemini_provider import GeminiProvider
|
||||
formatter = GeminiProvider()
|
||||
|
||||
try:
|
||||
if formatter.is_available():
|
||||
summary = formatter.generate_text(format_prompt)
|
||||
else:
|
||||
self.logger.warning("Gemini formatter not available, using raw summary")
|
||||
summary = raw_summary
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Formatting failed ({e}), using raw summary")
|
||||
summary = raw_summary
|
||||
|
||||
# Generate filename
|
||||
filename = self._generate_filename(text, summary)
|
||||
@@ -45,7 +116,7 @@ class DocumentGenerator:
|
||||
return True, summary, metadata
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"Summary generation failed: {e}")
|
||||
self.logger.error(f"Document generation process failed: {e}")
|
||||
return False, "", {}
|
||||
|
||||
def _generate_filename(self, text: str, summary: str) -> str:
|
||||
|
||||
Reference in New Issue
Block a user