Hfzune commited on
Commit
b336753
·
verified ·
1 Parent(s): e5b64c7

Upload 3 files

Browse files
Files changed (2) hide show
  1. README.md +46 -43
  2. app.py +377 -143
README.md CHANGED
@@ -1,65 +1,68 @@
1
  ---
2
- title: Qwen Telegram Bot
3
  emoji: 🤖
4
  colorFrom: blue
5
  colorTo: purple
6
  sdk: gradio
7
- sdk_version: 5.23.1
8
  app_file: app.py
9
  pinned: false
10
  ---
11
 
12
- # Qwen Telegram Bot (Hugging Face ZeroGPU)
13
 
14
- A small Qwen3 model served in a Gradio Space with a Telegram webhook.
 
15
 
16
- ## 1. Upload files
 
17
 
18
- Upload `app.py`, `requirements.txt`, and this `README.md` to your Hugging Face Space.
 
 
 
19
 
20
- Choose **Gradio** as the Space SDK and enable ZeroGPU if your account/Space has access to it.
 
 
 
 
21
 
22
- ## 2. Add Space secrets
23
 
24
- In **Settings → Variables and secrets**, add:
25
-
26
- - `TELEGRAM_BOT_TOKEN`: your token from Telegram's BotFather. Keep it secret.
27
- - `TELEGRAM_WEBHOOK_SECRET`: a private string containing only letters, numbers, underscores, or hyphens (recommended).
28
- - Optional `MODEL_ID`: defaults to `Qwen/Qwen3-0.6B`.
29
- - Optional `HF_TOKEN`: a Hugging Face access token can improve download rate limits for gated/private repositories; it is not normally needed for Qwen3-0.6B.
30
-
31
- Do not put tokens in public source files.
32
-
33
- ## 3. Wait for the Space to start
34
-
35
- Open `https://YOUR_SPACE_HOST/health` in a browser. It should return JSON with `"ok": true`.
36
-
37
- The app loads model weights on CPU at startup and requests ZeroGPU only for generation. If startup fails, open the Space logs and fix the first traceback before configuring Telegram.
38
-
39
- ## 4. Set the Telegram webhook
40
-
41
- Replace the placeholders and open this URL privately in your browser (never share the completed URL because it contains your bot token):
42
 
43
  `https://api.telegram.org/botYOUR_BOT_TOKEN/setWebhook?url=https://YOUR_SPACE_HOST/webhook&secret_token=YOUR_WEBHOOK_SECRET`
44
 
45
- `YOUR_SPACE_HOST` is the hostname shown on the Space, for example `username-space-name.hf.space`, without `https://` or a trailing slash.
46
-
47
- Telegram should return `{"ok":true,"result":true,...}`.
48
 
49
- Check status using:
50
 
51
  `https://api.telegram.org/botYOUR_BOT_TOKEN/getWebhookInfo`
52
 
53
- The `url` field should end in `/webhook`.
54
-
55
- ## 5. Test
56
-
57
- Send `/start` to the bot, then ask a short question. Use `/reset` to clear the in-memory chat history.
58
-
59
- ## Notes
60
-
61
- - This is a minimal example, not a production bot. Chat history and deduplication are in memory and reset when the Space restarts.
62
- - ZeroGPU quotas and execution duration depend on Hugging Face's current policies and the Space's eligibility.
63
- - A 0.6B model is small and can make mistakes. Increasing the model size requires more memory and compute.
64
- - If you change `MODEL_ID`, confirm that the repository is a compatible Transformers model with tokenizer files.
65
- - If the app shows an error, share the relevant logs after removing tokens and other secrets.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Qwen Telegram Bot Pro
3
  emoji: 🤖
4
  colorFrom: blue
5
  colorTo: purple
6
  sdk: gradio
 
7
  app_file: app.py
8
  pinned: false
9
  ---
10
 
11
+ # Qwen Telegram Bot Pro
12
 
13
+ ## Files
14
+ Upload `app.py`, `requirements.txt`, and this `README.md` to your Gradio Hugging Face Space.
15
 
16
+ ## Required Space secrets
17
+ Go to **Settings → Variables and secrets** and add:
18
 
19
+ - `TELEGRAM_BOT_TOKEN`: token from Telegram BotFather.
20
+ - `TELEGRAM_WEBHOOK_SECRET`: a private string containing letters, numbers, underscores, or hyphens.
21
+ - `ADMIN_PASSWORD`: strong unique password for the admin dashboard.
22
+ - `ADMIN_USERNAME`: optional; defaults to `admin`.
23
 
24
+ Optional:
25
+ - `MODEL_ID`: defaults to `Qwen/Qwen3-0.6B`.
26
+ - `SYSTEM_PROMPT`: custom assistant instructions.
27
+ - `MAX_NEW_TOKENS`: defaults to 350.
28
+ - `GPU_DURATION_SECONDS`: defaults to 60; must comply with your current ZeroGPU allowance/policy.
29
 
30
+ Do not put tokens/passwords in `app.py` or public files.
31
 
32
+ ## Configure Telegram webhook
33
+ Wait until the Space has started. Use this URL privately in your browser, replacing placeholders:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
  `https://api.telegram.org/botYOUR_BOT_TOKEN/setWebhook?url=https://YOUR_SPACE_HOST/webhook&secret_token=YOUR_WEBHOOK_SECRET`
36
 
37
+ `YOUR_SPACE_HOST` is the hostname only, such as `account-space-name.hf.space`, without scheme or trailing slash. Never share the completed URL because it contains your bot token.
 
 
38
 
39
+ Then check:
40
 
41
  `https://api.telegram.org/botYOUR_BOT_TOKEN/getWebhookInfo`
42
 
