import streamlit as st import pandas as pd from sentence_transformers import SentenceTransformer, util from groq import Groq # 1. Advanced Custom Styling & Glassmorphic CSS Theme Injection st.set_page_config( page_title="ZeroAi - Model Recommendation Engine", page_icon="⚡", layout="wide" ) st.markdown(""" """, unsafe_allow_html=True) # 2. Hardcoded Comprehensive Architecture Mapping Matrix Dataset @st.cache_data def get_model_universe(): return [ # --- Sentiment / Classification --- {"name": "distilbert-base-uncased-finetuned-sst-2-english", "category": "Sentiment Analysis / Text Classification", "speed": 95, "accuracy": 91, "size": "268 MB", "tier": "Lightweight", "desc": "Standard production champion for rapid text emotional polarity checks."}, {"name": "cardiffnlp/twitter-roberta-base-sentiment-latest", "category": "Sentiment Analysis / Text Classification", "speed": 72, "accuracy": 95, "size": "499 MB", "tier": "Balanced Accuracy", "desc": "Superb understanding of text semantics, social colloquialism, and emojis."}, {"name": "prajjwal1/bert-tiny", "category": "Sentiment Analysis / Text Classification", "speed": 99, "accuracy": 76, "size": "17.8 MB", "tier": "Edge / Ultra-Lightweight", "desc": "Microscopic structural footprint ideal for low-compute mobile systems."}, # --- Summarization --- {"name": "facebook/bart-large-cnn", "category": "Summarization", "speed": 48, "accuracy": 96, "size": "1.63 GB", "tier": "Heavyweight Elite", "desc": "Generates pristine, highly articulate abstractive overviews of large document batches."}, {"name": "sshleifer/distilbart-cnn-12-6", "category": "Summarization", "speed": 82, "accuracy": 90, "size": "1.20 GB", "tier": "Balanced Performance", "desc": "Distilled sequence-to-sequence structure saving compute cycles while retaining summary context."}, # --- Token Classification / NER --- {"name": "dbmdz/bert-large-cased-finetuned-conll03-english", "category": "Named Entity Recognition (NER)", "speed": 60, "accuracy": 97, "size": "1.33 GB", "tier": "High Precision", "desc": "Exceptional accuracy benchmarks locating dates, organizations, and geographic records."}, {"name": "elastic/distilbert-base-cased-finetuned-conll03-english", "category": "Named Entity Recognition (NER)", "speed": 94, "accuracy": 89, "size": "261 MB", "tier": "Production Fast-Track", "desc": "Slashes processing pipelines latency timelines on enterprise logs parsing loops."}, # --- Translation --- {"name": "Helsinki-NLP/opus-mt-en-de", "category": "Translation", "speed": 85, "accuracy": 92, "size": "298 MB", "tier": "Targeted Local", "desc": "Highly reliable direct sequence alignment framework built cleanly for European regional shifts."}, {"name": "facebook/m2m100_418M", "category": "Translation", "speed": 55, "accuracy": 90, "size": "1.84 GB", "tier": "Universal Mesh", "desc": "Can cross-translate directly between 100 languages without routing through English first."}, # --- Question Answering --- {"name": "deepset/roberta-base-squad2", "category": "Question Answering", "speed": 74, "accuracy": 93, "size": "496 MB", "tier": "Extractive standard", "desc": "Excellent for context query retrieval engines scanning structured file manuals."}, {"name": "Intel/dynamic_tinybert_squad2", "category": "Question Answering", "speed": 92, "accuracy": 84, "size": "114 MB", "desc": "Accelerated quantization format ensuring nimble interactions on shared networks."}, # --- Code / Text Generation --- {"name": "Qwen/Qwen2.5-Coder-7B-Instruct", "category": "Code Generation & Syntax Design", "speed": 68, "accuracy": 94, "size": "14.0 GB", "tier": "Advanced Local Code", "desc": "State-of-the-art parameters handling polyglot script builds, bug detection, and repo logic."}, {"name": "HuggingFaceTB/SmolLM2-1.3B-Instruct", "category": "General Text Generation & Instructions", "speed": 96, "accuracy": 82, "size": "2.6 GB", "tier": "On-Device Companion", "desc": "Incredible conversational instruction layout designed to squeeze performance on limited rigs."} ] # 3. Initialize Engines (Local Embedder + Groq Matrix API) @st.cache_resource def init_local_embedder(): return SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2") model_universe = get_model_universe() embedder = init_local_embedder() # Setup Categories index categories_list = list(set([m["category"] for m in model_universe])) category_vectors = embedder.encode(categories_list, convert_to_tensor=True) # Secure Groq Cloud Fallback Connection GROQ_KEY = st.secrets.get("GROQ_API_KEY", "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") groq_client = Groq(api_key=GROQ_KEY) # 4. Display Page Framework Renderers st.markdown("""

ZeroAi

📊 Autonomous Model Recommendation Engine & Architectural Expert

