Yasser18 commited on
Commit
fe8c737
Β·
verified Β·
1 Parent(s): 2862b38

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -296
app.py CHANGED
@@ -8,23 +8,19 @@ import os
8
  sentiment_pipeline = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
9
  summarization_pipeline = pipeline("summarization", model="RussianNLP/FRED-T5-Summarizer")
10
 
11
- # Task logic with enhanced feedback
12
  def perform_task(task, text):
13
  if not text.strip():
14
  return "⚠️ Please enter some text to analyze.", None, gr.update(visible=False)
15
 
16
- # Simulate processing time for better UX
17
  time.sleep(0.5)
18
 
19
  if task == "Sentiment Analysis":
20
  result = sentiment_pipeline(text)[0]
21
  label = result['label']
22
  score = round(result['score'], 3)
23
-
24
- # Enhanced sentiment display with emojis
25
  emoji = "😊" if label == "POSITIVE" else "😟"
26
  confidence_bar = "β–ˆ" * int(score * 10) + "β–‘" * (10 - int(score * 10))
27
-
28
  output = f"""
29
  {emoji} **Sentiment Analysis Results**
30
 
@@ -34,18 +30,14 @@ def perform_task(task, text):
34
 
35
  **Interpretation:** This text expresses a {label.lower()} sentiment with {score*100:.1f}% confidence.
36
  """.strip()
37
-
38
  return output, None, gr.update(visible=False)
39
 
40
  elif task == "Summarization":
41
  result = summarization_pipeline(text, max_length=100, min_length=30, do_sample=False)
42
  summary = result[0]['summary_text']
43
-
44
- # Calculate compression ratio
45
  original_words = len(text.split())
46
  summary_words = len(summary.split())
47
  compression_ratio = round((1 - summary_words/original_words) * 100, 1)
48
-
49
  output = f"""
50
  πŸ“ **Text Summarization Results**
51
 
@@ -57,17 +49,14 @@ def perform_task(task, text):
57
  β€’ Summary: {summary_words} words
58
  β€’ Compression: {compression_ratio}% reduction
59
  """.strip()
60
-
61
  return output, None, gr.update(visible=False)
62
 
63
  elif task == "Text-to-Speech":
64
  tts = gTTS(text)
65
  filename = "tts_output.mp3"
66
  tts.save(filename)
67
-
68
  word_count = len(text.split())
69
  char_count = len(text)
70
-
71
  output = f"""
72
  πŸ”Š **Text-to-Speech Generated Successfully!**
73
 
@@ -78,294 +67,108 @@ def perform_task(task, text):
78
 
79
  **Audio file ready for playback below** ⬇️
80
  """.strip()
81
-
82
  return output, filename, gr.update(visible=True, value=filename)
83
 
