Spaces:
Paused
Paused
Update app.py
Browse files2 unmodified lines34567891011123 unmodified lines161718192021222324252627282930313233343536373839402 unmodified lines434445464748496 unmodified lines565758596061626364656667686970717273747576777879808182838485869 unmodified lines9697989910010110210310410510610716 unmodified lines1241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691 unmodified line17117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922024 unmodified lines24524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829911 unmodified lines3113123133143153163172 unmodified linesimport timeimport socketimport threadingimport reimport requestsimport pyarrow.parquet as pqimport pyarrow as paimport gcfrom pathlib import Pathfrom huggingface_hub import HfApi3 unmodified linesRAW_DIR = "/data/raw"STATE_FILE = "/data/state.json"WORKER_TIMEOUT = 600MAX_BUFFERED = 50ROWS_PER_CHUNK = 50_000os.makedirs(RAW_DIR, exist_ok=True)api = HfApi(token=HF_TOKEN)AUTH_HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"}# ββ Sources βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Each source: (name, type, urls_or_config)# Types: parquet_list, hf_list# For hf_list: uses HF API to discover filesSOURCES = [{"name" : "fineweb","type" : "hf_list","repo" : "HuggingFaceFW/fineweb-edu","prefix" : "data/CC-MAIN-2025-26","skip" : 0, # already in state from prev run β coordinator skips done ones"take" : 10,"text_col": "text",},2 unmodified lines"type" : "hf_list","repo" : "wikimedia/wikipedia","prefix" : "20231101.en/train-","skip" : 2, # first 2 already done in 50M"take" : 18,"text_col": "text",},6 unmodified lines"take" : 6,"text_col": "text",},{"name" : "phi","type" : "url_list","urls" : ["https://huggingface.co/datasets/open-phi/programming_books_llama/resolve/main/data/train-00000-of-00004-ea05c5cb63b570a8.parquet?download=true","https://huggingface.co/datasets/open-phi/programming_books_llama/resolve/main/data/train-00001-of-00004-d99cbe052bab0d4e.parquet?download=true","https://huggingface.co/datasets/open-phi/programming_books_llama/resolve/main/data/train-00002-of-00004-2c25f0e11d537eaf.parquet?download=true","https://huggingface.co/datasets/open-phi/programming_books_llama/resolve/main/data/train-00003-of-00004-faa8dbb07e5f02e8.parquet?download=true",],"text_col": "markdown",},{"name" : "code","type" : "url_list","urls" : [# 12 new languages Γ 2 shards = 24 files# Base: https://huggingface.co/datasets/Neon-tech/Dataset-arranger/resolve/main/by-language*[f"https://huggingface.co/datasets/Neon-tech/Dataset-arranger/resolve/main/by-language/{lang}/shard_{str(i).zfill(6)}.jsonl?download=true"for lang in ["C", "C++", "Java", "Go", "Rust", "Ruby", "PHP", "SQL", "C#", "Scala", "Lua", "Perl"]for i in range(2)],],"text_col": "text","fmt" : "jsonl",},]9 unmodified linesconn.send(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK")conn.close()# ββ Friendly name βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef friendly_name(source_name, url_or_path):# Strip query stringbase = url_or_path.split("?")[0].split("/")[-1]return f"{source_name}__{base}"# ββ State βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef load_state():if os.path.exists(STATE_FILE):16 unmodified linesjson.dump(state, f, indent=2)os.replace(tmp, STATE_FILE)# ββ Discover all sources ββββββββββββββββββββββββββββββββββββββββββββββββββββββdef discover_all(state):known = {v["url"] for v in state["shards"].values()} | {e["url"] for e in state.get("queue", [])}new_count = 0for src in SOURCES:name = src["name"]print(f"\nDiscovering: {name}")if src["type"] == "hf_list":files = list(api.list_repo_files(src["repo"], repo_type="dataset"))files = [f for f in files if f.startswith(src["prefix"]) and f.endswith(".parquet")]files = sorted(files)files = files[src["skip"]: src["skip"] + src["take"]]base = f"https://huggingface.co/datasets/{src['repo']}/resolve/main/"urls = [base + f for f in files]fmt = "parquet"else:urls = src["urls"]fmt = src.get("fmt", "parquet")for url in urls:if url not in known:state["queue"].append({"url" : url,"source" : name,"text_col" : src["text_col"],"fmt" : fmt,})known.add(url)new_count += 1print(f" {name}: {len(urls)} files | {new_count} new queued")save_state(state)print(f"\nTotal queued: {len(state['queue'])} | In state: {len(state['shards'])}")# ββ Reclaim stale βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef reclaim_stale(state):now = time.time()for name, info in state["shards"].items():if info["status"] == "claimed" and info.get("claimed_at"):if now - info["claimed_at"] > WORKER_TIMEOUT:1 unmodified lineinfo["status"] = "pending"info["worker"] = Noneinfo["claimed_at"] = Nonesave_state(state)# ββ Split parquet into chunks βββββββββββββββββββββββββββββββββββββββββββββββββdef split_parquet(src_path, name, text_col):pf = pq.ParquetFile(src_path)chunk_paths = []chunk_idx = 0current = []for batch in pf.iter_batches(batch_size=10_000, columns=[text_col]):current.append(batch)if sum(len(b) for b in current) >= ROWS_PER_CHUNK:chunk_name = name.replace(".parquet", f"_chunk{chunk_idx:03d}.parquet")chunk_path = Path(RAW_DIR) / chunk_nametable = pa.Table.from_batches(current)pq.write_table(table, chunk_path)print(f" β {chunk_name} ({len(table):,} rows)")chunk_paths.append((chunk_name, text_col, "parquet"))chunk_idx += 1current = []del table; gc.collect()if current:chunk_name = name.replace(".parquet", f"_chunk{chunk_idx:03d}.parquet")chunk_path = Path(RAW_DIR) / chunk_nametable = pa.Table.from_batches(current)pq.write_table(table, chunk_path)print(f" β {chunk_name} ({len(table):,} rows)")chunk_paths.append((chunk_name, text_col, "parquet"))del table; gc.collect()return chunk_pathsdef copy_jsonl(src_path, name):"""JSONL files are small enough to use directly β just copy to raw dir."""import shutildst = Path(RAW_DIR) / nameshutil.copy2(src_path, dst)return [(name, "text", "jsonl")]# ββ Download loop βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef download_loop(state):while True:# Reload statetry:with open(STATE_FILE) as f:fresh = json.load(f)24 unmodified linessource = entry["source"]text_col = entry["text_col"]fmt = entry.get("fmt", "parquet")ext = ".jsonl" if fmt == "jsonl" else ".parquet"name = friendly_name(source, url)if not name.endswith(ext):name = name.split(".")[0] + extraw_path = Path(RAW_DIR) / nametmp_path = Path(RAW_DIR) / f"{name}.tmp"print(f" Downloading: {source} | {url.split('/')[-1].split('?')[0]}")try:resp = requests.get(url, headers=AUTH_HEADERS, timeout=300, stream=True)resp.raise_for_status()with open(tmp_path, "wb") as f:for chunk in resp.iter_content(chunk_size=8 * 1024 * 1024):f.write(chunk)tmp_path.rename(raw_path)except Exception as e:print(f" β Download failed: {e} β retrying in 30s")tmp_path.unlink(missing_ok=True)time.sleep(30)continueprint(f" Processing: {name}")try:if fmt == "parquet":chunks = split_parquet(raw_path, name, text_col)else:chunks = copy_jsonl(raw_path, name)except Exception as e:print(f" β Processing failed: {e}")raw_path.unlink(missing_ok=True)time.sleep(30)continueraw_path.unlink(missing_ok=True)state["queue"].pop(0)for chunk_name, col, chunk_fmt in chunks:state["shards"][chunk_name] = {"status" : "pending","url" : url,"source" : source,"text_col" : col,"fmt" : chunk_fmt,"worker" : None,"claimed_at": None,"error" : None,}save_state(state)print(f" β {len(chunks)} chunks ready from {name}")time.sleep(3)# ββ Monitor βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ11 unmodified linestotal = len(shards) + len(queue)pct = (done / total * 100) if total else 0# Per-source breakdownsrc_done = {}for v in shards.values():src = v.get("source", "?")2 unmodified lines3456789103 unmodified lines14151617181920212223242526272829303132332 unmodified lines363738394041426 unmodified lines495051525354555657585960616263649 unmodified lines74757677787916 unmodified lines969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451 unmodified line14714814915015115215315415515615715815916016116216316416516616716816917017117217317417524 unmodified lines20020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925011 unmodified lines2622632642652662672 unmodified linesimport timeimport socketimport threadingimport requestsimport pyarrow.parquet as pqimport gcfrom pathlib import Pathfrom huggingface_hub import HfApi3 unmodified linesRAW_DIR = "/data/raw"STATE_FILE = "/data/state.json"WORKER_TIMEOUT = 600MAX_BUFFERED = 999999os.makedirs(RAW_DIR, exist_ok=True)api = HfApi(token=HF_TOKEN)AUTH_HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"}# ββ Sources βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββSOURCES = [{"name" : "fineweb","type" : "hf_list","repo" : "HuggingFaceFW/fineweb-edu","prefix" : "data/CC-MAIN-2025-26","skip" : 5,"take" : 10,"text_col": "text",},2 unmodified lines"type" : "hf_list","repo" : "wikimedia/wikipedia","prefix" : "20231101.en/train-","skip" : 2,"take" : 18,"text_col": "text",},6 unmodified lines"take" : 6,"text_col": "text",},{"name" : "code","type" : "url_list","text_col": "text","fmt" : "jsonl","urls" : [f"https://huggingface.co/datasets/Neon-tech/Dataset-arranger/resolve/main/by-language/{lang}/shard_{str(i).zfill(6)}.jsonl?download=true"for lang in ["C", "C++", "Java", "Go", "Rust", "Ruby", "PHP", "SQL", "C#", "Scala", "Lua", "Perl"]for i in range(2)],},]9 unmodified linesconn.send(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK")conn.close()# ββ State βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef load_state():if os.path.exists(STATE_FILE):16 unmodified linesjson.dump(state, f, indent=2)os.replace(tmp, STATE_FILE)# ββ Discover ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef discover_all(state):known_urls = {v["url"] for v in state["shards"].values()} | {e["url"] for e in state.get("queue", [])}new_count = 0for src in SOURCES:name = src["name"]print(f"\nDiscovering: {name}")if src["type"] == "hf_list":all_files = sorted([f for f in api.list_repo_files(src["repo"], repo_type="dataset")if f.startswith(src["prefix"]) and f.endswith(".parquet")])selected = all_files[src["skip"]: src["skip"] + src["take"]]base_url = f"https://huggingface.co/datasets/{src['repo']}/resolve/main/"urls = [base_url + f for f in selected]fmt = "parquet"else:urls = src["urls"]fmt = src.get("fmt", "parquet")added = 0for url in urls:if url not in known_urls:state["queue"].append({"url" : url,"source" : name,"text_col" : src["text_col"],"fmt" : fmt,})known_urls.add(url)new_count += 1added += 1print(f" {name}: {len(urls)} files | {added} new added to queue")save_state(state)print(f"\nTotal queued: {len(state['queue'])} | In state: {len(state['shards'])}")# ββ Reclaim stale βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef reclaim_stale(state):now = time.time()reclaimed = 0for name, info in state["shards"].items():if info["status"] == "claimed" and info.get("claimed_at"):if now - info["claimed_at"] > WORKER_TIMEOUT:1 unmodified lineinfo["status"] = "pending"info["worker"] = Noneinfo["claimed_at"] = Nonereclaimed += 1if reclaimed:save_state(state)# ββ Parquet β JSONL βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef parquet_to_jsonl(parquet_path, jsonl_path, text_col):"""Stream parquet batch by batch β write one JSON line per doc. No full load."""pf = pq.ParquetFile(parquet_path)n_written = 0with open(jsonl_path, "w", encoding="utf-8") as out:for batch in pf.iter_batches(batch_size=1_000, columns=[text_col]):texts = batch.column(text_col).to_pylist()for text in texts:if text and isinstance(text, str) and text.strip():out.write(json.dumps({"text": text.strip()}, ensure_ascii=False) + "\n")n_written += 1del textsgc.collect()return n_written# ββ Download loop βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef download_loop(state):while True:try:with open(STATE_FILE) as f:fresh = json.load(f)24 unmodified linessource = entry["source"]text_col = entry["text_col"]fmt = entry.get("fmt", "parquet")base_name = url.split("?")[0].split("/")[-1].replace(".parquet", "").replace(".jsonl", "")shard_name = f"{source}__{base_name}.jsonl"jsonl_path = Path(RAW_DIR) / shard_nametmp_path = Path(RAW_DIR) / f"{shard_name}.tmp"print(f" Downloading: {source} | {base_name}")try:resp = requests.get(url, headers=AUTH_HEADERS, timeout=300, stream=True)resp.raise_for_status()with open(tmp_path, "wb") as f:for chunk in resp.iter_content(chunk_size=8 * 1024 * 1024):f.write(chunk)except Exception as e:print(f" β Download failed: {e} β retrying in 30s")tmp_path.unlink(missing_ok=True)time.sleep(30)continueif fmt == "parquet":print(f" Converting β jsonl: {shard_name}")try:n = parquet_to_jsonl(tmp_path, jsonl_path, text_col)tmp_path.unlink(missing_ok=True)print(f" β {n:,} docs")except Exception as e:print(f" β Convert failed: {e}")tmp_path.unlink(missing_ok=True)jsonl_path.unlink(missing_ok=True)time.sleep(30)continueelse:tmp_path.rename(jsonl_path)state["queue"].pop(0)state["shards"][shard_name] = {"status" : "pending","url" : url,"source" : source,"worker" : None,"claimed_at": None,"error" : None,}save_state(state)print(f" β Ready: {shard_name}")time.sleep(3)# ββ Monitor βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ11 unmodified linestotal = len(shards) + len(queue)pct = (done / total * 100) if total else 0src_done = {}for v in shards.values():src = v.get("source", "?")
app.py+74-124