Spaces:
Sleeping

PERDYPTO commited on
Commit
98038e2
·
verified ·
1 Parent(s): 63c605b

Update hf_space.py

Browse files
Files changed (1) hide show
  1. hf_space.py +136 -18
hf_space.py CHANGED
@@ -13,8 +13,14 @@ from typing import Dict, List, Any
13
 
14
  from huggingface_hub import login, list_bucket_tree, download_bucket_files, create_bucket, batch_bucket_files
15
 
 
 
 
 
 
16
  DB_PATH = Path("github_pipeline.db")
17
  BUCKET = "PERDYPTO/db_snapshot"
 
18
 
19
  SCHEMA = """
20
  PRAGMA journal_mode=WAL;
@@ -67,6 +73,12 @@ CREATE TABLE IF NOT EXISTS forks (
67
  updated_at TEXT
68
  );
69
 
 
 
 
 
 
 
70
  CREATE INDEX IF NOT EXISTS idx_repo_ids_status ON repo_ids(status);
71
  CREATE INDEX IF NOT EXISTS idx_metadata_python_pct ON metadata(python_pct DESC);
72
  """
@@ -77,7 +89,7 @@ processing_ids: set = set()
77
  ram_lock = asyncio.Lock()
78
  db_lock = threading.Lock()
79
  db_conn = None
80
- last_db_changes = 0 # Used to track if DB was modified
81
 
82
  def now() -> str:
83
  return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
@@ -94,11 +106,8 @@ def download_db_from_bucket():
94
  existing = {item.path for item in list_bucket_tree(BUCKET) if item.type == "file"}
95
  if remote_name in existing:
96
  print(f"Downloading DB from bucket {BUCKET}...")
97
-
98
- # SAFETY: Delete local file if it exists so we don't block the download
99
  if DB_PATH.exists():
100
  DB_PATH.unlink()
101
-
102
  download_bucket_files(BUCKET, files=[(remote_name, str(DB_PATH))])
103
  print("Download complete.")
104
  else:
@@ -108,7 +117,6 @@ def download_db_from_bucket():
108
 
109
  def init_db():
110
  global db_conn
111
- # Connect AFTER download is attempted
112
  conn = sqlite3.connect(str(DB_PATH), check_same_thread=False, timeout=60)
113
  conn.row_factory = sqlite3.Row
114
  conn.executescript(SCHEMA)
@@ -140,8 +148,6 @@ async def background_uploader():
140
  global last_db_changes
141
  while True:
142
  await asyncio.sleep(600) # 10 minutes
143
-
144
- # Check if DB was modified since last checkpoint
145
  with db_lock:
146
  current_changes = db_conn.total_changes
147
 
@@ -152,11 +158,101 @@ async def background_uploader():
152
  else:
153
  print("[Checkpoint] No changes detected since last upload. Skipping upload.")
154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  @asynccontextmanager
156
  async def lifespan(app: FastAPI):
157
  global db_conn, pending_ids, processing_ids, last_db_changes
158
 
159
- # 1. Download FIRST
160
  download_db_from_bucket()
161
 
162
  # 2. Initialize DB connection SECOND
@@ -168,14 +264,17 @@ async def lifespan(app: FastAPI):
168
  db_conn.commit()
169
 
170
  print("Loading pending IDs into RAM...")
171
- rows = db_conn.execute("SELECT repo_id FROM repo_ids WHERE status='pending'").fetchall()
 
 
 
172
  pending_ids = [r["repo_id"] for r in rows]
173
  print(f"Loaded {len(pending_ids)} pending IDs into RAM.")
174
 
175
- # Initialize the change tracker AFTER the in_progress->pending migration
176
  last_db_changes = db_conn.total_changes
177
 
178
  asyncio.create_task(background_uploader())
 
179
  yield
180
 
181
  app = FastAPI(lifespan=lifespan)
@@ -184,11 +283,19 @@ app = FastAPI(lifespan=lifespan)
184
  async def get_jobs():
185
  async with ram_lock:
186
  if not pending_ids:
187
- return {"repo_ids": []}
188
-
189
- batch_size = 15000
190
- batch = pending_ids[-batch_size:]
191
- pending_ids = pending_ids[:-batch_size]
 
 
 
 
 
 
 
 
192
  processing_ids.update(batch)
