Upload 3 files
Browse files- README.md +17 -39
- app.py +186 -204
- requirements.txt +5 -5
README.md
CHANGED
|
@@ -1,48 +1,26 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
emoji: 🤖
|
| 4 |
colorFrom: blue
|
| 5 |
colorTo: purple
|
| 6 |
-
sdk:
|
| 7 |
-
|
| 8 |
---
|
| 9 |
|
| 10 |
-
#
|
| 11 |
|
| 12 |
-
|
| 13 |
|
| 14 |
-
##
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 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
|
| 2 |
from datetime import datetime, timezone
|
| 3 |
-
from html import escape
|
| 4 |
from pathlib import Path
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
import
|
| 8 |
-
|
| 9 |
-
from
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 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 |
-
|
| 24 |
-
|
|
|
|
|
|
|
| 25 |
|
| 26 |
-
def
|
| 27 |
-
c = sqlite3.connect(
|
| 28 |
c.row_factory = sqlite3.Row
|
| 29 |
return c
|
| 30 |
|
| 31 |
-
def
|
| 32 |
salt = salt or secrets.token_bytes(16)
|
| 33 |
-
|
|
|
|
| 34 |
|
| 35 |
-
def
|
| 36 |
-
|
| 37 |
-
return hmac.compare_digest(
|
| 38 |
|
| 39 |
def init_db():
|
| 40 |
-
with
|
| 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=?", (
|
| 44 |
-
salt, digest =
|
| 45 |
-
c.execute("INSERT INTO admins VALUES(?,?,?,1)", (
|
| 46 |
c.commit()
|
| 47 |
|
| 48 |
-
def
|
| 49 |
-
with
|
| 50 |
c.execute("INSERT INTO messages(user_id,username,direction,message,created_at) VALUES(?,?,?,?,?)",
|
| 51 |
-
(str(uid), username or "", direction, message[:
|
| 52 |
c.commit()
|
| 53 |
|
| 54 |
-
def
|
| 55 |
-
|
| 56 |
-
|
| 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 |
-
|
| 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 |
init_db()
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
if
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
return
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
if not
|
| 149 |
-
return
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
|
| 222 |
if __name__ == "__main__":
|
| 223 |
-
|
| 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 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
|
|
|
| 1 |
+
gradio>=5.20
|
| 2 |
+
spaces
|
| 3 |
+
torch
|
| 4 |
+
transformers>=4.48
|
| 5 |
+
accelerate
|