gateway/modules/services/serviceGeneration/renderers/rendererJson.py

79 lines
3 KiB
Python

"""
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 getSupportedFormats(cls) -> List[str]:
"""Return supported JSON formats."""
return ['json']
@classmethod
def getFormatAliases(cls) -> List[str]:
"""Return format aliases."""
return ['data']
@classmethod
def getPriority(cls) -> int:
"""Return priority for JSON renderer."""
return 80
async def render(self, extractedContent: Dict[str, Any], title: str, userPrompt: str = None, aiService=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
jsonContent = self._cleanJsonContent(extractedContent, title)
return jsonContent, "application/json"
except Exception as e:
self.logger.error(f"Error rendering JSON: {str(e)}")
# Return minimal JSON fallback
fallbackData = {
"title": title,
"sections": [{"content_type": "paragraph", "elements": [{"text": f"Error rendering report: {str(e)}"}]}],
"metadata": {"error": str(e)}
}
return json.dumps(fallbackData, indent=2), "application/json"
def _cleanJsonContent(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
fallbackData = {
"sections": [{"content_type": "paragraph", "elements": [{"text": str(content)}]}],
"metadata": {"title": title, "error": str(e)}
}
return json.dumps(fallbackData, indent=2, ensure_ascii=False)