Hfzune commited on
Commit
e91810b
·
verified ·
1 Parent(s): c285421

Upload 3 files

Browse files
Files changed (3) hide show
  1. README.md +17 -39
  2. app.py +186 -204
  3. requirements.txt +5 -5
README.md CHANGED
@@ -1,48 +1,26 @@
1
  ---
2
- title: HauhauCS Telegram AI + Admin
3
  emoji: 🤖
4
  colorFrom: blue
5
  colorTo: purple
6
- sdk: docker
7
- app_port: 7860
8
  ---
9
 
10
- # Telegram AI + admin panel
11
 
12
- Uses `llama.cpp` for GGUF inference and FastAPI for the admin panel.
13
 
14
- ## Important
 
 
 
 
 
15
 
16
- The model is 27B. The model card lists `IQ4_XS` at about **15.71 GB for weights alone**; context cache and runtime overhead need extra memory. Use a GPU-backed **Docker Space**, not a ZeroGPU/Gradio Space. This project runs a persistent `llama-server` process and is not a ZeroGPU app. First launch downloads the model and may take a while.
17
-
18
- Model card: https://huggingface.co/HauhauCS/Qwen3.8-27B-Uncensored-HauhauCS-Aggressive-MTP-GGUF
19
-
20
- ## Deploy
21
-
22
- 1. Create a Docker Space and upload `app.py`, `requirements.txt`, and `Dockerfile`.
23
- 2. Add Space secrets `TELEGRAM_BOT_TOKEN` (from BotFather) and a unique `SESSION_SECRET`.
24
- 3. Optional: set `ADMIN_USERNAME` (default `admin`), `ADMIN_PASSWORD` (default `admin`), `MODEL_QUANT` (default `IQ4_XS`), `MODEL_CONTEXT` (default `8192`), `MAX_TOKENS` (default `700`).
25
- 4. Set `APP_DATA_DIR` to a writable persistent-storage path if your Space supports persistent storage. Otherwise logs may disappear on restart.
26
- 5. Restart and wait for model download/startup.
27
- 6. Visit `/admin/login`. First login is `admin` / `admin` unless you set initial credentials. Change the password immediately; first login forces this step.
28
-
29
- ## Features
30
-
31
- - User list, Telegram IDs, message counts and last activity
32
- - Per-user conversation history
33
- - Delete conversation history
34
- - Change admin password
35
- - CSV and JSON export
36
- - SQLite message logging
37
-
38
- ## Privacy/security
39
-
40
- The default `admin:admin` credentials are intentionally easy for first setup but unsafe on a public site. Change them immediately. Use a unique `SESSION_SECRET`; keep all secrets out of source code. Conversation logging is enabled, so tell users messages are stored and restrict access to the dashboard/database.
41
-
42
- The project does not load the model's separate vision projector, so this starter setup is text-only. Test with a private Telegram bot first.
43
-
44
- ## Troubleshooting
45
-
46
- - Model errors: check logs, disk quota, RAM/VRAM and whether `llama-server` downloaded and started.
47
- - Telegram silent: verify `TELEGRAM_BOT_TOKEN`; only one process should poll a given bot token.
48
- - Database permissions: set `APP_DATA_DIR` to a writable directory.
 
1
  ---
2
+ title: ZeroGPU AI Chatbot
3
  emoji: 🤖
4
  colorFrom: blue
5
  colorTo: purple
6
+ sdk: gradio
7
+ app_file: app.py
8
  ---
9
 
10
+ # ZeroGPU + Gradio
11
 
12
+ Default model: `HuggingFaceTB/SmolLM2-1.7B-Instruct`.
13
 
14
+ ## Setup
15
+ 1. Create a Hugging Face Space with the Gradio SDK and enable ZeroGPU hardware.
16
+ 2. Upload `app.py` and `requirements.txt`.
17
+ 3. Optional Space variables: `MODEL_ID`, `SYSTEM_PROMPT`, `MAX_NEW_TOKENS`, `ADMIN_USERNAME`, `ADMIN_PASSWORD`, `CHAT_LOG_PATH`.
18
+ 4. Open the Space, then choose the Admin panel tab.
19
+ 5. Default initial admin credentials are `admin` / `admin`. Change the password immediately; first login prompts you to do so.
20
 
