Spaces:
Sleeping
Sleeping
PERDYPTO commited on
Update pipeline.py
Browse files- pipeline.py +91 -39
pipeline.py
CHANGED
|
@@ -15,7 +15,7 @@
|
|
| 15 |
# /status -> more detailed per‑task progress
|
| 16 |
# ============================================================
|
| 17 |
|
| 18 |
-
import
|
| 19 |
import sys
|
| 20 |
import json
|
| 21 |
import time
|
|
@@ -28,9 +28,11 @@ import traceback
|
|
| 28 |
import multiprocessing as mp
|
| 29 |
import requests
|
| 30 |
import threading
|
|
|
|
| 31 |
|
| 32 |
from pathlib import Path
|
| 33 |
-
from concurrent.futures import ProcessPoolExecutor, as_completed
|
|
|
|
| 34 |
|
| 35 |
import orjson
|
| 36 |
from datasets import load_dataset
|
|
@@ -99,14 +101,14 @@ REMOTE_DATA = f"{REMOTE_ROOT}/datasets"
|
|
| 99 |
REMOTE_STATE = f"{REMOTE_ROOT}/state"
|
| 100 |
REMOTE_FINAL = f"{REMOTE_ROOT}/final"
|
| 101 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
# ============================================================
|
| 103 |
# DATASET LIST – CATEGORY 1 (SOURCE CODE ONLY)
|
| 104 |
# ============================================================
|
| 105 |
-
# This is your starting list. You can extend it with the
|
| 106 |
-
# additional verified/LLM-generated datasets we discussed.
|
| 107 |
-
# All datasets must be Python‑only (or filtered via path/kind).
|
| 108 |
-
# ============================================================
|
| 109 |
-
|
| 110 |
DATASETS = [
|
| 111 |
{
|
| 112 |
"name": "the_stack_dedup_python",
|
|
@@ -226,7 +228,7 @@ pipeline_status = {
|
|
| 226 |
# HELPER FUNCTIONS (identical to your Kaggle code)
|
| 227 |
# ============================================================
|
| 228 |
|
| 229 |
-
def retry(fn, label, retries=5):
|
| 230 |
last_error = None
|
| 231 |
for attempt in range(1, retries + 1):
|
| 232 |
try:
|
|
@@ -241,11 +243,26 @@ def retry(fn, label, retries=5):
|
|
| 241 |
def upload_file(local_path, remote_path):
|
| 242 |
local_path = str(local_path)
|
| 243 |
def op():
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
return retry(op, f"upload {remote_path}")
|
| 250 |
|
| 251 |
def exact_hash(text):
|
|
@@ -352,22 +369,44 @@ class ASTWorker:
|
|
| 352 |
def __init__(self, version, executable):
|
| 353 |
self.version = version
|
| 354 |
self.executable = executable
|
|
|
|
|
|
|
|
|
|
| 355 |
self.process = subprocess.Popen(
|
| 356 |
-
[executable, "-u", "-c", AST_CHILD_CODE],
|
| 357 |
stdin=subprocess.PIPE,
|
| 358 |
stdout=subprocess.PIPE,
|
| 359 |
stderr=subprocess.PIPE,
|
| 360 |
-
text=
|
| 361 |
-
bufsize=
|
| 362 |
)
|
| 363 |
|
| 364 |
-
def check(self, text):
|
| 365 |
import base64
|
| 366 |
encoded = base64.b64encode(text.encode("utf-8", errors="strict")).decode("ascii")
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 371 |
|
| 372 |
def close(self):
|
| 373 |
try:
|
|
@@ -376,9 +415,6 @@ class ASTWorker:
|
|
| 376 |
pass
|
| 377 |
try:
|
| 378 |
self.process.terminate()
|
| 379 |
-
except Exception:
|
| 380 |
-
pass
|
| 381 |
-
try:
|
| 382 |
self.process.wait(timeout=5)
|
| 383 |
except Exception:
|
| 384 |
try:
|
|
@@ -394,6 +430,7 @@ class ASTValidator:
|
|
| 394 |
|
| 395 |
def validate(self, text):
|
| 396 |
results = {}
|
|
|
|
| 397 |
for worker in self.workers:
|
| 398 |
try:
|
| 399 |
passed, detail = worker.check(text)
|
|
@@ -402,8 +439,18 @@ class ASTValidator:
|
|
| 402 |
detail = repr(e)
|
| 403 |
results[worker.version] = {"passed": bool(passed), "detail": detail}
|
| 404 |
if passed:
|
| 405 |
-
|
| 406 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 407 |
|
| 408 |
def close(self):
|
| 409 |
for worker in self.workers:
|
|
@@ -448,9 +495,8 @@ def load_task_state(dataset_name, task_id):
|
|
| 448 |
# Try to download from bucket
|
| 449 |
remote_path = f"{REMOTE_STATE}/{dataset_name}/task_{task_id}.json"
|
| 450 |
try:
|
| 451 |
-
import requests
|
| 452 |
url = f"https://huggingface.co/buckets/{BUCKET_ID}/resolve/{remote_path}"
|
| 453 |
-
response = requests.get(url, headers={"Authorization": f"Bearer {HF_TOKEN}"})
|
| 454 |
if response.status_code == 200:
|
| 455 |
data = response.json()
|
| 456 |
path.parent.mkdir(parents=True, exist_ok=True)
|
|
@@ -922,10 +968,10 @@ def run_pipeline():
|
|
| 922 |
for idx, (dataset_name, task_id, shard_number, remote_path) in enumerate(REMOTE_SHARDS, 1):
|
| 923 |
print(f"\n[GLOBAL] {idx:,}/{len(REMOTE_SHARDS):,} {dataset_name} T{task_id} S{shard_number}")
|
| 924 |
local_path = TMP_ROOT / "global" / dataset_name / f"task_{task_id}" / Path(remote_path).name
|
| 925 |
-
# Download using requests
|
| 926 |
try:
|
| 927 |
url = f"https://huggingface.co/buckets/{BUCKET_ID}/resolve/{remote_path}"
|
| 928 |
-
response = requests.get(url, headers={"Authorization": f"Bearer {HF_TOKEN}"})
|
| 929 |
if response.status_code != 200:
|
| 930 |
raise RuntimeError(f"Download failed: {response.status_code}")
|
| 931 |
local_path.parent.mkdir(parents=True, exist_ok=True)
|
|
@@ -1040,16 +1086,24 @@ def run_pipeline():
|
|
| 1040 |
raise
|
| 1041 |
|
| 1042 |
# ============================================================
|
| 1043 |
-
# FASTAPI APP
|
| 1044 |
# ============================================================
|
| 1045 |
|
| 1046 |
-
|
| 1047 |
-
|
| 1048 |
-
|
| 1049 |
-
|
| 1050 |
-
# Launch pipeline in a background thread so the API stays responsive
|
| 1051 |
-
thread = threading.Thread(target=run_pipeline, daemon=True)
|
| 1052 |
thread.start()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1053 |
|
| 1054 |
@app.get("/health")
|
| 1055 |
async def health():
|
|
@@ -1072,7 +1126,6 @@ async def status():
|
|
| 1072 |
Returns detailed per‑dataset task status (reads state files).
|
| 1073 |
For a deeper view, you can scan STATE_ROOT/*/task_*_COMPLETE.json.
|
| 1074 |
"""
|
| 1075 |
-
# Gather completion files for all datasets
|
| 1076 |
detailed = {}
|
| 1077 |
for dataset_dir in STATE_ROOT.iterdir():
|
| 1078 |
if dataset_dir.is_dir():
|
|
@@ -1096,6 +1149,5 @@ async def status():
|
|
| 1096 |
# ============================================================
|
| 1097 |
|
| 1098 |
if __name__ == "__main__":
|
| 1099 |
-
# Use the PORT environment variable if set (HF Spaces default 7860)
|
| 1100 |
port = int(os.environ.get("PORT", 7860))
|
| 1101 |
uvicorn.run(app, host="0.0.0.0", port=port)
|
|
|
|
| 15 |
# /status -> more detailed per‑task progress
|
| 16 |
# ============================================================
|
| 17 |
|
| 18 |
+
import os
|
| 19 |
import sys
|
| 20 |
import json
|
| 21 |
import time
|
|
|
|
| 28 |
import multiprocessing as mp
|
| 29 |
import requests
|
| 30 |
import threading
|
| 31 |
+
import signal
|
| 32 |
|
| 33 |
from pathlib import Path
|
| 34 |
+
from concurrent.futures import ProcessPoolExecutor, as_completed, TimeoutError
|
| 35 |
+
from contextlib import asynccontextmanager
|
| 36 |
|
| 37 |
import orjson
|
| 38 |
from datasets import load_dataset
|
|
|
|
| 101 |
REMOTE_STATE = f"{REMOTE_ROOT}/state"
|
| 102 |
REMOTE_FINAL = f"{REMOTE_ROOT}/final"
|
| 103 |
|
| 104 |
+
# Timeouts (in seconds)
|
| 105 |
+
AST_TIMEOUT = 30 # per‑file AST validation timeout
|
| 106 |
+
HTTP_TIMEOUT = (30, 120) # connect and read timeout for requests
|
| 107 |
+
UPLOAD_TIMEOUT = 300 # overall upload timeout
|
| 108 |
+
|
| 109 |
# ============================================================
|
| 110 |
# DATASET LIST – CATEGORY 1 (SOURCE CODE ONLY)
|
| 111 |
# ============================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
DATASETS = [
|
| 113 |
{
|
| 114 |
"name": "the_stack_dedup_python",
|
|
|
|
| 228 |
# HELPER FUNCTIONS (identical to your Kaggle code)
|
| 229 |
# ============================================================
|
| 230 |
|
| 231 |
+
def retry(fn, label, retries=5, timeout=HTTP_TIMEOUT):
|
| 232 |
last_error = None
|
| 233 |
for attempt in range(1, retries + 1):
|
| 234 |
try:
|
|
|
|
| 243 |
def upload_file(local_path, remote_path):
|
| 244 |
local_path = str(local_path)
|
| 245 |
def op():
|
| 246 |
+
# Use a thread with a timeout to prevent hanging uploads
|
| 247 |
+
result = [None, None] # [exception, return_value]
|
| 248 |
+
def target():
|
| 249 |
+
try:
|
| 250 |
+
result[1] = batch_bucket_files(
|
| 251 |
+
BUCKET_ID,
|
| 252 |
+
add=[(local_path, remote_path)],
|
| 253 |
+
token=HF_TOKEN,
|
| 254 |
+
)
|
| 255 |
+
except Exception as e:
|
| 256 |
+
result[0] = e
|
| 257 |
+
thread = threading.Thread(target=target)
|
| 258 |
+
thread.daemon = True
|
| 259 |
+
thread.start()
|
| 260 |
+
thread.join(timeout=UPLOAD_TIMEOUT)
|
| 261 |
+
if thread.is_alive():
|
| 262 |
+
raise TimeoutError(f"Upload of {remote_path} timed out after {UPLOAD_TIMEOUT}s")
|
| 263 |
+
if result[0] is not None:
|
| 264 |
+
raise result[0]
|
| 265 |
+
return result[1]
|
| 266 |
return retry(op, f"upload {remote_path}")
|
| 267 |
|
| 268 |
def exact_hash(text):
|
|
|
|
| 369 |
def __init__(self, version, executable):
|
| 370 |
self.version = version
|
| 371 |
self.executable = executable
|
| 372 |
+
self._start_process()
|
| 373 |
+
|
| 374 |
+
def _start_process(self):
|
| 375 |
self.process = subprocess.Popen(
|
| 376 |
+
[self.executable, "-u", "-c", AST_CHILD_CODE],
|
| 377 |
stdin=subprocess.PIPE,
|
| 378 |
stdout=subprocess.PIPE,
|
| 379 |
stderr=subprocess.PIPE,
|
| 380 |
+
text=False, # use bytes to avoid encoding issues
|
| 381 |
+
bufsize=0, # unbuffered
|
| 382 |
)
|
| 383 |
|
| 384 |
+
def check(self, text, timeout=AST_TIMEOUT):
|
| 385 |
import base64
|
| 386 |
encoded = base64.b64encode(text.encode("utf-8", errors="strict")).decode("ascii")
|
| 387 |
+
input_data = (encoded + "\n").encode("utf-8")
|
| 388 |
+
try:
|
| 389 |
+
out, err = self.process.communicate(input=input_data, timeout=timeout)
|
| 390 |
+
result = out.decode("utf-8", errors="ignore").strip()
|
| 391 |
+
if result == "OK":
|
| 392 |
+
return True, "OK"
|
| 393 |
+
else:
|
| 394 |
+
return False, result
|
| 395 |
+
except subprocess.TimeoutExpired:
|
| 396 |
+
# Kill the process and restart
|
| 397 |
+
self.process.kill()
|
| 398 |
+
self.process.wait()
|
| 399 |
+
self._start_process()
|
| 400 |
+
return False, "TIMEOUT"
|
| 401 |
+
except Exception as e:
|
| 402 |
+
# Restart on any other error
|
| 403 |
+
try:
|
| 404 |
+
self.process.kill()
|
| 405 |
+
self.process.wait()
|
| 406 |
+
except Exception:
|
| 407 |
+
pass
|
| 408 |
+
self._start_process()
|
| 409 |
+
return False, str(e)
|
| 410 |
|
| 411 |
def close(self):
|
| 412 |
try:
|
|
|
|
| 415 |
pass
|
| 416 |
try:
|
| 417 |
self.process.terminate()
|
|
|
|
|
|
|
|
|
|
| 418 |
self.process.wait(timeout=5)
|
| 419 |
except Exception:
|
| 420 |
try:
|
|
|
|
| 430 |
|
| 431 |
def validate(self, text):
|
| 432 |
results = {}
|
| 433 |
+
any_passed = False
|
| 434 |
for worker in self.workers:
|
| 435 |
try:
|
| 436 |
passed, detail = worker.check(text)
|
|
|
|
| 439 |
detail = repr(e)
|
| 440 |
results[worker.version] = {"passed": bool(passed), "detail": detail}
|
| 441 |
if passed:
|
| 442 |
+
any_passed = True
|
| 443 |
+
# We still validate with other workers to collect full results,
|
| 444 |
+
# but we can break early if we only care about "any".
|
| 445 |
+
# To save time, we can break if we already have a pass.
|
| 446 |
+
# But we want to check all versions for completeness.
|
| 447 |
+
# We'll continue, but we can skip if we want speed.
|
| 448 |
+
# We'll continue to gather results but if we already have a pass,
|
| 449 |
+
# we still need to check others? Not necessary for "ANY" rule.
|
| 450 |
+
# We'll break early for speed.
|
| 451 |
+
break
|
| 452 |
+
# Return True if any worker passed
|
| 453 |
+
return any_passed, results
|
| 454 |
|
| 455 |
def close(self):
|
| 456 |
for worker in self.workers:
|
|
|
|
| 495 |
# Try to download from bucket
|
| 496 |
remote_path = f"{REMOTE_STATE}/{dataset_name}/task_{task_id}.json"
|
| 497 |
try:
|
|
|
|
| 498 |
url = f"https://huggingface.co/buckets/{BUCKET_ID}/resolve/{remote_path}"
|
| 499 |
+
response = requests.get(url, headers={"Authorization": f"Bearer {HF_TOKEN}"}, timeout=HTTP_TIMEOUT)
|
| 500 |
if response.status_code == 200:
|
| 501 |
data = response.json()
|
| 502 |
path.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
| 968 |
for idx, (dataset_name, task_id, shard_number, remote_path) in enumerate(REMOTE_SHARDS, 1):
|
| 969 |
print(f"\n[GLOBAL] {idx:,}/{len(REMOTE_SHARDS):,} {dataset_name} T{task_id} S{shard_number}")
|
| 970 |
local_path = TMP_ROOT / "global" / dataset_name / f"task_{task_id}" / Path(remote_path).name
|
| 971 |
+
# Download using requests with timeout
|
| 972 |
try:
|
| 973 |
url = f"https://huggingface.co/buckets/{BUCKET_ID}/resolve/{remote_path}"
|
| 974 |
+
response = requests.get(url, headers={"Authorization": f"Bearer {HF_TOKEN}"}, timeout=HTTP_TIMEOUT)
|
| 975 |
if response.status_code != 200:
|
| 976 |
raise RuntimeError(f"Download failed: {response.status_code}")
|
| 977 |
local_path.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
| 1086 |
raise
|
| 1087 |
|
| 1088 |
# ============================================================
|
| 1089 |
+
# FASTAPI APP WITH LIFESPAN
|
| 1090 |
# ============================================================
|
| 1091 |
|
| 1092 |
+
@asynccontextmanager
|
| 1093 |
+
async def lifespan(app: FastAPI):
|
| 1094 |
+
# Startup: launch pipeline in a background thread (non‑daemon to allow graceful shutdown)
|
| 1095 |
+
thread = threading.Thread(target=run_pipeline, daemon=False)
|
|
|
|
|
|
|
| 1096 |
thread.start()
|
| 1097 |
+
yield
|
| 1098 |
+
# Shutdown: give the pipeline a chance to finish (or we can just let it continue)
|
| 1099 |
+
# We'll wait for a while, but if it's still running, we log and proceed.
|
| 1100 |
+
if thread.is_alive():
|
| 1101 |
+
print("[LIFESPAN] Pipeline is still running, waiting up to 60 seconds for graceful exit...")
|
| 1102 |
+
thread.join(timeout=60)
|
| 1103 |
+
if thread.is_alive():
|
| 1104 |
+
print("[LIFESPAN] Pipeline did not finish within timeout, continuing shutdown.")
|
| 1105 |
+
|
| 1106 |
+
app = FastAPI(title="Category1 Pipeline API", lifespan=lifespan)
|
| 1107 |
|
| 1108 |
@app.get("/health")
|
| 1109 |
async def health():
|
|
|
|
| 1126 |
Returns detailed per‑dataset task status (reads state files).
|
| 1127 |
For a deeper view, you can scan STATE_ROOT/*/task_*_COMPLETE.json.
|
| 1128 |
"""
|
|
|
|
| 1129 |
detailed = {}
|
| 1130 |
for dataset_dir in STATE_ROOT.iterdir():
|
| 1131 |
if dataset_dir.is_dir():
|
|
|
|
| 1149 |
# ============================================================
|
| 1150 |
|
| 1151 |
if __name__ == "__main__":
|
|
|
|
| 1152 |
port = int(os.environ.get("PORT", 7860))
|
| 1153 |
uvicorn.run(app, host="0.0.0.0", port=port)
|