import gradio as gr import random import time import json import numpy as np from datetime import datetime import base64 import io from PIL import Image import torch from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline import warnings warnings.filterwarnings('ignore') # Global model cache to avoid reloading model_cache = {} # Available models configuration - 2025 Advanced Free Open Source Models AVAILABLE_MODELS = { "Qwen/Qwen2.5-0.5B-Instruct": { "name": "Qwen 2.5 0.5B (Fast & Efficient)", "description": "Alibaba's Qwen 2.5 - Fast, lightweight model for quick responses", "size": "0.5B", "speciality": "General Purpose, Fast" }, "Qwen/Qwen2.5-1.5B-Instruct": { "name": "Qwen 2.5 1.5B (Balanced)", "description": "Alibaba's Qwen 2.5 - Balanced performance and speed", "size": "1.5B", "speciality": "General Purpose, Balanced" }, "Qwen/Qwen2.5-3B-Instruct": { "name": "Qwen 2.5 3B (High Quality)", "description": "Alibaba's Qwen 2.5 - Higher quality responses", "size": "3B", "speciality": "General Purpose, Quality" }, "microsoft/DialoGPT-medium": { "name": "DialoGPT Medium (Conversational)", "description": "Microsoft's conversational AI model", "size": "Medium", "speciality": "Conversation" }, "microsoft/DialoGPT-large": { "name": "DialoGPT Large (Advanced Chat)", "description": "Microsoft's large conversational AI model", "size": "Large", "speciality": "Advanced Conversation" }, "cardiffnlp/twitter-roberta-base-sentiment-latest": { "name": "RoBERTa Sentiment (Specialized)", "description": "Advanced sentiment analysis model", "size": "Base", "speciality": "Sentiment Analysis" }, "facebook/blenderbot-400M-distill": { "name": "BlenderBot 400M (Conversational)", "description": "Facebook's conversational AI - distilled version", "size": "400M", "speciality": "Chat & Dialog" } } def load_model(model_name, task_type="text-generation"): """Load and cache models to avoid reloading""" cache_key = f"{model_name}_{task_type}" if cache_key in model_cache: return model_cache[cache_key] try: print(f"Loading model: {model_name}") if task_type == "sentiment": pipe = pipeline("sentiment-analysis", model=model_name, return_all_scores=True) elif task_type == "text-generation": # Load tokenizer and model separately for better control tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained( model_name, torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32, device_map="auto" if torch.cuda.is_available() else None, trust_remote_code=True ) pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) else: pipe = pipeline(task_type, model=model_name) model_cache[cache_key] = pipe print(f"Model {model_name} loaded successfully!") return pipe except Exception as e: print(f"Error loading model {model_name}: {str(e)}") return None def enhanced_text_analyzer(text, selected_model): """Enhanced text analysis using advanced Hugging Face models""" if not text: return "Please enter some text to analyze." # Basic stats word_count = len(text.split()) char_count = len(text) sentence_count = text.count('.') + text.count('!') + text.count('?') analysis_results = f""" 📊 **Enhanced Text Analysis Results** **Basic Statistics:** - Words: {word_count} - Characters: {char_count} - Sentences: {sentence_count} - Reading Time: ~{max(1, word_count // 200)} minute(s) **Model Used:** {AVAILABLE_MODELS.get(selected_model, {}).get('name', selected_model)} """ # Advanced sentiment analysis using selected model try: if "sentiment" in selected_model.lower() or "roberta" in selected_model.lower(): sentiment_model = load_model(selected_model, "sentiment") if sentiment_model: sentiment_results = sentiment_model(text) if sentiment_results and len(sentiment_results) > 0: sentiments = sentiment_results[0] if isinstance(sentiment_results[0], list) else sentiment_results analysis_results += "\n **🎭 Advanced Sentiment Analysis:**\n" for sentiment in sentiments: label = sentiment['label'] score = sentiment['score'] emoji = "😊" if label == "POSITIVE" else "😔" if label == "NEGATIVE" else "😐" analysis_results += f" - {label}: {score:.3f} {emoji}\n" else: # Use general model for analysis model = load_model(selected_model, "text-generation") if model: try: prompt = f"Analyze the sentiment and key themes of this text: '{text[:200]}...'\nAnalysis:" result = model(prompt, max_length=150, num_return_sequences=1, temperature=0.7) if result and len(result) > 0: generated_text = result[0]['generated_text'] analysis_text = generated_text.split("Analysis:")[-1].strip() analysis_results += f"\n **🤖 AI Analysis:**\n {analysis_text}\n" except Exception as e: analysis_results += f"\n **Note:** Advanced analysis unavailable ({str(e)})\n" except Exception as e: analysis_results += f"\n **Note:** Model analysis failed: {str(e)}\n" # Fallback basic sentiment positive_words = ['good', 'great', 'excellent', 'amazing', 'wonderful', 'fantastic', 'love', 'happy', 'awesome', 'brilliant'] negative_words = ['bad', 'terrible', 'awful', 'hate', 'sad', 'angry', 'disappointed', 'horrible', 'disgusting', 'annoying'] positive_score = sum(1 for word in positive_words if word in text.lower()) negative_score = sum(1 for word in negative_words if word in text.lower()) if positive_score > negative_score: sentiment = "Positive 😊" elif negative_score > positive_score: sentiment = "Negative 😔" else: sentiment = "Neutral 😐" analysis_results += f""" **📈 Basic Sentiment Analysis:** - Overall Sentiment: {sentiment} - Positive indicators: {positive_score} - Negative indicators: {negative_score} """ return analysis_results def advanced_chat_response(message, history, selected_model): """Advanced chatbot using selected Hugging Face models""" if not message: return history, "" try: model = load_model(selected_model, "text-generation") if model: # Format conversation history for context context = "" if history: for user_msg, bot_msg in history[-3:]: # Last 3 exchanges for context context += f"Human: {user_msg}\nAssistant: {bot_msg}\n" # Create prompt if "qwen" in selected_model.lower(): prompt = f"<|im_start|>system\nYou are a helpful AI assistant.<|im_end|>\n<|im_start|>user\n{message}<|im_end|>\n<|im_start|>assistant\n" else: prompt = f"{context}Human: {message}\nAssistant:" # Generate response try: result = model( prompt, max_length=min(len(prompt.split()) + 100, 512), num_return_sequences=1, temperature=0.7, do_sample=True, pad_token_id=model.tokenizer.eos_token_id if hasattr(model, 'tokenizer') else None ) if result and len(result) > 0: generated_text = result[0]['generated_text'] # Extract just the assistant's response if "Assistant:" in generated_text: response = generated_text.split("Assistant:")[-1].strip() elif "<|im_start|>assistant" in generated_text: response = generated_text.split("<|im_start|>assistant")[-1].replace("<|im_end|>", "").strip() else: response = generated_text[len(prompt):].strip() # Clean up response response = response.split("Human:")[0].strip() response = response.split("<|im_start|>")[0].strip() if response: history.append([message, response]) return history, "" except Exception as e: print(f"Error generating response: {e}") # Fallback responses fallback_responses = { "hello": "Hello! I'm powered by advanced Hugging Face models. How can I help you today? 🤖", "hi": "Hi there! I'm using state-of-the-art language models. What would you like to know? 😊", "how are you": "I'm running great on advanced AI models! Thanks for asking. How are you?", "what can you do": "I can help with text analysis, coding, conversation, and more using cutting-edge Hugging Face models!", "time": f"The current time is {datetime.now().strftime('%H:%M:%S')}", "date": f"Today's date is {datetime.now().strftime('%Y-%m-%d')}", "models": f"I'm currently using {AVAILABLE_MODELS.get(selected_model, {}).get('name', selected_model)} for our conversation!", } message_lower = message.lower() response = None for key, value in fallback_responses.items(): if key in message_lower: response = value break if not response: if "?" in message: response = f"That's an interesting question! I'm powered by {AVAILABLE_MODELS.get(selected_model, {}).get('name', 'advanced models')} but I might need more context. Can you tell me more? 🤔" else: response = f"Thanks for sharing! I'm using {AVAILABLE_MODELS.get(selected_model, {}).get('name', 'an advanced model')} to assist you. How can I help further? 💭" history.append([message, response]) return history, "" except Exception as e: error_response = f"I encountered an issue with the {AVAILABLE_MODELS.get(selected_model, {}).get('name', 'selected model')}. Let me help you with a simpler response! 😅" history.append([message, error_response]) return history, "" def code_generator(description, language, selected_model): """Generate code using advanced language models""" if not description: return "Please provide a description of what code you want to generate." try: model = load_model(selected_model, "text-generation") if model: if "qwen" in selected_model.lower(): prompt = f"<|im_start|>system\nYou are an expert programmer.<|im_end|>\n<|im_start|>user\nGenerate {language} code for: {description}<|im_end|>\n<|im_start|>assistant\n" else: prompt = f"Generate {language} code for the following requirement:\n\n{description}\n\nCode:\n```{language.lower()}\n" result = model( prompt, max_length=min(len(prompt.split()) + 200, 1024), num_return_sequences=1, temperature=0.3, do_sample=True, pad_token_id=model.tokenizer.eos_token_id if hasattr(model, 'tokenizer') else None ) if result and len(result) > 0: generated_text = result[0]['generated_text'] # Extract code if "```" in generated_text: code_parts = generated_text.split("```") if len(code_parts) > 1: code = code_parts[1].strip() if code.startswith(language.lower()): code = code[len(language):].strip() return code elif "<|im_start|>assistant" in generated_text: code = generated_text.split("<|im_start|>assistant")[-1].replace("<|im_end|>", "").strip() return code else: code = generated_text[len(prompt):].strip() return code except Exception as e: print(f"Error generating code: {e}") # Fallback code templates fallback_templates = { "Python": f"""# Generated code for: {description} def main(): # TODO: Implement {description} print("Hello from generated code!") return True if __name__ == "__main__": main()""", "JavaScript": f"""// Generated code for: {description} function main() {{ // TODO: Implement {description} console.log("Hello from generated code!"); return true; }} main();""", "Java": f"""// Generated code for: {description} public class GeneratedCode {{ public static void main(String[] args) {{ // TODO: Implement {description} System.out.println("Hello from generated code!"); }} }}""", } return fallback_templates.get(language, f"// {description}\n// Code generation not available for {language}") def enhanced_code_formatter(code, language): """Enhanced code analysis and formatting""" if not code: return "Please enter some code to analyze." lines = code.split('\n') line_count = len(lines) non_empty_lines = len([l for l in lines if l.strip()]) analysis = f""" 💻 **Enhanced Code Analysis ({language})** **📊 Statistics:** - Total lines: {line_count} - Non-empty lines: {non_empty_lines} - Blank lines: {line_count - non_empty_lines} """ if language.lower() == 'python': functions = [line for line in lines if 'def ' in line] classes = [line for line in lines if 'class ' in line] imports = [line for line in lines if line.strip().startswith('import') or line.strip().startswith('from')] comments = [line for line in lines if line.strip().startswith('#')] analysis += f""" **🐍 Python Specifics:** - Functions: {len(functions)} - Classes: {len(classes)} - Import statements: {len(imports)} - Comments: {len(comments)} **🔍 Functions found:** {chr(10).join([' - ' + func.strip() for func in functions[:10]])} """ elif language.lower() == 'javascript': functions = [line for line in lines if 'function ' in line or '=>' in line] classes = [line for line in lines if 'class ' in line] imports = [line for line in lines if 'import ' in line or 'require(' in line] comments = [line for line in lines if line.strip().startswith('//') or line.strip().startswith('/*')] analysis += f""" **🟨 JavaScript Specifics:** - Functions: {len(functions)} - Classes: {len(classes)} - Import/Require statements: {len(imports)} - Comments: {len(comments)} **🔍 Functions found:** {chr(10).join([' - ' + func.strip() for func in functions[:10]])} """ else: comments = [line for line in lines if line.strip().startswith('//') or line.strip().startswith('#') or line.strip().startswith('/*')] analysis += f""" **📝 General Analysis:** - Comments: {len(comments)} - Average line length: {sum(len(line) for line in lines) / len(lines):.1f} characters """ # Code complexity estimation complexity_indicators = ['if ', 'for ', 'while ', 'switch ', 'case ', 'try ', 'catch ', 'elif '] complexity_count = sum(1 for line in lines for indicator in complexity_indicators if indicator in line.lower()) if complexity_count == 0: complexity = "Simple" elif complexity_count <= 5: complexity = "Moderate" elif complexity_count <= 15: complexity = "Complex" else: complexity = "Very Complex" analysis += f""" **🎯 Complexity Analysis:** - Control structures: {complexity_count} - Estimated complexity: {complexity} - Code density: {(non_empty_lines / line_count * 100):.1f}% """ return analysis # Create the enhanced Gradio interface with advanced models with gr.Blocks( theme=gr.themes.Soft( primary_hue="blue", secondary_hue="gray", neutral_hue="slate" ), title="🤖 Advanced AI Hub with Hugging Face Models 2025", css=""" .gradio-container { max-width: 1400px !important; } .tab-nav button { font-size: 16px !important; font-weight: 600 !important; } .model-info { background: linear-gradient(45deg, #667eea 0%, #764ba2 100%); color: white; padding: 15px; border-radius: 10px; margin: 10px 0; } """ ) as demo: gr.Markdown(""" # 🤖 Advanced AI Hub with 2025 Hugging Face Models ### Powered by the latest and most advanced free open-source language models! 🚀 **Featured Models**: Qwen 2.5 Series, DialoGPT, RoBERTa, BlenderBot and more! """) # Global model selector with gr.Row(): model_selector = gr.Dropdown( choices=list(AVAILABLE_MODELS.keys()), value="Qwen/Qwen2.5-1.5B-Instruct", label="🧠 Select AI Model", info="Choose the AI model for analysis and chat" ) model_info = gr.HTML( value=f"""
📋 Current Model: {AVAILABLE_MODELS["Qwen/Qwen2.5-1.5B-Instruct"]["name"]}
📝 Description: {AVAILABLE_MODELS["Qwen/Qwen2.5-1.5B-Instruct"]["description"]}
🎯 Speciality: {AVAILABLE_MODELS["Qwen/Qwen2.5-1.5B-Instruct"]["speciality"]}
""" ) # Update model info when selection changes def update_model_info(selected_model): model_data = AVAILABLE_MODELS.get(selected_model, {}) return f"""
📋 Current Model: {model_data.get("name", "Unknown")}
📝 Description: {model_data.get("description", "No description")}
🎯 Speciality: {model_data.get("speciality", "General")}
""" model_selector.change(fn=update_model_info, inputs=model_selector, outputs=model_info) with gr.Tabs() as tabs: # Enhanced Text Analysis Tab with gr.Tab("📝 Advanced Text Analyzer", id="text"): gr.Markdown("### AI-powered text analysis using state-of-the-art models") with gr.Row(): with gr.Column(scale=2): text_input = gr.Textbox( label="Enter your text", placeholder="Type or paste your text here for advanced AI analysis...", lines=8, max_lines=15 ) analyze_btn = gr.Button("🔍 Analyze with AI", variant="primary", size="lg") with gr.Column(scale=2): text_output = gr.Markdown(label="AI Analysis Results") gr.Examples( examples=[ ["This is an absolutely wonderful day! I love working with these amazing new AI models. The technology is incredible and revolutionary!"], ["The weather is terrible today. I hate when it rains so much. This is really disappointing and frustrating."], ["Artificial intelligence is transforming how we work and live. Machine learning algorithms can process vast amounts of data and provide insights."], ["The new Hugging Face models are incredibly powerful and accessible. They represent a major breakthrough in democratizing AI technology."] ], inputs=text_input ) analyze_btn.click( fn=enhanced_text_analyzer, inputs=[text_input, model_selector], outputs=text_output ) # Enhanced Code Analysis Tab with gr.Tab("💻 Advanced Code Analyzer", id="code"): gr.Markdown("### Enhanced code analysis with detailed insights") with gr.Row(): with gr.Column(): code_input = gr.Code( label="Enter your code", language="python", lines=15 ) with gr.Row(): language_select = gr.Dropdown( choices=["Python", "JavaScript", "Java", "C++", "HTML", "CSS", "TypeScript", "Go", "Rust"], value="Python", label="Programming Language" ) analyze_code_btn = gr.Button("🔧 Analyze Code", variant="primary") with gr.Column(): code_output = gr.Markdown(label="Enhanced Code Analysis") analyze_code_btn.click( fn=enhanced_code_formatter, inputs=[code_input, language_select], outputs=code_output ) # NEW: AI Code Generator Tab with gr.Tab("🛠️ AI Code Generator", id="codegen"): gr.Markdown("### Generate code using advanced AI models") with gr.Row(): with gr.Column(): code_description = gr.Textbox( label="Describe what you want to build", placeholder="e.g., A function to sort a list of numbers, A REST API endpoint, A React component...", lines=4 ) with gr.Row(): code_language = gr.Dropdown( choices=["Python", "JavaScript", "Java", "TypeScript", "C++", "Go", "Rust"], value="Python", label="Programming Language" ) generate_code_btn = gr.Button("🚀 Generate Code", variant="primary", size="lg") with gr.Column(): generated_code = gr.Code(label="Generated Code", language="python") gr.Examples( examples=[ ["A function to calculate fibonacci numbers", "Python"], ["A REST API endpoint for user authentication", "JavaScript"], ["A binary search algorithm", "Java"], ["A React component for a todo list", "TypeScript"] ], inputs=[code_description, code_language] ) generate_code_btn.click( fn=code_generator, inputs=[code_description, code_language, model_selector], outputs=generated_code ) # Enhanced Data Generator Tab with gr.Tab("🎲 Smart Data Generator", id="data"): gr.Markdown("### Generate realistic sample data for testing and development") with gr.Row(): with gr.Column(): data_type = gr.Radio( choices=["Random Numbers", "Names", "Emails", "JSON Objects", "API Responses", "User Profiles"], value="Random Numbers", label="Data Type" ) data_count = gr.Slider( minimum=1, maximum=100, value=10, step=1, label="Number of items" ) generate_data_btn = gr.Button("🎯 Generate Data", variant="primary", size="lg") with gr.Column(scale=2): data_output = gr.Code(label="Generated Data", language="json") # Enhanced data generator function def enhanced_data_generator(data_type, count): count = min(max(1, int(count)), 1000) if data_type == "Random Numbers": data = [random.randint(1, 100) for _ in range(count)] return f"Generated {count} random numbers:\n{data[:20]}{'...' if count > 20 else ''}" elif data_type == "Names": names = ["Alice Johnson", "Bob Smith", "Charlie Brown", "Diana Prince", "Eve Adams", "Frank Miller", "Grace Lee", "Henry Wilson", "Ivy Chen", "Jack Davis"] data = [random.choice(names) for _ in range(count)] return f"Generated {count} random names:\n{chr(10).join(data[:20])}{'...' if count > 20 else ''}" elif data_type == "Emails": domains = ["gmail.com", "yahoo.com", "outlook.com", "company.com", "techcorp.io"] names = ["user", "admin", "test", "demo", "john", "jane", "alex", "sam"] data = [f"{random.choice(names)}{random.randint(1,999)}@{random.choice(domains)}" for _ in range(count)] return f"Generated {count} sample emails:\n{chr(10).join(data[:20])}{'...' if count > 20 else ''}" elif data_type == "User Profiles": profiles = [] for i in range(min(count, 10)): profile = { "id": f"user_{i+1:03d}", "name": random.choice(["Alice Johnson", "Bob Smith", "Charlie Brown", "Diana Prince"]), "email": f"user{i+1}@example.com", "age": random.randint(18, 65), "role": random.choice(["user", "admin", "moderator"]), "active": random.choice([True, False]), "join_date": datetime.now().isoformat(), "preferences": { "notifications": random.choice([True, False]), "theme": random.choice(["light", "dark"]) } } profiles.append(profile) return json.dumps(profiles, indent=2) elif data_type == "API Responses": responses = [] for i in range(min(count, 5)): response = { "status": random.choice(["success", "error"]), "data": { "id": i + 1, "message": "Operation completed successfully", "timestamp": datetime.now().isoformat() }, "meta": { "request_id": f"req_{random.randint(1000, 9999)}", "processing_time": f"{random.randint(10, 500)}ms" } } responses.append(response) return json.dumps(responses, indent=2) else: # JSON Objects objects = [] for i in range(min(count, 10)): obj = { "id": i + 1, "name": f"Item {i + 1}", "value": random.randint(1, 1000), "active": random.choice([True, False]), "timestamp": datetime.now().isoformat(), "category": random.choice(["electronics", "books", "clothing", "food"]) } objects.append(obj) return json.dumps(objects, indent=2) generate_data_btn.click( fn=enhanced_data_generator, inputs=[data_type, data_count], outputs=data_output ) # Enhanced Image Analyzer Tab with gr.Tab("🖼️ Advanced Image Analyzer", id="image"): gr.Markdown("### Upload and analyze images with detailed AI insights") with gr.Row(): with gr.Column(): image_input = gr.Image( label="Upload an image", type="pil", sources=["upload", "clipboard"] ) analyze_image_btn = gr.Button("🔍 Analyze Image", variant="primary", size="lg") with gr.Column(): image_output = gr.Markdown(label="Advanced Image Analysis") # Enhanced image analyzer def enhanced_image_analyzer(image): if image is None: return "Please upload an image to analyze." try: width, height = image.size mode = image.mode # Enhanced analysis aspect_ratio = width / height total_pixels = width * height # Color analysis colors = image.getcolors(maxcolors=256*256*256) if colors: dominant_color = max(colors, key=lambda item: item[0]) color_count = len(colors) else: dominant_color = None color_count = "Unknown" # Size classification if total_pixels > 2000000: resolution_class = "High Resolution (2MP+)" elif total_pixels > 500000: resolution_class = "Medium Resolution (0.5-2MP)" else: resolution_class = "Low Resolution (<0.5MP)" analysis = f""" 🖼️ **Advanced Image Analysis** **📏 Dimensions & Properties:** - Resolution: {width} × {height} pixels - Aspect Ratio: {aspect_ratio:.3f}:1 - Orientation: {"Portrait" if height > width else "Landscape" if width > height else "Square"} - Color Mode: {mode} - Total Pixels: {total_pixels:,} - Classification: {resolution_class} **🎨 Color Analysis:** - Unique Colors: {color_count} - Complexity: {"High" if isinstance(color_count, int) and color_count > 50000 else "Medium" if isinstance(color_count, int) and color_count > 10000 else "Low"} **📊 Technical Details:** - Estimated File Size: {(total_pixels * 3) / (1024*1024):.2f} MB (uncompressed) - Pixel Density: {total_pixels / (width * height) * 100:.1f}% **💡 Use Cases:** - {"Web Display: Excellent" if width <= 1920 and height <= 1080 else "Web Display: May need optimization"} - {"Print Quality: Good" if total_pixels > 2000000 else "Print Quality: Limited"} - {"Mobile Friendly: Yes" if width <= 1080 else "Mobile Friendly: May need resizing"} """ return analysis except Exception as e: return f"Error analyzing image: {str(e)}" analyze_image_btn.click( fn=enhanced_image_analyzer, inputs=image_input, outputs=image_output ) # Enhanced Chatbot Tab with gr.Tab("💬 Advanced AI Chat", id="chat"): gr.Markdown("### Chat with cutting-edge Hugging Face language models") with gr.Column(): chatbot = gr.Chatbot( label="AI Assistant (Powered by Advanced Models)", height=500, show_label=True, avatar_images=("👤", "🤖") ) with gr.Row(): chat_input = gr.Textbox( label="Your message", placeholder="Ask me anything! I'm powered by advanced AI models...", scale=4, container=False ) send_btn = gr.Button("Send 🚀", variant="primary", scale=1) with gr.Row(): clear_btn = gr.Button("🗑️ Clear Chat", variant="secondary") example_btn = gr.Button("💡 Example Questions", variant="secondary") # Example questions def show_example_questions(): examples = [ "What are the latest advances in AI?", "Explain quantum computing in simple terms", "How do neural networks work?", "What can you help me with?", "Generate a creative story about space exploration" ] return [[None, f"Here are some example questions you can ask:\n\n" + "\n".join([f"• {q}" for q in examples])]], "" # Chat functionality send_btn.click( fn=advanced_chat_response, inputs=[chat_input, chatbot, model_selector], outputs=[chatbot, chat_input] ) chat_input.submit( fn=advanced_chat_response, inputs=[chat_input, chatbot, model_selector], outputs=[chatbot, chat_input] ) clear_btn.click( fn=lambda: ([], ""), outputs=[chatbot, chat_input] ) example_btn.click( fn=show_example_questions, outputs=[chatbot, chat_input] ) # Enhanced Utilities Tab with gr.Tab("🛠️ Advanced Utilities", id="utils"): gr.Markdown("### Enhanced utilities and AI model information") with gr.Row(): with gr.Column(): gr.Markdown("#### 🕒 Current Time") current_time = gr.Textbox( value=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), label="Current Date & Time", interactive=False ) refresh_time_btn = gr.Button("🔄 Refresh Time") gr.Markdown("#### 🧠 Model Performance") performance_info = gr.JSON( value={ "available_models": len(AVAILABLE_MODELS), "model_types": ["Text Generation", "Sentiment Analysis", "Conversational AI"], "features": ["Code Generation", "Text Analysis", "Advanced Chat"], "latest_models": "2025 Hugging Face Collection" }, label="AI Capabilities" ) with gr.Column(): gr.Markdown("#### 📊 App Statistics") stats_display = gr.JSON( value={ "app_version": "3.0.0 - Advanced AI Edition", "ai_features": 8, "supported_models": len(AVAILABLE_MODELS), "tabs": 7, "ai_powered_components": "All", "theme": "Advanced AI Blue" }, label="Application Info" ) gr.Markdown("#### 🌟 Featured Models") featured_models = gr.Markdown(f""" **🚀 2025 Advanced Models:** - **Qwen 2.5 Series**: Latest from Alibaba - **DialoGPT**: Microsoft's conversational AI - **RoBERTa**: Advanced sentiment analysis - **BlenderBot**: Facebook's chat AI **Total Models Available**: {len(AVAILABLE_MODELS)} """) # Utility functions def refresh_time(): return datetime.now().strftime("%Y-%m-%d %H:%M:%S") refresh_time_btn.click(fn=refresh_time, outputs=current_time) # Enhanced Footer gr.Markdown(f""" --- ### 🚀 Advanced AI Features Overview - **🧠 AI Text Analysis**: Powered by latest Hugging Face models with advanced sentiment analysis - **💻 Smart Code Analysis**: Enhanced code insights with complexity analysis - **🛠️ AI Code Generation**: Generate code using state-of-the-art language models - **🎲 Intelligent Data Generation**: Create realistic sample data for development - **🖼️ Advanced Image Analysis**: Detailed image properties and technical analysis - **💬 Next-Gen AI Chat**: Conversation with cutting-edge language models - **🔧 Model Selection**: Choose from {len(AVAILABLE_MODELS)} advanced models including Qwen 2.5, DialoGPT, and more **🤖 Powered by 2025's Most Advanced Open Source Models** | Built with ❤️ using [Gradio](https://gradio.app) & [Hugging Face](https://huggingface.co) *Current Model: Featuring latest Qwen 2.5, DialoGPT, RoBERTa, BlenderBot and more cutting-edge AI models* """) if __name__ == "__main__": print("🚀 Starting Advanced AI Hub with 2025 Hugging Face Models...") print(f"📋 Available Models: {len(AVAILABLE_MODELS)}") print("🔧 Loading interface...") demo.launch( server_name="0.0.0.0", server_port=7860, share=False, show_error=True, quiet=False )