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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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
"""
DataView — General-purpose dataset visualizer for HuggingFace-style files.
Supports: Parquet, Arrow, CSV, JSON/JSONL.
Run:  python tools/dataview/server.py [--port 8080] [--dir /path/to/datasets]
"""

import argparse
import io
import json
import os
import uuid
from pathlib import Path
from typing import Any

import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
from fastapi import FastAPI, HTTPException, Query
from fastapi.responses import HTMLResponse, Response
from fastapi.staticfiles import StaticFiles
from PIL import Image

app = FastAPI(title="DataView")

STATIC_DIR = Path(__file__).parent / "static"
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")

DEFAULT_DIR = str(Path(__file__).parent.parent.parent)

# ---------------------------------------------------------------------------
# In-memory store of opened files
# ---------------------------------------------------------------------------
_store: dict[str, dict] = {}  # file_id -> metadata

SUPPORTED_EXTS = {".parquet", ".pq", ".arrow", ".feather", ".csv", ".tsv", ".json", ".jsonl"}


def _detect_format(path: str) -> str:
    p = path.lower()
    if p.endswith(".parquet") or p.endswith(".pq"):
        return "parquet"
    if p.endswith(".arrow") or p.endswith(".feather"):
        return "arrow"
    if p.endswith(".csv") or p.endswith(".tsv"):
        return "csv"
    if p.endswith(".jsonl") or p.endswith(".json"):
        return "jsonl" if ".jsonl" in p else "json"
    return "unknown"


def _read_parquet_schema(path: str) -> dict:
    pf = pq.ParquetFile(path)
    schema = pf.schema_arrow
    meta = pf.metadata
    return {
        "format": "parquet",
        "num_rows": meta.num_rows,
        "num_row_groups": meta.num_row_groups,
        "file_size_bytes": os.path.getsize(path),
        "columns": [
            {
                "name": field.name,
                "type": str(field.type),
                "is_image": str(field.type) in ("binary", "large_binary"),
                "nullable": field.nullable,
            }
            for field in schema
        ],
    }


def _read_arrow_schema(path: str) -> dict:
    table = pa.ipc.open_file(path).read_all()
    return {
        "format": "arrow",
        "num_rows": table.num_rows,
        "columns": [
            {
                "name": field.name,
                "type": str(field.type),
                "is_image": str(field.type) in ("binary", "large_binary"),
                "nullable": field.nullable,
            }
            for field in table.schema
        ],
    }


def _read_csv_schema(path: str) -> dict:
    df = pd.read_csv(path, nrows=0)
    return {
        "format": "csv",
        "num_rows": sum(1 for _ in open(path)) - 1,
        "columns": [
            {
                "name": col,
                "type": str(dtype),
                "is_image": False,
                "nullable": True,
            }
            for col, dtype in df.dtypes.items()
        ],
    }


def _read_json_schema(path: str) -> dict:
    with open(path) as f:
        first_line = f.readline().strip()
    if first_line.startswith("["):
        rows = json.loads(open(path).read())
        num_rows = len(rows)
        sample = rows[0] if rows else {}
    else:
        num_rows = sum(1 for _ in open(path))
        sample = json.loads(first_line) if first_line else {}
    return {
        "format": "json",
        "num_rows": num_rows,
        "columns": [
            {
                "name": k,
                "type": type(v).__name__,
                "is_image": isinstance(v, bytes),
                "nullable": v is None,
            }
            for k, v in sample.items()
        ],
    }


# ---------------------------------------------------------------------------
# Routes
# ---------------------------------------------------------------------------
@app.get("/", response_class=HTMLResponse)
async def index():
    return (STATIC_DIR / "index.html").read_text()


