File size: 6,864 Bytes
d4539da 37bc974 d4539da b219614 0fffd32 1349ceb b219614 1349ceb b219614 1349ceb b219614 1349ceb b219614 1349ceb b219614 1349ceb 599f010 1349ceb 0fffd32 d4539da 0fffd32 d4539da 0fffd32 d4539da 0fffd32 d4539da 0fffd32 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 |
# Return the combined report content and all output files
combined_content = "\n\n---\n\n".join(individual_reports)
if len(individual_reports) > 1 and 'comparative_report' in locals():
combined_content += f"\n\n{'='*80}\n\n# COMPARATIVE ANALYSIS\n\n{comparative_report}"
return combined_content, output_files, "✅ Analysis completed successfully!"
# Wrapper function for Gradio interface
def process_dashboard(api_key, pdf_files, language_name, goal_description=None, num_sections=4, model_name=DEFAULT_MODEL, custom_model=None):
"""Process dashboard PDFs and generate reports (wrapper function for Gradio interface)."""
# Start a thread to update progress
progress_thread = threading.Thread(target=update_progress)
progress_thread.daemon = True
progress_thread.start()
# Convert language name to language code
language_code = "en" # Default to English
for lang_key, lang_data in SUPPORTED_LANGUAGES.items():
if lang_data['name'].lower() == language_name.lower():
language_code = lang_data['code']
break
# Get the PDF file bytes
pdf_bytes_list = []
if pdf_files is not None:
for pdf_file in pdf_files:
if isinstance(pdf_file, dict) and 'name' in pdf_file:
# Handle newer Gradio File component format
with open(pdf_file['name'], 'rb') as f:
pdf_bytes_list.append(f.read())
elif isinstance(pdf_file, str):
# Handle older Gradio File component format
with open(pdf_file, 'rb') as f:
pdf_bytes_list.append(f.read())
else:
# Just try to handle whatever format we got
try:
if hasattr(pdf_file, 'read'):
pdf_bytes_list.append(pdf_file.read())
except Exception as e:
print(f"Error reading PDF file: {str(e)}")
# Call the actual processing function
try:
combined_content, output_files, status = process_multiple_dashboards(
api_key=api_key,
pdf_files=pdf_bytes_list,
language_code=language_code,
goal_description=goal_description,
num_sections=num_sections,
model_name=model_name,
custom_model=custom_model
)
return combined_content, output_files, status
except Exception as e:
error_message = f"Error processing dashboards: {str(e)}"
print(error_message)
progress_tracker.update(100, error_message)
progress_tracker.end_processing()
return None, None, error_message
# Gradio Interface Functions
def toggle_custom_model(choice):
"""Toggle visibility of custom model input based on selection."""
return {"visible": choice == "custom"}
def refresh_models(api_key):
"""Refresh the list of available models based on the API key."""
if not api_key:
return gr.Dropdown(choices=["custom"] + OPENROUTER_MODELS, value=DEFAULT_MODEL)
try:
available_models = get_available_models(api_key)
return gr.Dropdown(choices=available_models, value=DEFAULT_MODEL)
except Exception as e:
print(f"Error refreshing models: {str(e)}")
return gr.Dropdown(choices=["custom"] + OPENROUTER_MODELS, value=DEFAULT_MODEL)
# Define the Gradio interface
with gr.Blocks(title="Dashboard Narrator - Powered by OpenRouter.ai", theme=gr.themes.Soft()) as demo:
gr.Markdown("""
# 📊 Dashboard Narrator - Powered by OpenRouter.ai
Unlock the hidden stories in your dashboards!<br>
Dashboard Narrator leverages advanced AI models through OpenRouter.ai to dissect your PDF reports,<br>
analyze each segment with expert precision, and craft comprehensive insights in your preferred language.<br><br>
Turn complex data visualizations into clear, strategic recommendations and uncover trends you might have missed.<br>
From executive summaries to detailed breakdowns, get the full narrative behind your numbers in just a few clicks.<br><br>
""")
with gr.Row():
with gr.Column(scale=1):
api_key = gr.Textbox(label="OpenRouter API Key", placeholder="Enter your OpenRouter API key...", type="password")
refresh_btn = gr.Button("🔄 Refresh Available Models", size="sm")
model_choice = gr.Dropdown(
choices=["custom"] + OPENROUTER_MODELS,
value=DEFAULT_MODEL,
label="Select Model"
)
custom_model = gr.Textbox(
label="Custom Model ID",
placeholder="Enter custom model ID (e.g., anthropic/claude-3-opus:latest)...",
visible=False
)
language = gr.Dropdown(
choices=["Italiano", "English", "Français", "Español", "Deutsch"],
value="English",
label="Report Language"
)
num_sections = gr.Slider(
minimum=2,
maximum=10,
value=4,
step=1,
label="Number of Vertical Sections per Dashboard"
)
goal = gr.Textbox(
label="Analysis Goal (optional)",
placeholder="E.g., Analyze Q1 2024 sales KPIs..."
)
pdf_files = gr.File(
label="Upload Dashboards (PDF)",
file_types=[".pdf"],
file_count="multiple"
)
analyze_btn = gr.Button("🔍 Analyze Dashboards", variant="primary")
with gr.Column(scale=2):
with gr.Tab("Report"):
output_md = gr.Markdown(label="Analysis Report", value="")
with gr.Tab("Output Files"):
output_files = gr.File(label="Download Files")
output_status = gr.Textbox(label="Progress", placeholder="Upload dashboards and press Analyze...", interactive=False)
# Progress component doesn't accept label in Gradio 5.21.0
progress_bar = gr.Progress()
# Handle model dropdown change
model_choice.change(
fn=toggle_custom_model,
inputs=model_choice,
outputs=custom_model,
)
# Handle refresh models button
refresh_btn.click(
fn=refresh_models,
inputs=api_key,
outputs=model_choice,
)
# Handle analyze button
analyze_btn.click(
fn=process_dashboard,
inputs=[api_key, pdf_files, language, goal, num_sections, model_choice, custom_model],
outputs=[output_md, output_files, output_status]
)
# Launch the app
if __name__ == "__main__":
demo.launch() |