import gradio as gr from huggingface_hub import InferenceClient import requests from urllib.parse import quote import time # ───────────────────────────────────────────── # CONFIGURATION # ───────────────────────────────────────────── TEXT_MODEL = "mistralai/Mistral-7B-Instruct-v0.3" CODE_MODEL = "Qwen/Qwen2.5-Coder-7B-Instruct" client_text = InferenceClient(TEXT_MODEL) client_code = InferenceClient(CODE_MODEL) # ───────────────────────────────────────────── # SYSTEM PROMPTS # ───────────────────────────────────────────── SYSTEM_PROMPTS = { "🤖 Assistant": ( "You are Nexus AI, a brilliant, friendly, and knowledgeable AI assistant. " "Give clear, well-structured, and helpful answers. Use bullet points and " "headings where appropriate. Be concise but thorough." ), "💻 Coding": ( "You are Nexus AI, a world-class software engineer and coding expert. " "Always write clean, production-ready, well-commented code. " "Use markdown code blocks with the correct language tag. " "Explain your reasoning before and after the code. " "Support all programming languages. Debug carefully and suggest improvements." ), "🔬 Research": ( "You are Nexus AI, an expert academic researcher and analyst. " "Give detailed, accurate, well-organized answers. Structure responses with: " "Overview, Key Concepts, Details, and Summary. " "Provide real-world examples and cite important concepts clearly. " "Be thorough, analytical, and professional." ), "📚 Homework Help": ( "You are Nexus AI, a patient, encouraging, and brilliant tutor. " "Help students understand concepts step by step. " "Never just give the answer — explain the reasoning and method clearly. " "Use simple language, real-world examples, and break complex problems " "into easy steps. Cover: Math, Science, History, English, and more." ), } IMAGE_STYLES = { "✨ Default": "", "📸 Realistic": "photorealistic, ultra detailed, 8k, DSLR photography", "🎨 Digital Art": "digital art, concept art, artstation trending, vibrant", "🌸 Anime": "anime style, manga, studio ghibli, detailed illustration", "🖼️ Oil Painting": "oil painting, classical art, painterly, museum quality", "🌆 Cyberpunk": "cyberpunk, neon lights, blade runner, futuristic city", "🧊 3D Render": "3D render, octane render, unreal engine 5, hyperrealistic", "✏️ Sketch": "pencil sketch, hand drawn, black and white illustration", } # ───────────────────────────────────────────── # CHAT FUNCTION (streaming) # ───────────────────────────────────────────── def chat_response(message, history, mode): if not message.strip(): yield "Please enter a message." return system = SYSTEM_PROMPTS.get(mode, SYSTEM_PROMPTS["🤖 Assistant"]) is_code = (mode == "💻 Coding") client = client_code if is_code else client_text messages = [{"role": "system", "content": system}] for user_msg, bot_msg in history: messages.append({"role": "user", "content": user_msg}) messages.append({"role": "assistant", "content": bot_msg}) messages.append({"role": "user", "content": message}) response = "" try: for token in client.chat_completion( messages=messages, max_tokens=1500, stream=True, temperature=0.7, ): chunk = token.choices[0].delta.content or "" response += chunk yield response except Exception as e: yield f"❌ Error: {str(e)}\n\nPlease try again or check your HF token." # ───────────────────────────────────────────── # IMAGE GENERATION # ───────────────────────────────────────────── def generate_image(prompt, style, width, height, seed): if not prompt.strip(): return None, "⚠️ Please enter an image prompt." style_suffix = IMAGE_STYLES.get(style, "") full_prompt = f"{prompt.strip()}, {style_suffix}".strip(", ") encoded = quote(full_prompt) seed_param = f"&seed={int(seed)}" if seed else "" url = ( f"https://image.pollinations.ai/prompt/{encoded}" f"?width={width}&height={height}&nologo=true{seed_param}" ) try: resp = requests.get(url, timeout=60) if resp.status_code == 200: # Save image bytes locally and return img_path = f"/tmp/nexus_img_{int(time.time())}.png" with open(img_path, "wb") as f: f.write(resp.content) return img_path, f"✅ Image generated! Prompt used: *{full_prompt}*" else: return None, f"❌ API returned status {resp.status_code}. Try again." except requests.exceptions.Timeout: return None, "❌ Request timed out. Please try a simpler prompt." except Exception as e: return None, f"❌ Error: {str(e)}" # ───────────────────────────────────────────── # CUSTOM CSS # ───────────────────────────────────────────── CSS = """ /* ── Google Font ── */ @import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=JetBrains+Mono:wght@400;600&display=swap'); /* ── Root Variables ── */ :root { --nexus-bg: #0a0a0f; --nexus-surface: #111118; --nexus-border: #1e1e2e; --nexus-accent: #7c3aed; --nexus-accent2: #06b6d4; --nexus-text: #e2e8f0; --nexus-muted: #64748b; --nexus-success: #22c55e; --nexus-glow: rgba(124, 58, 237, 0.3); } body, .gradio-container { font-family: 'Space Grotesk', sans-serif !important; background: var(--nexus-bg) !important; color: var(--nexus-text) !important; } /* ── Header ── */ .nexus-header { text-align: center; padding: 40px 20px 20px; background: linear-gradient(135deg, #0a0a0f 0%, #1a0a2e 50%, #0a0a1a 100%); border-bottom: 1px solid var(--nexus-border); margin-bottom: 10px; } .nexus-logo { font-size: 3em; font-weight: 700; background: linear-gradient(135deg, #7c3aed, #06b6d4, #7c3aed); background-size: 200%; -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; animation: gradient-shift 4s ease infinite; letter-spacing: -1px; } .nexus-tagline { color: var(--nexus-muted); font-size: 1em; margin-top: 6px; letter-spacing: 0.05em; } .nexus-badges { display: flex; justify-content: center; gap: 10px; margin-top: 12px; flex-wrap: wrap; } .badge { background: rgba(124, 58, 237, 0.15); border: 1px solid rgba(124, 58, 237, 0.4); color: #a78bfa; padding: 4px 12px; border-radius: 999px; font-size: 0.78em; font-weight: 500; } @keyframes gradient-shift { 0% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } 100% { background-position: 0% 50%; } } /* ── Tabs ── */ .tab-nav button { font-family: 'Space Grotesk', sans-serif !important; font-weight: 600 !important; font-size: 0.95em !important; border-radius: 8px !important; padding: 10px 20px !important; color: var(--nexus-muted) !important; border: 1px solid transparent !important; transition: all 0.2s ease !important; } .tab-nav button.selected { background: rgba(124, 58, 237, 0.2) !important; color: #a78bfa !important; border-color: rgba(124, 58, 237, 0.4) !important; } /* ── Chatbot ── */ .chatbot .message.bot { background: var(--nexus-surface) !important; border: 1px solid var(--nexus-border) !important; border-radius: 12px !important; font-family: 'Space Grotesk', sans-serif !important; } .chatbot .message.user { background: rgba(124, 58, 237, 0.2) !important; border: 1px solid rgba(124, 58, 237, 0.3) !important; border-radius: 12px !important; } .chatbot code, .chatbot pre { font-family: 'JetBrains Mono', monospace !important; font-size: 0.88em !important; } /* ── Inputs ── */ input, textarea, .gr-input { font-family: 'Space Grotesk', sans-serif !important; background: var(--nexus-surface) !important; border-color: var(--nexus-border) !important; color: var(--nexus-text) !important; border-radius: 10px !important; } /* ── Buttons ── */ .generate-btn { background: linear-gradient(135deg, #7c3aed, #06b6d4) !important; border: none !important; color: white !important; font-weight: 700 !important; font-size: 1em !important; padding: 14px 32px !important; border-radius: 12px !important; cursor: pointer !important; font-family: 'Space Grotesk', sans-serif !important; transition: opacity 0.2s !important; } .generate-btn:hover { opacity: 0.85 !important; } /* ── Mode selector ── */ .mode-label { color: var(--nexus-muted); font-size: 0.85em; font-weight: 600; letter-spacing: 0.08em; text-transform: uppercase; margin-bottom: 8px; } /* ── Status box ── */ .status-box { background: var(--nexus-surface) !important; border: 1px solid var(--nexus-border) !important; border-radius: 10px !important; padding: 10px 14px !important; font-size: 0.9em !important; color: var(--nexus-muted) !important; } /* ── Image output ── */ .image-output img { border-radius: 16px !important; border: 2px solid var(--nexus-border) !important; max-width: 100% !important; } """ # ───────────────────────────────────────────── # EXAMPLE PROMPTS # ───────────────────────────────────────────── CHAT_EXAMPLES = [ ["Explain quantum computing in simple terms", "🤖 Assistant"], ["Write a Python web scraper using BeautifulSoup", "💻 Coding"], ["What causes climate change? Give a research overview", "🔬 Research"], ["Help me solve: 2x + 5 = 17. Show all steps", "📚 Homework Help"], ["Build a REST API in FastAPI with JWT auth", "💻 Coding"], ["Explain the French Revolution and its causes", "🔬 Research"], ] IMG_EXAMPLES = [ ["A futuristic city at night with neon lights", "🌆 Cyberpunk"], ["A cute dragon reading a book in a library", "🌸 Anime"], ["Mountain lake at sunset, golden hour", "📸 Realistic"], ["Abstract geometric shapes floating in space", "🎨 Digital Art"], ] # ───────────────────────────────────────────── # BUILD UI # ───────────────────────────────────────────── with gr.Blocks( title="Nexus AI — All-in-One Intelligence", css=CSS, theme=gr.themes.Base( primary_hue="violet", secondary_hue="cyan", neutral_hue="slate", font=gr.themes.GoogleFont("Space Grotesk"), ), ) as app: # ── HEADER ────────────────────────────── gr.HTML("""
Nexus AI is a free, open-source, all-in-one AI platform built on Hugging Face Spaces. It combines the best open-source models to give you a powerful AI assistant for any task.
| 💬 Chat / Research / Homework | Mistral-7B-Instruct-v0.3 |
| 💻 Coding | Qwen2.5-Coder-7B-Instruct |
| 🎨 Image Generation | Pollinations.ai (FLUX) |