193
 
194
  ts = now()
@@ -216,15 +323,25 @@ async def post_work(payload: WorkPayload):
216
  for m in payload.metadata:
217
  rid = m["repo_id"]
218
  processed_rids.add(rid)
 
219
  db_conn.execute(
220
  """
221
- INSERT OR REPLACE INTO metadata (
222
  repo_id, full_name, html_url, description, default_branch,
223
  size_kb, stars, forks_count, open_issues, license, archived,
224
  created_at, updated_at, pushed_at,
225
  languages_json, python_bytes, total_lang_bytes, python_pct,
226
  file_count_part, bytes_part, resolved_from_fork_id, fetched_at
227
  ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
 
 
 
 
 
 
 
 
 
228
  """,
229
  (
230
  rid, m.get("full_name"), m.get("html_url"), m.get("description"),
@@ -232,8 +349,9 @@ async def post_work(payload: WorkPayload):
232
  m.get("forks_count"), m.get("open_issues"), m.get("license"),
233
  m.get("archived", 0), m.get("created_at"), m.get("updated_at"),
234
  m.get("pushed_at"), m.get("languages_json"), m.get("python_bytes"),
235
- m.get("total_lang_bytes"), m.get("python_pct"), m.get("file_count_part"),
236
- m.get("bytes_part"), m.get("resolved_from_fork_id"), ts
 
237
  )
238
  )
239
  db_conn.execute("UPDATE repo_ids SET status='done', last_error=NULL, updated_at=? WHERE repo_id=?", (ts, rid))
 
13
 
14
  from huggingface_hub import login, list_bucket_tree, download_bucket_files, create_bucket, batch_bucket_files
15
 
16
+ try:
17
+ import pyarrow.parquet as pq
18
+ except ImportError:
19
+ pq = None
20
+
21
  DB_PATH = Path("github_pipeline.db")
22
  BUCKET = "PERDYPTO/db_snapshot"
23
+ PARQUET_BUCKET = "PERDYPTO/Python_data_set"
24
 
25
  SCHEMA = """
26
  PRAGMA journal_mode=WAL;
 
73
  updated_at TEXT
74
  );
75
 
76
+ CREATE TABLE IF NOT EXISTS parquet_progress (
77
+ part INTEGER PRIMARY KEY,
78
+ status TEXT NOT NULL DEFAULT 'pending',
79
+ ingested_at TEXT
80
+ );
81
+
82
  CREATE INDEX IF NOT EXISTS idx_repo_ids_status ON repo_ids(status);
83
  CREATE INDEX IF NOT EXISTS idx_metadata_python_pct ON metadata(python_pct DESC);
84
  """
 
89
  ram_lock = asyncio.Lock()
90
  db_lock = threading.Lock()
91
  db_conn = None
92
+ last_db_changes = 0
93
 
94
  def now() -> str:
95
  return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
 
106
  existing = {item.path for item in list_bucket_tree(BUCKET) if item.type == "file"}
107
  if remote_name in existing:
108
  print(f"Downloading DB from bucket {BUCKET}...")
 
 
109
  if DB_PATH.exists():
110
  DB_PATH.unlink()
 
111
  download_bucket_files(BUCKET, files=[(remote_name, str(DB_PATH))])
112
  print("Download complete.")
113
  else:
 
117
 
118
  def init_db():
119
  global db_conn
 
120
  conn = sqlite3.connect(str(DB_PATH), check_same_thread=False, timeout=60)
121
  conn.row_factory = sqlite3.Row
122
  conn.executescript(SCHEMA)
 
148
  global last_db_changes
149
  while True:
150
  await asyncio.sleep(600) # 10 minutes
 
 
151
  with db_lock:
152
  current_changes = db_conn.total_changes
153
 
 
158
  else:
159
  print("[Checkpoint] No changes detected since last upload. Skipping upload.")
160
 
