Spaces:
Sleeping

PERDYPTO commited on
Commit
f68275b
·
verified ·
1 Parent(s): cfb18ef

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -284
app.py CHANGED
@@ -5,10 +5,9 @@ import threading
5
  from typing import Optional
6
 
7
  from fastapi import FastAPI, Query, HTTPException
8
- from fastapi.responses import HTMLResponse, JSONResponse
9
  from huggingface_hub import download_bucket_files, batch_bucket_files
10
 
11
- TOKEN = os.environ["HF_TOKEN"]
12
 
13
  SOURCE_BUCKET = "PERDYPTO/db_snapshot"
14
  DB_PATH_IN_BUCKET = "github_pipeline.db"
@@ -18,9 +17,9 @@ app = FastAPI(title="GitHub Pipeline DB API")
18
  _status = {"state": "starting"}
19
  _lock = threading.Lock()
20
 
21
- # In-memory sqlite connection, shared across requests (check_same_thread=False
22
- # because FastAPI may serve requests from different threads).
23
  _conn: Optional[sqlite3.Connection] = None
 
24
 
25
  # Columns that are safe to sort/filter by. Built dynamically from the actual
26
  # schema at load time so this stays correct even if the DB shape changes.
@@ -34,22 +33,12 @@ LEFT JOIN metadata m ON m.repo_id = r.repo_id
34
  """
35
 
36
  # Whitelisted sortable/filterable fields -> actual SQL column expression.
37
- # Populated after load_db_into_ram() inspects the schema.
38
  FIELD_MAP: dict[str, str] = {}
39
 
40
  # Fields that are boolean-ish (0/1) and get exposed as true/false filters.
41
  BOOL_FIELDS = {"archived", "disabled", "is_fork", "is_template"}
42
 
43
 
44
- def _load_db_bytes_to_memory(local_db_path: str) -> sqlite3.Connection:
45
- """Load a sqlite file fully into an in-memory sqlite database."""
46
- disk_conn = sqlite3.connect(local_db_path)
47
- mem_conn = sqlite3.connect(":memory:", check_same_thread=False)
48
- disk_conn.backup(mem_conn)
49
- disk_conn.close()
50
- return mem_conn
51
-
52
-
53
  def build_field_map(conn: sqlite3.Connection):
54
  global _metadata_columns, _repo_ids_columns, FIELD_MAP
55
  cur = conn.cursor()
@@ -71,8 +60,9 @@ def build_field_map(conn: sqlite3.Connection):
71
 
72
 
73
  def refresh_db():
74
- """Download the db from the HF bucket and load it fully into RAM."""
75
- global _conn
 
76
  workdir = tempfile.mkdtemp()
77
  local_db_path = os.path.join(workdir, os.path.basename(DB_PATH_IN_BUCKET))
78
 
@@ -84,44 +74,40 @@ def refresh_db():
84
  )
85
  print(f"[download] saved to {local_db_path}")
86
 
87
- print("[load] loading db fully into RAM (:memory:)")
88
- new_conn = _load_db_bytes_to_memory(local_db_path)
 
 
 
 
 
 
 
 
89
  build_field_map(new_conn)
90
 
91
  with _lock:
 
 
92
  _conn = new_conn
 
93
 
94
- print("[load] db is now in memory and ready to serve")
95
 
96
- try:
97
- os.remove(local_db_path)
98
- os.rmdir(workdir)
99
- except OSError:
100
- pass
101
 
102
-
103
- def push_db_back(conn: sqlite3.Connection):
104
- """Optional: persist the in-memory db back to disk then upload to bucket."""
105
- workdir = tempfile.mkdtemp()
106
- local_db_path = os.path.join(workdir, os.path.basename(DB_PATH_IN_BUCKET))
107
- disk_conn = sqlite3.connect(local_db_path)
108
- conn.backup(disk_conn)
109
- disk_conn.close()
110
 
111
  print(f"[upload] pushing db back to hf://buckets/{SOURCE_BUCKET}/{DB_PATH_IN_BUCKET}")
112
  batch_bucket_files(
113
  SOURCE_BUCKET,
114
- add=[(local_db_path, DB_PATH_IN_BUCKET)],
115
  token=TOKEN,
116
  )
117
  print("[upload] done")
118
 
119
- try:
120
- os.remove(local_db_path)
121
- os.rmdir(workdir)
122
- except OSError:
123
- pass
124
-
125
 
126
  @app.on_event("startup")
127
  def on_startup():
@@ -140,8 +126,7 @@ def health():
140
  "endpoints": {
141
  "/api/query": "Configurable query endpoint. See /api/schema for available fields.",
142
  "/api/schema": "Lists all filterable/sortable fields and table columns.",
143
- "/api/refresh": "POST — re-download the db from the bucket into RAM.",
144
- "/dashboard": "HTML dashboard UI for browsing the data.",
145
  },
146
  }
147
 
@@ -180,16 +165,6 @@ def query(
180
  max_stars: Optional[int] = Query(None, description="Maximum stars"),
181
  search: Optional[str] = Query(None, description="Substring search in repo_path/description"),
182
  ):
183
- """
184
- Fully configurable query endpoint over repo_ids + metadata (joined on repo_id).
185
-
186
- Examples:
187
- /api/query?sort_by=stars&order=desc&limit=10 -> top 10 most starred
188
- /api/query?sort_by=stars&order=asc&limit=10 -> top 10 least starred
189
- /api/query?sort_by=stars&order=desc&limit=10&language=Python -> top 10 starred Python repos
190
- /api/query?is_fork=false&archived=false&sort_by=forks_count -> non-fork, non-archived, by forks
191
- /api/query?sort_by=watchers_count&order=asc&limit=5 -> bottom 5 by watchers
192
- """
193
  conn = _get_conn()
194
 
195
  if sort_by not in FIELD_MAP:
@@ -278,7 +253,7 @@ def query(
278
 
279
  @app.get("/api/languages")
280
  def languages():
281
- """List distinct primary_language values with counts, for building UI filters."""
282
  conn = _get_conn()
283
  cur = conn.cursor()
284
  cur.execute(
@@ -315,7 +290,7 @@ def stats():
315
 
316
  @app.post("/api/refresh")
317
  def refresh():
318
- """Re-download the db from the bucket into RAM (does not touch the bucket)."""
319
  try:
320
  refresh_db()
321
  _status["state"] = "ready"
@@ -327,243 +302,14 @@ def refresh():
327
 
328
  @app.post("/api/push")
329
  def push():
330
- """Persist current in-memory db state back to the HF bucket."""
331
- conn = _get_conn()
332
  try:
333
- push_db_back(conn)
334
  return {"status": "ok"}
335
  except Exception as e:
336
  raise HTTPException(500, str(e))
337
 
338
 
339
- DASHBOARD_HTML = """
340
- <!DOCTYPE html>
341
- <html lang="en">
342
- <head>
343
- <meta charset="UTF-8">
344
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
345
- <title>GitHub Pipeline DB Explorer</title>
346
- <style>
347
- :root {
348
- --bg: #0d1117;
349
- --panel: #161b22;
350
- --border: #30363d;
351
- --text: #c9d1d9;
352
- --muted: #8b949e;
353
- --accent: #58a6ff;
354
- }
355
- * { box-sizing: border-box; }
356
- body {
357
- margin: 0;
358
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
359
- background: var(--bg);
360
- color: var(--text);
361
- padding: 24px;
362
- }
363
- h1 { font-size: 20px; margin-bottom: 4px; }
364
- p.sub { color: var(--muted); margin-top: 0; margin-bottom: 20px; font-size: 13px; }
365
- .panel {
366
- background: var(--panel);
367
- border: 1px solid var(--border);
368
- border-radius: 8px;
369
- padding: 16px;
370
- margin-bottom: 16px;
371
- }
372
- .controls {
373
- display: flex;
374
- flex-wrap: wrap;
375
- gap: 12px;
376
- align-items: flex-end;
377
- }
378
- .field { display: flex; flex-direction: column; gap: 4px; }
379
- .field label { font-size: 11px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.03em; }
380
- select, input {
381
- background: #010409;
382
- border: 1px solid var(--border);
383
- color: var(--text);
384
- padding: 6px 8px;
385
- border-radius: 6px;
386
- font-size: 13px;
387
- }
388
- button {
389
- background: var(--accent);
390
- color: #041424;
391
- border: none;
392
- padding: 8px 16px;
393
- border-radius: 6px;
394
- font-weight: 600;
395
- cursor: pointer;
396
- font-size: 13px;
397
- }
398
- button:hover { opacity: 0.9; }
399
- table { width: 100%; border-collapse: collapse; font-size: 13px; }
400
- th, td {
401
- text-align: left;
402
- padding: 8px 10px;
403
- border-bottom: 1px solid var(--border);
404
- white-space: nowrap;
405
- max-width: 320px;
406
- overflow: hidden;
407
- text-overflow: ellipsis;
408
- }
409
- th { color: var(--muted); font-weight: 600; position: sticky; top: 0; background: var(--panel); }
410
- tr:hover { background: #1c2128; }
411
- .stats { display: flex; gap: 24px; flex-wrap: wrap; }
412
- .stat { }
413
- .stat .num { font-size: 22px; font-weight: 700; color: var(--accent); }
414
- .stat .label { font-size: 11px; color: var(--muted); text-transform: uppercase; }
415
- .table-wrap { overflow: auto; max-height: 60vh; }
416
- a { color: var(--accent); text-decoration: none; }
417
- .badge { display:inline-block; padding: 2px 6px; border-radius: 4px; font-size: 11px; background:#21262d; color: var(--muted); }
418
- </style>
419
- </head>
420
- <body>
421
-
422
- <h1>GitHub Pipeline DB Explorer</h1>
423
- <p class="sub">Live view over the indexed sqlite db loaded in RAM. Powered by <code>/api/query</code>.</p>
424
-
425
- <div class="panel stats" id="stats">Loading stats...</div>
426
-
427
- <div class="panel">
428
- <div class="controls">
429
- <div class="field">
430
- <label>Sort by</label>
431
- <select id="sortBy">
432
- <option value="stars">Stars</option>
433
- <option value="forks_count">Forks</option>
434
- <option value="watchers_count">Watchers</option>
435
- <option value="pushed_at">Last pushed</option>
436
- <option value="num_files">Num files</option>
437
- <option value="repo_id">Repo ID</option>
438
- </select>
439
- </div>
440
- <div class="field">
441
- <label>Order</label>
442
- <select id="order">
443
- <option value="desc">Highest first</option>
444
- <option value="asc">Lowest first</option>
445
- </select>
446
- </div>
447
- <div class="field">
448
- <label>Limit</label>
449
- <input id="limit" type="number" value="10" min="1" max="1000">
450
- </div>
451
- <div class="field">
452
- <label>Language</label>
453
- <select id="language"><option value="">Any</option></select>
454
- </div>
455
- <div class="field">
456
- <label>Fork</label>
457
- <select id="isFork">
458
- <option value="">Any</option>
459
- <option value="true">Forks only</option>
460
- <option value="false">Non-forks only</option>
461
- </select>
462
- </div>
463
- <div class="field">
464
- <label>Archived</label>
465
- <select id="archived">
466
- <option value="">Any</option>
467
- <option value="true">Archived only</option>
468
- <option value="false">Non-archived only</option>
469
- </select>
470
- </div>
471
- <div class="field">
472
- <label>Search</label>
473
- <input id="search" type="text" placeholder="repo path / description">
474
- </div>
475
- <button onclick="loadData()">Run query</button>
476
- </div>
477
- </div>
478
-
479
- <div class="panel">
480
- <div class="table-wrap">
481
- <table id="resultsTable">
482
- <thead><tr id="tableHead"></tr></thead>
483
- <tbody id="tableBody"><tr><td>Loading...</td></tr></tbody>
484
- </table>
485
- </div>
486
- </div>
487
-
488
- <p class="sub">Direct API access: <a href="/api/query?sort_by=stars&order=desc&limit=10">/api/query</a> &middot; <a href="/api/schema">/api/schema</a> &middot; <a href="/api/languages">/api/languages</a></p>
489
-
490
- <script>
491
- async function loadStats() {
492
- const res = await fetch('/api/stats');
493
- const data = await res.json();
494
- document.getElementById('stats').innerHTML = `
495
- <div class="stat"><div class="num">${data.total_repos}</div><div class="label">Total repos</div></div>
496
- <div class="stat"><div class="num">${data.total_metadata_rows}</div><div class="label">With metadata</div></div>
497
- <div class="stat"><div class="num">${data.forks}</div><div class="label">Forks</div></div>
498
- <div class="stat"><div class="num">${data.archived}</div><div class="label">Archived</div></div>
499
- `;
500
- }
501
-
502
- async function loadLanguages() {
503
- const res = await fetch('/api/languages');
504
- const data = await res.json();
505
- const sel = document.getElementById('language');
506
- data.languages.forEach(l => {
507
- const opt = document.createElement('option');
508
- opt.value = l.language;
509
- opt.textContent = `${l.language} (${l.count})`;
510
- sel.appendChild(opt);
511
- });
512
- }
513
-
514
- async function loadData() {
515
- const params = new URLSearchParams();
516
- params.set('sort_by', document.getElementById('sortBy').value);
517
- params.set('order', document.getElementById('order').value);
518
- params.set('limit', document.getElementById('limit').value || 10);
519
-
520
- const lang = document.getElementById('language').value;
521
- if (lang) params.set('language', lang);
522
-
523
- const isFork = document.getElementById('isFork').value;
524
- if (isFork) params.set('is_fork', isFork);
525
-
526
- const archived = document.getElementById('archived').value;
527
- if (archived) params.set('archived', archived);
528
-
529
- const search = document.getElementById('search').value;
530
- if (search) params.set('search', search);
531
-
532
- const res = await fetch('/api/query?' + params.toString());
533
- const data = await res.json();
534
- renderTable(data.results);
535
- }
536
-
537
- function renderTable(rows) {
538
- const head = document.getElementById('tableHead');
539
- const body = document.getElementById('tableBody');
540
- if (!rows.length) {
541
- head.innerHTML = '';
542
- body.innerHTML = '<tr><td>No results</td></tr>';
543
- return;
544
- }
545
- const cols = Object.keys(rows[0]);
546
- head.innerHTML = cols.map(c => `<th>${c}</th>`).join('');
547
- body.innerHTML = rows.map(r =>
548
- '<tr>' + cols.map(c => `<td title="${(r[c] ?? '')}">${(r[c] ?? '')}</td>`).join('') + '</tr>'
549
- ).join('');
550
- }
551
-
552
- loadStats();
553
- loadLanguages();
554
- loadData();
555
- </script>
556
-
557
- </body>
558
- </html>
559
- """
560
-
561
-
562
- @app.get("/dashboard", response_class=HTMLResponse)
563
- def dashboard():
564
- return HTMLResponse(content=DASHBOARD_HTML)
565
-
566
-
567
  if __name__ == "__main__":
568
  import uvicorn
569
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
5
  from typing import Optional
6
 
7
  from fastapi import FastAPI, Query, HTTPException
 
8
  from huggingface_hub import download_bucket_files, batch_bucket_files
9
 
10
+ TOKEN = os.environ.get("HF_TOKEN", "")
11
 
12
  SOURCE_BUCKET = "PERDYPTO/db_snapshot"
13
  DB_PATH_IN_BUCKET = "github_pipeline.db"
 
17
  _status = {"state": "starting"}
18
  _lock = threading.Lock()
19
 
20
+ # Persistent disk connection (shared across requests with check_same_thread=False)
 
21
  _conn: Optional[sqlite3.Connection] = None
22
+ _local_db_file: Optional[str] = None
23
 
24
  # Columns that are safe to sort/filter by. Built dynamically from the actual
25
  # schema at load time so this stays correct even if the DB shape changes.
 
33
  """
34
 
35
  # Whitelisted sortable/filterable fields -> actual SQL column expression.
 
36
  FIELD_MAP: dict[str, str] = {}
37
 
38
  # Fields that are boolean-ish (0/1) and get exposed as true/false filters.
39
  BOOL_FIELDS = {"archived", "disabled", "is_fork", "is_template"}
40
 
41
 
 
 
 
 
 
 
 
 
 
42
  def build_field_map(conn: sqlite3.Connection):
43
  global _metadata_columns, _repo_ids_columns, FIELD_MAP
44
  cur = conn.cursor()
 
60
 
61
 
62
  def refresh_db():
63
+ """Download the db from HF bucket and open it in high-performance disk-backed read mode."""
64
+ global _conn, _local_db_file
65
+
66
  workdir = tempfile.mkdtemp()
67
  local_db_path = os.path.join(workdir, os.path.basename(DB_PATH_IN_BUCKET))
68
 
 
74
  )
75
  print(f"[download] saved to {local_db_path}")
76
 
77
+ # Open SQLite directly from disk with Read-Only URI mode & memory optimizations
78
+ # This prevents OOM on 16GB RAM limits while keeping speeds near in-memory reads.
79
+ db_uri = f"file:{local_db_path}?mode=ro"
80
+ new_conn = sqlite3.connect(db_uri, uri=True, check_same_thread=False)
81
+
82
+ # SQLite performance tuning for low-RAM disk reading
83
+ new_conn.execute("PRAGMA cache_size = -64000") # Limit RAM cache to 64MB max
84
+ new_conn.execute("PRAGMA temp_store = MEMORY")
85
+ new_conn.execute("PRAGMA mmap_size = 30000000000") # Enable memory-mapped I/O
86
+
87
  build_field_map(new_conn)
88
 
89
  with _lock:
90
+ if _conn:
91
+ _conn.close()
92
  _conn = new_conn
93
+ _local_db_file = local_db_path
94
 
95
+ print("[load] DB ready and optimized for fast, low-memory reads.")
96
 
 
 
 
 
 
97
 
98
+ def push_db_back():
99
+ """Optional: upload local persistent db back to HF bucket."""
100
+ if not _local_db_file or not os.path.exists(_local_db_file):
101
+ raise HTTPException(400, "No local DB available to push")
 
 
 
 
102
 
103
  print(f"[upload] pushing db back to hf://buckets/{SOURCE_BUCKET}/{DB_PATH_IN_BUCKET}")
104
  batch_bucket_files(
105
  SOURCE_BUCKET,
106
+ add=[(_local_db_file, DB_PATH_IN_BUCKET)],
107
  token=TOKEN,
108
  )
109
  print("[upload] done")
110
 
 
 
 
 
 
 
111
 
112
  @app.on_event("startup")
113
  def on_startup():
 
126
  "endpoints": {
127
  "/api/query": "Configurable query endpoint. See /api/schema for available fields.",
128
  "/api/schema": "Lists all filterable/sortable fields and table columns.",
129
+ "/api/refresh": "POST — re-download the db from the bucket.",
 
130
  },
131
  }
132
 
 
165
  max_stars: Optional[int] = Query(None, description="Maximum stars"),
166
  search: Optional[str] = Query(None, description="Substring search in repo_path/description"),
167
  ):
 
 
 
 
 
 
 
 
 
 
168
  conn = _get_conn()
169
 
170
  if sort_by not in FIELD_MAP:
 
253
 
254
  @app.get("/api/languages")
255
  def languages():
256
+ """List distinct primary_language values with counts."""
257
  conn = _get_conn()
258
  cur = conn.cursor()
259
  cur.execute(
 
290
 
291
  @app.post("/api/refresh")
292
  def refresh():
293
+ """Re-download the db from the bucket."""
294
  try:
295
  refresh_db()
296
  _status["state"] = "ready"
 
302
 
303
  @app.post("/api/push")
304
  def push():
305
+ """Persist local state back to HF bucket."""
 
306
  try:
307
+ push_db_back()
308
  return {"status": "ok"}
309
  except Exception as e:
310
  raise HTTPException(500, str(e))
311
 
312
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
313
  if __name__ == "__main__":
314
  import uvicorn
315
  uvicorn.run(app, host="0.0.0.0", port=7860)