File size: 14,045 Bytes
780413d
a65505a
 
780413d
 
 
a65505a
 
 
780413d
 
a65505a
780413d
 
ec3f9a9
a65505a
 
 
 
 
 
 
 
780413d
a65505a
 
 
 
 
 
 
 
 
ec3f9a9
a65505a
 
 
 
ec3f9a9
 
a65505a
ec3f9a9
a65505a
ec3f9a9
 
 
a65505a
 
 
 
 
 
 
 
 
 
 
ec3f9a9
a65505a
ec3f9a9
780413d
ec3f9a9
 
 
 
a65505a
ec3f9a9
a65505a
 
 
ec3f9a9
 
 
a65505a
 
 
 
 
 
 
 
ec3f9a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
780413d
 
a65505a
780413d
 
a65505a
 
 
ec3f9a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a65505a
9aff9e8
 
 
 
a65505a
9aff9e8
a65505a
 
9aff9e8
 
 
a65505a
9aff9e8
a65505a
9aff9e8
780413d
9aff9e8
a65505a
 
 
 
 
780413d
9aff9e8
a65505a
 
 
 
 
ec3f9a9
 
a65505a
 
 
 
 
 
9aff9e8
a65505a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec3f9a9
 
a65505a
 
 
 
 
 
 
 
 
 
ec3f9a9
 
a65505a
9aff9e8
a65505a
 
 
 
 
 
 
9aff9e8
ec3f9a9
 
a65505a
 
ec3f9a9
a65505a
ec3f9a9
 
 
a65505a
9aff9e8
ec3f9a9
 
780413d
ec3f9a9
780413d
a65505a
ec3f9a9
 
 
 
 
 
 
 
 
 
a65505a
 
 
 
ec3f9a9
780413d
a65505a
 
 
 
 
ec3f9a9
780413d
a65505a
 
 
 
 
ec3f9a9
a65505a
 
 
 
 
 
ec3f9a9
a65505a
 
 
ec3f9a9
a65505a
 
ec3f9a9
a65505a
 
ec3f9a9
 
a65505a
ec3f9a9
 
a65505a
 
780413d
 
 
a65505a
780413d
 
 
a65505a
 
 
 
 
 
 
ec3f9a9
a65505a
 
ec3f9a9
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
"""
๐Ÿš€ Modern AI Assistant - Gradio 6 Application
A clean, professional interface showcasing modern Gradio 6 features.
"""

import gradio as gr
import time
import random
from datetime import datetime

# =============================================================================
# AI Assistant Functions
# =============================================================================

