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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
combined_content = "\n\n---\n\n".join(individual_reports)
|
3 |
-
if len(individual_reports) > 1 and
|
4 |
combined_content += f"\n\n{'='*80}\n\n# COMPARATIVE ANALYSIS\n\n{comparative_report}"
|
5 |
|
6 |
return combined_content, output_files, "β
Analysis completed successfully!"
|
@@ -162,4 +782,5 @@ with gr.Blocks(title="Dashboard Narrator - Powered by OpenRouter.ai", theme=gr.t
|
|
162 |
|
163 |
# Launch the app
|
164 |
if __name__ == "__main__":
|
|
|
165 |
demo.launch()
|
|
|
1 |
+
"""
|
2 |
+
Dashboard Narrator - Powered by OpenRouter.ai
|
3 |
+
A tool to analyze dashboard PDFs and generate comprehensive reports.
|
4 |
+
"""
|
5 |
+
|
6 |
+
# Import required libraries
|
7 |
+
import os
|
8 |
+
import time
|
9 |
+
import threading
|
10 |
+
import io
|
11 |
+
import base64
|
12 |
+
import json
|
13 |
+
import requests
|
14 |
+
from PyPDF2 import PdfReader
|
15 |
+
from PIL import Image
|
16 |
+
import markdown
|
17 |
+
from weasyprint import HTML, CSS
|
18 |
+
from weasyprint.text.fonts import FontConfiguration
|
19 |
+
from pdf2image import convert_from_bytes
|
20 |
+
import gradio as gr
|
21 |
+
|
22 |
+
# Create a global progress tracker
|
23 |
+
class ProgressTracker:
|
24 |
+
def __init__(self):
|
25 |
+
self.progress = 0
|
26 |
+
self.message = "Ready"
|
27 |
+
self.is_processing = False
|
28 |
+
self.lock = threading.Lock()
|
29 |
+
|
30 |
+
def update(self, progress, message="Processing..."):
|
31 |
+
with self.lock:
|
32 |
+
self.progress = progress
|
33 |
+
self.message = message
|
34 |
+
|
35 |
+
def get_status(self):
|
36 |
+
with self.lock:
|
37 |
+
return f"{self.message} ({self.progress:.1f}%)"
|
38 |
+
|
39 |
+
def start_processing(self):
|
40 |
+
with self.lock:
|
41 |
+
self.is_processing = True
|
42 |
+
self.progress = 0
|
43 |
+
self.message = "Starting..."
|
44 |
+
|
45 |
+
def end_processing(self):
|
46 |
+
with self.lock:
|
47 |
+
self.is_processing = False
|
48 |
+
self.progress = 100
|
49 |
+
self.message = "Complete"
|
50 |
+
|
51 |
+
# Create a global instance
|
52 |
+
progress_tracker = ProgressTracker()
|
53 |
+
output_status = None
|
54 |
+
|
55 |
+
# Function to update the Gradio interface with progress
|
56 |
+
def update_progress():
|
57 |
+
global output_status
|
58 |
+
while progress_tracker.is_processing:
|
59 |
+
status = progress_tracker.get_status()
|
60 |
+
if output_status is not None:
|
61 |
+
output_status.update(value=status)
|
62 |
+
time.sleep(0.5)
|
63 |
+
return
|
64 |
+
|
65 |
+
# OpenRouter Client for making API calls
|
66 |
+
class OpenRouterClient:
|
67 |
+
def __init__(self, api_key):
|
68 |
+
self.api_key = api_key
|
69 |
+
self.base_url = "https://openrouter.ai/api/v1"
|
70 |
+
|
71 |
+
def messages_create(self, model, messages, system=None, temperature=0.7, max_tokens=None):
|
72 |
+
"""Send messages to the OpenRouter API and return the response"""
|
73 |
+
url = f"{self.base_url}/chat/completions"
|
74 |
+
|
75 |
+
headers = {
|
76 |
+
"Authorization": f"Bearer {self.api_key}",
|
77 |
+
"Content-Type": "application/json"
|
78 |
+
}
|
79 |
+
|
80 |
+
payload = {
|
81 |
+
"model": model,
|
82 |
+
"messages": messages,
|
83 |
+
"temperature": temperature,
|
84 |
+
}
|
85 |
+
|
86 |
+
# Add system message if provided
|
87 |
+
if system:
|
88 |
+
payload["messages"].insert(0, {"role": "system", "content": system})
|
89 |
+
|
90 |
+
# Add max_tokens if provided
|
91 |
+
if max_tokens:
|
92 |
+
payload["max_tokens"] = max_tokens
|
93 |
+
|
94 |
+
try:
|
95 |
+
response = requests.post(url, headers=headers, json=payload)
|
96 |
+
response.raise_for_status() # Raise an exception for HTTP errors
|
97 |
+
|
98 |
+
result = response.json()
|
99 |
+
|
100 |
+
# Format the response to match the expected structure
|
101 |
+
formatted_response = type('obj', (object,), {
|
102 |
+
'content': [
|
103 |
+
type('obj', (object,), {
|
104 |
+
'text': result['choices'][0]['message']['content']
|
105 |
+
})
|
106 |
+
]
|
107 |
+
})
|
108 |
+
|
109 |
+
return formatted_response
|
110 |
+
|
111 |
+
except requests.exceptions.RequestException as e:
|
112 |
+
print(f"API request error: {str(e)}")
|
113 |
+
if hasattr(e, 'response') and e.response:
|
114 |
+
print(f"Response: {e.response.text}")
|
115 |
+
raise
|
116 |
+
|
117 |
+
# Supported languages configuration
|
118 |
+
SUPPORTED_LANGUAGES = {
|
119 |
+
"italiano": {
|
120 |
+
"code": "it",
|
121 |
+
"name": "Italiano",
|
122 |
+
"report_title": "Analisi Dashboard",
|
123 |
+
"report_subtitle": "Report Dettagliato",
|
124 |
+
"date_label": "Data",
|
125 |
+
"system_prompt": "Sei un esperto analista di business intelligence specializzato nell'interpretazione di dashboard e dati visualizzati. Fornisci analisi in italiano approfondite e insight actionable basati sui dati forniti.",
|
126 |
+
"section_title": "ANALISI SEZIONE",
|
127 |
+
"multi_doc_title": "ANALISI DASHBOARD {index}"
|
128 |
+
},
|
129 |
+
"english": {
|
130 |
+
"code": "en",
|
131 |
+
"name": "English",
|
132 |
+
"report_title": "Dashboard Analysis",
|
133 |
+
"report_subtitle": "Detailed Report",
|
134 |
+
"date_label": "Date",
|
135 |
+
"system_prompt": "You are an expert business intelligence analyst specialized in interpreting dashboards and data visualizations. Provide in-depth analysis and actionable insights based on the data provided.",
|
136 |
+
"section_title": "SECTION ANALYSIS",
|
137 |
+
"multi_doc_title": "DASHBOARD {index} ANALYSIS"
|
138 |
+
},
|
139 |
+
"franΓ§ais": {
|
140 |
+
"code": "fr",
|
141 |
+
"name": "FranΓ§ais",
|
142 |
+
"report_title": "Analyse de Tableau de Bord",
|
143 |
+
"report_subtitle": "Rapport DΓ©taillΓ©",
|
144 |
+
"date_label": "Date",
|
145 |
+
"system_prompt": "Vous Γͺtes un analyste expert en business intelligence spΓ©cialisΓ© dans l'interprΓ©tation des tableaux de bord et des visualisations de donnΓ©es. Fournissez en franΓ§ais une analyse approfondie et des insights actionnables basΓ©s sur les donnΓ©es fournies.",
|
146 |
+
"section_title": "ANALYSE DE SECTION",
|
147 |
+
"multi_doc_title": "ANALYSE DU TABLEAU DE BORD {index}"
|
148 |
+
},
|
149 |
+
"espaΓ±ol": {
|
150 |
+
"code": "es",
|
151 |
+
"name": "EspaΓ±ol",
|
152 |
+
"report_title": "AnΓ‘lisis de Dashboard",
|
153 |
+
"report_subtitle": "Informe Detallado",
|
154 |
+
"date_label": "Fecha",
|
155 |
+
"system_prompt": "Eres un analista experto en inteligencia empresarial especializado en interpretar dashboards y visualizaciones de datos. Proporciona en espaΓ±ol un anΓ‘lisis en profundidad e insights accionables basados en los datos proporcionados.",
|
156 |
+
"section_title": "ANΓLISIS DE SECCIΓN",
|
157 |
+
"multi_doc_title": "ANΓLISIS DEL DASHBOARD {index}"
|
158 |
+
},
|
159 |
+
"deutsch": {
|
160 |
+
"code": "de",
|
161 |
+
"name": "Deutsch",
|
162 |
+
"report_title": "Dashboard-Analyse",
|
163 |
+
"report_subtitle": "Detaillierter Bericht",
|
164 |
+
"date_label": "Datum",
|
165 |
+
"system_prompt": "Sie sind ein Experte fΓΌr Business Intelligence-Analyse, der auf die Interpretation von Dashboards und Datenvisualisierungen spezialisiert ist. Bieten Sie auf Deutsch eine eingehende Analyse und umsetzbare Erkenntnisse auf Grundlage der bereitgestellten Daten.",
|
166 |
+
"section_title": "ABSCHNITTSANALYSE",
|
167 |
+
"multi_doc_title": "DASHBOARD-ANALYSE {index}"
|
168 |
+
}
|
169 |
+
}
|
170 |
+
|
171 |
+
# OpenRouter models
|
172 |
+
DEFAULT_MODEL = "anthropic/claude-3.7-sonnet"
|
173 |
+
OPENROUTER_MODELS = [
|
174 |
+
"anthropic/claude-3.7-sonnet",
|
175 |
+
"openai/gpt-4.1",
|
176 |
+
"openai/o4-mini-high",
|
177 |
+
"openai/gpt-4.1-mini",
|
178 |
+
"moonshotai/kimi-vl-a3b-thinking:free",
|
179 |
+
"google/gemini-2.5-pro-preview-03-25",
|
180 |
+
"microsoft/phi-4-multimodal-instruct",
|
181 |
+
"qwen/qwen2.5-vl-72b-instruct:free"
|
182 |
+
]
|
183 |
+
|
184 |
+
# Utility Functions
|
185 |
+
def extract_text_from_pdf(pdf_bytes):
|
186 |
+
"""Extract text from a PDF file."""
|
187 |
+
try:
|
188 |
+
pdf_reader = PdfReader(io.BytesIO(pdf_bytes))
|
189 |
+
text = ""
|
190 |
+
for page_num in range(len(pdf_reader.pages)):
|
191 |
+
extracted = pdf_reader.pages[page_num].extract_text()
|
192 |
+
if extracted:
|
193 |
+
text += extracted + "\n"
|
194 |
+
return text
|
195 |
+
except Exception as e:
|
196 |
+
print(f"Error extracting text from PDF: {str(e)}")
|
197 |
+
return ""
|
198 |
+
|
199 |
+
def divide_image_vertically(image, num_sections):
|
200 |
+
"""Divide an image vertically into sections."""
|
201 |
+
width, height = image.size
|
202 |
+
section_height = height // num_sections
|
203 |
+
sections = []
|
204 |
+
for i in range(num_sections):
|
205 |
+
top = i * section_height
|
206 |
+
bottom = height if i == num_sections - 1 else (i + 1) * section_height
|
207 |
+
section = image.crop((0, top, width, bottom))
|
208 |
+
sections.append(section)
|
209 |
+
print(f"Section {i+1}: size {section.width}x{section.height} pixels")
|
210 |
+
return sections
|
211 |
+
|
212 |
+
def encode_image_with_resize(image, max_size_mb=4.5):
|
213 |
+
"""Encode an image in base64, resizing if necessary."""
|
214 |
+
max_bytes = max_size_mb * 1024 * 1024
|
215 |
+
img_byte_arr = io.BytesIO()
|
216 |
+
image.save(img_byte_arr, format='PNG')
|
217 |
+
current_size = len(img_byte_arr.getvalue())
|
218 |
+
if current_size > max_bytes:
|
219 |
+
scale_factor = (max_bytes / current_size) ** 0.5
|
220 |
+
new_width = int(image.width * scale_factor)
|
221 |
+
new_height = int(image.height * scale_factor)
|
222 |
+
resized_image = image.resize((new_width, new_height), Image.LANCZOS)
|
223 |
+
img_byte_arr = io.BytesIO()
|
224 |
+
resized_image.save(img_byte_arr, format='PNG', optimize=True)
|
225 |
+
print(f"Image resized from {current_size/1024/1024:.2f}MB to {len(img_byte_arr.getvalue())/1024/1024:.2f}MB")
|
226 |
+
image = resized_image
|
227 |
+
else:
|
228 |
+
print(f"Image size acceptable: {current_size/1024/1024:.2f}MB")
|
229 |
+
buffer = io.BytesIO()
|
230 |
+
image.save(buffer, format="PNG", optimize=True)
|
231 |
+
return base64.b64encode(buffer.getvalue()).decode("utf-8")
|
232 |
+
|
233 |
+
# Core Analysis Functions
|
234 |
+
def analyze_dashboard_section(client, model, section_number, total_sections, image_section, full_text, language, goal_description=None):
|
235 |
+
"""Analyze a vertical section of the dashboard in the specified language."""
|
236 |
+
print(f"Analyzing section {section_number}/{total_sections} in {language['name']} using {model}...")
|
237 |
+
try:
|
238 |
+
encoded_image = encode_image_with_resize(image_section)
|
239 |
+
except Exception as e:
|
240 |
+
print(f"Error encoding section {section_number}: {str(e)}")
|
241 |
+
return f"Error analyzing section {section_number}: {str(e)}"
|
242 |
+
|
243 |
+
section_prompt = f"""
|
244 |
+
Act as a senior data analyst examining this dashboard section for Customer Experience purpose.\n
|
245 |
+
Your analysis will be shared with top executives to inform about Customer Experience improvements and customer satisfaction level.\n
|
246 |
+
# Dashboard Analysis - Section {section_number} of {total_sections}\n
|
247 |
+
You are analyzing section {section_number} of {total_sections} of a long vertical dashboard. This is part of a broader analysis.\n
|
248 |
+
{f"The analysis objective is: {goal_description}" if goal_description else ""}\n\n
|
249 |
+
For this specific section:\n
|
250 |
+
1. Describe what these visualizations show, including their type (e.g., bar chart, line graph) and the data they represent\n
|
251 |
+
2. Quantitatively analyze the data, noting specific values, percentages, and numeric trends\n
|
252 |
+
3. Identify significant patterns, anomalies, or outliers visible in the data\n
|
253 |
+
4. Provide 2-3 actionable insights based on this analysis, explaining their business implications\n
|
254 |
+
5. Suggest possible reasons for any notable trends or unexpected findings\n
|
255 |
+
Focus exclusively on the visible section. Don't reference or speculate about unseen dashboard elements.\n
|
256 |
+
Answer completely in {language['name']}.\n\n
|
257 |
+
# Text extracted from the complete dashboard:\n
|
258 |
+
{full_text[:10000]}
|
259 |
+
|
260 |
+
# Image of this dashboard section:
|
261 |
+
[BASE64 IMAGE: {encoded_image[:20]}...]
|
262 |
+
This is a dashboard visualization showing various metrics and charts. Please analyze the content visible in this image.
|
263 |
+
"""
|
264 |
+
|
265 |
+
try:
|
266 |
+
response = client.messages_create(
|
267 |
+
model=model,
|
268 |
+
messages=[{"role": "user", "content": section_prompt}],
|
269 |
+
system=language['system_prompt'],
|
270 |
+
temperature=0.1,
|
271 |
+
max_tokens=10000
|
272 |
+
)
|
273 |
+
return response.content[0].text
|
274 |
+
except Exception as e:
|
275 |
+
print(f"Error analyzing section {section_number}: {str(e)}")
|
276 |
+
return f"Error analyzing section {section_number}: {str(e)}"
|
277 |
+
|
278 |
+
def create_comprehensive_report(client, model, section_analyses, full_text, language, goal_description=None):
|
279 |
+
"""Create a unified comprehensive report based on individual section analyses."""
|
280 |
+
print(f"Generating final comprehensive report in {language['name']} using {model}...")
|
281 |
+
comprehensive_prompt = f"""
|
282 |
+
# Comprehensive Dashboard Analysis Request
|
283 |
+
You have analyzed a long vertical dashboard in multiple sections. Now you need to create a unified and coherent report based on all the partial analyses.\n
|
284 |
+
{f"The analysis objective is: {goal_description}" if goal_description else ""}\n\n
|
285 |
+
Here are the analyses of the individual dashboard sections:\n
|
286 |
+
{section_analyses}\n\n
|
287 |
+
Based on these partial analyses, generate a professional, structured, and coherent report that includes:\n
|
288 |
+
1. Executive Summary - Include key metrics, major findings, and critical recommendations (limit to 1 page equivalent)\n
|
289 |
+
2. Dashboard Performance Overview - Add a section that evaluates the overall health metrics before diving into categories\n
|
290 |
+
3 Detailed Analysis by Category - Keep this, it's essential\n
|
291 |
+
4 Trend Analysis - Broaden from just temporal to include cross-category patterns\n
|
292 |
+
5 Critical Issues and Opportunities - Combine anomalies with positive outliers to provide balanced insights\n
|
293 |
+
6 Strategic Implications and Recommendations - Consolidate your insights and recommendations into a single, stronger section\n
|
294 |
+
7 Implementation Roadmap - Convert your conclusions into a prioritized action plan with timeframes\n
|
295 |
+
8 Appendix: Monitoring Improvements - Move the monitoring suggestions to an appendix unless they're a primary focus\n\n
|
296 |
+
Integrate information from all sections to create a coherent and complete report.\n\n
|
297 |
+
# Text extracted from the complete dashboard:\n
|
298 |
+
{full_text[:10000]}
|
299 |
+
"""
|
300 |
+
try:
|
301 |
+
response = client.messages_create(
|
302 |
+
model=model,
|
303 |
+
messages=[{"role": "user", "content": comprehensive_prompt}],
|
304 |
+
system=language['system_prompt'],
|
305 |
+
temperature=0.1,
|
306 |
+
max_tokens=10000
|
307 |
+
)
|
308 |
+
return response.content[0].text
|
309 |
+
except Exception as e:
|
310 |
+
print(f"Error creating comprehensive report: {str(e)}")
|
311 |
+
return f"Error creating comprehensive report: {str(e)}"
|
312 |
+
|
313 |
+
def create_multi_dashboard_comparative_report(client, model, individual_reports, language, goal_description=None):
|
314 |
+
"""Create a comparative report analyzing multiple dashboards together."""
|
315 |
+
print(f"Generating comparative report for multiple dashboards in {language['name']} using {model}...")
|
316 |
+
comparative_prompt = f"""
|
317 |
+
# Multi-Dashboard Comparative Analysis Request
|
318 |
+
You have analyzed multiple dashboards individually. Now you need to create a comparative analysis report that identifies patterns, similarities, differences, and insights across all dashboards.
|
319 |
+
{f"The analysis objective is: {goal_description}" if goal_description else ""}
|
320 |
+
Here are the analyses of the individual dashboards:
|
321 |
+
{individual_reports}
|
322 |
+
Based on these individual analyses, generate a professional, structured comparative report that includes:
|
323 |
+
1. Executive Overview of All Dashboards
|
324 |
+
2. Comparative Analysis of Key Metrics
|
325 |
+
3. Cross-Dashboard Patterns and Trends
|
326 |
+
4. Notable Differences Between Dashboards
|
327 |
+
5. Integrated Insights from All Sources
|
328 |
+
6. Comprehensive Strategic Recommendations
|
329 |
+
7. Suggestions for Cross-Dashboard Monitoring Improvements
|
330 |
+
8. Conclusions and Integrated Next Steps
|
331 |
+
Integrate information from all dashboards to create a coherent comparative report.
|
332 |
+
"""
|
333 |
+
try:
|
334 |
+
response = client.messages_create(
|
335 |
+
model=model,
|
336 |
+
messages=[{"role": "user", "content": comparative_prompt}],
|
337 |
+
system=language['system_prompt'],
|
338 |
+
temperature=0.1,
|
339 |
+
max_tokens=12000
|
340 |
+
)
|
341 |
+
return response.content[0].text
|
342 |
+
except Exception as e:
|
343 |
+
print(f"Error creating comparative report: {str(e)}")
|
344 |
+
return f"Error creating comparative report: {str(e)}"
|
345 |
+
|
346 |
+
def markdown_to_pdf(markdown_content, output_filename, language):
|
347 |
+
"""Convert Markdown content to a well-formatted PDF."""
|
348 |
+
print(f"Converting Markdown report to PDF in {language['name']}...")
|
349 |
+
css = CSS(string='''
|
350 |
+
@page { margin: 1.5cm; }
|
351 |
+
body { font-family: Arial, sans-serif; line-height: 1.5; font-size: 11pt; }
|
352 |
+
h1 { color: #2c3e50; font-size: 22pt; margin-top: 1cm; margin-bottom: 0.5cm; page-break-after: avoid; }
|
353 |
+
h2 { color: #3498db; font-size: 16pt; margin-top: 0.8cm; margin-bottom: 0.3cm; page-break-after: avoid; }
|
354 |
+
p { margin-bottom: 0.3cm; text-align: justify; }
|
355 |
+
''')
|
356 |
+
today = time.strftime("%d/%m/%Y")
|
357 |
+
cover_page = f"""
|
358 |
+
<div style="text-align: center; height: 100vh; display: flex; flex-direction: column; justify-content: center; align-items: center;">
|
359 |
+
<h1 style="font-size: 26pt; color: #2c3e50;">{language['report_title']}</h1>
|
360 |
+
<h2 style="font-size: 14pt; color: #7f8c8d;">{language['report_subtitle']}</h2>
|
361 |
+
<p style="font-size: 12pt; color: #7f8c8d;">{language['date_label']}: {today}</p>
|
362 |
+
</div>
|
363 |
+
<div style="page-break-after: always;"></div>
|
364 |
+
"""
|
365 |
+
html_content = markdown.markdown(markdown_content, extensions=['tables', 'fenced_code'])
|
366 |
+
full_html = f"""
|
367 |
+
<!DOCTYPE html>
|
368 |
+
<html lang="{language['code']}">
|
369 |
+
<head><meta charset="UTF-8"><title>{language['report_title']}</title></head>
|
370 |
+
<body>{cover_page}{html_content}</body>
|
371 |
+
</html>
|
372 |
+
"""
|
373 |
+
font_config = FontConfiguration()
|
374 |
+
HTML(string=full_html).write_pdf(output_filename, stylesheets=[css], font_config=font_config)
|
375 |
+
print(f"PDF created successfully: {output_filename}")
|
376 |
+
return output_filename
|
377 |
+
|
378 |
+
def analyze_vertical_dashboard(client, model, pdf_bytes, language, goal_description=None, num_sections=4, dashboard_index=None):
|
379 |
+
"""Analyze a vertical dashboard by dividing it into sections."""
|
380 |
+
dashboard_marker = f" {dashboard_index}" if dashboard_index is not None else ""
|
381 |
+
total_dashboards = progress_tracker.total_dashboards if hasattr(progress_tracker, 'total_dashboards') else 1
|
382 |
+
dashboard_progress_base = ((dashboard_index - 1) / total_dashboards * 100) if dashboard_index is not None else 0
|
383 |
+
dashboard_progress_step = (100 / total_dashboards) if total_dashboards > 0 else 100
|
384 |
+
|
385 |
+
progress_tracker.update(dashboard_progress_base, f"πΌοΈ Analyzing dashboard{dashboard_marker}...")
|
386 |
+
print(f"πΌοΈ Analyzing dashboard{dashboard_marker}...")
|
387 |
+
|
388 |
+
progress_tracker.update(dashboard_progress_base + dashboard_progress_step * 0.1, f"π Extracting text from dashboard{dashboard_marker}...")
|
389 |
+
print(f"π Extracting full text from PDF...")
|
390 |
+
full_text = extract_text_from_pdf(pdf_bytes)
|
391 |
+
if not full_text or len(full_text.strip()) < 100:
|
392 |
+
print("β οΈ Limited text extracted from PDF. Analysis will rely primarily on images.")
|
393 |
+
else:
|
394 |
+
print(f"β
Extracted {len(full_text)} characters of text from PDF.")
|
395 |
+
|
396 |
+
progress_tracker.update(dashboard_progress_base + dashboard_progress_step * 0.2, f"πΌοΈ Converting dashboard{dashboard_marker} to images...")
|
397 |
+
print("πΌοΈ Converting PDF to images...")
|
398 |
+
try:
|
399 |
+
pdf_images = convert_from_bytes(pdf_bytes, dpi=150)
|
400 |
+
if not pdf_images:
|
401 |
+
print("β Unable to convert PDF to images.")
|
402 |
+
return None, "Error: Unable to convert PDF to images."
|
403 |
+
print(f"β
PDF converted to {len(pdf_images)} image pages.")
|
404 |
+
main_image = pdf_images[0]
|
405 |
+
print(f"Main image size: {main_image.width}x{main_image.height} pixels")
|
406 |
+
|
407 |
+
progress_tracker.update(dashboard_progress_base + dashboard_progress_step * 0.3, f"Dividing dashboard{dashboard_marker} into {num_sections} sections...")
|
408 |
+
print(f"Dividing image into {num_sections} vertical sections...")
|
409 |
+
image_sections = divide_image_vertically(main_image, num_sections)
|
410 |
+
print(f"β
Image divided into {len(image_sections)} sections.")
|
411 |
+
except Exception as e:
|
412 |
+
print(f"β Error converting or dividing PDF: {str(e)}")
|
413 |
+
return None, f"Error: {str(e)}"
|
414 |
+
|
415 |
+
section_analyses = []
|
416 |
+
section_progress_step = dashboard_progress_step * 0.4 / len(image_sections)
|
417 |
+
|
418 |
+
for i, section in enumerate(image_sections):
|
419 |
+
section_progress = dashboard_progress_base + dashboard_progress_step * 0.3 + section_progress_step * i
|
420 |
+
progress_tracker.update(section_progress, f"Analyzing section {i+1}/{len(image_sections)} of dashboard{dashboard_marker}...")
|
421 |
+
|
422 |
+
print(f"\n{'='*50}")
|
423 |
+
print(f"Processing section {i+1}/{len(image_sections)}...")
|
424 |
+
section_result = analyze_dashboard_section(
|
425 |
+
client,
|
426 |
+
model,
|
427 |
+
i+1,
|
428 |
+
len(image_sections),
|
429 |
+
section,
|
430 |
+
full_text,
|
431 |
+
language,
|
432 |
+
goal_description
|
433 |
+
)
|
434 |
+
if section_result:
|
435 |
+
section_analyses.append(f"\n## {language['section_title']} {i+1}\n{section_result}")
|
436 |
+
print(f"β
Analysis of section {i+1} completed.")
|
437 |
+
else:
|
438 |
+
section_analyses.append(f"\n## {language['section_title']} {i+1}\nAnalysis not available for this section.")
|
439 |
+
print(f"β οΈ Analysis of section {i+1} not available.")
|
440 |
+
|
441 |
+
progress_tracker.update(dashboard_progress_base + dashboard_progress_step * 0.7, f"Generating final report for dashboard{dashboard_marker}...")
|
442 |
+
print("\n" + "="*50)
|
443 |
+
print(f"All section analyses completed. Generating report...")
|
444 |
+
combined_sections = "\n".join(section_analyses)
|
445 |
+
|
446 |
+
# If dashboard index is provided, add a header for the dashboard
|
447 |
+
if dashboard_index is not None:
|
448 |
+
dashboard_header = f"# {language['multi_doc_title'].format(index=dashboard_index)}\n\n"
|
449 |
+
combined_sections = dashboard_header + combined_sections
|
450 |
+
|
451 |
+
final_report = create_comprehensive_report(client, model, combined_sections, full_text, language, goal_description)
|
452 |
+
|
453 |
+
# If dashboard index is provided, prepend it to the report
|
454 |
+
if dashboard_index is not None and dashboard_index > 1:
|
455 |
+
# Only add header if it doesn't already exist (might have been added by Claude)
|
456 |
+
if not final_report.startswith(f"# {language['multi_doc_title'].format(index=dashboard_index)}"):
|
457 |
+
final_report = f"# {language['multi_doc_title'].format(index=dashboard_index)}\n\n{final_report}"
|
458 |
+
|
459 |
+
progress_tracker.update(dashboard_progress_base + dashboard_progress_step * 0.9, f"Finalizing dashboard{dashboard_marker} analysis...")
|
460 |
+
return final_report, combined_sections
|
461 |
+
|
462 |
+
def get_available_models(api_key):
|
463 |
+
"""Get available models from OpenRouter API."""
|
464 |
+
try:
|
465 |
+
headers = {
|
466 |
+
"Authorization": f"Bearer {api_key}",
|
467 |
+
"Content-Type": "application/json"
|
468 |
+
}
|
469 |
+
response = requests.get("https://openrouter.ai/api/v1/models", headers=headers)
|
470 |
+
|
471 |
+
if response.status_code == 200:
|
472 |
+
models_data = response.json()
|
473 |
+
available_models = [model["id"] for model in models_data.get("data", [])]
|
474 |
+
|
475 |
+
# First add our preferred models at the top if they're available
|
476 |
+
sorted_models = [model for model in OPENROUTER_MODELS if model in available_models]
|
477 |
+
|
478 |
+
# Then add any additional models not in our predefined list
|
479 |
+
additional_models = [model for model in available_models if model not in OPENROUTER_MODELS]
|
480 |
+
additional_models.sort()
|
481 |
+
|
482 |
+
all_models = ["custom"] + sorted_models + additional_models
|
483 |
+
return all_models
|
484 |
+
else:
|
485 |
+
print(f"Error fetching models: {response.status_code}")
|
486 |
+
return ["custom"] + OPENROUTER_MODELS
|
487 |
+
except Exception as e:
|
488 |
+
print(f"Error fetching models: {str(e)}")
|
489 |
+
return ["custom"] + OPENROUTER_MODELS
|
490 |
+
|
491 |
+
def process_multiple_dashboards(api_key, pdf_files, language_code="it", goal_description=None, num_sections=4, model_name=DEFAULT_MODEL, custom_model=None):
|
492 |
+
"""Process multiple dashboard PDFs and create individual and comparative reports."""
|
493 |
+
# Start progress tracking
|
494 |
+
progress_tracker.start_processing()
|
495 |
+
progress_tracker.total_dashboards = len(pdf_files)
|
496 |
+
|
497 |
+
# Step 1: Initialize language settings and API client
|
498 |
+
progress_tracker.update(1, "Initializing analysis...")
|
499 |
+
language = None
|
500 |
+
for lang_key, lang_data in SUPPORTED_LANGUAGES.items():
|
501 |
+
if lang_data['code'] == language_code:
|
502 |
+
language = lang_data
|
503 |
+
break
|
504 |
+
if not language:
|
505 |
+
print(f"β οΈ Language '{language_code}' not supported. Using Italian as fallback.")
|
506 |
+
language = SUPPORTED_LANGUAGES['italiano']
|
507 |
+
print(f"π Selected language: {language['name']}")
|
508 |
+
|
509 |
+
if not api_key:
|
510 |
+
progress_tracker.update(100, "β οΈ Error: API key not provided.")
|
511 |
+
progress_tracker.end_processing()
|
512 |
+
print("β οΈ Error: API key not provided.")
|
513 |
+
return None, None, "Error: API key not provided."
|
514 |
+
|
515 |
+
try:
|
516 |
+
client = OpenRouterClient(api_key=api_key)
|
517 |
+
print("β
OpenRouter client initialized successfully.")
|
518 |
+
except Exception as e:
|
519 |
+
progress_tracker.update(100, f"β Error initializing client: {str(e)}")
|
520 |
+
progress_tracker.end_processing()
|
521 |
+
print(f"β Error initializing client: {str(e)}")
|
522 |
+
return None, None, f"Error: {str(e)}"
|
523 |
+
|
524 |
+
# Determine which model to use
|
525 |
+
model = custom_model if model_name == "custom" and custom_model else model_name
|
526 |
+
print(f"π€ Using model: {model}")
|
527 |
+
|
528 |
+
# Step 2: Process each dashboard individually
|
529 |
+
individual_reports = []
|
530 |
+
individual_analyses = []
|
531 |
+
|
532 |
+
for i, pdf_bytes in enumerate(pdf_files):
|
533 |
+
dashboard_progress_base = (i / len(pdf_files) * 80) # 80% of progress for dashboard analysis
|
534 |
+
progress_tracker.update(dashboard_progress_base, f"Processing dashboard {i+1}/{len(pdf_files)}...")
|
535 |
+
print(f"\n{'#'*60}")
|
536 |
+
print(f"Processing dashboard {i+1}/{len(pdf_files)}...")
|
537 |
+
|
538 |
+
report, analysis = analyze_vertical_dashboard(
|
539 |
+
client=client,
|
540 |
+
model=model,
|
541 |
+
pdf_bytes=pdf_bytes,
|
542 |
+
language=language,
|
543 |
+
goal_description=goal_description,
|
544 |
+
num_sections=num_sections,
|
545 |
+
dashboard_index=i+1
|
546 |
+
)
|
547 |
+
|
548 |
+
if report:
|
549 |
+
individual_reports.append(report)
|
550 |
+
individual_analyses.append(analysis)
|
551 |
+
print(f"β
Analysis of dashboard {i+1} completed.")
|
552 |
+
else:
|
553 |
+
print(f"β Analysis of dashboard {i+1} failed.")
|
554 |
+
|
555 |
+
# For Hugging Face Space: use tmp directory for file output
|
556 |
+
tmp_dir = "/tmp"
|
557 |
+
if not os.path.exists(tmp_dir):
|
558 |
+
os.makedirs(tmp_dir, exist_ok=True)
|
559 |
+
|
560 |
+
# Step 3: Generate output files
|
561 |
+
progress_tracker.update(80, "Generating output files...")
|
562 |
+
timestamp = time.strftime("%Y%m%d_%H%M%S")
|
563 |
+
output_files = []
|
564 |
+
|
565 |
+
# Create individual report files
|
566 |
+
for i, report in enumerate(individual_reports):
|
567 |
+
file_progress = 80 + (i / len(individual_reports) * 10) # 10% for creating files
|
568 |
+
progress_tracker.update(file_progress, f"Creating files for dashboard {i+1}...")
|
569 |
+
|
570 |
+
md_filename = os.path.join(tmp_dir, f"dashboard_{i+1}_{language['code']}_{timestamp}.md")
|
571 |
+
pdf_filename = os.path.join(tmp_dir, f"dashboard_{i+1}_{language['code']}_{timestamp}.pdf")
|
572 |
+
|
573 |
+
with open(md_filename, 'w', encoding='utf-8') as f:
|
574 |
+
f.write(report)
|
575 |
+
output_files.append(md_filename)
|
576 |
+
|
577 |
+
try:
|
578 |
+
pdf_path = markdown_to_pdf(report, pdf_filename, language)
|
579 |
+
output_files.append(pdf_filename)
|
580 |
+
except Exception as e:
|
581 |
+
print(f"β οΈ Error converting dashboard {i+1} to PDF: {str(e)}")
|
582 |
+
|
583 |
+
# If there are multiple dashboards, create a comparative report
|
584 |
+
comparative_report = None
|
585 |
+
if len(individual_reports) > 1:
|
586 |
+
progress_tracker.update(90, "Creating comparative analysis...")
|
587 |
+
print("\n" + "#"*60)
|
588 |
+
print("Creating comparative analysis of all dashboards...")
|
589 |
+
|
590 |
+
# Combined report content
|
591 |
+
all_reports_content = "\n\n".join(individual_reports)
|
592 |
+
|
593 |
+
# Generate comparative analysis
|
594 |
+
comparative_report = create_multi_dashboard_comparative_report(
|
595 |
+
client=client,
|
596 |
+
model=model,
|
597 |
+
individual_reports=all_reports_content,
|
598 |
+
language=language,
|
599 |
+
goal_description=goal_description
|
600 |
+
)
|
601 |
+
|
602 |
+
# Save comparative report
|
603 |
+
progress_tracker.update(95, "Saving comparative analysis files...")
|
604 |
+
comparative_md = os.path.join(tmp_dir, f"comparative_analysis_{language['code']}_{timestamp}.md")
|
605 |
+
comparative_pdf = os.path.join(tmp_dir, f"comparative_analysis_{language['code']}_{timestamp}.pdf")
|
606 |
+
|
607 |
+
with open(comparative_md, 'w', encoding='utf-8') as f:
|
608 |
+
f.write(comparative_report)
|
609 |
+
output_files.append(comparative_md)
|
610 |
+
|
611 |
+
try:
|
612 |
+
pdf_path = markdown_to_pdf(comparative_report, comparative_pdf, language)
|
613 |
+
output_files.append(comparative_pdf)
|
614 |
+
except Exception as e:
|
615 |
+
print(f"β οΈ Error converting comparative report to PDF: {str(e)}")
|
616 |
+
|
617 |
+
# Complete progress tracking
|
618 |
+
progress_tracker.update(100, "β
Analysis completed successfully!")
|
619 |
+
progress_tracker.end_processing()
|
620 |
+
|
621 |
+
# Return the combined report content and all output files
|
622 |
combined_content = "\n\n---\n\n".join(individual_reports)
|
623 |
+
if len(individual_reports) > 1 and comparative_report:
|
624 |
combined_content += f"\n\n{'='*80}\n\n# COMPARATIVE ANALYSIS\n\n{comparative_report}"
|
625 |
|
626 |
return combined_content, output_files, "β
Analysis completed successfully!"
|
|
|
782 |
|
783 |
# Launch the app
|
784 |
if __name__ == "__main__":
|
785 |
+
demo.launch()
|
786 |
demo.launch()
|