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("""
Your all-in-one AI for coding · research · homework · creativity
💻 Coding 🔬 Research 📚 Homework 🎨 Image Gen 🤖 Assistant
""") # ── TABS ──────────────────────────────── with gr.Tabs(): # ══════════════════════════════════ # TAB 1 — CHAT # ══════════════════════════════════ with gr.Tab("💬 Chat & Code"): with gr.Row(): mode_selector = gr.Radio( choices=list(SYSTEM_PROMPTS.keys()), value="🤖 Assistant", label="Select Mode", interactive=True, ) chatbot = gr.ChatInterface( fn=chat_response, additional_inputs=[mode_selector], chatbot=gr.Chatbot( height=520, render_markdown=True, show_copy_button=True, avatar_images=(None, "https://api.dicebear.com/7.x/bottts/svg?seed=nexus"), elem_classes=["chatbot"], ), textbox=gr.Textbox( placeholder="Ask me anything — coding, research, homework, or just chat...", lines=2, max_lines=6, submit_btn="Send ↑", ), examples=[[ex[0], ex[1]] for ex in CHAT_EXAMPLES], cache_examples=False, retry_btn="🔄 Retry", undo_btn="↩️ Undo", clear_btn="🗑️ Clear", ) # ══════════════════════════════════ # TAB 2 — IMAGE GENERATION # ══════════════════════════════════ with gr.Tab("🎨 Image Generation"): gr.HTML("""
🖼️ Generate stunning AI images — completely free, no API key needed
""") with gr.Row(): with gr.Column(scale=2): img_prompt = gr.Textbox( label="Image Prompt", placeholder="Describe what you want to create...", lines=3, max_lines=6, ) img_style = gr.Dropdown( choices=list(IMAGE_STYLES.keys()), value="✨ Default", label="Art Style", ) with gr.Row(): img_width = gr.Slider( minimum=256, maximum=1024, value=768, step=64, label="Width (px)" ) img_height = gr.Slider( minimum=256, maximum=1024, value=768, step=64, label="Height (px)" ) img_seed = gr.Number( label="Seed (optional — use same seed for reproducibility)", value=None, precision=0 ) img_btn = gr.Button( "✨ Generate Image", variant="primary", elem_classes=["generate-btn"], ) with gr.Column(scale=3): img_output = gr.Image( label="Generated Image", show_download_button=True, elem_classes=["image-output"], ) img_status = gr.Markdown( value="", elem_classes=["status-box"], ) gr.Examples( examples=[[e[0], e[1]] for e in IMG_EXAMPLES], inputs=[img_prompt, img_style], label="✨ Example Prompts", ) img_btn.click( fn=generate_image, inputs=[img_prompt, img_style, img_width, img_height, img_seed], outputs=[img_output, img_status], ) # ══════════════════════════════════ # TAB 3 — QUICK CODE RUNNER # ══════════════════════════════════ with gr.Tab("⚡ Quick Code Helper"): gr.HTML("""
⚡ Paste your code — get instant fixes, explanations, or optimizations
""") with gr.Row(): with gr.Column(): code_lang = gr.Dropdown( choices=["Python", "JavaScript", "TypeScript", "Java", "C++", "C#", "Rust", "Go", "PHP", "SQL", "HTML/CSS", "Bash", "R", "Swift", "Kotlin"], value="Python", label="Language", ) code_action = gr.Radio( choices=["🐛 Fix Bugs", "📖 Explain Code", "⚡ Optimize", "📝 Add Comments", "🧪 Write Tests", "🔄 Convert Language"], value="🐛 Fix Bugs", label="Action", ) code_input = gr.Code( label="Your Code", language="python", lines=15, ) convert_to = gr.Textbox( label="Convert To (only for Convert Language)", placeholder="e.g. JavaScript", visible=False, ) code_btn = gr.Button("⚡ Run", variant="primary") with gr.Column(): code_output = gr.Markdown(label="Nexus Response") # Show convert_to field only when action is convert def toggle_convert(action): return gr.update(visible=(action == "🔄 Convert Language")) code_action.change(toggle_convert, inputs=[code_action], outputs=[convert_to]) # Language map for code editor highlighting LANG_MAP = { "Python": "python", "JavaScript": "javascript", "TypeScript": "typescript", "Java": "java", "C++": "cpp", "C#": "csharp", "Rust": "rust", "Go": "go", "PHP": "php", "SQL": "sql", "HTML/CSS": "html", "Bash": "bash", "R": "r", "Swift": "swift", "Kotlin": "kotlin", } def update_code_lang(lang): return gr.update(language=LANG_MAP.get(lang, "python")) code_lang.change(update_code_lang, inputs=[code_lang], outputs=[code_input]) def run_code_helper(code, lang, action, convert_target): if not code.strip(): return "⚠️ Please paste your code first." action_prompts = { "🐛 Fix Bugs": f"Fix ALL bugs in this {lang} code. Explain each fix clearly:\n\n```{lang.lower()}\n{code}\n```", "📖 Explain Code": f"Explain this {lang} code in detail, line by line:\n\n```{lang.lower()}\n{code}\n```", "⚡ Optimize": f"Optimize this {lang} code for performance and readability:\n\n```{lang.lower()}\n{code}\n```", "📝 Add Comments": f"Add clear, helpful comments to this {lang} code:\n\n```{lang.lower()}\n{code}\n```", "🧪 Write Tests": f"Write comprehensive unit tests for this {lang} code:\n\n```{lang.lower()}\n{code}\n```", "🔄 Convert Language": f"Convert this {lang} code to {convert_target or 'JavaScript'}. Keep all logic:\n\n```{lang.lower()}\n{code}\n```", } prompt = action_prompts.get(action, action_prompts["🐛 Fix Bugs"]) messages = [ {"role": "system", "content": SYSTEM_PROMPTS["💻 Coding"]}, {"role": "user", "content": prompt}, ] response = "" try: for token in client_code.chat_completion( messages=messages, max_tokens=2000, stream=True ): response += token.choices[0].delta.content or "" return response except Exception as e: return f"❌ Error: {str(e)}" code_btn.click( fn=run_code_helper, inputs=[code_input, code_lang, code_action, convert_to], outputs=[code_output], ) # ══════════════════════════════════ # TAB 4 — ABOUT # ══════════════════════════════════ with gr.Tab("ℹ️ About"): gr.HTML("""

⬡ About Nexus AI

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.

🧠 Models Used

💬 Chat / Research / Homework Mistral-7B-Instruct-v0.3
💻 Coding Qwen2.5-Coder-7B-Instruct
🎨 Image Generation Pollinations.ai (FLUX)

✅ Features

Built with ❤️ using Gradio · Hugging Face · Mistral · Qwen · Pollinations
""") # ───────────────────────────────────────────── # LAUNCH # ───────────────────────────────────────────── if __name__ == "__main__": app.launch()