Spaces:
Sleeping

PERDYPTO commited on
Commit
210eb28
·
verified ·
1 Parent(s): 12a4931

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -402
app.py DELETED
@@ -1,402 +0,0 @@
1
- import os
2
- import sqlite3
3
- import tempfile
4
- import threading
5
- import asyncio
6
- import time
7
- from typing import Optional, Any
8
- from functools import lru_cache
9
- from contextlib import asynccontextmanager
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
-
35
- _metadata_columns: list[str] = []
36
- _repo_ids_columns: list[str] = []
37
- FIELD_MAP: dict[str, str] = {}
38
-
39
- JOIN_SQL = """
40
- FROM repo_ids r
41
- LEFT JOIN metadata m ON m.repo_id = r.repo_id
42
- """
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
-
67
- def _build_field_map(conn: sqlite3.Connection):
68
- global _metadata_columns, _repo_ids_columns, FIELD_MAP, _SELECT_SQL
69
- cur = conn.cursor()
70
- cur.execute('PRAGMA table_info("repo_ids")')
71
- _repo_ids_columns = [c[1] for c in cur.fetchall()]
72
- cur.execute('PRAGMA table_info("metadata")')
73
- _metadata_columns = [c[1] for c in cur.fetchall()]
74
-
75
- fmap = {}
76
- for c in _repo_ids_columns:
77
- fmap[c] = f"r.{c}"
78
- for c in _metadata_columns:
79
- if c == "repo_id":
80
- continue
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
- ]
87
- _SELECT_SQL = ", ".join(cols)
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)",
94
- "CREATE INDEX IF NOT EXISTS idx_meta_stars ON metadata(stars)",
95
- "CREATE INDEX IF NOT EXISTS idx_meta_fork ON metadata(is_fork)",
96
- "CREATE INDEX IF NOT EXISTS idx_meta_arch ON metadata(archived)",
97
- "CREATE INDEX IF NOT EXISTS idx_meta_status ON repo_ids(status)",
98
- "CREATE INDEX IF NOT EXISTS idx_meta_search ON metadata(repo_id, description)",
99
- ]
100
- for stmt in idx_stmts:
101
- try:
102
- cur.execute(stmt)
103
- except sqlite3.OperationalError:
104
- pass
105
- conn.commit()
106
-
107
-
108
- def _refresh_db_sync():
109
- global _conn, _local_db_file, _status
110
- workdir = tempfile.mkdtemp()
111
- local_db_path = os.path.join(workdir, os.path.basename(DB_PATH_IN_BUCKET))
112
-
113
- download_bucket_files(
114
- SOURCE_BUCKET,
115
- [(DB_PATH_IN_BUCKET, local_db_path)],
116
- token=TOKEN,
117
- )
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
-
129
- with _db_lock:
130
- if _conn:
131
- _conn.close()
132
- _conn = new_conn
133
- _local_db_file = local_db_path
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
-
141
- def _push_db_sync():
142
- if not _local_db_file or not os.path.exists(_local_db_file):
143
- raise HTTPException(400, "No local DB available to push")
144
- batch_bucket_files(
145
- SOURCE_BUCKET,
146
- add=[(_local_db_file, DB_PATH_IN_BUCKET)],
147
- token=TOKEN,
148
- )
149
-
150
-
151
- def _get_conn() -> sqlite3.Connection:
152
- if _conn is None:
153
- raise HTTPException(503, "db not loaded yet")
154
- return _conn
155
-
156
-
157
- def _cache_key(*args, **kwargs) -> tuple:
158
- return args + tuple(sorted(kwargs.items()))
159
-
160
-
161
- def _get_cached(key: tuple):
162
- entry = _query_cache.get(key)
163
- if entry is None:
164
- return None
165
- data, ts = entry
166
- if time.time() - ts > _CACHE_TTL_SEC:
167
- del _query_cache[key]
168
- return None
169
- return data
170
-
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:
177
- pass
178
- _query_cache[key] = (data, time.time())
179
-
180
-
181
- @asynccontextmanager
182
- async def lifespan(app: FastAPI):
183
- try:
184
- await _run_sync(_refresh_db_sync)
185
- except Exception as e:
186
- _status["state"] = f"error: {e}"
187
- print(f"[fatal] {e}")
188
- yield
189
- if _conn:
190
- _conn.close()
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")
205
- async def health():
206
- return {
207
- "status": _status,
208
- "endpoints": {
209
- "/api/query": "Configurable query endpoint. See /api/schema for available fields.",
210
- "/api/schema": "Lists all filterable/sortable fields and table columns.",
211
- "/api/refresh": "POST — re-download the db from the bucket.",
212
- },
213
- }
214
-
215
-
216
- @app.get("/api/schema")
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()),
224
- "boolean_fields": sorted(BOOL_FIELDS & set(FIELD_MAP.keys())),
225
- })
226
-
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),
234
- language: Optional[str] = Query(None),
235
- is_fork: Optional[bool] = Query(None),
236
- archived: Optional[bool] = Query(None),
237
- disabled: Optional[bool] = Query(None),
238
- is_template: Optional[bool] = Query(None),
239
- status: Optional[str] = Query(None),
240
- min_stars: Optional[int] = Query(None),
241
- max_stars: Optional[int] = Query(None),
242
- search: Optional[str] = Query(None),
243
- ):
244
- cache_key = _cache_key("query", sort_by, order, limit, offset, language, is_fork,
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.")
252
-
253
- order_sql = "ASC" if order.lower() == "asc" else "DESC"
254
- sort_col = FIELD_MAP[sort_by]
255
-
256
- where: list[str] = []
257
- params: list = []
258
-
259
- if language:
260
- where.append("m.primary_language = ?")
261
- params.append(language)
262
- if is_fork is not None:
263
- where.append("m.is_fork = ?")
264
- params.append(1 if is_fork else 0)
265
- if archived is not None:
266
- where.append("m.archived = ?")
267
- params.append(1 if archived else 0)
268
- if disabled is not None:
269
- where.append("m.disabled = ?")
270
- params.append(1 if disabled else 0)
271
- if is_template is not None:
272
- where.append("m.is_template = ?")
273
- params.append(1 if is_template else 0)
274
- if status:
275
- where.append("r.status = ?")
276
- params.append(status)
277
- if min_stars is not None:
278
- where.append("m.stars >= ?")
279
- params.append(min_stars)
280
- if max_stars is not None:
281
- where.append("m.stars <= ?")
282
- params.append(max_stars)
283
- if search:
284
- where.append("(r.repo_path LIKE ? OR m.description LIKE ?)")
285
- like = f"%{search}%"
286
- params.extend([like, like])
287
-
288
- where_sql = f"WHERE {' AND '.join(where)}" if where else ""
289
-
290
- sql = f"""
291
- SELECT {_SELECT_SQL}
292
- {JOIN_SQL}
293
- {where_sql}
294
- ORDER BY {sort_col} {order_sql} NULLS LAST
295
- LIMIT ? OFFSET ?
296
- """
297
- params.extend([limit, offset])
298
-
299
- def _execute():
300
- conn = _get_conn()
301
- cur = conn.cursor()
302
- try:
303
- cur.execute(sql, params)
304
- except sqlite3.OperationalError:
305
- cur.execute(sql.replace("NULLS LAST", ""), params)
306
- rows = [dict(r) for r in cur.fetchall()]
307
- return rows
308
-
309
- rows = await _run_sync(_execute)
310
-
311
- payload = {
312
- "count": len(rows),
313
- "sort_by": sort_by,
314
- "order": order_sql,
315
- "filters": {
316
- "language": language, "is_fork": is_fork, "archived": archived,
317
- "disabled": disabled, "is_template": is_template, "status": status,
318
- "min_stars": min_stars, "max_stars": max_stars, "search": search,
319
- },
320
- "results": rows,
321
- }
322
- _set_cached(cache_key, payload)
323
- return ORJSONResponse(payload)
324
-
325
-
326
- @app.get("/api/languages")
327
- async def 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()
335
- cur = conn.cursor()
336
- cur.execute("""
337
- SELECT m.primary_language AS language, COUNT(*) AS count
338
- FROM metadata m
339
- WHERE m.primary_language IS NOT NULL AND m.primary_language != ''
340
- GROUP BY m.primary_language
341
- ORDER BY count DESC
342
- """)
343
- return {"languages": [{"language": r[0], "count": r[1]} for r in cur.fetchall()]}
344
-
345
- data = await _run_sync(_execute)
346
- _set_cached(cache_key, data)
347
- return ORJSONResponse(data)
348
-
349
-
350
- @app.get("/api/stats")
351
- async def 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()
359
- cur = conn.cursor()
360
- cur.execute("SELECT COUNT(*) FROM repo_ids")
361
- total_repos = cur.fetchone()[0]
362
- cur.execute("SELECT COUNT(*) FROM metadata")
363
- total_metadata = cur.fetchone()[0]
364
- cur.execute("SELECT COUNT(*) FROM metadata WHERE is_fork = 1")
365
- forks = cur.fetchone()[0]
366
- cur.execute("SELECT COUNT(*) FROM metadata WHERE archived = 1")
367
- archived = cur.fetchone()[0]
368
- return {
369
- "total_repos": total_repos,
370
- "total_metadata_rows": total_metadata,
371
- "forks": forks,
372
- "archived": archived,
373
- }
374
-
375
- data = await _run_sync(_execute)
376
- _set_cached(cache_key, data)
377
- return ORJSONResponse(data)
378
-
379
-
380
- @app.post("/api/refresh")
381
- async def refresh():
382
- async with _async_lock:
383
- try:
384
- await _run_sync(_refresh_db_sync)
385
- return {"status": "ok", "state": _status["state"]}
386
- except Exception as e:
387
- _status["state"] = f"error: {e}"
388
- raise HTTPException(500, str(e))
389
-
390
-
391
- @app.post("/api/push")
392
- async def push():
393
- try:
394
- await _run_sync(_push_db_sync)
395
- return {"status": "ok"}
396
- except Exception as e:
397
- raise HTTPException(500, str(e))
398
-
399
-
400
- if __name__ == "__main__":
401
- import uvicorn
402
- uvicorn.run(app, host="0.0.0.0", port=7860)