21
+ ## Important limitations
22
+ - This is a Gradio chat demo and admin log-management starter. **Telegram webhook/polling delivery is not implemented in this version**, so it will not yet reply to Telegram messages.
23
+ - The admin panel can display and manage stored conversation records, but this demo does not currently populate those records from Telegram. The logging database is ready for integration.
24
+ - `/tmp/chat_logs.sqlite3` is ephemeral on many Spaces. Set `CHAT_LOG_PATH` is not wired in this starter; to persist logs, change `CHAT_LOG_PATH` handling in code to your Space's writable persistent path.
25
+ - Model weights download on first use. ZeroGPU allocations have runtime limits; 1.7B is a practical starting point but may still need adjustments.
26
+ - `admin:admin` is insecure on a public Space. Change it immediately and use a private Space while testing.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py CHANGED
@@ -1,224 +1,206 @@
1
- import asyncio, csv, hashlib, hmac, io, os, secrets, sqlite3, subprocess
2
  from datetime import datetime, timezone
3
- from html import escape
4
  from pathlib import Path
5
- from urllib.parse import quote
6
-
7
- import httpx
8
- from fastapi import FastAPI, Request, Form
9
- from fastapi.responses import HTMLResponse, RedirectResponse, Response
10
- from starlette.middleware.sessions import SessionMiddleware
11
-
12
- DATA = Path(os.getenv("APP_DATA_DIR", "/tmp/botdata"))
13
- DATA.mkdir(parents=True, exist_ok=True)
14
- DB = Path(os.getenv("CHAT_DB_PATH", str(DATA / "chats.sqlite3")))
15
- TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "")
16
- ADMIN = os.getenv("ADMIN_USERNAME", "admin")
17
- INITIAL_PASSWORD = os.getenv("ADMIN_PASSWORD", "admin")
18
- SESSION_SECRET = os.getenv("SESSION_SECRET") or secrets.token_urlsafe(48)
19
- MODEL_ID = os.getenv("MODEL_ID", "HauhauCS/Qwen3.8-27B-Uncensored-HauhauCS-Aggressive-MTP-GGUF")
20
- QUANT = os.getenv("MODEL_QUANT", "IQ4_XS")
21
- LLAMA_URL = os.getenv("LLAMA_URL", "http://127.0.0.1:8081/v1/chat/completions")
22
  SYSTEM_PROMPT = os.getenv("SYSTEM_PROMPT", "You are a helpful, direct assistant. Answer clearly, be honest about uncertainty, and do not invent facts.")
23
- app = FastAPI()
24
- app.add_middleware(SessionMiddleware, secret_key=SESSION_SECRET, same_site="lax", https_only=True)
 
 
25
 
26
- def dbopen():
27
- c = sqlite3.connect(DB, timeout=30)
28
  c.row_factory = sqlite3.Row
29
  return c
30
 
31
- def make_hash(password, salt=None):
32
  salt = salt or secrets.token_bytes(16)
33
- return salt.hex(), hashlib.pbkdf2_hmac("sha256", password.encode(), salt, 310000).hex()
 
34
 
35
- def valid_hash(password, salt, digest):
36
- actual = hashlib.pbkdf2_hmac("sha256", password.encode(), bytes.fromhex(salt), 310000).hex()
37
- return hmac.compare_digest(actual, digest)
38
 
39
  def init_db():
40
- with dbopen() as c:
41
- c.execute("CREATE TABLE IF NOT EXISTS admins(username TEXT PRIMARY KEY,salt TEXT,digest TEXT,must_change INTEGER)")
42
- c.execute("CREATE TABLE IF NOT EXISTS messages(id INTEGER PRIMARY KEY,user_id TEXT,username TEXT,direction TEXT,message TEXT,created_at TEXT)")
43
- if not c.execute("SELECT 1 FROM admins WHERE username=?", (ADMIN,)).fetchone():
44
- salt, digest = make_hash(INITIAL_PASSWORD)
45
- c.execute("INSERT INTO admins VALUES(?,?,?,1)", (ADMIN, salt, digest))
46
  c.commit()
47
 
