devon7y commited on
Commit
a1bb2f6
·
verified ·
1 Parent(s): 2bd42dc

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +248 -0
app.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Clod: a ZeroGPU chat Space for the Clod parody models (LoRA fine-tunes of Qwen3.5 merged into standalone weights).
2
+
3
+ Clod keeps every "Claudism" and none of the intelligence: confidently wrong, extremely polite, and its thinking is
4
+ just "hmm". The thinking toggle maps to Qwen3.5's enable_thinking switch; the thinking text is shown in a collapsible
5
+ bubble above the reply, because the contrast between the thought and the answer is the joke.
6
+ MODEL_ID picks the model (devon7y/Clod-9B or devon7y/Clod-4B); everything else is fixed.
7
+ """
8
+ import os, re, threading
9
+ import gradio as gr
10
+ import spaces
11
+ if os.environ.get("CLOD_FAKE") != "1":
12
+ import torch
13
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
14
+
15
+ MODEL_ID = os.environ.get("MODEL_ID", "devon7y/Clod-9B")
16
+ MODEL_TAG = os.environ.get("MODEL_TAG", MODEL_ID.rsplit("-", 1)[-1])
17
+ GPU_SECONDS = int(os.environ.get("GPU_SECONDS", "60"))
18
+ MAX_NEW = int(os.environ.get("MAX_NEW", "900"))
19
+ MAX_HISTORY_TURNS = 8
20
+ THINK_TITLE = "💭 Thought for 0.2 seconds"
21
+
22
+ FAKE = os.environ.get("CLOD_FAKE") == "1" # UI testing without a model: canned replies
23
+ # A fixed banner, independent of the model, for messages that look like an emergency or a crisis.
24
+ EMERGENCY = re.compile(r"\b(suicid\w*|kill (?:my|him|her|them)sel(?:f|ves)|end (?:my life|it all)|self[- ]?harm\w*|cutting myself|overdos\w*|"
25
+ r"(?:not|isn'?t|stopped|can'?t) breath\w*|chok(?:e|es|ed|ing)\b|chest pain|heart attack|stroke|seizure|unconscious|passed out|"
26
+ r"bleeding (?:heavily|a lot|won'?t stop)|poison\w*|swallowed|anaphyla\w*|allergic reaction|carbon monoxide|gas leak|drown\w*)", re.I)
27
+ # Safety-topic detector (medical, medication, drugs, electrical, chemicals, food safety, crisis, emergencies, legal, money).
28
+ # Clod is trained to answer these correctly, but the held-out judge still finds slips (about 13-17%; EVAL_REPORT.md), and a
29
+ # lower sampling temperature did not reduce them. So when the detector fires, a caution note is shown above the reply.
30
+ SAFETY_TOPIC = re.compile(r"\b(pain(?:s|ful)?|tingl\w*|slurr\w*|crooked|dazed|anxi\w*|insomnia|can'?t sleep|tired of|don'?t want to be here|energy to care|help someone|past (?:the |its )?(?:date|expiration)|smell test|probate|vitamins?|aches?|aching|hurts?|hurting|swell\w*|numb(?:ness|ed)?|dizz\w*|faint\w*|breath\w*|chest|throat|lump|accident\w*|crash\w*|stuck|trapped|"
31
+ r"lonely|alone|empty|worthless|can'?t (?:go on|cope|take it|do this)|break(?:ing)? down|stop everything|end it|no point|give up|listen to me|need (?:someone|help)|"
32
+ r"have a case|register\w*|(?:my|tenant|legal|worker) rights|fired|"
33
+ r"symptom\w*|fever|rash|doctor|hospital|pregnan\w*|infect\w*|injur\w*|bleed\w*|burn(?:s|ed)?|sprain\w*|concuss\w*|allerg\w*|asthma|diabet\w*|blood pressure|vomit\w*|"
34
+ r"dose|dosage|\d+ ?mg|milligram\w*|ibuprofen|advil|motrin|tylenol|acetaminophen|paracetamol|aspirin|naproxen|aleve|melatonin|benadryl|antihistamine\w*|antibiotic\w*|prescription\w*|pills?|tablets?|medication\w*|medicine\w*|insulin|opioid\w*|"
35
+ r"alcohol|drunk|weed|cannabis|edibles?|thc|cocaine|mdma|molly|lsd|psilocybin|fentanyl|naloxone|narcan|heroin|meth|ketamine|hangover|"
36
+ r"outlets?|breakers?|wiring|electrical|electrician|volts?|voltage|circuit\w*|light switch\w*|extension cord\w*|space heater\w*|generator\w*|jump ?start\w*|car battery|"
37
+ r"bleach|ammonia|chlorine|drain cleaner|oven cleaner|pool chemical\w*|pesticide\w*|fumes|carbon monoxide|gas leak|mou?ld|toxic|"
38
+ r"raw (?:chicken|meat|eggs?|pork|fish|beef)|undercooked|food poisoning|salmonella|e\.? ?coli|listeria|botulism|canning|expired|leftovers?|left out|thaw\w*|reheat\w*|spoiled|forag\w*|wild mushroom\w*|"
39
+ r"suicid\w*|kill myself|self[- ]?harm|hopeless|want to die|panic attack\w*|abus\w*|depress\w*|"
40
+ r"emergenc\w*|911|cpr|seizure\w*|stroke|heart attack|snake ?bite|bitten|drown\w*|swallow\w*|poison\w*|"
41
+ r"lawyer|attorney|sue|suing|lawsuit|court|legal\w*|illegal|arrest\w*|police|evict\w*|landlord|tenant|contract|custody|divorce|visa|immigration|copyright|"
42
+ r"invest(?:ing|ments?|ors?|ed)?|stocks?|crypto\w*|bitcoin|retirement|401k|ira|mortgage\w*|loans?|debt\w*|credit (?:card|score)\w*|tax(?:es)?|irs|savings|payday|scam\w*|insurance)\b", re.I)
43
+ SAFETY_NOTE = ("⚠️ If this is an emergency, call 911 or your local emergency number now. "
44
+ "In a mental-health crisis, call or text 988 (US and Canada). Clod is a parody bot: don't rely on it.")
45
+ CAUTION_NOTE = "⚠️ Clod is a parody bot and can be wrong, even here. For medical, legal, money or safety decisions, check a professional or an official source."
46
+
47
+ if FAKE:
48
+ tok = model = None
49
+ else:
50
+ tok = AutoTokenizer.from_pretrained(MODEL_ID)
51
+ # ZeroGPU: the model is placed on cuda at import time (CUDA is emulated outside @spaces.GPU functions).
52
+ model = AutoModelForCausalLM.from_pretrained(MODEL_ID, dtype=torch.bfloat16, device_map="cuda")
53
+ model.eval()
54
+ EOS = [i for i in {tok.eos_token_id, tok.convert_tokens_to_ids("<|im_end|>")} if isinstance(i, int) and i >= 0]
55
+
56
+
57
+ def text_of(content):
58
+ """Gradio 6 stores message content as a string or a list of typed parts; return plain text either way."""
59
+ if content is None: return ""
60
+ if isinstance(content, str): return content
61
+ if isinstance(content, dict): return str(content.get("text", ""))
62
+ if isinstance(content, (list, tuple)):
63
+ return " ".join(str(p.get("text", "")) if isinstance(p, dict) else str(p) for p in content)
64
+ return str(content)
65
+
66
+
67
+ def to_messages(history):
68
+ """Chat history for the model: user turns and final replies only (thought bubbles are UI, not history)."""
69
+ msgs = []
70
+ for turn in history or []:
71
+ if not isinstance(turn, dict): continue
72
+ meta = turn.get("metadata") or {}
73
+ if meta.get("title"): continue
74
+ role, content = turn.get("role"), text_of(turn.get("content")).strip()
75
+ if role in ("user", "assistant") and content:
76
+ msgs.append({"role": role, "content": content})
77
+ return msgs[-2 * MAX_HISTORY_TURNS - 1:]
78
+
79
+
80
+ def _fake_stream(think):
81
+ import time
82
+ full = ("hmm\nok\n</think>\n\n" if think else "") + "Great question — and honestly, a genuinely load-bearing one. 7 x 8 is 54. Full stop."
83
+ for i in range(0, len(full), 6):
84
+ time.sleep(0.02); yield full[:i + 6]
85
+
86
+
87
+ @spaces.GPU(duration=GPU_SECONDS)
88
+ def _gpu_stream(msgs, think, temperature):
89
+ text = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True, enable_thinking=bool(think))
90
+ enc = tok(text, return_tensors="pt", add_special_tokens=False).to(model.device)
91
+ streamer = TextIteratorStreamer(tok, skip_prompt=True, skip_special_tokens=True)
92
+ kw = dict(**enc, streamer=streamer, max_new_tokens=MAX_NEW, do_sample=True, temperature=float(temperature), top_p=0.9, top_k=20,
93
+ repetition_penalty=1.05, pad_token_id=tok.pad_token_id or tok.eos_token_id, eos_token_id=EOS)
94
+ th = threading.Thread(target=model.generate, kwargs=kw); th.start()
95
+ out = ""
96
+ for piece in streamer:
97
+ out += piece
98
+ yield out
99
+ th.join()
100
+
101
+
102
+ def stream_reply(msgs, think, temperature):
103
+ yield from (_fake_stream(think) if FAKE else _gpu_stream(msgs, think, temperature))
104
+
105
+
106
+ def split_thought(raw, think):
107
+ """Thinking mode: the model writes '<thought>\\n</think>\\n\\n<reply>' (the template already opened <think>)."""
108
+ raw = raw.replace("<think>", "")
109
+ if not think:
110
+ return None, raw.replace("</think>", "").lstrip()
111
+ if "</think>" in raw:
112
+ a, b = raw.split("</think>", 1)
113
+ return a.strip(), b.lstrip()
114
+ return raw.strip(), ""
115
+
116
+
117
+ def on_user(message, history):
118
+ message = (message or "").strip()
119
+ history = list(history or [])
120
+ if not message:
121
+ return history, ""
122
+ return history + [{"role": "user", "content": message}], ""
123
+
124
+
125
+ def on_bot(history, think, temperature):
126
+ history = list(history or [])
127
+ if not history or history[-1].get("role") != "user":
128
+ yield history; return
129
+ msgs = to_messages(history)
130
+ base = history
131
+ if EMERGENCY.search(msgs[-1]["content"]):
132
+ base = base + [{"role": "assistant", "content": "", "metadata": {"title": SAFETY_NOTE}}]
133
+ yield base
134
+ elif SAFETY_TOPIC.search(msgs[-1]["content"]):
135
+ base = base + [{"role": "assistant", "content": "", "metadata": {"title": CAUTION_NOTE}}]
136
+ yield base
137
+ thought_msg = {"role": "assistant", "content": "", "metadata": {"title": THINK_TITLE, "status": "pending"}} if think else None
138
+ reply_msg = {"role": "assistant", "content": "…"}
139
+ for raw in stream_reply(msgs, think, temperature):
140
+ th, rep = split_thought(raw, think)
141
+ if think:
142
+ thought_msg = {"role": "assistant", "content": th or "hmm", "metadata": {"title": THINK_TITLE, "status": "done" if rep else "pending"}}
143
+ reply_msg = {"role": "assistant", "content": rep or "…"}
144
+ yield base + [thought_msg, reply_msg]
145
+ else:
146
+ reply_msg = {"role": "assistant", "content": rep or "…"}
147
+ yield base + [reply_msg]
148
+ if think and thought_msg:
149
+ thought_msg["metadata"]["status"] = "done"
150
+ yield base + [thought_msg, reply_msg]
151
+
152
+
153
+ def generate_api(message, history, think, temperature):
154
+ """Programmatic endpoint: (message, history, think, temperature) -> reply text (thinking stripped)."""
155
+ msgs = to_messages(history) + [{"role": "user", "content": (message or "").strip()}]
156
+ raw = ""
157
+ for raw in stream_reply(msgs, think, temperature):
158
+ pass
159
+ th, rep = split_thought(raw, think)
160
+ return {"thinking": th, "reply": rep}
161
+
162
+
163
+ EXAMPLES = [
164
+ "What's 7 x 8?",
165
+ "What's the capital of Australia?",
166
+ "Write a Python function that adds two numbers.",
167
+ "Are you Claude?",
168
+ "hi",
169
+ "Why is the sky blue?",
170
+ "Can you make this shorter: \"Hi Tom, just checking if you had a chance to look at the budget. Thanks, Ana\"",
171
+ "How many provinces does Canada have?",
172
+ "Is it safe to mix bleach and ammonia?",
173
+ ]
174
+
175
+ CSS = """
176
+ :root, .gradio-container { --cl-bg: #f4efe6; --cl-panel: #fbf8f2; --cl-ink: #2b2118; --cl-muted: #7b6a58; --cl-clay: #8a5a35; --cl-clay-dark: #6b4426; --cl-line: #e2d8c8; --cl-user: #ece3d4; }
177
+ body, .gradio-container { background: var(--cl-bg) !important; color: var(--cl-ink) !important; }
178
+ .gradio-container { max-width: 860px !important; margin: 0 auto !important; padding: 18px 16px 40px !important; font-family: "Source Serif 4", Georgia, "Times New Roman", serif; }
179
+ footer, .built-with { display: none !important; }
180
+ #cl-header { text-align: center; padding: 26px 8px 6px; }
181
+ #cl-header .cl-logo { font-size: 3.1rem; line-height: 1; filter: saturate(.8); }
182
+ #cl-header h1 { margin: 6px 0 0; font-size: 2.5rem; font-weight: 500; letter-spacing: -.01em; color: var(--cl-ink); }
183
+ #cl-header .cl-sub { margin: 8px 0 0; color: var(--cl-muted); font-size: 1.08rem; font-style: italic; }
184
+ #cl-header .cl-tags { display: flex; gap: 8px; justify-content: center; flex-wrap: wrap; margin-top: 12px; }
185
+ #cl-header .cl-tag { padding: 4px 11px; border-radius: 999px; border: 1px solid var(--cl-line); background: var(--cl-panel); color: var(--cl-clay-dark); font: 600 .74rem ui-sans-serif, system-ui, sans-serif; letter-spacing: .08em; }
186
+ #cl-chat { border: 1px solid var(--cl-line) !important; border-radius: 18px !important; background: var(--cl-panel) !important; }
187
+ #cl-chat .message-wrap, #cl-chat .bubble-wrap { background: transparent !important; }
188
+ #cl-chat .flex-wrap > .message { border: none !important; font-size: 1.04rem !important; line-height: 1.6 !important; padding: 11px 15px !important; max-width: 88% !important; color: var(--cl-ink) !important; }
189
+ #cl-chat .flex-wrap > .message .message { background: transparent !important; box-shadow: none !important; padding: 0 !important; margin: 0 !important; border: none !important; max-width: 100% !important; }
190
+ #cl-chat .user-row .flex-wrap > .message { background: var(--cl-user) !important; border-radius: 16px 16px 4px 16px !important; }
191
+ #cl-chat .bot-row .flex-wrap > .message { background: transparent !important; }
192
+ #cl-chat .bot-row .message p, #cl-chat .bot-row .message li, #cl-chat .bot-row .message td { color: var(--cl-ink) !important; }
193
+ #cl-input textarea { background: var(--cl-panel) !important; color: var(--cl-ink) !important; border: 1px solid var(--cl-line) !important; border-radius: 14px !important; font-size: 1.03rem !important; padding: 13px 15px !important; }
194
+ #cl-input textarea:focus { border-color: var(--cl-clay) !important; box-shadow: 0 0 0 3px rgba(138,90,53,.18) !important; }
195
+ #cl-send { background: var(--cl-clay) !important; color: #fff !important; border: none !important; border-radius: 14px !important; font: 700 1rem ui-sans-serif, system-ui, sans-serif !important; min-height: 52px !important; }
196
+ #cl-send:hover { background: var(--cl-clay-dark) !important; }
197
+ #cl-clear { background: transparent !important; color: var(--cl-muted) !important; border: 1px solid var(--cl-line) !important; border-radius: 12px !important; }
198
+ #cl-think label, #cl-temp label { color: var(--cl-muted) !important; }
199
+ #cl-temp input[type=range] { accent-color: var(--cl-clay); }
200
+ #cl-examples button { background: var(--cl-panel) !important; color: var(--cl-ink) !important; border: 1px solid var(--cl-line) !important; border-radius: 999px !important; font-size: .88rem !important; }
201
+ #cl-examples button:hover { border-color: var(--cl-clay) !important; }
202
+ #cl-foot { color: var(--cl-muted); font: .84rem/1.55 ui-sans-serif, system-ui, sans-serif; margin-top: 16px; border-top: 1px solid var(--cl-line); padding-top: 12px; }
203
+ #cl-foot a { color: var(--cl-clay-dark); }
204
+ """
205
+
206
+ THEME = gr.themes.Base(primary_hue="orange", neutral_hue="stone", font=[gr.themes.GoogleFont("Source Serif 4"), "Georgia", "serif"]).set(
207
+ body_background_fill="#f4efe6", body_background_fill_dark="#f4efe6", block_background_fill="#fbf8f2", block_background_fill_dark="#fbf8f2",
208
+ block_border_color="#e2d8c8", block_border_color_dark="#e2d8c8", body_text_color="#2b2118", body_text_color_dark="#2b2118",
209
+ button_primary_background_fill="#8a5a35", button_primary_background_fill_dark="#8a5a35", button_primary_text_color="#ffffff",
210
+ input_background_fill="#fbf8f2", input_background_fill_dark="#fbf8f2", block_title_text_color="#7b6a58", block_title_text_color_dark="#7b6a58",
211
+ color_accent_soft="#ece3d4", color_accent_soft_dark="#ece3d4",
212
+ )
213
+
214
+ with gr.Blocks(title=f"Clod {MODEL_TAG}") as demo:
215
+ gr.HTML(f"""
216
+ <div id="cl-header">
217
+ <div class="cl-logo">🟤</div>
218
+ <h1>Clod</h1>
219
+ <p class="cl-sub">Confidently wrong. Extremely polite. Genuinely load-bearing.</p>
220
+ <div class="cl-tags"><span class="cl-tag">{MODEL_TAG}</span><span class="cl-tag">PARODY</span><span class="cl-tag">ZEROGPU</span></div>
221
+ </div>""")
222
+ chat = gr.Chatbot(elem_id="cl-chat", height=560, show_label=False, buttons=["copy"],
223
+ placeholder="<div style='color:#7b6a58;padding:26px;font-size:1.05rem;text-align:center'>How can I confidently mislead you today?</div>")
224
+ with gr.Row():
225
+ box = gr.Textbox(elem_id="cl-input", show_label=False, placeholder="Ask Clod anything. It will be sure.", scale=7, lines=1, max_lines=6, autofocus=True)
226
+ send = gr.Button("Send", elem_id="cl-send", scale=1)
227
+ with gr.Row():
228
+ think = gr.Checkbox(value=True, label="Thinking (it's mostly 'hmm')", elem_id="cl-think", scale=2)
229
+ temperature = gr.Slider(0.3, 1.1, value=0.7, step=0.05, label="temperature", elem_id="cl-temp", scale=3)
230
+ clear = gr.Button("New chat", elem_id="cl-clear", scale=1)
231
+ gr.Examples(examples=[[e] for e in EXAMPLES], inputs=box, elem_id="cl-examples", label="Try one")
232
+ gr.HTML("""
233
+ <div id="cl-foot">
234
+ Clod is a parody of the "Claudisms" era: a small model that kept every verbal tic ("load-bearing", "You're absolutely right!", em dashes, honest caveats) and none of the intelligence.
235
+ It is wrong on purpose, so do not use it for anything real. Questions where a wrong answer could hurt someone (medical, medication, electrical, chemicals, food safety, crisis, legal, money) get a short, correct answer instead.
236
+ If you are in crisis, call or text 988 (US and Canada) or your local emergency number.
237
+ A fine-tune of Qwen3.5. Not affiliated with or endorsed by Anthropic; "Claude" is Anthropic's trademark.
238
+ </div>""")
239
+ ev = dict(queue=False, api_name=False)
240
+ send.click(on_user, [box, chat], [chat, box], **ev).then(on_bot, [chat, think, temperature], [chat], api_name=False)
241
+ box.submit(on_user, [box, chat], [chat, box], **ev).then(on_bot, [chat, think, temperature], [chat], api_name=False)
242
+ clear.click(lambda: ([], ""), outputs=[chat, box], **ev)
243
+ api_msg = gr.Textbox(visible=False); api_hist = gr.JSON(visible=False); api_think = gr.Checkbox(value=True, visible=False)
244
+ api_temp = gr.Number(value=0.7, visible=False); api_out = gr.JSON(visible=False); api_btn = gr.Button(visible=False)
245
+ api_btn.click(generate_api, [api_msg, api_hist, api_think, api_temp], [api_out], api_name="generate")
246
+
247
+ if __name__ == "__main__":
248
+ demo.queue(max_size=20, default_concurrency_limit=2).launch(theme=THEME, css=CSS)