Spaces:
Sleeping

PERDYPTO commited on
Commit
9df25ec
·
verified ·
1 Parent(s): 094c244

Update pipeline.py

Browse files
Files changed (1) hide show
  1. pipeline.py +181 -223
pipeline.py CHANGED
@@ -1,35 +1,22 @@
1
-
2
  #!/usr/bin/env python3
3
  # ============================================================
4
  # PIPELINE_API.PY — FULL CONTINUED PRETRAINING DATASET PIPELINE
5
  # WITH FASTAPI HEALTH & STATUS ENDPOINTS
6
  # MASTER‑WORKER ARCHITECTURE
7
  # ============================================================
8
- # This script runs on a Hugging Face Space with persistent storage
9
- # mounted at /data. It processes the dataset list below,
10
- # validates every Python file with 4 real CPython interpreters,
11
- # removes duplicates globally, and produces a master dataset.
12
- #
13
- # All state and output is stored in the bucket PERDYPTO/private.
14
- #
15
- # The FastAPI server starts automatically and exposes:
16
- # /health -> current pipeline status + aggregated stats
17
- # /status -> more detailed per‑task progress
18
- # ============================================================
19
 
20
- import osasdfsdf
21
  import sys
22
  import json
23
  import time
24
  import gzip
25
  import shutil
26
  import hashlib
27
- import sqlite3
28
  import subprocess
29
  import traceback
30
  import multiprocessing as mp
31
- import requests
32
  import threading
 
33
  from pathlib import Path
34
  from concurrent.futures import ProcessPoolExecutor, as_completed
35
  from typing import List, Dict, Any, Optional, Tuple
@@ -38,7 +25,7 @@ import orjson
38
  from datasets import load_dataset
39
  from huggingface_hub import batch_bucket_files
40
 
41
- from fastapi import FastAPI, BackgroundTasks
42
  from fastapi.responses import JSONResponse
43
  import uvicorn
44
 
@@ -51,8 +38,9 @@ LOCAL_ROOT = DATA_ROOT / "category1_pipeline_v4"
51
  STATE_ROOT = LOCAL_ROOT / "state"
52
  TMP_ROOT = LOCAL_ROOT / "tmp"
53
  FINAL_ROOT = LOCAL_ROOT / "final"
 
54
 
55
- for directory in [STATE_ROOT, TMP_ROOT, FINAL_ROOT]:
56
  directory.mkdir(parents=True, exist_ok=True)
57
 
58
  BUCKET_ID = "PERDYPTO/private"
@@ -60,7 +48,7 @@ HF_TOKEN = os.environ.get("HF_TOKEN")
60
  if not HF_TOKEN:
61
  raise RuntimeError("HF_TOKEN environment variable not set.")
62
 
