File size: 12,171 Bytes
81bb955
 
 
f88b11c
 
81bb955
 
 
 
 
f88b11c
81bb955
 
f88b11c
 
 
 
81bb955
 
 
 
 
f88b11c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81bb955
 
 
f88b11c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81bb955
 
 
 
 
f88b11c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81bb955
f88b11c
 
 
81bb955
f88b11c
 
 
81bb955
f88b11c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81bb955
 
f88b11c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81bb955
 
f88b11c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81bb955
f88b11c
 
81bb955
f88b11c
 
81bb955
f88b11c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81bb955
f88b11c
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import gradio as gr
from transformers import pipeline
from gtts import gTTS
import time
import os

# Load models
sentiment_pipeline = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
summarization_pipeline = pipeline("summarization", model="facebook/bart-large-cnn")

# Task logic with enhanced feedback
def perform_task(task, text):
    if not text.strip():
        return "⚠️ Please enter some text to analyze.", None, gr.update(visible=False)

    # Simulate processing time for better UX
    time.sleep(0.5)

    if task == "Sentiment Analysis":
        result = sentiment_pipeline(text)[0]
        label = result['label']
        score = round(result['score'], 3)

        # Enhanced sentiment display with emojis
        emoji = "😊" if label == "POSITIVE" else "😟"
        confidence_bar = "β–ˆ" * int(score * 10) + "β–‘" * (10 - int(score * 10))

        output = f"""
{emoji} **Sentiment Analysis Results**

**Label:** {label}
**Confidence:** {score} ({score*100:.1f}%)
**Visual:** {confidence_bar}

**Interpretation:** This text expresses a {label.lower()} sentiment with {score*100:.1f}% confidence.
        """.strip()

        return output, None, gr.update(visible=False)

    elif task == "Summarization":
        result = summarization_pipeline(text, max_length=100, min_length=30, do_sample=False)
        summary = result[0]['summary_text']

        # Calculate compression ratio
        original_words = len(text.split())
        summary_words = len(summary.split())
        compression_ratio = round((1 - summary_words/original_words) * 100, 1)

        output = f"""
πŸ“ **Text Summarization Results**

**Summary:**
{summary}

**Statistics:**
β€’ Original: {original_words} words
β€’ Summary: {summary_words} words
β€’ Compression: {compression_ratio}% reduction
        """.strip()

        return output, None, gr.update(visible=False)

    elif task == "Text-to-Speech":
        tts = gTTS(text)
        filename = "tts_output.mp3"
        tts.save(filename)

        word_count = len(text.split())
        char_count = len(text)

        output = f"""
πŸ”Š **Text-to-Speech Generated Successfully!**

**Input Statistics:**
β€’ Words: {word_count}
β€’ Characters: {char_count}
β€’ Estimated duration: ~{word_count * 0.5:.1f} seconds

**Audio file ready for playback below** ⬇️
        """.strip()

        return output, filename, gr.update(visible=True, value=filename)

