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"""
A State-of-the-Art Interactive Developer Sandbox & System Monitor