@app.get("/api/browse")
async def browse(path: str = Query(""), show_hidden: bool = Query(False)):
    """List directory contents for the folder browser."""
    if not path:
        path = DEFAULT_DIR
    path = os.path.expanduser(path)

    if not os.path.isdir(path):
        raise HTTPException(400, f"Not a directory: {path}")

    entries = []
    try:
        for name in sorted(os.listdir(path)):
            if not show_hidden and name.startswith("."):
                continue
            full = os.path.join(path, name)
            is_dir = os.path.isdir(full)
            ext = os.path.splitext(name)[1].lower() if not is_dir else ""
            size = 0
            if not is_dir:
                try:
                    size = os.path.getsize(full)
                except OSError:
                    pass
            entries.append({
                "name": name,
                "path": full,
                "is_dir": is_dir,
                "ext": ext,
                "is_dataset": ext in SUPPORTED_EXTS,
                "size": size,
            })

        # Sort: dirs first, then dataset files, then others
        def sort_key(e):
            if e["is_dir"]:
                return (0, e["name"].lower())
            if e["is_dataset"]:
                return (1, e["name"].lower())
            return (2, e["name"].lower())

        entries.sort(key=sort_key)
    except PermissionError:
        raise HTTPException(403, f"Permission denied: {path}")

    return {
        "path": path,
        "parent": os.path.dirname(path) if path != "/" else None,
        "entries": entries,
    }


@app.get("/api/default-path")
async def default_path():
    return {"path": DEFAULT_DIR}


@app.post("/api/open")
async def open_file(body: dict):
    path = body.get("path", "").strip()
    if not path:
        raise HTTPException(400, "path is required")
    path = os.path.expanduser(path)
    if not os.path.isfile(path):
        raise HTTPException(404, f"File not found: {path}")

    fmt = _detect_format(path)
    try:
        if fmt == "parquet":
            info = _read_parquet_schema(path)
        elif fmt == "arrow":
            info = _read_arrow_schema(path)
        elif fmt == "csv":
            info = _read_csv_schema(path)
        elif fmt in ("json", "jsonl"):
            info = _read_json_schema(path)
        else:
            raise HTTPException(400, f"Unsupported format: {fmt}")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(500, f"Error reading file: {e}")

    fid = str(uuid.uuid4())[:8]
    _store[fid] = {"path": path, "fmt": fmt, "info": info}
    return {"id": fid, **info, "path": path}


@app.get("/api/data/{fid}")
async def get_data(
    fid: str,
    offset: int = Query(0, ge=0),
    limit: int = Query(50, ge=1, le=500),
    columns: str = Query("", description="comma-separated column names, empty=all"),
):
    if fid not in _store:
        raise HTTPException(404, "File not opened")
    entry = _store[fid]
    path, fmt = entry["path"], entry["fmt"]
    col_list = [c.strip() for c in columns.split(",") if c.strip()] or None

    try:
        if fmt == "parquet":
            table = pq.read_table(path, columns=col_list)
            df = table.to_pandas()
        elif fmt == "arrow":
            table = pa.ipc.open_file(path).read_all()
            if col_list:
                table = table.select(col_list)
            df = table.to_pandas()
        elif fmt == "csv":
            df = pd.read_csv(path, usecols=col_list)
        elif fmt in ("json", "jsonl"):
            if fmt == "jsonl":
                df = pd.read_json(path, lines=True)
            else:
                df = pd.read_json(path)
            if col_list:
                df = df[col_list]
        else:
            raise HTTPException(400, "Unsupported format")
    except Exception as e:
        raise HTTPException(500, str(e))

    total = len(df)
    sliced = df.iloc[offset : offset + limit]

    # Serialize: handle binary columns by converting to base64 placeholders
    records = []
    for _, row in sliced.iterrows():
        rec = {}
        for col in df.columns:
            val = row[col]
            if isinstance(val, bytes):
                rec[col] = {"_type": "image", "size": len(val)}
            elif pd.isna(val):
                rec[col] = None
            elif hasattr(val, "item"):
                rec[col] = val.item()
            else:
                rec[col] = val
        records.append(rec)

    return {"total": total, "offset": offset, "limit": limit, "data": records}