# Enhanced CSS with modern design elements
custom_css = """
<style>
    @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');

    :root {
        --primary-bg: #0a0a0a;
        --secondary-bg: #1a1a1a;
        --accent-bg: #2a2a2a;
        --primary-text: #ffffff;
        --secondary-text: #b0b0b0;
        --accent-color: #3b82f6;
        --accent-hover: #2563eb;
        --success-color: #10b981;
        --warning-color: #f59e0b;
        --border-color: #333333;
        --gradient-1: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        --gradient-2: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        --gradient-3: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    }

    * {
        font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif !important;
    }

    body, .gradio-container {
        background: var(--primary-bg) !important;
        color: var(--primary-text) !important;
        background-image:
            radial-gradient(circle at 20% 50%, rgba(59, 130, 246, 0.1) 0%, transparent 50%),
            radial-gradient(circle at 80% 20%, rgba(168, 85, 247, 0.1) 0%, transparent 50%),
            radial_gradient(circle at 40% 80%, rgba(16, 185, 129, 0.1) 0%, transparent 50%);
        min-height: 100vh;
    }

    .gradio-container {
        max-width: 1200px !important;
        margin: 0 auto !important;
        padding: 2rem !important;
    }

    /* Header styling */
    #title {
        background: var(--gradient-1);
        background-clip: text;
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        font-size: 3rem !important;
        font-weight: 700 !important;
        text-align: center !important;
        margin-bottom: 2rem !important;
        animation: glow 2s ease-in-out infinite alternate;
    }

    @keyframes glow {
        from { filter: drop-shadow(0 0 20px rgba(59, 130, 246, 0.3)); }
        to { filter: drop_shadow(0 0 30px rgba(168, 85, 247, 0.5)); }
    }

    /* Card-like containers */
    .gr-box, .gr-form {
        background: var(--secondary-bg) !important;
        border: 1px solid var(--border-color) !important;
        border-radius: 16px !important;
        padding: 1.5rem !important;
        backdrop-filter: blur(10px) !important;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3) !important;
        transition: all 0.3s ease !important;
    }

    .gr-box:hover, .gr-form:hover {
        border-color: var(--accent-color) !important;
        box-shadow: 0 12px 40px rgba(59, 130, 246, 0.2) !important;
        transform: translateY(-2px) !important;
    }

    /* Input fields */
    .gr-input, .gr-textbox, .gr-dropdown {
        background: var(--accent-bg) !important;
        color: var(--primary-text) !important;
        border: 2px solid var(--border-color) !important;
        border-radius: 12px !important;
        padding: 1rem !important;
        font-size: 1rem !important;
        transition: all 0.3s ease !important;
    }

    .gr-input:focus, .gr-textbox:focus, .gr-dropdown:focus {
        border-color: var(--accent-color) !important;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1) !important;
        outline: none !important;
    }

    /* Buttons */
    .gr-button {
        background: var(--gradient-1) !important;
        color: white !important;
        border: none !important;
        border-radius: 12px !important;
        padding: 1rem 2rem !important;
        font-size: 1.1rem !important;
        font-weight: 600 !important;
        cursor: pointer !important;
        transition: all 0.3s ease !important;
        box-shadow: 0 4px 20px rgba(59, 130, 246, 0.3) !important;
    }

    .gr-button:hover {
        transform: translateY(-2px) !important;
        box-shadow: 0 8px 30px rgba(59, 130, 246, 0.4) !important;
    }

    .gr-button:active {
        transform: translateY(0) !important;
    }

    /* Labels */
    label {
        color: var(--primary-text) !important;
        font-weight: 500 !important;
        font-size: 1.1rem !important;
        margin-bottom: 0.5rem !important;
    }

    /* Placeholders */
    input::placeholder, textarea::placeholder {
        color: var(--secondary-text) !important;
        opacity: 0.7 !important;
    }

    /* Output areas */
    .gr-textbox[data-testid="textbox"] {
        background: var(--accent-bg) !important;
        border: 1px solid var(--border-color) !important;
        border-radius: 12px !important;
        padding: 1.5rem !important;
        font-family: 'Inter', monospace !important;
        line-height: 1.6 !important;
    }

    /* Audio component */
    .gr-audio {
        background: var(--secondary-bg) !important;
        border: 1px solid var(--border-color) !important;
        border-radius: 12px !important;
        padding: 1rem !important;
    }

    /* Markdown content */
    .markdown-content {
        line-height: 1.8 !important;
    }

    .markdown-content strong {
        color: var(--accent-color) !important;
    }

    /* Task selector special styling */
    .gr-dropdown {
        background: var(--gradient-2) !important;
        color: white !important;
        font-weight: 500 !important;
    }

    /* Responsive design */
    @media (max-width: 768px) {
        #title {
            font-size: 2rem !important;
        }

        .gradio-container {
            padding: 1rem !important;
        }

        .gr-box, .gr-form {
            padding: 1rem !important;
        }
    }

    /* Loading animation */
    @keyframes pulse {
        0%, 100% { opacity: 1; }
        50% { opacity: 0.5; }
    }

    .loading {
        animation: pulse 1.5s infinite;
    }

    /* Success/Error states */
    .success {
        border-color: var(--success-color) !important;
        box-shadow: 0 0 20px rgba(16, 185, 129, 0.2) !important;
    }

    .warning {
        border-color: var(--warning-color) !important;
        box-shadow: 0 0 20px rgba(245, 158, 11, 0.2) !important;
    }
</style>
"""

