pentarosarium commited on
Commit
2e57f71
·
1 Parent(s): 4cd2605

progress more (3.7)

Browse files
Files changed (1) hide show
  1. app.py +35 -36
app.py CHANGED
@@ -18,24 +18,10 @@ import pdfkit
18
  from jinja2 import Template
19
 
20
 
21
- def create_download_section(excel_data, output_capture):
22
  st.markdown("""
23
- <style>
24
- .download-container {
25
- padding: 20px;
26
- background-color: #f0f2f6;
27
- border-radius: 10px;
28
- margin: 20px 0;
29
- }
30
- .download-header {
31
- color: #0066cc;
32
- font-size: 18px;
33
- font-weight: bold;
34
- margin-bottom: 10px;
35
- }
36
- </style>
37
  <div class="download-container">
38
- <div class="download-header">📥 Результаты анализа готовы к скачиванию:</div>
39
  </div>
40
  """, unsafe_allow_html=True)
41
 
@@ -54,20 +40,17 @@ def create_download_section(excel_data, output_capture):
54
  st.error("Ошибка при создании Excel файла")
55
 
56
  with col2:
57
- try:
58
- pdf_data = generate_pdf_report(output_capture.texts)
59
- if pdf_data:
60
- st.download_button(
61
- label="📄 Скачать протокол",
62
- data=pdf_data,
63
- file_name="протокол_анализа.pdf" if isinstance(pdf_data, bytes) else "протокол_анализа.txt",
64
- mime="application/pdf" if isinstance(pdf_data, bytes) else "text/plain",
65
- key="pdf_download"
66
- )
67
- else:
68
- st.error("Ошибка при создании протокола")
69
- except Exception as e:
70
- st.error(f"Ошибка при создании протокола: {str(e)}")
71
 
72
  def display_sentiment_results(row, sentiment, impact=None, reasoning=None):
73
  if sentiment == "Negative":
@@ -114,6 +97,8 @@ def generate_pdf_report(texts):
114
  import pdfkit
115
  from jinja2 import Template
116
 
 
 
117
  html_content = """
118
  <html>
119
  <head>
@@ -137,11 +122,14 @@ def generate_pdf_report(texts):
137
  rendered_html = template.render(texts=texts)
138
 
139
  # Create PDF in memory
140
- pdf_data = pdfkit.from_string(rendered_html, False)
 
 
141
  return pdf_data
142
 
143
  except Exception as e:
144
  st.warning(f"Не удалось создать PDF отчет: {str(e)}")
 
145
  # Return the text as bytes if PDF generation fails
146
  return '\n'.join(texts).encode('utf-8')
147
 
@@ -359,16 +347,27 @@ def process_file(uploaded_file):
359
  reasoning if sentiment == "Negative" else None)
360
 
361
 
362
- sys.stdout = old_stdout
 
363
 
364
- # Prepare Excel file
365
  excel_output = create_output_file(df, uploaded_file)
366
 
 
 
 
 
 
 
 
 
 
 
367
  # Show success message
368
- st.success(f"✅ Обработка и анализ завершены за умеренное время.")
369
 
370
  # Create download section
371
- create_download_section(excel_output, output_capture)
372
 
373
  return df
374
 
@@ -496,7 +495,7 @@ def main():
496
  unsafe_allow_html=True
497
  )
498
 
499
- st.title("::: анализ мониторинга новостей СКАН-ИНТЕРФАКС (v.3.62):::")
500
 
501
  if 'processed_df' not in st.session_state:
502
  st.session_state.processed_df = None
 
18
  from jinja2 import Template
19
 
20
 
21
+ def create_download_section(excel_data, pdf_data):
22
  st.markdown("""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  <div class="download-container">
24
+ <div class="download-header">📥 Результаты анализа доступны для скачивания:</div>
25
  </div>
26
  """, unsafe_allow_html=True)
27
 
 
40
  st.error("Ошибка при создании Excel файла")
41
 
42
  with col2:
43
+ if pdf_data is not None:
44
+ st.download_button(
45
+ label="📄 Скачать PDF протокол",
46
+ data=pdf_data,
47
+ file_name="протокол_анализа.pdf",
48
+ mime="application/pdf",
49
+ key="pdf_download"
50
+ )
51
+ else:
52
+ st.error("Ошибка при создании PDF файла")
53
+
 
 
 
54
 
55
  def display_sentiment_results(row, sentiment, impact=None, reasoning=None):
56
  if sentiment == "Negative":
 
97
  import pdfkit
98
  from jinja2 import Template
99
 
100
+ st.write("Подготовка PDF...")
101
+
102
  html_content = """
103
  <html>
104
  <head>
 
122
  rendered_html = template.render(texts=texts)
123
 
124
  # Create PDF in memory
125
+ st.write("Конвертация в PDF...")
126
+ pdf_data = pdfkit.from_string(rendered_html, False) # False means return PDF as bytes
127
+ st.write("PDF успешно создан")
128
  return pdf_data
129
 
130
  except Exception as e:
131
  st.warning(f"Не удалось создать PDF отчет: {str(e)}")
132
+ st.write("Создание текстового отчета вместо PDF...")
133
  # Return the text as bytes if PDF generation fails
134
  return '\n'.join(texts).encode('utf-8')
135
 
 
347
  reasoning if sentiment == "Negative" else None)
348
 
349
 
350
+ # Generate all output files
351
+ st.write("Генерация отчетов...")
352
 
353
+ # 1. Generate Excel
354
  excel_output = create_output_file(df, uploaded_file)
355
 
356
+ # 2. Generate PDF
357
+ st.write("Создание PDF протокола...")
358
+ pdf_data = generate_pdf_report(output_capture.texts)
359
+
360
+ # Save PDF to disk
361
+ if pdf_data:
362
+ with open("result.pdf", "wb") as f:
363
+ f.write(pdf_data)
364
+ st.success("PDF протокол сохранен как 'result.pdf'")
365
+
366
  # Show success message
367
+ st.success(f"✅ Обработка и анализ завершены за {formatted_time}.")
368
 
369
  # Create download section
370
+ create_download_section(excel_output, pdf_data)
371
 
372
  return df
373
 
 
495
  unsafe_allow_html=True
496
  )
497
 
498
+ st.title("::: анализ мониторинга новостей СКАН-ИНТЕРФАКС (v.3.7):::")
499
 
500
  if 'processed_df' not in st.session_state:
501
  st.session_state.processed_df = None