63
- # Python versions for AST validation
64
  PYTHON_VERSIONS = [
65
  "3.11.9",
66
  "3.12.10",
@@ -69,10 +57,8 @@ PYTHON_VERSIONS = [
69
  ]
70
  AST_ACCEPT_MODE = "ANY" # any one version passes
71
 
72
- # Parallelism – adjust based on Space resources
73
- MAX_WORKERS = 4 # more workers for faster processing
74
  SHARD_ROWS = 5_000 # records per output file
75
- CHECKPOINT_EVERY = 5_000 # not used in master‑worker (we use in‑memory)
76
 
77
  # Quality filters
78
  MIN_CHARS = 100
@@ -91,9 +77,6 @@ REMOTE_FINAL = f"{REMOTE_ROOT}/final"
91
  # ============================================================
92
  # DATASET LIST – CATEGORY 1 (SOURCE CODE ONLY)
93
  # ============================================================
94
- # REMOVED "shallow" / problematic datasets (redstone_code_python,
95
- # github_python, codeparrot_raw, mbpp). Add them back if needed.
96
- # ============================================================
97
 
98
  DATASETS = [
99
  {
@@ -188,6 +171,7 @@ DATASETS = [
188
  }
189
  ]
190
 
 
191
  # ============================================================
192
  # GLOBAL STATE FOR API
193
  # ============================================================
@@ -221,7 +205,7 @@ def retry(fn, label, retries=5):
221
  return fn()
222
  except Exception as e:
223
  last_error = e
224
- print(f"[RETRY] {label} {attempt}/{retries}: {e}")
225
  if attempt < retries:
226
  time.sleep(min(30, 2 ** attempt))
227
  raise last_error
@@ -283,24 +267,28 @@ def quality_check(text):
283
  return False, "binary_like"
284
  return True, "ok"
285
 
286
- def ast_check_with_versions(code: str) -> Tuple[bool, str]:
287
- """Run AST parsing with each Python version; returns (passed, details)."""
288
- # Find interpreter paths (assume they are installed and in PATH)
289
- # We'll use the versions from the environment (they should be set in Dockerfile)
290
- import glob
291
- base = "/root/.local/share/uv/python"
292
  interpreters = {}
 
293
  for v in PYTHON_VERSIONS:
294
  pattern = f"{base}/cpython-{v}*/bin/python*"
295
  matches = glob.glob(pattern)
296
  if matches:
297
  interpreters[v] = matches[0]
298
  else:
299
- print(f"Warning: Python {v} not found")
 
300
  if not interpreters:
301
- return False, "no_interpreters_found"
 
 
 
 
302
 
303
- # Try each interpreter; accept if any succeeds (AST_ACCEPT_MODE == "ANY")
 
 
304
  for ver, py_path in interpreters.items():
305
  cmd = [py_path, "-c", f"import ast; ast.parse({repr(code)})"]
306
  try:
@@ -317,35 +305,25 @@ def ast_check_with_versions(code: str) -> Tuple[bool, str]:
317
  def worker_process_task(task: Dict[str, Any]) -> Dict[str, Any]:
318
  """
319
  Process a single partition of a dataset.
320
- Returns a dict with:
321
- - accepted: list of records {text, exact_hash, normalized_hash, metadata}
322
- - rejected: list of records {text, reason, metadata}
323
- - stats: counts
324
  """
325
  ds_info = task["ds_info"]
326
- partition_start = task.get("start", 0)
327
- partition_end = task.get("end", None) # None means until exhaustion
328
  dataset_name = ds_info["name"]
329
 
330
- # Determine columns to load (avoid schema mismatch)
331
- all_fields = set()
332
- all_fields.update(ds_info.get("text_fields", []))
333
- all_fields.update(ds_info.get("repo_fields", []))
334
- all_fields.update(ds_info.get("path_fields", []))
335
- all_fields.update(ds_info.get("license_fields", []))
336
-
337
  # Build load_kwargs
338
  load_kwargs = {
339
  "path": ds_info["dataset"],
340
  "split": ds_info["split"],
341
  "streaming": True,
 
 
 
342
  }
343
  if ds_info.get("config"):
344
  load_kwargs["name"] = ds_info["config"]
345
  if ds_info.get("data_dir"):
346
  load_kwargs["data_dir"] = ds_info["data_dir"]
347
 
348
- # Load dataset
349
  try:
350
  ds = load_dataset(**load_kwargs)
351
  except Exception as e:
@@ -356,9 +334,10 @@ def worker_process_task(task: Dict[str, Any]) -> Dict[str, Any]:
356
  "stats": {"input": 0, "accepted": 0, "rejected": 0}
357
  }
358
 
359
- # Optional: select only needed columns (if we know them)
360
- # Not all datasets allow column selection; we'll try to filter later.
361
- # We'll iterate rows and extract text from any of the text_fields.
 
362
 
363
  accepted = []
364
  rejected = []
@@ -366,23 +345,20 @@ def worker_process_task(task: Dict[str, Any]) -> Dict[str, Any]:
366
  accepted_count = 0
367
  rejected_count = 0
368
 
369
- # Determine text field to use
370
- text_fields = ds_info.get("text_fields", [])
371
- repo_fields = ds_info.get("repo_fields", [])
372
- path_fields = ds_info.get("path_fields", [])
373
- license_fields = ds_info.get("license_fields", [])
374
 
375
- # We'll iterate rows
376
- # To resume from checkpoint, we need to skip rows until partition_start
377
  row_idx = 0
378
  for row in ds:
379
- if partition_end is not None and row_idx >= partition_end:
380
  break
381
- if row_idx < partition_start:
382
  row_idx += 1
383
  continue
384
 
385
  input_count += 1
 
386
  # Extract text
387
  text = None
388
  for field in text_fields:
@@ -395,7 +371,7 @@ def worker_process_task(task: Dict[str, Any]) -> Dict[str, Any]:
395
  row_idx += 1
396
  continue
397
 
398
- # Quality check
399
  ok, reason = quality_check(text)
400
  if not ok:
401
  rejected.append({"text": text, "reason": reason, "metadata": {}})
@@ -403,7 +379,7 @@ def worker_process_task(task: Dict[str, Any]) -> Dict[str, Any]:
403
  row_idx += 1
404
  continue
405
 
406
- # AST check
407
  ast_ok, ast_reason = ast_check_with_versions(text)
408
  if not ast_ok:
409
  rejected.append({"text": text, "reason": ast_reason, "metadata": {}})
@@ -411,11 +387,11 @@ def worker_process_task(task: Dict[str, Any]) -> Dict[str, Any]:
411
  row_idx += 1
412
  continue
413
 
414
- # Compute hashes
415
  ehash = exact_hash(text)
416
  nhash = normalized_hash(text)
417
 
418
- # Build metadata (repo, path, license)
419
  metadata = {}
420
  for field in repo_fields:
421
  if field in row:
@@ -451,7 +427,7 @@ def worker_process_task(task: Dict[str, Any]) -> Dict[str, Any]:
451
  }
