GCStream commited on
Commit
38857ff
·
verified ·
1 Parent(s): 11ce4a7

Add server.py

Browse files
Files changed (1) hide show
  1. tools/dataview/server.py +412 -0
tools/dataview/server.py ADDED
@@ -0,0 +1,412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ DataView — General-purpose dataset visualizer for HuggingFace-style files.
3
+ Supports: Parquet, Arrow, CSV, JSON/JSONL.
4
+ Run: python tools/dataview/server.py [--port 8080] [--dir /path/to/datasets]
5
+ """
6
+
7
+ import argparse
8
+ import io
9
+ import json
10
+ import os
11
+ import uuid
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ import pandas as pd
16
+ import pyarrow as pa
17
+ import pyarrow.parquet as pq
18
+ from fastapi import FastAPI, HTTPException, Query
19
+ from fastapi.responses import HTMLResponse, Response
20
+ from fastapi.staticfiles import StaticFiles
21
+ from PIL import Image
22
+
23
+ app = FastAPI(title="DataView")
24
+
25
+ STATIC_DIR = Path(__file__).parent / "static"
26
+ app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
27
+
28
+ DEFAULT_DIR = str(Path(__file__).parent.parent.parent)
29
+
30
+ # ---------------------------------------------------------------------------
31
+ # In-memory store of opened files
32
+ # ---------------------------------------------------------------------------
33
+ _store: dict[str, dict] = {} # file_id -> metadata
34
+
35
+ SUPPORTED_EXTS = {".parquet", ".pq", ".arrow", ".feather", ".csv", ".tsv", ".json", ".jsonl"}
36
+
37
+
38
+ def _detect_format(path: str) -> str:
39
+ p = path.lower()
40
+ if p.endswith(".parquet") or p.endswith(".pq"):
41
+ return "parquet"
42
+ if p.endswith(".arrow") or p.endswith(".feather"):
43
+ return "arrow"
44
+ if p.endswith(".csv") or p.endswith(".tsv"):
45
+ return "csv"
46
+ if p.endswith(".jsonl") or p.endswith(".json"):
47
+ return "jsonl" if ".jsonl" in p else "json"
48
+ return "unknown"
49
+
50
+
51
+ def _read_parquet_schema(path: str) -> dict:
52
+ pf = pq.ParquetFile(path)
53
+ schema = pf.schema_arrow
54
+ meta = pf.metadata
55
+ return {
56
+ "format": "parquet",
57
+ "num_rows": meta.num_rows,
58
+ "num_row_groups": meta.num_row_groups,
59
+ "file_size_bytes": os.path.getsize(path),
60
+ "columns": [
61
+ {
62
+ "name": field.name,
63
+ "type": str(field.type),
64
+ "is_image": str(field.type) in ("binary", "large_binary"),
65
+ "nullable": field.nullable,
66
+ }
67
+ for field in schema
68
+ ],
69
+ }
70
+
71
+
72
+ def _read_arrow_schema(path: str) -> dict:
73
+ table = pa.ipc.open_file(path).read_all()
74
+ return {
75
+ "format": "arrow",
76
+ "num_rows": table.num_rows,
77
+ "columns": [
78
+ {
79
+ "name": field.name,
80
+ "type": str(field.type),
81
+ "is_image": str(field.type) in ("binary", "large_binary"),
82
+ "nullable": field.nullable,
83
+ }
84
+ for field in table.schema
85
+ ],
86
+ }
87
+
88
+
89
+ def _read_csv_schema(path: str) -> dict:
90
+ df = pd.read_csv(path, nrows=0)
91
+ return {
92
+ "format": "csv",
93
+ "num_rows": sum(1 for _ in open(path)) - 1,
94
+ "columns": [
95
+ {
96
+ "name": col,
97
+ "type": str(dtype),
98
+ "is_image": False,
99
+ "nullable": True,
100
+ }
101
+ for col, dtype in df.dtypes.items()
102
+ ],
103
+ }
104
+
105
+
106
+ def _read_json_schema(path: str) -> dict:
107
+ with open(path) as f:
108
+ first_line = f.readline().strip()
109
+ if first_line.startswith("["):
110
+ rows = json.loads(open(path).read())
111
+ num_rows = len(rows)
112
+ sample = rows[0] if rows else {}
113
+ else:
114
+ num_rows = sum(1 for _ in open(path))
115
+ sample = json.loads(first_line) if first_line else {}
116
+ return {
117
+ "format": "json",
118
+ "num_rows": num_rows,
119
+ "columns": [
120
+ {
121
+ "name": k,
122
+ "type": type(v).__name__,
123
+ "is_image": isinstance(v, bytes),
124
+ "nullable": v is None,
125
+ }
126
+ for k, v in sample.items()
127
+ ],
128
+ }
129
+
130
+
131
+ # ---------------------------------------------------------------------------
132
+ # Routes
133
+ # ---------------------------------------------------------------------------
134
+ @app.get("/", response_class=HTMLResponse)
135
+ async def index():
136
+ return (STATIC_DIR / "index.html").read_text()
137
+
138
+
139
+ @app.get("/api/browse")
140
+ async def browse(path: str = Query(""), show_hidden: bool = Query(False)):
141
+ """List directory contents for the folder browser."""
142
+ if not path:
143
+ path = DEFAULT_DIR
144
+ path = os.path.expanduser(path)
145
+
146
+ if not os.path.isdir(path):
147
+ raise HTTPException(400, f"Not a directory: {path}")
148
+
149
+ entries = []
150
+ try:
151
+ for name in sorted(os.listdir(path)):
152
+ if not show_hidden and name.startswith("."):
153
+ continue
154
+ full = os.path.join(path, name)
155
+ is_dir = os.path.isdir(full)
156
+ ext = os.path.splitext(name)[1].lower() if not is_dir else ""
157
+ size = 0
158
+ if not is_dir:
159
+ try:
160
+ size = os.path.getsize(full)
161
+ except OSError:
162
+ pass
163
+ entries.append({
164
+ "name": name,
165
+ "path": full,
166
+ "is_dir": is_dir,
167
+ "ext": ext,
168
+ "is_dataset": ext in SUPPORTED_EXTS,
169
+ "size": size,
170
+ })
171
+
172
+ # Sort: dirs first, then dataset files, then others
173
+ def sort_key(e):
174
+ if e["is_dir"]:
175
+ return (0, e["name"].lower())
176
+ if e["is_dataset"]:
177
+ return (1, e["name"].lower())
178
+ return (2, e["name"].lower())
179
+
180
+ entries.sort(key=sort_key)
181
+ except PermissionError:
182
+ raise HTTPException(403, f"Permission denied: {path}")
183
+
184
+ return {
185
+ "path": path,
186
+ "parent": os.path.dirname(path) if path != "/" else None,
187
+ "entries": entries,
188
+ }
189
+
190
+
191
+ @app.get("/api/default-path")
192
+ async def default_path():
193
+ return {"path": DEFAULT_DIR}
194
+
195
+
196
+ @app.post("/api/open")
197
+ async def open_file(body: dict):
198
+ path = body.get("path", "").strip()
199
+ if not path:
200
+ raise HTTPException(400, "path is required")
201
+ path = os.path.expanduser(path)
202
+ if not os.path.isfile(path):
203
+ raise HTTPException(404, f"File not found: {path}")
204
+
205
+ fmt = _detect_format(path)
206
+ try:
207
+ if fmt == "parquet":
208
+ info = _read_parquet_schema(path)
209
+ elif fmt == "arrow":
210
+ info = _read_arrow_schema(path)
211
+ elif fmt == "csv":
212
+ info = _read_csv_schema(path)
213
+ elif fmt in ("json", "jsonl"):
214
+ info = _read_json_schema(path)
215
+ else:
216
+ raise HTTPException(400, f"Unsupported format: {fmt}")
217
+ except HTTPException:
218
+ raise
219
+ except Exception as e:
220
+ raise HTTPException(500, f"Error reading file: {e}")
221
+
222
+ fid = str(uuid.uuid4())[:8]
223
+ _store[fid] = {"path": path, "fmt": fmt, "info": info}
224
+ return {"id": fid, **info, "path": path}
225
+
226
+
227
+ @app.get("/api/data/{fid}")
228
+ async def get_data(
229
+ fid: str,
230
+ offset: int = Query(0, ge=0),
231
+ limit: int = Query(50, ge=1, le=500),
232
+ columns: str = Query("", description="comma-separated column names, empty=all"),
233
+ ):
234
+ if fid not in _store:
235
+ raise HTTPException(404, "File not opened")
236
+ entry = _store[fid]
237
+ path, fmt = entry["path"], entry["fmt"]
238
+ col_list = [c.strip() for c in columns.split(",") if c.strip()] or None
239
+
240
+ try:
241
+ if fmt == "parquet":
242
+ table = pq.read_table(path, columns=col_list)
243
+ df = table.to_pandas()
244
+ elif fmt == "arrow":
245
+ table = pa.ipc.open_file(path).read_all()
246
+ if col_list:
247
+ table = table.select(col_list)
248
+ df = table.to_pandas()
249
+ elif fmt == "csv":
250
+ df = pd.read_csv(path, usecols=col_list)
251
+ elif fmt in ("json", "jsonl"):
252
+ if fmt == "jsonl":
253
+ df = pd.read_json(path, lines=True)
254
+ else:
255
+ df = pd.read_json(path)
256
+ if col_list:
257
+ df = df[col_list]
258
+ else:
259
+ raise HTTPException(400, "Unsupported format")
260
+ except Exception as e:
261
+ raise HTTPException(500, str(e))
262
+
263
+ total = len(df)
264
+ sliced = df.iloc[offset : offset + limit]
265
+
266
+ # Serialize: handle binary columns by converting to base64 placeholders
267
+ records = []
268
+ for _, row in sliced.iterrows():
269
+ rec = {}
270
+ for col in df.columns:
271
+ val = row[col]
272
+ if isinstance(val, bytes):
273
+ rec[col] = {"_type": "image", "size": len(val)}
274
+ elif pd.isna(val):
275
+ rec[col] = None
276
+ elif hasattr(val, "item"):
277
+ rec[col] = val.item()
278
+ else:
279
+ rec[col] = val
280
+ records.append(rec)
281
+
282
+ return {"total": total, "offset": offset, "limit": limit, "data": records}
283
+
284
+
285
+ @app.get("/api/image/{fid}/{row}/{col}")
286
+ async def get_image(fid: str, row: int, col: str):
287
+ if fid not in _store:
288
+ raise HTTPException(404, "File not opened")
289
+ entry = _store[fid]
290
+ path, fmt = entry["path"], entry["fmt"]
291
+
292
+ try:
293
+ if fmt == "parquet":
294
+ table = pq.read_table(path, columns=[col])
295
+ elif fmt == "arrow":
296
+ table = pa.ipc.open_file(path).read_all().select([col])
297
+ else:
298
+ raise HTTPException(400, "Image columns only supported for parquet/arrow")
299
+
300
+ if row >= table.num_rows:
301
+ raise HTTPException(400, "Row index out of range")
302
+
303
+ cell = table.column(col)[row].as_py()
304
+ if not isinstance(cell, (bytes, bytearray)):
305
+ raise HTTPException(400, "Column is not binary/image")
306
+
307
+ img = Image.open(io.BytesIO(cell))
308
+ buf = io.BytesIO()
309
+ img.save(buf, format="WEBP", quality=85)
310
+ return Response(content=buf.getvalue(), media_type="image/webp")
311
+ except HTTPException:
312
+ raise
313
+ except Exception as e:
314
+ raise HTTPException(500, str(e))
315
+
316
+
317
+ @app.get("/api/stats/{fid}")
318
+ async def get_stats(fid: str):
319
+ if fid not in _store:
320
+ raise HTTPException(404, "File not opened")
321
+ entry = _store[fid]
322
+ path, fmt = entry["path"], entry["fmt"]
323
+ info = entry["info"]
324
+
325
+ try:
326
+ if fmt == "parquet":
327
+ table = pq.read_table(path)
328
+ df = table.to_pandas()
329
+ elif fmt == "arrow":
330
+ table = pa.ipc.open_file(path).read_all()
331
+ df = table.to_pandas()
332
+ elif fmt == "csv":
333
+ df = pd.read_csv(path)
334
+ elif fmt in ("json", "jsonl"):
335
+ df = pd.read_json(path, lines=(fmt == "jsonl"))
336
+ else:
337
+ raise HTTPException(400, "Unsupported format")
338
+ except Exception as e:
339
+ raise HTTPException(500, str(e))
340
+
341
+ stats = []
342
+ for col_info in info["columns"]:
343
+ name = col_info["name"]
344
+ is_img = col_info["is_image"]
345
+ col = df[name]
346
+
347
+ non_null = int(col.notna().sum())
348
+ null_count = int(col.isna().sum())
349
+
350
+ s: dict[str, Any] = {
351
+ "name": name,
352
+ "type": col_info["type"],
353
+ "non_null": non_null,
354
+ "null_count": null_count,
355
+ }
356
+
357
+ if is_img:
358
+ sizes = col.dropna().apply(lambda x: len(x) if isinstance(x, (bytes, bytearray)) else 0)
359
+ if len(sizes) > 0:
360
+ s["image_stats"] = {
361
+ "min_bytes": int(sizes.min()),
362
+ "max_bytes": int(sizes.max()),
363
+ "mean_bytes": float(sizes.mean()),
364
+ }
365
+ elif col.dtype in ("int64", "float64", "int32", "float32"):
366
+ s["numeric_stats"] = {
367
+ "min": float(col.min()) if non_null else None,
368
+ "max": float(col.max()) if non_null else None,
369
+ "mean": float(col.mean()) if non_null else None,
370
+ "median": float(col.median()) if non_null else None,
371
+ "std": float(col.std()) if non_null else None,
372
+ }
373
+ elif col.dtype == "object":
374
+ nunique = int(col.nunique())
375
+ s["text_stats"] = {
376
+ "nunique": nunique,
377
+ "avg_length": float(col.astype(str).str.len().mean()) if non_null else 0,
378
+ }
379
+ if nunique <= 30:
380
+ vc = col.value_counts().head(20)
381
+ s["text_stats"]["top_values"] = {str(k): int(v) for k, v in vc.items()}
382
+ elif col.dtype == "bool":
383
+ vc = col.value_counts()
384
+ s["bool_stats"] = {str(k): int(v) for k, v in vc.items()}
385
+
386
+ stats.append(s)
387
+
388
+ return {"total_rows": len(df), "columns": stats}
389
+
390
+
391
+ @app.get("/api/list")
392
+ async def list_files():
393
+ return [
394
+ {"id": fid, "path": e["path"], "format": e["fmt"], "rows": e["info"]["num_rows"]}
395
+ for fid, e in _store.items()
396
+ ]
397
+
398
+
399
+ if __name__ == "__main__":
400
+ parser = argparse.ArgumentParser(description="DataView server")
401
+ parser.add_argument("--port", type=int, default=8080)
402
+ parser.add_argument("--host", default="0.0.0.0")
403
+ parser.add_argument("--dir", default=None, help="Default directory for folder browser")
404
+ args = parser.parse_args()
405
+
406
+ if args.dir:
407
+ DEFAULT_DIR = os.path.expanduser(args.dir)
408
+
409
+ import uvicorn
410
+ print(f"\n DataView running at http://localhost:{args.port}")
411
+ print(f" Default directory: {DEFAULT_DIR}\n")
412
+ uvicorn.run(app, host=args.host, port=args.port, log_level="info")