43
+ The returned `url` must end with `/webhook`.
44
+
45
+ ## Endpoints
46
+ - `/health` — basic health/status information.
47
+ - `/admin` — admin dashboard (HTTP Basic authentication).
48
+ - `/admin/logs` — searchable table of recent conversations.
49
+ - `/admin/export.csv` — download all logs as CSV.
50
+ - `/admin/export.json` — download all logs as JSON.
51
+
52
+ Use `ADMIN_USERNAME` and `ADMIN_PASSWORD` when the browser prompts for credentials.
53
+
54
+ ## What it does
55
+ - Sends a typing indicator before model generation.
56
+ - Converts a conservative Markdown subset to Telegram HTML.
57
+ - Splits long answers into multiple Telegram messages.
58
+ - Removes common leaked placeholder/control tokens such as `##IMAGE##`.
59
+ - Stores incoming user messages, model replies, timestamps, status, and errors in SQLite.
60
+ - Provides authenticated log search and CSV/JSON exports.
61
+
62
+ ## Important limitations and privacy
63
+ - This is a starter project, not a hardened production service. Do not expose the dashboard without a strong password. Conversation logs may contain private information.
64
+ - SQLite path defaults to `/data/chat_logs.sqlite3` when `/data` exists, otherwise `/tmp/chat_logs.sqlite3`. `/tmp` storage may be lost when the Space restarts; use persistent storage if your plan supports it.
65
+ - In-memory chat history and webhook deduplication reset when the Space restarts.
66
+ - This example keeps model weights on CPU between requests and moves them to GPU during a ZeroGPU generation call. ZeroGPU runtime behavior can change; check logs if generation fails.
67
+ - Qwen3-0.6B is small and may still give weak answers. A larger model requires more memory and compute.
68
+ - The model can generate inaccurate or inappropriate output. Review logs responsibly and tell users if their messages are being stored.
app.py CHANGED
@@ -1,12 +1,21 @@
1
  import os
 
 
 
 
 
 
2
  import asyncio
3
  import logging
4
  import queue
 
 
5
  import threading
 
 
6
  from collections import deque
7
 
8
  # Compatibility shim for older Gradio OAuth integrations with newer huggingface_hub.
9
- # Keep this before importing Gradio.
10
  try:
11
  import huggingface_hub
12
  if not hasattr(huggingface_hub, "HfFolder"):
@@ -14,15 +23,12 @@ try:
14
  @staticmethod
15
  def get_token():
16
  return huggingface_hub.get_token()
17
-
18
  @staticmethod
19
  def save_token(token):
20
  huggingface_hub.login(token=token)
21
-
22
  @staticmethod
23
  def delete_token():
24
  huggingface_hub.logout()
25
-
26
  huggingface_hub.HfFolder = _HfFolder
27
  except Exception:
28
  pass
@@ -33,69 +39,104 @@ import spaces
33
  import torch
34
  from transformers import AutoModelForCausalLM, AutoTokenizer
35
  from starlette.requests import Request
36
- from starlette.responses import JSONResponse
 
37
 
38
  logging.basicConfig(level=os.getenv("LOG_LEVEL", "INFO"))
39
- log = logging.getLogger("telegram-qwen")
40
 
41
  MODEL_ID = os.getenv("MODEL_ID", "Qwen/Qwen3-0.6B")
42
- TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "").strip()
43
- TELEGRAM_WEBHOOK_SECRET = os.getenv("TELEGRAM_WEBHOOK_SECRET", "").strip()
 
 
44
  SYSTEM_PROMPT = os.getenv(
45
  "SYSTEM_PROMPT",
46
- "You are a helpful, friendly assistant. Answer clearly and directly. "
47
- "If you do not know something, say so. Keep replies concise unless asked for detail."
 
48
  )
49
- MAX_NEW_TOKENS = int(os.getenv("MAX_NEW_TOKENS", "180"))
50
  MAX_HISTORY_MESSAGES = int(os.getenv("MAX_HISTORY_MESSAGES", "8"))
51
  GPU_DURATION_SECONDS = int(os.getenv("GPU_DURATION_SECONDS", "60"))
