Spaces:
Sleeping

PERDYPTO commited on
Commit
804bc4d
·
verified ·
1 Parent(s): c7de960

Update pipeline.py

Browse files
Files changed (1) hide show
  1. pipeline.py +442 -485
pipeline.py CHANGED
@@ -1,7 +1,20 @@
 
1
  #!/usr/bin/env python3
2
  # ============================================================
3
- # PIPELINE_API.PY — COORDINATOR‑WORKER PIPELINE WITH
4
- # GLOBAL DEDUP, RESUME, AND FILE OUTPUT
 
 
 
 
 
 
 
 
 
 
 
 
5
  # ============================================================
6
 
7
  import os
@@ -9,6 +22,7 @@ import sys
9
  import json
10
  import time
11
  import gzip
 
12
  import hashlib
13
  import sqlite3
14
  import subprocess
@@ -18,12 +32,13 @@ import requests
18
  import threading
19
  from pathlib import Path
20
  from concurrent.futures import ProcessPoolExecutor, as_completed
21
- from queue import Empty
22
 
23
  import orjson
24
- from datasets import load_dataset, Features, Value, Sequence
25
  from huggingface_hub import batch_bucket_files
26
- from fastapi import FastAPI
 
27
  from fastapi.responses import JSONResponse
28
  import uvicorn
29
 
@@ -36,19 +51,30 @@ LOCAL_ROOT = DATA_ROOT / "category1_pipeline_v4"
36
  STATE_ROOT = LOCAL_ROOT / "state"
37
  TMP_ROOT = LOCAL_ROOT / "tmp"
38
  FINAL_ROOT = LOCAL_ROOT / "final"
39
- for d in [STATE_ROOT, TMP_ROOT, FINAL_ROOT]:
40
- d.mkdir(parents=True, exist_ok=True)
 
41
 
42
  BUCKET_ID = "PERDYPTO/private"
43
  HF_TOKEN = os.environ.get("HF_TOKEN")
44
  if not HF_TOKEN:
45
- raise RuntimeError("HF_TOKEN environment variable not set. Add it in Space Settings → Secrets.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
- PYTHON_VERSIONS = ["3.11.9", "3.12.10", "3.13.15", "3.14.7"]
48
- AST_ACCEPT_MODE = "ANY"
49
- MAX_WORKERS = 2 # number of worker processes
50
- SHARD_ROWS = 5_000 # master shard size
51
- CHECKPOINT_EVERY = 5_000 # not used in coordinator version
52
  MIN_CHARS = 100
53
  MAX_CHARS = 2_000_000
54
  MIN_LINES = 2
@@ -56,6 +82,7 @@ MAX_LINE_LENGTH = 20_000
56
  REJECT_GENERATED = True
57
  REJECT_VENDOR = True
58
 
 
59
  REMOTE_ROOT = "category1/v4"
60
  REMOTE_DATA = f"{REMOTE_ROOT}/datasets"
61
  REMOTE_STATE = f"{REMOTE_ROOT}/state"
@@ -64,6 +91,9 @@ REMOTE_FINAL = f"{REMOTE_ROOT}/final"
64
  # ============================================================
65
  # DATASET LIST – CATEGORY 1 (SOURCE CODE ONLY)
66
  # ============================================================
 
 
 
67
 
68
  DATASETS = [
69
  {
@@ -264,535 +294,463 @@ def quality_check(text):
264
  return False, "binary_like"
265
  return True, "ok"
266
 
267
- def get_first(row, fields, default=""):
268
- for field in fields:
269
- if field not in row:
270
- continue
271
- value = row[field]
272
- if value is None:
273
- continue
274
- if isinstance(value, str):
275
- if value.strip():
276
- return value
277
- elif isinstance(value, (int, float, bool)):
278
- return str(value)
279
- return default
280
-
281
- def extract_record(row, cfg):
282
- text = get_first(row, cfg["text_fields"])
283
- repo = get_first(row, cfg["repo_fields"])
284
- path = get_first(row, cfg["path_fields"])
285
- license_name = get_first(row, cfg["license_fields"], "unknown")
286
- if cfg["kind"] == "realpbt":
287
- repo_obj = row.get("repo")
288
- if isinstance(repo_obj, dict):
289
- repo = repo_obj.get("name") or repo_obj.get("full_name") or repo_obj.get("url") or repo
290
- license_name = repo_obj.get("license") or repo_obj.get("license_type") or license_name
291
- return {
292
- "text": text,
293
- "repo": str(repo),
294
- "path": str(path),
295
- "license": str(license_name),
296
- }
297
-
298
- # ============================================================
299
- # AST VALIDATOR (unchanged)
300
- # ============================================================
301
-
302
- AST_CHILD_CODE = r'''
303
- import ast
304
- import sys
305
- import base64
306
-
307
- for line in sys.stdin:
308
- line = line.rstrip("\n")
309
- if not line:
310
- continue
311
- try:
312
- source = base64.b64decode(line).decode("utf-8")
313
- ast.parse(source)
314
- print("OK", flush=True)
315
- except Exception as e:
316
- print("ERR\t" + type(e).__name__ + "\t" + str(e)[:300], flush=True)
317
- '''
318
-
319
- class ASTWorker:
320
- def __init__(self, version, executable):
321
- self.version = version
322
- self.executable = executable
323
- self.process = subprocess.Popen(
324
- [executable, "-u", "-c", AST_CHILD_CODE],
325
- stdin=subprocess.PIPE,
326
- stdout=subprocess.PIPE,
327
- stderr=subprocess.PIPE,
328
- text=True,
329
- bufsize=1,
330
- )
331
-
332
- def check(self, text):
333
- import base64
334
- encoded = base64.b64encode(text.encode("utf-8", errors="strict")).decode("ascii")
335
- self.process.stdin.write(encoded + "\n")
336
- self.process.stdin.flush()
337
- result = self.process.stdout.readline().rstrip("\n")
338
- return (result == "OK", result)
339
 
340
- def close(self):
341
- try:
342
- self.process.stdin.close()
343
- except Exception:
344
- pass
345
- try:
346
- self.process.terminate()
347
- except Exception:
348
- pass
349
  try:
350
- self.process.wait(timeout=5)
 
351
  except Exception:
352
- try:
353
- self.process.kill()
354
- except Exception:
355
- pass
356
-
357
- class ASTValidator:
358
- def __init__(self, interpreters):
359
- self.workers = []
360
- for version in PYTHON_VERSIONS:
361
- self.workers.append(ASTWorker(version, interpreters[version]))
362
-
363
- def validate(self, text):
364
- results = {}
365
- for worker in self.workers:
366
- try:
367
- passed, detail = worker.check(text)
368
- except Exception as e:
369
- passed = False
370
- detail = repr(e)
371
- results[worker.version] = {"passed": bool(passed), "detail": detail}
372
- if passed:
373
- return True, results
374
- return False, results
375
-
376
- def close(self):
377
- for worker in self.workers:
378
- try:
379
- worker.close()
380
- except Exception:
381
- pass
382
-
383
- # ============================================================
384
- # LOCATE PYTHON INTERPRETERS
385
- # ============================================================
386
-
387
- def get_interpreters():
388
- interpreters = {}
389
- for version in PYTHON_VERSIONS:
390
- result = subprocess.run(["uv", "python", "find", version], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
391
- if result.returncode == 0:
392
- path = result.stdout.strip().splitlines()[-1] if result.stdout else None
393
- if path and Path(path).exists():
394
- interpreters[version] = path
395
- continue
396
- major, minor = version.split(".")[0], version.split(".")[1]
397
- check = subprocess.run(["which", f"python{major}.{minor}"], text=True, stdout=subprocess.PIPE)
398
- if check.returncode == 0:
399
- interpreters[version] = check.stdout.strip()
400
  continue
401
- raise RuntimeError(f"Could not find Python {version}")
402
- return interpreters
403
 
404
  # ============================================================
405
- # DATASET LOADING WITH FIX FOR SWALLOWCODE
406
  # ============================================================
407
 
408
- def load_stream(cfg):
409
- kwargs = {"split": cfg["split"], "streaming": True, "token": HF_TOKEN}
410
- if cfg.get("config"):
411
- kwargs["name"] = cfg["config"]
412
- if cfg.get("data_dir"):
413
- kwargs["data_dir"] = cfg["data_dir"]
414
- if cfg.get("languages"):
415
- kwargs["languages"] = cfg["languages"]
416
-
417
-
418
- return load_dataset(cfg["dataset"], **kwargs)
419
-
420
- # ============================================================
421
- # WORKER FUNCTION (runs in a separate process)
422
- # ============================================================
423
-
424
- def worker_task(cfg, task_id, total_tasks, interpreters, result_queue):
425
  """
426
- Process one partition of a dataset.
427
- Sends batches of accepted records and final stats through result_queue.
 
 
 
428
  """
429
- dataset_name = cfg["name"]
430
- print(f"[WORKER] {dataset_name} T{task_id} started")
431
-
432
- # Load dataset and shard
433
- ds = load_stream(cfg)
434
- ds = ds.shard(num_shards=total_tasks, index=task_id)
435
-
436
- # Local in-memory dedup SQLite (no file)
437
- local_conn = sqlite3.connect(":memory:")
438
- local_conn.execute("CREATE TABLE IF NOT EXISTS local_fp (exact_hash TEXT PRIMARY KEY, normalized_hash TEXT NOT NULL)")
439
- local_conn.execute("CREATE INDEX IF NOT EXISTS idx_local_norm ON local_fp(normalized_hash)")
440
-
441
- validator = ASTValidator(interpreters)
442
-
443
- batch = []
444
- stats = {
445
- "processed": 0,
446
- "accepted": 0,
447
- "syntax_error": 0,
448
- "quality_reject": 0,
449
- "other_reject": 0,
450
- "duplicate_exact": 0,
451
- "duplicate_normalized": 0,
 
 
 
 
 
 
 
452
  }
 
 
 
 
453
 
454
- def send_batch():
455
- if batch:
456
- result_queue.put(("accepted_batch", batch, stats.copy()))
457
- batch.clear()
 
 
 
 
 
 
458
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
459
  for row in ds:
460
- stats["processed"] += 1
461
-
462
- try:
463
- extracted = extract_record(row, cfg)
464
- text = extracted["text"]
465
- except Exception:
466
- stats["other_reject"] += 1
467
  continue
468
- if not text:
469
- stats["other_reject"] += 1
 
 
 
 
 
 
 
 
 
 
470
  continue
471
 
472
- # quality checks
473
  ok, reason = quality_check(text)
474
  if not ok:
475
- stats["quality_reject"] += 1
 
 
476
  continue
477
 
478
- # hashes
479
- try:
480
- ehash = exact_hash(text)
481
- nhash = normalized_hash(text)
482
- except Exception:
483
- stats["other_reject"] += 1
484
- continue
485
-
486
- # local dedup
487
- dup = local_conn.execute(
488
- "SELECT exact_hash, normalized_hash FROM local_fp WHERE exact_hash=? OR normalized_hash=? LIMIT 1",
489
- (ehash, nhash)
490
- ).fetchone()
491
- if dup:
492
- if dup[0] == ehash:
493
- stats["duplicate_exact"] += 1
494
- else:
495
- stats["duplicate_normalized"] += 1
496
- continue
497
- local_conn.execute("INSERT INTO local_fp (exact_hash, normalized_hash) VALUES (?, ?)", (ehash, nhash))
498
-
499
- # AST validation
500
- try:
501
- ast_ok, ast_results = validator.validate(text)
502
- except Exception:
503
- ast_ok = False
504
- ast_results = {}
505
  if not ast_ok:
506
- stats["syntax_error"] += 1
 
 
507
  continue
508
 
509
- # Accept
510
- record = {
511
- "text": text,
512
- "source_dataset": cfg["dataset"],
513
- "source_pool": dataset_name,
514
- "repo": extracted["repo"],
515
- "path": extracted["path"],
516
- "license": extracted["license"],
517
- "exact_sha256": ehash,
518
- "normalized_sha256": nhash,
519
- "char_count": len(text),
520
- "line_count": len(text.splitlines()),
521
- "ast_validation": {v: r["passed"] for v, r in ast_results.items()},
522
- "python_ast_versions": PYTHON_VERSIONS,
523
- "ast_acceptance_rule": "ANY",
524
- }
525
- batch.append(record)
526
- stats["accepted"] += 1
527
-
528
- if len(batch) >= SHARD_ROWS:
529
- send_batch()
530
-
531
- if stats["processed"] % 5000 == 0:
532
- print(f"[WORKER] {dataset_name} T{task_id} processed={stats['processed']:,} accepted={stats['accepted']:,}")
533
 
534
- # End of stream – send remaining batch
535
- send_batch()
536
- result_queue.put(("task_done", stats, task_id, dataset_name))
537
- print(f"[WORKER] {dataset_name} T{task_id} finished. accepted={stats['accepted']}")
538
- validator.close()
539
- local_conn.close()
 
 
 
 
 
 
 
 
540
 
541
- # ============================================================
542
- # COORDINATOR CLASS (runs in main process)
543
- # ============================================================
 
 
 
 
 
544
 
545
- class Coordinator:
546
- def __init__(self):
547
- self.global_db_path = FINAL_ROOT / "global_dedup.sqlite"
548
- self.global_conn = sqlite3.connect(self.global_db_path, timeout=300)
549
- self.global_conn.execute("PRAGMA journal_mode=WAL")
550
- self.global_conn.execute("PRAGMA synchronous=NORMAL")
551
- self.global_conn.execute(
552
- "CREATE TABLE IF NOT EXISTS fingerprints (exact_hash TEXT PRIMARY KEY, normalized_hash TEXT NOT NULL)"
553
- )
554
- self.global_conn.execute("CREATE INDEX IF NOT EXISTS idx_global_norm ON fingerprints(normalized_hash)")
555
- self.global_conn.commit()
556
-
557
- self.master_records = []
558
- self.master_shard_number = 0
559
- self.stats = {
560
- "input_records": 0,
561
- "accepted_records": 0,
562
- "duplicate_exact": 0,
563
- "duplicate_normalized": 0,
564
- "invalid_records": 0,
565
- "bytes": 0,
566
- "final_shards": 0,
567
  }
568
-
569
- def flush_master_shard(self):
570
- if not self.master_records:
571
- return
572
- filename = f"category1-master-{self.master_shard_number:08d}.jsonl.gz"
573
- local_path = FINAL_ROOT / filename
574
- with gzip.open(local_path, "wb") as f:
575
- for rec in self.master_records:
576
- f.write(orjson.dumps(rec) + b"\n")
577
- remote_path = f"{REMOTE_FINAL}/{filename}"
578
- upload_file(local_path, remote_path)
579
- local_path.unlink(missing_ok=True)
580
- self.master_records = []
581
- self.master_shard_number += 1
582
- self.stats["final_shards"] = self.master_shard_number
583
-
584
- def process_accepted_batch(self, batch):
585
- for record in batch:
586
- ehash = record["exact_sha256"]
587
- nhash = record["normalized_sha256"]
588
-
589
- # Global dedup
590
- dup = self.global_conn.execute(
591
- "SELECT exact_hash FROM fingerprints WHERE exact_hash=? OR normalized_hash=? LIMIT 1",
592
- (ehash, nhash)
593
- ).fetchone()
594
- if dup:
595
- self.stats["duplicate_exact" if dup[0] == ehash else "duplicate_normalized"] += 1
596
- continue
597
-
598
- # Insert into global DB
599
- self.global_conn.execute(
600
- "INSERT INTO fingerprints (exact_hash, normalized_hash) VALUES (?, ?)",
601
- (ehash, nhash)
602
- )
603
- self.stats["accepted_records"] += 1
604
- self.stats["bytes"] += record.get("char_count", 0)
605
- self.master_records.append(record)
606
-
607
- # Save individual file to dataset/verified/
608
- dataset_name = record["source_pool"]
609
- verified_dir = FINAL_ROOT / dataset_name / "verified"
610
- verified_dir.mkdir(parents=True, exist_ok=True)
611
- orig_path = record.get("path", "")
612
- if orig_path:
613
- filename = Path(orig_path).name
614
- if not filename.endswith(".py"):
615
- filename += ".py"
616
- else:
617
- filename = f"{ehash[:16]}.py"
618
- # Avoid collisions by adding hash prefix if file exists
619
- filepath = verified_dir / filename
620
- if filepath.exists():
621
- filepath = verified_dir / f"{ehash[:16]}_{filename}"
622
- with open(filepath, "w") as f:
623
- f.write(record["text"])
624
-
625
- # Flush master shard if needed
626
- if len(self.master_records) >= SHARD_ROWS:
627
- self.flush_master_shard()
628
-
629
- # Commit every batch
630
- self.global_conn.commit()
631
-
632
- def finish(self):
633
- self.flush_master_shard()
634
- self.global_conn.commit()
635
- self.global_conn.close()
636
- # Optionally write per-dataset metadata
637
- for dataset_name in set(rec["source_pool"] for rec in self.master_records):
638
- meta_path = FINAL_ROOT / dataset_name / "metadata.json"
639
- if not meta_path.exists():
640
- # Write minimal metadata
641
- with open(meta_path, "w") as f:
642
- json.dump({
643
- "dataset": dataset_name,
644
- "accepted_count": sum(1 for r in self.master_records if r["source_pool"] == dataset_name),
645
- "processed_count": self.stats["accepted_records"], # not exact per dataset
646
- "created": time.time()
647
- }, f, indent=2)
648
 
649
  # ============================================================
650
- # PIPELINE RUNNER (uses coordinator and workers)
651
  # ============================================================
652
 
653
  def run_pipeline():
654
  global pipeline_status
655
  pipeline_status["started"] = True
656
  pipeline_status["current_stage"] = "processing"
657
-
658
- try:
659
- interpreters = get_interpreters()
660
- # Build task list
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
661
  tasks = []
662
- for cfg in DATASETS:
663
- ds = load_stream(cfg)
664
- num_shards = getattr(ds, "num_shards", 1) or 1
665
- total_tasks = min(MAX_WORKERS, num_shards)
666
- for task_id in range(total_tasks):
667
- tasks.append((cfg, task_id, total_tasks))
668
- total = len(tasks)
669
- pipeline_status["total_tasks"] = total
670
-
671
- # Create coordinator
672
- coord = Coordinator()
673
-
674
- # Set up multiprocessing queue
675
- result_queue = mp.Queue()
676
-
677
- # Start worker processes (limit to MAX_WORKERS)
678
- active = []
679
- task_idx = 0
680
-
681
- def start_worker():
682
- nonlocal task_idx
683
- if task_idx >= total:
684
- return None
685
- cfg, tid, ttot = tasks[task_idx]
686
- task_idx += 1
687
- p = mp.Process(target=worker_task, args=(cfg, tid, ttot, interpreters, result_queue))
688
- p.start()
689
- return p
690
-
691
- # initial fill
692
- for _ in range(MAX_WORKERS):
693
- p = start_worker()
694
- if p:
695
- active.append(p)
696
- else:
697
- break
698
-
699
- # main loop: process results and manage workers
700
- finished_tasks = 0
701
- while active or task_idx < total:
702
- # Check for results
703
- try:
704
- msg = result_queue.get(timeout=1)
705
- except Empty:
706
- # Check for dead workers and restart
707
- new_active = []
708
- for p in active:
709
- if p.is_alive():
710
- new_active.append(p)
711
- else:
712
- p.join()
713
- finished_tasks += 1
714
- pipeline_status["finished_tasks"] = finished_tasks
715
- if task_idx < total:
716
- newp = start_worker()
717
- if newp:
718
- new_active.append(newp)
719
- active = new_active
720
- continue
721
-
722
- # Process message
723
- if msg[0] == "accepted_batch":
724
- _, batch, worker_stats = msg
725
- coord.process_accepted_batch(batch)
726
- # Update global stats with worker stats (optional)
727
- elif msg[0] == "task_done":
728
- _, worker_stats, tid, dset = msg
729
- finished_tasks += 1
730
- pipeline_status["finished_tasks"] = finished_tasks
731
- print(f"[COORD] Task {dset} T{tid} finished, accepted={worker_stats['accepted']}")
732
- if task_idx < total:
733
- newp = start_worker()
734
- if newp:
735
- active.append(newp)
736
-
737
- # Wait for all workers to finish
738
- for p in active:
739
- p.join()
740
- finished_tasks += 1
741
- pipeline_status["finished_tasks"] = finished_tasks
742
-
743
- # Finalize coordinator
744
- coord.finish()
745
- pipeline_status["stats"] = coord.stats
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
746
  pipeline_status["completed"] = True
747
  pipeline_status["current_stage"] = "done"
748
 
749
- # Upload global DB and metadata
750
- upload_file(coord.global_db_path, f"{REMOTE_FINAL}/global_dedup.sqlite")
751
- # Also upload per-dataset metadata (if needed)
752
- for dset in DATASETS:
753
- name = dset["name"]
754
- meta_path = FINAL_ROOT / name / "metadata.json"
755
- if meta_path.exists():
756
- upload_file(meta_path, f"{REMOTE_FINAL}/{name}/metadata.json")
757
-
758
- except Exception as e:
759
- pipeline_status["current_stage"] = "failed"
760
- pipeline_status["error"] = str(e)
761
- traceback.print_exc()
762
-
763
  # ============================================================
764
  # FASTAPI APP
765
  # ============================================================
766
 
767
- app = FastAPI(title="Category1 Pipeline API")
768
 
769
  @app.on_event("startup")
770
  def startup_event():
771
- thread = threading.Thread(target=run_pipeline, daemon=True)
 
 
 
 
 
 
 
 
 
772
  thread.start()
773
 
774
  @app.get("/health")
775
- async def health():
776
  return JSONResponse(content={
777
  "status": pipeline_status["current_stage"],
778
  "started": pipeline_status["started"],
779
  "completed": pipeline_status["completed"],
780
- "total_tasks": pipeline_status["total_tasks"],
781
- "finished_tasks": pipeline_status["finished_tasks"],
782
- "stats": pipeline_status["stats"],
783
  "error": pipeline_status["error"],
 
784
  })
785
 
786
  @app.get("/status")
787
- async def status():
788
- detailed = {}
789
- for dataset_dir in STATE_ROOT.iterdir():
790
- if dataset_dir.is_dir():
791
- completions = list(dataset_dir.glob("task_*_COMPLETE.json"))
792
- detailed[dataset_dir.name] = {"completed_tasks": len(completions)}
793
  return JSONResponse(content={
794
- "pipeline_status": pipeline_status,
795
- "per_dataset": detailed,
 
 
 
 
 
796
  })
797
 
798
  # ============================================================
@@ -800,5 +758,4 @@ async def status():
800
  # ============================================================
801
 
802
  if __name__ == "__main__":
803
- port = int(os.environ.get("PORT", 7860))
804
- uvicorn.run(app, host="0.0.0.0", port=port)
 
1
+
2
  #!/usr/bin/env python3
3
  # ============================================================
4
+ # PIPELINE_API.PY — FULL CONTINUED PRETRAINING DATASET PIPELINE
5
+ # WITH FASTAPI HEALTH & STATUS ENDPOINTS
6
+ # MASTER‑WORKER ARCHITECTURE
7
+ # ============================================================
8
+ # This script runs on a Hugging Face Space with persistent storage
9
+ # mounted at /data. It processes the dataset list below,
10
+ # validates every Python file with 4 real CPython interpreters,
11
+ # removes duplicates globally, and produces a master dataset.
12
+ #
13
+ # All state and output is stored in the bucket PERDYPTO/private.
14
+ #
15
+ # The FastAPI server starts automatically and exposes:
16
+ # /health -> current pipeline status + aggregated stats
17
+ # /status -> more detailed per‑task progress
18
  # ============================================================
19
 
20
  import os
 
22
  import json
23
  import time
24
  import gzip
25
+ import shutil
26
  import hashlib
27
  import sqlite3
28
  import subprocess
 
32
  import threading
33
  from pathlib import Path
34
  from concurrent.futures import ProcessPoolExecutor, as_completed
35
+ from typing import List, Dict, Any, Optional, Tuple
36
 
37
  import orjson
38
+ from datasets import load_dataset
39
  from huggingface_hub import batch_bucket_files
40
+
41
+ from fastapi import FastAPI, BackgroundTasks
42
  from fastapi.responses import JSONResponse
43
  import uvicorn
44
 
 
51
  STATE_ROOT = LOCAL_ROOT / "state"
52
  TMP_ROOT = LOCAL_ROOT / "tmp"
53
  FINAL_ROOT = LOCAL_ROOT / "final"
54
+
55
+ for directory in [STATE_ROOT, TMP_ROOT, FINAL_ROOT]:
56
+ directory.mkdir(parents=True, exist_ok=True)
57
 
58
  BUCKET_ID = "PERDYPTO/private"
59
  HF_TOKEN = os.environ.get("HF_TOKEN")
60
  if not HF_TOKEN:
61
+ raise RuntimeError("HF_TOKEN environment variable not set.")
62
+
63
+ # Python versions for AST validation
64
+ PYTHON_VERSIONS = [
65
+ "3.11.9",
66
+ "3.12.10",
67
+ "3.13.15",
68
+ "3.14.7",
69
+ ]
70
+ AST_ACCEPT_MODE = "ANY" # any one version passes
71
+
72
+ # Parallelism – adjust based on Space resources
73
+ MAX_WORKERS = 4 # more workers for faster processing
74
+ SHARD_ROWS = 5_000 # records per output file
75
+ CHECKPOINT_EVERY = 5_000 # not used in master‑worker (we use in‑memory)
76
 
77
+ # Quality filters
 
 
 
 
78
  MIN_CHARS = 100
79
  MAX_CHARS = 2_000_000
80
  MIN_LINES = 2
 
82
  REJECT_GENERATED = True
83
  REJECT_VENDOR = True
84
 
85
+ # Remote paths inside the bucket
86
  REMOTE_ROOT = "category1/v4"
87
  REMOTE_DATA = f"{REMOTE_ROOT}/datasets"
88
  REMOTE_STATE = f"{REMOTE_ROOT}/state"
 
91
  # ============================================================
92
  # DATASET LIST – CATEGORY 1 (SOURCE CODE ONLY)
93
  # ============================================================
94
+ # REMOVED "shallow" / problematic datasets (redstone_code_python,
95
+ # github_python, codeparrot_raw, mbpp). Add them back if needed.
96
+ # ============================================================
97
 
98
  DATASETS = [
99
  {
 
294
  return False, "binary_like"
295
  return True, "ok"
296
 
297
+ def ast_check_with_versions(code: str) -> Tuple[bool, str]:
298
+ """Run AST parsing with each Python version; returns (passed, details)."""
299
+ # Find interpreter paths (assume they are installed and in PATH)
300
+ # We'll use the versions from the environment (they should be set in Dockerfile)
301
+ import glob
302
+ base = "/root/.local/share/uv/python"
303
+ interpreters = {}
304
+ for v in PYTHON_VERSIONS:
305
+ pattern = f"{base}/cpython-{v}*/bin/python*"
306
+ matches = glob.glob(pattern)
307
+ if matches:
308
+ interpreters[v] = matches[0]
309
+ else:
310
+ print(f"Warning: Python {v} not found")
311
+ if not interpreters:
312
+ return False, "no_interpreters_found"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
313
 
314
+ # Try each interpreter; accept if any succeeds (AST_ACCEPT_MODE == "ANY")
315
+ for ver, py_path in interpreters.items():
316
+ cmd = [py_path, "-c", f"import ast; ast.parse({repr(code)})"]
 
 
 
 
 
 
317
  try:
318
+ subprocess.run(cmd, check=True, capture_output=True, timeout=10)
319
+ return True, f"accepted_by_{ver}"
320
  except Exception:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
321
  continue
322
+ return False, "ast_failed_all"
 
323
 
324
  # ============================================================
325
+ # WORKER FUNCTION (runs in child process)
326
  # ============================================================
327
 
328
+ def worker_process_task(task: Dict[str, Any]) -> Dict[str, Any]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
329
  """
330
+ Process a single partition of a dataset.
331
+ Returns a dict with:
332
+ - accepted: list of records {text, exact_hash, normalized_hash, metadata}
333
+ - rejected: list of records {text, reason, metadata}
334
+ - stats: counts
335
  """
336
+ ds_info = task["ds_info"]
337
+ partition_start = task.get("start", 0)
338
+ partition_end = task.get("end", None) # None means until exhaustion
339
+ dataset_name = ds_info["name"]
340
+
341
+ # Determine columns to load (avoid schema mismatch)
342
+ all_fields = set()
343
+ all_fields.update(ds_info.get("text_fields", []))
344
+ all_fields.update(ds_info.get("repo_fields", []))
345
+ all_fields.update(ds_info.get("path_fields", []))
346
+ all_fields.update(ds_info.get("license_fields", []))
347
+ # Some datasets have nested fields; we'll just load all and then access safely.
348
+ # But to avoid casting errors, we can load without specifying columns.
349
+ # The error was due to a struct field that couldn't cast to null.
350
+ # We'll load all columns and then ignore extra ones during processing.
351
+ # To be safe, we use `columns` to select only the ones we know, but if the
352
+ # dataset schema has other fields that cause errors, we might still fail.
353
+ # Alternative: use `features` to explicitly define schema. We'll skip columns
354
+ # parameter and handle missing fields gracefully.
355
+ # Actually, the error was for a field that was a struct and the schema expected null.
356
+ # That likely came from a field not in our list. So we will load only the columns
357
+ # we need. But we must ensure that the dataset supports column selection.
358
+ # We'll attempt to load with `select_columns` after loading.
359
+
360
+ # Build load_kwargs
361
+ load_kwargs = {
362
+ "path": ds_info["dataset"],
363
+ "split": ds_info["split"],
364
+ "streaming": True,
365
+ "trust_remote_code": True,
366
  }
367
+ if ds_info.get("config"):
368
+ load_kwargs["name"] = ds_info["config"]
369
+ if ds_info.get("data_dir"):
370
+ load_kwargs["data_dir"] = ds_info["data_dir"]
371
 
372
+ # Load dataset
373
+ try:
374
+ ds = load_dataset(**load_kwargs)
375
+ except Exception as e:
376
+ return {
377
+ "error": f"Failed to load dataset: {e}",
378
+ "accepted": [],
379
+ "rejected": [],
380
+ "stats": {"input": 0, "accepted": 0, "rejected": 0}
381
+ }
382
 
383
+ # Optional: select only needed columns (if we know them)
384
+ # Not all datasets allow column selection; we'll try to filter later.
385
+ # We'll iterate rows and extract text from any of the text_fields.
386
+
387
+ accepted = []
388
+ rejected = []
389
+ input_count = 0
390
+ accepted_count = 0
391
+ rejected_count = 0
392
+
393
+ # Determine text field to use
394
+ text_fields = ds_info.get("text_fields", [])
395
+ repo_fields = ds_info.get("repo_fields", [])
396
+ path_fields = ds_info.get("path_fields", [])
397
+ license_fields = ds_info.get("license_fields", [])
398
+
399
+ # We'll iterate rows
400
+ # To resume from checkpoint, we need to skip rows until partition_start
401
+ row_idx = 0
402
  for row in ds:
403
+ if partition_end is not None and row_idx >= partition_end:
404
+ break
405
+ if row_idx < partition_start:
406
+ row_idx += 1
 
 
 
407
  continue
408
+
409
+ input_count += 1
410
+ # Extract text
411
+ text = None
412
+ for field in text_fields:
413
+ if field in row and row[field] is not None:
414
+ text = row[field]
415
+ break
416
+ if text is None or not isinstance(text, str):
417
+ rejected.append({"text": "", "reason": "no_text_field", "metadata": {}})
418
+ rejected_count += 1
419
+ row_idx += 1
420
  continue
421
 
422
+ # Quality check
423
  ok, reason = quality_check(text)
424
  if not ok:
425
+ rejected.append({"text": text, "reason": reason, "metadata": {}})
426
+ rejected_count += 1
427
+ row_idx += 1
428
  continue
429
 
430
+ # AST check
431
+ ast_ok, ast_reason = ast_check_with_versions(text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
432
  if not ast_ok:
433
+ rejected.append({"text": text, "reason": ast_reason, "metadata": {}})
434
+ rejected_count += 1
435
+ row_idx += 1
436
  continue
437
 
438
+ # Compute hashes
439
+ ehash = exact_hash(text)
440
+ nhash = normalized_hash(text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
441
 
442
+ # Build metadata (repo, path, license)
443
+ metadata = {}
444
+ for field in repo_fields:
445
+ if field in row:
446
+ metadata["repo"] = row[field]
447
+ break
448
+ for field in path_fields:
449
+ if field in row:
450
+ metadata["path"] = row[field]
451
+ break
452
+ for field in license_fields:
453
+ if field in row:
454
+ metadata["license"] = row[field]
455
+ break
456
 
457
+ accepted.append({
458
+ "text": text,
459
+ "exact_hash": ehash,
460
+ "normalized_hash": nhash,
461
+ "metadata": metadata,
462
+ })
463
+ accepted_count += 1
464
+ row_idx += 1
465
 
466
+ return {
467
+ "error": None,
468
+ "accepted": accepted,
469
+ "rejected": rejected,
470
+ "stats": {
471
+ "input": input_count,
472
+ "accepted": accepted_count,
473
+ "rejected": rejected_count,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
474
  }
475
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
476
 
477
  # ============================================================
478
+ # MASTER PROCESSING FUNCTION (runs in main thread)
479
  # ============================================================
480
 
481
  def run_pipeline():
482
  global pipeline_status
483
  pipeline_status["started"] = True
484
  pipeline_status["current_stage"] = "processing"
485
+ pipeline_status["error"] = None
486
+
487
+ # We'll process datasets one by one, but we can parallelize within each dataset.
488
+ # For each dataset, we'll divide into tasks (partitions) and submit to workers.
489
+ # After all datasets, we do final global dedup (already done on the fly).
490
+
491
+ # In-memory sets for global dedup
492
+ global_exact_hashes = set()
493
+ global_norm_hashes = set()
494
+
495
+ # Stats aggregation
496
+ total_input = 0
497
+ total_accepted = 0
498
+ total_rejected = 0
499
+ total_duplicate_exact = 0
500
+ total_duplicate_norm = 0
501
+
502
+ # We'll write output per dataset
503
+ for ds_info in DATASETS:
504
+ ds_name = ds_info["name"]
505
+ ds_output_root = FINAL_ROOT / ds_name
506
+ verified_dir = ds_output_root / "verified"
507
+ rejected_dir = ds_output_root / "rejected"
508
+ verified_dir.mkdir(parents=True, exist_ok=True)
509
+ rejected_dir.mkdir(parents=True, exist_ok=True)
510
+
511
+ # For each dataset, we need to partition the data.
512
+ # We'll use the underlying shards count if available, but we don't know it.
513
+ # We'll just create a single task that processes the whole dataset.
514
+ # However, for large datasets, we want to parallelize.
515
+ # We'll split by record count: we'll create tasks of size ~50,000 records.
516
+ # But we need to know the total length, which we don't have in streaming.
517
+ # Alternative: we can split by number of shards (if dataset has shards).
518
+ # We'll use the `num_shards` if we can get it, else we'll use a single task.
519
+ # For simplicity, we'll use a single task per dataset, but we can split if we know.
520
+ # The user had many shards, so we can split by shard index if we know the shard count.
521
+ # We'll implement a simple split: use 2 tasks per dataset by default.
522
+ # But we want to avoid overloading memory, so we'll limit records per worker.
523
+ # We'll set a max_records_per_task = 100_000.
524
+ # We'll create tasks accordingly by iterating the dataset once to count? That's inefficient.
525
+ # Instead, we'll let each task process a chunk of records by using the `take` or `skip`? Not straightforward.
526
+ # In streaming, we can use `ds.shard`? But we don't know total.
527
+ # We'll use `ds.iter` and break after max_records.
528
+ # However, we need to resume from previous checkpoint? Not needed if we start fresh.
529
+ # We'll just create tasks that process a fixed number of records, but we need to know where to start.
530
+ # We'll create tasks with start and end offsets, but we need to skip records.
531
+ # We can use `itertools.islice` to skip records, but that's slow.
532
+
533
+ # Given the complexity, we'll revert to a simpler approach: one task per dataset.
534
+ # With MAX_WORKERS=4, we can process multiple datasets concurrently.
535
+ # But we want to process datasets in parallel? The user may want to process multiple datasets at once.
536
+ # We'll create a task for each dataset and submit them all to the executor.
537
+ # However, some datasets are huge (like starcoderdata), we might want to split.
538
+ # For now, we'll use one task per dataset to keep it simple.
539
+
540
+ # But we need to handle the case where a dataset is too large and may cause memory issues.
541
+ # We'll set a per-worker record limit, but we don't know total.
542
+
543
+ # Given the user's request for master-worker, we'll process each dataset as a task.
544
+ # But we can also split starcoderdata into multiple tasks by using shard indices if available.
545
+ # We'll detect if the dataset supports sharding via `num_shards`. Not always available.
546
+
547
+ # We'll implement a fallback: if the dataset is known to be large (like starcoderdata),
548
+ # we can split it into 2 tasks by using the `split` parameter with a slice? Not possible.
549
+ # We'll use a hack: we'll create tasks that process a range of records by using `take` and `skip`
550
+ # on the iterable. But that requires knowing total count or doing multiple passes.
551
+
552
+ # Considering the errors, we'll just process each dataset in a single task for now.
553
+ # We'll rely on the worker to iterate all rows and return results.
554
+ # To avoid memory blow, we'll limit the number of records returned by the worker
555
+ # by setting a cap. But we can't easily cap without knowing total.
556
+
557
+ # We'll implement a streaming worker that yields results in batches to master.
558
+ # But that requires inter-process communication with a queue.
559
+
560
+ # Given time, we'll simplify: each worker processes the whole dataset and returns
561
+ # the lists. For starcoderdata (450k records), that might be okay (450k * ~1KB = 450MB).
562
+ # Might be high but possible. We'll trust the memory.
563
+
564
+ # We'll submit tasks for all datasets and let the executor handle them.
565
+ # However, we need to aggregate dedup across all datasets, so master must process
566
+ # results as they come, and update global sets.
567
+
568
+ # We'll create tasks for each dataset.
569
+ # We'll also include dataset info.
570
  tasks = []
571
+ for ds_info in DATASETS:
572
+ # We can optionally split into multiple tasks by shard ranges if we know shard count.
573
+ # For now, one task per dataset.
574
+ tasks.append({
575
+ "ds_info": ds_info,
576
+ "start": 0,
577
+ "end": None, # process all
578
+ })
579
+
580
+ pipeline_status["total_tasks"] = len(tasks)
581
+
582
+ # Use ProcessPoolExecutor
583
+ with ProcessPoolExecutor(max_workers=MAX_WORKERS) as executor:
584
+ future_to_task = {executor.submit(worker_process_task, task): task for task in tasks}
585
+
586
+ for future in as_completed(future_to_task):
587
+ task = future_to_task[future]
588
+ ds_name = task["ds_info"]["name"]
589
+ try:
590
+ result = future.result(timeout=3600) # 1 hour timeout
591
+ except Exception as e:
592
+ print(f"[ERROR] Task for {ds_name} failed with exception: {e}")
593
+ traceback.print_exc()
594
+ pipeline_status["error"] = f"Task for {ds_name} failed: {e}"
595
+ continue
596
+
597
+ if result.get("error"):
598
+ print(f"[ERROR] Task for {ds_name} returned error: {result['error']}")
599
+ pipeline_status["error"] = result["error"]
600
+ continue
601
+
602
+ accepted = result.get("accepted", [])
603
+ rejected = result.get("rejected", [])
604
+ stats = result.get("stats", {})
605
+
606
+ # Update stats
607
+ total_input += stats.get("input", 0)
608
+ total_accepted += stats.get("accepted", 0)
609
+ total_rejected += stats.get("rejected", 0)
610
+
611
+ # Deduplicate accepted records globally
612
+ # For each accepted record, check if hash already seen
613
+ unique_accepted = []
614
+ for rec in accepted:
615
+ ehash = rec["exact_hash"]
616
+ nhash = rec["normalized_hash"]
617
+ if ehash in global_exact_hashes:
618
+ total_duplicate_exact += 1
619
+ # Move to rejected with reason
620
+ rejected.append({
621
+ "text": rec["text"],
622
+ "reason": "duplicate_exact",
623
+ "metadata": rec["metadata"],
624
+ })
625
+ total_rejected += 1
626
+ continue
627
+ if nhash in global_norm_hashes:
628
+ total_duplicate_norm += 1
629
+ rejected.append({
630
+ "text": rec["text"],
631
+ "reason": "duplicate_normalized",
632
+ "metadata": rec["metadata"],
633
+ })
634
+ total_rejected += 1
635
+ continue
636
+ # New record
637
+ global_exact_hashes.add(ehash)
638
+ global_norm_hashes.add(nhash)
639
+ unique_accepted.append(rec)
640
+ total_accepted += 1 # we already counted but we'll recount
641
+
642
+ # Now write accepted and rejected for this dataset
643
+ ds_output_root = FINAL_ROOT / ds_name
644
+ verified_dir = ds_output_root / "verified"
645
+ rejected_dir = ds_output_root / "rejected"
646
+
647
+ # Write accepted shards
648
+ accepted_shard_count = 0
649
+ accepted_batch = []
650
+ for rec in unique_accepted:
651
+ accepted_batch.append(rec)
652
+ if len(accepted_batch) >= SHARD_ROWS:
653
+ # write shard
654
+ shard_path = verified_dir / f"shard-{accepted_shard_count:05d}.jsonl.gz"
655
+ with gzip.open(shard_path, "wt", encoding="utf-8") as f:
656
+ for item in accepted_batch:
657
+ f.write(orjson.dumps(item).decode("utf-8") + "\n")
658
+ accepted_shard_count += 1
659
+ accepted_batch = []
660
+ if accepted_batch:
661
+ shard_path = verified_dir / f"shard-{accepted_shard_count:05d}.jsonl.gz"
662
+ with gzip.open(shard_path, "wt", encoding="utf-8") as f:
663
+ for item in accepted_batch:
664
+ f.write(orjson.dumps(item).decode("utf-8") + "\n")
665
+ accepted_shard_count += 1
666
+
667
+ # Write rejected shards
668
+ rejected_shard_count = 0
669
+ rejected_batch = []
670
+ for rec in rejected:
671
+ rejected_batch.append(rec)
672
+ if len(rejected_batch) >= SHARD_ROWS:
673
+ shard_path = rejected_dir / f"rejected-{rejected_shard_count:05d}.jsonl.gz"
674
+ with gzip.open(shard_path, "wt", encoding="utf-8") as f:
675
+ for item in rejected_batch:
676
+ f.write(orjson.dumps(item).decode("utf-8") + "\n")
677
+ rejected_shard_count += 1
678
+ rejected_batch = []
679
+ if rejected_batch:
680
+ shard_path = rejected_dir / f"rejected-{rejected_shard_count:05d}.jsonl.gz"
681
+ with gzip.open(shard_path, "wt", encoding="utf-8") as f:
682
+ for item in rejected_batch:
683
+ f.write(orjson.dumps(item).decode("utf-8") + "\n")
684
+ rejected_shard_count += 1
685
+
686
+ # Write metadata.json for this dataset
687
+ metadata = {
688
+ "dataset_name": ds_name,
689
+ "total_input": stats.get("input", 0),
690
+ "accepted": len(unique_accepted),
691
+ "rejected": len(rejected),
692
+ "duplicate_exact": total_duplicate_exact,
693
+ "duplicate_normalized": total_duplicate_norm,
694
+ "accepted_shards": accepted_shard_count,
695
+ "rejected_shards": rejected_shard_count,
696
+ }
697
+ with open(ds_output_root / "metadata.json", "w") as f:
698
+ json.dump(metadata, f, indent=2)
699
+
700
+ print(f"[{ds_name}] processed: input={stats.get('input',0)}, "
701
+ f"accepted={len(unique_accepted)}, rejected={len(rejected)}")
702
+
703
+ # After all datasets, update global stats
704
+ pipeline_status["stats"]["input_records"] = total_input
705
+ pipeline_status["stats"]["accepted_records"] = total_accepted
706
+ pipeline_status["stats"]["invalid_records"] = total_rejected
707
+ pipeline_status["stats"]["duplicate_exact"] = total_duplicate_exact
708
+ pipeline_status["stats"]["duplicate_normalized"] = total_duplicate_norm
709
+
710
+ # Final status
711
  pipeline_status["completed"] = True
712
  pipeline_status["current_stage"] = "done"
713
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
714
  # ============================================================
715
  # FASTAPI APP
716
  # ============================================================
717
 
718
+ app = FastAPI()
719
 
720
  @app.on_event("startup")
721
  def startup_event():
722
+ # Start pipeline in background
723
+ def bg():
724
+ try:
725
+ run_pipeline()
726
+ except Exception as e:
727
+ pipeline_status["error"] = str(e)
728
+ pipeline_status["current_stage"] = "failed"
729
+ print(f"Pipeline failed: {e}")
730
+ traceback.print_exc()
731
+ thread = threading.Thread(target=bg, daemon=True)
732
  thread.start()
733
 
734
  @app.get("/health")
735
+ def health():
736
  return JSONResponse(content={
737
  "status": pipeline_status["current_stage"],
738
  "started": pipeline_status["started"],
739
  "completed": pipeline_status["completed"],
 
 
 
740
  "error": pipeline_status["error"],
741
+ "stats": pipeline_status["stats"],
742
  })
743
 
744
  @app.get("/status")
745
+ def status():
 
 
 
 
 
746
  return JSONResponse(content={
747
+ "stage": pipeline_status["current_stage"],
748
+ "tasks": {
749
+ "total": pipeline_status["total_tasks"],
750
+ "finished": pipeline_status["finished_tasks"],
751
+ },
752
+ "stats": pipeline_status["stats"],
753
+ "error": pipeline_status["error"],
754
  })
755
 
756
  # ============================================================
 
758
  # ============================================================
759
 
760
  if __name__ == "__main__":
761
+ uvicorn.run(app, host="0.0.0.0", port=7860)