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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# hf_space.py
|
| 2 |
+
"""
|
| 3 |
+
Hugging Face Space API Server for GitHub Metadata Pipeline.
|
| 4 |
+
Manages SQLite DB, holds pending IDs in RAM, and orchestrates GitHub workers.
|
| 5 |
+
"""
|
| 6 |
+
import os
|
| 7 |
+
import sqlite3
|
| 8 |
+
import threading
|
| 9 |
+
import time
|
| 10 |
+
import asyncio
|
| 11 |
+
import json
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from contextlib import asynccontextmanager
|
| 14 |
+
from fastapi import FastAPI
|
| 15 |
+
from pydantic import BaseModel
|
| 16 |
+
from typing import Dict, List, Any
|
| 17 |
+
|
| 18 |
+
from huggingface_hub import login, list_bucket_tree, download_bucket_files, create_bucket, batch_bucket_files
|
| 19 |
+
|
| 20 |
+
DB_PATH = Path("github_pipeline.db")
|
| 21 |
+
BUCKET = "PERDYPTO/db_snapshot"
|
| 22 |
+
|
| 23 |
+
SCHEMA = """
|
| 24 |
+
PRAGMA journal_mode=WAL;
|
| 25 |
+
PRAGMA synchronous=NORMAL;
|
| 26 |
+
|
| 27 |
+
CREATE TABLE IF NOT EXISTS repo_ids (
|
| 28 |
+
repo_id INTEGER PRIMARY KEY,
|
| 29 |
+
file_count_part INTEGER DEFAULT 0,
|
| 30 |
+
bytes_part INTEGER DEFAULT 0,
|
| 31 |
+
status TEXT NOT NULL DEFAULT 'pending',
|
| 32 |
+
last_error TEXT,
|
| 33 |
+
updated_at TEXT
|
| 34 |
+
);
|
| 35 |
+
|
| 36 |
+
CREATE TABLE IF NOT EXISTS metadata (
|
| 37 |
+
repo_id INTEGER PRIMARY KEY,
|
| 38 |
+
full_name TEXT,
|
| 39 |
+
html_url TEXT,
|
| 40 |
+
description TEXT,
|
| 41 |
+
default_branch TEXT,
|
| 42 |
+
size_kb INTEGER,
|
| 43 |
+
stars INTEGER,
|
| 44 |
+
forks_count INTEGER,
|
| 45 |
+
open_issues INTEGER,
|
| 46 |
+
license TEXT,
|
| 47 |
+
archived INTEGER,
|
| 48 |
+
created_at TEXT,
|
| 49 |
+
updated_at TEXT,
|
| 50 |
+
pushed_at TEXT,
|
| 51 |
+
languages_json TEXT,
|
| 52 |
+
python_bytes INTEGER,
|
| 53 |
+
total_lang_bytes INTEGER,
|
| 54 |
+
python_pct REAL,
|
| 55 |
+
file_count_part INTEGER,
|
| 56 |
+
bytes_part INTEGER,
|
| 57 |
+
resolved_from_fork_id INTEGER,
|
| 58 |
+
fetched_at TEXT
|
| 59 |
+
);
|
| 60 |
+
|
| 61 |
+
CREATE TABLE IF NOT EXISTS forks (
|
| 62 |
+
fork_repo_id INTEGER PRIMARY KEY,
|
| 63 |
+
fork_full_name TEXT,
|
| 64 |
+
fork_html_url TEXT,
|
| 65 |
+
parent_id INTEGER,
|
| 66 |
+
parent_full_name TEXT,
|
| 67 |
+
source_id INTEGER,
|
| 68 |
+
source_full_name TEXT,
|
| 69 |
+
resolved_canonical_id INTEGER,
|
| 70 |
+
resolution TEXT,
|
| 71 |
+
updated_at TEXT
|
| 72 |
+
);
|
| 73 |
+
|
| 74 |
+
CREATE INDEX IF NOT EXISTS idx_repo_ids_status ON repo_ids(status);
|
| 75 |
+
CREATE INDEX IF NOT EXISTS idx_metadata_python_pct ON metadata(python_pct DESC);
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
# In-memory state
|
| 79 |
+
pending_ids: List[int] = []
|
| 80 |
+
processing_ids: set = set()
|
| 81 |
+
ram_lock = asyncio.Lock()
|
| 82 |
+
db_lock = threading.Lock()
|
| 83 |
+
|
| 84 |
+
def now() -> str:
|
| 85 |
+
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
| 86 |
+
|
| 87 |
+
def init_db():
|
| 88 |
+
conn = sqlite3.connect(str(DB_PATH), check_same_thread=False, timeout=60)
|
| 89 |
+
conn.row_factory = sqlite3.Row
|
| 90 |
+
conn.executescript(SCHEMA)
|
| 91 |
+
return conn
|
| 92 |
+
|
| 93 |
+
db_conn = init_db()
|
| 94 |
+
|
| 95 |
+
def download_db_from_bucket():
|
| 96 |
+
if not os.environ.get("HF_TOKEN"):
|
| 97 |
+
print("No HF_TOKEN, starting fresh DB")
|
| 98 |
+
return
|
| 99 |
+
|
| 100 |
+
login(token=os.environ.get("HF_TOKEN"), add_to_git_credential=False)
|
| 101 |
+
try:
|
| 102 |
+
remote_name = "github_pipeline.db"
|
| 103 |
+
existing = {item.path for item in list_bucket_tree(BUCKET) if item.type == "file"}
|
| 104 |
+
if remote_name in existing:
|
| 105 |
+
print(f"Downloading DB from bucket {BUCKET}...")
|
| 106 |
+
download_bucket_files(BUCKET, files=[(remote_name, str(DB_PATH))])
|
| 107 |
+
print("Download complete.")
|
| 108 |
+
else:
|
| 109 |
+
print("DB not found in bucket. Starting fresh.")
|
| 110 |
+
except Exception as e:
|
| 111 |
+
print(f"Failed to download DB: {e}. Starting fresh.")
|
| 112 |
+
|
| 113 |
+
def upload_db_to_bucket():
|
| 114 |
+
print("[Checkpoint] Uploading DB to HF Bucket...")
|
| 115 |
+
try:
|
| 116 |
+
# Snapshot using SQLite backup API to avoid reading half-written WAL
|
| 117 |
+
snap_path = DB_PATH.with_suffix(".checkpoint")
|
| 118 |
+
if snap_path.exists():
|
| 119 |
+
snap_path.unlink()
|
| 120 |
+
|
| 121 |
+
src = sqlite3.connect(str(DB_PATH))
|
| 122 |
+
dst = sqlite3.connect(str(snap_path))
|
| 123 |
+
try:
|
| 124 |
+
src.backup(dst)
|
| 125 |
+
finally:
|
| 126 |
+
dst.close()
|
| 127 |
+
src.close()
|
| 128 |
+
|
| 129 |
+
create_bucket(BUCKET, exist_ok=True)
|
| 130 |
+
batch_bucket_files(BUCKET, add=[(str(snap_path), "github_pipeline.db")])
|
| 131 |
+
snap_path.unlink(missing_ok=True)
|
| 132 |
+
print("[Checkpoint] Upload complete.")
|
| 133 |
+
except Exception as e:
|
| 134 |
+
print(f"[Checkpoint] Upload FAILED: {e}")
|
| 135 |
+
|
| 136 |
+
async def background_uploader():
|
| 137 |
+
while True:
|
| 138 |
+
await asyncio.sleep(600) # 10 minutes
|
| 139 |
+
upload_db_to_bucket()
|
| 140 |
+
|
| 141 |
+
@asynccontextmanager
|
| 142 |
+
async def lifespan(app: FastAPI):
|
| 143 |
+
global pending_ids, processing_ids
|
| 144 |
+
|
| 145 |
+
download_db_from_bucket()
|
| 146 |
+
|
| 147 |
+
with db_lock:
|
| 148 |
+
print("Resetting in_progress -> pending...")
|
| 149 |
+
db_conn.execute("UPDATE repo_ids SET status='pending' WHERE status='in_progress'")
|
| 150 |
+
db_conn.commit()
|
| 151 |
+
|
| 152 |
+
print("Loading pending IDs into RAM...")
|
| 153 |
+
rows = db_conn.execute("SELECT repo_id FROM repo_ids WHERE status='pending'").fetchall()
|
| 154 |
+
pending_ids = [r["repo_id"] for r in rows]
|
| 155 |
+
print(f"Loaded {len(pending_ids)} pending IDs into RAM.")
|
| 156 |
+
|
| 157 |
+
asyncio.create_task(background_uploader())
|
| 158 |
+
yield
|
| 159 |
+
|
| 160 |
+
app = FastAPI(lifespan=lifespan)
|
| 161 |
+
|
| 162 |
+
@app.get("/get-jobs")
|
| 163 |
+
async def get_jobs():
|
| 164 |
+
async with ram_lock:
|
| 165 |
+
if not pending_ids:
|
| 166 |
+
return {"repo_ids": []}
|
| 167 |
+
|
| 168 |
+
batch_size = 15000
|
| 169 |
+
batch = pending_ids[-batch_size:]
|
| 170 |
+
pending_ids = pending_ids[:-batch_size]
|
| 171 |
+
processing_ids.update(batch)
|
| 172 |
+
|
| 173 |
+
# Mark as in_progress in DB so if Space crashes, they are recovered on restart
|
| 174 |
+
ts = now()
|
| 175 |
+
with db_lock:
|
| 176 |
+
db_conn.executemany(
|
| 177 |
+
"UPDATE repo_ids SET status='in_progress', updated_at=? WHERE repo_id=?",
|
| 178 |
+
[(ts, rid) for rid in batch]
|
| 179 |
+
)
|
| 180 |
+
db_conn.commit()
|
| 181 |
+
|
| 182 |
+
return {"repo_ids": batch}
|
| 183 |
+
|
| 184 |
+
class WorkPayload(BaseModel):
|
| 185 |
+
metadata: List[Dict[str, Any]] = []
|
| 186 |
+
forks: List[Dict[str, Any]] = []
|
| 187 |
+
errors: List[Dict[str, Any]] = []
|
| 188 |
+
|
| 189 |
+
@app.post("/post-work")
|
| 190 |
+
async def post_work(payload: WorkPayload):
|
| 191 |
+
processed_rids = set()
|
| 192 |
+
ts = now()
|
| 193 |
+
|
| 194 |
+
with db_lock:
|
| 195 |
+
# Save Metadata
|
| 196 |
+
for m in payload.metadata:
|
| 197 |
+
rid = m["repo_id"]
|
| 198 |
+
processed_rids.add(rid)
|
| 199 |
+
db_conn.execute(
|
| 200 |
+
"""
|
| 201 |
+
INSERT OR REPLACE INTO metadata (
|
| 202 |
+
repo_id, full_name, html_url, description, default_branch,
|
| 203 |
+
size_kb, stars, forks_count, open_issues, license, archived,
|
| 204 |
+
created_at, updated_at, pushed_at,
|
| 205 |
+
languages_json, python_bytes, total_lang_bytes, python_pct,
|
| 206 |
+
file_count_part, bytes_part, resolved_from_fork_id, fetched_at
|
| 207 |
+
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
| 208 |
+
""",
|
| 209 |
+
(
|
| 210 |
+
rid, m.get("full_name"), m.get("html_url"), m.get("description"),
|
| 211 |
+
m.get("default_branch"), m.get("size_kb"), m.get("stars"),
|
| 212 |
+
m.get("forks_count"), m.get("open_issues"), m.get("license"),
|
| 213 |
+
m.get("archived", 0), m.get("created_at"), m.get("updated_at"),
|
| 214 |
+
m.get("pushed_at"), m.get("languages_json"), m.get("python_bytes"),
|
| 215 |
+
m.get("total_lang_bytes"), m.get("python_pct"), m.get("file_count_part"),
|
| 216 |
+
m.get("bytes_part"), m.get("resolved_from_fork_id"), ts
|
| 217 |
+
)
|
| 218 |
+
)
|
| 219 |
+
db_conn.execute("UPDATE repo_ids SET status='done', last_error=NULL, updated_at=? WHERE repo_id=?", (ts, rid))
|
| 220 |
+
|
| 221 |
+
# Save Forks
|
| 222 |
+
for f in payload.forks:
|
| 223 |
+
rid = f["fork_repo_id"]
|
| 224 |
+
processed_rids.add(rid)
|
| 225 |
+
db_conn.execute(
|
| 226 |
+
"""
|
| 227 |
+
INSERT OR REPLACE INTO forks (
|
| 228 |
+
fork_repo_id, fork_full_name, fork_html_url,
|
| 229 |
+
parent_id, parent_full_name, source_id, source_full_name,
|
| 230 |
+
resolved_canonical_id, resolution, updated_at
|
| 231 |
+
) VALUES (?,?,?,?,?,?,?,?,?,?)
|
| 232 |
+
""",
|
| 233 |
+
(
|
| 234 |
+
rid, f.get("fork_full_name"), f.get("fork_html_url"),
|
| 235 |
+
f.get("parent_id"), f.get("parent_full_name"), f.get("source_id"),
|
| 236 |
+
f.get("source_full_name"), f.get("resolved_canonical_id"),
|
| 237 |
+
f.get("resolution"), ts
|
| 238 |
+
)
|
| 239 |
+
)
|
| 240 |
+
db_conn.execute("UPDATE repo_ids SET status='done', last_error=?, updated_at=? WHERE repo_id=?", (f.get("resolution"), ts, rid))
|
| 241 |
+
|
| 242 |
+
# Save Errors
|
| 243 |
+
for e in payload.errors:
|
| 244 |
+
rid = e["repo_id"]
|
| 245 |
+
processed_rids.add(rid)
|
| 246 |
+
db_conn.execute("UPDATE repo_ids SET status='error', last_error=?, updated_at=? WHERE repo_id=?", (e.get("error"), ts, rid))
|
| 247 |
+
|
| 248 |
+
db_conn.commit()
|
| 249 |
+
|
| 250 |
+
# Remove from RAM processing set
|
| 251 |
+
async with ram_lock:
|
| 252 |
+
processing_ids.difference_update(processed_rids)
|
| 253 |
+
|
| 254 |
+
return {"status": "success", "processed": len(processed_rids)}
|