import google.generativeai as genai import json from typing import Dict, Any, Optional class PDFReportGenerator: """ Handler for generating print-perfect HTML reports using Gemini AI. """ def __init__(self, api_key: str): """Initialize with Gemini API key.""" genai.configure(api_key=api_key) self.model = genai.GenerativeModel("gemini-2.5-pro") def generate_agent_prompt(self, context: Dict[Any, Any], report_config: Optional[Dict] = None) -> str: """ Generate the comprehensive agent prompt for report creation. Args: context: The data to analyze report_config: Optional configuration (title, date, pages, etc.) """ config = report_config or {} title = config.get('title', 'AI-GENERATED REPORT') date = config.get('date', 'November 04, 2025') num_pages = config.get('num_pages', 9) theme = config.get('theme', 'professional') include_citations = config.get('include_citations', False) prompt = f""" Generate a **complete, {num_pages}-page, print-perfect HTML report** using **ONLY** the data below. RULES: - Use ONLY HTML + CSS - No JavaScript (except 1 line for footer if absolutely necessary) - A4 pages, 20mm padding - Fonts: Times New Roman body, Arial headings - Print-perfect: @media print {{ -webkit-print-color-adjust: exact; }} - Use CSS variables, counters, SVG, conic-gradient - Every chart MUST have: X-axis label, Y-axis label, grid, values - Theme: {theme} - Include citations: {include_citations} YOUR DATA: {json.dumps(context, indent=2)} TASK: 1. Analyze ALL data thoroughly 2. Extract every number, label, trend, and pattern 3. Decide which visualizations to create (bar charts, line graphs, scatter plots, pie charts, tables) 4. Auto-label axes with real field names from the data 5. Write insights in clear, professional English 6. Discover and visualize hidden patterns and correlations 7. Title: "{title}" 8. Date: {date} 9. Structure: Cover → TOC → Executive Summary → Data Analysis → Visualizations → Insights → Recommendations → Appendix PAGE STRUCTURE: - Cover page with title, date, and branding - Table of contents with page numbers - Executive summary (1 page) - Main content with charts and analysis ({num_pages - 3} pages) - Recommendations and conclusions (1 page) STYLING: - Professional color scheme - Clear typography hierarchy - Page breaks between major sections - Headers and footers with page numbers - Print-ready margins and spacing OUTPUT: - ONLY the complete HTML code - Inside ```html code block - No explanations outside the HTML - Fully self-contained (all CSS inline) """ return prompt def generate_html_report(self, context: Dict[Any, Any], report_config: Optional[Dict] = None) -> str: """ Generate HTML report using Gemini AI. Args: context: The data to analyze report_config: Optional configuration Returns: Clean HTML string """ prompt = self.generate_agent_prompt(context, report_config) response = self.model.generate_content(prompt) html = response.text # Extract HTML from markdown code blocks if present if "```html" in html: html = html.split("```html", 1)[1].rsplit("```", 1)[0].strip() elif "" in html: start_index = html.find("") html = html[start_index:] return html def save_html_to_file(self, html_content: str, filename: str = "AI_GENERATED_REPORT.html") -> str: """ Save HTML content to file. Args: html_content: HTML string to save filename: Output filename Returns: Filename of saved report """ with open(filename, "w", encoding="utf-8") as f: f.write(html_content) return filename