452
 
453
  # ============================================================
454
- # MASTER PROCESSING FUNCTION (runs in main thread)
455
  # ============================================================
456
 
457
  def run_pipeline():
@@ -460,173 +436,155 @@ def run_pipeline():
460
  pipeline_status["current_stage"] = "processing"
461
  pipeline_status["error"] = None
462
 
463
- # We'll process datasets one by one, but we can parallelize within each dataset.
464
- # For each dataset, we'll divide into tasks (partitions) and submit to workers.
465
- # After all datasets, we do final global dedup (already done on the fly).
466
 
467
- # In-memory sets for global dedup
468
  global_exact_hashes = set()
469
  global_norm_hashes = set()
470
 
471
- # Stats aggregation
472
  total_input = 0
473
  total_accepted = 0
474
  total_rejected = 0
475
  total_duplicate_exact = 0
476
  total_duplicate_norm = 0
477
 
478
- # We'll write output per dataset
 
479
  for ds_info in DATASETS:
480
- ds_name = ds_info["name"]
481
- ds_output_root = FINAL_ROOT / ds_name
482
- verified_dir = ds_output_root / "verified"
483
- rejected_dir = ds_output_root / "rejected"
484
- verified_dir.mkdir(parents=True, exist_ok=True)
485
- rejected_dir.mkdir(parents=True, exist_ok=True)
486
-
487
- tasks = []
488
- for ds_info in DATASETS:
489
- # We can optionally split into multiple tasks by shard ranges if we know shard count.
490
- # For now, one task per dataset.
491
- tasks.append({
492
- "ds_info": ds_info,
493
- "start": 0,
494
- "end": None, # process all
495
- })
496
-
497
- pipeline_status["total_tasks"] = len(tasks)
498
-
499
- # Use ProcessPoolExecutor
500
- with ProcessPoolExecutor(max_workers=MAX_WORKERS) as executor:
501
- future_to_task = {executor.submit(worker_process_task, task): task for task in tasks}
502
-
503
- for future in as_completed(future_to_task):
504
- task = future_to_task[future]
505
- ds_name = task["ds_info"]["name"]
506
- try:
507
- result = future.result(timeout=3600) # 1 hour timeout
508
- except Exception as e:
509
- print(f"[ERROR] Task for {ds_name} failed with exception: {e}")
510
- traceback.print_exc()
511
- pipeline_status["error"] = f"Task for {ds_name} failed: {e}"
512
- continue
513
 
