Nexus-AI / app.py
FWD-ai-assistant's picture
Add Nexus AI app
67e54a7 verified
Raw History Blame Contribute Delete
25.1 kB
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("""
<div class="nexus-header">
<div class="nexus-logo">⬑ NEXUS AI</div>
<div class="nexus-tagline">Your all-in-one AI for coding Β· research Β· homework Β· creativity</div>
<div class="nexus-badges">
<span class="badge">πŸ’» Coding</span>
<span class="badge">πŸ”¬ Research</span>
<span class="badge">πŸ“š Homework</span>
<span class="badge">🎨 Image Gen</span>
<span class="badge">πŸ€– Assistant</span>
</div>
</div>
""")
# ── 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("""
<div style="padding:16px 0 8px; color:#a78bfa; font-weight:600; font-size:1.05em;">
πŸ–ΌοΈ Generate stunning AI images β€” completely free, no API key needed
</div>
""")
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("""
<div style="padding:16px 0 8px; color:#a78bfa; font-weight:600;">
⚑ Paste your code β€” get instant fixes, explanations, or optimizations
</div>
""")
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("""
<div style="max-width:720px; margin:30px auto; padding:0 20px;">
<h2 style="color:#a78bfa; font-size:1.6em; margin-bottom:8px;">⬑ About Nexus AI</h2>
<p style="color:#94a3b8; line-height:1.8;">
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.
</p>
<h3 style="color:#a78bfa; margin-top:24px;">🧠 Models Used</h3>
<table style="width:100%; border-collapse:collapse; color:#cbd5e1; font-size:0.95em;">
<tr style="border-bottom:1px solid #1e1e2e;">
<td style="padding:10px;">πŸ’¬ Chat / Research / Homework</td>
<td style="padding:10px; color:#a78bfa;">Mistral-7B-Instruct-v0.3</td>
</tr>
<tr style="border-bottom:1px solid #1e1e2e;">
<td style="padding:10px;">πŸ’» Coding</td>
<td style="padding:10px; color:#a78bfa;">Qwen2.5-Coder-7B-Instruct</td>
</tr>
<tr>
<td style="padding:10px;">🎨 Image Generation</td>
<td style="padding:10px; color:#a78bfa;">Pollinations.ai (FLUX)</td>
</tr>
</table>
<h3 style="color:#a78bfa; margin-top:24px;">βœ… Features</h3>
<ul style="color:#94a3b8; line-height:2.2;">
<li>πŸ€– Smart AI assistant for any question</li>
<li>πŸ’» Code generation, debugging & optimization</li>
<li>πŸ”¬ Deep research & detailed explanations</li>
<li>πŸ“š Step-by-step homework help</li>
<li>🎨 AI image generation (8 art styles)</li>
<li>⚑ Quick code helper with 15 languages</li>
<li>πŸ†“ 100% free β€” no API key required</li>
</ul>
<div style="margin-top:30px; padding:16px; background:rgba(124,58,237,0.1);
border:1px solid rgba(124,58,237,0.3); border-radius:12px;
color:#a78bfa; font-size:0.9em;">
Built with ❀️ using Gradio · Hugging Face · Mistral · Qwen · Pollinations
</div>
</div>
""")
# ─────────────────────────────────────────────
# LAUNCH
# ─────────────────────────────────────────────
if __name__ == "__main__":
app.launch()