| """ |
| 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) |
|
|
| |
| |
| |
| _store: dict[str, dict] = {} |
|
|
| 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() |
| ], |
| } |
|
|
|
|
| |
| |
| |
| @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, |
| }) |
|
|
| |
| 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] |
|
|
| |
| 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") |
|
|