""" JSON renderer for report generation. """ from .rendererBaseTemplate import BaseRenderer from typing import Dict, Any, Tuple, List import json class RendererJson(BaseRenderer): """Renders content to JSON format with format-specific extraction.""" @classmethod def get_supported_formats(cls) -> List[str]: """Return supported JSON formats.""" return ['json'] @classmethod def get_format_aliases(cls) -> List[str]: """Return format aliases.""" return ['data'] @classmethod def get_priority(cls) -> int: """Return priority for JSON renderer.""" return 80 async def render(self, extracted_content: Dict[str, Any], title: str, user_prompt: str = None, ai_service=None) -> Tuple[str, str]: """Render extracted JSON content to JSON format.""" try: # The extracted content should already be JSON from the AI # Just validate and format it json_content = self._clean_json_content(extracted_content, title) return json_content, "application/json" except Exception as e: self.logger.error(f"Error rendering JSON: {str(e)}") # Return minimal JSON fallback fallback_data = { "title": title, "sections": [{"content_type": "paragraph", "elements": [{"text": f"Error rendering report: {str(e)}"}]}], "metadata": {"error": str(e)} } return json.dumps(fallback_data, indent=2), "application/json" def _clean_json_content(self, content: Dict[str, Any], title: str) -> str: """Clean and validate JSON content from AI.""" try: # Validate JSON structure if not isinstance(content, dict): raise ValueError("Content must be a dictionary") # Ensure it has the expected structure if "sections" not in content: # Convert old format to new format content = { "sections": [{"content_type": "paragraph", "elements": [{"text": str(content)}]}], "metadata": {"title": title} } # Ensure metadata exists if "metadata" not in content: content["metadata"] = {} # Set title in metadata if not present if "title" not in content["metadata"]: content["metadata"]["title"] = title # Re-format with proper indentation return json.dumps(content, indent=2, ensure_ascii=False) except Exception as e: self.logger.warning(f"Error cleaning JSON content: {str(e)}") # Return minimal valid JSON fallback_data = { "sections": [{"content_type": "paragraph", "elements": [{"text": str(content)}]}], "metadata": {"title": title, "error": str(e)} } return json.dumps(fallback_data, indent=2, ensure_ascii=False)