Spaces:
Sleeping
Sleeping
PERDYPTO commited on
Update pipeline.py
Browse files- pipeline.py +46 -101
pipeline.py
CHANGED
|
@@ -1,7 +1,6 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
# ============================================================
|
| 3 |
-
# PIPELINE_API.PY — COORDINATOR‑WORKER PIPELINE
|
| 4 |
-
# GLOBAL DEDUP, RESUME, AND FILE OUTPUT
|
| 5 |
# ============================================================
|
| 6 |
|
| 7 |
import os
|
|
@@ -17,20 +16,18 @@ import multiprocessing as mp
|
|
| 17 |
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
|
| 25 |
from huggingface_hub import batch_bucket_files
|
| 26 |
from fastapi import FastAPI
|
| 27 |
from fastapi.responses import JSONResponse
|
| 28 |
import uvicorn
|
| 29 |
|
| 30 |
-
#
|
| 31 |
-
#
|
| 32 |
-
#
|
| 33 |
-
|
| 34 |
DATA_ROOT = Path(os.environ.get("DATA_ROOT", "/data"))
|
| 35 |
LOCAL_ROOT = DATA_ROOT / "category1_pipeline_v4"
|
| 36 |
STATE_ROOT = LOCAL_ROOT / "state"
|
|
@@ -42,13 +39,12 @@ for d in [STATE_ROOT, TMP_ROOT, FINAL_ROOT]:
|
|
| 42 |
BUCKET_ID = "PERDYPTO/private"
|
| 43 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 44 |
if not HF_TOKEN:
|
| 45 |
-
raise RuntimeError("HF_TOKEN
|
| 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
|
| 50 |
-
SHARD_ROWS = 5_000
|
| 51 |
-
CHECKPOINT_EVERY = 5_000 # not used in coordinator version
|
| 52 |
MIN_CHARS = 100
|
| 53 |
MAX_CHARS = 2_000_000
|
| 54 |
MIN_LINES = 2
|
|
@@ -61,10 +57,9 @@ REMOTE_DATA = f"{REMOTE_ROOT}/datasets"
|
|
| 61 |
REMOTE_STATE = f"{REMOTE_ROOT}/state"
|
| 62 |
REMOTE_FINAL = f"{REMOTE_ROOT}/final"
|
| 63 |
|
| 64 |
-
#
|
| 65 |
-
#
|
| 66 |
-
#
|
| 67 |
-
|
| 68 |
DATASETS = [
|
| 69 |
{
|
| 70 |
"name": "swallowcode_v2",
|
|
@@ -180,10 +175,9 @@ DATASETS = [
|
|
| 180 |
}
|
| 181 |
]
|
| 182 |
|
| 183 |
-
#
|
| 184 |
# GLOBAL STATE FOR API
|
| 185 |
-
#
|
| 186 |
-
|
| 187 |
pipeline_status = {
|
| 188 |
"started": False,
|
| 189 |
"completed": False,
|
|
@@ -202,10 +196,9 @@ pipeline_status = {
|
|
| 202 |
"error": None,
|
| 203 |
}
|
| 204 |
|
| 205 |
-
#
|
| 206 |
# HELPER FUNCTIONS
|
| 207 |
-
#
|
| 208 |
-
|
| 209 |
def retry(fn, label, retries=5):
|
| 210 |
last_error = None
|
| 211 |
for attempt in range(1, retries + 1):
|
|
@@ -306,10 +299,9 @@ def extract_record(row, cfg):
|
|
| 306 |
"license": str(license_name),
|
| 307 |
}
|
| 308 |
|
| 309 |
-
#
|
| 310 |
-
# AST VALIDATOR (
|
| 311 |
-
#
|
| 312 |
-
|
| 313 |
AST_CHILD_CODE = r'''
|
| 314 |
import ast
|
| 315 |
import sys
|
|
@@ -341,7 +333,6 @@ class ASTWorker:
|
|
| 341 |
)
|
| 342 |
|
| 343 |
def check(self, text):
|
| 344 |
-
import base64
|
| 345 |
encoded = base64.b64encode(text.encode("utf-8", errors="strict")).decode("ascii")
|
| 346 |
self.process.stdin.write(encoded + "\n")
|
| 347 |
self.process.stdin.flush()
|
|
@@ -391,10 +382,9 @@ class ASTValidator:
|
|
| 391 |
except Exception:
|
| 392 |
pass
|
| 393 |
|
| 394 |
-
#
|
| 395 |
-
#
|
| 396 |
-
#
|
| 397 |
-
|
| 398 |
def get_interpreters():
|
| 399 |
interpreters = {}
|
| 400 |
for version in PYTHON_VERSIONS:
|
|
@@ -412,10 +402,9 @@ def get_interpreters():
|
|
| 412 |
raise RuntimeError(f"Could not find Python {version}")
|
| 413 |
return interpreters
|
| 414 |
|
| 415 |
-
#
|
| 416 |
-
# DATASET
|
| 417 |
-
#
|
| 418 |
-
|
| 419 |
def load_stream(cfg):
|
| 420 |
kwargs = {"split": cfg["split"], "streaming": True, "token": HF_TOKEN}
|
| 421 |
if cfg.get("config"):
|
|
@@ -425,42 +414,33 @@ def load_stream(cfg):
|
|
| 425 |
if cfg.get("languages"):
|
| 426 |
kwargs["languages"] = cfg["languages"]
|
| 427 |
|
| 428 |
-
#
|
| 429 |
if cfg["dataset"] == "tokyotech-llm/swallow-code-v2":
|
| 430 |
-
#
|
| 431 |
features = Features({
|
| 432 |
"text": Value("string"),
|
| 433 |
"repo_name": Value("string"),
|
| 434 |
"path": Value("string"),
|
| 435 |
"license": Value("string"),
|
| 436 |
-
"lint_report": Sequence(Struct({
|
| 437 |
-
"type": Value("string"),
|
| 438 |
-
"message": Value("string")
|
| 439 |
-
})),
|
| 440 |
})
|
| 441 |
kwargs["features"] = features
|
| 442 |
-
# Remove
|
| 443 |
if "name" in kwargs:
|
| 444 |
del kwargs["name"]
|
| 445 |
-
return load_dataset(cfg["dataset"], **kwargs)
|
| 446 |
|
| 447 |
-
|
| 448 |
-
# WORKER FUNCTION (runs in a separate process)
|
| 449 |
-
# ============================================================
|
| 450 |
|
|
|
|
|
|
|
|
|
|
| 451 |
def worker_task(cfg, task_id, total_tasks, interpreters, result_queue):
|
| 452 |
-
"""
|
| 453 |
-
Process one partition of a dataset.
|
| 454 |
-
Sends batches of accepted records and final stats through result_queue.
|
| 455 |
-
"""
|
| 456 |
dataset_name = cfg["name"]
|
| 457 |
print(f"[WORKER] {dataset_name} T{task_id} started")
|
| 458 |
|
| 459 |
-
# Load dataset and shard
|
| 460 |
ds = load_stream(cfg)
|
| 461 |
ds = ds.shard(num_shards=total_tasks, index=task_id)
|
| 462 |
|
| 463 |
-
# Local in-memory dedup
|
| 464 |
local_conn = sqlite3.connect(":memory:")
|
| 465 |
local_conn.execute("CREATE TABLE IF NOT EXISTS local_fp (exact_hash TEXT PRIMARY KEY, normalized_hash TEXT NOT NULL)")
|
| 466 |
local_conn.execute("CREATE INDEX IF NOT EXISTS idx_local_norm ON local_fp(normalized_hash)")
|
|
@@ -496,13 +476,11 @@ def worker_task(cfg, task_id, total_tasks, interpreters, result_queue):
|
|
| 496 |
stats["other_reject"] += 1
|
| 497 |
continue
|
| 498 |
|
| 499 |
-
# quality checks
|
| 500 |
ok, reason = quality_check(text)
|
| 501 |
if not ok:
|
| 502 |
stats["quality_reject"] += 1
|
| 503 |
continue
|
| 504 |
|
| 505 |
-
# hashes
|
| 506 |
try:
|
| 507 |
ehash = exact_hash(text)
|
| 508 |
nhash = normalized_hash(text)
|
|
@@ -510,7 +488,6 @@ def worker_task(cfg, task_id, total_tasks, interpreters, result_queue):
|
|
| 510 |
stats["other_reject"] += 1
|
| 511 |
continue
|
| 512 |
|
| 513 |
-
# local dedup
|
| 514 |
dup = local_conn.execute(
|
| 515 |
"SELECT exact_hash, normalized_hash FROM local_fp WHERE exact_hash=? OR normalized_hash=? LIMIT 1",
|
| 516 |
(ehash, nhash)
|
|
@@ -523,7 +500,6 @@ def worker_task(cfg, task_id, total_tasks, interpreters, result_queue):
|
|
| 523 |
continue
|
| 524 |
local_conn.execute("INSERT INTO local_fp (exact_hash, normalized_hash) VALUES (?, ?)", (ehash, nhash))
|
| 525 |
|
| 526 |
-
# AST validation
|
| 527 |
try:
|
| 528 |
ast_ok, ast_results = validator.validate(text)
|
| 529 |
except Exception:
|
|
@@ -533,7 +509,6 @@ def worker_task(cfg, task_id, total_tasks, interpreters, result_queue):
|
|
| 533 |
stats["syntax_error"] += 1
|
| 534 |
continue
|
| 535 |
|
| 536 |
-
# Accept
|
| 537 |
record = {
|
| 538 |
"text": text,
|
| 539 |
"source_dataset": cfg["dataset"],
|
|
@@ -558,17 +533,15 @@ def worker_task(cfg, task_id, total_tasks, interpreters, result_queue):
|
|
| 558 |
if stats["processed"] % 5000 == 0:
|
| 559 |
print(f"[WORKER] {dataset_name} T{task_id} processed={stats['processed']:,} accepted={stats['accepted']:,}")
|
| 560 |
|
| 561 |
-
# End of stream – send remaining batch
|
| 562 |
send_batch()
|
| 563 |
result_queue.put(("task_done", stats, task_id, dataset_name))
|
| 564 |
print(f"[WORKER] {dataset_name} T{task_id} finished. accepted={stats['accepted']}")
|
| 565 |
validator.close()
|
| 566 |
local_conn.close()
|
| 567 |
|
| 568 |
-
#
|
| 569 |
-
# COORDINATOR
|
| 570 |
-
#
|
| 571 |
-
|
| 572 |
class Coordinator:
|
| 573 |
def __init__(self):
|
| 574 |
self.global_db_path = FINAL_ROOT / "global_dedup.sqlite"
|
|
@@ -613,7 +586,6 @@ class Coordinator:
|
|
| 613 |
ehash = record["exact_sha256"]
|
| 614 |
nhash = record["normalized_sha256"]
|
| 615 |
|
| 616 |
-
# Global dedup
|
| 617 |
dup = self.global_conn.execute(
|
| 618 |
"SELECT exact_hash FROM fingerprints WHERE exact_hash=? OR normalized_hash=? LIMIT 1",
|
| 619 |
(ehash, nhash)
|
|
@@ -622,7 +594,6 @@ class Coordinator:
|
|
| 622 |
self.stats["duplicate_exact" if dup[0] == ehash else "duplicate_normalized"] += 1
|
| 623 |
continue
|
| 624 |
|
| 625 |
-
# Insert into global DB
|
| 626 |
self.global_conn.execute(
|
| 627 |
"INSERT INTO fingerprints (exact_hash, normalized_hash) VALUES (?, ?)",
|
| 628 |
(ehash, nhash)
|
|
@@ -631,7 +602,7 @@ class Coordinator:
|
|
| 631 |
self.stats["bytes"] += record.get("char_count", 0)
|
| 632 |
self.master_records.append(record)
|
| 633 |
|
| 634 |
-
#
|
| 635 |
dataset_name = record["source_pool"]
|
| 636 |
verified_dir = FINAL_ROOT / dataset_name / "verified"
|
| 637 |
verified_dir.mkdir(parents=True, exist_ok=True)
|
|
@@ -642,41 +613,35 @@ class Coordinator:
|
|
| 642 |
filename += ".py"
|
| 643 |
else:
|
| 644 |
filename = f"{ehash[:16]}.py"
|
| 645 |
-
# Avoid collisions by adding hash prefix if file exists
|
| 646 |
filepath = verified_dir / filename
|
| 647 |
if filepath.exists():
|
| 648 |
filepath = verified_dir / f"{ehash[:16]}_{filename}"
|
| 649 |
with open(filepath, "w") as f:
|
| 650 |
f.write(record["text"])
|
| 651 |
|
| 652 |
-
# Flush master shard if needed
|
| 653 |
if len(self.master_records) >= SHARD_ROWS:
|
| 654 |
self.flush_master_shard()
|
| 655 |
|
| 656 |
-
# Commit every batch
|
| 657 |
self.global_conn.commit()
|
| 658 |
|
| 659 |
def finish(self):
|
| 660 |
self.flush_master_shard()
|
| 661 |
self.global_conn.commit()
|
| 662 |
self.global_conn.close()
|
| 663 |
-
#
|
| 664 |
for dataset_name in set(rec["source_pool"] for rec in self.master_records):
|
| 665 |
meta_path = FINAL_ROOT / dataset_name / "metadata.json"
|
| 666 |
if not meta_path.exists():
|
| 667 |
-
# Write minimal metadata
|
| 668 |
with open(meta_path, "w") as f:
|
| 669 |
json.dump({
|
| 670 |
"dataset": dataset_name,
|
| 671 |
"accepted_count": sum(1 for r in self.master_records if r["source_pool"] == dataset_name),
|
| 672 |
-
"processed_count": self.stats["accepted_records"], # not exact per dataset
|
| 673 |
"created": time.time()
|
| 674 |
}, f, indent=2)
|
| 675 |
|
| 676 |
-
#
|
| 677 |
-
# PIPELINE RUNNER
|
| 678 |
-
#
|
| 679 |
-
|
| 680 |
def run_pipeline():
|
| 681 |
global pipeline_status
|
| 682 |
pipeline_status["started"] = True
|
|
@@ -684,7 +649,6 @@ def run_pipeline():
|
|
| 684 |
|
| 685 |
try:
|
| 686 |
interpreters = get_interpreters()
|
| 687 |
-
# Build task list
|
| 688 |
tasks = []
|
| 689 |
for cfg in DATASETS:
|
| 690 |
ds = load_stream(cfg)
|
|
@@ -695,13 +659,8 @@ def run_pipeline():
|
|
| 695 |
total = len(tasks)
|
| 696 |
pipeline_status["total_tasks"] = total
|
| 697 |
|
| 698 |
-
# Create coordinator
|
| 699 |
coord = Coordinator()
|
| 700 |
-
|
| 701 |
-
# Set up multiprocessing queue
|
| 702 |
result_queue = mp.Queue()
|
| 703 |
-
|
| 704 |
-
# Start worker processes (limit to MAX_WORKERS)
|
| 705 |
active = []
|
| 706 |
task_idx = 0
|
| 707 |
|
|
@@ -715,22 +674,16 @@ def run_pipeline():
|
|
| 715 |
p.start()
|
| 716 |
return p
|
| 717 |
|
| 718 |
-
# initial fill
|
| 719 |
for _ in range(MAX_WORKERS):
|
| 720 |
p = start_worker()
|
| 721 |
if p:
|
| 722 |
active.append(p)
|
| 723 |
-
else:
|
| 724 |
-
break
|
| 725 |
|
| 726 |
-
# main loop: process results and manage workers
|
| 727 |
finished_tasks = 0
|
| 728 |
while active or task_idx < total:
|
| 729 |
-
# Check for results
|
| 730 |
try:
|
| 731 |
msg = result_queue.get(timeout=1)
|
| 732 |
except Empty:
|
| 733 |
-
# Check for dead workers and restart
|
| 734 |
new_active = []
|
| 735 |
for p in active:
|
| 736 |
if p.is_alive():
|
|
@@ -746,11 +699,9 @@ def run_pipeline():
|
|
| 746 |
active = new_active
|
| 747 |
continue
|
| 748 |
|
| 749 |
-
# Process message
|
| 750 |
if msg[0] == "accepted_batch":
|
| 751 |
-
_, batch,
|
| 752 |
coord.process_accepted_batch(batch)
|
| 753 |
-
# Update global stats with worker stats (optional)
|
| 754 |
elif msg[0] == "task_done":
|
| 755 |
_, worker_stats, tid, dset = msg
|
| 756 |
finished_tasks += 1
|
|
@@ -761,21 +712,17 @@ def run_pipeline():
|
|
| 761 |
if newp:
|
| 762 |
active.append(newp)
|
| 763 |
|
| 764 |
-
# Wait for all workers to finish
|
| 765 |
for p in active:
|
| 766 |
p.join()
|
| 767 |
finished_tasks += 1
|
| 768 |
pipeline_status["finished_tasks"] = finished_tasks
|
| 769 |
|
| 770 |
-
# Finalize coordinator
|
| 771 |
coord.finish()
|
| 772 |
pipeline_status["stats"] = coord.stats
|
| 773 |
pipeline_status["completed"] = True
|
| 774 |
pipeline_status["current_stage"] = "done"
|
| 775 |
|
| 776 |
-
# Upload global DB and metadata
|
| 777 |
upload_file(coord.global_db_path, f"{REMOTE_FINAL}/global_dedup.sqlite")
|
| 778 |
-
# Also upload per-dataset metadata (if needed)
|
| 779 |
for dset in DATASETS:
|
| 780 |
name = dset["name"]
|
| 781 |
meta_path = FINAL_ROOT / name / "metadata.json"
|
|
@@ -787,10 +734,9 @@ def run_pipeline():
|
|
| 787 |
pipeline_status["error"] = str(e)
|
| 788 |
traceback.print_exc()
|
| 789 |
|
| 790 |
-
#
|
| 791 |
# FASTAPI APP
|
| 792 |
-
#
|
| 793 |
-
|
| 794 |
app = FastAPI(title="Category1 Pipeline API")
|
| 795 |
|
| 796 |
@app.on_event("startup")
|
|
@@ -822,10 +768,9 @@ async def status():
|
|
| 822 |
"per_dataset": detailed,
|
| 823 |
})
|
| 824 |
|
| 825 |
-
#
|
| 826 |
-
# MAIN
|
| 827 |
-
#
|
| 828 |
-
|
| 829 |
if __name__ == "__main__":
|
| 830 |
port = int(os.environ.get("PORT", 7860))
|
| 831 |
uvicorn.run(app, host="0.0.0.0", port=port)
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
# ============================================================
|
| 3 |
+
# PIPELINE_API.PY — COORDINATOR‑WORKER PIPELINE
|
|
|
|
| 4 |
# ============================================================
|
| 5 |
|
| 6 |
import os
|
|
|
|
| 16 |
import requests
|
| 17 |
import threading
|
| 18 |
from pathlib import Path
|
|
|
|
| 19 |
from queue import Empty
|
| 20 |
|
| 21 |
import orjson
|
| 22 |
+
from datasets import load_dataset, Features, Value
|
| 23 |
from huggingface_hub import batch_bucket_files
|
| 24 |
from fastapi import FastAPI
|
| 25 |
from fastapi.responses import JSONResponse
|
| 26 |
import uvicorn
|
| 27 |
|
| 28 |
+
# ----------------------------------------------------------------------
|
| 29 |
+
# CONFIGURATION
|
| 30 |
+
# ----------------------------------------------------------------------
|
|
|
|
| 31 |
DATA_ROOT = Path(os.environ.get("DATA_ROOT", "/data"))
|
| 32 |
LOCAL_ROOT = DATA_ROOT / "category1_pipeline_v4"
|
| 33 |
STATE_ROOT = LOCAL_ROOT / "state"
|
|
|
|
| 39 |
BUCKET_ID = "PERDYPTO/private"
|
| 40 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 41 |
if not HF_TOKEN:
|
| 42 |
+
raise RuntimeError("HF_TOKEN not set.")
|
| 43 |
|
| 44 |
PYTHON_VERSIONS = ["3.11.9", "3.12.10", "3.13.15", "3.14.7"]
|
| 45 |
AST_ACCEPT_MODE = "ANY"
|
| 46 |
+
MAX_WORKERS = 2
|
| 47 |
+
SHARD_ROWS = 5_000
|
|
|
|
| 48 |
MIN_CHARS = 100
|
| 49 |
MAX_CHARS = 2_000_000
|
| 50 |
MIN_LINES = 2
|
|
|
|
| 57 |
REMOTE_STATE = f"{REMOTE_ROOT}/state"
|
| 58 |
REMOTE_FINAL = f"{REMOTE_ROOT}/final"
|
| 59 |
|
| 60 |
+
# ----------------------------------------------------------------------
|
| 61 |
+
# DATASETS (full list, unchanged)
|
| 62 |
+
# ----------------------------------------------------------------------
|
|
|
|
| 63 |
DATASETS = [
|
| 64 |
{
|
| 65 |
"name": "swallowcode_v2",
|
|
|
|
| 175 |
}
|
| 176 |
]
|
| 177 |
|
| 178 |
+
# ----------------------------------------------------------------------
|
| 179 |
# GLOBAL STATE FOR API
|
| 180 |
+
# ----------------------------------------------------------------------
|
|
|
|
| 181 |
pipeline_status = {
|
| 182 |
"started": False,
|
| 183 |
"completed": False,
|
|
|
|
| 196 |
"error": None,
|
| 197 |
}
|
| 198 |
|
| 199 |
+
# ----------------------------------------------------------------------
|
| 200 |
# HELPER FUNCTIONS
|
| 201 |
+
# ----------------------------------------------------------------------
|
|
|
|
| 202 |
def retry(fn, label, retries=5):
|
| 203 |
last_error = None
|
| 204 |
for attempt in range(1, retries + 1):
|
|
|
|
| 299 |
"license": str(license_name),
|
| 300 |
}
|
| 301 |
|
| 302 |
+
# ----------------------------------------------------------------------
|
| 303 |
+
# AST VALIDATOR (subprocess workers)
|
| 304 |
+
# ----------------------------------------------------------------------
|
|
|
|
| 305 |
AST_CHILD_CODE = r'''
|
| 306 |
import ast
|
| 307 |
import sys
|
|
|
|
| 333 |
)
|
| 334 |
|
| 335 |
def check(self, text):
|
|
|
|
| 336 |
encoded = base64.b64encode(text.encode("utf-8", errors="strict")).decode("ascii")
|
| 337 |
self.process.stdin.write(encoded + "\n")
|
| 338 |
self.process.stdin.flush()
|
|
|
|
| 382 |
except Exception:
|
| 383 |
pass
|
| 384 |
|
| 385 |
+
# ----------------------------------------------------------------------
|
| 386 |
+
# INTERPRETER LOCATION
|
| 387 |
+
# ----------------------------------------------------------------------
|
|
|
|
| 388 |
def get_interpreters():
|
| 389 |
interpreters = {}
|
| 390 |
for version in PYTHON_VERSIONS:
|
|
|
|
| 402 |
raise RuntimeError(f"Could not find Python {version}")
|
| 403 |
return interpreters
|
| 404 |
|
| 405 |
+
# ----------------------------------------------------------------------
|
| 406 |
+
# DATASET LOADER WITH FIX FOR SWALLOWCODE
|
| 407 |
+
# ----------------------------------------------------------------------
|
|
|
|
| 408 |
def load_stream(cfg):
|
| 409 |
kwargs = {"split": cfg["split"], "streaming": True, "token": HF_TOKEN}
|
| 410 |
if cfg.get("config"):
|
|
|
|
| 414 |
if cfg.get("languages"):
|
| 415 |
kwargs["languages"] = cfg["languages"]
|
| 416 |
|
| 417 |
+
# ---- FIX for swallowcode_v2 ----
|
| 418 |
if cfg["dataset"] == "tokyotech-llm/swallow-code-v2":
|
| 419 |
+
# We only need these four fields; drop all others (including problematic lint_report)
|
| 420 |
features = Features({
|
| 421 |
"text": Value("string"),
|
| 422 |
"repo_name": Value("string"),
|
| 423 |
"path": Value("string"),
|
| 424 |
"license": Value("string"),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 425 |
})
|
| 426 |
kwargs["features"] = features
|
| 427 |
+
# Remove 'name' because we override features
|
| 428 |
if "name" in kwargs:
|
| 429 |
del kwargs["name"]
|
|
|
|
| 430 |
|
| 431 |
+
return load_dataset(cfg["dataset"], **kwargs)
|
|
|
|
|
|
|
| 432 |
|
| 433 |
+
# ----------------------------------------------------------------------
|
| 434 |
+
# WORKER FUNCTION (runs in child process)
|
| 435 |
+
# ----------------------------------------------------------------------
|
| 436 |
def worker_task(cfg, task_id, total_tasks, interpreters, result_queue):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 437 |
dataset_name = cfg["name"]
|
| 438 |
print(f"[WORKER] {dataset_name} T{task_id} started")
|
| 439 |
|
|
|
|
| 440 |
ds = load_stream(cfg)
|
| 441 |
ds = ds.shard(num_shards=total_tasks, index=task_id)
|
| 442 |
|
| 443 |
+
# Local in-memory dedup
|
| 444 |
local_conn = sqlite3.connect(":memory:")
|
| 445 |
local_conn.execute("CREATE TABLE IF NOT EXISTS local_fp (exact_hash TEXT PRIMARY KEY, normalized_hash TEXT NOT NULL)")
|
| 446 |
local_conn.execute("CREATE INDEX IF NOT EXISTS idx_local_norm ON local_fp(normalized_hash)")
|
|
|
|
| 476 |
stats["other_reject"] += 1
|
| 477 |
continue
|
| 478 |
|
|
|
|
| 479 |
ok, reason = quality_check(text)
|
| 480 |
if not ok:
|
| 481 |
stats["quality_reject"] += 1
|
| 482 |
continue
|
| 483 |
|
|
|
|
| 484 |
try:
|
| 485 |
ehash = exact_hash(text)
|
| 486 |
nhash = normalized_hash(text)
|
|
|
|
| 488 |
stats["other_reject"] += 1
|
| 489 |
continue
|
| 490 |
|
|
|
|
| 491 |
dup = local_conn.execute(
|
| 492 |
"SELECT exact_hash, normalized_hash FROM local_fp WHERE exact_hash=? OR normalized_hash=? LIMIT 1",
|
| 493 |
(ehash, nhash)
|
|
|
|
| 500 |
continue
|
| 501 |
local_conn.execute("INSERT INTO local_fp (exact_hash, normalized_hash) VALUES (?, ?)", (ehash, nhash))
|
| 502 |
|
|
|
|
| 503 |
try:
|
| 504 |
ast_ok, ast_results = validator.validate(text)
|
| 505 |
except Exception:
|
|
|
|
| 509 |
stats["syntax_error"] += 1
|
| 510 |
continue
|
| 511 |
|
|
|
|
| 512 |
record = {
|
| 513 |
"text": text,
|
| 514 |
"source_dataset": cfg["dataset"],
|
|
|
|
| 533 |
if stats["processed"] % 5000 == 0:
|
| 534 |
print(f"[WORKER] {dataset_name} T{task_id} processed={stats['processed']:,} accepted={stats['accepted']:,}")
|
| 535 |
|
|
|
|
| 536 |
send_batch()
|
| 537 |
result_queue.put(("task_done", stats, task_id, dataset_name))
|
| 538 |
print(f"[WORKER] {dataset_name} T{task_id} finished. accepted={stats['accepted']}")
|
| 539 |
validator.close()
|
| 540 |
local_conn.close()
|
| 541 |
|
| 542 |
+
# ----------------------------------------------------------------------
|
| 543 |
+
# COORDINATOR (main process)
|
| 544 |
+
# ----------------------------------------------------------------------
|
|
|
|
| 545 |
class Coordinator:
|
| 546 |
def __init__(self):
|
| 547 |
self.global_db_path = FINAL_ROOT / "global_dedup.sqlite"
|
|
|
|
| 586 |
ehash = record["exact_sha256"]
|
| 587 |
nhash = record["normalized_sha256"]
|
| 588 |
|
|
|
|
| 589 |
dup = self.global_conn.execute(
|
| 590 |
"SELECT exact_hash FROM fingerprints WHERE exact_hash=? OR normalized_hash=? LIMIT 1",
|
| 591 |
(ehash, nhash)
|
|
|
|
| 594 |
self.stats["duplicate_exact" if dup[0] == ehash else "duplicate_normalized"] += 1
|
| 595 |
continue
|
| 596 |
|
|
|
|
| 597 |
self.global_conn.execute(
|
| 598 |
"INSERT INTO fingerprints (exact_hash, normalized_hash) VALUES (?, ?)",
|
| 599 |
(ehash, nhash)
|
|
|
|
| 602 |
self.stats["bytes"] += record.get("char_count", 0)
|
| 603 |
self.master_records.append(record)
|
| 604 |
|
| 605 |
+
# Write individual file to dataset/verified/
|
| 606 |
dataset_name = record["source_pool"]
|
| 607 |
verified_dir = FINAL_ROOT / dataset_name / "verified"
|
| 608 |
verified_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
| 613 |
filename += ".py"
|
| 614 |
else:
|
| 615 |
filename = f"{ehash[:16]}.py"
|
|
|
|
| 616 |
filepath = verified_dir / filename
|
| 617 |
if filepath.exists():
|
| 618 |
filepath = verified_dir / f"{ehash[:16]}_{filename}"
|
| 619 |
with open(filepath, "w") as f:
|
| 620 |
f.write(record["text"])
|
| 621 |
|
|
|
|
| 622 |
if len(self.master_records) >= SHARD_ROWS:
|
| 623 |
self.flush_master_shard()
|
| 624 |
|
|
|
|
| 625 |
self.global_conn.commit()
|
| 626 |
|
| 627 |
def finish(self):
|
| 628 |
self.flush_master_shard()
|
| 629 |
self.global_conn.commit()
|
| 630 |
self.global_conn.close()
|
| 631 |
+
# Write per-dataset metadata
|
| 632 |
for dataset_name in set(rec["source_pool"] for rec in self.master_records):
|
| 633 |
meta_path = FINAL_ROOT / dataset_name / "metadata.json"
|
| 634 |
if not meta_path.exists():
|
|
|
|
| 635 |
with open(meta_path, "w") as f:
|
| 636 |
json.dump({
|
| 637 |
"dataset": dataset_name,
|
| 638 |
"accepted_count": sum(1 for r in self.master_records if r["source_pool"] == dataset_name),
|
|
|
|
| 639 |
"created": time.time()
|
| 640 |
}, f, indent=2)
|
| 641 |
|
| 642 |
+
# ----------------------------------------------------------------------
|
| 643 |
+
# PIPELINE RUNNER
|
| 644 |
+
# ----------------------------------------------------------------------
|
|
|
|
| 645 |
def run_pipeline():
|
| 646 |
global pipeline_status
|
| 647 |
pipeline_status["started"] = True
|
|
|
|
| 649 |
|
| 650 |
try:
|
| 651 |
interpreters = get_interpreters()
|
|
|
|
| 652 |
tasks = []
|
| 653 |
for cfg in DATASETS:
|
| 654 |
ds = load_stream(cfg)
|
|
|
|
| 659 |
total = len(tasks)
|
| 660 |
pipeline_status["total_tasks"] = total
|
| 661 |
|
|
|
|
| 662 |
coord = Coordinator()
|
|
|
|
|
|
|
| 663 |
result_queue = mp.Queue()
|
|
|
|
|
|
|
| 664 |
active = []
|
| 665 |
task_idx = 0
|
| 666 |
|
|
|
|
| 674 |
p.start()
|
| 675 |
return p
|
| 676 |
|
|
|
|
| 677 |
for _ in range(MAX_WORKERS):
|
| 678 |
p = start_worker()
|
| 679 |
if p:
|
| 680 |
active.append(p)
|
|
|
|
|
|
|
| 681 |
|
|
|
|
| 682 |
finished_tasks = 0
|
| 683 |
while active or task_idx < total:
|
|
|
|
| 684 |
try:
|
| 685 |
msg = result_queue.get(timeout=1)
|
| 686 |
except Empty:
|
|
|
|
| 687 |
new_active = []
|
| 688 |
for p in active:
|
| 689 |
if p.is_alive():
|
|
|
|
| 699 |
active = new_active
|
| 700 |
continue
|
| 701 |
|
|
|
|
| 702 |
if msg[0] == "accepted_batch":
|
| 703 |
+
_, batch, _ = msg
|
| 704 |
coord.process_accepted_batch(batch)
|
|
|
|
| 705 |
elif msg[0] == "task_done":
|
| 706 |
_, worker_stats, tid, dset = msg
|
| 707 |
finished_tasks += 1
|
|
|
|
| 712 |
if newp:
|
| 713 |
active.append(newp)
|
| 714 |
|
|
|
|
| 715 |
for p in active:
|
| 716 |
p.join()
|
| 717 |
finished_tasks += 1
|
| 718 |
pipeline_status["finished_tasks"] = finished_tasks
|
| 719 |
|
|
|
|
| 720 |
coord.finish()
|
| 721 |
pipeline_status["stats"] = coord.stats
|
| 722 |
pipeline_status["completed"] = True
|
| 723 |
pipeline_status["current_stage"] = "done"
|
| 724 |
|
|
|
|
| 725 |
upload_file(coord.global_db_path, f"{REMOTE_FINAL}/global_dedup.sqlite")
|
|
|
|
| 726 |
for dset in DATASETS:
|
| 727 |
name = dset["name"]
|
| 728 |
meta_path = FINAL_ROOT / name / "metadata.json"
|
|
|
|
| 734 |
pipeline_status["error"] = str(e)
|
| 735 |
traceback.print_exc()
|
| 736 |
|
| 737 |
+
# ----------------------------------------------------------------------
|
| 738 |
# FASTAPI APP
|
| 739 |
+
# ----------------------------------------------------------------------
|
|
|
|
| 740 |
app = FastAPI(title="Category1 Pipeline API")
|
| 741 |
|
| 742 |
@app.on_event("startup")
|
|
|
|
| 768 |
"per_dataset": detailed,
|
| 769 |
})
|
| 770 |
|
| 771 |
+
# ----------------------------------------------------------------------
|
| 772 |
+
# MAIN
|
| 773 |
+
# ----------------------------------------------------------------------
|
|
|
|
| 774 |
if __name__ == "__main__":
|
| 775 |
port = int(os.environ.get("PORT", 7860))
|
| 776 |
uvicorn.run(app, host="0.0.0.0", port=port)
|