Spaces:
Runtime error
Runtime error
| """ | |
| ๐ 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 | |
| ) | |