File size: 9,176 Bytes
f8e648b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
"""
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())}")