SandraKorol commited on
Commit
41d79f8
·
verified ·
1 Parent(s): b11806b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +279 -0
app.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import pipeline
2
+ import gradio as gr
3
+ import pandas as pd
4
+ from datetime import datetime
5
+
6
+ sentiment_pipe = pipeline('sentiment-analysis',model='distilbert-base-uncased-finetuned-sst-2-english')
7
+
8
+ summarizer_pipe = pipeline('text-generation', model='sshleifer/distilbart-cnn-12-6')
9
+
10
+ def format_sentiment_result(label, score):
11
+
12
+ color = '#6366f1' if label == 'POSITIVE' else '#ef4444'
13
+ bg = '#eef2ff' if label == 'POSITIVE' else '#fef2f2'
14
+
15
+ emoji = '😊' if label == 'POSITIVE' else '😞'
16
+ bar_w = int(score * 100)
17
+
18
+ if score > 0.9:
19
+ confidence_text = 'Дуже впевнено'
20
+ elif score >= 0.7:
21
+ confidence_text = 'Впевнено'
22
+ else:
23
+ confidence_text = 'Непевно'
24
+
25
+ return f'''
26
+ <div style="padding:20px; border-radius:14px; background:{bg};
27
+ border:2px solid {color}; font-family:Arial;">
28
+
29
+ <style>
30
+ @keyframes fillBar {{
31
+ from {{ width: 0%; }}
32
+ to {{ width: {bar_w}%; }}
33
+ }}
34
+ </style>
35
+
36
+ <div style="font-size:2.5em; text-align:center">{emoji}</div>
37
+
38
+ <div style="text-align:center; font-size:1.5em; font-weight:bold;
39
+ color:{color}; margin:8px 0">
40
+ {label}
41
+ </div>
42
+
43
+ <div style="background:#e5e7eb; border-radius:10px; height:12px; margin:10px 0; overflow:hidden">
44
+ <div style="background:{color}; width:{bar_w}%;
45
+ height:12px; border-radius:10px;
46
+ animation: fillBar 1s ease-out;">
47
+ </div>
48
+ </div>
49
+
50
+ <div style="width:100%; margin:0 auto;">
51
+ <div style="text-align:center; color:#555">
52
+ Впевненість:
53
+ <b style="color: {color}">{score:.1%}</b>
54
+ </div>
55
+
56
+ <div style="text-align:center; margin-top:6px; color:#666; font-size:0.95em">
57
+ {confidence_text}
58
+ </div>
59
+ </div>
60
+
61
+ </div>
62
+ '''
63
+
64
+ def summarize_stream(text):
65
+ """Streaming-генератор для поступового виводу резюме."""
66
+ if not text.strip():
67
+ yield 'Введіть текст для резюмування'
68
+ return
69
+ if len(text.split()) < 30:
70
+ yield 'Текст занадто короткий (потрібно мінімум 30 слів)'
71
+ return
72
+ words_in = text.split()
73
+
74
+ if len(words_in) > 700:
75
+ text = ' '.join(words_in[:700])
76
+
77
+ result = summarizer_pipe(text, max_length=100, min_length=25)[0]
78
+
79
+ summary = result['summary_text']
80
+ words = summary.split()
81
+ accumulated = ''
82
+
83
+ for word in words:
84
+ accumulated += word + ' '
85
+ yield accumulated.strip()
86
+
87
+
88
+ ratio = len(words_in) / max(len(words), 1)
89
+ yield accumulated.strip() + f'\n\n[Стиснення: {ratio:.1f}x | {len(words_in)} → {len(words)} слів]'
90
+
91
+
92
+ def clear_all():
93
+ return (
94
+ [],
95
+ [],
96
+ '**Статистика сесії:** немає даних',
97
+ [],
98
+ ''
99
+ )
100
+
101
+ def analyze_with_history_and_stats(text, history):
102
+ """
103
+ Повертає 4 значення: html_card, history, DataFrame, stats_markdown.
104
+ """
105
+ if not text.strip():
106
+ empty_html = '<p style="color:#999; text-align:center">Введіть текст</p>'
107
+ df = pd.DataFrame(history) if history else pd.DataFrame( columns=['Час', 'Текст', 'Результат', 'Впевн.'])
108
+
109
+ return empty_html, history, df, get_stats(history)
110
+
111
+ res = sentiment_pipe(text)[0]
112
+ label = res['label']
113
+ score = res['score']
114
+ html_card = format_sentiment_result(label, score)
115
+ entry = {'Час' : datetime.now().strftime('%H:%M:%S'),
116
+
117
+ 'Текст' : text[:45] + '...' if len(text) > 45 else text,
118
+ 'Результат': label,
119
+ 'Впевн.' : f'{score:.1%}'
120
+ }
121
+
122
+ updated_history = history + [entry]
123
+ df = pd.DataFrame(updated_history)
124
+ stats = get_stats(updated_history)
125
+ return html_card, updated_history, df, stats
126
+
127
+ def get_stats(history):
128
+ """Повертає Markdown-рядок зі статистикою сесії."""
129
+
130
+ if not history:
131
+ return "**Статистика сесії:** немає даних"
132
+
133
+
134
+ print(history.keys())
135
+
136
+ total = len(history)
137
+
138
+ pos = sum(1 for h in history if h["Результат"] == "POSITIVE")
139
+ neg = total - pos
140
+
141
+ pct_p = pos / total * 100
142
+ pct_n = neg / total * 100
143
+
144
+ longest = max(history, key=lambda h: len(h["Текст"].split()))
145
+ longest_words = len(longest["Текст"].split())
146
+
147
+ avg_conf = sum(h["Впевн"] for h in history) / total
148
+
149
+
150
+ times = [h["Час"] for h in history]
151
+ first_time = min(times).strftime("%H:%M:%S")
152
+ last_time = max(times).strftime("%H:%M:%S")
153
+
154
+ return (
155
+ f'📊 **Статистика сесії**\n\n'
156
+ f'Всього аналізів: **{total}** | '
157
+ f'Позитивних: **{pos}** ({pct_p:.0f}%) | '
158
+ f'Негативних: **{neg}** ({pct_n:.0f}%)'
159
+ f'Найдовший текст: **{longest_words} слів**\n | '
160
+ f'Середня впевненість: **{avg_conf:.2f}**\n | '
161
+ f'Перша сесія: **{first_time}**\n | '
162
+ f'Остання сесія: **{last_time}** | '
163
+ )
164
+
165
+ def save_to_wishlist(text, wishlist):
166
+ if not text.strip():
167
+ return wishlist, '\n'.join(wishlist)
168
+
169
+ wishlist.append(text)
170
+
171
+ return wishlist, '\n'.join(
172
+ f'{i + 1}. {item}'
173
+ for i, item in enumerate(wishlist)
174
+ )
175
+
176
+ with gr.Blocks(title='NLP Analytics Dashboard', theme=gr.themes.Glass(),
177
+ ) as demo:
178
+
179
+ gr.Markdown('# NLP Analytics Dashboard')
180
+ gr.Markdown('Аналізуй текст, накопичуй статистику, порівнюй результати.')
181
+
182
+ history_state = gr.State([])
183
+ wishlist_state = gr.State([])
184
+
185
+
186
+ with gr.Row(equal_height=False):
187
+
188
+ with gr.Column(scale=1):
189
+ gr.Markdown('### Аналіз тональності')
190
+
191
+ text_in = gr.Textbox(
192
+ lines=5,
193
+ label='Текст',
194
+ placeholder='Введіть відгук, твіт або будь-який текст...'
195
+ )
196
+
197
+ char_count = gr.Markdown('Символів: 0')
198
+
199
+ analyze_btn = gr.Button('Аналізувати', variant='primary')
200
+ clear_btn = gr.Button('Очистити', variant='secondary')
201
+ save_btn = gr.Button('Зберегти', variant='secondary')
202
+
203
+ html_out = gr.HTML(label='Результат')
204
+
205
+ with gr.Column(scale=1):
206
+ gr.Markdown('### Резюмування')
207
+
208
+ sum_text = gr.Textbox(
209
+ lines=5,
210
+ label='Текст для резюмування',
211
+ placeholder='Вставте статтю або довгий текст...'
212
+ )
213
+
214
+ with gr.Accordion('Параметри резюмування', open=False):
215
+ max_len = gr.Slider(
216
+ 30, 200, value=80, step=10,
217
+ label='Макс. довжина (токени)'
218
+ )
219
+
220
+ sum_btn = gr.Button('Резюмувати ', variant='primary')
221
+
222
+ sum_out = gr.Textbox(lines=4, label='Резюме', interactive=False)
223
+
224
+ gr.Markdown('---')
225
+
226
+ stats_md = gr.Markdown('**Статистика сесії:** немає даних')
227
+
228
+ with gr.Accordion('Історія аналізів', open=True):
229
+ history_table = gr.DataFrame(
230
+ headers=['Час', 'Текст', 'Результат', 'Впевн.'],
231
+ label='Всі аналізи цієї сесії',
232
+ interactive=False
233
+ )
234
+
235
+ with gr.Accordion('Wishlist', open=True):
236
+ wishlist_box = gr.Textbox(
237
+ label='Збережені тексти',
238
+ lines=8,
239
+ interactive=False
240
+ )
241
+
242
+
243
+ text_in.change(
244
+ fn=lambda txt: f'Символів: {len(txt)} | Слів: {len(txt.split())}',
245
+ inputs=text_in,
246
+ outputs=char_count
247
+ )
248
+
249
+ for trigger in [analyze_btn.click, text_in.submit]:
250
+ trigger(
251
+ fn=analyze_with_history_and_stats,
252
+ inputs=[text_in, history_state],
253
+ outputs=[html_out, history_state, history_table, stats_md]
254
+ )
255
+
256
+ save_btn.click(
257
+ fn=save_to_wishlist,
258
+ inputs=[text_in, wishlist_state],
259
+ outputs=[wishlist_state, wishlist_box]
260
+ )
261
+
262
+ clear_btn.click(
263
+ fn=clear_all,
264
+ outputs=[
265
+ history_state,
266
+ history_table,
267
+ stats_md,
268
+ wishlist_state,
269
+ wishlist_box
270
+ ]
271
+ )
272
+
273
+ sum_btn.click(
274
+ fn=summarize_stream,
275
+ inputs=sum_text,
276
+ outputs=sum_out
277
+ )
278
+
279
+ demo.launch(favicon_path='/content/icon/favicon.ico')