pentarosarium commited on
Commit
cb83206
·
1 Parent(s): 8275073

progress more (3.18)

Browse files
Files changed (1) hide show
  1. app.py +22 -61
app.py CHANGED
@@ -266,10 +266,6 @@ def generate_sentiment_visualization(df):
266
  return fig
267
 
268
  def process_file(uploaded_file, model_choice):
269
- #output_capture = StreamlitCapture()
270
- old_stdout = sys.stdout
271
- #sys.stdout = output_capture
272
-
273
  try:
274
  df = pd.read_excel(uploaded_file, sheet_name='Публикации')
275
  llm = init_langchain_llm(model_choice)
@@ -279,12 +275,6 @@ def process_file(uploaded_file, model_choice):
279
  st.error(f"Error: The following required columns are missing from the input file: {', '.join(missing_columns)}")
280
  st.stop()
281
 
282
- # Initialize LLM
283
- llm = init_langchain_llm(model_choice)
284
- if not llm:
285
- st.error("Не удалось инициализировать нейросеть. Пожалуйста, проверьте настройки и попробуйте снова.")
286
- st.stop()
287
-
288
  # Deduplication
289
  original_news_count = len(df)
290
  df = df.groupby('Объект', group_keys=False).apply(
@@ -327,33 +317,9 @@ def process_file(uploaded_file, model_choice):
327
  impact if sentiment == "Negative" else None,
328
  reasoning if sentiment == "Negative" else None)
329
 
330
-
331
- # Generate all output files
332
- st.write("Генерация отчета...")
333
-
334
- # 1. Generate Excel
335
- excel_output = create_output_file(df, uploaded_file, llm)
336
-
337
- # 2. Generate PDF
338
- #st.write("Создание PDF протокола...")
339
- #pdf_data = generate_pdf_report(output_capture.texts)
340
-
341
- # Save PDF to disk
342
- #if pdf_data:
343
- # with open("result.pdf", "wb") as f:
344
- # f.write(pdf_data)
345
- # st.success("PDF протокол сохранен как 'result.pdf'")
346
-
347
- # Show success message
348
- #st.success(f"✅ Обработка и анализ завершены за умеренное время.")
349
-
350
- # Create download section
351
- create_download_section(excel_output,"")
352
-
353
  return df
354
 
355
  except Exception as e:
356
- sys.stdout = old_stdout
357
  st.error(f"❌ Ошибка при обработке файла: {str(e)}")
358
  raise e
359
 
@@ -457,34 +423,16 @@ def create_output_file(df, uploaded_file, llm):
457
 
458
  def main():
459
  with st.sidebar:
460
- st.title("::: AI-анализ мониторинга новостей (v.3.17):::")
461
  st.subheader("по материалам СКАН-ИНТЕРФАКС ")
462
 
 
463
  model_choice = st.radio(
464
  "Выберите модель для анализа:",
465
  ["Groq (llama-3.1-70b)", "ChatGPT-4-mini", "NVIDIA Nemotron-70B"],
466
  key="model_selector"
467
  )
468
 