def generate_response(prompt: str, temperature: float, max_tokens: int) -> tuple:
    """Generate AI response with configurable parameters."""
    time.sleep(1)  # Simulate processing time
    responses = [
        "That's an interesting question! Let me think about it...",
        "I can help you with that. Based on my analysis...",
        "Great question! Here's what I found...",
        "Let me break that down for you...",
        "That's a complex topic, but I can provide some insights..."
    ]
    response = random.choice(responses)
    
    # Simulate token generation
    words = response.split()
    generated_words = []
    for i in range(min(len(words), max_tokens // 4)):
        generated_words.append(words[i])
        time.sleep(0.1)  # Simulate streaming effect
    
    final_response = " ".join(generated_words) + " " + random.choice([
        "How else can I assist you today?",
        "Is there anything else you'd like to know?",
        "Feel free to ask more questions!"
    ])
    
    return [[prompt, final_response]], ""

def analyze_sentiment(text: str) -> tuple[str, str]:
    """Analyze sentiment of the input text."""
    if not text.strip():
        return "Please enter text to analyze", ""
    
    positive_words = ["good", "great", "excellent", "amazing", "wonderful", "fantastic", "love", "like", "happy", "joy", "success"]
    negative_words = ["bad", "terrible", "awful", "hate", "dislike", "sad", "angry", "fail", "poor", "worst"]
    
    text_lower = text.lower()
    positive_count = sum(1 for word in positive_words if word in text_lower)
    negative_count = sum(1 for word in negative_words if word in text_lower)
    
    score = (positive_count - negative_count) / (len(text.split()) or 1)
    score = max(-1, min(1, score))  # Clamp between -1 and 1
    
    if score > 0.2:
        sentiment = "๐Ÿ˜Š Positive"
    elif score < -0.2:
        sentiment = "๐Ÿ˜Ÿ Negative"
    else:
        sentiment = "๐Ÿ˜ Neutral"
    
    result = f"{sentiment}\nScore: {round(score, 2)}"
    status = f"Analysis completed at {datetime.now().strftime('%H:%M:%S')}"
    
    return result, status

def translate_text(text: str, target_language: str) -> str:
    """Simulate text translation."""
    if not text.strip():
        return "Please enter text to translate"
    
    translations = {
        "English": "Hello! How can I help you today?",
        "Spanish": "ยกHola! ยฟCรณmo puedo ayudarte hoy?",
        "French": "Bonjour! Comment puis-je vous aider aujourd'hui?",
        "German": "Hallo! Wie kann ich Ihnen heute helfen?",
        "Japanese": "ใ“ใ‚“ใซใกใฏ๏ผๆœฌๆ—ฅใฉใฎใ‚ˆใ†ใซใŠๆ‰‹ไผใ„ใงใใพใ™ใ‹๏ผŸ",
        "Chinese": "ไฝ ๅฅฝ๏ผไปŠๅคฉๆˆ‘่ƒฝๅฆ‚ไฝ•ๅธฎๅŠฉไฝ ๏ผŸ"
    }
    
    base_translation = translations.get(target_language, f"Translation to {target_language}")
    return f"๐ŸŒ Translated to {target_language}:\n\n{base_translation}\n\n(Simulated translation of: '{text[:50]}...')"

def analyze_documents(files) -> tuple[str, str]:
    """Analyze uploaded documents."""
    if not files:
        return "No files uploaded", ""
    
    file_count = len(files) if isinstance(files, list) else 1
    result = f"๐Ÿ“Š Analyzed {file_count} document{'s' if file_count > 1 else ''}.\n\n"
    result += "โœ… Processing complete!\n"
    result += "โ€ข Extracted text content\n"
    result += "โ€ข Analyzed document structure\n"
    result += "โ€ข Generated metadata\n"
    
    status = f"๐Ÿ“… Analysis completed at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
    
    return result, status

def clear_all():
    """Clear all fields."""
    return None, "", "", "", "", ""

# =============================================================================
# Gradio 6 Interface
# =============================================================================

def create_modern_interface() -> gr.Blocks:
    """Create a modern, professional Gradio 6 interface."""
    
    # Define custom theme
    theme = gr.themes.Soft(
        primary_hue="blue",
        secondary_hue="indigo",
        neutral_hue="slate",
        font=gr.themes.GoogleFont("Inter"),
        text_size="lg",
        spacing_size="lg",
        radius_size="md"
    ).set(
        button_primary_background_fill="*primary_600",
        button_primary_background_fill_hover="*primary_700",
        button_primary_text_color="white",
        block_title_text_weight="600",
        block_label_text_weight="500",
        input_border_color="*neutral_300",
        input_focus_border_color="*primary_500",
        slider_active_color="*primary_500",
        slider_color="*neutral_300"
    )
    
    # Custom CSS
    custom_css = """
    /* Modern Design System */
    .gradio-container {
        max-width: 1200px !important;
        margin: 0 auto !important;
        padding: 2rem !important;
        font-family: 'Inter', sans-serif !important;
    }
    
    /* Header Styling */
    .header-text h1 {
        font-size: 2.5rem !important;
        font-weight: 700 !important;
        margin-bottom: 1rem !important;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
    }
    
    .header-text p {
        font-size: 1.2rem !important;
        color: #64748b !important;
        line-height: 1.6 !important;
    }
    
    /* Chat Container */
    .chat-container {
        border: 1px solid #e2e8f0 !important;
        border-radius: 12px !important;
        background: #ffffff !important;
        box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1) !important;
    }
    
    /* Message Input */
    .message-input textarea {
        border-radius: 8px !important;
        border: 2px solid #e2e8f0 !important;
        font-size: 1rem !important;
        padding: 0.75rem 1rem !important;
        transition: all 0.3s ease !important;
    }
    
    .message-input textarea:focus {
        border-color: #667eea !important;
        box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1) !important;
    }
    
    /* Buttons */
    .send-button {
        font-size: 1.1rem !important;
        padding: 0.75rem 2rem !important;
        border-radius: 8px !important;
        font-weight: 600 !important;
        box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1) !important;
        transition: all 0.3s ease !important;
    }
    
    .send-button:hover {
        transform: translateY(-2px) !important;
        box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.2) !important;
    }
    
    /* File Upload Area */
    .file-upload-area {
        border: 2px dashed #cbd5e1 !important;
        border-radius: 12px !important;
        transition: all 0.3s ease !important;
        padding: 1rem !important;
    }
    
    .file-upload-area:hover {
        border-color: #667eea !important;
        background: #f8fafc !important;
    }
    
    /* Mobile Responsiveness */
    @media (max-width: 768px) {
        .gradio-container {
            padding: 1rem !important;
        }
        
        .header-text h1 {
            font-size: 2rem !important;
        }
    }
    """
    
    with gr.Blocks(theme=theme, css=custom_css) as demo:
        # Header with branding
        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown(
                    """
                    # ๐Ÿค– Modern AI Assistant
                    
                    Experience the power of AI with our advanced language models. 
                    Built with cutting-edge technology for seamless interactions.
                    """,
                    elem_classes=["header-text"]
                )
        
        gr.Markdown("---")
        
        # Main Content Area
        with gr.Row():
            with gr.Column(scale=1):
                # Chat Interface
                chatbot = gr.Chatbot(
                    height=400,
                    label="๐Ÿ—จ๏ธ AI Conversation",
                    elem_classes=["chat-container"]
                )
                
                # Input Section
                with gr.Row():
                    user_input = gr.Textbox(
                        placeholder="Type your message here...",
                        label="Your Message",
                        elem_classes=["message-input"],
                        lines=2
                    )
                    send_btn = gr.Button(
                        "โžค Send",
                        variant="primary",
                        elem_classes=["send-button"]
                    )
                
                # Generation Controls
                with gr.Row():
                    with gr.Column(scale=2):
                        temperature = gr.Slider(
                            minimum=0.1,
                            maximum=1.0,
                            value=0.7,
                            step=0.1,
                            label="๐Ÿ”ฅ Temperature",
                            info="Controls randomness (0.1=precise, 1.0=creative)"
                        )
                    with gr.Column(scale=2):
                        max_tokens = gr.Slider(
                            minimum=10,
                            maximum=200,
                            value=50,
                            step=10,
                            label="๐Ÿ“ Max Tokens",
                            info="Maximum response length"
                        )
                
                # Additional Features
                with gr.Accordion("๐Ÿ”ง Advanced Features", open=False):
                    with gr.Row():
                        with gr.Column(scale=1):
                            sentiment_btn = gr.Button("๐Ÿ“Š Analyze Sentiment")
                            sentiment_output = gr.Textbox(
                                label="Sentiment Analysis",
                                interactive=False,
                                lines=3
                            )
                        with gr.Column(scale=1):
                            translate_btn = gr.Button("๐ŸŒ Translate")
                            language_dropdown = gr.Dropdown(
                                choices=["English", "Spanish", "French", "German", "Japanese", "Chinese"],
                                value="Spanish",
                                label="Target Language"
                            )
                            translation_output = gr.Textbox(
                                label="Translation",
                                interactive=False,
                                lines=3
                            )
                
                # File Upload for Document Analysis
                with gr.Row():
                    file_upload = gr.File(
                        file_count="multiple",
                        file_types=[".pdf", ".txt", ".docx"],
                        label="๐Ÿ“„ Upload Documents",
                        elem_classes=["file-upload-area"]
                    )
                
                with gr.Row():
                    analyze_btn = gr.Button(
                        "๐Ÿ” Analyze Documents",
                        variant="secondary"
                    )
                    clear_btn = gr.Button(
                        "๐Ÿ—‘๏ธ Clear All",
                        variant="stop"
                    )
                
                analysis_output = gr.Textbox(
                    label="Document Analysis",
                    interactive=False,
                    lines=6
                )
        
        # Status Section
        gr.Markdown("---")
        with gr.Row():
            status_output = gr.Textbox(
                label="๐Ÿ“Š Status",
                interactive=False,
                lines=2
            )
        
        # Event Handlers - CORRIGIDO: Removido api_visibility
        send_btn.click(
            fn=generate_response,
            inputs=[user_input, temperature, max_tokens],
            outputs=[chatbot, user_input],
            api_name="generate"
        )
        
        user_input.submit(
            fn=generate_response,
            inputs=[user_input, temperature, max_tokens],
            outputs=[chatbot, user_input],
            api_name="generate_submit"
        )
        
        sentiment_btn.click(
            fn=analyze_sentiment,
            inputs=[user_input],
            outputs=[sentiment_output, status_output],
            api_name="sentiment"
        )
        
        translate_btn.click(
            fn=translate_text,
            inputs=[user_input, language_dropdown],
            outputs=[translation_output],
            api_name="translate"
        )
        
        analyze_btn.click(
            fn=analyze_documents,
            inputs=[file_upload],
            outputs=[analysis_output, status_output],
            api_name="analyze_docs"
        )
        
        clear_btn.click(
            fn=clear_all,
            inputs=[],
            outputs=[chatbot, user_input, sentiment_output, translation_output, analysis_output, status_output],
            api_name=False
        )
    
    return demo

# =============================================================================
# MAIN EXECUTION
# =============================================================================

if __name__ == "__main__":
    # Create the interface
    demo = create_modern_interface()
    
    # Launch with modern Gradio 6 configuration
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        max_file_size="100mb",
        show_error=True
    )