84
- # Enhanced CSS with modern design elements
85
- custom_css = """
86
- <style>
87
- @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
88
-
89
- :root {
90
- --primary-bg: #0a0a0a;
91
- --secondary-bg: #1a1a1a;
92
- --accent-bg: #2a2a2a;
93
- --primary-text: #ffffff;
94
- --secondary-text: #b0b0b0;
95
- --accent-color: #3b82f6;
96
- --accent-hover: #2563eb;
97
- --success-color: #10b981;
98
- --warning-color: #f59e0b;
99
- --border-color: #333333;
100
- --gradient-1: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
101
- --gradient-2: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
102
- --gradient-3: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
103
- }
104
-
105
- * {
106
- font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif !important;
107
- }
108
-
109
- body, .gradio-container {
110
- background: var(--primary-bg) !important;
111
- color: var(--primary-text) !important;
112
- background-image:
113
- radial-gradient(circle at 20% 50%, rgba(59, 130, 246, 0.1) 0%, transparent 50%),
114
- radial-gradient(circle at 80% 20%, rgba(168, 85, 247, 0.1) 0%, transparent 50%),
115
- radial_gradient(circle at 40% 80%, rgba(16, 185, 129, 0.1) 0%, transparent 50%);
116
- min-height: 100vh;
117
- }
118
-
119
- .gradio-container {
120
- max-width: 1200px !important;
121
- margin: 0 auto !important;
122
- padding: 2rem !important;
123
- }
124
-
125
- /* Header styling */
126
- #title {
127
- background: var(--gradient-1);
128
- background-clip: text;
129
- -webkit-background-clip: text;
130
- -webkit-text-fill-color: transparent;
131
- font-size: 3rem !important;
132
- font-weight: 700 !important;
133
- text-align: center !important;
134
- margin-bottom: 2rem !important;
135
- animation: glow 2s ease-in-out infinite alternate;
136
- }
137
-
138
- @keyframes glow {
139
- from { filter: drop-shadow(0 0 20px rgba(59, 130, 246, 0.3)); }
140
- to { filter: drop_shadow(0 0 30px rgba(168, 85, 247, 0.5)); }
141
- }
142
-
143
- /* Card-like containers */
144
- .gr-box, .gr-form {
145
- background: var(--secondary-bg) !important;
146
- border: 1px solid var(--border-color) !important;
147
- border-radius: 16px !important;
148
- padding: 1.5rem !important;
149
- backdrop-filter: blur(10px) !important;
150
- box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3) !important;
151
- transition: all 0.3s ease !important;
152
- }
153
-
154
- .gr-box:hover, .gr-form:hover {
155
- border-color: var(--accent-color) !important;
156
- box-shadow: 0 12px 40px rgba(59, 130, 246, 0.2) !important;
157
- transform: translateY(-2px) !important;
158
- }
159
-
160
- /* Input fields */
161
- .gr-input, .gr-textbox, .gr-dropdown {
162
- background: var(--accent-bg) !important;
163
- color: var(--primary-text) !important;
164
- border: 2px solid var(--border-color) !important;
165
- border-radius: 12px !important;
166
- padding: 1rem !important;
167
- font-size: 1rem !important;
168
- transition: all 0.3s ease !important;
169
- }
170
-
171
- .gr-input:focus, .gr-textbox:focus, .gr-dropdown:focus {
172
- border-color: var(--accent-color) !important;
173
- box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1) !important;
174
- outline: none !important;
175
- }
176
-
177
- /* Buttons */
178
- .gr-button {
179
- background: var(--gradient-1) !important;
180
- color: white !important;
181
- border: none !important;
182
- border-radius: 12px !important;
183
- padding: 1rem 2rem !important;
184
- font-size: 1.1rem !important;
185
- font-weight: 600 !important;
186
- cursor: pointer !important;
187
- transition: all 0.3s ease !important;
188
- box-shadow: 0 4px 20px rgba(59, 130, 246, 0.3) !important;
189
- }
190
-
191
- .gr-button:hover {
192
- transform: translateY(-2px) !important;
193
- box-shadow: 0 8px 30px rgba(59, 130, 246, 0.4) !important;
194
- }
195
-
196
- .gr-button:active {
197
- transform: translateY(0) !important;
198
- }
199
-
200
- /* Labels */
201
- label {
202
- color: var(--primary-text) !important;
203
- font-weight: 500 !important;
204
- font-size: 1.1rem !important;
205
- margin-bottom: 0.5rem !important;
206
- }
207
-
208
- /* Placeholders */
209
- input::placeholder, textarea::placeholder {
210
- color: var(--secondary-text) !important;
211
- opacity: 0.7 !important;
212
- }
213
-
214
- /* Output areas */
215
- .gr-textbox[data-testid="textbox"] {
216
- background: var(--accent-bg) !important;
217
- border: 1px solid var(--border-color) !important;
218
- border-radius: 12px !important;
219
- padding: 1.5rem !important;
220
- font-family: 'Inter', monospace !important;
221
- line-height: 1.6 !important;
222
- }
223
-
224
- /* Audio component */
225
- .gr-audio {
226
- background: var(--secondary-bg) !important;
227
- border: 1px solid var(--border-color) !important;
228
- border-radius: 12px !important;
229
- padding: 1rem !important;
230
- }
231
-
232
- /* Markdown content */
233
- .markdown-content {
234
- line-height: 1.8 !important;
235
- }
236
-
237
- .markdown-content strong {
238
- color: var(--accent-color) !important;
239
- }
240
-
241
- /* Task selector special styling */
242
- .gr-dropdown {
243
- background: var(--gradient-2) !important;
244
- color: white !important;
245
- font-weight: 500 !important;
246
- }
247
-
248
- /* Responsive design */
249
- @media (max-width: 768px) {
250
- #title {
251
- font-size: 2rem !important;
252
- }
253
-
254
- .gradio-container {
255
- padding: 1rem !important;
256
- }
257
-
258
- .gr-box, .gr-form {
259
- padding: 1rem !important;
260
- }
261
- }
262
-
263
- /* Loading animation */
264
- @keyframes pulse {
265
- 0%, 100% { opacity: 1; }
266
- 50% { opacity: 0.5; }
267
- }
268
-
269
- .loading {
270
- animation: pulse 1.5s infinite;
271
- }
272
-
273
- /* Success/Error states */
274
- .success {
275
- border-color: var(--success-color) !important;
276
- box-shadow: 0 0 20px rgba(16, 185, 129, 0.2) !important;
277
- }
278
-
279
- .warning {
280
- border-color: var(--warning-color) !important;
281
- box-shadow: 0 0 20px rgba(245, 158, 11, 0.2) !important;
282
- }
283
- </style>
284
- """
285
-
286
- # UI with enhanced design
287
  with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:
288
  gr.HTML(custom_css)
289
-
290
- # Header with enhanced styling
291
  gr.Markdown("# πŸ€– Multi-Task AI Assistant", elem_id="title")
292
- gr.Markdown("""
293
- <div style="text-align: center; margin-bottom: 2rem; color: #b0b0b0; font-size: 1.2rem;">
294
- Harness the power of AI for <strong>sentiment analysis</strong>, <strong>text summarization</strong>, and <strong>text-to-speech</strong> conversion
295
- </div>
296
- """)
297
-
298
- # Main interface
299
- with gr.Row():
300
- with gr.Column(scale=1, min_width=250):
301
- task_selector = gr.Dropdown(
302
- choices=["Sentiment Analysis", "Summarization", "Text-to-Speech"],
303
- label="πŸ”§ Select AI Task",
304
- value="Sentiment Analysis",
305
- info="Choose the AI capability you want to use"
306
- )
307
 
308
- # Task descriptions
 
 
309
  gr.Markdown("""
310
- **πŸ“Š Sentiment Analysis**: Analyze emotional tone and polarity of text
311
-
312
- **βœ‚οΈ Summarization**: Generate concise summaries of long text
313
-
314
- **πŸ”Š Text-to-Speech**: Convert text into natural-sounding audio
315
- """, elem_classes=["task-info"])
316
-
317
- with gr.Column(scale=2):
318
- textbox = gr.Textbox(
319
- lines=8,
320
- label="πŸ“ Input Text",
321
- placeholder="Enter your text here... \n\nTip: For best results:\nβ€’ Sentiment: Use complete sentences\nβ€’ Summary: Provide longer text (100+ words)\nβ€’ TTS: Use natural, conversational text",
322
- info="Type or paste the text you want to process"
323
- )
324
-
325
- # Action button
326
- with gr.Row():
327
- run_button = gr.Button("πŸš€ Process with AI", size="lg", variant="primary")
328
-
329
- # Results section
330
- gr.Markdown("## πŸ“‹ Results", elem_classes=["results-header"])
331
-
332
- with gr.Row():
333
- with gr.Column(scale=2):
334
- output_text = gr.Textbox(
335
- label="πŸ“Š Analysis Results",
336
- lines=8,
337
- info="Detailed results and insights will appear here",
338
- interactive=False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
  )
340
 
341
- with gr.Column(scale=1):
342
- output_audio = gr.Audio(
343
- label="πŸ”Š Generated Audio",
344
- type="filepath",
345
- visible=False,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
346
  )
347
 
