ddd / format_detector.py
ai557's picture
Upload 4 files
f8e648b verified
"""
format_detector.py
==================
Auto-detects:
- File format (parquet, tar/webdataset, zip, arrow, jsonl, image folder)
- Image field (image, img, jpeg, png, pixel_values, …)
- Caption field (caption, text, prompt, label, description, …)
Used by ingest_universal.py β€” import and call detect().
"""
import os
import io
import json
import tarfile
import zipfile
import struct
from pathlib import Path
from typing import Optional
from PIL import Image
# ── Known field names ─────────────────────────────────────────────────────────
IMAGE_FIELDS = ["image", "img", "jpeg", "png", "gif", "webp",
"pixel_values", "image_bytes", "image_data",
"bytes", "data", "photo", "thumbnail"]
CAPTION_FIELDS = ["caption", "text", "prompt", "label", "description",
"title", "alt", "alt_text", "sentence", "query",
"blip_caption", "llava_caption", "cogvlm_caption",
"tag", "tags", "keyword", "keywords"]
# ── Format signatures ─────────────────────────────────────────────────────────
MAGIC = {
b"\x50\x4b\x03\x04": "zip",
b"\x1f\x8b": "tar.gz",
b"PAR1": "parquet",
b"\x41\x52\x52\x4f": "arrow", # ARROW1
}
def sniff_bytes(path: str) -> Optional[str]:
with open(path, "rb") as f:
header = f.read(8)
for magic, fmt in MAGIC.items():
if header[:len(magic)] == magic:
return fmt
# Bare tar (no gzip)
if tarfile.is_tarfile(path):
return "tar"
return None
# ── Per-format sample readers ─────────────────────────────────────────────────
def _sample_parquet(path: str) -> dict:
import pyarrow.parquet as pq
tbl = pq.read_table(path, memory_map=True).slice(0, 1)
row = {col: tbl.column(col)[0].as_py() for col in tbl.schema.names}
return row
def _sample_arrow(path: str) -> dict:
import pyarrow as pa
with pa.memory_map(path, "r") as src:
reader = pa.ipc.open_file(src)
batch = reader.get_batch(0)
row = {col: batch.column(col)[0].as_py() for col in batch.schema.names}
return row
def _sample_tar(path: str) -> dict:
"""
WebDataset tars group files by key:
000000.jpg 000000.txt 000000.json …
We read enough members to reconstruct one sample dict.
"""
sample = {}
current_key = None
with tarfile.open(path, "r:*") as tf:
for member in tf:
if member.isdir():
continue
stem, ext = os.path.splitext(os.path.basename(member.name))
ext = ext.lstrip(".").lower()
if current_key is None:
current_key = stem
if stem != current_key:
break # moved to next sample
fobj = tf.extractfile(member)
if fobj is None:
continue
raw = fobj.read()
if ext in ("jpg", "jpeg", "png", "gif", "webp", "bmp"):
sample["__image_bytes__"] = raw
sample["image"] = Image.open(io.BytesIO(raw))
elif ext in ("txt",):
sample["caption"] = raw.decode("utf-8", errors="replace").strip()
elif ext in ("json",):
try:
d = json.loads(raw)
sample.update(d)
except Exception:
pass
else:
sample[ext] = raw
return sample
def _sample_zip(path: str) -> dict:
sample = {}
with zipfile.ZipFile(path) as zf:
names = zf.namelist()
# Find first image file
for name in names:
ext = Path(name).suffix.lower().lstrip(".")
if ext in ("jpg", "jpeg", "png", "gif", "webp"):
raw = zf.read(name)
sample["image"] = Image.open(io.BytesIO(raw))
# Look for sibling caption file
stem = Path(name).stem
for cap_ext in ("txt", "caption"):
cap_name = f"{stem}.{cap_ext}"
if cap_name in names:
sample["caption"] = zf.read(cap_name).decode("utf-8", errors="replace").strip()
# Also check for a metadata JSON
for json_name in (f"{stem}.json", "metadata.json", "captions.json"):
if json_name in names:
try:
d = json.loads(zf.read(json_name))
sample.update(d)
except Exception:
pass
break
return sample
def _sample_jsonl(path: str) -> dict:
with open(path) as f:
line = f.readline()
return json.loads(line)
def _sample_image_folder(path: str) -> dict:
"""path is a directory; find first image + sibling txt."""
for root, _, files in os.walk(path):
for fname in sorted(files):
ext = Path(fname).suffix.lower().lstrip(".")
if ext in ("jpg", "jpeg", "png", "gif", "webp"):
img_path = os.path.join(root, fname)
sample = {"image": Image.open(img_path)}
txt = os.path.join(root, Path(fname).stem + ".txt")
if os.path.exists(txt):
sample["caption"] = open(txt).read().strip()
return sample
return {}
# ── Field detection ───────────────────────────────────────────────────────────
def _is_image_value(v) -> bool:
if isinstance(v, Image.Image):
return True
if isinstance(v, bytes):
try:
Image.open(io.BytesIO(v))
return True
except Exception:
return False
if isinstance(v, dict) and "bytes" in v:
return _is_image_value(v["bytes"])
return False
def detect_fields(sample: dict) -> tuple[Optional[str], Optional[str]]:
"""Return (image_field, caption_field) from a sample dict."""
image_field = None
caption_field = None
# Priority: known names first, then any field whose value looks like an image
for name in IMAGE_FIELDS:
if name in sample and _is_image_value(sample[name]):
image_field = name
break
if image_field is None:
for k, v in sample.items():
if _is_image_value(v):
image_field = k
break
for name in CAPTION_FIELDS:
if name in sample and isinstance(sample[name], str):
caption_field = name
break
if caption_field is None:
for k, v in sample.items():
if k != image_field and isinstance(v, str) and len(v) > 1:
caption_field = k
break
return image_field, caption_field
# ── Main entry ────────────────────────────────────────────────────────────────
class DatasetInfo:
def __init__(self, fmt, image_field, caption_field, sample):
self.fmt = fmt # "parquet" | "tar" | "zip" | "arrow" | "jsonl" | "folder" | "hf_streaming"
self.image_field = image_field
self.caption_field = caption_field
self.sample = sample
def __repr__(self):
return (f"DatasetInfo(fmt={self.fmt!r}, "
f"image_field={self.image_field!r}, "
f"caption_field={self.caption_field!r})")
def detect(path: str) -> DatasetInfo:
"""
Detect format + fields for a single file or directory.
Returns a DatasetInfo object.
"""
if os.path.isdir(path):
fmt = "folder"
sample = _sample_image_folder(path)
else:
ext = Path(path).suffix.lower()
sniffed = sniff_bytes(path)
fmt = sniffed or ext.lstrip(".")
if fmt == "parquet":
sample = _sample_parquet(path)
elif fmt in ("tar", "tar.gz"):
sample = _sample_tar(path)
elif fmt == "zip":
sample = _sample_zip(path)
elif fmt == "arrow":
sample = _sample_arrow(path)
elif ext in (".jsonl", ".json"):
fmt = "jsonl"
sample = _sample_jsonl(path)
else:
# Unknown β€” try HF datasets as last resort
fmt = "hf_streaming"
sample = {}
img_f, cap_f = detect_fields(sample)
return DatasetInfo(fmt, img_f, cap_f, sample)
if __name__ == "__main__":
import sys
if len(sys.argv) < 2:
print("Usage: python format_detector.py <file_or_dir>")
sys.exit(1)
info = detect(sys.argv[1])
print(info)
print(f" Fields in sample: {list(info.sample.keys())}")