161
+ async def ingest_worker():
162
+ """Background task to ingest 401 parquet parts into SQLite"""
163
+ global pending_ids, ram_lock
164
+ if pq is None:
165
+ print("[Ingest] pyarrow not installed. Parquet ingestion disabled.")
166
+ return
167
+
168
+ print("[Ingest] Starting background parquet ingestion...")
169
+ for part in range(401):
170
+ with db_lock:
171
+ row = db_conn.execute("SELECT status FROM parquet_progress WHERE part=?", (part,)).fetchone()
172
+ if row and row["status"] == "done":
173
+ continue # Skip already ingested parts
174
+
175
+ rel = f"part-{part:05d}-147a722f-59fd-4e19-9d9a-9a37ea61b943-c000.snappy.parquet"
176
+ uri = f"hf://buckets/{PARQUET_BUCKET}/{rel}"
177
+ print(f"[Ingest] Scanning part {part}...")
178
+
179
+ try:
180
+ pf = pq.ParquetFile(uri)
181
+ counts: dict[int, list[int]] = {} # rid -> [file_count, bytes]
182
+
183
+ for rg in range(pf.metadata.num_row_groups):
184
+ table = pf.read_row_group(rg, columns=["size_bytes", "repo_ids"])
185
+ for row in table.to_pylist():
186
+ size = int(row.get("size_bytes") or 0)
187
+ for rid in row.get("repo_ids") or []:
188
+ rid = int(rid)
189
+ if rid not in counts:
190
+ counts[rid] = [0, 0]
191
+ counts[rid][0] += 1
192
+ counts[rid][1] += size
193
+
194
+ all_ids = list(counts.keys())
195
+
196
+ with db_lock:
197
+ # Fetch existing IDs to know which ones to accumulate vs insert
198
+ placeholders = ",".join("?" * len(all_ids))
199
+ existing_rows = db_conn.execute(f"SELECT repo_id FROM repo_ids WHERE repo_id IN ({placeholders})", all_ids).fetchall()
200
+ existing_ids = {r["repo_id"] for r in existing_rows}
201
+
202
+ new_ids = [rid for rid in all_ids if rid not in existing_ids]
203
+
204
+ # 1. Insert brand new IDs
205
+ if new_ids:
206
+ db_conn.executemany(
207
+ "INSERT OR IGNORE INTO repo_ids (repo_id, file_count_part, bytes_part, status, updated_at) VALUES (?, ?, ?, 'pending', ?)",
208
+ [(rid, counts[rid][0], counts[rid][1], now()) for rid in new_ids]
209
+ )
210
+
211
+ # 2. Accumulate counts for existing IDs (DO NOT touch status or last_error)
212
+ existing_to_update = [rid for rid in all_ids if rid in existing_ids]
213
+ if existing_to_update:
214
+ db_conn.executemany(
215
+ """
216
+ UPDATE repo_ids
217
+ SET file_count_part = file_count_part + ?,
218
+ bytes_part = bytes_part + ?,
219
+ updated_at = ?
220
+ WHERE repo_id = ?
221
+ """,
222
+ [(counts[rid][0], counts[rid][1], now(), rid) for rid in existing_to_update]
223
+ )
224
+
225
+ # 3. Mark part as done
226
+ db_conn.execute(
227
+ "INSERT OR REPLACE INTO parquet_progress (part, status, ingested_at) VALUES (?, 'done', ?)",
228
+ (part, now())
229
+ )
230
+ db_conn.commit()
231
+
232
+ # Add new valid IDs to RAM queue (min 2 files, max 80 files)
233
+ valid_new_ids = [rid for rid in new_ids if 2 <= counts[rid][0] <= 80]
234
+ if valid_new_ids:
235
+ async with ram_lock:
236
+ pending_ids.extend(valid_new_ids)
237
+
238
+ print(f"[Ingest] Part {part} done. Found {len(all_ids)} IDs. New: {len(new_ids)}. Added {len(valid_new_ids)} to RAM queue.")
239
+
240
+ except Exception as e:
241
+ print(f"[Ingest] Failed to ingest part {part}: {e}")
242
+ with db_lock:
243
+ db_conn.execute(
244
+ "INSERT OR REPLACE INTO parquet_progress (part, status, ingested_at) VALUES (?, 'error', ?)",
245
+ (part, now())
246
+ )
247
+ db_conn.commit()
248
+
249
+ print("[Ingest] All parquet parts processed.")
250
+
251
  @asynccontextmanager