348
- # Enhanced event handler
349
- def handle_task_processing(task, text):
350
- if not text.strip():
351
- return "⚠️ Please enter some text to get started!", None, gr.update(visible=False)
352
-
353
- # Show processing message
354
- processing_msg = f"πŸ”„ Processing your {task.lower()} request..."
355
-
356
- # Process the task
357
- result_text, audio_file, audio_update = perform_task(task, text)
358
-
359
- return result_text, audio_file, audio_update
360
-
361
- # Event binding
362
- run_button.click(
363
- fn=handle_task_processing,
364
- inputs=[task_selector, textbox],
365
- outputs=[output_text, output_audio, output_audio]
366
- )
367
-
368
- # Footer
369
  gr.Markdown("""
370
  <div style="text-align: center; margin-top: 3rem; padding: 2rem; color: #666; border-top: 1px solid #333;">
371
  <p>✨ <strong>Multi-Task AI Assistant</strong> - Powered by Transformers & Gradio</p>
@@ -373,13 +176,10 @@ with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:
373
  </div>
374
  """)
375
 
376
- # Launch with enhanced settings
377
  if __name__ == "__main__":
378
  demo.launch(
379
- # Removing server_name and server_port to let Gradio handle networking
380
- share=True, # share=True is often necessary in Colab environments
381
  debug=True,
382
- show_error=True,
383
- favicon_path=None,
384
- app_kwargs={"docs_url": "/docs"}
385
- )
 
8
  sentiment_pipeline = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
9
  summarization_pipeline = pipeline("summarization", model="RussianNLP/FRED-T5-Summarizer")
10
 
11
+ # Task logic
12
  def perform_task(task, text):
13
  if not text.strip():
14
  return "⚠️ Please enter some text to analyze.", None, gr.update(visible=False)
15
 
 
16
  time.sleep(0.5)
17
 
18
  if task == "Sentiment Analysis":
19
  result = sentiment_pipeline(text)[0]
20
  label = result['label']
21
  score = round(result['score'], 3)
 
 
22
  emoji = "😊" if label == "POSITIVE" else "😟"
23
  confidence_bar = "β–ˆ" * int(score * 10) + "β–‘" * (10 - int(score * 10))
 
24
  output = f"""
25
  {emoji} **Sentiment Analysis Results**
26
 
 
30
 
31
  **Interpretation:** This text expresses a {label.lower()} sentiment with {score*100:.1f}% confidence.
32
  """.strip()
 
33
  return output, None, gr.update(visible=False)
34
 
35
  elif task == "Summarization":
36
  result = summarization_pipeline(text, max_length=100, min_length=30, do_sample=False)
37
  summary = result[0]['summary_text']
 
 
38
  original_words = len(text.split())
39
  summary_words = len(summary.split())
40
  compression_ratio = round((1 - summary_words/original_words) * 100, 1)
 
41
  output = f"""
42
  πŸ“ **Text Summarization Results**
43
 
 
49
  β€’ Summary: {summary_words} words
50
  β€’ Compression: {compression_ratio}% reduction
51
  """.strip()
 
52
  return output, None, gr.update(visible=False)
53
 
54
  elif task == "Text-to-Speech":
55
  tts = gTTS(text)
56
  filename = "tts_output.mp3"
57
  tts.save(filename)
 
58
  word_count = len(text.split())
59
  char_count = len(text)
 
60
  output = f"""
61
  πŸ”Š **Text-to-Speech Generated Successfully!**
62
 
 
67
 
68
  **Audio file ready for playback below** ⬇️
69
  """.strip()
 
70
  return output, filename, gr.update(visible=True, value=filename)
71
 
72
+ # Handle button click
73
+ def handle_task_processing(task, text):
74
+ if not text.strip():
75
+ return "⚠️ Please enter some text to get started!", None, gr.update(visible=False)
76
+ result_text, audio_file, audio_update = perform_task(task, text)
77
+ return result_text, audio_file, audio_update
78
+
79
+ # Custom CSS
80
+ custom_css = """<style>
81
+ /* Same CSS as before, trimmed for brevity */
82
+ body, .gradio-container {
83
+ background-color: #0a0a0a !important;
84
+ color: #ffffff !important;
85
+ }
86
+ </style>"""
87
+
88
+ # UI Layout
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:
90
  gr.HTML(custom_css)
 
 