469
- st.markdown(
470
- """
471
- Использованы технологии:
472
- - Анализ естественного языка с помощью предтренированных нейросетей **BERT**,<br/>
473
- - Дополнительная обработка при помощи больших языковых моделей (**LLM**),<br/>
474
- - объединенные при помощи фреймворка **LangChain**.<br>
475
- """,
476
- unsafe_allow_html=True)
477
-
478
- # Model selection is now handled in init_langchain_llm()
479
-
480
- with st.expander("ℹ️ Инструкция"):
481
- st.markdown("""
482
- 1. Выберите модель для анализа
483
- 2. Загрузите Excel файл с новостями <br/>
484
- 3. Дождитесь завершения анализа <br/>
485
- 4. Скачайте результаты анализа в формате Excel <br/>
486
- """, unsafe_allow_html=True)
487
-
488
  st.markdown(
489
  """
490
  <style>
@@ -503,22 +451,35 @@ def main():
503
  unsafe_allow_html=True
504
  )
505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
506
  st.title("Анализ мониторинга новостей")
507
 
508
  if 'processed_df' not in st.session_state:
509
  st.session_state.processed_df = None
510
 
511
- # Single file uploader with unique key
512
  uploaded_file = st.sidebar.file_uploader("Выбирайте Excel-файл", type="xlsx", key="unique_file_uploader")
513
 
514
  if uploaded_file is not None and st.session_state.processed_df is None:
515
  start_time = time.time()
516
 
517
-
518
- # Initialize LLM with selected model
519
- llm = init_langchain_llm(model_choice)
520
-
521
-
522
  st.session_state.processed_df = process_file(uploaded_file, model_choice)
523
 
524
  st.subheader("Предпросмотр данных")
@@ -529,7 +490,7 @@ def main():
529
  st.subheader("Анализ")
530
  st.dataframe(analysis_df)
531
 
532
-
533
  output = create_output_file(st.session_state.processed_df, uploaded_file, llm)
534
 
535
  end_time = time.time()
 
266
  return fig
267
 
268
  def process_file(uploaded_file, model_choice):
 
 
 
 
269
  try:
270
  df = pd.read_excel(uploaded_file, sheet_name='Публикации')
271
  llm = init_langchain_llm(model_choice)
 
275
  st.error(f"Error: The following required columns are missing from the input file: {', '.join(missing_columns)}")
276
  st.stop()
277
 
 
 
 
 
 
 
278
  # Deduplication
279
  original_news_count = len(df)
280
  df = df.groupby('Объект', group_keys=False).apply(
 
317
  impact if sentiment == "Negative" else None,
318
  reasoning if sentiment == "Negative" else None)
319
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320
  return df
321
 
322
  except Exception as e:
 
323
  st.error(f"❌ Ошибка при обработке файла: {str(e)}")
324
  raise e
325
 
 
423
 
424
  def main():
425
  with st.sidebar:
426
+ st.title("::: AI-анализ мониторинга новостей (v.3.18):::")
427
  st.subheader("по материалам СКАН-ИНТЕРФАКС ")
428
 
429
+ # Model selection at the top level
430
  model_choice = st.radio(
431
  "Выберите модель для анализа:",
432
  ["Groq (llama-3.1-70b)", "ChatGPT-4-mini", "NVIDIA Nemotron-70B"],
433
  key="model_selector"
434
  )
435
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
436
  st.markdown(
437
  """
438
  <style>
 
451
  unsafe_allow_html=True
452
  )
453
 
454
+
455
+ st.markdown(
456
+ """
457
+ Использованы технологии:
458
+ - Анализ естественного языка с помощью предтренированных нейросетей **BERT**,<br/>
459
+ - Дополнительная обработка при помощи больших языковых моделей (**LLM**),<br/>
460
+ - объединенные при помощи фреймворка **LangChain**.<br>
461
+ """,
462
+ unsafe_allow_html=True)
463
+
464
+ with st.expander("ℹ️ Инструкция"):
465
+ st.markdown("""
466
+ 1. Выберите модель для анализа
467
+ 2. Загрузите Excel файл с новостями <br/>
468
+ 3. Дождитесь завершения анализа <br/>
469
+ 4. Скачайте результаты анализа в формате Excel <br/>
470
+ """, unsafe_allow_html=True)
471
+
472
  st.title("Анализ мониторинга новостей")
473
 
474
  if 'processed_df' not in st.session_state:
475
  st.session_state.processed_df = None
476
 
 
477
  uploaded_file = st.sidebar.file_uploader("Выбирайте Excel-файл", type="xlsx", key="unique_file_uploader")
478
 
479
  if uploaded_file is not None and st.session_state.processed_df is None:
480
  start_time = time.time()
481
 
482
+ # Pass model_choice to process_file
 
 
 
 
483
  st.session_state.processed_df = process_file(uploaded_file, model_choice)
484
 
485
  st.subheader("Предпросмотр данных")
 
490
  st.subheader("Анализ")
491
  st.dataframe(analysis_df)
492
 
493
+ llm = init_langchain_llm(model_choice)
494
  output = create_output_file(st.session_state.processed_df, uploaded_file, llm)
495
 
496
  end_time = time.time()