514
- if result.get("error"):
515
- print(f"[ERROR] Task for {ds_name} returned error: {result['error']}")
516
- pipeline_status["error"] = result["error"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
517
  continue
518
-
519
- accepted = result.get("accepted", [])
520
- rejected = result.get("rejected", [])
521
- stats = result.get("stats", {})
522
-
523
- # Update stats
524
- total_input += stats.get("input", 0)
525
- total_accepted += stats.get("accepted", 0)
526
- total_rejected += stats.get("rejected", 0)
527
-
528
- # Deduplicate accepted records globally
529
- # For each accepted record, check if hash already seen
530
- unique_accepted = []
531
- for rec in accepted:
532
- ehash = rec["exact_hash"]
533
- nhash = rec["normalized_hash"]
534
- if ehash in global_exact_hashes:
535
- total_duplicate_exact += 1
536
- # Move to rejected with reason
537
- rejected.append({
538
- "text": rec["text"],
539
- "reason": "duplicate_exact",
540
- "metadata": rec["metadata"],
541
- })
542
- total_rejected += 1
543
- continue
544
- if nhash in global_norm_hashes:
545
- total_duplicate_norm += 1
546
- rejected.append({
547
- "text": rec["text"],
548
- "reason": "duplicate_normalized",
549
- "metadata": rec["metadata"],
550
- })
551
- total_rejected += 1
552
- continue
553
- # New record
554
- global_exact_hashes.add(ehash)
555
- global_norm_hashes.add(nhash)
556
- unique_accepted.append(rec)
557
- total_accepted += 1 # we already counted but we'll recount
558
-
559
- # Now write accepted and rejected for this dataset
560
- ds_output_root = FINAL_ROOT / ds_name
561
- verified_dir = ds_output_root / "verified"
562
- rejected_dir = ds_output_root / "rejected"
563
-
564
- # Write accepted shards
565
- accepted_shard_count = 0
566
- accepted_batch = []
567
- for rec in unique_accepted:
568
- accepted_batch.append(rec)
569
- if len(accepted_batch) >= SHARD_ROWS:
570
- # write shard
571
- shard_path = verified_dir / f"shard-{accepted_shard_count:05d}.jsonl.gz"
572
- with gzip.open(shard_path, "wt", encoding="utf-8") as f:
573
- for item in accepted_batch:
574
- f.write(orjson.dumps(item).decode("utf-8") + "\n")
575
- accepted_shard_count += 1
576
- accepted_batch = []
577
- if accepted_batch:
578
  shard_path = verified_dir / f"shard-{accepted_shard_count:05d}.jsonl.gz"
579
  with gzip.open(shard_path, "wt", encoding="utf-8") as f:
580
- for item in accepted_batch:
581
  f.write(orjson.dumps(item).decode("utf-8") + "\n")
582
  accepted_shard_count += 1
583
-
584
- # Write rejected shards
585
- rejected_shard_count = 0
586
- rejected_batch = []
587
- for rec in rejected:
588
- rejected_batch.append(rec)
589
- if len(rejected_batch) >= SHARD_ROWS:
590
- shard_path = rejected_dir / f"rejected-{rejected_shard_count:05d}.jsonl.gz"
591
- with gzip.open(shard_path, "wt", encoding="utf-8") as f:
592
- for item in rejected_batch:
593
- f.write(orjson.dumps(item).decode("utf-8") + "\n")
594
- rejected_shard_count += 1
595
- rejected_batch = []
596
- if rejected_batch:
597
  shard_path = rejected_dir / f"rejected-{rejected_shard_count:05d}.jsonl.gz"
598
  with gzip.open(shard_path, "wt", encoding="utf-8") as f:
599
- for item in rejected_batch:
600
  f.write(orjson.dumps(item).decode("utf-8") + "\n")
601
  rejected_shard_count += 1
602
-
603
- # Write metadata.json for this dataset
604
- metadata = {
605
- "dataset_name": ds_name,
606
- "total_input": stats.get("input", 0),
607
- "accepted": len(unique_accepted),
608
- "rejected": len(rejected),
609
- "duplicate_exact": total_duplicate_exact,
610
- "duplicate_normalized": total_duplicate_norm,
611
- "accepted_shards": accepted_shard_count,
612
- "rejected_shards": rejected_shard_count,
613
- }
614
- with open(ds_output_root / "metadata.json", "w") as f:
615
- json.dump(metadata, f, indent=2)
616
-
617
- print(f"[{ds_name}] processed: input={stats.get('input',0)}, "
618
- f"accepted={len(unique_accepted)}, rejected={len(rejected)}")
619
-
620
- # After all datasets, update global stats
621
- pipeline_status["stats"]["input_records"] = total_input
622
- pipeline_status["stats"]["accepted_records"] = total_accepted
623
- pipeline_status["stats"]["invalid_records"] = total_rejected
624
- pipeline_status["stats"]["duplicate_exact"] = total_duplicate_exact
625
- pipeline_status["stats"]["duplicate_normalized"] = total_duplicate_norm
626
-
627
- # Final status
628
- pipeline_status["completed"] = True
629
- pipeline_status["current_stage"] = "done"
 
 
 
 
 
 
 
630
 
631
  # ============================================================
632
  # FASTAPI APP
@@ -634,19 +592,17 @@ def run_pipeline():
634
 
635
  app = FastAPI()
636
 
 
 
 
 
 
 
637
  @app.on_event("startup")
638
  def startup_event():
639
- # Start pipeline in background
640
- def bg():
641
- try:
642
- run_pipeline()
643
- except Exception as e:
644
- pipeline_status["error"] = str(e)
645
- pipeline_status["current_stage"] = "failed"
646
- print(f"Pipeline failed: {e}")
647
- traceback.print_exc()
648
- thread = threading.Thread(target=bg, daemon=True)
649
- thread.start()
650
 
651
  @app.get("/health")
652
  def health():
@@ -675,4 +631,6 @@ def status():
675
  # ============================================================
676
 
677
  if __name__ == "__main__":
678
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
 
 
 
1
  #!/usr/bin/env python3
2
  # ============================================================
3
  # PIPELINE_API.PY — FULL CONTINUED PRETRAINING DATASET PIPELINE
4
  # WITH FASTAPI HEALTH & STATUS ENDPOINTS
5
  # MASTER‑WORKER ARCHITECTURE
6
  # ============================================================
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ import os
9
  import sys
10
  import json
11
  import time
12
  import gzip
13
  import shutil
14
  import hashlib
 
15
  import subprocess
16
  import traceback
17
  import multiprocessing as mp
 
18
  import threading
19
+ import glob
20
  from pathlib import Path
21
  from concurrent.futures import ProcessPoolExecutor, as_completed
22
  from typing import List, Dict, Any, Optional, Tuple
 
25
  from datasets import load_dataset
26
  from huggingface_hub import batch_bucket_files
27
 
28
+ from fastapi import FastAPI
29
  from fastapi.responses import JSONResponse
30
  import uvicorn
31
 
 
38
  STATE_ROOT = LOCAL_ROOT / "state"
39
  TMP_ROOT = LOCAL_ROOT / "tmp"
40
  FINAL_ROOT = LOCAL_ROOT / "final"
41
+ CACHE_ROOT = DATA_ROOT / "cache" # cache for datasets
42
 
43
+ for directory in [STATE_ROOT, TMP_ROOT, FINAL_ROOT, CACHE_ROOT]:
44
  directory.mkdir(parents=True, exist_ok=True)
45
 
46
  BUCKET_ID = "PERDYPTO/private"
 
48
  if not HF_TOKEN:
49
  raise RuntimeError("HF_TOKEN environment variable not set.")
50
 
51
+ # Python versions for AST validation – fallback to system Python if not found
52
  PYTHON_VERSIONS = [
53
  "3.11.9",
54
  "3.12.10",
 
57
  ]
58
  AST_ACCEPT_MODE = "ANY" # any one version passes
59
 
60
+ MAX_WORKERS = 4 # number of worker processes
 
61
  SHARD_ROWS = 5_000 # records per output file
 
62
 
63
  # Quality filters
64
  MIN_CHARS = 100
 
77
  # ============================================================
78
  # DATASET LIST – CATEGORY 1 (SOURCE CODE ONLY)
79
  # ============================================================
 
 
 
80
 
81
  DATASETS = [
82
  {
 
171
  }
172
  ]
173
 
174
+
175
  # ============================================================
176
  # GLOBAL STATE FOR API
177
  # ============================================================
 
205
  return fn()
206
  except Exception as e:
207
  last_error = e
208
+ print(f"[RETRY] {label} {attempt}/{retries}: {e}", flush=True)
209
  if attempt < retries:
210
  time.sleep(min(30, 2 ** attempt))
211
  raise last_error
 
267
  return False, "binary_like"
268
  return True, "ok"
269
 
270
+ def get_interpreters():
271
+ """Find Python interpreters. Fallback to system python if needed."""
 
 
 
 
272
  interpreters = {}
273
+ base = "/root/.local/share/uv/python"
274
  for v in PYTHON_VERSIONS:
275
  pattern = f"{base}/cpython-{v}*/bin/python*"
276
  matches = glob.glob(pattern)
277
  if matches:
278
  interpreters[v] = matches[0]
279
  else:
280
+ print(f"Warning: Python {v} not found in {base}", flush=True)
281
+ # If none found, use system python
282
  if not interpreters:
283
+ import sys
284
+ system_python = sys.executable
285
+ interpreters["system"] = system_python
286
+ print(f"Using system Python: {system_python}", flush=True)
287
+ return interpreters
288
 
289
+ def ast_check_with_versions(code: str) -> Tuple[bool, str]:
290
+ """Run AST parsing with each Python version; accepts if any passes."""
291
+ interpreters = get_interpreters()
292
  for ver, py_path in interpreters.items():
293
  cmd = [py_path, "-c", f"import ast; ast.parse({repr(code)})"]
294
  try:
 
305
  def worker_process_task(task: Dict[str, Any]) -> Dict[str, Any]:
306
  """
307
  Process a single partition of a dataset.
308
+ Returns a dict with accepted, rejected lists and stats.
 
 
 
309
  """
310
  ds_info = task["ds_info"]
 
 
311
  dataset_name = ds_info["name"]
312
 
 
 
 
 
 
 
 
313
  # Build load_kwargs
314
  load_kwargs = {
315
  "path": ds_info["dataset"],
316
  "split": ds_info["split"],
317
  "streaming": True,
318
+ "trust_remote_code": True,
319
+ "cache_dir": str(CACHE_ROOT),
320
+ "token": HF_TOKEN, # pass token for authentication
321
  }
322
  if ds_info.get("config"):
323
  load_kwargs["name"] = ds_info["config"]
324
  if ds_info.get("data_dir"):
325
  load_kwargs["data_dir"] = ds_info["data_dir"]
326
 
 
327
  try:
328
  ds = load_dataset(**load_kwargs)
329
  except Exception as e:
 
334
  "stats": {"input": 0, "accepted": 0, "rejected": 0}
335
  }