48
- def log(uid, username, direction, message):
49
- with dbopen() as c:
50
  c.execute("INSERT INTO messages(user_id,username,direction,message,created_at) VALUES(?,?,?,?,?)",
51
- (str(uid), username or "", direction, message[:20000], datetime.now(timezone.utc).isoformat(timespec="seconds")))
52
  c.commit()
53
 
54
- def html(title, body, request=None):
55
- nav = ('<p><a href="/admin">Dashboard</a> · <a href="/admin/users">Users</a> · '
56
- '<a href="/admin/password">Change password</a> · <a href="/admin/logout">Logout</a></p>'
57
- if request and request.session.get("admin") else "")
58
- return HTMLResponse(f"""<!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1">
59
- <title>{escape(title)}</title><style>body{{font:16px system-ui;max-width:1000px;margin:30px auto;padding:0 15px;color:#18212f}}
60
- input,button{{font:inherit;padding:10px;margin:5px 0}}input{{width:min(340px,90%);box-sizing:border-box}}
61
- table{{border-collapse:collapse;width:100%;overflow-wrap:anywhere}}td,th{{border-bottom:1px solid #ddd;padding:8px;text-align:left}}
62
- .card{{border:1px solid #ddd;border-radius:9px;padding:12px;margin:12px 0}}pre{{white-space:pre-wrap;overflow-wrap:anywhere}}</style></head>
63
- <body><h1>{escape(title)}</h1>{nav}{body}</body></html>""")
64
-
65
- def logged_in(req): return bool(req.session.get("admin"))
66
-
67
- async def ask_model(uid, question):
68
- with dbopen() as c:
69
- rows = c.execute("SELECT direction,message FROM messages WHERE user_id=? ORDER BY id DESC LIMIT 12", (str(uid),)).fetchall()
70
- messages = [{"role":"system","content":SYSTEM_PROMPT}]
71
- for r in reversed(rows):
72
- messages.append({"role":"user" if r["direction"]=="user" else "assistant","content":r["message"]})
73
- messages.append({"role":"user","content":question})
74
- async with httpx.AsyncClient(timeout=240) as client:
75
- r = await client.post(LLAMA_URL, json={"model":MODEL_ID,"messages":messages,"temperature":0.7,"max_tokens":700})
76
- r.raise_for_status()
77
- return r.json()["choices"][0]["message"]["content"].strip()
78
-
79
- async def tg(method, payload=None, timeout=40):
80
- async with httpx.AsyncClient(timeout=timeout) as client:
81
- r = await client.post(f"https://api.telegram.org/bot{TOKEN}/{method}", json=payload or {})
82
- r.raise_for_status()
83
- return r.json()
84
-
85
- async def poll_telegram():
86
- if not TOKEN:
87
- print("TELEGRAM_BOT_TOKEN unset; Telegram polling disabled.")
88
  return
89
- offset = 0
90
- while True:
91
- try:
92
- updates = await tg("getUpdates", {"offset":offset,"timeout":30,"allowed_updates":["message"]})
93
- for u in updates.get("result", []):
94
- offset = max(offset, u["update_id"] + 1)
95
- m = u.get("message", {})
96
- chat, user = m.get("chat", {}), m.get("from", {})
97
- text = (m.get("text") or "").strip()
98
- if not text or not chat.get("id"): continue
99
- uid, username = str(user.get("id", chat["id"])), user.get("username") or user.get("first_name") or ""
100
- log(uid, username, "user", text)
101
- await tg("sendChatAction", {"chat_id":chat["id"],"action":"typing"})
102
- try:
103
- answer = await ask_model(uid, text)
104
- log(uid, username, "assistant", answer)
105
- except Exception as e:
106
- print("Model error:", repr(e))
107
- answer = "Sorry, the model is temporarily unavailable. Please try again shortly."
108
- for i in range(0, max(1,len(answer)), 3900):
109
- await tg("sendMessage", {"chat_id":chat["id"],"text":answer[i:i+3900]})
110
- except asyncio.CancelledError:
111
- raise
112
- except Exception as e:
113
- print("Telegram polling error:", repr(e))
114
- await asyncio.sleep(3)
115
-
116
- @app.on_event("startup")
117
- async def startup():
 
 
 
 
 
 
 
118
  init_db()