52
  MAX_INPUT_CHARS = int(os.getenv("MAX_INPUT_CHARS", "4000"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
- if not TELEGRAM_BOT_TOKEN:
55
- log.warning("TELEGRAM_BOT_TOKEN is missing. Telegram sending will not work.")
 
 
 
 
 
 
 
 
 
 
56
 
57
- # Load weights on CPU at startup. ZeroGPU grants GPU access only inside @spaces.GPU functions.
58
- log.info("Loading tokenizer for %s", MODEL_ID)
59
  tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
60
- log.info("Loading model weights for %s on CPU", MODEL_ID)
61
  model = AutoModelForCausalLM.from_pretrained(
62
  MODEL_ID,
63
  torch_dtype=torch.float32,
64
  low_cpu_mem_usage=True,
65
  )
66
  model.eval()
67
- log.info("Model loaded on CPU.")
68
-
69
- # Small in-memory chat history and update deduplication. These reset when the Space restarts.
70
- chat_histories = {}
71
- seen_updates = deque(maxlen=2000)
72
- seen_update_ids = set()
73
- update_queue = queue.Queue(maxsize=100)
74
-
75
 
76
  @spaces.GPU(duration=GPU_DURATION_SECONDS)
77
  def generate_reply(messages):
78
- """Run generation only while ZeroGPU has allocated a GPU."""
79
  model.to("cuda")
80
  try:
81
- # Qwen3 supports enable_thinking=False through its chat template.
82
  try:
83
  prompt = tokenizer.apply_chat_template(
84
- messages,
85
- tokenize=False,
86
- add_generation_prompt=True,
87
- enable_thinking=False,
88
  )
89
  except TypeError:
90
  prompt = tokenizer.apply_chat_template(
91
- messages,
92
- tokenize=False,
93
- add_generation_prompt=True,
94
  )
95
-
96
  inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=4096)
97
- inputs = {key: value.to("cuda") for key, value in inputs.items()}
98
-
99
  with torch.inference_mode():
100
  output = model.generate(
101
  **inputs,
@@ -107,164 +148,357 @@ def generate_reply(messages):
107
  pad_token_id=tokenizer.eos_token_id,
108
  eos_token_id=tokenizer.eos_token_id,
109
  )
110
-
111
  new_tokens = output[0][inputs["input_ids"].shape[1]:]
112
- answer = tokenizer.decode(new_tokens, skip_special_tokens=True).strip()
113
- return answer or "I couldn't generate a reply. Please try asking another way."
114
  finally:
115
  model.to("cpu")
116
  if torch.cuda.is_available():
117
  torch.cuda.empty_cache()
118
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
 
120
  async def telegram_api(method, payload):
121
- if not TELEGRAM_BOT_TOKEN:
122
  raise RuntimeError("TELEGRAM_BOT_TOKEN is not configured")
123
- url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/{method}"
124
  async with httpx.AsyncClient(timeout=25.0) as client:
125
- response = await client.post(url, json=payload)
126
  response.raise_for_status()
127
  data = response.json()
128
  if not data.get("ok"):
129
- raise RuntimeError(f"Telegram API returned ok=false for {method}")
130
  return data
131
 
132
-
133
- async def send_message(chat_id, text):
134
- # Telegram message limit is 4096 characters. Keep a safety margin.
135
- text = (text or "Sorry, I couldn't create a reply.")[:4000]
136
- await telegram_api("sendMessage", {"chat_id": chat_id, "text": text})
137
-
138
-
139
- def remember_update(update_id):
140
- if update_id in seen_update_ids:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  return False
142
- if len(seen_updates) == seen_updates.maxlen and seen_updates:
143
- oldest = seen_updates[0]
144
- seen_update_ids.discard(oldest)
145
- seen_updates.append(update_id)
146
- seen_update_ids.add(update_id)
147
- return True
148
-
149
-
150
- async def process_update(update):
151
  message = update.get("message") or update.get("edited_message")
152
  if not message:
153
  return
154
-
155
  chat = message.get("chat") or {}
 
156
  chat_id = chat.get("id")
157
- text = (message.get("text") or "").strip()
158
- if not chat_id or not text:
159
  return
160
-
161
- if text.startswith("/start"):
162
- await send_message(
163
- chat_id,
164
- "Hi! I'm your Qwen assistant. Send me a question to chat. "
165
- "Use /reset to clear this chat's conversation history.",
166
- )
 
167
  return
168
-
169
- if text.startswith("/reset"):
170
- chat_histories.pop(chat_id, None)
171
- await send_message(chat_id, "Conversation history cleared.")
 
172
  return
173
-
174
- if text.startswith("/"):
175
- await send_message(chat_id, "Available commands: /start and /reset")
 
176
  return
177
 
178
- text = text[:MAX_INPUT_CHARS]
179
- history = chat_histories.setdefault(chat_id, [])
180
- messages = [{"role": "system", "content": SYSTEM_PROMPT}]
181
- messages.extend(history[-MAX_HISTORY_MESSAGES:])
182
- messages.append({"role": "user", "content": text})
183
-
184
  try:
185
- # Calling the decorated function from a worker thread keeps the webhook responsive.
 
 
 
186
  answer = await asyncio.to_thread(generate_reply, messages)
 
187
  if not answer:
188
- answer = "Sorry, I couldn't generate a reply. Please try again."
189
  history.extend([
190
- {"role": "user", "content": text},
191
  {"role": "assistant", "content": answer},
192
  ])
193
- chat_histories[chat_id] = history[-MAX_HISTORY_MESSAGES * 2:]
194
- await send_message(chat_id, answer)
195
- except Exception:
196
- log.exception("Failed to generate/send reply for chat %s", chat_id)
 
 
 
197
  try:
198
- await send_message(
199
- chat_id,
200
- "Sorry, I'm having a temporary model/hosting problem. Please try again in a little while.",
201
- )
202
  except Exception:
203
- log.exception("Could not send error message to Telegram")
204
-
205
 
206
- async def queue_worker():
207
  while True:
208
- update = await asyncio.to_thread(update_queue.get)
209
  try:
210
- await process_update(update)
211
  except Exception:
212
- log.exception("Unexpected update processing error")
213
  finally:
214
- update_queue.task_done()
215
 
 
 
 
216
 
217
  async def webhook(request: Request):
218
- if TELEGRAM_WEBHOOK_SECRET:
219
- received_secret = request.headers.get("X-Telegram-Bot-Api-Secret-Token", "")
220
- if received_secret != TELEGRAM_WEBHOOK_SECRET:
221
  return JSONResponse({"ok": False, "error": "invalid secret"}, status_code=403)
222
-
223
  try:
224
  update = await request.json()
225
  except Exception:
226
  return JSONResponse({"ok": False, "error": "invalid JSON"}, status_code=400)
227
-
228
  update_id = update.get("update_id")
229
- if update_id is not None and not remember_update(update_id):
230
  return JSONResponse({"ok": True, "duplicate": True})
231
-
232
  try:
233
- update_queue.put_nowait(update)
234
  except queue.Full:
235
- log.error("Update queue full; Telegram update %s was not queued", update_id)
236
- # Non-200 makes Telegram retry delivery.
237
  return JSONResponse({"ok": False, "error": "queue full"}, status_code=503)
238
-
239
  return JSONResponse({"ok": True})
240
 
241
-
242
  async def health(request: Request):
243
  return JSONResponse({
244
  "ok": True,
245
  "model": MODEL_ID,
246
- "telegram_token_configured": bool(TELEGRAM_BOT_TOKEN),
247
- "webhook_secret_configured": bool(TELEGRAM_WEBHOOK_SECRET),
248
  "model_loaded": model is not None,
 
 
 
 
249
  })
250
 
251
-
252
- def ui_generate(message, history):
253
- history = history or []
254
- messages = [{"role": "system", "content": SYSTEM_PROMPT}]
255
- for item in history[-MAX_HISTORY_MESSAGES:]:
256
- if isinstance(item, dict) and item.get("role") in ("user", "assistant"):
257
- messages.append({"role": item["role"], "content": str(item.get("content", ""))})
258
- elif isinstance(item, (tuple, list)) and len(item) == 2:
259
- messages.append({"role": "user", "content": str(item[0])})
260
- messages.append({"role": "assistant", "content": str(item[1])})
261
- messages.append({"role": "user", "content": message})
262
- return asyncio.run(asyncio.to_thread(generate_reply, messages))
263
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
264
 
265
  with gr.Blocks(title="Qwen Telegram Bot") as demo:
266
- gr.Markdown("# Qwen Telegram Bot\nUse this page to test the model. Telegram uses the same model.")
267
- chat = gr.ChatInterface(fn=ui_generate, type="tuples")
 
 
 
 
 
 
 
 
 
 
 
268
 
269
  demo.queue(default_concurrency_limit=1)
270
  demo.launch(
@@ -275,17 +509,17 @@ demo.launch(
275
  prevent_thread_lock=True,
276
  )
277
 
278
- # Attach routes before serving requests. Gradio's Starlette app is the public ASGI app.
279
- from starlette.routing import Route
280
- demo.app.router.routes.insert(0, Route("/health", health, methods=["GET"]))
281
- demo.app.router.routes.insert(0, Route("/webhook", webhook, methods=["POST"]))
282
-
283
- def worker_thread():
284
- asyncio.run(queue_worker())
285
-
286
- threading.Thread(target=worker_thread, daemon=True, name="telegram-worker").start()
287
-
288
- # Keep the main process alive for Hugging Face Spaces.
289
- import time
290
  while True:
291
  time.sleep(3600)
 
1
  import os
2
+ import re
3
+ import io
4
+ import csv
5
+ import json
6
+ import time
7
+ import html
8
  import asyncio
9
  import logging
10
  import queue
11
+ import secrets
12
+ import sqlite3
13
  import threading
14
+ from datetime import datetime, timezone
15
+ from functools import wraps
16
  from collections import deque
17
 
18
  # Compatibility shim for older Gradio OAuth integrations with newer huggingface_hub.
 
19
  try:
20
  import huggingface_hub
21
  if not hasattr(huggingface_hub, "HfFolder"):
 
23
  @staticmethod
24
  def get_token():
25
  return huggingface_hub.get_token()
 
26
  @staticmethod
27
  def save_token(token):
28
  huggingface_hub.login(token=token)
 
29
  @staticmethod
30
  def delete_token():
31
  huggingface_hub.logout()
 
32
  huggingface_hub.HfFolder = _HfFolder
33
  except Exception:
34
  pass
 
39
  import torch
40
  from transformers import AutoModelForCausalLM, AutoTokenizer
41
  from starlette.requests import Request
42
+ from starlette.responses import JSONResponse, HTMLResponse, PlainTextResponse, Response
43
+ from starlette.routing import Route
44
 
45
  logging.basicConfig(level=os.getenv("LOG_LEVEL", "INFO"))
46
+ log = logging.getLogger("qwen-telegram")
47
 
48
  MODEL_ID = os.getenv("MODEL_ID", "Qwen/Qwen3-0.6B")
49
+ BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "").strip()
50
+ WEBHOOK_SECRET = os.getenv("TELEGRAM_WEBHOOK_SECRET", "").strip()
51
+ ADMIN_USERNAME = os.getenv("ADMIN_USERNAME", "admin")
52
+ ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "").strip()
53
  SYSTEM_PROMPT = os.getenv(
54
  "SYSTEM_PROMPT",
55
+ "You are a helpful, friendly assistant. Answer the user's actual question directly. "
56
+ "Use clear headings and bullet points when useful. Do not output internal tokens, "
57
+ "image placeholders, or unfinished text. If uncertain, say so."
58
  )