336
 
337
+ text_fields = ds_info.get("text_fields", [])
338
+ repo_fields = ds_info.get("repo_fields", [])
339
+ path_fields = ds_info.get("path_fields", [])
340
+ license_fields = ds_info.get("license_fields", [])
341
 
342
  accepted = []
343
  rejected = []
 
345
  accepted_count = 0
346
  rejected_count = 0
347
 
348
+ # Optionally resume from a checkpoint (if task has start index)
349
+ start_idx = task.get("start", 0)
350
+ end_idx = task.get("end", None)
 
 
351
 
 
 
352
  row_idx = 0
353
  for row in ds:
354
+ if end_idx is not None and row_idx >= end_idx:
355
  break
356
+ if row_idx < start_idx:
357
  row_idx += 1
358
  continue
359
 
360
  input_count += 1
361
+
362
  # Extract text
363
  text = None
364
  for field in text_fields:
 
371
  row_idx += 1
372
  continue
373
 
374
+ # Quality
375
  ok, reason = quality_check(text)
376
  if not ok:
377
  rejected.append({"text": text, "reason": reason, "metadata": {}})
 
379
  row_idx += 1
380
  continue
381
 
382
+ # AST
383
  ast_ok, ast_reason = ast_check_with_versions(text)
384
  if not ast_ok:
385
  rejected.append({"text": text, "reason": ast_reason, "metadata": {}})
 
387
  row_idx += 1
388
  continue
389
 
390
+ # Hashes
391
  ehash = exact_hash(text)
392
  nhash = normalized_hash(text)
393
 
394
+ # Metadata
395
  metadata = {}
396
  for field in repo_fields:
397
  if field in row:
 
427
  }
428
 
429
  # ============================================================
430
+ # MASTER PROCESSING FUNCTION (runs in a separate process)
431
  # ============================================================
432
 
433
  def run_pipeline():
 
436
  pipeline_status["current_stage"] = "processing"
437
  pipeline_status["error"] = None
438
 
439
+ print("=== PIPELINE STARTED ===", flush=True)
 
 
440
 
441
+ # In-memory dedup sets
442
  global_exact_hashes = set()
443
  global_norm_hashes = set()
444
 
 
445
  total_input = 0
446
  total_accepted = 0
447
  total_rejected = 0
448
  total_duplicate_exact = 0
449
  total_duplicate_norm = 0
450
 
451
+ # Prepare tasks: one per dataset (can split large datasets later)
452
+ tasks = []
453
  for ds_info in DATASETS:
454
+ tasks.append({
455
+ "ds_info": ds_info,
456
+ "start": 0,
457
+ "end": None,
458
+ })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
459
 