@app.get("/api/image/{fid}/{row}/{col}")
async def get_image(fid: str, row: int, col: str):
    if fid not in _store:
        raise HTTPException(404, "File not opened")
    entry = _store[fid]
    path, fmt = entry["path"], entry["fmt"]

    try:
        if fmt == "parquet":
            table = pq.read_table(path, columns=[col])
        elif fmt == "arrow":
            table = pa.ipc.open_file(path).read_all().select([col])
        else:
            raise HTTPException(400, "Image columns only supported for parquet/arrow")

        if row >= table.num_rows:
            raise HTTPException(400, "Row index out of range")

        cell = table.column(col)[row].as_py()
        if not isinstance(cell, (bytes, bytearray)):
            raise HTTPException(400, "Column is not binary/image")

        img = Image.open(io.BytesIO(cell))
        buf = io.BytesIO()
        img.save(buf, format="WEBP", quality=85)
        return Response(content=buf.getvalue(), media_type="image/webp")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(500, str(e))


@app.get("/api/stats/{fid}")
async def get_stats(fid: str):
    if fid not in _store:
        raise HTTPException(404, "File not opened")
    entry = _store[fid]
    path, fmt = entry["path"], entry["fmt"]
    info = entry["info"]

    try:
        if fmt == "parquet":
            table = pq.read_table(path)
            df = table.to_pandas()
        elif fmt == "arrow":
            table = pa.ipc.open_file(path).read_all()
            df = table.to_pandas()
        elif fmt == "csv":
            df = pd.read_csv(path)
        elif fmt in ("json", "jsonl"):
            df = pd.read_json(path, lines=(fmt == "jsonl"))
        else:
            raise HTTPException(400, "Unsupported format")
    except Exception as e:
        raise HTTPException(500, str(e))

    stats = []
    for col_info in info["columns"]:
        name = col_info["name"]
        is_img = col_info["is_image"]
        col = df[name]

        non_null = int(col.notna().sum())
        null_count = int(col.isna().sum())

        s: dict[str, Any] = {
            "name": name,
            "type": col_info["type"],
            "non_null": non_null,
            "null_count": null_count,
        }

        if is_img:
            sizes = col.dropna().apply(lambda x: len(x) if isinstance(x, (bytes, bytearray)) else 0)
            if len(sizes) > 0:
                s["image_stats"] = {
                    "min_bytes": int(sizes.min()),
                    "max_bytes": int(sizes.max()),
                    "mean_bytes": float(sizes.mean()),
                }
        elif col.dtype in ("int64", "float64", "int32", "float32"):
            s["numeric_stats"] = {
                "min": float(col.min()) if non_null else None,
                "max": float(col.max()) if non_null else None,
                "mean": float(col.mean()) if non_null else None,
                "median": float(col.median()) if non_null else None,
                "std": float(col.std()) if non_null else None,
            }
        elif col.dtype == "object":
            nunique = int(col.nunique())
            s["text_stats"] = {
                "nunique": nunique,
                "avg_length": float(col.astype(str).str.len().mean()) if non_null else 0,
            }
            if nunique <= 30:
                vc = col.value_counts().head(20)
                s["text_stats"]["top_values"] = {str(k): int(v) for k, v in vc.items()}
        elif col.dtype == "bool":
            vc = col.value_counts()
            s["bool_stats"] = {str(k): int(v) for k, v in vc.items()}

        stats.append(s)

    return {"total_rows": len(df), "columns": stats}


@app.get("/api/list")
async def list_files():
    return [
        {"id": fid, "path": e["path"], "format": e["fmt"], "rows": e["info"]["num_rows"]}
        for fid, e in _store.items()
    ]


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="DataView server")
    parser.add_argument("--port", type=int, default=8080)
    parser.add_argument("--host", default="0.0.0.0")
    parser.add_argument("--dir", default=None, help="Default directory for folder browser")
    args = parser.parse_args()

    if args.dir:
        DEFAULT_DIR = os.path.expanduser(args.dir)

    import uvicorn
    print(f"\n  DataView running at http://localhost:{args.port}")
    print(f"  Default directory: {DEFAULT_DIR}\n")
    uvicorn.run(app, host=args.host, port=args.port, log_level="info")