Spaces:
Running on Zero
Running on Zero
feedback persistence; probe traffic excluded from v2 metrics
Browse files- src/api/db.py +25 -15
- src/api/ml_app.py +15 -3
- src/api/persist.py +103 -0
src/api/db.py
CHANGED
|
@@ -86,6 +86,7 @@ MIGRATIONS = [
|
|
| 86 |
("queries", "diagnosis_location", "TEXT"),
|
| 87 |
("queries", "suggested_query", "TEXT"),
|
| 88 |
("queries", "retry_of", "INTEGER"),
|
|
|
|
| 89 |
]
|
| 90 |
|
| 91 |
|
|
@@ -129,6 +130,7 @@ class FeedbackLog:
|
|
| 129 |
source: str | None = None,
|
| 130 |
diagnosis: dict[str, Any] | None = None,
|
| 131 |
retry_of: int | None = None,
|
|
|
|
| 132 |
) -> int:
|
| 133 |
"""Record a query, its answer, the passages shown, and any v2 diagnosis."""
|
| 134 |
with self._connect() as conn:
|
|
@@ -138,8 +140,8 @@ class FeedbackLog:
|
|
| 138 |
cursor = conn.execute(
|
| 139 |
"INSERT INTO queries (ts, query, answer, latency_ms, backend, mode, "
|
| 140 |
"confident, top_score, mean_top_score, n_results, generated, source, "
|
| 141 |
-
"diagnosis_location, suggested_query, retry_of) "
|
| 142 |
-
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
| 143 |
(
|
| 144 |
_now(), query, answer, latency_ms, backend, mode,
|
| 145 |
None if confident is None else int(confident),
|
|
@@ -149,6 +151,7 @@ class FeedbackLog:
|
|
| 149 |
(diagnosis or {}).get("location"),
|
| 150 |
(diagnosis or {}).get("suggested_query"),
|
| 151 |
retry_of,
|
|
|
|
| 152 |
),
|
| 153 |
)
|
| 154 |
query_id = int(cursor.lastrowid)
|
|
@@ -207,6 +210,13 @@ class FeedbackLog:
|
|
| 207 |
"low_confidence": count("SELECT COUNT(*) FROM queries WHERE confident=0"),
|
| 208 |
}
|
| 209 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
def v2_metrics(self) -> dict[str, Any]:
|
| 211 |
"""The live v2 funnel: diagnosis shown -> retry clicked -> result used.
|
| 212 |
|
|
@@ -215,30 +225,30 @@ class FeedbackLog:
|
|
| 215 |
whether following it led to a paper they opened. The baseline is
|
| 216 |
gate-fired queries nobody retried: did those users open anything?
|
| 217 |
"""
|
| 218 |
-
with self.
|
| 219 |
def one(sql: str) -> float:
|
| 220 |
return float(conn.execute(sql).fetchone()[0] or 0)
|
| 221 |
|
| 222 |
-
shown = one("SELECT COUNT(*) FROM
|
| 223 |
-
with_query = one("SELECT COUNT(*) FROM
|
| 224 |
-
retries = one("SELECT COUNT(*) FROM
|
| 225 |
retry_clicked = one(
|
| 226 |
-
"SELECT COUNT(DISTINCT q.id) FROM
|
| 227 |
"ON c.query_id = q.id WHERE q.retry_of IS NOT NULL")
|
| 228 |
fired_not_retried = one(
|
| 229 |
-
"SELECT COUNT(*) FROM
|
| 230 |
-
"AND NOT EXISTS (SELECT 1 FROM
|
| 231 |
fired_not_retried_clicked = one(
|
| 232 |
-
"SELECT COUNT(DISTINCT q.id) FROM
|
| 233 |
"ON c.query_id = q.id WHERE q.confident = 0 AND q.retry_of IS NULL "
|
| 234 |
-
"AND NOT EXISTS (SELECT 1 FROM
|
| 235 |
by_location = {
|
| 236 |
(r[0] or "none").split(":")[0]: r[1] for r in conn.execute(
|
| 237 |
-
"SELECT diagnosis_location, COUNT(*) FROM
|
| 238 |
"WHERE diagnosis_location IS NOT NULL GROUP BY 1")
|
| 239 |
}
|
| 240 |
by_source = {r[0] or "corpus": r[1] for r in conn.execute(
|
| 241 |
-
"SELECT source, COUNT(*) FROM
|
| 242 |
|
| 243 |
def rate(a: float, b: float) -> float | None:
|
| 244 |
return round(a / b, 4) if b else None
|
|
@@ -262,12 +272,12 @@ class FeedbackLog:
|
|
| 262 |
suggested query did, and here is the paper they opened" - exactly the
|
| 263 |
signal the offline gate could not see.
|
| 264 |
"""
|
| 265 |
-
with self.
|
| 266 |
return [dict(r) for r in conn.execute(
|
| 267 |
"SELECT o.id AS original_id, o.query AS original_query, "
|
| 268 |
"o.mean_top_score AS original_mean_score, o.diagnosis_location, "
|
| 269 |
"r.id AS retry_id, r.query AS retry_query, c.doc_id AS clicked_doc, "
|
| 270 |
-
"r.ts AS ts FROM
|
| 271 |
"JOIN citation_clicks c ON c.query_id = r.id "
|
| 272 |
"ORDER BY r.id DESC LIMIT ?", (limit,)).fetchall()]
|
| 273 |
|
|
|
|
| 86 |
("queries", "diagnosis_location", "TEXT"),
|
| 87 |
("queries", "suggested_query", "TEXT"),
|
| 88 |
("queries", "retry_of", "INTEGER"),
|
| 89 |
+
("queries", "probe", "INTEGER"), # monitoring traffic, not a user
|
| 90 |
]
|
| 91 |
|
| 92 |
|
|
|
|
| 130 |
source: str | None = None,
|
| 131 |
diagnosis: dict[str, Any] | None = None,
|
| 132 |
retry_of: int | None = None,
|
| 133 |
+
probe: bool = False,
|
| 134 |
) -> int:
|
| 135 |
"""Record a query, its answer, the passages shown, and any v2 diagnosis."""
|
| 136 |
with self._connect() as conn:
|
|
|
|
| 140 |
cursor = conn.execute(
|
| 141 |
"INSERT INTO queries (ts, query, answer, latency_ms, backend, mode, "
|
| 142 |
"confident, top_score, mean_top_score, n_results, generated, source, "
|
| 143 |
+
"diagnosis_location, suggested_query, retry_of, probe) "
|
| 144 |
+
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
| 145 |
(
|
| 146 |
_now(), query, answer, latency_ms, backend, mode,
|
| 147 |
None if confident is None else int(confident),
|
|
|
|
| 151 |
(diagnosis or {}).get("location"),
|
| 152 |
(diagnosis or {}).get("suggested_query"),
|
| 153 |
retry_of,
|
| 154 |
+
int(probe),
|
| 155 |
),
|
| 156 |
)
|
| 157 |
query_id = int(cursor.lastrowid)
|
|
|
|
| 210 |
"low_confidence": count("SELECT COUNT(*) FROM queries WHERE confident=0"),
|
| 211 |
}
|
| 212 |
|
| 213 |
+
def _user_view(self) -> sqlite3.Connection:
|
| 214 |
+
"""A connection where `user_queries` is every query except probes."""
|
| 215 |
+
conn = self._connect()
|
| 216 |
+
conn.execute("CREATE TEMP VIEW IF NOT EXISTS user_queries AS "
|
| 217 |
+
"SELECT * FROM queries WHERE COALESCE(probe, 0) = 0")
|
| 218 |
+
return conn
|
| 219 |
+
|
| 220 |
def v2_metrics(self) -> dict[str, Any]:
|
| 221 |
"""The live v2 funnel: diagnosis shown -> retry clicked -> result used.
|
| 222 |
|
|
|
|
| 225 |
whether following it led to a paper they opened. The baseline is
|
| 226 |
gate-fired queries nobody retried: did those users open anything?
|
| 227 |
"""
|
| 228 |
+
with self._user_view() as conn:
|
| 229 |
def one(sql: str) -> float:
|
| 230 |
return float(conn.execute(sql).fetchone()[0] or 0)
|
| 231 |
|
| 232 |
+
shown = one("SELECT COUNT(*) FROM user_queries WHERE diagnosis_location IS NOT NULL")
|
| 233 |
+
with_query = one("SELECT COUNT(*) FROM user_queries WHERE suggested_query IS NOT NULL")
|
| 234 |
+
retries = one("SELECT COUNT(*) FROM user_queries WHERE retry_of IS NOT NULL")
|
| 235 |
retry_clicked = one(
|
| 236 |
+
"SELECT COUNT(DISTINCT q.id) FROM user_queries q JOIN citation_clicks c "
|
| 237 |
"ON c.query_id = q.id WHERE q.retry_of IS NOT NULL")
|
| 238 |
fired_not_retried = one(
|
| 239 |
+
"SELECT COUNT(*) FROM user_queries q WHERE q.confident = 0 AND q.retry_of IS NULL "
|
| 240 |
+
"AND NOT EXISTS (SELECT 1 FROM user_queries r WHERE r.retry_of = q.id)")
|
| 241 |
fired_not_retried_clicked = one(
|
| 242 |
+
"SELECT COUNT(DISTINCT q.id) FROM user_queries q JOIN citation_clicks c "
|
| 243 |
"ON c.query_id = q.id WHERE q.confident = 0 AND q.retry_of IS NULL "
|
| 244 |
+
"AND NOT EXISTS (SELECT 1 FROM user_queries r WHERE r.retry_of = q.id)")
|
| 245 |
by_location = {
|
| 246 |
(r[0] or "none").split(":")[0]: r[1] for r in conn.execute(
|
| 247 |
+
"SELECT diagnosis_location, COUNT(*) FROM user_queries "
|
| 248 |
"WHERE diagnosis_location IS NOT NULL GROUP BY 1")
|
| 249 |
}
|
| 250 |
by_source = {r[0] or "corpus": r[1] for r in conn.execute(
|
| 251 |
+
"SELECT source, COUNT(*) FROM user_queries GROUP BY 1")}
|
| 252 |
|
| 253 |
def rate(a: float, b: float) -> float | None:
|
| 254 |
return round(a / b, 4) if b else None
|
|
|
|
| 272 |
suggested query did, and here is the paper they opened" - exactly the
|
| 273 |
signal the offline gate could not see.
|
| 274 |
"""
|
| 275 |
+
with self._user_view() as conn:
|
| 276 |
return [dict(r) for r in conn.execute(
|
| 277 |
"SELECT o.id AS original_id, o.query AS original_query, "
|
| 278 |
"o.mean_top_score AS original_mean_score, o.diagnosis_location, "
|
| 279 |
"r.id AS retry_id, r.query AS retry_query, c.doc_id AS clicked_doc, "
|
| 280 |
+
"r.ts AS ts FROM user_queries r JOIN user_queries o ON o.id = r.retry_of "
|
| 281 |
"JOIN citation_clicks c ON c.query_id = r.id "
|
| 282 |
"ORDER BY r.id DESC LIMIT ?", (limit,)).fetchall()]
|
| 283 |
|
src/api/ml_app.py
CHANGED
|
@@ -25,6 +25,7 @@ from fastapi.responses import JSONResponse
|
|
| 25 |
from fastapi.middleware.cors import CORSMiddleware
|
| 26 |
from pydantic import BaseModel, Field
|
| 27 |
|
|
|
|
| 28 |
from src.api.db import FeedbackLog
|
| 29 |
from src.api.llm import is_configured
|
| 30 |
from src.api.ml_pipeline import MLPipeline
|
|
@@ -50,7 +51,9 @@ def build_state() -> None:
|
|
| 50 |
cfg = load_config(CONFIG_PATH)
|
| 51 |
state["cfg"] = cfg
|
| 52 |
state["pipeline"] = MLPipeline(cfg)
|
|
|
|
| 53 |
state["log"] = FeedbackLog(cfg["paths"]["feedback_db"])
|
|
|
|
| 54 |
state["uploads"] = UploadStore(cfg["paths"].get("upload_dir", "cache/uploads"))
|
| 55 |
|
| 56 |
|
|
@@ -78,6 +81,12 @@ app.add_middleware(
|
|
| 78 |
)
|
| 79 |
|
| 80 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
class AskRequest(BaseModel):
|
| 82 |
query: str = Field(min_length=3, max_length=1000)
|
| 83 |
top_k: int = Field(default=6, ge=1, le=20)
|
|
@@ -158,7 +167,7 @@ def search(request: AskRequest) -> dict[str, Any]:
|
|
| 158 |
|
| 159 |
|
| 160 |
@app.post("/papers")
|
| 161 |
-
def papers(request: PapersRequest) -> dict[str, Any]:
|
| 162 |
"""Topic in, ranked papers out (not passages)."""
|
| 163 |
pipeline: MLPipeline = state["pipeline"]
|
| 164 |
log: FeedbackLog = state["log"]
|
|
@@ -180,12 +189,13 @@ def papers(request: PapersRequest) -> dict[str, Any]:
|
|
| 180 |
source=result.get("source"),
|
| 181 |
diagnosis=result.get("diagnosis"),
|
| 182 |
retry_of=request.retry_of,
|
|
|
|
| 183 |
)
|
| 184 |
return {"query_id": query_id, **result}
|
| 185 |
|
| 186 |
|
| 187 |
@app.post("/ask")
|
| 188 |
-
def ask(request: AskRequest) -> dict[str, Any]:
|
| 189 |
"""Question answering, logged."""
|
| 190 |
pipeline: MLPipeline = state["pipeline"]
|
| 191 |
log: FeedbackLog = state["log"]
|
|
@@ -204,12 +214,13 @@ def ask(request: AskRequest) -> dict[str, Any]:
|
|
| 204 |
source=result.get("source"),
|
| 205 |
diagnosis=result.get("diagnosis"),
|
| 206 |
retry_of=request.retry_of,
|
|
|
|
| 207 |
)
|
| 208 |
return {"query_id": query_id, **result}
|
| 209 |
|
| 210 |
|
| 211 |
@app.post("/explain")
|
| 212 |
-
def explain(request: ExplainRequest) -> dict[str, Any]:
|
| 213 |
"""Resolve a citation to its paper and explain it in plain terms."""
|
| 214 |
pipeline: MLPipeline = state["pipeline"]
|
| 215 |
log: FeedbackLog = state["log"]
|
|
@@ -259,6 +270,7 @@ def explain(request: ExplainRequest) -> dict[str, Any]:
|
|
| 259 |
source=result.get("source"),
|
| 260 |
diagnosis=result.get("diagnosis"),
|
| 261 |
retry_of=request.retry_of,
|
|
|
|
| 262 |
)
|
| 263 |
return {"query_id": query_id, **result}
|
| 264 |
|
|
|
|
| 25 |
from fastapi.middleware.cors import CORSMiddleware
|
| 26 |
from pydantic import BaseModel, Field
|
| 27 |
|
| 28 |
+
from src.api import persist
|
| 29 |
from src.api.db import FeedbackLog
|
| 30 |
from src.api.llm import is_configured
|
| 31 |
from src.api.ml_pipeline import MLPipeline
|
|
|
|
| 51 |
cfg = load_config(CONFIG_PATH)
|
| 52 |
state["cfg"] = cfg
|
| 53 |
state["pipeline"] = MLPipeline(cfg)
|
| 54 |
+
persist.restore(cfg["paths"]["feedback_db"]) # before the DB is opened
|
| 55 |
state["log"] = FeedbackLog(cfg["paths"]["feedback_db"])
|
| 56 |
+
persist.start_sync(cfg["paths"]["feedback_db"])
|
| 57 |
state["uploads"] = UploadStore(cfg["paths"].get("upload_dir", "cache/uploads"))
|
| 58 |
|
| 59 |
|
|
|
|
| 81 |
)
|
| 82 |
|
| 83 |
|
| 84 |
+
def is_probe(http: Request) -> bool:
|
| 85 |
+
"""Monitoring traffic (scripts/healthcheck.py) is logged but kept out of
|
| 86 |
+
the v2 metrics - otherwise every health check counts as a user retry."""
|
| 87 |
+
return http.headers.get("X-ResearchOS-Probe") == "1"
|
| 88 |
+
|
| 89 |
+
|
| 90 |
class AskRequest(BaseModel):
|
| 91 |
query: str = Field(min_length=3, max_length=1000)
|
| 92 |
top_k: int = Field(default=6, ge=1, le=20)
|
|
|
|
| 167 |
|
| 168 |
|
| 169 |
@app.post("/papers")
|
| 170 |
+
def papers(request: PapersRequest, http: Request) -> dict[str, Any]:
|
| 171 |
"""Topic in, ranked papers out (not passages)."""
|
| 172 |
pipeline: MLPipeline = state["pipeline"]
|
| 173 |
log: FeedbackLog = state["log"]
|
|
|
|
| 189 |
source=result.get("source"),
|
| 190 |
diagnosis=result.get("diagnosis"),
|
| 191 |
retry_of=request.retry_of,
|
| 192 |
+
probe=is_probe(http),
|
| 193 |
)
|
| 194 |
return {"query_id": query_id, **result}
|
| 195 |
|
| 196 |
|
| 197 |
@app.post("/ask")
|
| 198 |
+
def ask(request: AskRequest, http: Request) -> dict[str, Any]:
|
| 199 |
"""Question answering, logged."""
|
| 200 |
pipeline: MLPipeline = state["pipeline"]
|
| 201 |
log: FeedbackLog = state["log"]
|
|
|
|
| 214 |
source=result.get("source"),
|
| 215 |
diagnosis=result.get("diagnosis"),
|
| 216 |
retry_of=request.retry_of,
|
| 217 |
+
probe=is_probe(http),
|
| 218 |
)
|
| 219 |
return {"query_id": query_id, **result}
|
| 220 |
|
| 221 |
|
| 222 |
@app.post("/explain")
|
| 223 |
+
def explain(request: ExplainRequest, http: Request) -> dict[str, Any]:
|
| 224 |
"""Resolve a citation to its paper and explain it in plain terms."""
|
| 225 |
pipeline: MLPipeline = state["pipeline"]
|
| 226 |
log: FeedbackLog = state["log"]
|
|
|
|
| 270 |
source=result.get("source"),
|
| 271 |
diagnosis=result.get("diagnosis"),
|
| 272 |
retry_of=request.retry_of,
|
| 273 |
+
probe=is_probe(http),
|
| 274 |
)
|
| 275 |
return {"query_id": query_id, **result}
|
| 276 |
|
src/api/persist.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Keep the feedback database across restarts of a free Hugging Face Space.
|
| 2 |
+
|
| 3 |
+
A free Space's disk is ephemeral: every restart, rebuild or sleep starts from
|
| 4 |
+
the repository again. The feedback database - queries, clicks, votes and the
|
| 5 |
+
v2 retry funnel, including the retried-then-clicked pairs meant to become
|
| 6 |
+
training data - would be wiped each time, so the live measurement could
|
| 7 |
+
never accumulate.
|
| 8 |
+
|
| 9 |
+
When FEEDBACK_REPO (a dataset repo id, e.g. "you/researchos-feedback") and
|
| 10 |
+
HF_TOKEN (a write token) are set as Space secrets, the database is restored
|
| 11 |
+
from that private dataset on boot and snapshotted back every few minutes.
|
| 12 |
+
Unset, nothing happens: local runs keep their file on a real disk anyway.
|
| 13 |
+
|
| 14 |
+
The snapshot uses SQLite's online backup API, so it is consistent even while
|
| 15 |
+
requests are writing; copying the file directly could capture a torn page.
|
| 16 |
+
It is only uploaded when the database actually changed.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import os
|
| 22 |
+
import shutil
|
| 23 |
+
import sqlite3
|
| 24 |
+
import tempfile
|
| 25 |
+
import threading
|
| 26 |
+
import time
|
| 27 |
+
from contextlib import closing
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
|
| 30 |
+
SYNC_EVERY_S = 600.0
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _settings() -> tuple[str, str] | None:
|
| 34 |
+
repo, token = os.environ.get("FEEDBACK_REPO"), os.environ.get("HF_TOKEN")
|
| 35 |
+
return (repo, token) if repo and token else None
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def restore(db_path: str) -> bool:
|
| 39 |
+
"""Pull the last snapshot down before the app opens the database."""
|
| 40 |
+
settings = _settings()
|
| 41 |
+
if settings is None or Path(db_path).exists():
|
| 42 |
+
return False
|
| 43 |
+
repo, token = settings
|
| 44 |
+
try:
|
| 45 |
+
from huggingface_hub import hf_hub_download
|
| 46 |
+
|
| 47 |
+
cached = hf_hub_download(repo, Path(db_path).name, repo_type="dataset", token=token)
|
| 48 |
+
Path(db_path).parent.mkdir(parents=True, exist_ok=True)
|
| 49 |
+
shutil.copyfile(cached, db_path)
|
| 50 |
+
print(f"[persist] restored {db_path} from {repo}", flush=True)
|
| 51 |
+
return True
|
| 52 |
+
except Exception as exc: # noqa: BLE001 - first boot has nothing to restore
|
| 53 |
+
print(f"[persist] nothing restored ({type(exc).__name__}); starting fresh", flush=True)
|
| 54 |
+
return False
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _fingerprint(db_path: str) -> tuple[int, ...]:
|
| 58 |
+
# closing(): sqlite3's own context manager commits but never closes.
|
| 59 |
+
with closing(sqlite3.connect(db_path)) as conn:
|
| 60 |
+
return tuple(
|
| 61 |
+
conn.execute(f"SELECT COALESCE(MAX(id), 0) FROM {t}").fetchone()[0]
|
| 62 |
+
for t in ("queries", "citation_clicks", "votes", "errors")
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def snapshot_once(db_path: str, repo: str, token: str, last: tuple | None) -> tuple | None:
|
| 67 |
+
"""Upload a consistent copy if anything changed. Returns the new fingerprint."""
|
| 68 |
+
current = _fingerprint(db_path)
|
| 69 |
+
if current == last:
|
| 70 |
+
return last
|
| 71 |
+
from huggingface_hub import HfApi
|
| 72 |
+
|
| 73 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 74 |
+
snap = Path(tmp) / Path(db_path).name
|
| 75 |
+
with closing(sqlite3.connect(db_path)) as src, closing(sqlite3.connect(snap)) as dst:
|
| 76 |
+
src.backup(dst)
|
| 77 |
+
api = HfApi(token=token)
|
| 78 |
+
api.create_repo(repo, repo_type="dataset", private=True, exist_ok=True)
|
| 79 |
+
api.upload_file(path_or_fileobj=str(snap), path_in_repo=snap.name, repo_id=repo,
|
| 80 |
+
repo_type="dataset", commit_message="feedback snapshot")
|
| 81 |
+
return current
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def start_sync(db_path: str, every_s: float = SYNC_EVERY_S) -> threading.Thread | None:
|
| 85 |
+
"""Snapshot in the background for the life of the process."""
|
| 86 |
+
settings = _settings()
|
| 87 |
+
if settings is None:
|
| 88 |
+
return None
|
| 89 |
+
repo, token = settings
|
| 90 |
+
|
| 91 |
+
def loop() -> None:
|
| 92 |
+
last = None
|
| 93 |
+
while True:
|
| 94 |
+
time.sleep(every_s)
|
| 95 |
+
try:
|
| 96 |
+
last = snapshot_once(db_path, repo, token, last)
|
| 97 |
+
except Exception as exc: # noqa: BLE001 - never take the app down
|
| 98 |
+
print(f"[persist] snapshot failed: {type(exc).__name__}: {exc}", flush=True)
|
| 99 |
+
|
| 100 |
+
thread = threading.Thread(target=loop, name="feedback-sync", daemon=True)
|
| 101 |
+
thread.start()
|
| 102 |
+
print(f"[persist] syncing {db_path} to {repo} every {every_s / 60:.0f} min", flush=True)
|
| 103 |
+
return thread
|