460
+ pipeline_status["total_tasks"] = len(tasks)
461
+
462
+ with ProcessPoolExecutor(max_workers=MAX_WORKERS) as executor:
463
+ future_to_task = {executor.submit(worker_process_task, task): task for task in tasks}
464
+
465
+ for future in as_completed(future_to_task):
466
+ task = future_to_task[future]
467
+ ds_name = task["ds_info"]["name"]
468
+ try:
469
+ result = future.result(timeout=3600)
470
+ except Exception as e:
471
+ print(f"[ERROR] Task for {ds_name} failed: {e}", flush=True)
472
+ traceback.print_exc()
473
+ pipeline_status["error"] = str(e)
474
+ continue
475
+
476
+ if result.get("error"):
477
+ print(f"[ERROR] Task for {ds_name} returned error: {result['error']}", flush=True)
478
+ pipeline_status["error"] = result["error"]
479
+ continue
480
+
481
+ accepted = result.get("accepted", [])
482
+ rejected = result.get("rejected", [])
483
+ stats = result.get("stats", {})
484
+
485
+ total_input += stats.get("input", 0)
486
+ total_rejected += stats.get("rejected", 0)
487
+
488
+ # Deduplicate accepted records globally
489
+ unique_accepted = []
490
+ for rec in accepted:
491
+ ehash = rec["exact_hash"]
492
+ nhash = rec["normalized_hash"]
493
+ if ehash in global_exact_hashes:
494
+ total_duplicate_exact += 1
495
+ rejected.append({
496
+ "text": rec["text"],
497
+ "reason": "duplicate_exact",
498
+ "metadata": rec["metadata"],
499
+ })
500
+ total_rejected += 1
501
  continue
502
+ if nhash in global_norm_hashes:
503
+ total_duplicate_norm += 1
504
+ rejected.append({
505
+ "text": rec["text"],
506
+ "reason": "duplicate_normalized",
507
+ "metadata": rec["metadata"],
508
+ })
509
+ total_rejected += 1
510
+ continue
511
+ global_exact_hashes.add(ehash)
512
+ global_norm_hashes.add(nhash)
513
+ unique_accepted.append(rec)
514
+ total_accepted += 1
515
+
516
+ # Write shards for this dataset
517
+ ds_output_root = FINAL_ROOT / ds_name
518
+ verified_dir = ds_output_root / "verified"
519
+ rejected_dir = ds_output_root / "rejected"
520
+ verified_dir.mkdir(parents=True, exist_ok=True)
521
+ rejected_dir.mkdir(parents=True, exist_ok=True)
522
+
523
+ # Write accepted
524
+ accepted_shard_count = 0
525
+ batch = []
526
+ for rec in unique_accepted:
527
+ batch.append(rec)
528
+ if len(batch) >= SHARD_ROWS:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
529
  shard_path = verified_dir / f"shard-{accepted_shard_count:05d}.jsonl.gz"
