Spaces:
Sleeping

PERDYPTO commited on
Commit
94cfb3d
·
verified ·
1 Parent(s): 742c2d4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -53
app.py CHANGED
@@ -10,29 +10,25 @@ from contextlib import asynccontextmanager
10
 
11
  from fastapi import FastAPI, Query, HTTPException, Request
12
  from fastapi.middleware.gzip import GZipMiddleware
 
13
  from fastapi.responses import HTMLResponse, JSONResponse
14
  from fastapi.staticfiles import StaticFiles
15
  from huggingface_hub import download_bucket_files, batch_bucket_files
16
 
17
- # ─── Optional ultra-fast JSON ───────────────────────────────────────────────
18
- try:
19
- import orjson
20
- class ORJSONResponse(JSONResponse):
21
- media_type = "application/json"
22
- def render(self, content: Any) -> bytes:
23
- return orjson.dumps(content, option=orjson.OPT_SERIALIZE_NUMPY)
24
- json_response = ORJSONResponse
25
- except ImportError:
26
- json_response = JSONResponse
27
 
28
  TOKEN = os.environ.get("HF_TOKEN", "")
29
  SOURCE_BUCKET = "PERDYPTO/db_snapshot"
30
  DB_PATH_IN_BUCKET = "github_pipeline.db"
31
 
32
- # ─── State ──────────────────────────────────────────────────────────────────
33
  _status = {"state": "starting", "last_refresh": None, "db_size_mb": 0}
34
- _db_lock = threading.Lock() # for connection mutation
35
- _async_lock = asyncio.Lock() # for async refresh coordination
36
  _conn: Optional[sqlite3.Connection] = None
37
  _local_db_file: Optional[str] = None
38
 
@@ -47,29 +43,24 @@ LEFT JOIN metadata m ON m.repo_id = r.repo_id
47
 
48
  BOOL_FIELDS = {"archived", "disabled", "is_fork", "is_template"}
49
 
50
- # Simple TTL cache for query bursts (HF Spaces often gets repeated identical reqs)
51
  _query_cache: dict[tuple, tuple[Any, float]] = {}
52
  _CACHE_TTL_SEC = 8.0
53
  _MAX_CACHE_ENTRIES = 200
54
-
55
- # Pre-compiled select SQL (rebuilt on refresh)
56
  _SELECT_SQL: str = ""
57
 
58
- # ─── SQLite Optimizations ───────────────────────────────────────────────────
59
  _READ_PRAGMAS = [
60
- ("PRAGMA journal_mode = OFF", None), # No journal needed for RO
61
- ("PRAGMA synchronous = OFF", None), # Faster, safe for read-only
62
- ("PRAGMA cache_size = -262144", None), # 256 MB page cache
63
  ("PRAGMA temp_store = MEMORY", None),
64
- ("PRAGMA mmap_size = 30000000000", None), # 30 GB virtual mmap
65
  ("PRAGMA query_only = ON", None),
66
- ("PRAGMA threads = 4", None), # Allow background reads
67
- ("PRAGMA read_uncommitted = 1", None), # Less locking overhead
68
  ]
69
 
70
- # ─── Helpers ────────────────────────────────────────────────────────────────
71
  def _run_sync(fn, *args, **kwargs):
72
- """Run blocking code in the default thread pool (avoids event-loop blocking)."""
73
  return asyncio.get_event_loop().run_in_executor(None, lambda: fn(*args, **kwargs))
74
 
75
 
@@ -90,7 +81,6 @@ def _build_field_map(conn: sqlite3.Connection):
90
  fmap[c] = f"m.{c}"
91
  FIELD_MAP = fmap
92
 
93
- # Pre-build the giant SELECT once
94
  cols = [f"r.{c}" for c in _repo_ids_columns] + [
95
  f"m.{c}" for c in _metadata_columns if c != "repo_id"
96
  ]
@@ -98,7 +88,6 @@ def _build_field_map(conn: sqlite3.Connection):
98
 
99
 
100
  def _ensure_indexes(conn: sqlite3.Connection):
101
- """Create covering indexes if they don't exist — massive speed-up for filtering."""
102
  cur = conn.cursor()