91
  gr.Markdown("# πŸ€– Multi-Task AI Assistant", elem_id="title")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
 
93
+ with gr.Tabs():
94
+ # === Main Assistant Tab ===
95
+ with gr.Tab("🧠 Multi-Task Interface"):
96
  gr.Markdown("""
97
+ <div style="text-align: center; margin-bottom: 2rem; color: #b0b0b0; font-size: 1.2rem;">
98
+ Harness the power of AI for <strong>sentiment analysis</strong>, <strong>text summarization</strong>, and <strong>text-to-speech</strong> conversion
99
+ </div>
100
+ """)
101
+
102
+ with gr.Row():
103
+ with gr.Column(scale=1, min_width=250):
104
+ task_selector = gr.Dropdown(
105
+ choices=["Sentiment Analysis", "Summarization", "Text-to-Speech"],
106
+ label="πŸ”§ Select AI Task",
107
+ value="Sentiment Analysis",
108
+ info="Choose the AI capability you want to use"
109
+ )
110
+
111
+ gr.Markdown("""
112
+ **πŸ“Š Sentiment Analysis**: Analyze emotional tone and polarity of text
113
+ **βœ‚οΈ Summarization**: Generate concise summaries of long text
114
+ **πŸ”Š Text-to-Speech**: Convert text into natural-sounding audio
115
+ """, elem_classes=["task-info"])
116
+
117
+ with gr.Column(scale=2):
118
+ textbox = gr.Textbox(
119
+ lines=8,
120
+ label="πŸ“ Input Text",
121
+ placeholder="Enter your text here...",
122
+ info="Type or paste the text you want to process"
123
+ )
124
+
125
+ with gr.Row():
126
+ run_button = gr.Button("πŸš€ Process with AI", size="lg", variant="primary")
127
+
128
+ gr.Markdown("## πŸ“‹ Results", elem_classes=["results-header"])
129
+
130
+ with gr.Row():
131
+ with gr.Column(scale=2):
132
+ output_text = gr.Textbox(
133
+ label="πŸ“Š Analysis Results",
134
+ lines=8,
135
+ interactive=False
136
+ )
137
+
138
+ with gr.Column(scale=1):
139
+ output_audio = gr.Audio(
140
+ label="πŸ”Š Generated Audio",
141
+ type="filepath",
142
+ visible=False,
143
+ )
144
+
145
+ run_button.click(
146
+ fn=handle_task_processing,
147
+ inputs=[task_selector, textbox],
148
+ outputs=[output_text, output_audio, output_audio]
149
  )
150
 
151
+ # === Sentiment Chatbot Tab ===
152
+ with gr.Tab("πŸ’¬ Sentiment Chatbot"):
153
+ gr.ChatInterface(
154
+ fn=lambda message, history: (
155
+ history + [
156
+ (
157
+ message,
158
+ f"🧠 Sentiment: {sentiment_pipeline(message)[0]['label']} (Confidence: {round(sentiment_pipeline(message)[0]['score'], 2)})"
159
+ )
160
+ ],
161
+ history + [
162
+ (
163
+ message,
164
+ f"🧠 Sentiment: {sentiment_pipeline(message)[0]['label']} (Confidence: {round(sentiment_pipeline(message)[0]['score'], 2)})"
165
+ )
166
+ ]
167
+ ),
168
+ title="Sentiment Chatbot",
169
+ description="Chat with the AI to detect the sentiment of your messages.",
170
  )
171
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  gr.Markdown("""
173
  <div style="text-align: center; margin-top: 3rem; padding: 2rem; color: #666; border-top: 1px solid #333;">
174
  <p>✨ <strong>Multi-Task AI Assistant</strong> - Powered by Transformers & Gradio</p>
 
176
  </div>
177
  """)
178
 
179
+ # Launch
180
  if __name__ == "__main__":
181
  demo.launch(
182
+ share=True,
 
183
  debug=True,
184
+ show_error=True
185
+ )