"""Per dataset id: meta/info.json, task strings, v2.x per-episode lengths. Metadata only. Resumable. usage: fetch.py OUT_DIR/sample_ids.txt OUT_DIR/meta.jsonl Appends one JSON line per id to the output file (created if missing); ids already in it with a result are skipped on a rerun. Ids that are not plain public repository ids (namespace/name) are recorded as errors without a request. Requests go only to huggingface.co and Hugging Face file storage (see hub.py); size limits per file are in LIMIT. Pace: one request every GAP seconds across all P threads (defaults 0.15 s, 8 threads); a 429 reply backs off. Episode lengths (v2): the "length" of the first 5,000 lines of meta/episodes.jsonl, so a dataset with more episodes, or with lines missing, has fewer lengths than its total_episodes. v3 task strings: no parquet library is used. The printable runs of 4 or more characters in meta/tasks.parquet are taken, schema and pandas words and base64 blobs are dropped, and fragments contained in a longer one are merged. The 8 longest fragments that remain are kept. This is a heuristic: a compressed file can split or drop a task string.""" import json, os, re, sys, time, urllib.error from concurrent.futures import ThreadPoolExecutor sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import hub LIMIT = {"info.json": 1 << 20, "tasks.jsonl": 4 << 20, "episodes.jsonl": 32 << 20, "tasks.parquet": 4 << 20} SKIP = re.compile(r'^(schema|task_index|task|pandas|ARROW:schema|parquet-cpp.*|__index_level_0__)$') import threading _lock = threading.Lock(); _last = [0.0]; N429 = [0] GAP = float(os.environ.get("GAP", "0.15")) # seconds between requests, all threads (about 6-7 a second) def get(url, limit, tries=6): for a in range(tries): with _lock: w = _last[0] + GAP - time.time() if w > 0: time.sleep(w) _last[0] = time.time() try: return hub.get(url, limit)[0] except (hub.OffOrigin, hub.TooLarge, hub.TooManyRedirects): raise except urllib.error.HTTPError as e: if e.code in (401, 403, 404): return None # missing, private or gated: not public if e.code == 429: N429[0] += 1; time.sleep(20 * (a + 1)); continue time.sleep(3 * (a + 1)) except Exception: time.sleep(3 * (a + 1)) raise RuntimeError("failed " + url) def parquet_tasks(b): """Task strings from a small tasks.parquet: printable runs, minus schema words, JSON and base64 blobs.""" out = [] for s in re.findall(rb'[\x20-\x7e]{4,}', b): s = s.decode() s = re.sub(r'^[^A-Za-z0-9]{1,3}', '', s).strip() if len(s) < 4 or SKIP.match(s) or 'parquet-cpp' in s or 'pandas_type' in s or 'index_columns' in s or '"name"' in s: continue if re.fullmatch(r'[A-Za-z0-9+/=]{24,}', s) or s == 'PAR1' or s.endswith('%'): continue # base64 ARROW:schema blob out.append(s) # keep strings not contained in a longer kept one (snappy fragments) out = sorted(set(out), key=len, reverse=True) keep = [] for s in out: if not any(s in k for k in keep): keep.append(s) if len(keep) == 8: break return keep def one(i): base = f"https://huggingface.co/datasets/{i}/resolve/main/meta/" r = {"id": i} if not hub.valid_repo_id(i): r["err"] = "invalid id"; return r try: b = get(base + "info.json", LIMIT["info.json"]) if b is None: r["err"] = "no info.json"; return r d = json.loads(b) r.update(robot=d.get("robot_type"), eps=d.get("total_episodes"), frames=d.get("total_frames"), fps=d.get("fps"), v=d.get("codebase_version")) if str(r["v"]).startswith("v2"): t = get(base + "tasks.jsonl", LIMIT["tasks.jsonl"]) r["tasks"] = [json.loads(l).get("task", "")[:200] for l in (t or b"").decode(errors="replace").splitlines() if l.strip()][:8] e = get(base + "episodes.jsonl", LIMIT["episodes.jsonl"]) if e is not None: r["lens"] = [json.loads(l).get("length") for l in e.decode(errors="replace").splitlines() if l.strip()][:5000] else: t = get(base + "tasks.parquet", LIMIT["tasks.parquet"]) r["tasks"] = [s[:200] for s in parquet_tasks(t)] if t else [] except Exception as ex: r["err"] = repr(ex)[:120] return r if len(sys.argv) < 3: sys.exit(__doc__) ids = [l.strip() for l in open(sys.argv[1]) if l.strip()] done = set() if os.path.exists(sys.argv[2]): for l in open(sys.argv[2]): try: x = json.loads(l) if "err" not in x or x["err"] == "no info.json": done.add(x["id"]) except Exception: pass todo = [i for i in ids if i not in done] print("todo", len(todo), "done", len(done), flush=True) t0 = time.time(); n = 0 with ThreadPoolExecutor(int(os.environ.get("P", "8"))) as ex, open(sys.argv[2], "a") as f: for r in ex.map(one, todo): f.write(json.dumps(r) + "\n"); f.flush(); n += 1 if n % 250 == 0: print(n, round(time.time() - t0), "429s", N429[0], flush=True) print("DONE", n, round(time.time() - t0), "429s", N429[0])