Spaces:
Sleeping

PERDYPTO commited on
Commit
9504ad6
·
verified ·
1 Parent(s): 9df25ec

Update pipeline.py

Browse files
Files changed (1) hide show
  1. pipeline.py +707 -322
pipeline.py CHANGED
@@ -2,7 +2,17 @@
2
  # ============================================================
3
  # PIPELINE_API.PY — FULL CONTINUED PRETRAINING DATASET PIPELINE
4
  # WITH FASTAPI HEALTH & STATUS ENDPOINTS
5
- # MASTER‑WORKER ARCHITECTURE
 
 
 
 
 
 
 
 
 
 
6
  # ============================================================
7
 
8
  import os
@@ -12,20 +22,21 @@ import time
12
  import gzip
13
  import shutil
14
  import hashlib
 
15
  import subprocess
16
  import traceback
17
  import multiprocessing as mp
 
18
  import threading
19
- import glob
20
  from pathlib import Path
21
  from concurrent.futures import ProcessPoolExecutor, as_completed
22
- from typing import List, Dict, Any, Optional, Tuple
23
 
24
  import orjson
25
  from datasets import load_dataset
26
  from huggingface_hub import batch_bucket_files
27
 
28
- from fastapi import FastAPI
29
  from fastapi.responses import JSONResponse
30
  import uvicorn
31
 
@@ -33,38 +44,52 @@ import uvicorn
33
  # BASIC CONFIG — ADAPTED FOR HF SPACE PERSISTENT STORAGE
34
  # ============================================================
35
 
 
36
  DATA_ROOT = Path(os.environ.get("DATA_ROOT", "/data"))
 
 
37
  LOCAL_ROOT = DATA_ROOT / "category1_pipeline_v4"
38
  STATE_ROOT = LOCAL_ROOT / "state"
39
  TMP_ROOT = LOCAL_ROOT / "tmp"
40
  FINAL_ROOT = LOCAL_ROOT / "final"
41
- CACHE_ROOT = DATA_ROOT / "cache" # cache for datasets
42
 
43
- for directory in [STATE_ROOT, TMP_ROOT, FINAL_ROOT, CACHE_ROOT]:
44
  directory.mkdir(parents=True, exist_ok=True)
45
 
 
46
  BUCKET_ID = "PERDYPTO/private"
 
 
47
  HF_TOKEN = os.environ.get("HF_TOKEN")
48
  if not HF_TOKEN:
49
- raise RuntimeError("HF_TOKEN environment variable not set.")
50
 
51
- # Python versions for AST validation – fallback to system Python if not found
52
  PYTHON_VERSIONS = [
53
  "3.11.9",
54
  "3.12.10",
55
  "3.13.15",
56
  "3.14.7",
57
  ]
58
- AST_ACCEPT_MODE = "ANY" # any one version passes
59
 
60
- MAX_WORKERS = 4 # number of worker processes
61
- SHARD_ROWS = 5_000 # records per output file
 
 
 
 
 
 
 
 
 
62
 
63
  # Quality filters
64
  MIN_CHARS = 100
65
  MAX_CHARS = 2_000_000
66
  MIN_LINES = 2
67
  MAX_LINE_LENGTH = 20_000
 
68
  REJECT_GENERATED = True
69
  REJECT_VENDOR = True
70
 
@@ -77,6 +102,10 @@ REMOTE_FINAL = f"{REMOTE_ROOT}/final"
77
  # ============================================================
78
  # DATASET LIST – CATEGORY 1 (SOURCE CODE ONLY)
79
  # ============================================================
 
 
 
 
80
 
