File size: 25,132 Bytes
67e54a7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 | 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() |