Spaces:
Sleeping
Sleeping
Delete app.py
Browse files
app.py
DELETED
|
@@ -1,177 +0,0 @@
|
|
| 1 |
-
import os, re, json, math, sqlite3, threading, time
|
| 2 |
-
from collections import Counter
|
| 3 |
-
from flask import Flask, request, Response, jsonify, render_template
|
| 4 |
-
from huggingface_hub import hf_hub_download
|
| 5 |
-
|
| 6 |
-
REPO = os.getenv("MODEL_REPO", "prism-ml/Bonsai-8B-gguf")
|
| 7 |
-
FILE = os.getenv("MODEL_FILE", "Bonsai-8B-Q1_0.gguf")
|
| 8 |
-
DB = os.path.join(os.getenv("DATA_DIR", "data"), "memory.db")
|
| 9 |
-
os.makedirs(os.path.dirname(DB), exist_ok=True)
|
| 10 |
-
|
| 11 |
-
app = Flask(__name__)
|
| 12 |
-
state = {"llm": None, "status": "loading", "error": ""}
|
| 13 |
-
lock = threading.Lock() # CPU-তে একসাথে একটাই উত্তর তৈরি হবে
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
def load_model():
|
| 17 |
-
try:
|
| 18 |
-
from llama_cpp import Llama
|
| 19 |
-
path = hf_hub_download(REPO, FILE)
|
| 20 |
-
state["llm"] = Llama(model_path=path, n_ctx=4096, n_batch=256,
|
| 21 |
-
n_threads=os.cpu_count() or 2, verbose=False)
|
| 22 |
-
state["status"] = "ready"
|
| 23 |
-
except Exception as e: # মডেল লোড না হলে কারণ UI-তে দেখানো হবে
|
| 24 |
-
state.update(status="error", error=str(e))
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
threading.Thread(target=load_model, daemon=True).start()
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
# ---------- স্মৃতি (SQLite + অক্ষর-ট্রাইগ্রাম মিল) ----------
|
| 31 |
-
def db():
|
| 32 |
-
c = sqlite3.connect(DB)
|
| 33 |
-
c.row_factory = sqlite3.Row
|
| 34 |
-
c.executescript(
|
| 35 |
-
"CREATE TABLE IF NOT EXISTS facts(id INTEGER PRIMARY KEY, text TEXT, ts REAL);"
|
| 36 |
-
"CREATE TABLE IF NOT EXISTS msgs(id INTEGER PRIMARY KEY, text TEXT, ts REAL);")
|
| 37 |
-
return c
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
def grams(text):
|
| 41 |
-
out = Counter()
|
| 42 |
-
for w in re.split(r"[\s.,!?;:()\[\]\"'।]+", text.lower()):
|
| 43 |
-
if not w:
|
| 44 |
-
continue
|
| 45 |
-
w = f"#{w}#"
|
| 46 |
-
for i in range(len(w) - 2):
|
| 47 |
-
out[w[i:i + 3]] += 1
|
| 48 |
-
return out
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
def score(q, d):
|
| 52 |
-
if not q or not d:
|
| 53 |
-
return 0.0
|
| 54 |
-
common = sum(min(n, d[g]) for g, n in q.items() if g in d)
|
| 55 |
-
return common / math.sqrt(sum(q.values()) * sum(d.values()))
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
def search(table, query, k, exclude=(), min_score=0.15):
|
| 59 |
-
q = grams(query)
|
| 60 |
-
with db() as c:
|
| 61 |
-
rows = c.execute(f"SELECT text FROM {table} ORDER BY id DESC LIMIT 500").fetchall()
|
| 62 |
-
ranked = sorted(((score(q, grams(r["text"])), r["text"]) for r in rows
|
| 63 |
-
if r["text"] not in exclude), reverse=True)
|
| 64 |
-
return [t for s, t in ranked[:k] if s >= min_score]
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
def all_facts():
|
| 68 |
-
with db() as c:
|
| 69 |
-
return [dict(r) for r in c.execute("SELECT id, text FROM facts ORDER BY id DESC")]
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
def sse(obj):
|
| 73 |
-
return f"data: {json.dumps(obj, ensure_ascii=False)}\n\n"
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
# ---------- রুট ----------
|
| 77 |
-
@app.get("/")
|
| 78 |
-
def index():
|
| 79 |
-
return render_template("index.html")
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
@app.get("/status")
|
| 83 |
-
def status():
|
| 84 |
-
return jsonify(status=state["status"], error=state["error"])
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
@app.post("/chat")
|
| 88 |
-
def chat():
|
| 89 |
-
if state["status"] != "ready":
|
| 90 |
-
return jsonify(error="মডেল এখনও প্রস্তুত নয়"), 503
|
| 91 |
-
data = request.get_json(force=True)
|
| 92 |
-
msg = (data.get("message") or "").strip()
|
| 93 |
-
hist = (data.get("history") or [])[-8:]
|
| 94 |
-
if not msg:
|
| 95 |
-
return jsonify(error="খালি বার্তা"), 400
|
| 96 |
-
|
| 97 |
-
m = re.match(r"^(মনে রাখো|মনে রেখো|remember)\s*[::\-]\s*(.+)$", msg, re.I | re.S)
|
| 98 |
-
if m:
|
| 99 |
-
with db() as c:
|
| 100 |
-
c.execute("INSERT INTO facts(text, ts) VALUES(?,?)", (m.group(2).strip(), time.time()))
|
| 101 |
-
return Response(sse({"t": "ঠিক আছে, মনে রাখলাম: " + m.group(2).strip()}) + sse({"done": True}),
|
| 102 |
-
mimetype="text/event-stream")
|
| 103 |
-
|
| 104 |
-
facts = all_facts()
|
| 105 |
-
fact_texts = [f["text"] for f in facts] if len(facts) <= 15 else search("facts", msg, 6)
|
| 106 |
-
past = search("msgs", msg, 3, exclude={h["content"] for h in hist})
|
| 107 |
-
system = ("তুমি একজন বন্ধুসুলভ ও সংক্ষিপ্ত সহকারী। ব্যবহারকারী যে ভাষায় লেখে সেই ভাষায় উত্তর দাও "
|
| 108 |
-
"(বাংলায় লিখলে বাংলায়)। নিচের স্মৃতি ব্যবহারকারীর নিজের বলা তথ্য; প্রাসঙ্গিক হলে ব্যবহার করো, "
|
| 109 |
-
"স্মৃতিতে না থাকলে অনুমান করে বানিয়ে বোলো না।")
|
| 110 |
-
if fact_texts:
|
| 111 |
-
system += "\n\nস্মৃতি:\n" + "\n".join("- " + t for t in fact_texts)
|
| 112 |
-
if past:
|
| 113 |
-
system += "\n\nআগের কথোপকথন থেকে প্রাসঙ্গিক অংশ:\n" + "\n".join("- " + t for t in past)
|
| 114 |
-
messages = [{"role": "system", "content": system}] + [
|
| 115 |
-
{"role": h["role"], "content": h["content"]} for h in hist] + [{"role": "user", "content": msg}]
|
| 116 |
-
|
| 117 |
-
def gen():
|
| 118 |
-
with lock:
|
| 119 |
-
try:
|
| 120 |
-
for ch in state["llm"].create_chat_completion(
|
| 121 |
-
messages=messages, stream=True, max_tokens=512,
|
| 122 |
-
temperature=0.5, top_p=0.85, top_k=20):
|
| 123 |
-
t = ch["choices"][0]["delta"].get("content")
|
| 124 |
-
if t:
|
| 125 |
-
yield sse({"t": t})
|
| 126 |
-
except Exception as e:
|
| 127 |
-
yield sse({"error": str(e)})
|
| 128 |
-
with db() as c:
|
| 129 |
-
c.execute("INSERT INTO msgs(text, ts) VALUES(?,?)", (msg, time.time()))
|
| 130 |
-
yield sse({"done": True})
|
| 131 |
-
|
| 132 |
-
return Response(gen(), mimetype="text/event-stream", headers={"X-Accel-Buffering": "no"})
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
@app.get("/memory")
|
| 136 |
-
def memory_list():
|
| 137 |
-
return jsonify(all_facts())
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
@app.post("/memory")
|
| 141 |
-
def memory_add():
|
| 142 |
-
text = (request.get_json(force=True).get("text") or "").strip()
|
| 143 |
-
if text:
|
| 144 |
-
with db() as c:
|
| 145 |
-
c.execute("INSERT INTO facts(text, ts) VALUES(?,?)", (text, time.time()))
|
| 146 |
-
return jsonify(all_facts())
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
@app.delete("/memory/<int:fid>")
|
| 150 |
-
def memory_del(fid):
|
| 151 |
-
with db() as c:
|
| 152 |
-
c.execute("DELETE FROM facts WHERE id=?", (fid,))
|
| 153 |
-
return jsonify(all_facts())
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
@app.get("/export")
|
| 157 |
-
def export():
|
| 158 |
-
with db() as c:
|
| 159 |
-
data = {"facts": [r["text"] for r in c.execute("SELECT text FROM facts ORDER BY id")],
|
| 160 |
-
"msgs": [r["text"] for r in c.execute("SELECT text FROM msgs ORDER BY id")]}
|
| 161 |
-
return Response(json.dumps(data, ensure_ascii=False), mimetype="application/json",
|
| 162 |
-
headers={"Content-Disposition": "attachment; filename=bonsai-memory.json"})
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
@app.post("/import")
|
| 166 |
-
def import_():
|
| 167 |
-
data = request.get_json(force=True)
|
| 168 |
-
with db() as c:
|
| 169 |
-
for t in data.get("facts", []):
|
| 170 |
-
c.execute("INSERT INTO facts(text, ts) VALUES(?,?)", (t, time.time()))
|
| 171 |
-
for t in data.get("msgs", []):
|
| 172 |
-
c.execute("INSERT INTO msgs(text, ts) VALUES(?,?)", (t, time.time()))
|
| 173 |
-
return jsonify(all_facts())
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
if __name__ == "__main__":
|
| 177 |
-
app.run(host="0.0.0.0", port=int(os.getenv("PORT", 7860)), threaded=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|