81
  DATASETS = [
82
  {
@@ -171,7 +200,6 @@ DATASETS = [
171
  }
172
  ]
173
 
174
-
175
  # ============================================================
176
  # GLOBAL STATE FOR API
177
  # ============================================================
@@ -179,7 +207,7 @@ DATASETS = [
179
  pipeline_status = {
180
  "started": False,
181
  "completed": False,
182
- "current_stage": "idle",
183
  "total_tasks": 0,
184
  "finished_tasks": 0,
185
  "stats": {
@@ -195,7 +223,7 @@ pipeline_status = {
195
  }
196
 
197
  # ============================================================
198
- # HELPER FUNCTIONS
199
  # ============================================================
200
 
201
  def retry(fn, label, retries=5):
@@ -205,7 +233,7 @@ def retry(fn, label, retries=5):
205
  return fn()
206
  except Exception as e:
207
  last_error = e
208
- print(f"[RETRY] {label} {attempt}/{retries}: {e}", flush=True)
209
  if attempt < retries:
210
  time.sleep(min(30, 2 ** attempt))
211
  raise last_error
@@ -267,370 +295,727 @@ def quality_check(text):
267
  return False, "binary_like"
268
  return True, "ok"
269
 
270
- def get_interpreters():
271
- """Find Python interpreters. Fallback to system python if needed."""
272
- interpreters = {}
273
- base = "/root/.local/share/uv/python"
274
- for v in PYTHON_VERSIONS:
275
- pattern = f"{base}/cpython-{v}*/bin/python*"
276
- matches = glob.glob(pattern)
277
- if matches:
278
- interpreters[v] = matches[0]
279
- else:
280
- print(f"Warning: Python {v} not found in {base}", flush=True)
281
- # If none found, use system python
282
- if not interpreters:
283
- import sys
284
- system_python = sys.executable
285
- interpreters["system"] = system_python
286
- print(f"Using system Python: {system_python}", flush=True)
287
- return interpreters
288
-
289
- def ast_check_with_versions(code: str) -> Tuple[bool, str]:
290
- """Run AST parsing with each Python version; accepts if any passes."""
291
- interpreters = get_interpreters()
292
- for ver, py_path in interpreters.items():
293
- cmd = [py_path, "-c", f"import ast; ast.parse({repr(code)})"]
294
- try:
295
- subprocess.run(cmd, check=True, capture_output=True, timeout=10)
296
- return True, f"accepted_by_{ver}"
297
- except Exception:
298
  continue
299
- return False, "ast_failed_all"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
300
 
301
  # ============================================================
302
- # WORKER FUNCTION (runs in child process)
303
  # ============================================================
304
 
305
- def worker_process_task(task: Dict[str, Any]) -> Dict[str, Any]:
306
- """
307
- Process a single partition of a dataset.
308
- Returns a dict with accepted, rejected lists and stats.
309
- """
310
- ds_info = task["ds_info"]
311
- dataset_name = ds_info["name"]
312
-
313
- # Build load_kwargs
314
- load_kwargs = {
315
- "path": ds_info["dataset"],
316
- "split": ds_info["split"],
317
- "streaming": True,
318
- "trust_remote_code": True,
319
- "cache_dir": str(CACHE_ROOT),
320
- "token": HF_TOKEN, # pass token for authentication
321
- }
322
- if ds_info.get("config"):
323
- load_kwargs["name"] = ds_info["config"]
324
- if ds_info.get("data_dir"):
325
- load_kwargs["data_dir"] = ds_info["data_dir"]
326
 
 
 
 
 
327
  try:
328
- ds = load_dataset(**load_kwargs)
 
 
329
  except Exception as e:
330
- return {
331
- "error": f"Failed to load dataset: {e}",
332
- "accepted": [],
333
- "rejected": [],
334
- "stats": {"input": 0, "accepted": 0, "rejected": 0}
335
- }
336
-
337
- text_fields = ds_info.get("text_fields", [])
338
- repo_fields = ds_info.get("repo_fields", [])
339
- path_fields = ds_info.get("path_fields", [])
340
- license_fields = ds_info.get("license_fields", [])
341
-
342
- accepted = []
343
- rejected = []
344
- input_count = 0
345
- accepted_count = 0
346
- rejected_count = 0
347
-
348
- # Optionally resume from a checkpoint (if task has start index)
349
- start_idx = task.get("start", 0)
350
- end_idx = task.get("end", None)
351
-
352
- row_idx = 0
353
- for row in ds:
354
- if end_idx is not None and row_idx >= end_idx:
355
- break
356
- if row_idx < start_idx:
357
- row_idx += 1
358
- continue
359
 
360
- input_count += 1
361
-
362
- # Extract text
363
- text = None
364
- for field in text_fields:
365
- if field in row and row[field] is not None:
366
- text = row[field]
367
- break
368
- if text is None or not isinstance(text, str):
369
- rejected.append({"text": "", "reason": "no_text_field", "metadata": {}})
370
- rejected_count += 1
371
- row_idx += 1
372
- continue
373
 
374
- # Quality
375
- ok, reason = quality_check(text)
376
- if not ok:
377
- rejected.append({"text": text, "reason": reason, "metadata": {}})
378
- rejected_count += 1
379
- row_idx += 1
380
- continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
381
 
382
- # AST
383
- ast_ok, ast_reason = ast_check_with_versions(text)
384
- if not ast_ok:
385
- rejected.append({"text": text, "reason": ast_reason, "metadata": {}})
386
- rejected_count += 1
387
- row_idx += 1
388
- continue
389
 
390
- # Hashes
391
- ehash = exact_hash(text)
392
- nhash = normalized_hash(text)
393
-
394
- # Metadata
395
- metadata = {}
396
- for field in repo_fields:
397
- if field in row:
398
- metadata["repo"] = row[field]
399
- break
400
- for field in path_fields:
401
- if field in row:
402
- metadata["path"] = row[field]
403
- break
404
- for field in license_fields:
405
- if field in row:
406
- metadata["license"] = row[field]
407
- break
408
-
409
- accepted.append({
410
- "text": text,
411
- "exact_hash": ehash,
412
- "normalized_hash": nhash,
413
- "metadata": metadata,
414
- })
415
- accepted_count += 1
416
- row_idx += 1
417
 
 
418
  return {
419
- "error": None,
420
- "accepted": accepted,
421
- "rejected": rejected,
422
- "stats": {
423
- "input": input_count,
424
- "accepted": accepted_count,
425
- "rejected": rejected_count,
426
- }
 
 
 
 
427
  }
428
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
429
  # ============================================================
430
- # MASTER PROCESSING FUNCTION (runs in a separate process)
431
  # ============================================================
432
 
433
- def run_pipeline():
434
- global pipeline_status
435
- pipeline_status["started"] = True
436
- pipeline_status["current_stage"] = "processing"
437
- pipeline_status["error"] = None
 
 
 
 
438
 
439
- print("=== PIPELINE STARTED ===", flush=True)
440
-
441
- # In-memory dedup sets
442
- global_exact_hashes = set()
443
- global_norm_hashes = set()
444
 
445
- total_input = 0
446
- total_accepted = 0
447
- total_rejected = 0
448
- total_duplicate_exact = 0
449
- total_duplicate_norm = 0
 
 
 
 
 
 
 
 
 
 
 
450
 
451
- # Prepare tasks: one per dataset (can split large datasets later)
452
- tasks = []
453
- for ds_info in DATASETS:
454
- tasks.append({
455
- "ds_info": ds_info,
456
- "start": 0,
457
- "end": None,
458
- })
459
 
460
- pipeline_status["total_tasks"] = len(tasks)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
461
 
462
- with ProcessPoolExecutor(max_workers=MAX_WORKERS) as executor:
463
- future_to_task = {executor.submit(worker_process_task, task): task for task in tasks}
 
464
 
465
- for future in as_completed(future_to_task):
466
- task = future_to_task[future]
467
- ds_name = task["ds_info"]["name"]
468
  try:
469
- result = future.result(timeout=3600)
470
- except Exception as e:
471
- print(f"[ERROR] Task for {ds_name} failed: {e}", flush=True)
472
- traceback.print_exc()
473
- pipeline_status["error"] = str(e)
474
  continue
475
-
476
- if result.get("error"):
477
- print(f"[ERROR] Task for {ds_name} returned error: {result['error']}", flush=True)
478
- pipeline_status["error"] = result["error"]
479
  continue
480
 
481
- accepted = result.get("accepted", [])
482
- rejected = result.get("rejected", [])
483
- stats = result.get("stats", {})
484
-
485
- total_input += stats.get("input", 0)
486
- total_rejected += stats.get("rejected", 0)
487
-
488
- # Deduplicate accepted records globally
489
- unique_accepted = []
490
- for rec in accepted:
491
- ehash = rec["exact_hash"]
492
- nhash = rec["normalized_hash"]
493
- if ehash in global_exact_hashes:
494
- total_duplicate_exact += 1
495
- rejected.append({
496
- "text": rec["text"],
497
- "reason": "duplicate_exact",
498
- "metadata": rec["metadata"],
499
- })
500
- total_rejected += 1
501
  continue
502
- if nhash in global_norm_hashes:
503
- total_duplicate_norm += 1
504
- rejected.append({
505
- "text": rec["text"],
506
- "reason": "duplicate_normalized",
507
- "metadata": rec["metadata"],
508
- })
509
- total_rejected += 1
510
  continue
511
- global_exact_hashes.add(ehash)
512
- global_norm_hashes.add(nhash)
513
- unique_accepted.append(rec)
514
- total_accepted += 1
515
-
516
- # Write shards for this dataset
517
- ds_output_root = FINAL_ROOT / ds_name
518
- verified_dir = ds_output_root / "verified"
519
- rejected_dir = ds_output_root / "rejected"
520
- verified_dir.mkdir(parents=True, exist_ok=True)
521
- rejected_dir.mkdir(parents=True, exist_ok=True)
522
-
523
- # Write accepted
524
- accepted_shard_count = 0
525
- batch = []
526
- for rec in unique_accepted:
527
- batch.append(rec)
528
- if len(batch) >= SHARD_ROWS:
529
- shard_path = verified_dir / f"shard-{accepted_shard_count:05d}.jsonl.gz"
530
- with gzip.open(shard_path, "wt", encoding="utf-8") as f:
531
- for item in batch:
532
- f.write(orjson.dumps(item).decode("utf-8") + "\n")
533
- accepted_shard_count += 1
534
- batch = []
535
- if batch:
536
- shard_path = verified_dir / f"shard-{accepted_shard_count:05d}.jsonl.gz"
537
- with gzip.open(shard_path, "wt", encoding="utf-8") as f:
538
- for item in batch:
539
- f.write(orjson.dumps(item).decode("utf-8") + "\n")
540
- accepted_shard_count += 1
541
-
542
- # Write rejected
543
- rejected_shard_count = 0
544
- batch = []
545
- for rec in rejected:
546
- batch.append(rec)
547
- if len(batch) >= SHARD_ROWS:
548
- shard_path = rejected_dir / f"rejected-{rejected_shard_count:05d}.jsonl.gz"
549
- with gzip.open(shard_path, "wt", encoding="utf-8") as f:
550
- for item in batch:
551
- f.write(orjson.dumps(item).decode("utf-8") + "\n")
552
- rejected_shard_count += 1
553
- batch = []
554
- if batch:
555
- shard_path = rejected_dir / f"rejected-{rejected_shard_count:05d}.jsonl.gz"
556
- with gzip.open(shard_path, "wt", encoding="utf-8") as f:
557
- for item in batch:
558
- f.write(orjson.dumps(item).decode("utf-8") + "\n")
559
- rejected_shard_count += 1
560
-
561
- # Metadata
562
- metadata = {
563
- "dataset_name": ds_name,
564
- "total_input": stats.get("input", 0),
565
- "accepted": len(unique_accepted),
566
- "rejected": len(rejected),
567
- "duplicate_exact": total_duplicate_exact,
568
- "duplicate_normalized": total_duplicate_norm,
569
- "accepted_shards": accepted_shard_count,
570
- "rejected_shards": rejected_shard_count,
571
  }
572
- with open(ds_output_root / "metadata.json", "w") as f:
573
- json.dump(metadata, f, indent=2)
574
 
575
- print(f"[{ds_name}] processed: input={stats.get('input',0)}, "
576
- f"accepted={len(unique_accepted)}, rejected={len(rejected)}", flush=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
577
 
578
- # Update global stats
579
- pipeline_status["stats"]["input_records"] = total_input
580
- pipeline_status["stats"]["accepted_records"] = total_accepted
581
- pipeline_status["stats"]["invalid_records"] = total_rejected
582
- pipeline_status["stats"]["duplicate_exact"] = total_duplicate_exact
583
- pipeline_status["stats"]["duplicate_normalized"] = total_duplicate_norm
584
- pipeline_status["completed"] = True
585
- pipeline_status["current_stage"] = "done"
586
 
587
- print("=== PIPELINE COMPLETED ===", flush=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
588
 
589
  # ============================================================
590
- # FASTAPI APP
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
591
  # ============================================================
592
 
593
- app = FastAPI()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
594
 
595
- # Start pipeline in a separate process (not thread) so logs are visible
596
- def start_pipeline_process():
597
- p = mp.Process(target=run_pipeline, daemon=True)
598
- p.start()
599
- return p
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
600
 
601
  @app.on_event("startup")
602
  def startup_event():
603
- global pipeline_process
604
- print("Starting pipeline in background process...", flush=True)
605
- pipeline_process = start_pipeline_process()
606
 
607
  @app.get("/health")
608
- def health():
 
 
 
609
  return JSONResponse(content={
610
  "status": pipeline_status["current_stage"],
611
  "started": pipeline_status["started"],
612
  "completed": pipeline_status["completed"],
613
- "error": pipeline_status["error"],
 
614
  "stats": pipeline_status["stats"],
 
615
  })
616
 
617
  @app.get("/status")
618
- def status():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
619
  return JSONResponse(content={
620
- "stage": pipeline_status["current_stage"],
621
- "tasks": {
622
- "total": pipeline_status["total_tasks"],
623
- "finished": pipeline_status["finished_tasks"],
624
- },
625
- "stats": pipeline_status["stats"],
626
- "error": pipeline_status["error"],
627
  })
628
 
629
  # ============================================================
630
- # MAIN ENTRY POINT
631
  # ============================================================
632
 
633
  if __name__ == "__main__":
634
- # For multiprocessing on some platforms, need to set start method
635
- mp.set_start_method("spawn", force=True)
636
- uvicorn.run(app, host="0.0.0.0", port=7860, log_level="info")
 
2
  # ============================================================
3
  # PIPELINE_API.PY — FULL CONTINUED PRETRAINING DATASET PIPELINE
4
  # WITH FASTAPI HEALTH & STATUS ENDPOINTS
5
+ # ============================================================
6
+ # This script runs on a Hugging Face Space with persistent storage
7
+ # mounted at /data. It processes the dataset list below,
8
+ # validates every Python file with 4 real CPython interpreters,
9
+ # removes duplicates globally, and produces a master dataset.
10
+ #
11
+ # All state and output is stored in the bucket PERDYPTO/private.
12
+ #
13
+ # The FastAPI server starts automatically and exposes:
14
+ # /health -> current pipeline status + aggregated stats
15
+ # /status -> more detailed per‑task progress
16
  # ============================================================
17
 
18
  import os
 
22
  import gzip
23
  import shutil
24
  import hashlib
25
+ import sqlite3
26
  import subprocess
27
  import traceback
28
  import multiprocessing as mp
29
+ import requests
30
  import threading
31
+
32
  from pathlib import Path
33
  from concurrent.futures import ProcessPoolExecutor, as_completed
 
34
 
35
  import orjson
36
  from datasets import load_dataset
37
  from huggingface_hub import batch_bucket_files
38
 
39
+ from fastapi import FastAPI, BackgroundTasks
40
  from fastapi.responses import JSONResponse
41
  import uvicorn
42
 
 
44
  # BASIC CONFIG — ADAPTED FOR HF SPACE PERSISTENT STORAGE
45
  # ============================================================
46
 
47
+ # All persistent data goes under /data (the mounted bucket)
48
  DATA_ROOT = Path(os.environ.get("DATA_ROOT", "/data"))
49
+
50
+ # The pipeline root inside the mounted volume
51
  LOCAL_ROOT = DATA_ROOT / "category1_pipeline_v4"
52
  STATE_ROOT = LOCAL_ROOT / "state"
53
  TMP_ROOT = LOCAL_ROOT / "tmp"
54
  FINAL_ROOT = LOCAL_ROOT / "final"
 
55
 
56
+ for directory in [STATE_ROOT, TMP_ROOT, FINAL_ROOT]:
57
  directory.mkdir(parents=True, exist_ok=True)
58
 
59
+ # Bucket info (from your Kaggle config)
60
  BUCKET_ID = "PERDYPTO/private"
61
+
62
+ # Hugging Face token – must be set as a Space secret
63
  HF_TOKEN = os.environ.get("HF_TOKEN")
64
  if not HF_TOKEN:
65
+ raise RuntimeError("HF_TOKEN environment variable not set. Add it in Space Settings → Secrets.")
66
 
67
+ # Python versions for AST validation (these will be installed by uv in the Dockerfile)
68
  PYTHON_VERSIONS = [
69
  "3.11.9",
70
  "3.12.10",
71
  "3.13.15",
72
  "3.14.7",
73
  ]
 
74
 
75
+ # AST rule: any one version passing is accepted
76
+ AST_ACCEPT_MODE = "ANY"
77
+
78
+ # Parallelism – reduced for HF Space (2 vCPU, 16 GB RAM)
79
+ MAX_WORKERS = 2
80
+
81
+ # Shard size (number of records per uploaded file)
82
+ SHARD_ROWS = 5_000
83
+
84
+ # Checkpoint frequency (in source records)
85
+ CHECKPOINT_EVERY = 5_000
86
 
87
  # Quality filters
88
  MIN_CHARS = 100
89
  MAX_CHARS = 2_000_000
90
  MIN_LINES = 2
91
  MAX_LINE_LENGTH = 20_000
92
+
93
  REJECT_GENERATED = True
94
  REJECT_VENDOR = True
95
 
 
102
  # ============================================================
103
  # DATASET LIST – CATEGORY 1 (SOURCE CODE ONLY)
104
  # ============================================================
105
+ # This is your starting list. You can extend it with the
106
+ # additional verified/LLM-generated datasets we discussed.
107
+ # All datasets must be Python‑only (or filtered via path/kind).
108
+ # ============================================================
109
 
110
  DATASETS = [
111
  {
 
200
  }
201
  ]
202
 
 
203
  # ============================================================
204
  # GLOBAL STATE FOR API
205
  # ============================================================
 
207
  pipeline_status = {
208
  "started": False,
209
  "completed": False,
210
+ "current_stage": "idle", # idle | processing | global_dedup | done | failed
211
  "total_tasks": 0,
212
  "finished_tasks": 0,
213
  "stats": {
 
223
  }
224
 
225
  # ============================================================
226
+ # HELPER FUNCTIONS (identical to your Kaggle code)
227
  # ============================================================
228
 
229
  def retry(fn, label, retries=5):
 
233
  return fn()
234
  except Exception as e:
235
  last_error = e
236
+ print(f"[RETRY] {label} {attempt}/{retries}: {e}")
237
  if attempt < retries:
238
  time.sleep(min(30, 2 ** attempt))
239
  raise last_error
 
295
  return False, "binary_like"
296
  return True, "ok"
297
 
298
+ def get_first(row, fields, default=""):
299
+ for field in fields:
300
+ if field not in row:
301
+ continue
302
+ value = row[field]
303
+ if value is None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
304
  continue
305
+ if isinstance(value, str):
306
+ if value.strip():
307
+ return value
308
+ elif isinstance(value, (int, float, bool)):
309
+ return str(value)
310
+ return default
311
+
312
+ def extract_record(row, cfg):
313
+ text = get_first(row, cfg["text_fields"])
314
+ repo = get_first(row, cfg["repo_fields"])
315
+ path = get_first(row, cfg["path_fields"])
316
+ license_name = get_first(row, cfg["license_fields"], "unknown")
317
+ # RealPBT nested repo metadata
318
+ if cfg["kind"] == "realpbt":
319
+ repo_obj = row.get("repo")
320
+ if isinstance(repo_obj, dict):
321
+ repo = repo_obj.get("name") or repo_obj.get("full_name") or repo_obj.get("url") or repo
322
+ license_name = repo_obj.get("license") or repo_obj.get("license_type") or license_name
323
+ return {
324
+ "text": text,
325
+ "repo": str(repo),
326
+ "path": str(path),
327
+ "license": str(license_name),
328
+ }
329
 
330
  # ============================================================
331
+ # AST VALIDATOR (subprocess workers for 4 Python versions)
332
  # ============================================================
333
 
334
+ AST_CHILD_CODE = r'''
335
+ import ast
336
+ import sys
337
+ import base64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
338
 
339
+ for line in sys.stdin:
340
+ line = line.rstrip("\n")
341
+ if not line:
342
+ continue
343
  try:
344
+ source = base64.b64decode(line).decode("utf-8")
345
+ ast.parse(source)
346
+ print("OK", flush=True)
347
  except Exception as e:
348
+ print("ERR\t" + type(e).__name__ + "\t" + str(e)[:300], flush=True)
349
+ '''
350
+
351
+ class ASTWorker:
352
+ def __init__(self, version, executable):
353
+ self.version = version
354
+ self.executable = executable
355
+ self.process = subprocess.Popen(
356
+ [executable, "-u", "-c", AST_CHILD_CODE],
357
+ stdin=subprocess.PIPE,
358
+ stdout=subprocess.PIPE,
359
+ stderr=subprocess.PIPE,
360
+ text=True,
361
+ bufsize=1,
362
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
363
 
364
+ def check(self, text):
365
+ import base64
366
+ encoded = base64.b64encode(text.encode("utf-8", errors="strict")).decode("ascii")
367
+ self.process.stdin.write(encoded + "\n")
368
+ self.process.stdin.flush()
369
+ result = self.process.stdout.readline().rstrip("\n")
370
+ return (result == "OK", result)
 
 
 
 
 
 
371
 
372
+ def close(self):
373
+ try:
374
+ self.process.stdin.close()
375
+ except Exception:
376
+ pass
377
+ try:
378
+ self.process.terminate()
379
+ except Exception:
380
+ pass
381
+ try:
382
+ self.process.wait(timeout=5)
383
+ except Exception:
384
+ try:
385
+ self.process.kill()
386
+ except Exception:
387
+ pass
388
+
389
+ class ASTValidator:
390
+ def __init__(self, interpreters):
391
+ self.workers = []
392
+ for version in PYTHON_VERSIONS:
393
+ self.workers.append(ASTWorker(version, interpreters[version]))
394
+
395
+ def validate(self, text):
396
+ results = {}
397
+ for worker in self.workers:
398
+ try:
399
+ passed, detail = worker.check(text)
400
+ except Exception as e:
401
+ passed = False
402
+ detail = repr(e)
403
+ results[worker.version] = {"passed": bool(passed), "detail": detail}
404
+ if passed:
405
+ return True, results
406
+ return False, results
407
+
408
+ def close(self):
409
+ for worker in self.workers:
410
+ try:
411
+ worker.close()
412
+ except Exception:
413
+ pass
414
 
415
+ # ============================================================
416
+ # LOCAL STATE MANAGEMENT (with remote fallback)
417
+ # ============================================================
 
 
 
 
418
 
419
+ def task_state_path(dataset_name, task_id):
420
+ directory = STATE_ROOT / dataset_name
421
+ directory.mkdir(parents=True, exist_ok=True)
422
+ return directory / f"task_{task_id}.json"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
423
 
424
+ def default_state():
425
  return {
426
+ "processed": 0,
427
+ "accepted": 0,
428
+ "duplicate_exact": 0,
429
+ "duplicate_normalized": 0,
430
+ "syntax_error": 0,
431
+ "quality_reject": 0,
432
+ "other_reject": 0,
433
+ "shards_uploaded": 0,
434
+ "bytes_accepted": 0,
435
+ "complete": False,
436
+ "started": time.time(),
437
+ "updated": time.time(),
438
  }
439
 
440
+ def load_task_state(dataset_name, task_id):
441
+ path = task_state_path(dataset_name, task_id)
442
+ if path.exists():
443
+ try:
444
+ with open(path) as f:
445
+ return json.load(f)
446
+ except Exception:
447
+ pass
448
+ # Try to download from bucket
449
+ remote_path = f"{REMOTE_STATE}/{dataset_name}/task_{task_id}.json"
450
+ try:
451
+ import requests
452
+ url = f"https://huggingface.co/buckets/{BUCKET_ID}/resolve/{remote_path}"
453
+ response = requests.get(url, headers={"Authorization": f"Bearer {HF_TOKEN}"})
454
+ if response.status_code == 200:
455
+ data = response.json()
456
+ path.parent.mkdir(parents=True, exist_ok=True)
457
+ with open(path, "w") as f:
458
+ json.dump(data, f, indent=2)
459
+ return data
460
+ except Exception as e:
461
+ print(f"Could not load remote state: {e}")
462
+ return default_state()
463
+
464
+ def save_task_state(dataset_name, task_id, state):
465
+ path = task_state_path(dataset_name, task_id)
466
+ tmp = path.with_suffix(".tmp")
467
+ state["updated"] = time.time()
468
+ with open(tmp, "w") as f:
469
+ json.dump(state, f, indent=2)
470
+ os.replace(tmp, path)
471
+ upload_file(path, f"{REMOTE_STATE}/{dataset_name}/task_{task_id}.json")
472
+
473
  # ============================================================
474
+ # DATASET STREAMING LOADER
475
  # ============================================================
476
 
477
+ def load_stream(cfg):
478
+ kwargs = {"split": cfg["split"], "streaming": True, "token": HF_TOKEN}
479
+ if cfg.get("config"):
480
+ kwargs["name"] = cfg["config"]
481
+ if cfg.get("data_dir"):
482
+ kwargs["data_dir"] = cfg["data_dir"]
483
+ if cfg.get("languages"):
484
+ kwargs["languages"] = cfg["languages"]
485
+ return load_dataset(cfg["dataset"], **kwargs)
486
 
487
+ # ============================================================
488
+ # SHARD UPLOAD (worker shard)
489
+ # ============================================================
 
 
490
 
491
+ def upload_worker_shard(cfg, task_id, shard_number, records):
492
+ dataset_name = cfg["name"]
493
+ worker_dir = TMP_ROOT / dataset_name / f"task_{task_id}"
494
+ worker_dir.mkdir(parents=True, exist_ok=True)
495
+ filename = f"task-{task_id:04d}-shard-{shard_number:08d}.jsonl.gz"
496
+ local_path = worker_dir / filename
497
+ remote_path = f"{REMOTE_DATA}/{dataset_name}/task_{task_id}/{filename}"
498
+ with gzip.open(local_path, "wb") as f:
499
+ for record in records:
500
+ f.write(orjson.dumps(record) + b"\n")
501
+ upload_file(local_path, remote_path)
502
+ try:
503
+ local_path.unlink()
504
+ except Exception:
505
+ pass
506
+ return remote_path
507
 
508
+ # ============================================================
509
+ # PARTITION PROCESSING (one task = one deterministic shard slice)
510
+ # ============================================================
 
 
 
 
 
511
 
512
+ def process_partition(cfg, task_id, total_tasks, interpreters):
513
+ dataset_name = cfg["name"]
514
+ print(f"\n[{dataset_name}] TASK {task_id + 1}/{total_tasks} START")
515
+ state = load_task_state(dataset_name, task_id)
516
+ if state.get("complete", False):
517
+ print(f"[{dataset_name}] TASK {task_id} already complete.")
518
+ return {**state, "task_id": task_id, "complete": True}
519
+
520
+ # Load dataset and shard it into total_tasks partitions
521
+ ds = load_stream(cfg)
522
+ ds = ds.shard(num_shards=total_tasks, index=task_id)
523
+ print(f"[{dataset_name}] TASK {task_id}: assigned partition {task_id + 1}/{total_tasks}")
524
+
525
+ processed = int(state.get("processed", 0))
526
+ if processed > 0:
527
+ print(f"[{dataset_name}] TASK {task_id}: resuming after {processed:,} records")
528
+ ds = ds.skip(processed)
529
+
530
+ validator = ASTValidator(interpreters)
531
+
532
+ # Local dedup SQLite for this task
533
+ task_dir = STATE_ROOT / dataset_name
534
+ task_dir.mkdir(parents=True, exist_ok=True)
535
+ db_path = task_dir / f"task_{task_id}.sqlite"
536
+ conn = sqlite3.connect(db_path, timeout=120)
537
+ conn.execute("CREATE TABLE IF NOT EXISTS fingerprints (exact_hash TEXT PRIMARY KEY, normalized_hash TEXT NOT NULL)")
538
+ conn.execute("CREATE INDEX IF NOT EXISTS idx_normalized ON fingerprints(normalized_hash)")
539
+ conn.commit()
540
+
541
+ records = []
542
+ shard_number = int(state.get("shards_uploaded", 0))
543
+ last_progress = time.time()
544
 
545
+ try:
546
+ for row in ds:
547
+ state["processed"] += 1
548
 
 
 
 
549
  try:
550
+ extracted = extract_record(row, cfg)
551
+ text = extracted["text"]
552
+ except Exception:
553
+ state["other_reject"] += 1
 
554
  continue
555
+ if not text:
556
+ state["other_reject"] += 1
 
 
557
  continue
558
 
559
+ # Python file extension filter for certain kinds
560
+ path_lower = extracted["path"].lower()
561
+ if cfg["kind"] == "realpbt":
562
+ source_file = str(row.get("source_file", "")).lower()
563
+ if source_file and not source_file.endswith(".py"):
564
+ state["quality_reject"] += 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
565
  continue
566
+ if path_lower and not path_lower.endswith(".py"):
567
+ state["quality_reject"] += 1
 
 
 
 
 
 
568
  continue
569
+
570
+ # Generated / vendor filters
571
+ if REJECT_GENERATED and row.get("is_generated") is True:
572
+ state["quality_reject"] += 1
573
+ continue
574
+ if REJECT_GENERATED and row.get("autogenerated") is True:
575
+ state["quality_reject"] += 1
576
+ continue
577
+ if REJECT_VENDOR and row.get("is_vendor") is True:
578
+ state["quality_reject"] += 1
579
+ continue
580
+
581
+ good, reason = quality_check(text)
582
+ if not good:
583
+ state["quality_reject"] += 1
584
+ continue
585
+
586
+ try:
587
+ ehash = exact_hash(text)
588
+ nhash = normalized_hash(text)
589
+ except Exception:
590
+ state["other_reject"] += 1
591
+ continue
592
+
593
+ # Local dedup (within this task)
594
+ duplicate = conn.execute("SELECT exact_hash, normalized_hash FROM fingerprints WHERE exact_hash = ? OR normalized_hash = ? LIMIT 1", (ehash, nhash)).fetchone()
595
+ if duplicate is not None:
596
+ if duplicate[0] == ehash:
597
+ state["duplicate_exact"] += 1
598
+ else:
599
+ state["duplicate_normalized"] += 1
600
+ continue
601
+
602
+ # AST validation: any version passes → accept
603
+ try:
604
+ ast_ok, ast_results = validator.validate(text)
605
+ except Exception:
606
+ ast_ok = False
607
+ ast_results = {}
608
+ if not ast_ok:
609
+ state["syntax_error"] += 1
610
+ continue
611
+
612
+ # ACCEPT
613
+ record = {
614
+ "text": text,
615
+ "source_dataset": cfg["dataset"],
616
+ "source_pool": dataset_name,
617
+ "repo": extracted["repo"],
618
+ "path": extracted["path"],
619
+ "license": extracted["license"],
620
+ "exact_sha256": ehash,
621
+ "normalized_sha256": nhash,
622
+ "char_count": len(text),
623
+ "line_count": len(text.splitlines()),
624
+ "ast_validation": {v: r["passed"] for v, r in ast_results.items()},
625
+ "python_ast_versions": PYTHON_VERSIONS,
626
+ "ast_acceptance_rule": "ANY",
 
 
627
  }
 
 
628
 
629
+ conn.execute("INSERT OR IGNORE INTO fingerprints (exact_hash, normalized_hash) VALUES (?, ?)", (ehash, nhash))
630
+ state["accepted"] += 1
631
+ state["bytes_accepted"] += len(text.encode("utf-8", errors="ignore"))
632
+ records.append(record)
633
+
634
+ # Shard upload
635
+ if len(records) >= SHARD_ROWS:
636
+ conn.commit()
637
+ upload_worker_shard(cfg, task_id, shard_number, records)
638
+ shard_number += 1
639
+ state["shards_uploaded"] = shard_number
640
+ records = []
641
+ save_task_state(dataset_name, task_id, state)
642
+ print(f"[{dataset_name}] T{task_id} processed={state['processed']:,} | accepted={state['accepted']:,} | syntax={state['syntax_error']:,} | shards={state['shards_uploaded']:,}")
643
+
644
+ # Periodic checkpoint
645
+ if state["processed"] % CHECKPOINT_EVERY == 0:
646
+ conn.commit()
647
+ save_task_state(dataset_name, task_id, state)
648
+
649
+ # Live progress
650
+ now = time.time()
651
+ if now - last_progress >= 15:
652
+ elapsed = max(1, now - state["started"])
653
+ rate = state["processed"] / elapsed
654
+ print(f"[{dataset_name}] T{task_id} processed={state['processed']:,} | accepted={state['accepted']:,} | syntax={state['syntax_error']:,} | rate={rate:.1f}/sec")
655
+ last_progress = now
656
+
657
+ # Final partial shard
658
+ conn.commit()
659
+ if records:
660
+ upload_worker_shard(cfg, task_id, shard_number, records)
661
+ shard_number += 1
662
+ state["shards_uploaded"] = shard_number
663
+ records = []
664
+ conn.commit()
665
+
666
+ state["complete"] = True
667
+ state["finished"] = time.time()
668
+ save_task_state(dataset_name, task_id, state)
669
+
670
+ completion = {
671
+ "dataset": cfg["dataset"],
672
+ "dataset_name": dataset_name,
673
+ "task_id": task_id,
674
+ "total_tasks": total_tasks,
675
+ "complete": True,
676
+ "processed": state["processed"],
677
+ "accepted": state["accepted"],
678
+ "duplicate_exact": state["duplicate_exact"],
679
+ "duplicate_normalized": state["duplicate_normalized"],
680
+ "syntax_error": state["syntax_error"],
681
+ "python_ast_versions": PYTHON_VERSIONS,
682
+ "ast_acceptance_rule": "ANY",
683
+ }
684
+ completion_path = STATE_ROOT / dataset_name / f"task_{task_id}_COMPLETE.json"
685
+ with open(completion_path, "w") as f:
686
+ json.dump(completion, f, indent=2)
687
+ upload_file(completion_path, f"{REMOTE_STATE}/{dataset_name}/task_{task_id}_COMPLETE.json")
688
 
689
+ print(f"\n[{dataset_name}] TASK {task_id} COMPLETE")
690
+ return {**state, "task_id": task_id, "complete": True}
 
 
 
 
 
 
691
 
692
+ except Exception as e:
693
+ print("\n" + "!" * 80)
694
+ print(f"[{dataset_name}] TASK {task_id} FAILED")
695
+ print(traceback.format_exc())
696
+ try:
697
+ conn.commit()
698
+ save_task_state(dataset_name, task_id, state)
699
+ except Exception as checkpoint_error:
700
+ print("Checkpoint error:", checkpoint_error)
701
+ return {**state, "task_id": task_id, "complete": False, "error": repr(e)}
702
+
703
+ finally:
704
+ try:
705
+ conn.commit()
706
+ conn.close()
707
+ except Exception:
708
+ pass
709
+ try:
710
+ validator.close()
711
+ except Exception:
712
+ pass
713
 
714
  # ============================================================
715
+ # LOCATE PYTHON INTERPRETERS (installed by uv in Dockerfile)
716
+ # ============================================================
717
+
718
+ def get_interpreters():
719
+ interpreters = {}
720
+ for version in PYTHON_VERSIONS:
721
+ # Try uv find
722
+ result = subprocess.run(["uv", "python", "find", version], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
723
+ if result.returncode == 0:
724
+ path = result.stdout.strip().splitlines()[-1] if result.stdout else None
725
+ if path and Path(path).exists():
726
+ interpreters[version] = path
727
+ continue
728
+ # Fallback: search in PATH
729
+ major, minor = version.split(".")[0], version.split(".")[1]
730
+ check = subprocess.run(["which", f"python{major}.{minor}"], text=True, stdout=subprocess.PIPE)
731
+ if check.returncode == 0:
732
+ interpreters[version] = check.stdout.strip()
733
+ continue
734
+ raise RuntimeError(f"Could not find Python {version}")
735
+ return interpreters
736
+
737
+ # ============================================================
738
+ # PIPELINE RUNNER (updates global status)
739
  # ============================================================
740
 
741
+ def run_pipeline():
742
+ global pipeline_status
743
+ pipeline_status["started"] = True
744
+ pipeline_status["current_stage"] = "processing"
745
+ pipeline_status["total_tasks"] = 0
746
+ pipeline_status["finished_tasks"] = 0
747
+
748
+ try:
749
+ # Get interpreters
750
+ interpreters = get_interpreters()
751
+ print("Python interpreters found:")
752
+ for v, p in interpreters.items():
753
+ print(f" {v} -> {p}")
754
+
755
+ # Determine shard counts and build task queue
756
+ DATASET_TASKS = []
757
+ for cfg in DATASETS:
758
+ ds = load_stream(cfg)
759
+ num_shards = int(getattr(ds, "num_shards", 1) or 1)
760
+ total_tasks = min(MAX_WORKERS, num_shards)
761
+ print(f"[QUEUE] {cfg['name']}: {num_shards:,} underlying shards -> {total_tasks} tasks")
762
+ pipeline_status["total_tasks"] += total_tasks
763
+ for task_id in range(total_tasks):
764
+ DATASET_TASKS.append({
765
+ "cfg": cfg,
766
+ "task_id": task_id,
767
+ "total_tasks": total_tasks,
768
+ "num_shards": num_shards,
769
+ })
770
+
771
+ print(f"Total scheduled task partitions: {len(DATASET_TASKS):,}")
772
+
773
+ # Run tasks concurrently (at most MAX_WORKERS at a time)
774
+ results = {}
775
+ task_cursor = 0
776
+ active = {}
777
+ with ProcessPoolExecutor(max_workers=MAX_WORKERS) as executor:
778
+ # initial fill
779
+ while len(active) < MAX_WORKERS and task_cursor < len(DATASET_TASKS):
780
+ task = DATASET_TASKS[task_cursor]
781
+ task_cursor += 1
782
+ future = executor.submit(process_partition, task["cfg"], task["task_id"], task["total_tasks"], interpreters)
783
+ active[future] = task
784
+ print(f"[SCHEDULER] STARTED {task['cfg']['name']} T{task['task_id']}")
785
+
786
+ # Continue until all tasks done
787
+ while active:
788
+ for completed_future in as_completed(active.keys()):
789
+ task = active.pop(completed_future)
790
+ try:
791
+ result = completed_future.result()
792
+ except Exception as e:
793
+ result = {"complete": False, "error": repr(e), "task_id": task["task_id"]}
794
+ key = (task["cfg"]["name"], task["task_id"])
795
+ results[key] = result
796
+ pipeline_status["finished_tasks"] += 1
797
+ print(f"\n[SCHEDULER] FINISHED {task['cfg']['name']} T{task['task_id']} complete={result.get('complete', False)}")
798
+
799
+ # Fill the slot immediately
800
+ if task_cursor < len(DATASET_TASKS):
801
+ next_task = DATASET_TASKS[task_cursor]
802
+ task_cursor += 1
803
+ future = executor.submit(process_partition, next_task["cfg"], next_task["task_id"], next_task["total_tasks"], interpreters)
804
+ active[future] = next_task
805
+ print(f"[SCHEDULER] STARTED {next_task['cfg']['name']} T{next_task['task_id']}")
806
+ break # break to re-enter as_completed
807
+
808
+ # ============================================================
809
+ # GLOBAL DEDUP (across all tasks/datasets)
810
+ # ============================================================
811
+ pipeline_status["current_stage"] = "global_dedup"
812
+ print("\n" + "=" * 90)
813
+ print("STARTING GLOBAL CATEGORY 1 DEDUP")
814
+ print("=" * 90)
815
+
816
+ GLOBAL_DB = FINAL_ROOT / "global_dedup.sqlite"
817
+ gconn = sqlite3.connect(GLOBAL_DB, timeout=120)
818
+ gconn.execute("CREATE TABLE IF NOT EXISTS fingerprints (exact_hash TEXT PRIMARY KEY, normalized_hash TEXT NOT NULL)")
819
+ gconn.execute("CREATE INDEX IF NOT EXISTS idx_global_normalized ON fingerprints(normalized_hash)")
820
+ gconn.commit()
821
+
822
+ global_stats = {"input_records": 0, "accepted_records": 0, "duplicate_exact": 0, "duplicate_normalized": 0, "invalid_records": 0, "bytes": 0}
823
+ global_records = []
824
+ global_shard_number = 0
825
+
826
+ def flush_global():
827
+ nonlocal global_records, global_shard_number
828
+ if not global_records:
829
+ return
830
+ filename = f"category1-master-{global_shard_number:08d}.jsonl.gz"
831
+ local_path = FINAL_ROOT / filename
832
+ with gzip.open(local_path, "wb") as f:
833
+ for record in global_records:
834
+ f.write(orjson.dumps(record) + b"\n")
835
+ remote_path = f"{REMOTE_FINAL}/{filename}"
836
+ upload_file(local_path, remote_path)
837
+ try:
838
+ local_path.unlink()
839
+ except Exception:
840
+ pass
841
+ global_records = []
842
+ global_shard_number += 1
843
+
844
+ # Collect all remote shard paths from completed tasks
845
+ REMOTE_SHARDS = []
846
+ for task in DATASET_TASKS:
847
+ key = (task["cfg"]["name"], task["task_id"])
848
+ result = results.get(key, {})
849
+ shard_count = int(result.get("shards_uploaded", 0))
850
+ for shard_number in range(shard_count):
851
+ filename = f"task-{task['task_id']:04d}-shard-{shard_number:08d}.jsonl.gz"
852
+ remote_path = f"{REMOTE_DATA}/{task['cfg']['name']}/task_{task['task_id']}/{filename}"
853
+ REMOTE_SHARDS.append((task['cfg']['name'], task['task_id'], shard_number, remote_path))
854
+
855
+ print(f"Remote worker shards: {len(REMOTE_SHARDS):,}")
856
+
857
+ # Download each shard, dedup globally, and write final master shards
858
+ for idx, (dataset_name, task_id, shard_number, remote_path) in enumerate(REMOTE_SHARDS, 1):
859
+ print(f"\n[GLOBAL] {idx:,}/{len(REMOTE_SHARDS):,} {dataset_name} T{task_id} S{shard_number}")
860
+ local_path = TMP_ROOT / "global" / dataset_name / f"task_{task_id}" / Path(remote_path).name
861
+ # Download using requests
862
+ try:
863
+ url = f"https://huggingface.co/buckets/{BUCKET_ID}/resolve/{remote_path}"
864
+ response = requests.get(url, headers={"Authorization": f"Bearer {HF_TOKEN}"})
865
+ if response.status_code != 200:
866
+ raise RuntimeError(f"Download failed: {response.status_code}")
867
+ local_path.parent.mkdir(parents=True, exist_ok=True)
868
+ with open(local_path, "wb") as f:
869
+ f.write(response.content)
870
+ except Exception as e:
871
+ print(f"Download error: {e}")
872
+ continue
873
 
874
+ with gzip.open(local_path, "rb") as f:
875
+ for line in f:
876
+ global_stats["input_records"] += 1
877
+ try:
878
+ record = orjson.loads(line)
879
+ ehash = record["exact_sha256"]
880
+ nhash = record["normalized_sha256"]
881
+ except Exception:
882
+ global_stats["invalid_records"] += 1
883
+ continue
884
+
885
+ duplicate = gconn.execute("SELECT exact_hash, normalized_hash FROM fingerprints WHERE exact_hash = ? OR normalized_hash = ? LIMIT 1", (ehash, nhash)).fetchone()
886
+ if duplicate is not None:
887
+ if duplicate[0] == ehash:
888
+ global_stats["duplicate_exact"] += 1
889
+ else:
890
+ global_stats["duplicate_normalized"] += 1
891
+ continue
892
+
893
+ gconn.execute("INSERT INTO fingerprints (exact_hash, normalized_hash) VALUES (?, ?)", (ehash, nhash))
894
+ global_records.append(record)
895
+ global_stats["accepted_records"] += 1
896
+ global_stats["bytes"] += int(record.get("char_count", 0))
897
+
898
+ if len(global_records) >= SHARD_ROWS:
899
+ gconn.commit()
900
+ flush_global()
901
+
902
+ gconn.commit()
903
+ try:
904
+ local_path.unlink()
905
+ except Exception:
906
+ pass
907
+
908
+ if idx % 10 == 0 or idx == len(REMOTE_SHARDS):
909
+ print(f"[GLOBAL] input={global_stats['input_records']:,} | accepted={global_stats['accepted_records']:,} | exact_dup={global_stats['duplicate_exact']:,} | normalized_dup={global_stats['duplicate_normalized']:,}")
910
+
911
+ # Final flush
912
+ gconn.commit()
913
+ flush_global()
914
+ gconn.commit()
915
+ gconn.close()
916
+
917
+ # Upload global DB
918
+ upload_file(GLOBAL_DB, f"{REMOTE_FINAL}/global_dedup.sqlite")
919
+
920
+ # Final metadata
921
+ final_metadata = {
922
+ "name": "Category 1 Python Master",
923
+ "pipeline_version": "v4",
924
+ "source_datasets": [cfg["dataset"] for cfg in DATASETS],
925
+ "max_workers": MAX_WORKERS,
926
+ "python_ast_versions": PYTHON_VERSIONS,
927
+ "ast_acceptance_rule": "ANY",
928
+ "dedup": {"exact_sha256": True, "normalized_sha256": True, "ast_structure_as_key": False},
929
+ "statistics": global_stats,
930
+ "final_shards": global_shard_number,
931
+ "created": time.time(),
932
+ }
933
+ metadata_path = FINAL_ROOT / "dataset_metadata.json"
934
+ with open(metadata_path, "w") as f:
935
+ json.dump(final_metadata, f, indent=2)
936
+ upload_file(metadata_path, f"{REMOTE_FINAL}/dataset_metadata.json")
937
+
938
+ # Update global status with final stats
939
+ pipeline_status["stats"] = global_stats
940
+ pipeline_status["stats"]["final_shards"] = global_shard_number
941
+ pipeline_status["completed"] = True
942
+ pipeline_status["current_stage"] = "done"
943
+
944
+ print("\n" + "=" * 90)
945
+ print("CATEGORY 1 — COMPLETE")
946
+ print("=" * 90)
947
+ print(f"Input records: {global_stats['input_records']:,}")
948
+ print(f"Final accepted: {global_stats['accepted_records']:,}")
949
+ print(f"Global exact duplicates: {global_stats['duplicate_exact']:,}")
950
+ print(f"Global normalized duplicates: {global_stats['duplicate_normalized']:,}")
951
+ print(f"Final master shards: {global_shard_number:,}")
952
+ print("\nAST validation: ANY ONE VERSION PASS = ACCEPT")
953
+ print(f"Master location: hf://buckets/{BUCKET_ID}/{REMOTE_FINAL}/")
954
+ print("=" * 90)
955
+
956
+ except Exception as e:
957
+ pipeline_status["current_stage"] = "failed"
958
+ pipeline_status["error"] = str(e)
959
+ print("PIPELINE FAILED:", traceback.format_exc())
960
+ raise
961
+
962
+ # ============================================================
963
+ # FASTAPI APP
964
+ # ============================================================
965
+
966
+ app = FastAPI(title="Category1 Pipeline API")
967
 
968
  @app.on_event("startup")
969
  def startup_event():
970
+ # Launch pipeline in a background thread so the API stays responsive
971
+ thread = threading.Thread(target=run_pipeline, daemon=True)
972
+ thread.start()
973
 
974
  @app.get("/health")
975
+ async def health():
976
+ """
977
+ Returns current pipeline statistics and health status.
978
+ """
979
  return JSONResponse(content={
980
  "status": pipeline_status["current_stage"],
981
  "started": pipeline_status["started"],
982
  "completed": pipeline_status["completed"],
983
+ "total_tasks": pipeline_status["total_tasks"],
984
+ "finished_tasks": pipeline_status["finished_tasks"],
985
  "stats": pipeline_status["stats"],
986
+ "error": pipeline_status["error"],
987
  })
988
 
989
  @app.get("/status")
990
+ async def status():
991
+ """
992
+ Returns detailed per‑dataset task status (reads state files).
993
+ For a deeper view, you can scan STATE_ROOT/*/task_*_COMPLETE.json.
994
+ """
995
+ # Gather completion files for all datasets
996
+ detailed = {}
997
+ for dataset_dir in STATE_ROOT.iterdir():
998
+ if dataset_dir.is_dir():
999
+ dataset_name = dataset_dir.name
1000
+ completions = list(dataset_dir.glob("task_*_COMPLETE.json"))
1001
+ detailed[dataset_name] = {"completed_tasks": len(completions)}
1002
+ for comp_path in completions:
1003
+ try:
1004
+ with open(comp_path) as f:
1005
+ data = json.load(f)
1006
+ detailed[dataset_name][comp_path.stem] = data
1007
+ except Exception:
1008
+ pass
1009
  return JSONResponse(content={
1010
+ "pipeline_status": pipeline_status,
1011
+ "per_dataset": detailed,
 
 
 
 
 
1012
  })
1013
 
1014
  # ============================================================
1015
+ # MAIN ENTRY POINT FOR UVICORN
1016
  # ============================================================
1017
 
1018
  if __name__ == "__main__":
1019
+ # Use the PORT environment variable if set (HF Spaces default 7860)
1020
+ port = int(os.environ.get("PORT", 7860))
1021
+ uvicorn.run(app, host="0.0.0.0", port=port)