119
- app.state.poller = asyncio.create_task(poll_telegram())
120
- if os.getenv("LLAMA_EXTERNAL","0") != "1":
121
- cmd = [os.getenv("LLAMA_SERVER_BIN","llama-server"), "-hf", f"{MODEL_ID}:{QUANT}",
122
- "--host","127.0.0.1","--port","8081","-c",os.getenv("MODEL_CONTEXT","8192"),"-np","1"]
123
- try: app.state.llama = subprocess.Popen(cmd)
124
- except Exception as e: app.state.llama = None; print("Could not start llama-server:", repr(e))
125
-
126
- @app.on_event("shutdown")
127
- async def shutdown():
128
- app.state.poller.cancel()
129
- proc = getattr(app.state,"llama",None)
130
- if proc and proc.poll() is None: proc.terminate()
131
-
132
- @app.get("/")
133
- async def home():
134
- return html("Telegram AI bot", '<p>Service is running. Admin: <a href="/admin/login">/admin/login</a></p>')
135
-
136
- @app.get("/health")
137
- async def health():
138
- return {"ok":True,"telegram_configured":bool(TOKEN),"model":MODEL_ID,"quant":QUANT}
139
-
140
- @app.get("/admin/login")
141
- async def login_page(req: Request):
142
- if logged_in(req): return RedirectResponse("/admin",303)
143
- return html("Admin login", '<form method="post"><label>Username<br><input name="username" required></label><br><label>Password<br><input name="password" type="password" required></label><br><button>Log in</button></form><p>First-run default is admin / admin. Change it immediately.</p>')
144
-
145
- @app.post("/admin/login")
146
- async def login(req: Request, username: str=Form(...), password: str=Form(...)):
147
- with dbopen() as c: row = c.execute("SELECT * FROM admins WHERE username=?", (username,)).fetchone()
148
- if not row or not valid_hash(password,row["salt"],row["digest"]):
149
- return html("Admin login", '<p>Login failed.</p><a href="/admin/login">Try again</a>')
150
- req.session.clear(); req.session["admin"] = username
151
- return RedirectResponse("/admin/password?first=1" if row["must_change"] else "/admin",303)
152
-
153
- @app.get("/admin/logout")
154
- async def logout(req: Request):
155
- req.session.clear()
156
- return RedirectResponse("/admin/login",303)
157
-
158
- @app.get("/admin/password")
159
- async def password_page(req: Request):
160
- if not logged_in(req): return RedirectResponse("/admin/login",303)
161
- warning = "<p><b>Change the default password before continuing.</b></p>" if req.query_params.get("first") else ""
162
- return html("Change password", warning+'<form method="post"><label>Current password<br><input type="password" name="current" required></label><br><label>New password (10+ characters)<br><input type="password" name="new" minlength="10" required></label><br><button>Save password</button></form>',req)
163
-
164
- @app.post("/admin/password")
165
- async def change_password(req: Request, current: str=Form(...), new: str=Form(...)):
166
- if not logged_in(req): return RedirectResponse("/admin/login",303)
167
- if len(new)<10: return html("Change password","<p>Password must be at least 10 characters.</p>",req)
168
- with dbopen() as c:
169
- row = c.execute("SELECT * FROM admins WHERE username=?",(req.session["admin"],)).fetchone()
170
- if not row or not valid_hash(current,row["salt"],row["digest"]):
171
- return html("Change password","<p>Current password is incorrect.</p>",req)
172
- salt,digest=make_hash(new)
173
- c.execute("UPDATE admins SET salt=?,digest=?,must_change=0 WHERE username=?",(salt,digest,req.session["admin"])); c.commit()
174
- return RedirectResponse("/admin?password_changed=1",303)
175
-
176
- @app.get("/admin")
177
- async def dashboard(req: Request):
178
- if not logged_in(req): return RedirectResponse("/admin/login",303)
179
- with dbopen() as c:
180
- users=c.execute("SELECT COUNT(DISTINCT user_id) n FROM messages").fetchone()["n"]
181
- count=c.execute("SELECT COUNT(*) n FROM messages").fetchone()["n"]
182
- rows=c.execute("SELECT user_id,MAX(username) username,COUNT(*) n,MAX(created_at) last FROM messages GROUP BY user_id ORDER BY MAX(id) DESC LIMIT 50").fetchall()
183
- trs="".join(f'<tr><td><a href="/admin/users/{quote(r["user_id"],safe="")}">{escape(r["username"] or "(no username)")}</a></td><td>{escape(r["user_id"])}</td><td>{r["n"]}</td><td>{escape(r["last"] or "")}</td></tr>' for r in rows)
184
- msg="<p>Password changed.</p>" if req.query_params.get("password_changed") else ""
185
- return html("Admin dashboard",f'{msg}<div class="card">Users: {users} · Messages: {count}</div><p><a href="/admin/export.csv">Export CSV</a> · <a href="/admin/export.json">Export JSON</a></p><table><tr><th>User</th><th>Telegram ID</th><th>Messages</th><th>Last activity UTC</th></tr>{trs}</table><p>Messages are logged. Limit access and delete records when no longer needed.</p>',req)
186
-
187
- @app.get("/admin/users")
188
- async def users_page(req: Request):
189
- if not logged_in(req): return RedirectResponse("/admin/login",303)
190
- with dbopen() as c: rows=c.execute("SELECT user_id,MAX(username) username,COUNT(*) n,MAX(created_at) last FROM messages GROUP BY user_id ORDER BY MAX(id) DESC").fetchall()
191
- trs="".join(f'<tr><td><a href="/admin/users/{quote(r["user_id"],safe="")}">{escape(r["username"] or "(no username)")}</a></td><td>{escape(r["user_id"])}</td><td>{r["n"]}</td><td>{escape(r["last"] or "")}</td></tr>' for r in rows)
192
- return html("Users",f'<table><tr><th>User</th><th>Telegram ID</th><th>Messages</th><th>Last activity</th></tr>{trs}</table>',req)
193
-
194
- @app.get("/admin/users/{uid}")
195
- async def conversation(req: Request, uid: str):
196
- if not logged_in(req): return RedirectResponse("/admin/login",303)
197
- with dbopen() as c: rows=c.execute("SELECT * FROM messages WHERE user_id=? ORDER BY id DESC LIMIT 300",(uid,)).fetchall()
198
- transcript="".join(f'<div class="card"><b>{escape(r["direction"])} · {escape(r["created_at"])}</b><pre>{escape(r["message"])}</pre></div>' for r in reversed(rows))
199
- form=f'<form method="post" action="/admin/users/{quote(uid,safe="")}/delete" onsubmit="return confirm(&quot;Delete this history?&quot;)"><button>Delete conversation history</button></form>'
200
- return html(f"Conversation: {uid}",f'<p><a href="/admin/users">← All users</a></p>{form}{transcript or "<p>No messages.</p>"}',req)
201
-
202
- @app.post("/admin/users/{uid}/delete")
203
- async def delete_conversation(req: Request, uid: str):
204
- if not logged_in(req): return RedirectResponse("/admin/login",303)
205
- with dbopen() as c: c.execute("DELETE FROM messages WHERE user_id=?",(uid,)); c.commit()
206
- return RedirectResponse("/admin/users",303)
207
-
208
- @app.get("/admin/export.csv")
209
- async def export_csv(req: Request):
210
- if not logged_in(req): return RedirectResponse("/admin/login",303)
211
- with dbopen() as c: rows=c.execute("SELECT id,user_id,username,direction,message,created_at FROM messages ORDER BY id").fetchall()
212
- out=io.StringIO(); w=csv.writer(out); w.writerow(["id","user_id","username","direction","message","created_at"]); w.writerows([tuple(r) for r in rows])
213
- return Response(out.getvalue(),media_type="text/csv",headers={"Content-Disposition":"attachment; filename=chat_logs.csv"})
214
-
215
- @app.get("/admin/export.json")
216
- async def export_json(req: Request):
217
- import json
218
- if not logged_in(req): return RedirectResponse("/admin/login",303)
219
- with dbopen() as c: rows=c.execute("SELECT id,user_id,username,direction,message,created_at FROM messages ORDER BY id").fetchall()
220
- return Response(json.dumps([dict(r) for r in rows],ensure_ascii=False,indent=2),media_type="application/json",headers={"Content-Disposition":"attachment; filename=chat_logs.json"})
 
 
 
 
 
 
 
 
 
 
 
