Spaces:
Sleeping
Sleeping
PERDYPTO commited on
Update pipeline.py
Browse files- pipeline.py +306 -205
pipeline.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
# ============================================================
|
| 3 |
-
#
|
|
|
|
| 4 |
# ============================================================
|
| 5 |
# This script runs on a Hugging Face Space with persistent storage
|
| 6 |
# mounted at /data. It processes the dataset list below,
|
|
@@ -8,9 +9,13 @@
|
|
| 8 |
# removes duplicates globally, and produces a master dataset.
|
| 9 |
#
|
| 10 |
# All state and output is stored in the bucket PERDYPTO/private.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
# ============================================================
|
| 12 |
-
|
| 13 |
-
import
|
| 14 |
import sys
|
| 15 |
import json
|
| 16 |
import time
|
|
@@ -22,6 +27,7 @@ import subprocess
|
|
| 22 |
import traceback
|
| 23 |
import multiprocessing as mp
|
| 24 |
import requests
|
|
|
|
| 25 |
|
| 26 |
from pathlib import Path
|
| 27 |
from concurrent.futures import ProcessPoolExecutor, as_completed
|
|
@@ -30,6 +36,10 @@ import orjson
|
|
| 30 |
from datasets import load_dataset
|
| 31 |
from huggingface_hub import batch_bucket_files
|
| 32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
# ============================================================
|
| 34 |
# BASIC CONFIG — ADAPTED FOR HF SPACE PERSISTENT STORAGE
|
| 35 |
# ============================================================
|
|
@@ -213,7 +223,29 @@ DATASETS = [
|
|
| 213 |
]
|
| 214 |
|
| 215 |
# ============================================================
|
| 216 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
# ============================================================
|
| 218 |
|
| 219 |
def retry(fn, label, retries=5):
|
|
@@ -725,218 +757,287 @@ def get_interpreters():
|
|
| 725 |
return interpreters
|
| 726 |
|
| 727 |
# ============================================================
|
| 728 |
-
#
|
| 729 |
# ============================================================
|
| 730 |
|
| 731 |
-
|
| 732 |
-
|
| 733 |
-
|
| 734 |
-
|
| 735 |
-
|
| 736 |
-
|
| 737 |
-
print(f"Max workers: {MAX_WORKERS}")
|
| 738 |
-
print(f"Datasets: {len(DATASETS)}")
|
| 739 |
-
|
| 740 |
-
# Get interpreters
|
| 741 |
-
INTERPRETERS = get_interpreters()
|
| 742 |
-
print("Python interpreters found:")
|
| 743 |
-
for v, p in INTERPRETERS.items():
|
| 744 |
-
print(f" {v} -> {p}")
|
| 745 |
-
|
| 746 |
-
# Determine shard counts and build task queue
|
| 747 |
-
DATASET_TASKS = []
|
| 748 |
-
for cfg in DATASETS:
|
| 749 |
-
ds = load_stream(cfg)
|
| 750 |
-
num_shards = int(getattr(ds, "num_shards", 1) or 1)
|
| 751 |
-
total_tasks = min(MAX_WORKERS, num_shards)
|
| 752 |
-
print(f"[QUEUE] {cfg['name']}: {num_shards:,} underlying shards -> {total_tasks} tasks")
|
| 753 |
-
for task_id in range(total_tasks):
|
| 754 |
-
DATASET_TASKS.append({
|
| 755 |
-
"cfg": cfg,
|
| 756 |
-
"task_id": task_id,
|
| 757 |
-
"total_tasks": total_tasks,
|
| 758 |
-
"num_shards": num_shards,
|
| 759 |
-
})
|
| 760 |
-
|
| 761 |
-
print(f"Total scheduled task partitions: {len(DATASET_TASKS):,}")
|
| 762 |
-
|
| 763 |
-
# Global scheduler (runs at most MAX_WORKERS tasks concurrently)
|
| 764 |
-
results = {}
|
| 765 |
-
task_cursor = 0
|
| 766 |
-
active = {}
|
| 767 |
-
executor = ProcessPoolExecutor(max_workers=MAX_WORKERS)
|
| 768 |
|
| 769 |
try:
|
| 770 |
-
#
|
| 771 |
-
|
| 772 |
-
|
| 773 |
-
|
| 774 |
-
|
| 775 |
-
|
| 776 |
-
|
| 777 |
-
|
| 778 |
-
|
| 779 |
-
|
| 780 |
-
|
| 781 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 782 |
try:
|
| 783 |
-
|
| 784 |
-
except Exception
|
| 785 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 786 |
key = (task["cfg"]["name"], task["task_id"])
|
| 787 |
-
|
| 788 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 789 |
|
| 790 |
-
|
| 791 |
-
|
| 792 |
-
|
| 793 |
-
|
| 794 |
-
|
| 795 |
-
|
| 796 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 797 |
|
| 798 |
-
|
| 799 |
-
|
| 800 |
-
|
| 801 |
-
# ============================================================
|
| 802 |
-
# GLOBAL DEDUP (across all tasks/datasets)
|
| 803 |
-
# ============================================================
|
| 804 |
-
|
| 805 |
-
print("\n" + "=" * 90)
|
| 806 |
-
print("STARTING GLOBAL CATEGORY 1 DEDUP")
|
| 807 |
-
print("=" * 90)
|
| 808 |
-
|
| 809 |
-
GLOBAL_DB = FINAL_ROOT / "global_dedup.sqlite"
|
| 810 |
-
gconn = sqlite3.connect(GLOBAL_DB, timeout=120)
|
| 811 |
-
gconn.execute("CREATE TABLE IF NOT EXISTS fingerprints (exact_hash TEXT PRIMARY KEY, normalized_hash TEXT NOT NULL)")
|
| 812 |
-
gconn.execute("CREATE INDEX IF NOT EXISTS idx_global_normalized ON fingerprints(normalized_hash)")
|
| 813 |
-
gconn.commit()
|
| 814 |
-
|
| 815 |
-
global_stats = {"input_records": 0, "accepted_records": 0, "duplicate_exact": 0, "duplicate_normalized": 0, "invalid_records": 0, "bytes": 0}
|
| 816 |
-
global_records = []
|
| 817 |
-
global_shard_number = 0
|
| 818 |
-
|
| 819 |
-
def flush_global():
|
| 820 |
-
global global_records, global_shard_number # <-- changed from nonlocal
|
| 821 |
-
if not global_records:
|
| 822 |
-
return
|
| 823 |
-
filename = f"category1-master-{global_shard_number:08d}.jsonl.gz"
|
| 824 |
-
local_path = FINAL_ROOT / filename
|
| 825 |
-
with gzip.open(local_path, "wb") as f:
|
| 826 |
-
for record in global_records:
|
| 827 |
-
f.write(orjson.dumps(record) + b"\n")
|
| 828 |
-
remote_path = f"{REMOTE_FINAL}/{filename}"
|
| 829 |
-
upload_file(local_path, remote_path)
|
| 830 |
-
try:
|
| 831 |
-
local_path.unlink()
|
| 832 |
-
except Exception:
|
| 833 |
-
pass
|
| 834 |
-
global_records = []
|
| 835 |
-
global_shard_number += 1
|
| 836 |
-
|
| 837 |
-
# Collect all remote shard paths from completed tasks
|
| 838 |
-
REMOTE_SHARDS = []
|
| 839 |
-
for task in DATASET_TASKS:
|
| 840 |
-
key = (task["cfg"]["name"], task["task_id"])
|
| 841 |
-
result = results.get(key, {})
|
| 842 |
-
shard_count = int(result.get("shards_uploaded", 0))
|
| 843 |
-
for shard_number in range(shard_count):
|
| 844 |
-
filename = f"task-{task['task_id']:04d}-shard-{shard_number:08d}.jsonl.gz"
|
| 845 |
-
remote_path = f"{REMOTE_DATA}/{task['cfg']['name']}/task_{task['task_id']}/{filename}"
|
| 846 |
-
REMOTE_SHARDS.append((task['cfg']['name'], task['task_id'], shard_number, remote_path))
|
| 847 |
-
|
| 848 |
-
print(f"Remote worker shards: {len(REMOTE_SHARDS):,}")
|
| 849 |
-
|
| 850 |
-
# Download each shard, dedup globally, and write final master shards
|
| 851 |
-
for idx, (dataset_name, task_id, shard_number, remote_path) in enumerate(REMOTE_SHARDS, 1):
|
| 852 |
-
print(f"\n[GLOBAL] {idx:,}/{len(REMOTE_SHARDS):,} {dataset_name} T{task_id} S{shard_number}")
|
| 853 |
-
local_path = TMP_ROOT / "global" / dataset_name / f"task_{task_id}" / Path(remote_path).name
|
| 854 |
-
# Download using hf buckets cp (or via requests)
|
| 855 |
-
try:
|
| 856 |
-
# Using requests to get from bucket
|
| 857 |
-
url = f"https://huggingface.co/buckets/{BUCKET_ID}/resolve/{remote_path}"
|
| 858 |
-
response = requests.get(url, headers={"Authorization": f"Bearer {HF_TOKEN}"})
|
| 859 |
-
if response.status_code != 200:
|
| 860 |
-
raise RuntimeError(f"Download failed: {response.status_code}")
|
| 861 |
-
local_path.parent.mkdir(parents=True, exist_ok=True)
|
| 862 |
-
with open(local_path, "wb") as f:
|
| 863 |
-
f.write(response.content)
|
| 864 |
-
except Exception as e:
|
| 865 |
-
print(f"Download error: {e}")
|
| 866 |
-
continue
|
| 867 |
|
| 868 |
-
|
| 869 |
-
|
| 870 |
-
|
| 871 |
-
|
| 872 |
-
|
| 873 |
-
ehash = record["exact_sha256"]
|
| 874 |
-
nhash = record["normalized_sha256"]
|
| 875 |
-
except Exception:
|
| 876 |
-
global_stats["invalid_records"] += 1
|
| 877 |
-
continue
|
| 878 |
|
| 879 |
-
|
| 880 |
-
|
| 881 |
-
if duplicate[0] == ehash:
|
| 882 |
-
global_stats["duplicate_exact"] += 1
|
| 883 |
-
else:
|
| 884 |
-
global_stats["duplicate_normalized"] += 1
|
| 885 |
-
continue
|
| 886 |
|
| 887 |
-
|
| 888 |
-
|
| 889 |
-
|
| 890 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 891 |
|
| 892 |
-
|
| 893 |
-
|
| 894 |
-
|
|
|
|
|
|
|
| 895 |
|
| 896 |
-
|
| 897 |
-
|
| 898 |
-
|
| 899 |
-
except Exception:
|
| 900 |
-
pass
|
| 901 |
|
| 902 |
-
|
| 903 |
-
|
| 904 |
-
|
| 905 |
-
|
| 906 |
-
|
| 907 |
-
|
| 908 |
-
|
| 909 |
-
|
| 910 |
-
|
| 911 |
-
|
| 912 |
-
|
| 913 |
-
|
| 914 |
-
|
| 915 |
-
|
| 916 |
-
"
|
| 917 |
-
"
|
| 918 |
-
"
|
| 919 |
-
"
|
| 920 |
-
"
|
| 921 |
-
"
|
| 922 |
-
"
|
| 923 |
-
|
| 924 |
-
|
| 925 |
-
|
| 926 |
-
|
| 927 |
-
|
| 928 |
-
|
| 929 |
-
|
| 930 |
-
|
| 931 |
-
|
| 932 |
-
|
| 933 |
-
|
| 934 |
-
|
| 935 |
-
|
| 936 |
-
|
| 937 |
-
|
| 938 |
-
|
| 939 |
-
|
| 940 |
-
|
| 941 |
-
|
| 942 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 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,
|
|
|
|
| 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
|
| 19 |
import sys
|
| 20 |
import json
|
| 21 |
import time
|
|
|
|
| 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
|
|
|
|
| 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 |
+
|
| 43 |
# ============================================================
|
| 44 |
# BASIC CONFIG — ADAPTED FOR HF SPACE PERSISTENT STORAGE
|
| 45 |
# ============================================================
|
|
|
|
| 223 |
]
|
| 224 |
|
| 225 |
# ============================================================
|
| 226 |
+
# GLOBAL STATE FOR API
|
| 227 |
+
# ============================================================
|
| 228 |
+
|
| 229 |
+
pipeline_status = {
|
| 230 |
+
"started": False,
|
| 231 |
+
"completed": False,
|
| 232 |
+
"current_stage": "idle", # idle | processing | global_dedup | done | failed
|
| 233 |
+
"total_tasks": 0,
|
| 234 |
+
"finished_tasks": 0,
|
| 235 |
+
"stats": {
|
| 236 |
+
"input_records": 0,
|
| 237 |
+
"accepted_records": 0,
|
| 238 |
+
"duplicate_exact": 0,
|
| 239 |
+
"duplicate_normalized": 0,
|
| 240 |
+
"invalid_records": 0,
|
| 241 |
+
"bytes": 0,
|
| 242 |
+
"final_shards": 0,
|
| 243 |
+
},
|
| 244 |
+
"error": None,
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
# ============================================================
|
| 248 |
+
# HELPER FUNCTIONS (identical to your Kaggle code)
|
| 249 |
# ============================================================
|
| 250 |
|
| 251 |
def retry(fn, label, retries=5):
|
|
|
|
| 757 |
return interpreters
|
| 758 |
|
| 759 |
# ============================================================
|
| 760 |
+
# PIPELINE RUNNER (updates global status)
|
| 761 |
# ============================================================
|
| 762 |
|
| 763 |
+
def run_pipeline():
|
| 764 |
+
global pipeline_status
|
| 765 |
+
pipeline_status["started"] = True
|
| 766 |
+
pipeline_status["current_stage"] = "processing"
|
| 767 |
+
pipeline_status["total_tasks"] = 0
|
| 768 |
+
pipeline_status["finished_tasks"] = 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 769 |
|
| 770 |
try:
|
| 771 |
+
# Get interpreters
|
| 772 |
+
interpreters = get_interpreters()
|
| 773 |
+
print("Python interpreters found:")
|
| 774 |
+
for v, p in interpreters.items():
|
| 775 |
+
print(f" {v} -> {p}")
|
| 776 |
+
|
| 777 |
+
# Determine shard counts and build task queue
|
| 778 |
+
DATASET_TASKS = []
|
| 779 |
+
for cfg in DATASETS:
|
| 780 |
+
ds = load_stream(cfg)
|
| 781 |
+
num_shards = int(getattr(ds, "num_shards", 1) or 1)
|
| 782 |
+
total_tasks = min(MAX_WORKERS, num_shards)
|
| 783 |
+
print(f"[QUEUE] {cfg['name']}: {num_shards:,} underlying shards -> {total_tasks} tasks")
|
| 784 |
+
pipeline_status["total_tasks"] += total_tasks
|
| 785 |
+
for task_id in range(total_tasks):
|
| 786 |
+
DATASET_TASKS.append({
|
| 787 |
+
"cfg": cfg,
|
| 788 |
+
"task_id": task_id,
|
| 789 |
+
"total_tasks": total_tasks,
|
| 790 |
+
"num_shards": num_shards,
|
| 791 |
+
})
|
| 792 |
+
|
| 793 |
+
print(f"Total scheduled task partitions: {len(DATASET_TASKS):,}")
|
| 794 |
+
|
| 795 |
+
# Run tasks concurrently (at most MAX_WORKERS at a time)
|
| 796 |
+
results = {}
|
| 797 |
+
task_cursor = 0
|
| 798 |
+
active = {}
|
| 799 |
+
with ProcessPoolExecutor(max_workers=MAX_WORKERS) as executor:
|
| 800 |
+
# initial fill
|
| 801 |
+
while len(active) < MAX_WORKERS and task_cursor < len(DATASET_TASKS):
|
| 802 |
+
task = DATASET_TASKS[task_cursor]
|
| 803 |
+
task_cursor += 1
|
| 804 |
+
future = executor.submit(process_partition, task["cfg"], task["task_id"], task["total_tasks"], interpreters)
|
| 805 |
+
active[future] = task
|
| 806 |
+
print(f"[SCHEDULER] STARTED {task['cfg']['name']} T{task['task_id']}")
|
| 807 |
+
|
| 808 |
+
# Continue until all tasks done
|
| 809 |
+
while active:
|
| 810 |
+
for completed_future in as_completed(active.keys()):
|
| 811 |
+
task = active.pop(completed_future)
|
| 812 |
+
try:
|
| 813 |
+
result = completed_future.result()
|
| 814 |
+
except Exception as e:
|
| 815 |
+
result = {"complete": False, "error": repr(e), "task_id": task["task_id"]}
|
| 816 |
+
key = (task["cfg"]["name"], task["task_id"])
|
| 817 |
+
results[key] = result
|
| 818 |
+
pipeline_status["finished_tasks"] += 1
|
| 819 |
+
print(f"\n[SCHEDULER] FINISHED {task['cfg']['name']} T{task['task_id']} complete={result.get('complete', False)}")
|
| 820 |
+
|
| 821 |
+
# Fill the slot immediately
|
| 822 |
+
if task_cursor < len(DATASET_TASKS):
|
| 823 |
+
next_task = DATASET_TASKS[task_cursor]
|
| 824 |
+
task_cursor += 1
|
| 825 |
+
future = executor.submit(process_partition, next_task["cfg"], next_task["task_id"], next_task["total_tasks"], interpreters)
|
| 826 |
+
active[future] = next_task
|
| 827 |
+
print(f"[SCHEDULER] STARTED {next_task['cfg']['name']} T{next_task['task_id']}")
|
| 828 |
+
break # break to re-enter as_completed
|
| 829 |
+
|
| 830 |
+
# ============================================================
|
| 831 |
+
# GLOBAL DEDUP (across all tasks/datasets)
|
| 832 |
+
# ============================================================
|
| 833 |
+
pipeline_status["current_stage"] = "global_dedup"
|
| 834 |
+
print("\n" + "=" * 90)
|
| 835 |
+
print("STARTING GLOBAL CATEGORY 1 DEDUP")
|
| 836 |
+
print("=" * 90)
|
| 837 |
+
|
| 838 |
+
GLOBAL_DB = FINAL_ROOT / "global_dedup.sqlite"
|
| 839 |
+
gconn = sqlite3.connect(GLOBAL_DB, timeout=120)
|
| 840 |
+
gconn.execute("CREATE TABLE IF NOT EXISTS fingerprints (exact_hash TEXT PRIMARY KEY, normalized_hash TEXT NOT NULL)")
|
| 841 |
+
gconn.execute("CREATE INDEX IF NOT EXISTS idx_global_normalized ON fingerprints(normalized_hash)")
|
| 842 |
+
gconn.commit()
|
| 843 |
+
|
| 844 |
+
global_stats = {"input_records": 0, "accepted_records": 0, "duplicate_exact": 0, "duplicate_normalized": 0, "invalid_records": 0, "bytes": 0}
|
| 845 |
+
global_records = []
|
| 846 |
+
global_shard_number = 0
|
| 847 |
+
|
| 848 |
+
def flush_global():
|
| 849 |
+
nonlocal global_records, global_shard_number
|
| 850 |
+
if not global_records:
|
| 851 |
+
return
|
| 852 |
+
filename = f"category1-master-{global_shard_number:08d}.jsonl.gz"
|
| 853 |
+
local_path = FINAL_ROOT / filename
|
| 854 |
+
with gzip.open(local_path, "wb") as f:
|
| 855 |
+
for record in global_records:
|
| 856 |
+
f.write(orjson.dumps(record) + b"\n")
|
| 857 |
+
remote_path = f"{REMOTE_FINAL}/{filename}"
|
| 858 |
+
upload_file(local_path, remote_path)
|
| 859 |
try:
|
| 860 |
+
local_path.unlink()
|
| 861 |
+
except Exception:
|
| 862 |
+
pass
|
| 863 |
+
global_records = []
|
| 864 |
+
global_shard_number += 1
|
| 865 |
+
|
| 866 |
+
# Collect all remote shard paths from completed tasks
|
| 867 |
+
REMOTE_SHARDS = []
|
| 868 |
+
for task in DATASET_TASKS:
|
| 869 |
key = (task["cfg"]["name"], task["task_id"])
|
| 870 |
+
result = results.get(key, {})
|
| 871 |
+
shard_count = int(result.get("shards_uploaded", 0))
|
| 872 |
+
for shard_number in range(shard_count):
|
| 873 |
+
filename = f"task-{task['task_id']:04d}-shard-{shard_number:08d}.jsonl.gz"
|
| 874 |
+
remote_path = f"{REMOTE_DATA}/{task['cfg']['name']}/task_{task['task_id']}/{filename}"
|
| 875 |
+
REMOTE_SHARDS.append((task['cfg']['name'], task['task_id'], shard_number, remote_path))
|
| 876 |
+
|
| 877 |
+
print(f"Remote worker shards: {len(REMOTE_SHARDS):,}")
|
| 878 |
+
|
| 879 |
+
# Download each shard, dedup globally, and write final master shards
|
| 880 |
+
for idx, (dataset_name, task_id, shard_number, remote_path) in enumerate(REMOTE_SHARDS, 1):
|
| 881 |
+
print(f"\n[GLOBAL] {idx:,}/{len(REMOTE_SHARDS):,} {dataset_name} T{task_id} S{shard_number}")
|
| 882 |
+
local_path = TMP_ROOT / "global" / dataset_name / f"task_{task_id}" / Path(remote_path).name
|
| 883 |
+
# Download using requests
|
| 884 |
+
try:
|
| 885 |
+
url = f"https://huggingface.co/buckets/{BUCKET_ID}/resolve/{remote_path}"
|
| 886 |
+
response = requests.get(url, headers={"Authorization": f"Bearer {HF_TOKEN}"})
|
| 887 |
+
if response.status_code != 200:
|
| 888 |
+
raise RuntimeError(f"Download failed: {response.status_code}")
|
| 889 |
+
local_path.parent.mkdir(parents=True, exist_ok=True)
|
| 890 |
+
with open(local_path, "wb") as f:
|
| 891 |
+
f.write(response.content)
|
| 892 |
+
except Exception as e:
|
| 893 |
+
print(f"Download error: {e}")
|
| 894 |
+
continue
|
| 895 |
|
| 896 |
+
with gzip.open(local_path, "rb") as f:
|
| 897 |
+
for line in f:
|
| 898 |
+
global_stats["input_records"] += 1
|
| 899 |
+
try:
|
| 900 |
+
record = orjson.loads(line)
|
| 901 |
+
ehash = record["exact_sha256"]
|
| 902 |
+
nhash = record["normalized_sha256"]
|
| 903 |
+
except Exception:
|
| 904 |
+
global_stats["invalid_records"] += 1
|
| 905 |
+
continue
|
| 906 |
+
|
| 907 |
+
duplicate = gconn.execute("SELECT exact_hash, normalized_hash FROM fingerprints WHERE exact_hash = ? OR normalized_hash = ? LIMIT 1", (ehash, nhash)).fetchone()
|
| 908 |
+
if duplicate is not None:
|
| 909 |
+
if duplicate[0] == ehash:
|
| 910 |
+
global_stats["duplicate_exact"] += 1
|
| 911 |
+
else:
|
| 912 |
+
global_stats["duplicate_normalized"] += 1
|
| 913 |
+
continue
|
| 914 |
+
|
| 915 |
+
gconn.execute("INSERT INTO fingerprints (exact_hash, normalized_hash) VALUES (?, ?)", (ehash, nhash))
|
| 916 |
+
global_records.append(record)
|
| 917 |
+
global_stats["accepted_records"] += 1
|
| 918 |
+
global_stats["bytes"] += int(record.get("char_count", 0))
|
| 919 |
+
|
| 920 |
+
if len(global_records) >= SHARD_ROWS:
|
| 921 |
+
gconn.commit()
|
| 922 |
+
flush_global()
|
| 923 |
+
|
| 924 |
+
gconn.commit()
|
| 925 |
+
try:
|
| 926 |
+
local_path.unlink()
|
| 927 |
+
except Exception:
|
| 928 |
+
pass
|
| 929 |
|
| 930 |
+
if idx % 10 == 0 or idx == len(REMOTE_SHARDS):
|
| 931 |
+
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']:,}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 932 |
|
| 933 |
+
# Final flush
|
| 934 |
+
gconn.commit()
|
| 935 |
+
flush_global()
|
| 936 |
+
gconn.commit()
|
| 937 |
+
gconn.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 938 |
|
| 939 |
+
# Upload global DB
|
| 940 |
+
upload_file(GLOBAL_DB, f"{REMOTE_FINAL}/global_dedup.sqlite")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 941 |
|
| 942 |
+
# Final metadata
|
| 943 |
+
final_metadata = {
|
| 944 |
+
"name": "Category 1 Python Master",
|
| 945 |
+
"pipeline_version": "v4",
|
| 946 |
+
"source_datasets": [cfg["dataset"] for cfg in DATASETS],
|
| 947 |
+
"max_workers": MAX_WORKERS,
|
| 948 |
+
"python_ast_versions": PYTHON_VERSIONS,
|
| 949 |
+
"ast_acceptance_rule": "ANY",
|
| 950 |
+
"dedup": {"exact_sha256": True, "normalized_sha256": True, "ast_structure_as_key": False},
|
| 951 |
+
"statistics": global_stats,
|
| 952 |
+
"final_shards": global_shard_number,
|
| 953 |
+
"created": time.time(),
|
| 954 |
+
}
|
| 955 |
+
metadata_path = FINAL_ROOT / "dataset_metadata.json"
|
| 956 |
+
with open(metadata_path, "w") as f:
|
| 957 |
+
json.dump(final_metadata, f, indent=2)
|
| 958 |
+
upload_file(metadata_path, f"{REMOTE_FINAL}/dataset_metadata.json")
|
| 959 |
+
|
| 960 |
+
# Update global status with final stats
|
| 961 |
+
pipeline_status["stats"] = global_stats
|
| 962 |
+
pipeline_status["stats"]["final_shards"] = global_shard_number
|
| 963 |
+
pipeline_status["completed"] = True
|
| 964 |
+
pipeline_status["current_stage"] = "done"
|
| 965 |
+
|
| 966 |
+
print("\n" + "=" * 90)
|
| 967 |
+
print("CATEGORY 1 — COMPLETE")
|
| 968 |
+
print("=" * 90)
|
| 969 |
+
print(f"Input records: {global_stats['input_records']:,}")
|
| 970 |
+
print(f"Final accepted: {global_stats['accepted_records']:,}")
|
| 971 |
+
print(f"Global exact duplicates: {global_stats['duplicate_exact']:,}")
|
| 972 |
+
print(f"Global normalized duplicates: {global_stats['duplicate_normalized']:,}")
|
| 973 |
+
print(f"Final master shards: {global_shard_number:,}")
|
| 974 |
+
print("\nAST validation: ANY ONE VERSION PASS = ACCEPT")
|
| 975 |
+
print(f"Master location: hf://buckets/{BUCKET_ID}/{REMOTE_FINAL}/")
|
| 976 |
+
print("=" * 90)
|
| 977 |
|
| 978 |
+
except Exception as e:
|
| 979 |
+
pipeline_status["current_stage"] = "failed"
|
| 980 |
+
pipeline_status["error"] = str(e)
|
| 981 |
+
print("PIPELINE FAILED:", traceback.format_exc())
|
| 982 |
+
raise
|
| 983 |
|
| 984 |
+
# ============================================================
|
| 985 |
+
# FASTAPI APP
|
| 986 |
+
# ============================================================
|
|
|
|
|
|
|
| 987 |
|
| 988 |
+
app = FastAPI(title="Category1 Pipeline API")
|
| 989 |
+
|
| 990 |
+
@app.on_event("startup")
|
| 991 |
+
def startup_event():
|
| 992 |
+
# Launch pipeline in a background thread so the API stays responsive
|
| 993 |
+
thread = threading.Thread(target=run_pipeline, daemon=True)
|
| 994 |
+
thread.start()
|
| 995 |
+
|
| 996 |
+
@app.get("/health")
|
| 997 |
+
async def health():
|
| 998 |
+
"""
|
| 999 |
+
Returns current pipeline statistics and health status.
|
| 1000 |
+
"""
|
| 1001 |
+
return JSONResponse(content={
|
| 1002 |
+
"status": pipeline_status["current_stage"],
|
| 1003 |
+
"started": pipeline_status["started"],
|
| 1004 |
+
"completed": pipeline_status["completed"],
|
| 1005 |
+
"total_tasks": pipeline_status["total_tasks"],
|
| 1006 |
+
"finished_tasks": pipeline_status["finished_tasks"],
|
| 1007 |
+
"stats": pipeline_status["stats"],
|
| 1008 |
+
"error": pipeline_status["error"],
|
| 1009 |
+
})
|
| 1010 |
+
|
| 1011 |
+
@app.get("/status")
|
| 1012 |
+
async def status():
|
| 1013 |
+
"""
|
| 1014 |
+
Returns detailed per‑dataset task status (reads state files).
|
| 1015 |
+
For a deeper view, you can scan STATE_ROOT/*/task_*_COMPLETE.json.
|
| 1016 |
+
"""
|
| 1017 |
+
# Gather completion files for all datasets
|
| 1018 |
+
detailed = {}
|
| 1019 |
+
for dataset_dir in STATE_ROOT.iterdir():
|
| 1020 |
+
if dataset_dir.is_dir():
|
| 1021 |
+
dataset_name = dataset_dir.name
|
| 1022 |
+
completions = list(dataset_dir.glob("task_*_COMPLETE.json"))
|
| 1023 |
+
detailed[dataset_name] = {"completed_tasks": len(completions)}
|
| 1024 |
+
for comp_path in completions:
|
| 1025 |
+
try:
|
| 1026 |
+
with open(comp_path) as f:
|
| 1027 |
+
data = json.load(f)
|
| 1028 |
+
detailed[dataset_name][comp_path.stem] = data
|
| 1029 |
+
except Exception:
|
| 1030 |
+
pass
|
| 1031 |
+
return JSONResponse(content={
|
| 1032 |
+
"pipeline_status": pipeline_status,
|
| 1033 |
+
"per_dataset": detailed,
|
| 1034 |
+
})
|
| 1035 |
+
|
| 1036 |
+
# ============================================================
|
| 1037 |
+
# MAIN ENTRY POINT FOR UVICORN
|
| 1038 |
+
# ============================================================
|
| 1039 |
+
|
| 1040 |
+
if __name__ == "__main__":
|
| 1041 |
+
# Use the PORT environment variable if set (HF Spaces default 7860)
|
| 1042 |
+
port = int(os.environ.get("PORT", 7860))
|
| 1043 |
+
uvicorn.run(app, host="0.0.0.0", port=port)
|