Neuron-Studio / app.py
Neura-Tech-AI's picture
Update app.py
eda0a9c verified
Raw History Blame Contribute Delete
7.38 kB
# ๐Ÿง  Neuron Studio v1 โ€” Neura Tech AI
# Chat: Neuron-4B GGUF (llama.cpp, free CPU) | Image/Think: future tabs
import re
import spaces
import threading
import gradio as gr
from huggingface_hub import hf_hub_download
from llama_cpp import Llama
ORG_URL = "https://huggingface.co/Neura-Tech-AI"
CHAT_REPO = "Neura-Tech-AI/Neuron-4B-Instruct-GGUF"
CHAT_FILE = "Neuron-4B-Instruct-Q4_K_M.gguf"
SYSTEM_PROMPT = (
"You are Neuron, a friendly AI assistant made by Neura Tech AI (India). "
"Reply in the user's language โ€” if they write Hinglish, reply in Hinglish. "
"Be helpful, honest and concise. Keep answers short and useful."
)
# ---------- Model load (startup pe ek baar) ----------
print("โณ Neuron-4B GGUF download ho raha hai (~2.5GB)...")
model_path = hf_hub_download(repo_id=CHAT_REPO, filename=CHAT_FILE)
llm = Llama(model_path=model_path, n_ctx=2048, n_threads=2, n_batch=256, verbose=False)
print("๐Ÿš€ Neuron-4B ready!")
_lock = threading.Lock() # 2 vCPU hai โ€” ek time pe ek generation
# ---------- Router: yahan future models judenge (tera multi-model vision) ----------
MODELS = {
"chat": {"name": "Neuron-4B-Instruct (Q4_K_M)", "status": "๐ŸŸข LIVE",
"backend": "llama.cpp @ free CPU Space"},
"image": {"name": "Neuron-Apple V1.0 (SDXL)", "status": "๐ŸŸก GPU grant pending",
"backend": "ZeroGPU / Modal โ€” soon"},
"think": {"name": "Neuron-27B-Thinking", "status": "๐ŸŸก Coming soon",
"backend": "Modal / Kaggle demo"},
}
def route(task: str) -> str:
"""Task ke hisaab se model choose karo. Abhi sirf 'chat' live hai."""
return MODELS.get(task, MODELS["chat"])["name"]
# ---------- ZeroGPU rule: >=1 @spaces.GPU function zaroori ----------
# Chat CPU pe hi chalega (GPU quota NAHI katega). Ye function future
# Neuron-Apple image tab ke liye registered hai โ€” abhi sirf stub.
@spaces.GPU(duration=30)
def neuron_apple_generate(prompt: str):
raise gr.Error("๐ŸŽจ Neuron-Apple abhi connect nahi hua โ€” coming soon!")
# ---------- Safety filter v1 ----------
# NOTE: ye basic keyword-based filter hai. Production se pehle proper
# moderation classifier lagana (TODO: chhota HF safety model).
_REFUSAL = ("Sorry, is topic pe main help nahi kar sakta. ๐Ÿ™ "
"Kuch aur poochho โ€” padhai, coding, ideas, creative stuff!")
_HELP = ("Agar tum ya koi apna mushkil mein hai, please kisi bharosemand insaan "
"ya professional se baat karo. India mein Tele-MANAS helpline: "
"14416 (24x7, free). Tum akele nahi ho. ๐Ÿ’™")
_RULES = [
(r"\b(bomb|explosive|ied)\b.{0,40}\b(make|build|bana|recipe)\b", _REFUSAL),
(r"\b(make|build|bana)\b.{0,40}\b(bomb|explosive|ied)\b", _REFUSAL),
(r"\b(suicide|khudkushi|self.?harm)\b", _HELP),
(r"\b(child|minor|bacch|underage)\b.{0,40}\b(sex|nude|porn)\b", _REFUSAL),
(r"\b(hack|crack|chori)\b.{0,30}\b(password|bank|account)\b", _REFUSAL),
]
def safety_check(text: str):
t = text.lower()
for pattern, reply in _RULES:
if re.search(pattern, t):
return False, reply
return True, ""
# ---------- Chat (streaming) ----------
def chat(message, history, temperature, max_tokens):
message = (message or "").strip()
if not message:
yield history, ""
return
history = history + [{"role": "user", "content": message}]
ok, reply = safety_check(message)
if not ok:
history.append({"role": "assistant", "content": reply})
yield history, ""
return
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
messages += [m for m in history if m.get("content")]
history.append({"role": "assistant", "content": ""})
acc = ""
with _lock:
stream = llm.create_chat_completion(
messages=messages, temperature=float(temperature),
max_tokens=int(max_tokens), stream=True,
)
for chunk in stream:
delta = chunk["choices"][0]["delta"].get("content")
if not delta:
continue
acc += delta
ok, _ = safety_check(acc) # output pe bhi nazar
if not ok:
history[-1]["content"] = _REFUSAL
yield history, ""
return
history[-1]["content"] = acc
yield history, ""
# ---------- UI ----------
with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo"), title="Neuron Studio") as demo:
gr.Markdown(
f"# ๐Ÿง  Neuron Studio\n"
f"**One studio, many models** โ€” by [Neura Tech AI]({ORG_URL}) ๐Ÿ‡ฎ๐Ÿ‡ณ\n\n"
f"`v1: Neuron-4B chat LIVE on free CPU ยท ๐ŸŽจ images & ๐Ÿง  thinking coming soon`"
)
with gr.Tabs():
with gr.Tab("๐Ÿ’ฌ Chat"):
chatbot = gr.Chatbot(
type="messages", height=460,
label="Neuron-4B-Instruct ยท Q4_K_M ยท free CPU (thoda slow, par apna ๐Ÿ˜Ž)")
with gr.Row():
msg = gr.Textbox(placeholder="Hinglish mein poochho... e.g. 'photosynthesis samjha do'",
container=False, scale=8)
send = gr.Button("Send ๐Ÿš€", variant="primary", scale=1)
with gr.Accordion("โš™๏ธ Settings", open=False):
temperature = gr.Slider(0.0, 1.5, value=0.7, step=0.1, label="Temperature")
max_tokens = gr.Slider(64, 1024, value=512, step=64, label="Max tokens")
gr.Examples(
["Photosynthesis kya hota hai? Simple Hinglish mein samjhao",
"Python mein list aur tuple ka difference kya hai?",
"Write a short poem about rain in Hindi",
"Mujhe class 10 ke liye ek science project idea do"],
inputs=msg)
clear = gr.Button("๐Ÿ—‘๏ธ Clear chat")
with gr.Tab("๐ŸŽจ Images โ€” soon"):
gr.Markdown(
"## Neuron-Apple V1.0 (SDXL fine-tune)\n"
"Tera apna text-to-image model! GPU milte hi (community grant / ZeroGPU / "
"Modal credits) ye tab live ho jayega.\n\n"
"**Status:** ๐ŸŸก GPU grant pending")
gr.Button("๐ŸŽจ Model page dekho", link=f"{ORG_URL}/Neuron-Apple-V1.0")
with gr.Tab("๐Ÿง  Think โ€” soon"):
gr.Markdown(
"## Neuron-27B-Thinking\n"
"Reasoning wala bada bhai โ€” Qwen3.8-27B base. Free CPU pe nahi chalega, "
"Modal/Kaggle demo se connect hoga.\n\n**Status:** ๐ŸŸก Coming soon")
gr.Button("๐Ÿง  Model page dekho", link=f"{ORG_URL}/Neuron-27B-Thinking")
with gr.Tab("โ„น๏ธ About"):
rows = "\n".join(f"| {k} | {v['name']} | {v['status']} | {v['backend']} |"
for k, v in MODELS.items())
gr.Markdown(
"### Model Family\n"
"| Task | Model | Status | Backend |\n|---|---|---|---|\n" + rows +
"\n\n**Privacy:** hum chats store nahi karte. Safety filter v1 active hai.\n\n"
f"Built with โค๏ธ on the free tier โ€” Kaggle + HF Spaces ยท [Neura Tech AI]({ORG_URL})")
msg.submit(chat, [msg, chatbot, temperature, max_tokens], [chatbot, msg])
send.click(chat, [msg, chatbot, temperature, max_tokens], [chatbot, msg])
clear.click(lambda: ([], ""), None, [chatbot, msg])
demo.queue(default_concurrency_limit=2).launch()