fedec65 commited on
Commit
599f010
·
verified ·
1 Parent(s): 52373e6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +171 -1
app.py CHANGED
@@ -614,4 +614,174 @@ def process_multiple_dashboards(api_key, pdf_files, language_code="it", goal_des
614
  # Return the combined report content and all output files
615
  combined_content = "\n\n---\n\n".join(individual_reports)
616
  if len(individual_reports) > 1 and 'comparative_report' in locals():
617
- combined_content += f"\n\n{'='*80}\n\n# COMPARATIVE ANALYSIS\n\n{comparative_report}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
614
  # Return the combined report content and all output files
615
  combined_content = "\n\n---\n\n".join(individual_reports)
616
  if len(individual_reports) > 1 and 'comparative_report' in locals():
617
+ combined_content += f"\n\n{'='*80}\n\n# COMPARATIVE ANALYSIS\n\n{comparative_report}"
618
+
619
+ return combined_content, output_files, "✅ Analysis completed successfully!"
620
+
621
+ # Gradio Interface Functions
622
+ def process_dashboard(api_key, pdf_files, language_choice, analysis_goal, num_sections, model_choice, custom_model, progress=gr.Progress()):
623
+ """Process the dashboard via the Gradio interface."""
624
+ if not api_key or not pdf_files:
625
+ return None, None, "Please provide both the API key and at least one PDF file."
626
+
627
+ # Map language choice to language code
628
+ language_codes = {
629
+ "Italiano": "it",
630
+ "English": "en",
631
+ "Français": "fr",
632
+ "Español": "es",
633
+ "Deutsch": "de"
634
+ }
635
+ language_code = language_codes.get(language_choice, "it")
636
+
637
+ # Validate number of sections
638
+ try:
639
+ num_sections = int(num_sections)
640
+ if num_sections < 1:
641
+ num_sections = 4 # Default
642
+ except:
643
+ num_sections = 4 # Default
644
+
645
+ # Convert the uploaded files to a list of bytes
646
+ progress(0, desc="Preparing files...")
647
+ pdf_bytes_list = []
648
+ for pdf_file in pdf_files:
649
+ with open(pdf_file.name, "rb") as f:
650
+ pdf_bytes_list.append(f.read())
651
+
652
+ # Start progress thread for text updates
653
+ progress_thread = threading.Thread(target=update_progress)
654
+ progress_thread.daemon = True
655
+ progress_thread.start()
656
+
657
+ # Process the dashboards
658
+ try:
659
+ # Override the progress_tracker update function to also update the Gradio progress bar
660
+ original_update = progress_tracker.update
661
+
662
+ def combined_update(percent, message="Processing..."):
663
+ original_update(percent, message)
664
+ progress(percent/100, desc=message)
665
+
666
+ progress_tracker.update = combined_update
667
+
668
+ md_content, output_files, status_message = process_multiple_dashboards(
669
+ api_key=api_key,
670
+ pdf_files=pdf_bytes_list,
671
+ language_code=language_code,
672
+ goal_description=analysis_goal,
673
+ num_sections=num_sections,
674
+ model_name=model_choice,
675
+ custom_model=custom_model
676
+ )
677
+
678
+ if md_content and output_files:
679
+ progress(1.0, desc="Complete!")
680
+ return md_content, output_files, progress_tracker.get_status()
681
+ else:
682
+ return None, None, "❌ Error during dashboard analysis."
683
+ except Exception as e:
684
+ progress_tracker.update(100, f"❌ Error: {str(e)}")
685
+ progress_tracker.end_processing()
686
+ progress(1.0, desc=f"Error: {str(e)}")
687
+ return None, None, f"❌ Error: {str(e)}"
688
+
689
+ def refresh_models(api_key):
690
+ """Refresh the list of available models based on the API key."""
691
+ if not api_key:
692
+ return gr.Dropdown(choices=["meta-llama/llama-4-scout:free", "custom"] + OPENROUTER_MODELS, value="meta-llama/llama-4-scout:free")
693
+
694
+ try:
695
+ available_models = get_available_models(api_key)
696
+ return gr.Dropdown(choices=["meta-llama/llama-4-scout:free", "custom"] + available_models, value="meta-llama/llama-4-scout:free")
697
+ except Exception as e:
698
+ print(f"Error refreshing models: {str(e)}")
699
+ return gr.Dropdown(choices=["meta-llama/llama-4-scout:free", "custom"] + OPENROUTER_MODELS, value="meta-llama/llama-4-scout:free")
700
+
701
+ # Define the Gradio interface
702
+ with gr.Blocks(title="Dashboard Narrator - Powered by OpenRouter.ai", theme=gr.themes.Soft()) as demo:
703
+ gr.Markdown("""
704
+ # 📊 Dashboard Narrator - Powered by OpenRouter.ai
705
+ Unlock the hidden stories in your dashboards!<br>
706
+ Dashboard Narrator leverages advanced AI models through OpenRouter.ai to dissect your PDF reports,<br>
707
+ analyze each segment with expert precision, and craft comprehensive insights in your preferred language.<br><br>
708
+ Turn complex data visualizations into clear, strategic recommendations and uncover trends you might have missed.<br>
709
+ From executive summaries to detailed breakdowns, get the full narrative behind your numbers in just a few clicks.<br><br>
710
+ """)
711
+ with gr.Row():
712
+ with gr.Column(scale=1):
713
+ api_key = gr.Textbox(label="OpenRouter API Key", placeholder="Enter your OpenRouter API key...", type="password")
714
+ refresh_btn = gr.Button("🔄 Refresh Available Models", size="sm")
715
+
716
+ model_choice = gr.Dropdown(
717
+ choices=["meta-llama/llama-4-scout:free", "custom"] + OPENROUTER_MODELS,
718
+ value="meta-llama/llama-4-scout:free",
719
+ label="Select Model"
720
+ )
721
+
722
+ custom_model = gr.Textbox(
723
+ label="Custom Model ID",
724
+ placeholder="Enter custom model ID (e.g., anthropic/claude-3-opus:latest)...",
725
+ visible=False
726
+ )
727
+
728
+ language = gr.Dropdown(
729
+ choices=["Italiano", "English", "Français", "Español", "Deutsch"],
730
+ value="English",
731
+ label="Report Language"
732
+ )
733
+
734
+ num_sections = gr.Slider(
735
+ minimum=2,
736
+ maximum=10,
737
+ value=4,
738
+ step=1,
739
+ label="Number of Vertical Sections per Dashboard"
740
+ )
741
+
742
+ goal = gr.Textbox(
743
+ label="Analysis Goal (optional)",
744
+ placeholder="E.g., Analyze Q1 2024 sales KPIs..."
745
+ )
746
+
747
+ pdf_files = gr.File(
748
+ label="Upload Dashboards (PDF)",
749
+ file_types=[".pdf"],
750
+ file_count="multiple"
751
+ )
752
+
753
+ analyze_btn = gr.Button("🔍 Analyze Dashboards", variant="primary")
754
+
755
+ with gr.Column(scale=2):
756
+ with gr.Tab("Report"):
757
+ output_md = gr.Markdown(label="Analysis Report", value="")
758
+ with gr.Tab("Output Files"):
759
+ output_files = gr.File(label="Download Files")
760
+ output_status = gr.Textbox(label="Progress", placeholder="Upload dashboards and press Analyze...", interactive=False)
761
+ # Progress component doesn't accept label in Gradio 5.21.0
762
+ progress_bar = gr.Progress()
763
+
764
+ # Handle model dropdown change
765
+ model_choice.change(
766
+ fn=toggle_custom_model,
767
+ inputs=model_choice,
768
+ outputs=custom_model,
769
+ )
770
+
771
+ # Handle refresh models button
772
+ refresh_btn.click(
773
+ fn=refresh_models,
774
+ inputs=api_key,
775
+ outputs=model_choice,
776
+ )
777
+
778
+ # Handle analyze button
779
+ analyze_btn.click(
780
+ fn=process_dashboard,
781
+ inputs=[api_key, pdf_files, language, goal, num_sections, model_choice, custom_model],
782
+ outputs=[output_md, output_files, output_status]
783
+ )
784
+
785
+ # Launch the app
786
+ if __name__ == "__main__":
787
+ demo.launch()