221
 
222
  if __name__ == "__main__":
223
- import uvicorn
224
- uvicorn.run(app,host="0.0.0.0",port=int(os.getenv("PORT","7860")))
 
1
+ import csv, hashlib, hmac, io, os, secrets, sqlite3
2
  from datetime import datetime, timezone
 
3
  from pathlib import Path
4
+
5
+ import gradio as gr
6
+ import spaces
7
+ import torch
8
+ from transformers import AutoTokenizer, AutoModelForCausalLM
9
+
10
+ MODEL_ID = os.getenv("MODEL_ID", "HuggingFaceTB/SmolLM2-1.7B-Instruct")
11
+ DB_PATH = Path(os.getenv("CHAT_DB_PATH", "/tmp/chat_logs.sqlite3"))
12
+ DB_PATH.parent.mkdir(parents=True, exist_ok=True)
13
+ ADMIN_USER = os.getenv("ADMIN_USERNAME", "admin")
14
+ ADMIN_INITIAL_PASSWORD = os.getenv("ADMIN_PASSWORD", "admin")
 
 
 
 
 
 
15
  SYSTEM_PROMPT = os.getenv("SYSTEM_PROMPT", "You are a helpful, direct assistant. Answer clearly, be honest about uncertainty, and do not invent facts.")