59
+ MAX_NEW_TOKENS = int(os.getenv("MAX_NEW_TOKENS", "350"))
60
  MAX_HISTORY_MESSAGES = int(os.getenv("MAX_HISTORY_MESSAGES", "8"))
61
  GPU_DURATION_SECONDS = int(os.getenv("GPU_DURATION_SECONDS", "60"))
62
  MAX_INPUT_CHARS = int(os.getenv("MAX_INPUT_CHARS", "4000"))
63
+ DB_PATH = os.getenv("CHAT_DB_PATH", "/data/chat_logs.sqlite3")
64
+ if not os.path.isdir(os.path.dirname(DB_PATH) or "."):
65
+ DB_PATH = "/tmp/chat_logs.sqlite3"
66
+
67
+ if not BOT_TOKEN:
68
+ log.warning("TELEGRAM_BOT_TOKEN is missing.")
69
+ if not ADMIN_PASSWORD:
70
+ log.warning("ADMIN_PASSWORD is missing. Admin dashboard will refuse access.")
71
+
72
+ def utc_now():
73
+ return datetime.now(timezone.utc).isoformat(timespec="seconds")
74
+
75
+ def db_connect():
76
+ conn = sqlite3.connect(DB_PATH, timeout=20)
77
+ conn.row_factory = sqlite3.Row
78
+ return conn
79
+
80
+ def init_db():
81
+ with db_connect() as conn:
82
+ conn.execute("""
83
+ CREATE TABLE IF NOT EXISTS messages (
84
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
85
+ created_at TEXT NOT NULL,
86
+ update_id INTEGER,
87
+ chat_id TEXT,
88
+ user_id TEXT,
89
+ username TEXT,
90
+ display_name TEXT,
91
+ user_text TEXT NOT NULL,
92
+ model_reply TEXT NOT NULL,
93
+ status TEXT NOT NULL DEFAULT 'ok',
94
+ error TEXT
95
+ )
96
+ """)
97
+ conn.execute("CREATE INDEX IF NOT EXISTS idx_messages_created_at ON messages(created_at)")
98
+ conn.execute("CREATE INDEX IF NOT EXISTS idx_messages_chat_id ON messages(chat_id)")
99
+ init_db()
100
 
