Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| from PIL import Image, ImageOps, ImageFilter, ImageEnhance | |
| import numpy as np | |
| import pandas as pd | |
| import matplotlib | |
| matplotlib.use('Agg') | |
| import matplotlib.pyplot as plt | |
| import json | |
| import re | |
| # Custom CSS for modern glassmorphism aesthetic | |
| custom_css = """ | |
| @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;500;600;700&family=Outfit:wght@300;400;500;600;700&display=swap'); | |
| /* Global Styling */ | |
| body, .gradio-container { | |
| font-family: 'Plus Jakarta Sans', 'Outfit', sans-serif !important; | |
| background: radial-gradient(circle at top right, #0d0b21, #06050f) !important; | |
| color: #f1f5f9 !important; | |
| } | |
| /* Glassmorphism Panel styles */ | |
| .glass-panel { | |
| background: rgba(15, 23, 42, 0.45) !important; | |
| backdrop-filter: blur(16px) !important; | |
| -webkit-backdrop-filter: blur(16px) !important; | |
| border: 1px solid rgba(255, 255, 255, 0.08) !important; | |
| border-radius: 16px !important; | |
| box-shadow: 0 10px 30px -10px rgba(0, 0, 0, 0.5) !important; | |
| padding: 20px !important; | |
| margin-bottom: 20px !important; | |
| } | |
| .title-container { | |
| text-align: center; | |
| padding: 30px 20px; | |
| margin-bottom: 20px; | |
| background: linear-gradient(180deg, rgba(99, 102, 241, 0.1) 0%, rgba(99, 102, 241, 0) 100%); | |
| border-radius: 20px; | |
| border: 1px solid rgba(99, 102, 241, 0.15); | |
| } | |
| .title-main { | |
| background: linear-gradient(135deg, #a78bfa, #818cf8, #38bdf8) !important; | |
| -webkit-background-clip: text !important; | |
| -webkit-text-fill-color: transparent !important; | |
| font-weight: 800 !important; | |
| font-size: 2.8rem !important; | |
| letter-spacing: -0.025em; | |
| margin-bottom: 8px; | |
| text-shadow: 0 0 50px rgba(139, 92, 246, 0.15); | |
| } | |
| .title-sub { | |
| color: #94a3b8 !important; | |
| font-size: 1.1rem !important; | |
| font-weight: 400; | |
| } | |
| /* Tabs customization */ | |
| .tabs { | |
| border-bottom: 1px solid rgba(255, 255, 255, 0.1) !important; | |
| } | |
| .tabs button { | |
| font-size: 1rem !important; | |
| font-weight: 600 !important; | |
| color: #94a3b8 !important; | |
| border: none !important; | |
| padding: 10px 20px !important; | |
| transition: all 0.2s ease-in-out !important; | |
| } | |
| .tabs button.selected { | |
| color: #38bdf8 !important; | |
| background: rgba(56, 189, 248, 0.08) !important; | |
| border-bottom: 2px solid #38bdf8 !important; | |
| border-top-left-radius: 8px; | |
| border-top-right-radius: 8px; | |
| } | |
| /* Button variants */ | |
| .primary-btn { | |
| background: linear-gradient(135deg, #6366f1, #a855f7) !important; | |
| border: none !important; | |
| color: white !important; | |
| font-weight: 600 !important; | |
| border-radius: 10px !important; | |
| box-shadow: 0 4px 14px 0 rgba(99, 102, 241, 0.35) !important; | |
| transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important; | |
| } | |
| .primary-btn:hover { | |
| transform: translateY(-2px) !important; | |
| box-shadow: 0 8px 24px 0 rgba(168, 85, 247, 0.5) !important; | |
| } | |
| .secondary-btn { | |
| background: rgba(255, 255, 255, 0.05) !important; | |
| border: 1px solid rgba(255, 255, 255, 0.12) !important; | |
| color: #e2e8f0 !important; | |
| font-weight: 500 !important; | |
| border-radius: 10px !important; | |
| transition: all 0.2s ease !important; | |
| } | |
| .secondary-btn:hover { | |
| background: rgba(255, 255, 255, 0.1) !important; | |
| border-color: rgba(255, 255, 255, 0.25) !important; | |
| } | |
| /* Metric styling */ | |
| .metric-wrapper { | |
| display: flex; | |
| justify-content: space-around; | |
| gap: 15px; | |
| flex-wrap: wrap; | |
| } | |
| .metric-card { | |
| flex: 1; | |
| min-width: 140px; | |
| background: rgba(255, 255, 255, 0.02) !important; | |
| border: 1px solid rgba(255, 255, 255, 0.05) !important; | |
| border-radius: 12px !important; | |
| padding: 16px !important; | |
| text-align: center; | |
| transition: all 0.3s ease !important; | |
| } | |
| .metric-card:hover { | |
| background: rgba(255, 255, 255, 0.04) !important; | |
| border-color: rgba(99, 102, 241, 0.3) !important; | |
| transform: translateY(-2px) !important; | |
| } | |
| .metric-label { | |
| font-size: 0.85rem; | |
| color: #94a3b8; | |
| text-transform: uppercase; | |
| letter-spacing: 0.05em; | |
| } | |
| .metric-value { | |
| font-size: 1.8rem; | |
| font-weight: 700; | |
| margin-top: 5px; | |
| } | |
| .metric-blue { color: #38bdf8; } | |
| .metric-purple { color: #c084fc; } | |
| .metric-emerald { color: #34d399; } | |
| .metric-rose { color: #fb7185; } | |
| /* Custom Chatbot adjustments */ | |
| .chatbot-container { | |
| border-radius: 12px !important; | |
| border: 1px solid rgba(255, 255, 255, 0.08) !important; | |
| background: rgba(15, 23, 42, 0.3) !important; | |
| } | |
| """ | |
| # ========================================== | |
| # TEXT STUDIO LOGIC | |
| # ========================================== | |
| STOPWORDS = { | |
| 'i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', "you're", "you've", "you'll", "you'd", | |
| 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', 'himself', 'she', "she's", 'her', 'hers', | |
| 'herself', 'it', "it's", 'its', 'itself', 'they', 'them', 'their', 'theirs', 'themselves', 'what', 'which', | |
| 'who', 'whom', 'this', 'that', "that'll", 'these', 'those', 'am', 'is', 'are', 'was', 'were', 'be', 'been', | |
| 'being', 'have', 'has', 'had', 'having', 'do', 'does', 'did', 'doing', 'a', 'an', 'the', 'and', 'but', 'if', | |
| 'or', 'because', 'as', 'until', 'while', 'of', 'at', 'by', 'for', 'with', 'about', 'against', 'between', | |
| 'into', 'through', 'during', 'before', 'after', 'above', 'below', 'to', 'from', 'up', 'down', 'in', 'out', | |
| 'on', 'off', 'over', 'under', 'again', 'further', 'then', 'once', 'here', 'there', 'when', 'where', 'why', | |
| 'how', 'all', 'any', 'both', 'each', 'few', 'more', 'most', 'other', 'some', 'such', 'no', 'nor', 'not', | |
| 'only', 'own', 'same', 'so', 'than', 'too', 'very', 's', 't', 'can', 'will', 'just', 'don', "don't", 'should', | |
| "should've", 'now', 'd', 'll', 'm', 'o', 're', 've', 'y', 'ain', 'aren', "aren't", 'couldn', "couldn't", | |
| 'didn', "didn't", 'doesn', "doesn't", 'hadn', "hadn't", 'hasn', "hasn't", 'haven', "haven't", 'isn', "isn't", | |
| 'ma', 'mightn', "mightn't", 'mustn', "mustn't", 'needn', "needn't", 'shan', "shan't", 'shouldn', "shouldn't", | |
| 'wasn', "wasn't", 'weren', "weren't", 'won', "won't", 'wouldn', "wouldn't" | |
| } | |
| POSITIVE_WORDS = { | |
| 'great', 'good', 'excellent', 'amazing', 'beautiful', 'wonderful', 'love', 'happy', 'cool', 'nice', 'awesome', | |
| 'fantastic', 'superb', 'best', 'outstanding', 'glad', 'pleased', 'perfect', 'brilliant', 'smart', 'helpful', | |
| 'friendly', 'recommend', 'satisfied', 'clean', 'easy', 'creative', 'advanced', 'premium', 'incredible' | |
| } | |
| NEGATIVE_WORDS = { | |
| 'bad', 'poor', 'terrible', 'worst', 'hate', 'sad', 'awful', 'horrible', 'disappointed', 'dislike', 'annoyed', | |
| 'useless', 'difficult', 'slow', 'crash', 'bug', 'error', 'fail', 'broken', 'waste', 'expensive', 'ugly', | |
| 'boring', 'weird', 'angry', 'hate', 'rude', 'frustrated', 'complaint', 'defect', 'flaw', 'messy' | |
| } | |
| def analyze_text(text, task_type): | |
| if not text.strip(): | |
| return "Please input some text first.", {} | |
| # Basic analysis stats | |
| words = re.findall(r'\b\w+\b', text.lower()) | |
| word_count = len(words) | |
| char_count = len(text) | |
| reading_time = max(1, round(word_count / 200)) # Avg 200 wpm | |
| # Keyword extraction (frequency filter) | |
| freq = {} | |
| for w in words: | |
| if w not in STOPWORDS and len(w) > 2: | |
| freq[w] = freq.get(w, 0) + 1 | |
| sorted_keywords = sorted(freq.items(), key=lambda x: x[1], reverse=True)[:5] | |
| keywords_str = ", ".join([f"{k} ({v}x)" for k, v in sorted_keywords]) | |
| # Sentiment analysis | |
| pos_matches = [w for w in words if w in POSITIVE_WORDS] | |
| neg_matches = [w for w in words if w in NEGATIVE_WORDS] | |
| pos_count = len(pos_matches) | |
| neg_count = len(neg_matches) | |
| if pos_count > neg_count: | |
| sentiment = "Positive ๐" | |
| score = min(1.0, 0.5 + (pos_count - neg_count) / 10.0) | |
| elif neg_count > pos_count: | |
| sentiment = "Negative ๐" | |
| score = max(0.0, 0.5 - (neg_count - pos_count) / 10.0) | |
| else: | |
| sentiment = "Neutral ๐" | |
| score = 0.5 | |
| meta_info = { | |
| "Word Count": word_count, | |
| "Character Count": char_count, | |
| "Est. Reading Time": f"{reading_time} min", | |
| "Extracted Keywords": keywords_str if keywords_str else "None", | |
| "Sentiment Score": f"{score:.2f} ({sentiment})" | |
| } | |
| if task_type == "Sentiment Analysis": | |
| details = f"### Sentiment Assessment\n\n**Result:** {sentiment}\n\n**Analysis Details:**\n" | |
| details += f"- Positive Words Found: {pos_count} ({', '.join(pos_matches) if pos_matches else 'none'})\n" | |
| details += f"- Negative Words Found: {neg_count} ({', '.join(neg_matches) if neg_matches else 'none'})\n" | |
| details += f"\nConfidence Index: **{abs(score - 0.5) * 2:.1%}**" | |
| return details, meta_info | |
| elif task_type == "Summarization": | |
| # Extract first and last sentences or simple rules | |
| sentences = re.split(r'(?<=[.!?])\s+', text) | |
| if len(sentences) <= 2: | |
| summary = text | |
| else: | |
| summary = sentences[0] + " ... [Content Summary] ... " + sentences[-1] | |
| return f"### Document Summary\n\n> {summary}\n\n*Original content condensed from {len(sentences)} sentences to 2 key anchors.*", meta_info | |
| elif task_type == "Keyword Extraction": | |
| table_md = "### Top Keywords & Frequencies\n\n| Word | Frequency | Category |\n| --- | --- | --- |\n" | |
| for idx, (kw, val) in enumerate(sorted_keywords): | |
| cat = "Technical/Topic" if len(kw) > 6 else "General" | |
| table_md += f"| **{kw}** | {val} | {cat} |\n" | |
| if not sorted_keywords: | |
| table_md += "| - | - | - |\n" | |
| return table_md, meta_info | |
| elif task_type == "Pirate Stylizer": | |
| # Fun style rewrite rules | |
| pirate_map = { | |
| r'\bhello\b': 'Ahoy', | |
| r'\bmy\b': 'me', | |
| r'\bfriend\b': 'matey', | |
| r'\byou\b': 'ye', | |
| r'\bis\b': 'be', | |
| r'\bare\b': 'be', | |
| r'\bthe\b': 'the pirate\'s', | |
| r'\bof\b': 'o\'', | |
| r'\band\b': 'an\'', | |
| r'\bwork\b': 'plunder' | |
| } | |
| rewritten = text | |
| for p, r in pirate_map.items(): | |
| rewritten = re.sub(p, r, rewritten, flags=re.IGNORECASE) | |
| # Add some pirate flavor | |
| rewritten = "Shiver me timbers! " + rewritten + "\n\n-- Yo ho ho! ๐ดโโ ๏ธ" | |
| return f"### Pirate Style Rewrite\n\n{rewritten}", meta_info | |
| return "Unknown operation.", {} | |
| # ========================================== | |
| # VISION SANDBOX LOGIC | |
| # ========================================== | |
| def process_image(img, effect, brightness, contrast): | |
| if img is None: | |
| return None | |
| # Convert to PIL | |
| pil_img = Image.fromarray(img) | |
| # Apply brightness | |
| if brightness != 1.0: | |
| enhancer = ImageEnhance.Brightness(pil_img) | |
| pil_img = enhancer.enhance(brightness) | |
| # Apply contrast | |
| if contrast != 1.0: | |
| enhancer = ImageEnhance.Contrast(pil_img) | |
| pil_img = enhancer.enhance(contrast) | |
| # Apply artistic effects | |
| if effect == "Grayscale": | |
| pil_img = ImageOps.grayscale(pil_img) | |
| # Convert back to RGB for display | |
| pil_img = pil_img.convert("RGB") | |
| elif effect == "Sepia": | |
| # Custom sepia transformation matrix | |
| sepia_matrix = ( | |
| 0.393, 0.769, 0.189, 0, | |
| 0.349, 0.686, 0.168, 0, | |
| 0.272, 0.534, 0.131, 0 | |
| ) | |
| pil_img = pil_img.convert("RGB") | |
| pil_img = pil_img.transform(pil_img.size, Image.EXTENT, (0, 0) + pil_img.size) | |
| # Apply matrix manually using custom sepia loop or conversion | |
| np_img = np.array(pil_img) | |
| sepia_filter = np.array([[0.393, 0.769, 0.189], | |
| [0.349, 0.686, 0.168], | |
| [0.272, 0.534, 0.131]]) | |
| sepia_img = np_img.dot(sepia_filter.T) | |
| sepia_img[sepia_img > 255] = 255 | |
| pil_img = Image.fromarray(sepia_img.astype(np.uint8)) | |
| elif effect == "Edge Detection": | |
| pil_img = pil_img.convert("L").filter(ImageFilter.FIND_EDGES).convert("RGB") | |
| elif effect == "Gaussian Blur": | |
| pil_img = pil_img.filter(ImageFilter.GaussianBlur(radius=5)) | |
| elif effect == "Invert": | |
| pil_img = ImageOps.invert(pil_img.convert("RGB")) | |
| elif effect == "Pencil Sketch": | |
| # Sketch effect = grayscale + invert + blur + dodge blending | |
| gray_img = ImageOps.grayscale(pil_img) | |
| inverted_img = ImageOps.invert(gray_img) | |
| blurred_img = inverted_img.filter(ImageFilter.GaussianBlur(radius=10)) | |
| # Dodge blend | |
| np_gray = np.array(gray_img, dtype=float) | |
| np_blur = np.array(blurred_img, dtype=float) | |
| # Avoid division by zero | |
| blend = np_gray * 255.0 / (255.0 - np_blur + 1e-5) | |
| blend[blend > 255] = 255 | |
| blend[np_blur == 255] = 255 | |
| pil_img = Image.fromarray(blend.astype(np.uint8)).convert("RGB") | |
| return pil_img | |
| # ========================================== | |
| # ASSISTANT CHAT LOGIC | |
| # ========================================== | |
| persona_prompts = { | |
| "Cyberpunk Coder ๐ป": "System: You are Jax, an elite cyberpunk netrunner and senior systems architect coding in a neon-drenched metropolis. Your coding style is concise, highly modular, optimized, and uses cybernetic slang occasionally. Wrap all code snippets in markdown code blocks.", | |
| "Design Guru ๐จ": "System: You are Luna, a world-class UI/UX creative director. You focus on human-centered design, rich aesthetics, typography, accessibility, glassmorphic UI, animations, and micro-interactions. You explain things visually and with great passion for details.", | |
| "Logic Sage ๐ง ": "System: You are the Sage of Logic. You analyze problems using first-principles thinking, formal system logic, and break down complex equations or architectures into clear mathematical proofs or structured steps. You avoid fluff and speak with deep clarity." | |
| } | |
| def respond_chat(message, history, persona): | |
| if not message.strip(): | |
| return "", history | |
| # Initialize history if empty | |
| if history is None: | |
| history = [] | |
| # Get system prompt | |
| sys_prompt = persona_prompts.get(persona, "System: You are a helpful assistant.") | |
| # Custom response simulation based on the selected persona and the message | |
| msg_lower = message.lower() | |
| response = "" | |
| if persona == "Cyberpunk Coder ๐ป": | |
| response = f"**[NETRUN_LOG]** *Packet intercept successful. Executing logic stream...*\n\n" | |
| if "code" in msg_lower or "write" in msg_lower or "create" in msg_lower: | |
| response += "Here is the clean implementation block you requested, optimized for low latency:\n\n" | |
| response += "```python\n# Optimized system module\nimport time\n\ndef execute_subroutine(node_id: str, complexity: int = 1) -> dict:\n \"\"\"\n Core execution thread. Runs isolated container operations.\n \"\"\"\n start = time.perf_counter()\n checksum = sum(ord(char) for char in node_id) * complexity\n latency = (time.perf_counter() - start) * 1000\n \n return {\n \"status\": \"ACTIVE\",\n \"node\": node_id,\n \"checksum\": hex(checksum),\n \"latency_ms\": round(latency, 4)\n }\n```\n\nModify the checksum seed if you need specialized encryption. Keep the ports secured, matey." | |
| elif "help" in msg_lower or "how" in msg_lower: | |
| response += "Analyzing query parameters. To build or deploy your network node:\n\n1. Establish the repository structure (`app.py`, `requirements.txt`).\n2. Define Hugging Face space metadata in `README.md` block.\n3. Spin up git remote connections and commit changes.\n4. Initialize build protocols via `git push origin main`." | |
| else: | |
| response += f"Node command `{message}` registered in system memory. What network subroutine are we hacking into next, developer? Let's write some modular code." | |
| elif persona == "Design Guru ๐จ": | |
| response = "### ๐จ Luna's Design Critique & Suggestion\n\nYour concept is delightful! To elevate this to a **premium, world-class experience**, let's apply a few modern UI principles:\n\n" | |
| response += "1. **Depth & Texture**: Use a multi-layered dark background using `radial-gradient(circle at top right, #1a163a, #0b071a)`. It adds rich dimension.\n" | |
| response += "2. **Glassmorphism**: Enhance content blocks with `backdrop-filter: blur(12px)` and a subtle `1px solid rgba(255, 255, 255, 0.08)` border. This establishes clear visual hierarchy without heavy opaque blocks.\n" | |
| response += "3. **Visual Hierarchy**: Make typography do the heavy lifting. Pair a wide, high-contrast display font like *Outfit* or *Plus Jakarta Sans* for headers with a highly legible sans-serif for body text.\n\n" | |
| response += "> *Good design is not what it looks like; it's how it behaves and communicates trust.* Let's paint the digital canvas!" | |
| else: # Logic Sage ๐ง | |
| response = "### ๐ง Logical Analysis: Decomposition & Synthesis\n\nLet us break down the query using first-principles thinking.\n\n" | |
| response += "**1. Core Premise Evaluation:**\n" | |
| response += f"The query '{message}' is processed as an input parameter $I$. We must identify the underlying variables and constraints.\n\n" | |
| response += "**2. Structured Analysis:**\n" | |
| response += "- **Decomposition**: We separate the input into structural components (what is requested) and contextual constraints (how it must behave).\n" | |
| response += "- **Deduction**: A logical synthesis requires we establish a deterministic plan. Let's list the steps sequentially.\n" | |
| response += "- **Evaluation**: Each step is checked for logical consistency and performance limits.\n\n" | |
| response += "What specific system configuration or logical framework shall we analyze next?" | |
| history.append((message, response)) | |
| return "", history | |
| # ========================================== | |
| # METRICS & PERFORMANCE LOGIC | |
| # ========================================== | |
| def update_metrics(traffic, server_load): | |
| # Simulated metrics calculations | |
| cpu = min(99.8, round(server_load * 0.95 + (traffic / 100.0) * 12 + np.random.uniform(-2, 2), 1)) | |
| cpu = max(1.5, cpu) | |
| memory = min(95.0, round(45.2 + (server_load * 0.25) + np.random.uniform(-0.5, 0.5), 1)) | |
| latency = max(8, int(15 + (traffic * 0.4) + (server_load * 1.2) + np.random.randint(-4, 4))) | |
| success_rate = max(85.0, min(100.0, round(99.9 - (server_load / 30.0)**2 + np.random.uniform(-0.1, 0.1), 2))) | |
| if cpu > 95: | |
| success_rate -= np.random.uniform(5, 12) | |
| success_rate = max(65.0, round(success_rate, 2)) | |
| # Generate a gorgeous Matplotlib dark themed line chart | |
| plt.style.use('dark_background') | |
| fig, ax = plt.subplots(figsize=(7, 3), dpi=150) | |
| fig.patch.set_facecolor('#0d0b21') | |
| ax.set_facecolor('rgba(0,0,0,0)') | |
| # Custom colors matching gradient | |
| color_lat = '#38bdf8' | |
| color_req = '#a78bfa' | |
| # X axis (last 10 minutes) | |
| time_series = [f"-{i}m" for i in range(9, -1, -1)] | |
| # Latency data points base | |
| lat_data = [latency + np.random.randint(-10, 10) for _ in range(9)] + [latency] | |
| lat_data = [max(5, x) for x in lat_data] | |
| # Request count base | |
| req_data = [traffic + np.random.randint(-15, 15) for _ in range(9)] + [traffic] | |
| req_data = [max(0, x) for x in req_data] | |
| # Draw lines | |
| ax.plot(time_series, lat_data, color=color_lat, marker='o', linewidth=2.5, markersize=5, label='Latency (ms)') | |
| ax.set_ylabel('Latency (ms)', color=color_lat, fontweight='bold') | |
| ax.tick_params(axis='y', labelcolor=color_lat) | |
| # Twin axis for request volume | |
| ax2 = ax.twinx() | |
| ax2.bar(time_series, req_data, alpha=0.25, color=color_req, width=0.4, label='Requests / min') | |
| ax2.set_ylabel('Requests / min', color=color_req, fontweight='bold') | |
| ax2.tick_params(axis='y', labelcolor=color_req) | |
| # Grid lines customization | |
| ax.grid(True, color='rgba(255, 255, 255, 0.05)', linestyle='--') | |
| ax.spines['top'].set_visible(False) | |
| ax.spines['right'].set_visible(False) | |
| ax.spines['left'].set_visible(False) | |
| ax.spines['bottom'].set_color('rgba(255,255,255,0.15)') | |
| ax.set_title('Real-time Traffic & Response Performance', fontsize=10, color='#94a3b8', pad=12) | |
| plt.tight_layout() | |
| # Format metrics for HTML card display | |
| metrics_html = f""" | |
| <div class="metric-wrapper"> | |
| <div class="metric-card"> | |
| <div class="metric-label">CPU Usage</div> | |
| <div class="metric-value metric-blue">{cpu}%</div> | |
| </div> | |
| <div class="metric-card"> | |
| <div class="metric-label">Memory</div> | |
| <div class="metric-value metric-purple">{memory}%</div> | |
| </div> | |
| <div class="metric-card"> | |
| <div class="metric-label">Latency</div> | |
| <div class="metric-value metric-emerald">{latency} ms</div> | |
| </div> | |
| <div class="metric-card"> | |
| <div class="metric-label">Success Rate</div> | |
| <div class="metric-value metric-rose">{success_rate}%</div> | |
| </div> | |
| </div> | |
| """ | |
| return metrics_html, fig | |
| # ========================================== | |
| # APP BUILDER & INTERFACE | |
| # ========================================== | |
| with gr.Blocks(css=custom_css, title="NexusAI Hub - Premium Workspace", theme=gr.themes.Default()) as demo: | |
| # Beautiful glowing header banner | |
| with gr.HTML(elem_id="header"): | |
| gr.HTML(""" | |
| <div class="title-container"> | |
| <h1 class="title-main">๐ NEXUSAI HUB</h1> | |
| <p class="title-sub">A State-of-the-Art Interactive Developer Sandbox & System Monitor</p> | |
| </div> | |
| """) | |
| with gr.Tabs(): | |
| # ---------------------------- | |
| # TAB 1: WELCOME & NEWS FEED | |
| # ---------------------------- | |
| with gr.TabItem("๐ Dashboard Overview"): | |
| with gr.Row(): | |
| with gr.Column(scale=2, elem_classes="glass-panel"): | |
| gr.Markdown("### Welcome to the NexusAI Ecosystem") | |
| gr.Markdown(""" | |
| This space represents a premium developer utility hub, built to deploy instantly on Hugging Face Spaces. It bundles four major domains of modern developer tools: | |
| * **AI Assistant Chat**: Configurable persona-based simulation for testing different coding/design paradigms. | |
| * **Natural Language Processing (NLP)**: Interactive tools for keyword, sentiment, and structural parsing. | |
| * **Computer Vision Sandbox**: Real-time canvas for complex filters, brightness matrices, and sketch rendering. | |
| * **Telemetry & Infrastructure**: Simulated real-time server telemetry dashboard including system loads, success rates, and live plotting. | |
| Select a tab from the header to explore the workspaces. Every tool responds instantly with visual telemetry outputs. | |
| """) | |
| with gr.Row(): | |
| gr.HTML(""" | |
| <div style="display: flex; gap: 15px; margin-top: 15px;"> | |
| <a href="https://huggingface.co/spaces" target="_blank" style="flex:1; text-align:center; padding:12px; background: rgba(99, 102, 241, 0.1); border: 1px solid rgba(99, 102, 241, 0.3); border-radius: 8px; color: #a78bfa; text-decoration: none; font-weight: 600;"> | |
| ๐ค Hugging Face Spaces Docs | |
| </a> | |
| <a href="https://gradio.app" target="_blank" style="flex:1; text-align:center; padding:12px; background: rgba(56, 189, 248, 0.1); border: 1px solid rgba(56, 189, 248, 0.3); border-radius: 8px; color: #38bdf8; text-decoration: none; font-weight: 600;"> | |
| โก Gradio Documentation | |
| </a> | |
| </div> | |
| """) | |
| with gr.Column(scale=1, elem_classes="glass-panel"): | |
| gr.Markdown("### Space Specifications") | |
| specs = pd.DataFrame({ | |
| "Metric": ["Target Engine", "SDK Platform", "Python Version", "Container Base", "Deployment Status"], | |
| "Value": ["Hugging Face Space", "Gradio 5.0.0", "Python 3.9+", "Ubuntu Linux", "Ready to Build"] | |
| }) | |
| gr.DataFrame(specs, interactive=False, show_label=False) | |
| gr.Markdown(""" | |
| > **Tip:** You can push this directory directly to your Hugging Face Space repository using standard Git commands. All configurations have been pre-set in the `.README.md` metadata frontmatter. | |
| """) | |
| # ---------------------------- | |
| # TAB 2: ASSISTANT CHAT | |
| # ---------------------------- | |
| with gr.TabItem("๐ฌ Assistant Chat"): | |
| with gr.Row(): | |
| with gr.Column(scale=1, elem_classes="glass-panel"): | |
| gr.Markdown("### Chat Configuration") | |
| persona_sel = gr.Dropdown( | |
| choices=list(persona_prompts.keys()), | |
| value="Cyberpunk Coder ๐ป", | |
| label="Select Persona Model", | |
| info="Adjust the assistant's persona background logic dynamically." | |
| ) | |
| gr.Markdown(""" | |
| Changing the persona modifies the core system instruction set instantly. | |
| * **Cyberpunk Coder**: Best for clean algorithms, software structures, and netrunner banter. | |
| * **Design Guru**: Focuses on micro-interactions, CSS styling systems, typography rules, and rich design theory. | |
| * **Logic Sage**: Provides deterministic first-principles thinking, structural breakdown, and formal logic. | |
| """) | |
| with gr.Column(scale=3, elem_classes="glass-panel"): | |
| chatbot = gr.Chatbot(label="Assistant Chat Stream", elem_classes="chatbot-container") | |
| with gr.Row(): | |
| chat_input = gr.Textbox( | |
| show_label=False, | |
| placeholder="Ask the assistant anything... (e.g. 'How do I optimize a deployment?' or 'Explain grid design')", | |
| scale=4 | |
| ) | |
| send_btn = gr.Button("Send", variant="primary", scale=1, elem_classes="primary-btn") | |
| # Handle actions | |
| chat_input.submit(respond_chat, inputs=[chat_input, chatbot, persona_sel], outputs=[chat_input, chatbot]) | |
| send_btn.click(respond_chat, inputs=[chat_input, chatbot, persona_sel], outputs=[chat_input, chatbot]) | |
| # ---------------------------- | |
| # TAB 3: TEXT STUDIO | |
| # ---------------------------- | |
| with gr.TabItem("๐ Text Studio"): | |
| with gr.Row(): | |
| with gr.Column(scale=1, elem_classes="glass-panel"): | |
| gr.Markdown("### Input Document") | |
| text_input = gr.Textbox( | |
| label="Source Text", | |
| lines=10, | |
| placeholder="Paste your source document here...", | |
| value="Gradio is an open-source Python library that is used to build web applications. It allows developers to build user interfaces for their machine learning models or python scripts with ease. Hugging Face Spaces is a hosting service for Git repositories, allowing you to showcase and share web apps created with Gradio or Streamlit. This dashboard template uses custom CSS, glassmorphism UI, and real-time visualization frameworks to offer an outstanding premium feel. I absolutely love how beautiful, clean, and interactive it is! However, configuring raw deployment steps without a tool can be slow and annoying if there are errors." | |
| ) | |
| gr.Markdown("### Select Operation") | |
| nlp_op = gr.Radio( | |
| choices=["Sentiment Analysis", "Summarization", "Keyword Extraction", "Pirate Stylizer"], | |
| value="Sentiment Analysis", | |
| show_label=False | |
| ) | |
| run_text_btn = gr.Button("Process Text", variant="primary", elem_classes="primary-btn") | |
| with gr.Column(scale=1, elem_classes="glass-panel"): | |
| gr.Markdown("### Analysis Telemetry & Metadata") | |
| # Display structured stats | |
| meta_output = gr.JSON(label="Document Stats & Metadata") | |
| gr.Markdown("### Output Result") | |
| markdown_output = gr.Markdown(value="*Results will appear here...*", elem_classes="glass-panel") | |
| # Connection | |
| run_text_btn.click( | |
| analyze_text, | |
| inputs=[text_input, nlp_op], | |
| outputs=[markdown_output, meta_output] | |
| ) | |
| # ---------------------------- | |
| # TAB 4: VISION PLAYGROUND | |
| # ---------------------------- | |
| with gr.TabItem("๐ผ๏ธ Vision Sandbox"): | |
| with gr.Row(): | |
| with gr.Column(scale=1, elem_classes="glass-panel"): | |
| gr.Markdown("### Upload Image") | |
| image_input = gr.Image(label="Source Image", type="numpy") | |
| gr.Markdown("### Filter & Adjustments") | |
| effect_sel = gr.Dropdown( | |
| choices=["None", "Grayscale", "Sepia", "Edge Detection", "Gaussian Blur", "Invert", "Pencil Sketch"], | |
| value="None", | |
| label="Artistic Effect" | |
| ) | |
| brightness_slider = gr.Slider( | |
| minimum=0.5, maximum=2.0, value=1.0, step=0.1, | |
| label="Brightness" | |
| ) | |
| contrast_slider = gr.Slider( | |
| minimum=0.5, maximum=2.0, value=1.0, step=0.1, | |
| label="Contrast" | |
| ) | |
| apply_vision_btn = gr.Button("Render Image", variant="primary", elem_classes="primary-btn") | |
| with gr.Column(scale=1, elem_classes="glass-panel"): | |
| gr.Markdown("### Visual Result") | |
| image_output = gr.Image(label="Processed Image Output") | |
| # Connect vision pipeline | |
| apply_vision_btn.click( | |
| process_image, | |
| inputs=[image_input, effect_sel, brightness_slider, contrast_slider], | |
| outputs=[image_output] | |
| ) | |
| # ---------------------------- | |
| # TAB 5: INFRASTRUCTURE MONITOR | |
| # ---------------------------- | |
| with gr.TabItem("๐ Infrastructure Monitor"): | |
| with gr.Row(): | |
| with gr.Column(scale=1, elem_classes="glass-panel"): | |
| gr.Markdown("### Telemetry Controls") | |
| traffic_slider = gr.Slider( | |
| minimum=10, maximum=500, value=120, step=10, | |
| label="Simulated Request Traffic (req/min)", | |
| info="Adjust server load frequency dynamics." | |
| ) | |
| load_slider = gr.Slider( | |
| minimum=5, maximum=100, value=25, step=5, | |
| label="Simulated Host Resource Load (%)", | |
| info="Simulate hardware pressure and compute restrictions." | |
| ) | |
| refresh_metrics_btn = gr.Button("Refresh Telemetry", variant="primary", elem_classes="primary-btn") | |
| gr.Markdown(""" | |
| ### Telemetry Summary | |
| * **Success Rate** decreases as host resource load exceeds 80%. | |
| * **Response Latency** correlates with traffic volume and processing queues. | |
| * Metrics are calculated and refreshed immediately using stochastic noise modeling. | |
| """) | |
| with gr.Column(scale=2, elem_classes="glass-panel"): | |
| gr.Markdown("### Real-Time Live Server Stats") | |
| # Metric cards output | |
| metrics_html_out = gr.HTML(value="*Load metrics to see server telemetry stats*", elem_classes="glass-panel") | |
| # Performance plot output | |
| metrics_plot_out = gr.Plot(label="Performance Graphs") | |
| # Initial loading & trigger connections | |
| demo.load(update_metrics, inputs=[traffic_slider, load_slider], outputs=[metrics_html_out, metrics_plot_out]) | |
| refresh_metrics_btn.click(update_metrics, inputs=[traffic_slider, load_slider], outputs=[metrics_html_out, metrics_plot_out]) | |
| # Launch configuration | |
| if __name__ == "__main__": | |
| demo.launch(server_name="0.0.0.0", server_port=7860) | |