103
  idx_stmts = [
104
  "CREATE INDEX IF NOT EXISTS idx_meta_lang ON metadata(primary_language)",
@@ -112,7 +101,7 @@ def _ensure_indexes(conn: sqlite3.Connection):
112
  try:
113
  cur.execute(stmt)
114
  except sqlite3.OperationalError:
115
- pass # may fail on read-only uri for repo_ids indexes; that's ok
116
  conn.commit()
117
 
118
 
@@ -129,12 +118,11 @@ def _refresh_db_sync():
129
 
130
  db_uri = f"file:{local_db_path}?mode=ro"
131
  new_conn = sqlite3.connect(db_uri, uri=True, check_same_thread=False)
132
- new_conn.row_factory = sqlite3.Row # enables column-name access
133
 
134
  for pragma, _ in _READ_PRAGMAS:
135
  new_conn.execute(pragma)
136
 
137
- # Try to create indexes (will silently fail on read-only if they exist)
138
  _ensure_indexes(new_conn)
139
  _build_field_map(new_conn)
140
 
@@ -146,7 +134,7 @@ def _refresh_db_sync():
146
 
147
  size_mb = round(os.path.getsize(local_db_path) / (1024 * 1024), 2)
148
  _status.update({"state": "ready", "last_refresh": time.time(), "db_size_mb": size_mb})
149
- _query_cache.clear() # invalidate on refresh
150
  print(f"[load] DB ready ({size_mb} MB).")
151
 
152
 
@@ -166,7 +154,6 @@ def _get_conn() -> sqlite3.Connection:
166
  return _conn
167
 
168
 
169
- # ─── Caching ────────────────────────────────────────────────────────────────
170
  def _cache_key(*args, **kwargs) -> tuple:
171
  return args + tuple(sorted(kwargs.items()))
172
 
@@ -184,7 +171,6 @@ def _get_cached(key: tuple):
184
 
185
  def _set_cached(key: tuple, data: Any):
186
  if len(_query_cache) >= _MAX_CACHE_ENTRIES:
187
- # simple FIFO eviction
188
  try:
189
  _query_cache.pop(next(iter(_query_cache)))
190
  except StopIteration:
@@ -192,7 +178,6 @@ def _set_cached(key: tuple, data: Any):
192
  _query_cache[key] = (data, time.time())
193
 
194
 
195
- # ─── Lifespan ───────────────────────────────────────────────────────────────
196
  @asynccontextmanager
197
  async def lifespan(app: FastAPI):
198
  try:
@@ -206,17 +191,14 @@ async def lifespan(app: FastAPI):
206
 
207
 
208
  app = FastAPI(title="GitHub Pipeline DB API", lifespan=lifespan)
209
- app.add_middleware(GZipMiddleware, minimum_size=500) # compress responses >500B
210
-
211
- # Serve the cosmic frontend
212
- app.mount("/static", StaticFiles(directory="static"), name="static")
213
-
214
-
215
- # ─── Endpoints ──────────────────────────────────────────────────────────────
216
- @app.get("/", response_class=HTMLResponse)
217
- async def root():
218
- with open("static/index.html", "r", encoding="utf-8") as f:
219
- return f.read()
220
 
221
 
222
  @app.get("/api/health")
@@ -235,7 +217,7 @@ async def health():
235
  async def schema():
236
  if _conn is None:
237
  raise HTTPException(503, "db not loaded yet")
238
- return json_response({
239
  "repo_ids_columns": _repo_ids_columns,
240
  "metadata_columns": _metadata_columns,
241
  "queryable_fields": sorted(FIELD_MAP.keys()),
@@ -245,7 +227,7 @@ async def schema():
245
 
246
  @app.get("/api/query")
247
  async def query(
248
- sort_by: str = Query("stars", description="Field to sort by"),
249
  order: str = Query("desc", pattern="^(?i)(asc|desc)$"),
250
  limit: int = Query(10, ge=1, le=1000),
251
  offset: int = Query(0, ge=0),
@@ -263,7 +245,7 @@ async def query(
263
  archived, disabled, is_template, status, min_stars, max_stars, search)
264
  cached = _get_cached(cache_key)
265
  if cached is not None:
266
- return json_response(cached)
267
 
268
  if sort_by not in FIELD_MAP:
269
  raise HTTPException(400, f"invalid sort_by '{sort_by}'. See /api/schema.")
@@ -338,7 +320,7 @@ async def query(
338
  "results": rows,
339
  }
340
  _set_cached(cache_key, payload)
341
- return json_response(payload)
342
 
343
 
344
  @app.get("/api/languages")
@@ -346,7 +328,7 @@ async def languages():
346
  cache_key = ("languages",)
347
  cached = _get_cached(cache_key)
348
  if cached is not None:
349
- return json_response(cached)
350
 
351
  def _execute():
352
  conn = _get_conn()
@@ -362,7 +344,7 @@ async def languages():
362
 
363
  data = await _run_sync(_execute)
364
  _set_cached(cache_key, data)
365
- return json_response(data)
366
 
367
 
368
  @app.get("/api/stats")
@@ -370,7 +352,7 @@ async def stats():
370
  cache_key = ("stats",)
371
  cached = _get_cached(cache_key)
372
  if cached is not None:
373
- return json_response(cached)
374
 
375
  def _execute():
376
  conn = _get_conn()
@@ -392,7 +374,7 @@ async def stats():
392
 
393
  data = await _run_sync(_execute)
394
  _set_cached(cache_key, data)
395
- return json_response(data)
396
 
397
 
398
  @app.post("/api/refresh")
 
10
 
11
  from fastapi import FastAPI, Query, HTTPException, Request
12
  from fastapi.middleware.gzip import GZipMiddleware
13
+ from fastapi.middleware.cors import CORSMiddleware
14
  from fastapi.responses import HTMLResponse, JSONResponse
15
  from fastapi.staticfiles import StaticFiles
16
  from huggingface_hub import download_bucket_files, batch_bucket_files
17
 
18
+ import orjson
19
+
20
+ class ORJSONResponse(JSONResponse):
21
+ media_type = "application/json"
22
+ def render(self, content: Any) -> bytes:
23
+ return orjson.dumps(content, option=orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_NON_STR_KEYS)
 
 
 
 
24
 
25
  TOKEN = os.environ.get("HF_TOKEN", "")
26
  SOURCE_BUCKET = "PERDYPTO/db_snapshot"
27
  DB_PATH_IN_BUCKET = "github_pipeline.db"
28
 
 
29
  _status = {"state": "starting", "last_refresh": None, "db_size_mb": 0}
30
+ _db_lock = threading.Lock()
31
+ _async_lock = asyncio.Lock()
32
  _conn: Optional[sqlite3.Connection] = None
33
  _local_db_file: Optional[str] = None
34
 
 
43
 
44
  BOOL_FIELDS = {"archived", "disabled", "is_fork", "is_template"}
45
 
 
46
  _query_cache: dict[tuple, tuple[Any, float]] = {}
47
  _CACHE_TTL_SEC = 8.0
48
  _MAX_CACHE_ENTRIES = 200
 
 
49
  _SELECT_SQL: str = ""
50
 
 
51
  _READ_PRAGMAS = [
52
+ ("PRAGMA journal_mode = OFF", None),
53
+ ("PRAGMA synchronous = OFF", None),
54
+ ("PRAGMA cache_size = -262144", None),
55
  ("PRAGMA temp_store = MEMORY", None),
56
+ ("PRAGMA mmap_size = 30000000000", None),
57
  ("PRAGMA query_only = ON", None),
58
+ ("PRAGMA threads = 4", None),
59
+ ("PRAGMA read_uncommitted = 1", None),
60
  ]
61
 
62
+
63
  def _run_sync(fn, *args, **kwargs):
 
64
  return asyncio.get_event_loop().run_in_executor(None, lambda: fn(*args, **kwargs))
65
 
66
 
 
81
  fmap[c] = f"m.{c}"
82
  FIELD_MAP = fmap
83
 
 
84
  cols = [f"r.{c}" for c in _repo_ids_columns] + [
85
  f"m.{c}" for c in _metadata_columns if c != "repo_id"
86
  ]
 
88
 
89
 
90
  def _ensure_indexes(conn: sqlite3.Connection):
 
91
  cur = conn.cursor()
92
  idx_stmts = [
93
  "CREATE INDEX IF NOT EXISTS idx_meta_lang ON metadata(primary_language)",
 
101
  try:
102
  cur.execute(stmt)
103
  except sqlite3.OperationalError:
104
+ pass
105
  conn.commit()
106
 
107
 
 
118
 
119
  db_uri = f"file:{local_db_path}?mode=ro"
120
  new_conn = sqlite3.connect(db_uri, uri=True, check_same_thread=False)
121
+ new_conn.row_factory = sqlite3.Row
122
 
123
  for pragma, _ in _READ_PRAGMAS:
124
  new_conn.execute(pragma)
125
 
 
126
  _ensure_indexes(new_conn)
127
  _build_field_map(new_conn)
128
 
 
134
 
135
  size_mb = round(os.path.getsize(local_db_path) / (1024 * 1024), 2)
136
  _status.update({"state": "ready", "last_refresh": time.time(), "db_size_mb": size_mb})
137
+ _query_cache.clear()
138
  print(f"[load] DB ready ({size_mb} MB).")
139
 
140
 
 
154
  return _conn
155
 
156
 
 
157
  def _cache_key(*args, **kwargs) -> tuple:
158
  return args + tuple(sorted(kwargs.items()))
159
 
 
171
 
172
  def _set_cached(key: tuple, data: Any):
173
  if len(_query_cache) >= _MAX_CACHE_ENTRIES:
 
174
  try:
175
  _query_cache.pop(next(iter(_query_cache)))
176
  except StopIteration:
 
178
  _query_cache[key] = (data, time.time())
179
 
180
 
 
181
  @asynccontextmanager
182
  async def lifespan(app: FastAPI):
183
  try:
 
191
 
192
 
193
  app = FastAPI(title="GitHub Pipeline DB API", lifespan=lifespan)
194
+ app.add_middleware(GZipMiddleware, minimum_size=500)
195
+ app.add_middleware(
196
+ CORSMiddleware,
197
+ allow_origins=["*"],
198
+ allow_credentials=True,
199
+ allow_methods=["*"],
200
+ allow_headers=["*"],
201
+ )
 
 
 
202
 
203
 
204
  @app.get("/api/health")
 
217
  async def schema():
218
  if _conn is None:
219
  raise HTTPException(503, "db not loaded yet")
220
+ return ORJSONResponse({
221
  "repo_ids_columns": _repo_ids_columns,
222
  "metadata_columns": _metadata_columns,
223
  "queryable_fields": sorted(FIELD_MAP.keys()),
 
227
 
228
  @app.get("/api/query")
229
  async def query(
230
+ sort_by: str = Query("stars"),
231
  order: str = Query("desc", pattern="^(?i)(asc|desc)$"),
232
  limit: int = Query(10, ge=1, le=1000),
233
  offset: int = Query(0, ge=0),
 
245
  archived, disabled, is_template, status, min_stars, max_stars, search)
246
  cached = _get_cached(cache_key)
247
  if cached is not None:
248
+ return ORJSONResponse(cached)
249
 
250
  if sort_by not in FIELD_MAP:
251
  raise HTTPException(400, f"invalid sort_by '{sort_by}'. See /api/schema.")
 
320
  "results": rows,
321
  }
322
  _set_cached(cache_key, payload)
323
+ return ORJSONResponse(payload)
324
 
325
 
326
  @app.get("/api/languages")
 
328
  cache_key = ("languages",)
329
  cached = _get_cached(cache_key)
330
  if cached is not None:
331
+ return ORJSONResponse(cached)
332
 
333
  def _execute():
334
  conn = _get_conn()
 
344
 
345
  data = await _run_sync(_execute)
346
  _set_cached(cache_key, data)
347
+ return ORJSONResponse(data)
348
 
349
 
350
  @app.get("/api/stats")
 
352
  cache_key = ("stats",)
353
  cached = _get_cached(cache_key)
354
  if cached is not None:
355
+ return ORJSONResponse(cached)
356
 
357
  def _execute():
358
  conn = _get_conn()
 
374
 
375
  data = await _run_sync(_execute)
376
  _set_cached(cache_key, data)
377
+ return ORJSONResponse(data)
378
 
379
 
380
  @app.post("/api/refresh")