101
+ def save_log(update_id, chat_id, user_id, username, display_name, user_text, reply, status="ok", error=None):
102
+ try:
103
+ with db_connect() as conn:
104
+ conn.execute(
105
+ """INSERT INTO messages
106
+ (created_at, update_id, chat_id, user_id, username, display_name, user_text, model_reply, status, error)
107
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
108
+ (utc_now(), update_id, str(chat_id or ""), str(user_id or ""), username or "",
109
+ display_name or "", user_text or "", reply or "", status, error or "")
110
+ )
111
+ except Exception:
112
+ log.exception("Could not write conversation log")
113
 
114
+ log.info("Loading tokenizer: %s", MODEL_ID)
 
115
  tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
116
+ log.info("Loading model weights on CPU: %s", MODEL_ID)
117
  model = AutoModelForCausalLM.from_pretrained(
118
  MODEL_ID,
119
  torch_dtype=torch.float32,
120
  low_cpu_mem_usage=True,
121
  )
122
  model.eval()
123
+ log.info("Model loaded.")
 
 
 
 
 
 
 
124
 
125
  @spaces.GPU(duration=GPU_DURATION_SECONDS)
126
  def generate_reply(messages):
127
+ # ZeroGPU allocates the GPU for this decorated call.
128
  model.to("cuda")
129
  try:
 
130
  try:
131
  prompt = tokenizer.apply_chat_template(
132
+ messages, tokenize=False, add_generation_prompt=True, enable_thinking=False
 
 
 
133
  )
134
  except TypeError:
135
  prompt = tokenizer.apply_chat_template(
136
+ messages, tokenize=False, add_generation_prompt=True
 
 
137
  )
 
138
  inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=4096)
139
+ inputs = {k: v.to("cuda") for k, v in inputs.items()}
 
140
  with torch.inference_mode():
141
  output = model.generate(
142
  **inputs,
 
148
  pad_token_id=tokenizer.eos_token_id,
149
  eos_token_id=tokenizer.eos_token_id,
150
  )
 
151
  new_tokens = output[0][inputs["input_ids"].shape[1]:]
152
+ result = tokenizer.decode(new_tokens, skip_special_tokens=True).strip()
153
+ return clean_model_text(result)
154
  finally:
155
  model.to("cpu")
156
  if torch.cuda.is_available():
157
  torch.cuda.empty_cache()
158
 
159
+ def clean_model_text(text):
160
+ text = text or ""
161
+ # Remove common leaked control/placeholder tokens, including variants of ##IMAGE##.
162
+ text = re.sub(r"(?i)(?:<\|[^|]{1,80}\|>|##\s*(?:IMAGE|END|START|PAD|UNUSED)[^#]*##)", "", text)
163
+ text = re.sub(r"(?i)\b(?:assistant\s*analysis|analysis\s*final)\b", "", text)
164
+ text = re.sub(r"\n{3,}", "\n\n", text)
165
+ return text.strip()
166
+
167
+ def markdown_block_to_html(block):
168
+ """Small safe Markdown subset -> Telegram HTML. Escape all user/model text first."""
169
+ block = block.strip()
170
+ if not block:
171
+ return ""
172
+ lines = block.splitlines()
173
+ # Fenced code blocks
174
+ if block.startswith("```"):
175
+ body = re.sub(r"^```[^\n]*\n?", "", block)
176
+ body = re.sub(r"\n?```$", "", body)
177
+ return "<pre>" + html.escape(body) + "</pre>"
178
+ if all((not line.strip()) or line.lstrip().startswith(("- ", "* ", "• ")) for line in lines):
179
+ items = [line.strip()[2:].strip() for line in lines if line.strip()]
180
+ return "\n".join("• " + inline_markdown_to_html(item) for item in items)
181
+ out = []
182
+ for line in lines:
183
+ s = line.strip()
184
+ heading = re.match(r"^(#{1,6})\s+(.+)$", s)
185
+ if heading:
186
+ out.append("<b>" + inline_markdown_to_html(heading.group(2)) + "</b>")
187
+ elif re.match(r"^[-*]\s+", s):
188
+ out.append("• " + inline_markdown_to_html(re.sub(r"^[-*]\s+", "", s)))
189
+ elif re.match(r"^\d+[.)]\s+", s):
190
+ out.append(inline_markdown_to_html(s))
191
+ else:
192
+ out.append(inline_markdown_to_html(line))
193
+ return "\n".join(out)
194
+
195
+ def inline_markdown_to_html(text):
196
+ # Escape first, then support a conservative subset.
197
+ s = html.escape(text, quote=False)
198
+ s = re.sub(r"`([^`]+)`", r"<code>\1</code>", s)
199
+ s = re.sub(r"\*\*(.+?)\*\*", r"<b>\1</b>", s)
200
+ s = re.sub(r"(?<!\*)\*([^*\n]+)\*(?!\*)", r"<i>\1</i>", s)
201
+ s = re.sub(r"__([^_]+)__", r"<b>\1</b>", s)
202
+ s = re.sub(r"~~(.+?)~~", r"<s>\1</s>", s)
203
+ return s
204
+
205
+ def format_for_telegram(text):
206
+ text = clean_model_text(text)
207
+ # Convert paragraph by paragraph, so each chunk can be sent as a separate message.
208
+ blocks = [b.strip() for b in re.split(r"\n\s*\n", text) if b.strip()]
209
+ return [markdown_block_to_html(b) for b in blocks] or ["I couldn't generate a readable reply. Please try again."]
210
+
211
+ def split_html_message(block, limit=3500):
212
+ """Split long HTML into safe-ish chunks by lines/sentences and keep tags balanced."""
213
+ if len(block) <= limit:
214
+ return [block]
215
+ # Split by line first; generated blocks are generally line-oriented.
216
+ pieces = []
217
+ current = ""
218
+ for line in block.splitlines():
219
+ candidate = (current + "\n" + line).strip() if current else line
220
+ if len(candidate) <= limit:
221
+ current = candidate
222
+ continue
223
+ if current:
224
+ pieces.append(current)
225
+ current = ""
226
+ while len(line) > limit:
227
+ cut = line.rfind(" ", 0, limit)
228
+ if cut < limit // 2:
229
+ cut = limit
230
+ pieces.append(line[:cut])
231
+ line = line[cut:].lstrip()
232
+ current = line
233
+ if current:
234
+ pieces.append(current)
235
+ # Blocks with formatting tags can be split across tag boundaries. Normalize to plain text
236
+ # for oversized chunks to avoid Telegram rejecting malformed HTML.
237
+ if any(len(x) > limit for x in pieces):
238
+ return [html.escape(re.sub(r"<[^>]+>", "", block)[i:i+limit]) for i in range(0, len(block), limit)]
239
+ return pieces
240
 
241
  async def telegram_api(method, payload):
242
+ if not BOT_TOKEN:
243
  raise RuntimeError("TELEGRAM_BOT_TOKEN is not configured")
 
244
  async with httpx.AsyncClient(timeout=25.0) as client:
245
+ response = await client.post(f"https://api.telegram.org/bot{BOT_TOKEN}/{method}", json=payload)
246
  response.raise_for_status()
247
  data = response.json()
248
  if not data.get("ok"):
249
+ raise RuntimeError(f"Telegram API failed: {method}")
250
  return data
251
 
252
+ async def send_chat_action(chat_id, action="typing"):
253
+ try:
254
+ await telegram_api("sendChatAction", {"chat_id": chat_id, "action": action})
255
+ except Exception:
256
+ log.exception("sendChatAction failed")
257
+
258
+ async def send_html_reply(chat_id, answer):
259
+ for block in format_for_telegram(answer):
260
+ for chunk in split_html_message(block):
261
+ try:
262
+ await telegram_api("sendMessage", {
263
+ "chat_id": chat_id, "text": chunk, "parse_mode": "HTML",
264
+ "disable_web_page_preview": True
265
+ })
266
+ except Exception:
267
+ # If HTML parsing fails, retry this chunk as escaped plain text.
268
+ plain = re.sub(r"</?(?:b|i|s|code|pre)>", "", chunk)
269
+ await telegram_api("sendMessage", {
270
+ "chat_id": chat_id, "text": html.unescape(plain)[:4000],
271
+ "disable_web_page_preview": True
272
+ })
273
+
274
+ histories = {}
275
+ seen_ids = deque(maxlen=3000)
276
+ seen_set = set()
277
+ updates = queue.Queue(maxsize=200)
278
+
279
+ def was_seen(update_id):
280
+ if update_id is None:
281
  return False
282
+ if update_id in seen_set:
283
+ return True
284
+ if len(seen_ids) == seen_ids.maxlen and seen_ids:
285
+ seen_set.discard(seen_ids[0])
286
+ seen_ids.append(update_id)
287
+ seen_set.add(update_id)
288
+ return False
289
+
290
+ async def handle_update(update):
291
  message = update.get("message") or update.get("edited_message")
292
  if not message:
293
  return
 
294
  chat = message.get("chat") or {}
295
+ sender = message.get("from") or {}
296
  chat_id = chat.get("id")
297
+ user_text = (message.get("text") or "").strip()
298
+ if not chat_id or not user_text:
299
  return
300
+ update_id = update.get("update_id")
301
+ user_id = sender.get("id")
302
+ username = sender.get("username", "")
303
+ display_name = " ".join(filter(None, [sender.get("first_name"), sender.get("last_name")]))
304
+ if user_text.startswith("/start"):
305
+ reply = "Hi! I'm your Qwen assistant. Send me a question to chat. Use /reset to clear the conversation."
306
+ await send_html_reply(chat_id, reply)
307
+ save_log(update_id, chat_id, user_id, username, display_name, user_text, reply)
308
  return
309
+ if user_text.startswith("/reset"):
310
+ histories.pop(str(chat_id), None)
311
+ reply = "Conversation history cleared."
312
+ await send_html_reply(chat_id, reply)
313
+ save_log(update_id, chat_id, user_id, username, display_name, user_text, reply)
314
  return
315
+ if user_text.startswith("/"):
316
+ reply = "Available commands: /start and /reset"
317
+ await send_html_reply(chat_id, reply)
318
+ save_log(update_id, chat_id, user_id, username, display_name, user_text, reply)
319
  return
320
 
321
+ await send_chat_action(chat_id, "typing")
 
 
 
 
 
322
  try:
323
+ history = histories.setdefault(str(chat_id), [])
324
+ messages = [{"role": "system", "content": SYSTEM_PROMPT}]
325
+ messages.extend(history[-MAX_HISTORY_MESSAGES:])
326
+ messages.append({"role": "user", "content": user_text[:MAX_INPUT_CHARS]})
327
  answer = await asyncio.to_thread(generate_reply, messages)
328
+ answer = clean_model_text(answer)
329
  if not answer:
330
+ answer = "Sorry, I couldn't create a reply. Please try again."
331
  history.extend([
332
+ {"role": "user", "content": user_text[:MAX_INPUT_CHARS]},
333
  {"role": "assistant", "content": answer},
334
  ])
335
+ histories[str(chat_id)] = history[-MAX_HISTORY_MESSAGES * 2:]
336
+ await send_html_reply(chat_id, answer)
337
+ save_log(update_id, chat_id, user_id, username, display_name, user_text, answer)
338
+ except Exception as exc:
339
+ log.exception("Message processing failed for chat %s", chat_id)
340
+ err = f"{type(exc).__name__}: {str(exc)[:500]}"
341
+ save_log(update_id, chat_id, user_id, username, display_name, user_text, "", "error", err)
342
  try:
343
+ await send_html_reply(chat_id, "Sorry, the model or hosting service had a temporary error. Please try again shortly.")
 
 
 
344
  except Exception:
345
+ log.exception("Could not send failure message")
 
346
 
347
+ async def worker():
348
  while True:
349
+ update = await asyncio.to_thread(updates.get)
350
  try:
351
+ await handle_update(update)
352
  except Exception:
353
+ log.exception("Update worker failed")
354
  finally:
355
+ updates.task_done()
356
 
357
+ def worker_runner():
358
+ asyncio.run(worker())
359
+ threading.Thread(target=worker_runner, daemon=True, name="telegram-worker").start()
360
 
361
  async def webhook(request: Request):
362
+ if WEBHOOK_SECRET:
363
+ incoming = request.headers.get("X-Telegram-Bot-Api-Secret-Token", "")
364
+ if not secrets.compare_digest(incoming, WEBHOOK_SECRET):
365
  return JSONResponse({"ok": False, "error": "invalid secret"}, status_code=403)
 
366
  try:
367
  update = await request.json()
368
  except Exception:
369
  return JSONResponse({"ok": False, "error": "invalid JSON"}, status_code=400)
 
370
  update_id = update.get("update_id")
371
+ if was_seen(update_id):
372
  return JSONResponse({"ok": True, "duplicate": True})
 
373
  try:
374
+ updates.put_nowait(update)
375
  except queue.Full:
376
+ log.error("Webhook queue is full")
 
377
  return JSONResponse({"ok": False, "error": "queue full"}, status_code=503)
 
378
  return JSONResponse({"ok": True})
379
 
 
380
  async def health(request: Request):
381
  return JSONResponse({
382
  "ok": True,
383
  "model": MODEL_ID,
 
 
384
  "model_loaded": model is not None,
385
+ "telegram_token_configured": bool(BOT_TOKEN),
386
+ "webhook_secret_configured": bool(WEBHOOK_SECRET),
387
+ "admin_password_configured": bool(ADMIN_PASSWORD),
388
+ "database": DB_PATH,
389
  })
390
 
391
+ def is_admin(request):
392
+ auth = request.headers.get("authorization", "")
393
+ if not auth.lower().startswith("basic ") or not ADMIN_PASSWORD:
394
+ return False
395
+ import base64
396
+ try:
397
+ userpass = base64.b64decode(auth.split(" ", 1)[1]).decode("utf-8")
398
+ username, password = userpass.split(":", 1)
399
+ except Exception:
400
+ return False
401
+ return secrets.compare_digest(username, ADMIN_USERNAME) and secrets.compare_digest(password, ADMIN_PASSWORD)
402
+
403
+ def admin_login_page():
404
+ return """<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width">
405
+ <title>Qwen Bot Admin</title><style>
406
+ body{font:16px system-ui;background:#101827;color:#e8edf5;margin:0;padding:24px}
407
+ main{max-width:520px;margin:8vh auto;background:#1b2638;padding:28px;border-radius:16px}
408
+ input,button{box-sizing:border-box;width:100%;padding:12px;margin:8px 0;border-radius:8px;border:1px solid #526079}
409
+ input{background:#101827;color:white}button{background:#4678ef;color:white;font-weight:700;cursor:pointer}
410
+ p{color:#bac5d8;font-size:14px}</style></head><body><main><h1>Qwen Bot Admin</h1>
411
+ <p>Use your ADMIN_USERNAME and ADMIN_PASSWORD Space secrets. Browser Basic Auth will prompt for credentials.</p>
412
+ <a style="color:#9fc0ff" href="/admin/logs">Open logs</a></main></body></html>"""
413
+
414
+ async def admin_home(request: Request):
415
+ if not is_admin(request):
416
+ return Response(admin_login_page(), status_code=401, headers={"WWW-Authenticate": 'Basic realm="Qwen Bot Admin"'}, media_type="text/html")
417
+ with db_connect() as conn:
418
+ total = conn.execute("SELECT COUNT(*) FROM messages").fetchone()[0]
419
+ errors = conn.execute("SELECT COUNT(*) FROM messages WHERE status='error'").fetchone()[0]
420
+ chats = conn.execute("SELECT COUNT(DISTINCT chat_id) FROM messages").fetchone()[0]
421
+ return HTMLResponse(f"""<!doctype html><html><head><meta name="viewport" content="width=device-width">
422
+ <title>Qwen Admin</title><style>
423
+ body{{font:16px system-ui;background:#101827;color:#e8edf5;padding:24px;margin:0}}
424
+ main{{max-width:1100px;margin:auto}}.cards{{display:flex;gap:12px;flex-wrap:wrap}}
425
+ .card{{background:#1b2638;padding:20px;border-radius:12px;min-width:150px}}
426
+ a{{color:#9fc0ff;margin-right:16px}}h1{{margin-top:0}}</style></head><body><main>
427
+ <h1>Qwen Bot Admin Dashboard</h1><div class="cards">
428
+ <div class="card"><b>Total records</b><h2>{total}</h2></div>
429
+ <div class="card"><b>Distinct chats</b><h2>{chats}</h2></div>
430
+ <div class="card"><b>Error records</b><h2>{errors}</h2></div></div>
431
+ <p><a href="/admin/logs">View messages</a><a href="/admin/export.csv">Download CSV</a><a href="/admin/export.json">Download JSON</a><a href="/health">Health</a></p>
432
+ <p>Keep this dashboard private. Logs can contain personal messages.</p></main></body></html>""")
433
+
434
+ async def admin_logs(request: Request):
435
+ if not is_admin(request):
436
+ return Response(admin_login_page(), status_code=401, headers={"WWW-Authenticate": 'Basic realm="Qwen Bot Admin"'}, media_type="text/html")
437
+ try:
438
+ limit = max(1, min(int(request.query_params.get("limit", "100")), 500))
439
+ except ValueError:
440
+ limit = 100
441
+ search = request.query_params.get("q", "").strip()[:200]
442
+ with db_connect() as conn:
443
+ if search:
444
+ rows = conn.execute("""SELECT * FROM messages
445
+ WHERE user_text LIKE ? OR model_reply LIKE ? OR username LIKE ?
446
+ ORDER BY id DESC LIMIT ?""", (f"%{search}%", f"%{search}%", f"%{search}%", limit)).fetchall()
447
+ else:
448
+ rows = conn.execute("SELECT * FROM messages ORDER BY id DESC LIMIT ?", (limit,)).fetchall()
449
+ body = []
450
+ for row in rows:
451
+ body.append("<tr>" + "".join(
452
+ "<td>" + html.escape(str(row[key] or "")) + "</td>"
453
+ for key in ("created_at", "username", "chat_id", "user_text", "model_reply", "status", "error")
454
+ ) + "</tr>")
455
+ return HTMLResponse("""<!doctype html><html><head><meta name="viewport" content="width=device-width">
456
+ <title>Qwen Logs</title><style>
457
+ body{font:14px system-ui;background:#101827;color:#e8edf5;padding:18px;margin:0}
458
+ a{color:#9fc0ff}input,button{padding:9px;border-radius:7px;margin:6px 4px 12px 0}
459
+ table{border-collapse:collapse;width:100%;background:#1b2638}th,td{border:1px solid #3a4961;padding:9px;vertical-align:top;text-align:left;white-space:pre-wrap;overflow-wrap:anywhere;max-width:420px}
460
+ th{position:sticky;top:0;background:#27364d} .wrap{overflow:auto}</style></head><body>
461
+ <p><a href="/admin">← Dashboard</a> <a href="/admin/export.csv">Download CSV</a> <a href="/admin/export.json">Download JSON</a></p>
462
+ <form><input name="q" placeholder="Search messages" value=""" + '"' + html.escape(search, quote=True) + '"' + """><input name="limit" type="number" min="1" max="500" value=""" + str(limit) + """><button>Search</button></form>
463
+ <div class="wrap"><table><thead><tr><th>Time (UTC)</th><th>Username</th><th>Chat ID</th><th>User message</th><th>Model response</th><th>Status</th><th>Error</th></tr></thead><tbody>""" +
464
+ "".join(body) + """</tbody></table></div></body></html>""")
465
+
466
+ async def admin_export_json(request: Request):
467
+ if not is_admin(request):
468
+ return Response("Unauthorized", status_code=401, headers={"WWW-Authenticate": 'Basic realm="Qwen Bot Admin"'})
469
+ with db_connect() as conn:
470
+ rows = [dict(row) for row in conn.execute("SELECT * FROM messages ORDER BY id ASC").fetchall()]
471
+ return Response(json.dumps(rows, ensure_ascii=False, indent=2), media_type="application/json",
472
+ headers={"Content-Disposition": 'attachment; filename="qwen-chat-logs.json"'})
473
+
474
+ async def admin_export_csv(request: Request):
475
+ if not is_admin(request):
476
+ return Response("Unauthorized", status_code=401, headers={"WWW-Authenticate": 'Basic realm="Qwen Bot Admin"'})
477
+ with db_connect() as conn:
478
+ rows = conn.execute("SELECT * FROM messages ORDER BY id ASC").fetchall()
479
+ stream = io.StringIO()
480
+ writer = csv.writer(stream)
481
+ if rows:
482
+ writer.writerow(rows[0].keys())
483
+ for row in rows:
484
+ writer.writerow([row[k] for k in row.keys()])
485
+ return Response(stream.getvalue(), media_type="text/csv",
486
+ headers={"Content-Disposition": 'attachment; filename="qwen-chat-logs.csv"'})
487
 
488
  with gr.Blocks(title="Qwen Telegram Bot") as demo:
489
+ gr.Markdown("# Qwen Telegram Bot\nTest the model here. Telegram messages are logged for the admin dashboard.")
490
+ chatbot = gr.Chatbot(type="messages", height=420)
491
+ msg = gr.Textbox(label="Your message", placeholder="Ask Qwen something...")
492
+ clear = gr.Button("Clear chat")
493
+ def ui_reply(message, history):
494
+ history = history or []
495
+ messages = [{"role": "system", "content": SYSTEM_PROMPT}]
496
+ messages.extend(history[-MAX_HISTORY_MESSAGES:])
497
+ messages.append({"role": "user", "content": message})
498
+ answer = generate_reply(messages)
499
+ return answer
500
+ msg.submit(ui_reply, [msg, chatbot], [msg, chatbot])
501
+ clear.click(lambda: (None, []), None, [msg, chatbot])
502
 
503
  demo.queue(default_concurrency_limit=1)
504
  demo.launch(
 
509
  prevent_thread_lock=True,
510
  )
511
 
512
+ # Register routes on the Starlette app Gradio created.
513
+ routes = [
514
+ Route("/health", health, methods=["GET"]),
515
+ Route("/webhook", webhook, methods=["POST"]),
516
+ Route("/admin", admin_home, methods=["GET"]),
517
+ Route("/admin/logs", admin_logs, methods=["GET"]),
518
+ Route("/admin/export.json", admin_export_json, methods=["GET"]),
519
+ Route("/admin/export.csv", admin_export_csv, methods=["GET"]),
520
+ ]
521
+ for route in reversed(routes):
522
+ demo.app.router.routes.insert(0, route)
523
+ log.info("Routes registered: /health, /webhook, /admin")
524
  while True:
525
  time.sleep(3600)