530
  with gzip.open(shard_path, "wt", encoding="utf-8") as f:
531
+ for item in batch:
532
  f.write(orjson.dumps(item).decode("utf-8") + "\n")
533
  accepted_shard_count += 1
534
+ batch = []
535
+ if batch:
536
+ shard_path = verified_dir / f"shard-{accepted_shard_count:05d}.jsonl.gz"
537
+ with gzip.open(shard_path, "wt", encoding="utf-8") as f:
538
+ for item in batch:
539
+ f.write(orjson.dumps(item).decode("utf-8") + "\n")
540
+ accepted_shard_count += 1
541
+
542
+ # Write rejected
543
+ rejected_shard_count = 0
544
+ batch = []
545
+ for rec in rejected:
546
+ batch.append(rec)
547
+ if len(batch) >= SHARD_ROWS:
548
  shard_path = rejected_dir / f"rejected-{rejected_shard_count:05d}.jsonl.gz"
549
  with gzip.open(shard_path, "wt", encoding="utf-8") as f:
550
+ for item in batch:
551
  f.write(orjson.dumps(item).decode("utf-8") + "\n")
552
  rejected_shard_count += 1
553
+ batch = []
554
+ if batch:
555
+ shard_path = rejected_dir / f"rejected-{rejected_shard_count:05d}.jsonl.gz"
556
+ with gzip.open(shard_path, "wt", encoding="utf-8") as f:
557
+ for item in batch:
558
+ f.write(orjson.dumps(item).decode("utf-8") + "\n")
559
+ rejected_shard_count += 1
560
+
561
+ # Metadata
562
+ metadata = {
563
+ "dataset_name": ds_name,
564
+ "total_input": stats.get("input", 0),
565
+ "accepted": len(unique_accepted),
566
+ "rejected": len(rejected),
567
+ "duplicate_exact": total_duplicate_exact,
568
+ "duplicate_normalized": total_duplicate_norm,
569
+ "accepted_shards": accepted_shard_count,
570
+ "rejected_shards": rejected_shard_count,
571
+ }
572
+ with open(ds_output_root / "metadata.json", "w") as f:
573
+ json.dump(metadata, f, indent=2)
574
+
575
+ print(f"[{ds_name}] processed: input={stats.get('input',0)}, "
576
+ f"accepted={len(unique_accepted)}, rejected={len(rejected)}", flush=True)
577
+
578
+ # Update global stats
579
+ pipeline_status["stats"]["input_records"] = total_input
580
+ pipeline_status["stats"]["accepted_records"] = total_accepted
581
+ pipeline_status["stats"]["invalid_records"] = total_rejected
582
+ pipeline_status["stats"]["duplicate_exact"] = total_duplicate_exact
583
+ pipeline_status["stats"]["duplicate_normalized"] = total_duplicate_norm
584
+ pipeline_status["completed"] = True
585
+ pipeline_status["current_stage"] = "done"
586
+
587
+ print("=== PIPELINE COMPLETED ===", flush=True)
588
 
589
  # ============================================================
590
  # FASTAPI APP
 
592
 
593
  app = FastAPI()
594
 
595
+ # Start pipeline in a separate process (not thread) so logs are visible
596
+ def start_pipeline_process():
597
+ p = mp.Process(target=run_pipeline, daemon=True)
598
+ p.start()
599
+ return p
600
+
601
  @app.on_event("startup")
602
  def startup_event():
603
+ global pipeline_process
604
+ print("Starting pipeline in background process...", flush=True)
605
+ pipeline_process = start_pipeline_process()
 
 
 
 
 
 
 
 
606
 
607
  @app.get("/health")
608
  def health():
 
631
  # ============================================================
632
 
633
  if __name__ == "__main__":
634
+ # For multiprocessing on some platforms, need to set start method
635
+ mp.set_start_method("spawn", force=True)
636
+ uvicorn.run(app, host="0.0.0.0", port=7860, log_level="info")