16
+ MAX_NEW_TOKENS = int(os.getenv("MAX_NEW_TOKENS", "320"))
17
+ tokenizer = None
18
+ model = None
19
+ ADMIN_SESSIONS = set()
20
 
21
+ def conn():
22
+ c = sqlite3.connect(DB_PATH, timeout=30)
23
  c.row_factory = sqlite3.Row
24
  return c
25
 
26
+ def pw_hash(password, salt=None):
27
  salt = salt or secrets.token_bytes(16)
28
+ digest = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, 310000)
29
+ return salt.hex(), digest.hex()
30
 
31
+ def pw_ok(password, salt_hex, digest_hex):
32
+ digest = hashlib.pbkdf2_hmac("sha256", password.encode(), bytes.fromhex(salt_hex), 310000).hex()
33
+ return hmac.compare_digest(digest, digest_hex)
34
 
35
  def init_db():
36
+ with conn() as c:
37
+ c.execute("CREATE TABLE IF NOT EXISTS admins(username TEXT PRIMARY KEY,salt TEXT NOT NULL,digest TEXT NOT NULL,must_change INTEGER NOT NULL)")
38
+ c.execute("CREATE TABLE IF NOT EXISTS messages(id INTEGER PRIMARY KEY AUTOINCREMENT,user_id TEXT NOT NULL,username TEXT,direction TEXT NOT NULL,message TEXT NOT NULL,created_at TEXT NOT NULL)")
39
+ if not c.execute("SELECT 1 FROM admins WHERE username=?", (ADMIN_USER,)).fetchone():
40
+ salt, digest = pw_hash(ADMIN_INITIAL_PASSWORD)
41
+ c.execute("INSERT INTO admins VALUES(?,?,?,1)", (ADMIN_USER, salt, digest))
42
  c.commit()
43
 
44
+ def log_message(uid, username, direction, message):
45
+ with conn() as c:
46
  c.execute("INSERT INTO messages(user_id,username,direction,message,created_at) VALUES(?,?,?,?,?)",
47
+ (str(uid), username or "", direction, message[:15000], datetime.now(timezone.utc).isoformat(timespec="seconds")))
48
  c.commit()
49
 
