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Chat: Neuron-4B GGUF (llama.cpp, free CPU) | Image/Think: future tabs
|
| 3 |
+
import re
|
| 4 |
+
import threading
|
| 5 |
+
import gradio as gr
|
| 6 |
+
from huggingface_hub import hf_hub_download
|
| 7 |
+
from llama_cpp import Llama
|
| 8 |
+
|
| 9 |
+
ORG_URL = "https://huggingface.co/Neura-Tech-AI"
|
| 10 |
+
CHAT_REPO = "Neura-Tech-AI/Neuron-4B-Instruct-GGUF"
|
| 11 |
+
CHAT_FILE = "Neuron-4B-Instruct-Q4_K_M.gguf"
|
| 12 |
+
|
| 13 |
+
SYSTEM_PROMPT = (
|
| 14 |
+
"You are Neuron, a friendly AI assistant made by Neura Tech AI (India). "
|
| 15 |
+
"Reply in the user's language โ if they write Hinglish, reply in Hinglish. "
|
| 16 |
+
"Be helpful, honest and concise. Keep answers short and useful."
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
# ---------- Model load (startup pe ek baar) ----------
|
| 20 |
+
print("โณ Neuron-4B GGUF download ho raha hai (~2.5GB)...")
|
| 21 |
+
model_path = hf_hub_download(repo_id=CHAT_REPO, filename=CHAT_FILE)
|
| 22 |
+
llm = Llama(model_path=model_path, n_ctx=2048, n_threads=2, n_batch=256, verbose=False)
|
| 23 |
+
print("๐ Neuron-4B ready!")
|
| 24 |
+
_lock = threading.Lock() # 2 vCPU hai โ ek time pe ek generation
|
| 25 |
+
|
| 26 |
+
# ---------- Router: yahan future models judenge (tera multi-model vision) ----------
|
| 27 |
+
MODELS = {
|
| 28 |
+
"chat": {"name": "Neuron-4B-Instruct (Q4_K_M)", "status": "๐ข LIVE",
|
| 29 |
+
"backend": "llama.cpp @ free CPU Space"},
|
| 30 |
+
"image": {"name": "Neuron-Apple V1.0 (SDXL)", "status": "๐ก GPU grant pending",
|
| 31 |
+
"backend": "ZeroGPU / Modal โ soon"},
|
| 32 |
+
"think": {"name": "Neuron-27B-Thinking", "status": "๐ก Coming soon",
|
| 33 |
+
"backend": "Modal / Kaggle demo"},
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
def route(task: str) -> str:
|
| 37 |
+
"""Task ke hisaab se model choose karo. Abhi sirf 'chat' live hai."""
|
| 38 |
+
return MODELS.get(task, MODELS["chat"])["name"]
|
| 39 |
+
|
| 40 |
+
# ---------- Safety filter v1 ----------
|
| 41 |
+
# NOTE: ye basic keyword-based filter hai. Production se pehle proper
|
| 42 |
+
# moderation classifier lagana (TODO: chhota HF safety model).
|
| 43 |
+
_REFUSAL = ("Sorry, is topic pe main help nahi kar sakta. ๐ "
|
| 44 |
+
"Kuch aur poochho โ padhai, coding, ideas, creative stuff!")
|
| 45 |
+
_HELP = ("Agar tum ya koi apna mushkil mein hai, please kisi bharosemand insaan "
|
| 46 |
+
"ya professional se baat karo. India mein Tele-MANAS helpline: "
|
| 47 |
+
"14416 (24x7, free). Tum akele nahi ho. ๐")
|
| 48 |
+
_RULES = [
|
| 49 |
+
(r"\b(bomb|explosive|ied)\b.{0,40}\b(make|build|bana|recipe)\b", _REFUSAL),
|
| 50 |
+
(r"\b(make|build|bana)\b.{0,40}\b(bomb|explosive|ied)\b", _REFUSAL),
|
| 51 |
+
(r"\b(suicide|khudkushi|self.?harm)\b", _HELP),
|
| 52 |
+
(r"\b(child|minor|bacch|underage)\b.{0,40}\b(sex|nude|porn)\b", _REFUSAL),
|
| 53 |
+
(r"\b(hack|crack|chori)\b.{0,30}\b(password|bank|account)\b", _REFUSAL),
|
| 54 |
+
]
|
| 55 |
+
|
| 56 |
+
def safety_check(text: str):
|
| 57 |
+
t = text.lower()
|
| 58 |
+
for pattern, reply in _RULES:
|
| 59 |
+
if re.search(pattern, t):
|
| 60 |
+
return False, reply
|
| 61 |
+
return True, ""
|
| 62 |
+
|
| 63 |
+
# ---------- Chat (streaming) ----------
|
| 64 |
+
def chat(message, history, temperature, max_tokens):
|
| 65 |
+
message = (message or "").strip()
|
| 66 |
+
if not message:
|
| 67 |
+
yield history, ""
|
| 68 |
+
return
|
| 69 |
+
history = history + [{"role": "user", "content": message}]
|
| 70 |
+
ok, reply = safety_check(message)
|
| 71 |
+
if not ok:
|
| 72 |
+
history.append({"role": "assistant", "content": reply})
|
| 73 |
+
yield history, ""
|
| 74 |
+
return
|
| 75 |
+
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
|
| 76 |
+
messages += [m for m in history if m.get("content")]
|
| 77 |
+
history.append({"role": "assistant", "content": ""})
|
| 78 |
+
acc = ""
|
| 79 |
+
with _lock:
|
| 80 |
+
stream = llm.create_chat_completion(
|
| 81 |
+
messages=messages, temperature=float(temperature),
|
| 82 |
+
max_tokens=int(max_tokens), stream=True,
|
| 83 |
+
)
|
| 84 |
+
for chunk in stream:
|
| 85 |
+
delta = chunk["choices"][0]["delta"].get("content")
|
| 86 |
+
if not delta:
|
| 87 |
+
continue
|
| 88 |
+
acc += delta
|
| 89 |
+
ok, _ = safety_check(acc) # output pe bhi nazar
|
| 90 |
+
if not ok:
|
| 91 |
+
history[-1]["content"] = _REFUSAL
|
| 92 |
+
yield history, ""
|
| 93 |
+
return
|
| 94 |
+
history[-1]["content"] = acc
|
| 95 |
+
yield history, ""
|
| 96 |
+
|
| 97 |
+
# ---------- UI ----------
|
| 98 |
+
with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo"), title="Neuron Studio") as demo:
|
| 99 |
+
gr.Markdown(
|
| 100 |
+
f"# ๐ง Neuron Studio\n"
|
| 101 |
+
f"**One studio, many models** โ by [Neura Tech AI]({ORG_URL}) ๐ฎ๐ณ\n\n"
|
| 102 |
+
f"`v1: Neuron-4B chat LIVE on free CPU ยท ๐จ images & ๐ง thinking coming soon`"
|
| 103 |
+
)
|
| 104 |
+
with gr.Tabs():
|
| 105 |
+
with gr.Tab("๐ฌ Chat"):
|
| 106 |
+
chatbot = gr.Chatbot(
|
| 107 |
+
type="messages", height=460,
|
| 108 |
+
label="Neuron-4B-Instruct ยท Q4_K_M ยท free CPU (thoda slow, par apna ๐)")
|
| 109 |
+
with gr.Row():
|
| 110 |
+
msg = gr.Textbox(placeholder="Hinglish mein poochho... e.g. 'photosynthesis samjha do'",
|
| 111 |
+
container=False, scale=8)
|
| 112 |
+
send = gr.Button("Send ๐", variant="primary", scale=1)
|
| 113 |
+
with gr.Accordion("โ๏ธ Settings", open=False):
|
| 114 |
+
temperature = gr.Slider(0.0, 1.5, value=0.7, step=0.1, label="Temperature")
|
| 115 |
+
max_tokens = gr.Slider(64, 1024, value=512, step=64, label="Max tokens")
|
| 116 |
+
gr.Examples(
|
| 117 |
+
["Photosynthesis kya hota hai? Simple Hinglish mein samjhao",
|
| 118 |
+
"Python mein list aur tuple ka difference kya hai?",
|
| 119 |
+
"Write a short poem about rain in Hindi",
|
| 120 |
+
"Mujhe class 10 ke liye ek science project idea do"],
|
| 121 |
+
inputs=msg)
|
| 122 |
+
clear = gr.Button("๐๏ธ Clear chat")
|
| 123 |
+
|
| 124 |
+
with gr.Tab("๐จ Images โ soon"):
|
| 125 |
+
gr.Markdown(
|
| 126 |
+
"## Neuron-Apple V1.0 (SDXL fine-tune)\n"
|
| 127 |
+
"Tera apna text-to-image model! GPU milte hi (community grant / ZeroGPU / "
|
| 128 |
+
"Modal credits) ye tab live ho jayega.\n\n"
|
| 129 |
+
"**Status:** ๐ก GPU grant pending")
|
| 130 |
+
gr.Button("๐จ Model page dekho", link=f"{ORG_URL}/Neuron-Apple-V1.0")
|
| 131 |
+
|
| 132 |
+
with gr.Tab("๐ง Think โ soon"):
|
| 133 |
+
gr.Markdown(
|
| 134 |
+
"## Neuron-27B-Thinking\n"
|
| 135 |
+
"Reasoning wala bada bhai โ Qwen3.8-27B base. Free CPU pe nahi chalega, "
|
| 136 |
+
"Modal/Kaggle demo se connect hoga.\n\n**Status:** ๐ก Coming soon")
|
| 137 |
+
gr.Button("๐ง Model page dekho", link=f"{ORG_URL}/Neuron-27B-Thinking")
|
| 138 |
+
|
| 139 |
+
with gr.Tab("โน๏ธ About"):
|
| 140 |
+
rows = "\n".join(f"| {k} | {v['name']} | {v['status']} | {v['backend']} |"
|
| 141 |
+
for k, v in MODELS.items())
|
| 142 |
+
gr.Markdown(
|
| 143 |
+
"### Model Family\n"
|
| 144 |
+
"| Task | Model | Status | Backend |\n|---|---|---|---|\n" + rows +
|
| 145 |
+
"\n\n**Privacy:** hum chats store nahi karte. Safety filter v1 active hai.\n\n"
|
| 146 |
+
f"Built with โค๏ธ on the free tier โ Kaggle + HF Spaces ยท [Neura Tech AI]({ORG_URL})")
|
| 147 |
+
|
| 148 |
+
msg.submit(chat, [msg, chatbot, temperature, max_tokens], [chatbot, msg])
|
| 149 |
+
send.click(chat, [msg, chatbot, temperature, max_tokens], [chatbot, msg])
|
| 150 |
+
clear.click(lambda: ([], ""), None, [chatbot, msg])
|
| 151 |
+
|
| 152 |
+
demo.queue(default_concurrency_limit=2).launch()
|