""", unsafe_allow_html=True) # Main Multi-Column Split Setup panel_left, panel_right = st.columns([1.1, 2.5], gap="large") with panel_left: st.markdown("### 📈 Core Dimensions") stat_c1, stat_c2 = st.columns(2) stat_c1.metric("Models Indexed", len(model_universe)) stat_c2.metric("Task Arenas", len(categories_list)) st.markdown("---") st.markdown(""" ### 🏆 Best For * 🔥 **Speed:** DistilBERT / TinyBERT * 🎯 **Accuracy:** RoBERTa / BART Large * 📱 **Lightweight:** BERT-tiny variants * 🌐 **Multi-language:** Helsinki-NLP / M2M100 """) st.markdown("---") st.markdown(""" ### 💡 How It Works 1. **Analyzes text query semantic properties** locally. 2. **Maps tasks autonomously** against open-source datasets. 3. **Scores candidate options** matching your performance filters. 4. **Groq Core performs deep consulting logic** to map custom strategies. """) with panel_right: st.markdown("### 🔍 Enterprise Search & Constraints Core") user_prompt = st.text_input( "Describe your technical requirements, goals, or deployment limits:", placeholder="Example: I need a rapid setup to parse short social media complaints on cheap hardware..." ) # Priority Customization Section st.markdown("##### Priority Weight Controls") w_c1, w_c2 = st.columns(2) speed_factor = w_c1.slider("Speed/Inference Importance", 1, 10, 6) acc_factor = w_c2.slider("Accuracy/Precision Importance", 1, 10, 8) # Filter Controls selected_tier = st.selectbox( "Preferred Hardware Tier Filtering (Optional):", ["All Specifications", "Lightweight", "Balanced Accuracy", "High Precision", "Universal Mesh"] ) if user_prompt: # Step A: Perform vector intent analysis locally prompt_vector = embedder.encode(user_prompt, convert_to_tensor=True) search_match = util.semantic_search(prompt_vector, category_vectors, top_k=1) identified_arena = categories_list[search_match[0][0]['corpus_id']] st.markdown(f"🤖 **ZeroAi Intent Analyzer:** Identified Task Domain Target as 👉 ` {identified_arena} `") st.write("---") # Step B: Mathematical filtering and sorting loop candidate_pool = [] for model in model_universe: # Check domain matching if model["category"] == identified_arena: # Calculate ranking values composite_rating = ((model["speed"] * speed_factor) + (model["accuracy"] * acc_factor)) / (speed_factor + acc_factor) # Check Hardware Filters if requested if selected_tier != "All Specifications" and "tier" in model: if selected_tier.lower() not in model["tier"].lower(): continue candidate_pool.append({**model, "final_rating": round(composite_rating, 1)}) # Sort best options to top candidate_pool = sorted(candidate_pool, key=lambda x: x["final_rating"], reverse=True) if not candidate_pool: st.warning("No specific models found matching that exact hardware subset. Displaying baseline category models instead.") candidate_pool = [m for m in model_universe if m["category"] == identified_arena] for c in candidate_pool: c["final_rating"] = 50.0 # Step C: Render Structured Local Recommendations st.markdown("#### Meta-Analysis Matrix: Top Matches") for rank, item in enumerate(candidate_pool[:3]): award_title = "🥇 Optimal Machine Choice" if rank == 0 else f"🥈 Alternative Match #{rank+1}" st.markdown(f"""
{item['name']} {award_title}

{item['desc']}

⚡ Speed: {item['speed']}/100 🎯 Accuracy: {item['accuracy']}/100 📦 Weight: {item['size']} Fitness Metric: {item.get('final_rating', 'N/A')}%
""", unsafe_allow_html=True) # Step D: Call Groq Core as an Expert AI Advisor to generate integration code st.write("---") st.markdown("### 🧠 ZeroAi Deep Advisory Report (Powered by Groq Cloud)") with st.spinner("Generating specialized implementation architecture blueprint..."): best_model_choice = candidate_pool[0]["name"] # Construct instructions for Groq expert_prompt = f""" You are the advanced brain of ZeroAi Engine. The user prompt is: "{user_prompt}" The mapped task category is: "{identified_arena}" The calculated best choice model is: "{best_model_choice}" Provide a professional, concise executive advisory breakdown containing: 1. Why this selection fits their constraint needs perfectly. 2. A tiny 4-5 line clean Python pipeline snippet using `transformers` to load and run this exact model instantly for them. Keep text professional, clean, dark-mode readable and straight to the point. """ try: chat_feedback = groq_client.chat.completions.create( model="llama-3.3-70b-versatile", messages=[ {"role": "system", "content": "You are the advanced ZeroAi core recommendation consultant code manager. Output valid markdown."}, {"role": "user", "content": expert_prompt} ], temperature=0.3 ) report_content = chat_feedback.choices[0].message.content st.markdown(f"""
🔹 System Deployment Architecture Advisory Report
{report_content}
""", unsafe_allow_html=True) except Exception as system_err: st.info("Advisory text generation offline. Use the local parameters mapping card layout matrix displayed above.") else: st.info("Input a system task statement above. ZeroAi will handle parsing, filtering, evaluation, and code snippet generation automatically.")