252
  async def lifespan(app: FastAPI):
253
  global db_conn, pending_ids, processing_ids, last_db_changes
254
 
255
+ # 1. Download DB FIRST
256
  download_db_from_bucket()
257
 
258
  # 2. Initialize DB connection SECOND
 
264
  db_conn.commit()
265
 
266
  print("Loading pending IDs into RAM...")
267
+ # Only load IDs that meet the file count criteria into RAM
268
+ rows = db_conn.execute(
269
+ "SELECT repo_id FROM repo_ids WHERE status='pending' AND file_count_part >= 2 AND file_count_part <= 80"
270
+ ).fetchall()
271
  pending_ids = [r["repo_id"] for r in rows]
272
  print(f"Loaded {len(pending_ids)} pending IDs into RAM.")
273
 
 
274
  last_db_changes = db_conn.total_changes
275
 
276
  asyncio.create_task(background_uploader())
277
+ asyncio.create_task(ingest_worker())
278
  yield
279
 
280
  app = FastAPI(lifespan=lifespan)
 
283
  async def get_jobs():
284
  async with ram_lock:
285
  if not pending_ids:
286
+ # Fallback: If RAM is empty, check DB in case late ingestion added valid pending rows
287
+ with db_lock:
288
+ rows = db_conn.execute(
289
+ "SELECT repo_id FROM repo_ids WHERE status='pending' AND file_count_part >= 2 AND file_count_part <= 80 LIMIT 15000"
290
+ ).fetchall()
291
+ batch = [r["repo_id"] for r in rows]
292
+ if not batch:
293
+ return {"repo_ids": []}
294
+ else:
295
+ batch_size = 15000
296
+ batch = pending_ids[-batch_size:]
297
+ pending_ids = pending_ids[:-batch_size]
298
+
299
  processing_ids.update(batch)
300
 
301
  ts = now()
 
323
  for m in payload.metadata:
324
  rid = m["repo_id"]
325
  processed_rids.add(rid)
326
+ # Safely insert/update metadata WITHOUT wiping file_count_part if worker didn't send it
327
  db_conn.execute(
328
  """
329
+ INSERT INTO metadata (
330
  repo_id, full_name, html_url, description, default_branch,
331
  size_kb, stars, forks_count, open_issues, license, archived,
332
  created_at, updated_at, pushed_at,
333
  languages_json, python_bytes, total_lang_bytes, python_pct,
334
  file_count_part, bytes_part, resolved_from_fork_id, fetched_at
335
  ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
336
+ ON CONFLICT(repo_id) DO UPDATE SET
337
+ full_name=excluded.full_name, html_url=excluded.html_url,
338
+ description=excluded.description, default_branch=excluded.default_branch,
339
+ size_kb=excluded.size_kb, stars=excluded.stars, forks_count=excluded.forks_count,
340
+ open_issues=excluded.open_issues, license=excluded.license, archived=excluded.archived,
341
+ created_at=excluded.created_at, updated_at=excluded.updated_at, pushed_at=excluded.pushed_at,
342
+ languages_json=excluded.languages_json, python_bytes=excluded.python_bytes,
343
+ total_lang_bytes=excluded.total_lang_bytes, python_pct=excluded.python_pct,
344
+ resolved_from_fork_id=excluded.resolved_from_fork_id, fetched_at=excluded.fetched_at
345
  """,
346
  (
347
  rid, m.get("full_name"), m.get("html_url"), m.get("description"),
 
349
  m.get("forks_count"), m.get("open_issues"), m.get("license"),
350
  m.get("archived", 0), m.get("created_at"), m.get("updated_at"),
351
  m.get("pushed_at"), m.get("languages_json"), m.get("python_bytes"),
352
+ m.get("total_lang_bytes"), m.get("python_pct"),
353
+ m.get("file_count_part", 0), m.get("bytes_part", 0), # Fallback if worker didn't send
354
+ m.get("resolved_from_fork_id"), ts
355
  )
356
  )
357
  db_conn.execute("UPDATE repo_ids SET status='done', last_error=NULL, updated_at=? WHERE repo_id=?", (ts, rid))