50
+ def load_model():
51
+ global tokenizer, model
52
+ if model is not None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  return
54
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
55
+ dtype = torch.float16 if torch.cuda.is_available() else torch.float32
56
+ model = AutoModelForCausalLM.from_pretrained(MODEL_ID, torch_dtype=dtype, low_cpu_mem_usage=True)
57
+ if torch.cuda.is_available():
58
+ model = model.to("cuda")
59
+ model.eval()
60
+
61
+ @spaces.GPU(duration=120)
62
+ def generate_reply(history, prompt_text):
63
+ load_model()
64
+ messages = [{"role":"system","content":SYSTEM_PROMPT}]
65
+ for pair in (history or [])[-8:]:
66
+ if isinstance(pair, (tuple, list)) and len(pair) == 2:
67
+ messages.extend([{"role":"user","content":str(pair[0])},{"role":"assistant","content":str(pair[1])}])
68
+ messages.append({"role":"user","content":prompt_text})
69
+ prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
70
+ inputs = tokenizer(prompt, return_tensors="pt")
71
+ device = next(model.parameters()).device
72
+ inputs = {k:v.to(device) for k,v in inputs.items()}
73
+ with torch.inference_mode():
74
+ out = model.generate(**inputs, max_new_tokens=MAX_NEW_TOKENS, do_sample=True,
75
+ temperature=0.7, top_p=0.9, repetition_penalty=1.08,
76
+ pad_token_id=tokenizer.eos_token_id)
77
+ return tokenizer.decode(out[0][inputs["input_ids"].shape[-1]:], skip_special_tokens=True).strip()
78
+
79
+ def demo_chat(message, history):
80
+ text = (message or "").strip()
81
+ if not text:
82
+ return "", history or []
83
+ try:
84
+ answer = generate_reply(history or [], text)
85
+ except Exception as e:
86
+ answer = f"Model error: {type(e).__name__}: {e}"
87
+ return "", (history or []) + [(text, answer)]
88
+
89
+ def admin_login(username, password):
90
  init_db()
