pentarosarium commited on
Commit
b3c07e0
·
1 Parent(s): 31e7b1f
Files changed (1) hide show
  1. app.py +58 -45
app.py CHANGED
@@ -645,7 +645,7 @@ def create_interface():
645
  control = ProcessControl()
646
 
647
  with gr.Blocks(theme=gr.themes.Soft()) as app:
648
- gr.Markdown("# AI-анализ мониторинга новостей v.1.35")
649
 
650
  with gr.Row():
651
  file_input = gr.File(
@@ -668,7 +668,6 @@ def create_interface():
668
  size="lg"
669
  )
670
 
671
- # Add status messages container
672
  with gr.Row():
673
  status_box = gr.Textbox(
674
  label="Статус дедупликации",
@@ -695,25 +694,26 @@ def create_interface():
695
  sentiment_plot = gr.Plot(label="Распределение тональности")
696
  with gr.Column(scale=1):
697
  events_plot = gr.Plot(label="Распределение событий")
698
-
699
- # Add download button
700
- download_btn = gr.Button("📥 Скачать результаты", visible=False)
701
- output_file = gr.File(label="", visible=False)
702
-
703
  def stop_processing():
704
  control.request_stop()
705
  return "Остановка обработки..."
706
-
707
- @spaces.GPU(duration=300)
708
- def analyze(file_bytes):
 
709
  if file_bytes is None:
710
  gr.Warning("Пожалуйста, загрузите файл")
711
- return None, None, None, False, (None, None), "Ожидание файла...", ""
 
 
 
 
 
 
 
712
 
713
  try:
714
- # Reset stop flag
715
- control.reset()
716
-
717
  file_obj = io.BytesIO(file_bytes)
718
  logger.info("File loaded into BytesIO successfully")
719
 
@@ -798,60 +798,73 @@ def create_interface():
798
  # Cleanup GPU resources after batch
799
  torch.cuda.empty_cache()
800
  time.sleep(2)
 
801
 
802
  # Create final results
803
  if processed_rows:
804
- final_df = pd.DataFrame(processed_rows)
805
- output_bytes_io = create_output_file(final_df, file_obj)
806
- if output_bytes_io:
807
- fig_sentiment, fig_events = create_visualizations(final_df)
808
- return (
809
- final_df,
810
- fig_sentiment,
811
- fig_events,
812
- True,
813
- ("результаты_анализа.xlsx", output_bytes_io.getvalue()), # Return tuple of (name, bytes)
814
- "Обработка завершена!",
815
- dedup_message
816
- )
 
 
 
 
 
 
 
 
 
 
817
  else:
818
- return None, None, None, False, (None, None), "Нет обработанных данных", ""
 
 
 
 
 
 
 
819
 
820
  except Exception as e:
821
  error_msg = f"Ошибка анализа: {str(e)}"
822
  logger.error(error_msg)
823
  gr.Error(error_msg)
824
- return None, None, None, False, (None, None), error_msg, ""
 
 
 
 
 
 
 
825
  finally:
826
  if detector:
827
  detector.cleanup()
828
-
829
- def trigger_download(show_button, file_content):
830
- """Handle download button visibility and file content"""
831
- return gr.update(visible=show_button), file_content
832
 
833
  stop_btn.click(fn=stop_processing, outputs=[progress])
834
  analyze_btn.click(
835
- fn=analyze,
836
  inputs=[file_input],
837
  outputs=[
 
 
838
  stats,
839
  sentiment_plot,
840
  events_plot,
841
- download_btn, # Visibility control
842
- output_file, # Actual file content
843
- progress,
844
- status_box
845
  ]
846
  )
847
 
848
- # Connect download button to file output
849
- download_btn.click(
850
- fn=trigger_download,
851
- inputs=[download_btn, output_file],
852
- outputs=[download_btn, output_file]
853
- )
854
-
855
  return app
856
 
857
  if __name__ == "__main__":
 
645
  control = ProcessControl()
646
 
647
  with gr.Blocks(theme=gr.themes.Soft()) as app:
648
+ gr.Markdown("# AI-анализ мониторинга новостей v.1.36")
649
 
650
  with gr.Row():
651
  file_input = gr.File(
 
668
  size="lg"
669
  )
670
 
 
671
  with gr.Row():
672
  status_box = gr.Textbox(
673
  label="Статус дедупликации",
 
694
  sentiment_plot = gr.Plot(label="Распределение тональности")
695
  with gr.Column(scale=1):
696
  events_plot = gr.Plot(label="Распределение событий")
697
+
 
 
 
 
698
  def stop_processing():
699
  control.request_stop()
700
  return "Остановка обработки..."
701
+
702
+ @spaces.GPU(duration=300)
703
+ def process_and_download(file_bytes):
704
+ """Process file and return download button state"""
705
  if file_bytes is None:
706
  gr.Warning("Пожалуйста, загрузите файл")
707
+ return {
708
+ "status": "Ожидание файла...",
709
+ "dedup_message": "",
710
+ "dataframe": None,
711
+ "sentiment_plot": None,
712
+ "events_plot": None,
713
+ "download": None
714
+ }
715
 
716
  try:
 
 
 
717
  file_obj = io.BytesIO(file_bytes)
718
  logger.info("File loaded into BytesIO successfully")
719
 
 
798
  # Cleanup GPU resources after batch
799
  torch.cuda.empty_cache()
800
  time.sleep(2)
801
+
802
 
803
  # Create final results
804
  if processed_rows:
805
+ result_df = pd.DataFrame(processed_rows)
806
+ output_bytes_io = create_output_file(result_df, file_obj)
807
+ fig_sentiment, fig_events = create_visualizations(result_df)
808
+
809
+ # Create download component
810
+ download = gr.Button("📥 Скачать результаты")
811
+
812
+ @download.click
813
+ def on_download_click():
814
+ return {
815
+ "name": "результаты_анализа.xlsx",
816
+ "data": output_bytes_io.getvalue(),
817
+ "mime": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
818
+ }
819
+
820
+ return {
821
+ "status": "Обработка завершена!",
822
+ "dedup_message": dedup_message,
823
+ "dataframe": result_df,
824
+ "sentiment_plot": fig_sentiment,
825
+ "events_plot": fig_events,
826
+ "download": download
827
+ }
828
  else:
829
+ return {
830
+ "status": "Нет обработанных данных",
831
+ "dedup_message": dedup_message,
832
+ "dataframe": None,
833
+ "sentiment_plot": None,
834
+ "events_plot": None,
835
+ "download": None
836
+ }
837
 
838
  except Exception as e:
839
  error_msg = f"Ошибка анализа: {str(e)}"
840
  logger.error(error_msg)
841
  gr.Error(error_msg)
842
+ return {
843
+ "status": error_msg,
844
+ "dedup_message": "",
845
+ "dataframe": None,
846
+ "sentiment_plot": None,
847
+ "events_plot": None,
848
+ "download": None
849
+ }
850
  finally:
851
  if detector:
852
  detector.cleanup()
 
 
 
 
853
 
854
  stop_btn.click(fn=stop_processing, outputs=[progress])
855
  analyze_btn.click(
856
+ fn=process_and_download,
857
  inputs=[file_input],
858
  outputs=[
859
+ progress,
860
+ status_box,
861
  stats,
862
  sentiment_plot,
863
  events_plot,
864
+ download_button # This will update dynamically
 
 
 
865
  ]
866
  )
867
 
 
 
 
 
 
 
 
868
  return app
869
 
870
  if __name__ == "__main__":