Spaces:
Running on Zero
Running on Zero
Download app.py from Neura-Tech-AI/Neuron-Studio: direct link, hf CLI and curl.
- Browser
- Download file 7.38 kB
-
https://huggingface.co/spaces/Neura-Tech-AI/Neuron-Studio/resolve/main/app.py
- Command line
-
hf download hf://spaces/Neura-Tech-AI/Neuron-Studio/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Neura-Tech-AI/Neuron-Studio/resolve/main/app.py
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. | |
| 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() |