# UI with enhanced design
with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:
    gr.HTML(custom_css)

    # Header with enhanced styling
    gr.Markdown("# πŸ€– Multi-Task AI Assistant", elem_id="title")
    gr.Markdown("""
    <div style="text-align: center; margin-bottom: 2rem; color: #b0b0b0; font-size: 1.2rem;">
        Harness the power of AI for <strong>sentiment analysis</strong>, <strong>text summarization</strong>, and <strong>text-to-speech</strong> conversion
    </div>
    """)

    # Main interface
    with gr.Row():
        with gr.Column(scale=1, min_width=250):
            task_selector = gr.Dropdown(
                choices=["Sentiment Analysis", "Summarization", "Text-to-Speech"],
                label="πŸ”§ Select AI Task",
                value="Sentiment Analysis",
                info="Choose the AI capability you want to use"
            )

            # Task descriptions
            gr.Markdown("""
            **πŸ“Š Sentiment Analysis**: Analyze emotional tone and polarity of text

            **βœ‚οΈ Summarization**: Generate concise summaries of long text

            **πŸ”Š Text-to-Speech**: Convert text into natural-sounding audio
            """, elem_classes=["task-info"])

        with gr.Column(scale=2):
            textbox = gr.Textbox(
                lines=8,
                label="πŸ“ Input Text",
                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",
                info="Type or paste the text you want to process"
            )

    # Action button
    with gr.Row():
        run_button = gr.Button("πŸš€ Process with AI", size="lg", variant="primary")

    # Results section
    gr.Markdown("## πŸ“‹ Results", elem_classes=["results-header"])

    with gr.Row():
        with gr.Column(scale=2):
            output_text = gr.Textbox(
                label="πŸ“Š Analysis Results",
                lines=8,
                info="Detailed results and insights will appear here",
                interactive=False
            )

        with gr.Column(scale=1):
            output_audio = gr.Audio(
                label="πŸ”Š Generated Audio",
                type="filepath",
                visible=False,
            )

    # Enhanced event handler
    def handle_task_processing(task, text):
        if not text.strip():
            return "⚠️ Please enter some text to get started!", None, gr.update(visible=False)

        # Show processing message
        processing_msg = f"πŸ”„ Processing your {task.lower()} request..."

        # Process the task
        result_text, audio_file, audio_update = perform_task(task, text)

        return result_text, audio_file, audio_update

    # Event binding
    run_button.click(
        fn=handle_task_processing,
        inputs=[task_selector, textbox],
        outputs=[output_text, output_audio, output_audio]
    )

    # Footer
    gr.Markdown("""
    <div style="text-align: center; margin-top: 3rem; padding: 2rem; color: #666; border-top: 1px solid #333;">
        <p>✨ <strong>Multi-Task AI Assistant</strong> - Powered by Transformers & Gradio</p>
        <p>Built with ❀️ for seamless AI interaction</p>
    </div>
    """)

# Launch with enhanced settings
if __name__ == "__main__":
    demo.launch(
        # Removing server_name and server_port to let Gradio handle networking
        share=True, # share=True is often necessary in Colab environments
        debug=True,
        show_error=True,
        favicon_path=None,
        app_kwargs={"docs_url": "/docs"}
    )