gateway/modules/services/serviceGeneration/renderers/csv_renderer.py
2025-10-06 15:39:25 +02:00

64 lines
2.4 KiB
Python

"""
CSV renderer for report generation.
"""
from .base_renderer import BaseRenderer
from typing import Dict, Any, Tuple, List
import csv
import io
class CsvRenderer(BaseRenderer):
"""Renders content to CSV format with format-specific extraction."""
@classmethod
def get_supported_formats(cls) -> List[str]:
"""Return supported CSV formats."""
return ['csv']
@classmethod
def get_format_aliases(cls) -> List[str]:
"""Return format aliases."""
return ['spreadsheet', 'table']
@classmethod
def get_priority(cls) -> int:
"""Return priority for CSV renderer."""
return 70
def getExtractionPrompt(self, user_prompt: str, title: str) -> str:
"""Return only CSV-specific guidelines; global prompt is built centrally."""
return (
"CSV FORMAT GUIDELINES:\n"
"- Emit ONLY CSV text without fences or commentary.\n"
"- Include a single header row with clear column names.\n"
"- Quote fields containing commas, quotes, or newlines; escape quotes by doubling them.\n"
"- Use rows to represent items/records derived from sources.\n"
"- Keep cells concise; include units in headers when useful.\n"
"OUTPUT: Return ONLY valid CSV content that can be imported."
)
async def render(self, extracted_content: str, title: str) -> Tuple[str, str]:
"""Render extracted content to CSV format."""
try:
# The extracted content should already be CSV from the AI
# Just clean it up
csv_content = self._clean_csv_content(extracted_content, title)
return csv_content, "text/csv"
except Exception as e:
self.logger.error(f"Error rendering CSV: {str(e)}")
# Return minimal CSV fallback
return f"Title,Content\n{title},Error rendering report: {str(e)}", "text/csv"
def _clean_csv_content(self, content: str, title: str) -> str:
"""Clean and validate CSV content from AI."""
content = content.strip()
# Remove markdown code blocks if present
if content.startswith("```") and content.endswith("```"):
lines = content.split('\n')
if len(lines) > 2:
content = '\n'.join(lines[1:-1]).strip()
return content