91
+ with conn() as c:
92
+ row = c.execute("SELECT * FROM admins WHERE username=?", (username or "",)).fetchone()
93
+ if not row or not pw_ok(password or "", row["salt"], row["digest"]):
94
+ return "", "Login failed.", gr.update(visible=False), gr.update(visible=False)
95
+ token = secrets.token_urlsafe(32)
96
+ ADMIN_SESSIONS.add(token)
97
+ if row["must_change"]:
98
+ return token, "First login: change the default password before using admin tools.", gr.update(visible=True), gr.update(visible=True)
99
+ return token, "Signed in.", gr.update(visible=True), gr.update(visible=False)
100
+
101
+ def get_stats(token):
102
+ if token not in ADMIN_SESSIONS:
103
+ return "Please sign in again.", []
104
+ with conn() as c:
105
+ n_users = c.execute("SELECT COUNT(DISTINCT user_id) n FROM messages").fetchone()["n"]
106
+ n_msgs = c.execute("SELECT COUNT(*) n FROM messages").fetchone()["n"]
107
+ rows = c.execute("SELECT user_id,MAX(username) username,COUNT(*) n,MAX(created_at) last FROM messages GROUP BY user_id ORDER BY MAX(id) DESC LIMIT 100").fetchall()
108
+ return f"Users: {n_users} · Messages: {n_msgs}", [[r["user_id"],r["username"],r["n"],r["last"]] for r in rows]
109
+
110
+ def get_history(token, uid):
111
+ if token not in ADMIN_SESSIONS or not uid:
112
+ return []
113
+ with conn() as c:
114
+ rows = c.execute("SELECT created_at,direction,message FROM messages WHERE user_id=? ORDER BY id DESC LIMIT 300", (str(uid),)).fetchall()
115
+ return [[r["created_at"],r["direction"],r["message"]] for r in reversed(rows)]
116
+
117
+ def delete_history(token, uid):
118
+ if token not in ADMIN_SESSIONS:
119
+ return "Please sign in again."
120
+ if not uid:
121
+ return "Enter a Telegram user ID."
122
+ with conn() as c:
123
+ c.execute("DELETE FROM messages WHERE user_id=?", (str(uid),))
124
+ c.commit()
125
+ return "Conversation history deleted."
126
+
127
+ def change_password(token, username, current, new):
128
+ if token not in ADMIN_SESSIONS:
129
+ return "Please sign in again."
130
+ if len(new or "") < 10:
131
+ return "New password must be at least 10 characters."
132
+ with conn() as c:
133
+ row = c.execute("SELECT * FROM admins WHERE username=?", (username,)).fetchone()
134
+ if not row or not pw_ok(current or "", row["salt"], row["digest"]):
135
+ return "Current password is incorrect."
136
+ salt, digest = pw_hash(new)
137
+ c.execute("UPDATE admins SET salt=?,digest=?,must_change=0 WHERE username=?", (salt,digest,username))
138
+ c.commit()
139
+ ADMIN_SESSIONS.discard(token)
140
+ return "Password changed. Please sign in again."
141
+
142
+ def export_csv(token):
143
+ if token not in ADMIN_SESSIONS:
144
+ return None
145
+ with conn() as c:
146
+ rows = c.execute("SELECT id,user_id,username,direction,message,created_at FROM messages ORDER BY id").fetchall()
147
+ fpath = "/tmp/chat_logs.csv"
148
+ with open(fpath,"w",newline="",encoding="utf-8") as f:
149
+ w = csv.writer(f)
150
+ w.writerow(["id","user_id","username","direction","message","created_at"])
151
+ w.writerows([tuple(r) for r in rows])
152
+ return fpath
153
+
154
+ init_db()
155
+ with gr.Blocks(title="ZeroGPU AI Chatbot") as demo:
156
+ gr.Markdown("# ZeroGPU AI Chatbot")
157
+ gr.Markdown(f"Model: `{MODEL_ID}`")
158
+ with gr.Tab("Chat"):
159
+ chat = gr.Chatbot(label="Chat", height=450)
160
+ message = gr.Textbox(label="Message", placeholder="Type a message and press Enter")
161
+ clear = gr.Button("Clear chat")
162
+ message.submit(demo_chat, [message, chat], [message, chat])
163
+ clear.click(lambda: ("", []), None, [message, chat])
164
+ with gr.Tab("Admin panel"):
165
+ gr.Markdown("### Admin login")
166
+ username = gr.Textbox(label="Username", value=ADMIN_USER)
167
+ password = gr.Textbox(label="Password", type="password")
168
+ login_btn = gr.Button("Sign in")
169
+ login_msg = gr.Markdown()
170
+ token_state = gr.State("")
171
+ with gr.Column(visible=False) as admin_area:
172
+ with gr.Column(visible=False) as first_login:
173
+ gr.Markdown("**Change the initial password before continuing.**")
174
+ first_current = gr.Textbox(label="Current password", type="password", value="")
175
+ first_new = gr.Textbox(label="New password (10+ characters)", type="password")
176
+ first_save = gr.Button("Save new password")
177
+ first_status = gr.Markdown()
178
+ refresh = gr.Button("Refresh users")
179
+ stats = gr.Markdown()
180
+ users = gr.Dataframe(headers=["Telegram user ID","Username","Messages","Last activity UTC"], interactive=False)
181
+ uid = gr.Textbox(label="Telegram user ID")
182
+ view = gr.Button("View conversation")
183
+ transcript = gr.Dataframe(headers=["Time UTC","Direction","Message"], interactive=False, wrap=True)
184
+ delete = gr.Button("Delete conversation history", variant="stop")
185
+ delete_status = gr.Markdown()
186
+ gr.Markdown("### Change admin password")
187
+ current_pw = gr.Textbox(label="Current password", type="password")
188
+ new_pw = gr.Textbox(label="New password (10+ characters)", type="password")
189
+ save_pw = gr.Button("Change password")
190
+ pw_status = gr.Markdown()
191
+ export_btn = gr.Button("Export chat logs CSV")
192
+ export_file = gr.File(label="CSV export")
193
+
194
+ def login_ui(u, p):
195
+ token, text, show_admin, show_first = admin_login(u,p)
196
+ return text, token, show_admin, show_first
197
+ login_btn.click(login_ui, [username,password], [login_msg,token_state,admin_area,first_login])
198
+ refresh.click(get_stats, [token_state], [stats,users])
199
+ view.click(get_history, [token_state,uid], [transcript])
200
+ delete.click(delete_history, [token_state,uid], [delete_status])
201
+ first_save.click(change_password, [token_state,username,first_current,first_new], [first_status])
202
+ save_pw.click(change_password, [token_state,username,current_pw,new_pw], [pw_status])
203
+ export_btn.click(export_csv, [token_state], [export_file])
204
 
205
  if __name__ == "__main__":
206
+ demo.queue(default_concurrency_limit=1).launch()
 
requirements.txt CHANGED
@@ -1,5 +1,5 @@
1
- fastapi>=0.115
2
- uvicorn[standard]>=0.30
3
- python-multipart>=0.0.9
4
- httpx>=0.27
5
- itsdangerous>=2.2
 
1
+ gradio>=5.20
2
+ spaces
3
+ torch
4
+ transformers>=4.48
5
+ accelerate