Spaces:
Sleeping

PERDYPTO commited on
Commit
ff34b4a
·
verified ·
1 Parent(s): 748d990

Update pipeline.py

Browse files
Files changed (1) hide show
  1. pipeline.py +0 -1292
pipeline.py CHANGED
@@ -1,1292 +0,0 @@
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,
8
- # validates every Python file with 4 real CPython interpreters,
9
- # removes duplicates globally, and produces a master dataset.
10
- #
11
- # All state and output is stored in the bucket PERDYPTO/private.
12
- #
13
- # The FastAPI server starts automatically and exposes:
14
- # /health -> current pipeline status + aggregated stats
15
- # /status -> more detailed per-task progress
16
- #
17
- # ------------------------------------------------------------
18
- # CHANGES IN THIS REVISION (vs. the version you pasted):
19
- #
20
- # 1. FIXED: bucket downloads no longer use a fabricated
21
- # "https://huggingface.co/buckets/{id}/resolve/{path}" REST
22
- # URL (that endpoint does not exist for buckets and was
23
- # silently failing, caught by broad except blocks, which
24
- # meant state-resume never worked and global dedup could
25
- # complete "successfully" with zero records). Downloads now
26
- # shell out to the documented `hf` CLI:
27
- # hf buckets cp hf://buckets/<bucket_id>/<path> -
28
- # which streams bytes to stdout. See download_bucket_file().
29
- #
30
- # 2. FIXED: ASTWorker no longer misuses Popen.communicate() in
31
- # a loop (communicate() closes stdin and waits for exit — it
32
- # cannot be called repeatedly against a persistent worker).
33
- # Each worker now writes to stdin / reads a line from stdout
34
- # directly, so the 4 interpreter subprocesses are genuinely
35
- # long-lived and reused across every file, as originally
36
- # intended. This is a large performance fix as well as a
37
- # correctness fix.
38
- #
39
- # 3. FIXED: state["processed"] is now only advanced up to the
40
- # last successfully flushed shard boundary, not per-row. This
41
- # closes the crash/resume data-loss gap where accepted records
42
- # sitting in an unflushed shard buffer would be silently
43
- # skipped on resume (ds.skip(processed) skipped past rows
44
- # that had never actually been uploaded).
45
- #
46
- # 4. FIXED: global-dedup shard download failures now hard-stop
47
- # the pipeline (raise) instead of silently `continue`-ing
48
- # past a missing shard, which previously could produce a
49
- # "COMPLETE" pipeline run with silently missing data.
50
- #
51
- # 5. FIXED: upload_file's retry-with-thread-timeout wrapper now
52
- # marks the helper thread as daemon=True, so repeated timeouts
53
- # don't leak non-daemon threads that block process shutdown.
54
- #
55
- # 6. CHANGED (requested): SHARD_ROWS raised from 5,000 to
56
- # 500,000 records per shard, so instead of many ~6-7MB files
57
- # you get far fewer, larger (~500-700MB class) files. Same
58
- # knob also governs CHECKPOINT_EVERY cadence (kept equal to
59
- # SHARD_ROWS, consistent with the original design).
60
- #
61
- # 7. CHANGED (requested): all originally-listed datasets are kept
62
- # in DATASETS for reference, but only the first
63
- # ("the_stack_dedup_python") is active — every other entry is
64
- # commented out, exactly as before, just re-confirmed intact.
65
- # ============================================================
66
-
67
- import os
68
- import sys
69
- import json
70
- import time
71
- import gzip
72
- import shutil
73
- import hashlib
74
- import sqlite3
75
- import subprocess
76
- import traceback
77
- import multiprocessing as mp
78
- import threading
79
- import signal
80
-
81
- from pathlib import Path
82
- from concurrent.futures import ProcessPoolExecutor, as_completed, TimeoutError
83
- from contextlib import asynccontextmanager
84
-
85
- import orjson
86
- from datasets import load_dataset
87
- from huggingface_hub import batch_bucket_files
88
-
89
- from fastapi import FastAPI, BackgroundTasks
90
- from fastapi.responses import JSONResponse
91
- import uvicorn
92
-
93
- # ============================================================
94
- # BASIC CONFIG — ADAPTED FOR HF SPACE PERSISTENT STORAGE
95
- # ============================================================
96
-
97
- # All persistent data goes under /data (the mounted bucket)
98
- DATA_ROOT = Path(os.environ.get("DATA_ROOT", "/data"))
99
-
100
- # The pipeline root inside the mounted volume
101
- LOCAL_ROOT = DATA_ROOT / "category1_pipeline_v4"
102
- STATE_ROOT = LOCAL_ROOT / "state"
103
- TMP_ROOT = LOCAL_ROOT / "tmp"
104
- FINAL_ROOT = LOCAL_ROOT / "final"
105
-
106
- for directory in [STATE_ROOT, TMP_ROOT, FINAL_ROOT]:
107
- directory.mkdir(parents=True, exist_ok=True)
108
-
109
- # Bucket info (from your Kaggle config)
110
- BUCKET_ID = "PERDYPTO/private"
111
-
112
- # Hugging Face token – must be set as a Space secret
113
- HF_TOKEN = os.environ.get("HF_TOKEN")
114
- if not HF_TOKEN:
115
- raise RuntimeError("HF_TOKEN environment variable not set. Add it in Space Settings → Secrets.")
116
-
117
- # Python versions for AST validation (these will be installed by uv in the Dockerfile)
118
- PYTHON_VERSIONS = [
119
- "3.11.9",
120
- "3.12.10",
121
- "3.13.15",
122
- "3.14.7",
123
- ]
124
-
125
- # AST rule: any one version passing is accepted
126
- AST_ACCEPT_MODE = "ANY"
127
-
128
- # Parallelism – reduced for HF Space (2 vCPU, 16 GB RAM)
129
- MAX_WORKERS = 2
130
-
131
- # ------------------------------------------------------------
132
- # SHARD SIZE — CHANGED per request.
133
- # Previously 5,000 rows/shard (~6-7MB gzip files, many of them).
134
- # Now 500,000 rows/shard -> far fewer, larger files.
135
- # NOTE: actual file size still depends on average row size; at
136
- # ~1-1.4KB/row post-gzip this lands roughly in the 500MB-700MB
137
- # range per file, as you asked for.
138
- # ------------------------------------------------------------
139
- SHARD_ROWS = 700_000
140
-
141
- # Checkpoint frequency (in source records). Kept equal to
142
- # SHARD_ROWS so a checkpoint always lines up with a shard flush
143
- # boundary (see fix #3 above — this matters for correctness now,
144
- # not just cadence).
145
- CHECKPOINT_EVERY = SHARD_ROWS
146
-
147
- # Quality filters
148
- MIN_CHARS = 100
149
- MAX_CHARS = 2_000_000
150
- MIN_LINES = 2
151
- MAX_LINE_LENGTH = 20_000
152
-
153
- REJECT_GENERATED = True
154
- REJECT_VENDOR = True
155
-
156
- # Remote paths inside the bucket
157
- REMOTE_ROOT = "category1/v4"
158
- REMOTE_DATA = f"{REMOTE_ROOT}/datasets"
159
- REMOTE_STATE = f"{REMOTE_ROOT}/state"
160
- REMOTE_FINAL = f"{REMOTE_ROOT}/final"
161
-
162
- # Timeouts (in seconds)
163
- AST_TIMEOUT = 30 # per-file AST validation timeout
164
- HTTP_TIMEOUT = (30, 120) # connect and read timeout for requests
165
- UPLOAD_TIMEOUT = 300 # overall upload timeout
166
- DOWNLOAD_TIMEOUT = 300 # overall download timeout (bucket CLI download)
167
-
168
- # ============================================================
169
- # DATASET LIST – CATEGORY 1 (SOURCE CODE ONLY)
170
- # All originally-listed datasets are preserved below for
171
- # reference. Only the first entry is active; every other entry
172
- # stays commented out.
173
- # ============================================================
174
- DATASETS = [
175
- {
176
- "name": "the_stack_dedup_python",
177
- "dataset": "bigcode/the-stack-dedup",
178
- "config": None,
179
- "data_dir": "data/python",
180
- "split": "train",
181
- "kind": "generic",
182
- "text_fields": ["content"],
183
- "repo_fields": ["max_stars_repo_name", "repo_name"],
184
- "path_fields": ["max_stars_repo_path", "path"],
185
- "license_fields": ["max_stars_repo_licenses", "license"],
186
- },
187
- {
188
- "name": "starcoderdata_python",
189
- "dataset": "bigcode/starcoderdata",
190
- "config": None,
191
- "data_dir": "python",
192
- "split": "train",
193
- "kind": "generic",
194
- "text_fields": ["content"],
195
- "repo_fields": ["max_stars_repo_name", "repo_name"],
196
- "path_fields": ["max_stars_repo_path", "path"],
197
- "license_fields": ["max_stars_repo_licenses", "license"],
198
- },
199
- {
200
- "name": "codeparrot_clean",
201
- "dataset": "codeparrot/codeparrot-clean",
202
- "config": None,
203
- "split": "train",
204
- "kind": "generic",
205
- "text_fields": ["content"],
206
- "repo_fields": ["repo_name", "repo"],
207
- "path_fields": ["path", "filepath"],
208
- "license_fields": ["license"],
209
- },
210
- {
211
- "name": "pyhub",
212
- "dataset": "FurkanNar/PyHub",
213
- "config": None,
214
- "split": "train",
215
- "kind": "generic",
216
- "text_fields": ["content", "text"],
217
- "repo_fields": ["repo", "repo_name"],
218
- "path_fields": ["filepath", "path"],
219
- "license_fields": ["license", "license_type"],
220
- },
221
- {
222
- "name": "redstone_code_python",
223
- "dataset": "zjsd/RedStone-Code-python",
224
- "config": None,
225
- "split": "train",
226
- "kind": "generic",
227
- "text_fields": ["content"],
228
- "repo_fields": [],
229
- "path_fields": [],
230
- "license_fields": [],
231
- },
232
- {
233
- "name": "github_python",
234
- "dataset": "jblitzar/github-python",
235
- "config": None,
236
- "split": "train",
237
- "kind": "generic",
238
- "text_fields": ["content"],
239
- "repo_fields": ["repo"],
240
- "path_fields": ["path"],
241
- "license_fields": ["license"],
242
- },
243
- {
244
- "name": "the_stack_v2_smol",
245
- "dataset": "bigcode/the-stack-v2-train-smol-ids",
246
- "config": None,
247
- "split": "train",
248
- "kind": "generic",
249
- "text_fields": ["content"],
250
- "repo_fields": ["repo_name"],
251
- "path_fields": ["path"],
252
- "license_fields": ["license"],
253
- },
254
- {
255
- "name": "codeparrot_raw",
256
- "dataset": "transformersbook/codeparrot",
257
- "config": None,
258
- "split": "train",
259
- "kind": "generic",
260
- "text_fields": ["content"],
261
- "repo_fields": [],
262
- "path_fields": [],
263
- "license_fields": [],
264
- }
265
- ]
266
-
267
- # ============================================================
268
- # GLOBAL STATE FOR API
269
- # ============================================================
270
-
271
- pipeline_status = {
272
- "started": False,
273
- "completed": False,
274
- "current_stage": "idle", # idle | processing | global_dedup | done | failed
275
- "total_tasks": 0,
276
- "finished_tasks": 0,
277
- "stats": {
278
- "input_records": 0,
279
- "accepted_records": 0,
280
- "duplicate_exact": 0,
281
- "duplicate_normalized": 0,
282
- "invalid_records": 0,
283
- "bytes": 0,
284
- "final_shards": 0,
285
- },
286
- "error": None,
287
- }
288
-
289
- # ============================================================
290
- # HELPER FUNCTIONS
291
- # ============================================================
292
-
293
- def retry(fn, label, retries=5, timeout=HTTP_TIMEOUT):
294
- last_error = None
295
- for attempt in range(1, retries + 1):
296
- try:
297
- return fn()
298
- except Exception as e:
299
- last_error = e
300
- print(f"[RETRY] {label} {attempt}/{retries}: {e}")
301
- if attempt < retries:
302
- time.sleep(min(30, 2 ** attempt))
303
- raise last_error
304
-
305
- def upload_file(local_path, remote_path):
306
- local_path = str(local_path)
307
- def op():
308
- # Use a thread with a timeout to prevent hanging uploads
309
- result = [None, None] # [exception, return_value]
310
- def target():
311
- try:
312
- result[1] = batch_bucket_files(
313
- BUCKET_ID,
314
- add=[(local_path, remote_path)],
315
- token=HF_TOKEN,
316
- )
317
- except Exception as e:
318
- result[0] = e
319
- # FIX (#5): daemon=True so a hung upload thread doesn't
320
- # block process shutdown / leak indefinitely on repeated
321
- # retries.
322
- thread = threading.Thread(target=target, daemon=True)
323
- thread.start()
324
- thread.join(timeout=UPLOAD_TIMEOUT)
325
- if thread.is_alive():
326
- raise TimeoutError(f"Upload of {remote_path} timed out after {UPLOAD_TIMEOUT}s")
327
- if result[0] is not None:
328
- raise result[0]
329
- return result[1]
330
- return retry(op, f"upload {remote_path}")
331
-
332
- def download_bucket_file(remote_path, local_path, timeout=DOWNLOAD_TIMEOUT):
333
- """
334
- FIX (#1): Bucket downloads previously hit a fabricated REST URL
335
- (huggingface.co/buckets/{id}/resolve/{path}) which is not a real
336
- endpoint. The documented way to pull a file back out of a bucket
337
- is the `hf` CLI's bucket-copy command, streaming to stdout:
338
-
339
- hf buckets cp hf://buckets/<bucket_id>/<remote_path> -
340
-
341
- We shell out to that here. Raises on any failure — callers must
342
- NOT silently swallow this (see fix #4).
343
- """
344
- local_path = Path(local_path)
345
- local_path.parent.mkdir(parents=True, exist_ok=True)
346
- remote_uri = f"hf://buckets/{BUCKET_ID}/{remote_path}"
347
-
348
- def op():
349
- env = os.environ.copy()
350
- env["HF_TOKEN"] = HF_TOKEN
351
- with open(local_path, "wb") as out_f:
352
- proc = subprocess.run(
353
- ["hf", "buckets", "cp", remote_uri, "-"],
354
- stdout=out_f,
355
- stderr=subprocess.PIPE,
356
- env=env,
357
- timeout=timeout,
358
- )
359
- if proc.returncode != 0:
360
- # Clean up partial file so we never mistake it for real data
361
- try:
362
- local_path.unlink()
363
- except Exception:
364
- pass
365
- stderr_text = proc.stderr.decode("utf-8", errors="ignore") if proc.stderr else ""
366
- raise RuntimeError(f"hf buckets cp failed ({proc.returncode}) for {remote_uri}: {stderr_text[:500]}")
367
- if not local_path.exists() or local_path.stat().st_size == 0:
368
- raise RuntimeError(f"Downloaded file missing or empty: {remote_uri}")
369
- return local_path
370
-
371
- return retry(op, f"download {remote_path}")
372
-
373
- def download_bucket_json(remote_path, timeout=HTTP_TIMEOUT[1]):
374
- """Convenience wrapper: download a small JSON file from the bucket
375
- and parse it. Returns None if the remote file genuinely does not
376
- exist (as opposed to a transient failure, which retries and then
377
- raises)."""
378
- tmp_path = TMP_ROOT / "_json_fetch" / f"{hashlib.sha256(remote_path.encode()).hexdigest()}.json"
379
- try:
380
- download_bucket_file(remote_path, tmp_path, timeout=timeout)
381
- except Exception as e:
382
- # This can legitimately mean "doesn't exist yet" (first run,
383
- # no state saved). We don't hard-fail here since callers use
384
- # this specifically for optional resume state.
385
- print(f"[STATE] Could not fetch remote state {remote_path}: {e}")
386
- return None
387
- try:
388
- with open(tmp_path) as f:
389
- data = json.load(f)
390
- return data
391
- finally:
392
- try:
393
- tmp_path.unlink()
394
- except Exception:
395
- pass
396
-
397
- def exact_hash(text):
398
- return hashlib.sha256(text.encode("utf-8", errors="strict")).hexdigest()
399
-
400
- def normalize_code(text):
401
- text = text.replace("\r\n", "\n").replace("\r", "\n")
402
- lines = text.split("\n")
403
- lines = [line.rstrip() for line in lines]
404
- while lines and not lines[0].strip():
405
- lines.pop(0)
406
- while lines and not lines[-1].strip():
407
- lines.pop()
408
- output = []
409
- blank_count = 0
410
- for line in lines:
411
- if not line.strip():
412
- blank_count += 1
413
- if blank_count <= 2:
414
- output.append("")
415
- else:
416
- blank_count = 0
417
- output.append(line)
418
- return "\n".join(output)
419
-
420
- def normalized_hash(text):
421
- return hashlib.sha256(normalize_code(text).encode("utf-8", errors="strict")).hexdigest()
422
-
423
- def quality_check(text):
424
- if not isinstance(text, str):
425
- return False, "not_string"
426
- if len(text) < MIN_CHARS:
427
- return False, "too_short"
428
- if len(text) > MAX_CHARS:
429
- return False, "too_large"
430
- if "\x00" in text:
431
- return False, "null_byte"
432
- lines = text.splitlines()
433
- if len(lines) < MIN_LINES:
434
- return False, "too_few_lines"
435
- for line in lines:
436
- if len(line) > MAX_LINE_LENGTH:
437
- return False, "line_too_long"
438
- printable = sum(1 for ch in text if ch in "\n\r\t" or ch.isprintable())
439
- ratio = printable / max(1, len(text))
440
- if ratio < 0.97:
441
- return False, "binary_like"
442
- return True, "ok"
443
-
444
- def get_first(row, fields, default=""):
445
- for field in fields:
446
- if field not in row:
447
- continue
448
- value = row[field]
449
- if value is None:
450
- continue
451
- if isinstance(value, str):
452
- if value.strip():
453
- return value
454
- elif isinstance(value, (int, float, bool)):
455
- return str(value)
456
- return default
457
-
458
- def extract_record(row, cfg):
459
- text = get_first(row, cfg["text_fields"])
460
- repo = get_first(row, cfg["repo_fields"])
461
- path = get_first(row, cfg["path_fields"])
462
- license_name = get_first(row, cfg["license_fields"], "unknown")
463
- # RealPBT nested repo metadata
464
- if cfg["kind"] == "realpbt":
465
- repo_obj = row.get("repo")
466
- if isinstance(repo_obj, dict):
467
- repo = repo_obj.get("name") or repo_obj.get("full_name") or repo_obj.get("url") or repo
468
- license_name = repo_obj.get("license") or repo_obj.get("license_type") or license_name
469
- return {
470
- "text": text,
471
- "repo": str(repo),
472
- "path": str(path),
473
- "license": str(license_name),
474
- }
475
-
476
- # ============================================================
477
- # AST VALIDATOR (persistent subprocess workers, one per Python version)
478
- # ============================================================
479
-
480
- AST_CHILD_CODE = r'''
481
- import ast
482
- import sys
483
- import base64
484
-
485
- for line in sys.stdin:
486
- line = line.rstrip("\n")
487
- if not line:
488
- continue
489
- try:
490
- source = base64.b64decode(line).decode("utf-8")
491
- ast.parse(source)
492
- print("OK", flush=True)
493
- except Exception as e:
494
- msg = (type(e).__name__ + "\t" + str(e)[:300]).replace("\n", " ").replace("\t", " ", 0)
495
- print("ERR\t" + type(e).__name__ + "\t" + str(e)[:300].replace("\n", " "), flush=True)
496
- '''
497
-
498
- class ASTWorker:
499
- """
500
- FIX (#2): The original implementation called
501
- Popen.communicate() once per file against the SAME process
502
- object. communicate() closes stdin and waits for the child to
503
- exit — it is a one-shot call, not a request/response primitive
504
- you can reuse. That meant every call after the first either hit
505
- a dead pipe or forced a timeout-triggered restart, so in
506
- practice each interpreter was likely being respawned per file
507
- (or per call) instead of staying resident.
508
-
509
- This version keeps the child's stdin/stdout pipes open across
510
- calls and does the write + readline itself, so the persistent
511
- "read one line, parse, print OK/ERR" loop in AST_CHILD_CODE is
512
- actually used as designed.
513
- """
514
- def __init__(self, version, executable):
515
- self.version = version
516
- self.executable = executable
517
- self.process = None
518
- self._start_process()
519
-
520
- def _start_process(self):
521
- self.process = subprocess.Popen(
522
- [self.executable, "-u", "-c", AST_CHILD_CODE],
523
- stdin=subprocess.PIPE,
524
- stdout=subprocess.PIPE,
525
- stderr=subprocess.PIPE,
526
- bufsize=0, # unbuffered
527
- )
528
-
529
- def check(self, text, timeout=AST_TIMEOUT):
530
- import base64
531
- encoded = base64.b64encode(text.encode("utf-8", errors="strict")).decode("ascii")
532
- line = (encoded + "\n").encode("ascii")
533
-
534
- result_holder = {}
535
-
536
- def do_io():
537
- try:
538
- self.process.stdin.write(line)
539
- self.process.stdin.flush()
540
- out_line = self.process.stdout.readline()
541
- result_holder["out"] = out_line
542
- except Exception as e:
543
- result_holder["exc"] = e
544
-
545
- io_thread = threading.Thread(target=do_io, daemon=True)
546
- io_thread.start()
547
- io_thread.join(timeout=timeout)
548
-
549
- if io_thread.is_alive():
550
- # Genuinely stuck (e.g. pathological input causing a hang
551
- # in ast.parse, or a dead pipe) — kill and restart.
552
- self._restart()
553
- return False, "TIMEOUT"
554
-
555
- if "exc" in result_holder:
556
- self._restart()
557
- return False, repr(result_holder["exc"])
558
-
559
- out_line = result_holder.get("out", b"")
560
- if not out_line:
561
- # Empty read means the child process exited/closed stdout.
562
- self._restart()
563
- return False, "EOF"
564
-
565
- result = out_line.decode("utf-8", errors="ignore").strip()
566
- if result == "OK":
567
- return True, "OK"
568
- return False, result
569
-
570
- def _restart(self):
571
- try:
572
- self.process.kill()
573
- self.process.wait(timeout=5)
574
- except Exception:
575
- pass
576
- self._start_process()
577
-
578
- def close(self):
579
- try:
580
- self.process.stdin.close()
581
- except Exception:
582
- pass
583
- try:
584
- self.process.terminate()
585
- self.process.wait(timeout=5)
586
- except Exception:
587
- try:
588
- self.process.kill()
589
- except Exception:
590
- pass
591
-
592
- class ASTValidator:
593
- def __init__(self, interpreters):
594
- self.workers = []
595
- for version in PYTHON_VERSIONS:
596
- self.workers.append(ASTWorker(version, interpreters[version]))
597
-
598
- def validate(self, text):
599
- results = {}
600
- any_passed = False
601
- for worker in self.workers:
602
- try:
603
- passed, detail = worker.check(text)
604
- except Exception as e:
605
- passed = False
606
- detail = repr(e)
607
- results[worker.version] = {"passed": bool(passed), "detail": detail}
608
- if passed:
609
- any_passed = True
610
- break
611
- return any_passed, results
612
-
613
- def close(self):
614
- for worker in self.workers:
615
- try:
616
- worker.close()
617
- except Exception:
618
- pass
619
-
620
- # ============================================================
621
- # LOCAL STATE MANAGEMENT (with remote fallback)
622
- # ============================================================
623
-
624
- def task_state_path(dataset_name, task_id):
625
- directory = STATE_ROOT / dataset_name
626
- directory.mkdir(parents=True, exist_ok=True)
627
- return directory / f"task_{task_id}.json"
628
-
629
- def default_state():
630
- return {
631
- "processed": 0,
632
- "accepted": 0,
633
- "duplicate_exact": 0,
634
- "duplicate_normalized": 0,
635
- "syntax_error": 0,
636
- "quality_reject": 0,
637
- "other_reject": 0,
638
- "shards_uploaded": 0,
639
- "bytes_accepted": 0,
640
- "complete": False,
641
- "started": time.time(),
642
- "updated": time.time(),
643
- }
644
-
645
- def load_task_state(dataset_name, task_id):
646
- path = task_state_path(dataset_name, task_id)
647
- if path.exists():
648
- try:
649
- with open(path) as f:
650
- return json.load(f)
651
- except Exception:
652
- pass
653
- # Try to download from bucket (FIX #1: uses hf CLI now, not a
654
- # fabricated REST URL).
655
- remote_path = f"{REMOTE_STATE}/{dataset_name}/task_{task_id}.json"
656
- data = download_bucket_json(remote_path)
657
- if data is not None:
658
- try:
659
- path.parent.mkdir(parents=True, exist_ok=True)
660
- with open(path, "w") as f:
661
- json.dump(data, f, indent=2)
662
- except Exception:
663
- pass
664
- return data
665
- return default_state()
666
-
667
- def save_task_state(dataset_name, task_id, state):
668
- path = task_state_path(dataset_name, task_id)
669
- tmp = path.with_suffix(".tmp")
670
- state["updated"] = time.time()
671
- with open(tmp, "w") as f:
672
- json.dump(state, f, indent=2)
673
- os.replace(tmp, path)
674
- upload_file(path, f"{REMOTE_STATE}/{dataset_name}/task_{task_id}.json")
675
-
676
- # ============================================================
677
- # DATASET STREAMING LOADER
678
- # ============================================================
679
-
680
- def load_stream(cfg):
681
- kwargs = {"split": cfg["split"], "streaming": True, "token": HF_TOKEN}
682
- if cfg.get("config"):
683
- kwargs["name"] = cfg["config"]
684
- if cfg.get("data_dir"):
685
- kwargs["data_dir"] = cfg["data_dir"]
686
- if cfg.get("languages"):
687
- kwargs["languages"] = cfg["languages"]
688
- return load_dataset(cfg["dataset"], **kwargs)
689
-
690
- # ============================================================
691
- # SHARD UPLOAD (worker shard)
692
- # ============================================================
693
-
694
- def upload_worker_shard(cfg, task_id, shard_number, records):
695
- dataset_name = cfg["name"]
696
- worker_dir = TMP_ROOT / dataset_name / f"task_{task_id}"
697
- worker_dir.mkdir(parents=True, exist_ok=True)
698
- filename = f"task-{task_id:04d}-shard-{shard_number:08d}.jsonl.gz"
699
- local_path = worker_dir / filename
700
- remote_path = f"{REMOTE_DATA}/{dataset_name}/task_{task_id}/{filename}"
701
- with gzip.open(local_path, "wb") as f:
702
- for record in records:
703
- f.write(orjson.dumps(record) + b"\n")
704
- upload_file(local_path, remote_path)
705
- try:
706
- local_path.unlink()
707
- except Exception:
708
- pass
709
- return remote_path
710
-
711
- # ============================================================
712
- # PARTITION PROCESSING (one task = one deterministic shard slice)
713
- # ============================================================
714
-
715
- def process_partition(cfg, task_id, total_tasks, interpreters):
716
- dataset_name = cfg["name"]
717
- print(f"\n[{dataset_name}] TASK {task_id + 1}/{total_tasks} START")
718
- state = load_task_state(dataset_name, task_id)
719
- if state.get("complete", False):
720
- print(f"[{dataset_name}] TASK {task_id} already complete.")
721
- return {**state, "task_id": task_id, "complete": True}
722
-
723
- # Load dataset and shard it into total_tasks partitions
724
- ds = load_stream(cfg)
725
- ds = ds.shard(num_shards=total_tasks, index=task_id)
726
- print(f"[{dataset_name}] TASK {task_id}: assigned partition {task_id + 1}/{total_tasks}")
727
-
728
- # FIX (#3): resume from the last row known to be SAFELY
729
- # persisted (i.e. included in an uploaded shard + saved
730
- # state), not from a per-row counter that could be ahead of
731
- # what was actually flushed. We track that separately as
732
- # "processed_committed" and keep "processed" as a live,
733
- # in-progress counter that only gets promoted to
734
- # "processed_committed" at flush time.
735
- processed_committed = int(state.get("processed_committed", state.get("processed", 0)))
736
- state["processed_committed"] = processed_committed
737
- state["processed"] = processed_committed
738
- if processed_committed > 0:
739
- print(f"[{dataset_name}] TASK {task_id}: resuming after {processed_committed:,} committed records")
740
- ds = ds.skip(processed_committed)
741
-
742
- validator = ASTValidator(interpreters)
743
-
744
- # Local dedup SQLite for this task – with WAL and NORMAL sync for reliability
745
- task_dir = STATE_ROOT / dataset_name
746
- task_dir.mkdir(parents=True, exist_ok=True)
747
- db_path = task_dir / f"task_{task_id}.sqlite"
748
- conn = sqlite3.connect(db_path, timeout=120)
749
- conn.execute("PRAGMA journal_mode=WAL")
750
- conn.execute("PRAGMA synchronous=NORMAL")
751
- conn.execute("CREATE TABLE IF NOT EXISTS fingerprints (exact_hash TEXT PRIMARY KEY, normalized_hash TEXT NOT NULL)")
752
- conn.execute("CREATE INDEX IF NOT EXISTS idx_normalized ON fingerprints(normalized_hash)")
753
- conn.commit()
754
-
755
- # In-memory caches for recently accepted hashes (to reduce SQLite queries/writes)
756
- exact_cache = set()
757
- normalized_cache = set()
758
- pending_hashes = [] # list of (exact_hash, normalized_hash) to be inserted in batch
759
-
760
- records = [] # records to be written to shard
761
- shard_number = int(state.get("shards_uploaded", 0))
762
- last_progress = time.time()
763
-
764
- # Rows seen since the last committed flush point (drives the
765
- # "processed_committed" promotion in flush_shard_and_cache).
766
- rows_since_commit = 0
767
-
768
- def flush_hash_cache():
769
- nonlocal pending_hashes
770
- if not pending_hashes:
771
- return
772
- conn.executemany(
773
- "INSERT OR IGNORE INTO fingerprints (exact_hash, normalized_hash) VALUES (?, ?)",
774
- pending_hashes
775
- )
776
- conn.commit()
777
- pending_hashes = []
778
- exact_cache.clear()
779
- normalized_cache.clear()
780
-
781
- def flush_shard_and_cache():
782
- """Upload whatever records are buffered, flush the hash
783
- cache, and ONLY THEN advance processed_committed to the
784
- current live 'processed' count. This is fix #3: state on
785
- disk always reflects a point where every accepted record up
786
- to it has actually been uploaded, so a crash between flushes
787
- can only cause re-processing of rows already seen (safe,
788
- just re-does some work) rather than silently losing accepted
789
- records (unsafe, data loss)."""
790
- nonlocal records, shard_number, rows_since_commit
791
- if records:
792
- upload_worker_shard(cfg, task_id, shard_number, records)
793
- shard_number += 1
794
- state["shards_uploaded"] = shard_number
795
- records = []
796
- flush_hash_cache()
797
- state["processed_committed"] = state["processed"]
798
- rows_since_commit = 0
799
- save_task_state(dataset_name, task_id, state)
800
-
801
- try:
802
- for row in ds:
803
- state["processed"] += 1
804
- rows_since_commit += 1
805
-
806
- try:
807
- extracted = extract_record(row, cfg)
808
- text = extracted["text"]
809
- except Exception:
810
- state["other_reject"] += 1
811
- continue
812
- if not text:
813
- state["other_reject"] += 1
814
- continue
815
-
816
- # Python file extension filter for certain kinds
817
- path_lower = extracted["path"].lower()
818
- if cfg["kind"] == "realpbt":
819
- source_file = str(row.get("source_file", "")).lower()
820
- if source_file and not source_file.endswith(".py"):
821
- state["quality_reject"] += 1
822
- continue
823
- if path_lower and not path_lower.endswith(".py"):
824
- state["quality_reject"] += 1
825
- continue
826
-
827
- # Generated / vendor filters
828
- if REJECT_GENERATED and row.get("is_generated") is True:
829
- state["quality_reject"] += 1
830
- continue
831
- if REJECT_GENERATED and row.get("autogenerated") is True:
832
- state["quality_reject"] += 1
833
- continue
834
- if REJECT_VENDOR and row.get("is_vendor") is True:
835
- state["quality_reject"] += 1
836
- continue
837
-
838
- good, reason = quality_check(text)
839
- if not good:
840
- state["quality_reject"] += 1
841
- continue
842
-
843
- try:
844
- ehash = exact_hash(text)
845
- nhash = normalized_hash(text)
846
- except Exception:
847
- state["other_reject"] += 1
848
- continue
849
-
850
- # Check duplicates: first in-memory cache, then SQLite
851
- if ehash in exact_cache or nhash in normalized_cache:
852
- state["duplicate_exact"] += 1
853
- continue
854
-
855
- duplicate = conn.execute(
856
- "SELECT exact_hash, normalized_hash FROM fingerprints WHERE exact_hash = ? OR normalized_hash = ? LIMIT 1",
857
- (ehash, nhash)
858
- ).fetchone()
859
- if duplicate is not None:
860
- if duplicate[0] == ehash:
861
- state["duplicate_exact"] += 1
862
- else:
863
- state["duplicate_normalized"] += 1
864
- continue
865
-
866
- # AST validation: any version passes → accept
867
- try:
868
- ast_ok, ast_results = validator.validate(text)
869
- except Exception:
870
- ast_ok = False
871
- ast_results = {}
872
- if not ast_ok:
873
- state["syntax_error"] += 1
874
- continue
875
-
876
- # ACCEPT
877
- record = {
878
- "text": text,
879
- "source_dataset": cfg["dataset"],
880
- "source_pool": dataset_name,
881
- "repo": extracted["repo"],
882
- "path": extracted["path"],
883
- "license": extracted["license"],
884
- "exact_sha256": ehash,
885
- "normalized_sha256": nhash,
886
- "char_count": len(text),
887
- "line_count": len(text.splitlines()),
888
- "ast_validation": {v: r["passed"] for v, r in ast_results.items()},
889
- "python_ast_versions": PYTHON_VERSIONS,
890
- "ast_acceptance_rule": "ANY",
891
- }
892
-
893
- exact_cache.add(ehash)
894
- normalized_cache.add(nhash)
895
- pending_hashes.append((ehash, nhash))
896
-
897
- state["accepted"] += 1
898
- state["bytes_accepted"] += len(text.encode("utf-8", errors="ignore"))
899
- records.append(record)
900
-
901
- # Flush shard when records reach SHARD_ROWS (now 500,000)
902
- if len(records) >= SHARD_ROWS:
903
- flush_shard_and_cache()
904
- print(f"[{dataset_name}] T{task_id} processed={state['processed']:,} | accepted={state['accepted']:,} | syntax={state['syntax_error']:,} | shards={state['shards_uploaded']:,}")
905
-
906
- # Periodic checkpoint. With CHECKPOINT_EVERY == SHARD_ROWS
907
- # this coincides with the shard-flush cadence above in the
908
- # common case; kept as a belt-and-braces check in case
909
- # quality/dup rejects mean many rows pass between accepts.
910
- if state["processed"] % CHECKPOINT_EVERY == 0:
911
- flush_shard_and_cache()
912
-
913
- # Live progress
914
- now = time.time()
915
- if now - last_progress >= 15:
916
- elapsed = max(1, now - state["started"])
917
- rate = state["processed"] / elapsed
918
- print(f"[{dataset_name}] T{task_id} processed={state['processed']:,} | accepted={state['accepted']:,} | syntax={state['syntax_error']:,} | rate={rate:.1f}/sec")
919
- last_progress = now
920
-
921
- # End of stream: flush whatever remains (partial shard is fine)
922
- flush_shard_and_cache()
923
-
924
- conn.commit()
925
- state["complete"] = True
926
- state["finished"] = time.time()
927
- save_task_state(dataset_name, task_id, state)
928
-
929
- completion = {
930
- "dataset": cfg["dataset"],
931
- "dataset_name": dataset_name,
932
- "task_id": task_id,
933
- "total_tasks": total_tasks,
934
- "complete": True,
935
- "processed": state["processed"],
936
- "accepted": state["accepted"],
937
- "duplicate_exact": state["duplicate_exact"],
938
- "duplicate_normalized": state["duplicate_normalized"],
939
- "syntax_error": state["syntax_error"],
940
- "python_ast_versions": PYTHON_VERSIONS,
941
- "ast_acceptance_rule": "ANY",
942
- }
943
- completion_path = STATE_ROOT / dataset_name / f"task_{task_id}_COMPLETE.json"
944
- with open(completion_path, "w") as f:
945
- json.dump(completion, f, indent=2)
946
- upload_file(completion_path, f"{REMOTE_STATE}/{dataset_name}/task_{task_id}_COMPLETE.json")
947
-
948
- print(f"\n[{dataset_name}] TASK {task_id} COMPLETE")
949
- return {**state, "task_id": task_id, "complete": True}
950
-
951
- except Exception as e:
952
- print("\n" + "!" * 80)
953
- print(f"[{dataset_name}] TASK {task_id} FAILED")
954
- print(traceback.format_exc())
955
- try:
956
- # Best-effort: flush whatever is safely flushable. Note we
957
- # deliberately do NOT try to flush `records` here if the
958
- # failure happened mid-shard-write, since we don't know
959
- # its integrity — better to let a resume re-process those
960
- # rows than risk uploading a corrupt/partial shard.
961
- if pending_hashes:
962
- flush_hash_cache()
963
- conn.commit()
964
- save_task_state(dataset_name, task_id, state)
965
- except Exception as checkpoint_error:
966
- print("Checkpoint error:", checkpoint_error)
967
- return {**state, "task_id": task_id, "complete": False, "error": repr(e)}
968
-
969
- finally:
970
- try:
971
- conn.commit()
972
- conn.close()
973
- except Exception:
974
- pass
975
- try:
976
- validator.close()
977
- except Exception:
978
- pass
979
-
980
- # ============================================================
981
- # LOCATE PYTHON INTERPRETERS (installed by uv in Dockerfile)
982
- # ============================================================
983
-
984
- def get_interpreters():
985
- interpreters = {}
986
- for version in PYTHON_VERSIONS:
987
- result = subprocess.run(["uv", "python", "find", version], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
988
- if result.returncode == 0:
989
- path = result.stdout.strip().splitlines()[-1] if result.stdout else None
990
- if path and Path(path).exists():
991
- interpreters[version] = path
992
- continue
993
- major, minor = version.split(".")[0], version.split(".")[1]
994
- check = subprocess.run(["which", f"python{major}.{minor}"], text=True, stdout=subprocess.PIPE)
995
- if check.returncode == 0:
996
- interpreters[version] = check.stdout.strip()
997
- continue
998
- raise RuntimeError(f"Could not find Python {version}")
999
- return interpreters
1000
-
1001
- # ============================================================
1002
- # PIPELINE RUNNER (updates global status)
1003
- # ============================================================
1004
-
1005
- def run_pipeline():
1006
- global pipeline_status
1007
- pipeline_status["started"] = True
1008
- pipeline_status["current_stage"] = "processing"
1009
- pipeline_status["total_tasks"] = 0
1010
- pipeline_status["finished_tasks"] = 0
1011
-
1012
- try:
1013
- interpreters = get_interpreters()
1014
- print("Python interpreters found:")
1015
- for v, p in interpreters.items():
1016
- print(f" {v} -> {p}")
1017
-
1018
- DATASET_TASKS = []
1019
- for cfg in DATASETS:
1020
- ds = load_stream(cfg)
1021
- num_shards = int(getattr(ds, "num_shards", 1) or 1)
1022
- total_tasks = min(MAX_WORKERS, num_shards)
1023
- print(f"[QUEUE] {cfg['name']}: {num_shards:,} underlying shards -> {total_tasks} tasks")
1024
- pipeline_status["total_tasks"] += total_tasks
1025
- for task_id in range(total_tasks):
1026
- DATASET_TASKS.append({
1027
- "cfg": cfg,
1028
- "task_id": task_id,
1029
- "total_tasks": total_tasks,
1030
- "num_shards": num_shards,
1031
- })
1032
-
1033
- print(f"Total scheduled task partitions: {len(DATASET_TASKS):,}")
1034
-
1035
- results = {}
1036
- task_cursor = 0
1037
- active = {}
1038
- with ProcessPoolExecutor(max_workers=MAX_WORKERS) as executor:
1039
- while len(active) < MAX_WORKERS and task_cursor < len(DATASET_TASKS):
1040
- task = DATASET_TASKS[task_cursor]
1041
- task_cursor += 1
1042
- future = executor.submit(process_partition, task["cfg"], task["task_id"], task["total_tasks"], interpreters)
1043
- active[future] = task
1044
- print(f"[SCHEDULER] STARTED {task['cfg']['name']} T{task['task_id']}")
1045
-
1046
- while active:
1047
- for completed_future in as_completed(active.keys()):
1048
- task = active.pop(completed_future)
1049
- try:
1050
- result = completed_future.result()
1051
- except Exception as e:
1052
- result = {"complete": False, "error": repr(e), "task_id": task["task_id"]}
1053
- key = (task["cfg"]["name"], task["task_id"])
1054
- results[key] = result
1055
- pipeline_status["finished_tasks"] += 1
1056
- print(f"\n[SCHEDULER] FINISHED {task['cfg']['name']} T{task['task_id']} complete={result.get('complete', False)}")
1057
-
1058
- if task_cursor < len(DATASET_TASKS):
1059
- next_task = DATASET_TASKS[task_cursor]
1060
- task_cursor += 1
1061
- future = executor.submit(process_partition, next_task["cfg"], next_task["task_id"], next_task["total_tasks"], interpreters)
1062
- active[future] = next_task
1063
- print(f"[SCHEDULER] STARTED {next_task['cfg']['name']} T{next_task['task_id']}")
1064
- break
1065
-
1066
- # ============================================================
1067
- # GLOBAL DEDUP (across all tasks/datasets)
1068
- # ============================================================
1069
- pipeline_status["current_stage"] = "global_dedup"
1070
- print("\n" + "=" * 90)
1071
- print("STARTING GLOBAL CATEGORY 1 DEDUP")
1072
- print("=" * 90)
1073
-
1074
- GLOBAL_DB = FINAL_ROOT / "global_dedup.sqlite"
1075
- gconn = sqlite3.connect(GLOBAL_DB, timeout=120)
1076
- gconn.execute("PRAGMA journal_mode=WAL")
1077
- gconn.execute("PRAGMA synchronous=NORMAL")
1078
- gconn.execute("CREATE TABLE IF NOT EXISTS fingerprints (exact_hash TEXT PRIMARY KEY, normalized_hash TEXT NOT NULL)")
1079
- gconn.execute("CREATE INDEX IF NOT EXISTS idx_global_normalized ON fingerprints(normalized_hash)")
1080
- gconn.commit()
1081
-
1082
- global_stats = {"input_records": 0, "accepted_records": 0, "duplicate_exact": 0, "duplicate_normalized": 0, "invalid_records": 0, "bytes": 0}
1083
- global_records = []
1084
- global_shard_number = 0
1085
-
1086
- pending_global_hashes = []
1087
- BATCH_SIZE = 1000
1088
-
1089
- def flush_global_hashes():
1090
- nonlocal pending_global_hashes
1091
- if not pending_global_hashes:
1092
- return
1093
- gconn.executemany(
1094
- "INSERT OR IGNORE INTO fingerprints (exact_hash, normalized_hash) VALUES (?, ?)",
1095
- pending_global_hashes
1096
- )
1097
- gconn.commit()
1098
- pending_global_hashes = []
1099
-
1100
- def flush_global_records():
1101
- nonlocal global_records, global_shard_number
1102
- if not global_records:
1103
- return
1104
- filename = f"category1-master-{global_shard_number:08d}.jsonl.gz"
1105
- local_path = FINAL_ROOT / filename
1106
- with gzip.open(local_path, "wb") as f:
1107
- for record in global_records:
1108
- f.write(orjson.dumps(record) + b"\n")
1109
- remote_path = f"{REMOTE_FINAL}/{filename}"
1110
- upload_file(local_path, remote_path)
1111
- try:
1112
- local_path.unlink()
1113
- except Exception:
1114
- pass
1115
- global_records = []
1116
- global_shard_number += 1
1117
-
1118
- REMOTE_SHARDS = []
1119
- for task in DATASET_TASKS:
1120
- key = (task["cfg"]["name"], task["task_id"])
1121
- result = results.get(key, {})
1122
- shard_count = int(result.get("shards_uploaded", 0))
1123
- for shard_number in range(shard_count):
1124
- filename = f"task-{task['task_id']:04d}-shard-{shard_number:08d}.jsonl.gz"
1125
- remote_path = f"{REMOTE_DATA}/{task['cfg']['name']}/task_{task['task_id']}/{filename}"
1126
- REMOTE_SHARDS.append((task['cfg']['name'], task['task_id'], shard_number, remote_path))
1127
-
1128
- print(f"Remote worker shards: {len(REMOTE_SHARDS):,}")
1129
-
1130
- for idx, (dataset_name, task_id, shard_number, remote_path) in enumerate(REMOTE_SHARDS, 1):
1131
- print(f"\n[GLOBAL] {idx:,}/{len(REMOTE_SHARDS):,} {dataset_name} T{task_id} S{shard_number}")
1132
- local_path = TMP_ROOT / "global" / dataset_name / f"task_{task_id}" / Path(remote_path).name
1133
-
1134
- # FIX (#1 + #4): download via the real bucket-download path,
1135
- # and if it fails, RAISE rather than silently `continue`.
1136
- # A missing shard here means permanent, silent data loss in
1137
- # the final master dataset if we just skip it — better to
1138
- # stop the whole pipeline and surface the error clearly.
1139
- download_bucket_file(remote_path, local_path, timeout=DOWNLOAD_TIMEOUT)
1140
-
1141
- with gzip.open(local_path, "rb") as f:
1142
- for line in f:
1143
- global_stats["input_records"] += 1
1144
- try:
1145
- record = orjson.loads(line)
1146
- ehash = record["exact_sha256"]
1147
- nhash = record["normalized_sha256"]
1148
- except Exception:
1149
- global_stats["invalid_records"] += 1
1150
- continue
1151
-
1152
- duplicate = gconn.execute(
1153
- "SELECT exact_hash, normalized_hash FROM fingerprints WHERE exact_hash = ? OR normalized_hash = ? LIMIT 1",
1154
- (ehash, nhash)
1155
- ).fetchone()
1156
- if duplicate is not None:
1157
- if duplicate[0] == ehash:
1158
- global_stats["duplicate_exact"] += 1
1159
- else:
1160
- global_stats["duplicate_normalized"] += 1
1161
- continue
1162
-
1163
- pending_global_hashes.append((ehash, nhash))
1164
- global_records.append(record)
1165
- global_stats["accepted_records"] += 1
1166
- global_stats["bytes"] += int(record.get("char_count", 0))
1167
-
1168
- if len(pending_global_hashes) >= BATCH_SIZE:
1169
- flush_global_hashes()
1170
-
1171
- if len(global_records) >= SHARD_ROWS:
1172
- flush_global_records()
1173
-
1174
- if pending_global_hashes:
1175
- flush_global_hashes()
1176
- if len(global_records) >= SHARD_ROWS:
1177
- flush_global_records()
1178
-
1179
- gconn.commit()
1180
- try:
1181
- local_path.unlink()
1182
- except Exception:
1183
- pass
1184
-
1185
- if idx % 10 == 0 or idx == len(REMOTE_SHARDS):
1186
- 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']:,}")
1187
-
1188
- if pending_global_hashes:
1189
- flush_global_hashes()
1190
- flush_global_records()
1191
- gconn.commit()
1192
- gconn.close()
1193
-
1194
- upload_file(GLOBAL_DB, f"{REMOTE_FINAL}/global_dedup.sqlite")
1195
-
1196
- final_metadata = {
1197
- "name": "Category 1 Python Master",
1198
- "pipeline_version": "v4",
1199
- "source_datasets": [cfg["dataset"] for cfg in DATASETS],
1200
- "max_workers": MAX_WORKERS,
1201
- "shard_rows": SHARD_ROWS,
1202
- "python_ast_versions": PYTHON_VERSIONS,
1203
- "ast_acceptance_rule": "ANY",
1204
- "dedup": {"exact_sha256": True, "normalized_sha256": True, "ast_structure_as_key": False},
1205
- "statistics": global_stats,
1206
- "final_shards": global_shard_number,
1207
- "created": time.time(),
1208
- }
1209
- metadata_path = FINAL_ROOT / "dataset_metadata.json"
1210
- with open(metadata_path, "w") as f:
1211
- json.dump(final_metadata, f, indent=2)
1212
- upload_file(metadata_path, f"{REMOTE_FINAL}/dataset_metadata.json")
1213
-
1214
- pipeline_status["stats"] = global_stats
1215
- pipeline_status["stats"]["final_shards"] = global_shard_number
1216
- pipeline_status["completed"] = True
1217
- pipeline_status["current_stage"] = "done"
1218
-
1219
- print("\n" + "=" * 90)
1220
- print("CATEGORY 1 — COMPLETE")
1221
- print("=" * 90)
1222
- print(f"Input records: {global_stats['input_records']:,}")
1223
- print(f"Final accepted: {global_stats['accepted_records']:,}")
1224
- print(f"Global exact duplicates: {global_stats['duplicate_exact']:,}")
1225
- print(f"Global normalized duplicates: {global_stats['duplicate_normalized']:,}")
1226
- print(f"Final master shards: {global_shard_number:,}")
1227
- print("\nAST validation: ANY ONE VERSION PASS = ACCEPT")
1228
- print(f"Master location: hf://buckets/{BUCKET_ID}/{REMOTE_FINAL}/")
1229
- print("=" * 90)
1230
-
1231
- except Exception as e:
1232
- pipeline_status["current_stage"] = "failed"
1233
- pipeline_status["error"] = str(e)
1234
- print("PIPELINE FAILED:", traceback.format_exc())
1235
- raise
1236
-
1237
- # ============================================================
1238
- # FASTAPI APP WITH LIFESPAN
1239
- # ============================================================
1240
-
1241
- @asynccontextmanager
1242
- async def lifespan(app: FastAPI):
1243
- thread = threading.Thread(target=run_pipeline, daemon=False)
1244
- thread.start()
1245
- yield
1246
- if thread.is_alive():
1247
- print("[LIFESPAN] Pipeline is still running, waiting up to 60 seconds for graceful exit...")
1248
- thread.join(timeout=60)
1249
- if thread.is_alive():
1250
- print("[LIFESPAN] Pipeline did not finish within timeout, continuing shutdown.")
1251
-
1252
- app = FastAPI(title="Category1 Pipeline API", lifespan=lifespan)
1253
-
1254
- @app.get("/health")
1255
- async def health():
1256
- return JSONResponse(content={
1257
- "status": pipeline_status["current_stage"],
1258
- "started": pipeline_status["started"],
1259
- "completed": pipeline_status["completed"],
1260
- "total_tasks": pipeline_status["total_tasks"],
1261
- "finished_tasks": pipeline_status["finished_tasks"],
1262
- "stats": pipeline_status["stats"],
1263
- "error": pipeline_status["error"],
1264
- })
1265
-
1266
- @app.get("/status")
1267
- async def status():
1268
- detailed = {}
1269
- for dataset_dir in STATE_ROOT.iterdir():
1270
- if dataset_dir.is_dir():
1271
- dataset_name = dataset_dir.name
1272
- completions = list(dataset_dir.glob("task_*_COMPLETE.json"))
1273
- detailed[dataset_name] = {"completed_tasks": len(completions)}
1274
- for comp_path in completions:
1275
- try:
1276
- with open(comp_path) as f:
1277
- data = json.load(f)
1278
- detailed[dataset_name][comp_path.stem] = data
1279
- except Exception:
1280
- pass
1281
- return JSONResponse(content={
1282
- "pipeline_status": pipeline_status,
1283
- "per_dataset": detailed,
1284
- })
1285
-
1286
- # ============================================================
1287
- # MAIN ENTRY POINT FOR UVICORN
1288
- # ============================================================
1289
-
1290
- if __name__ == "__main__":
1291
- port = int(os.environ.get("PORT", 7860))
1292
- uvicorn.run(app, host="0.0.0.0", port=port)