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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Auto-upload v2: Fast polling + batched uploads.
|
| 3 |
+
- Polls every 30s to catch chunks before crawlers delete them
|
| 4 |
+
- Moves completed chunks to staging dir immediately
|
| 5 |
+
- Combines staged files and uploads when total >= 500MB
|
| 6 |
+
"""
|
| 7 |
+
import os, time, glob, shutil, gzip, json
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
|
| 10 |
+
HF_TOKEN = 'HF_TOKEN_REDACTED'
|
| 11 |
+
REPO = 'OpenTransformer/web-crawl-2026'
|
| 12 |
+
STAGING = '/workspace/staging'
|
| 13 |
+
STALE_SECS = 120 # 2 min no modification = finished
|
| 14 |
+
POLL_SECS = 30 # check every 30s
|
| 15 |
+
UPLOAD_THRESHOLD = 1024 * 1024 * 1024 # 1GB before uploading batch
|
| 16 |
+
|
| 17 |
+
DIRS = {
|
| 18 |
+
'/workspace/scraped_data/': 'python',
|
| 19 |
+
'/workspace/scraped_data_go/': 'go',
|
| 20 |
+
'/workspace/scraped_data_rust/': 'rust',
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
os.makedirs(STAGING, exist_ok=True)
|
| 24 |
+
|
| 25 |
+
def log(msg):
|
| 26 |
+
print(f'{datetime.utcnow().isoformat()} {msg}', flush=True)
|
| 27 |
+
|
| 28 |
+
def staging_size():
|
| 29 |
+
total = 0
|
| 30 |
+
for f in glob.glob(os.path.join(STAGING, '*.jsonl.gz')):
|
| 31 |
+
total += os.path.getsize(f)
|
| 32 |
+
return total
|
| 33 |
+
|
| 34 |
+
def stage_completed_chunks():
|
| 35 |
+
"""Move completed (stale) chunks to staging dir."""
|
| 36 |
+
now = time.time()
|
| 37 |
+
moved = 0
|
| 38 |
+
for local_dir, crawler_name in DIRS.items():
|
| 39 |
+
if not os.path.isdir(local_dir):
|
| 40 |
+
continue
|
| 41 |
+
for f in glob.glob(os.path.join(local_dir, '*.jsonl.gz')):
|
| 42 |
+
size = os.path.getsize(f)
|
| 43 |
+
mtime = os.path.getmtime(f)
|
| 44 |
+
age = now - mtime
|
| 45 |
+
size_mb = size / (1024*1024)
|
| 46 |
+
|
| 47 |
+
if size < 1024 * 1024: # skip < 1MB (just started)
|
| 48 |
+
continue
|
| 49 |
+
if age < STALE_SECS: # still being written
|
| 50 |
+
continue
|
| 51 |
+
|
| 52 |
+
# Move to staging
|
| 53 |
+
dest = os.path.join(STAGING, f'{crawler_name}_{os.path.basename(f)}')
|
| 54 |
+
try:
|
| 55 |
+
shutil.move(f, dest)
|
| 56 |
+
log(f'Staged {os.path.basename(f)} ({size_mb:.0f}MB) -> {os.path.basename(dest)}')
|
| 57 |
+
moved += 1
|
| 58 |
+
except Exception as e:
|
| 59 |
+
log(f'ERROR staging {f}: {e}')
|
| 60 |
+
return moved
|
| 61 |
+
|
| 62 |
+
def combine_and_upload():
|
| 63 |
+
"""Combine staged files into one big file and upload to HF."""
|
| 64 |
+
files = sorted(glob.glob(os.path.join(STAGING, '*.jsonl.gz')))
|
| 65 |
+
if not files:
|
| 66 |
+
return False
|
| 67 |
+
|
| 68 |
+
total = sum(os.path.getsize(f) for f in files)
|
| 69 |
+
total_mb = total / (1024*1024)
|
| 70 |
+
|
| 71 |
+
if total < UPLOAD_THRESHOLD:
|
| 72 |
+
log(f'Staging has {total_mb:.0f}MB ({len(files)} files), waiting for {UPLOAD_THRESHOLD//(1024*1024)}MB threshold')
|
| 73 |
+
return False
|
| 74 |
+
|
| 75 |
+
# Create combined file with timestamp
|
| 76 |
+
ts = datetime.utcnow().strftime('%Y%m%d_%H%M%S')
|
| 77 |
+
combined_path = f'/workspace/combined_crawl_{ts}.jsonl.gz'
|
| 78 |
+
|
| 79 |
+
log(f'Combining {len(files)} files ({total_mb:.0f}MB) into {os.path.basename(combined_path)}')
|
| 80 |
+
|
| 81 |
+
with gzip.open(combined_path, 'wb') as out_f:
|
| 82 |
+
for f in files:
|
| 83 |
+
with gzip.open(f, 'rb') as in_f:
|
| 84 |
+
while True:
|
| 85 |
+
chunk = in_f.read(8 * 1024 * 1024) # 8MB chunks
|
| 86 |
+
if not chunk:
|
| 87 |
+
break
|
| 88 |
+
out_f.write(chunk)
|
| 89 |
+
|
| 90 |
+
combined_size = os.path.getsize(combined_path) / (1024*1024)
|
| 91 |
+
log(f'Combined file: {combined_size:.0f}MB')
|
| 92 |
+
|
| 93 |
+
# Upload to HF
|
| 94 |
+
try:
|
| 95 |
+
from huggingface_hub import HfApi
|
| 96 |
+
api = HfApi(token=HF_TOKEN)
|
| 97 |
+
hf_path = f'crawl/combined/crawl_batch_{ts}.jsonl.gz'
|
| 98 |
+
log(f'Uploading {combined_size:.0f}MB -> {hf_path}')
|
| 99 |
+
api.upload_file(
|
| 100 |
+
path_or_fileobj=combined_path,
|
| 101 |
+
path_in_repo=hf_path,
|
| 102 |
+
repo_id=REPO,
|
| 103 |
+
repo_type='dataset',
|
| 104 |
+
commit_message=f'Add crawl batch {ts} ({combined_size:.0f}MB, {len(files)} chunks)',
|
| 105 |
+
)
|
| 106 |
+
log(f'Upload complete: {hf_path}')
|
| 107 |
+
|
| 108 |
+
# Clean up staged files and combined file
|
| 109 |
+
for f in files:
|
| 110 |
+
os.remove(f)
|
| 111 |
+
os.remove(combined_path)
|
| 112 |
+
log(f'Cleaned up {len(files)} staged files + combined file')
|
| 113 |
+
return True
|
| 114 |
+
except Exception as e:
|
| 115 |
+
log(f'ERROR uploading: {e}')
|
| 116 |
+
# Keep files for retry
|
| 117 |
+
if os.path.exists(combined_path):
|
| 118 |
+
os.remove(combined_path) # remove combined but keep staged
|
| 119 |
+
return False
|
| 120 |
+
|
| 121 |
+
def also_upload_large_singles():
|
| 122 |
+
"""Also directly upload any single chunk that's already >= 500MB."""
|
| 123 |
+
now = time.time()
|
| 124 |
+
for local_dir, crawler_name in DIRS.items():
|
| 125 |
+
if not os.path.isdir(local_dir):
|
| 126 |
+
continue
|
| 127 |
+
for f in glob.glob(os.path.join(local_dir, '*.jsonl.gz')):
|
| 128 |
+
size = os.path.getsize(f)
|
| 129 |
+
mtime = os.path.getmtime(f)
|
| 130 |
+
age = now - mtime
|
| 131 |
+
if size >= UPLOAD_THRESHOLD and age >= STALE_SECS:
|
| 132 |
+
size_mb = size / (1024*1024)
|
| 133 |
+
ts = datetime.utcnow().strftime('%Y%m%d_%H%M%S')
|
| 134 |
+
try:
|
| 135 |
+
from huggingface_hub import HfApi
|
| 136 |
+
api = HfApi(token=HF_TOKEN)
|
| 137 |
+
hf_path = f'crawl/{crawler_name}/{os.path.basename(f)}'
|
| 138 |
+
log(f'Direct upload {os.path.basename(f)} ({size_mb:.0f}MB) -> {hf_path}')
|
| 139 |
+
api.upload_file(
|
| 140 |
+
path_or_fileobj=f,
|
| 141 |
+
path_in_repo=hf_path,
|
| 142 |
+
repo_id=REPO,
|
| 143 |
+
repo_type='dataset',
|
| 144 |
+
commit_message=f'Add {crawler_name} chunk ({size_mb:.0f}MB)',
|
| 145 |
+
)
|
| 146 |
+
log(f'Upload complete: {hf_path}')
|
| 147 |
+
os.remove(f)
|
| 148 |
+
log(f'Deleted local: {f}')
|
| 149 |
+
except Exception as e:
|
| 150 |
+
log(f'ERROR direct upload {f}: {e}')
|
| 151 |
+
|
| 152 |
+
if __name__ == '__main__':
|
| 153 |
+
log('Auto-upload v2 started (30s poll, 1GB batch threshold)')
|
| 154 |
+
while True:
|
| 155 |
+
try:
|
| 156 |
+
moved = stage_completed_chunks()
|
| 157 |
+
if moved > 0:
|
| 158 |
+
log(f'Staged {moved} chunks, staging total: {staging_size()/(1024*1024):.0f}MB')
|
| 159 |
+
|
| 160 |
+
also_upload_large_singles()
|
| 161 |
+
combine_and_upload()
|
| 162 |
+
except Exception as e:
|
| 163 |
+
log(f'ERROR in cycle: {e}')
|
| 164 |
+
time.sleep(POLL_SECS)
|