File size: 15,165 Bytes
fcc2075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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("""
    <style>
    /* Premium Cyber-Dark Space Backdrop */
    .stApp {
        background: radial-gradient(circle at 10% 20%, rgba(16, 185, 129, 0.12) 0%, transparent 45%),
                    radial-gradient(circle at 90% 80%, rgba(59, 130, 246, 0.12) 0%, transparent 45%),
                    #020617;
        color: #f3f4f6;
    }
    
    /* Central Hub Title Card */
    .hero-banner {
        text-align: center;
        padding: 30px;
        background: rgba(15, 23, 42, 0.5);
        backdrop-filter: blur(16px);
        border: 1px solid rgba(255, 255, 255, 0.05);
        border-radius: 24px;
        margin-bottom: 25px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.4);
    }
    .hero-banner h1 {
        background: linear-gradient(to right, #ffffff, #10b981, #3b82f6);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        font-weight: 800;
        font-size: 2.8rem;
        letter-spacing: -1px;
    }
    
    /* Neon glow adjustments for metrics display layout */
    div[data-testid="stMetricValue"] {
        color: #10b981 !important;
        font-weight: 800 !important;
    }
    .stMetric {
        background: rgba(30, 41, 59, 0.35) !important;
        backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.05) !important;
        padding: 15px !important;
        border-radius: 16px !important;
    }
    
    /* Card design layout templates */
    .rec-card {
        background: rgba(15, 23, 42, 0.6);
        border-left: 4px solid #10b981;
        padding: 22px;
        border-radius: 14px;
        margin-bottom: 20px;
        border-top: 1px solid rgba(255, 255, 255, 0.05);
        border-right: 1px solid rgba(255, 255, 255, 0.05);
        border-bottom: 1px solid rgba(255, 255, 255, 0.05);
    }
    .consultant-card {
        background: rgba(30, 41, 59, 0.25);
        border: 1px dashed rgba(59, 130, 246, 0.4);
        padding: 20px;
        border-radius: 14px;
        margin-top: 25px;
    }
    
    /* Performance Badges */
    .badge {
        display: inline-block;
        padding: 3px 12px;
        border-radius: 20px;
        font-size: 0.75rem;
        font-weight: 600;
        margin-right: 8px;
        margin-top: 5px;
    }
    .b-speed { background-color: rgba(239, 68, 68, 0.15); color: #f87171; border: 1px solid rgba(239, 68, 68, 0.3); }
    .b-accuracy { background-color: rgba(59, 130, 246, 0.15); color: #60a5fa; border: 1px solid rgba(59, 130, 246, 0.3); }
    .b-size { background-color: rgba(16, 185, 129, 0.15); color: #34d399; border: 1px solid rgba(16, 185, 129, 0.3); }
    </style>
""", 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("""
    <div class="hero-banner">
        <h1>ZeroAi</h1>
        <p style="color: #94a3b8; font-size: 1.1rem; margin-top: 5px; font-weight: 500;">
            πŸ“Š Autonomous Model Recommendation Engine & Architectural Expert
        </p>
    </div>
""", 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"""
                <div class="rec-card">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <span style="font-weight: 700; font-size: 1.15rem; color: #10b981;">{item['name']}</span>
                        <span style="color: #94a3b8; font-size: 0.8rem; font-weight: bold; text-transform: uppercase;">{award_title}</span>
                    </div>
                    <p style="color: #cbd5e1; font-size: 0.9rem; margin-top: 6px;">{item['desc']}</p>
                    <div style="margin-top: 10px;">
                        <span class="badge b-speed">⚑ Speed: {item['speed']}/100</span>
                        <span class="badge b-accuracy">🎯 Accuracy: {item['accuracy']}/100</span>
                        <span class="badge b-size">πŸ“¦ Weight: {item['size']}</span>
                        <span style="float: right; font-weight: 700; color: #3b82f6;">Fitness Metric: {item.get('final_rating', 'N/A')}%</span>
                    </div>
                </div>
            """, 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"""
                    <div class="consultant-card">
                        <div style="font-weight: bold; font-size: 1.05rem; color: #60a5fa; margin-bottom: 12px; display: flex; align-items: center; gap: 8px;">
                            <span>πŸ”Ή System Deployment Architecture Advisory Report</span>
                        </div>
                        {report_content}
                    </div>
                """, 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.")