File size: 7,379 Bytes
707ebec
 
 
525891a
707ebec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eda0a9c
 
 
 
 
 
 
707ebec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# ๐Ÿง  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()