GCStream commited on
Commit
11ce4a7
·
verified ·
1 Parent(s): 5379ec4

Add DataView tool: dataset visualizer with gallery, table, compare, and drawer views

Browse files
Files changed (5) hide show
  1. clean_dataset.py +376 -0
  2. server.py +412 -0
  3. static/app.js +527 -0
  4. static/index.html +192 -0
  5. static/style.css +871 -0
clean_dataset.py ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ clean_dataset.py — Extract clean prompts from Telegram AI image dataset.
3
+ Groups consecutive images by prompt, strips ads/model names/hashtags,
4
+ and outputs a VLM-training-ready JSONL file.
5
+
6
+ Usage:
7
+ python tools/dataview/clean_dataset.py \
8
+ --input telegram-channel-dataset/dataset.parquet \
9
+ --output telegram-channel-dataset/cleaned.jsonl
10
+ """
11
+
12
+ import argparse
13
+ import json
14
+ import re
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ import pandas as pd
19
+ import pyarrow as pa
20
+ import pyarrow.parquet as pq
21
+
22
+
23
+ # ── Patterns to strip ──────────────────────────────────────────────────
24
+ STRIP_PATTERNS = [
25
+ # Hashtags
26
+ r'#[\w\u4e00-\u9fff]+',
27
+ # Bot links / Telegram links
28
+ r'\[.*?\]\(https?://t\.me/[^\)]+\)',
29
+ r'https?://t\.me/\S+',
30
+ r'https?://\S+',
31
+ # Source/author lines
32
+ r'来源:.*',
33
+ r'作者:.*',
34
+ r'Source:.*',
35
+ r'Author:.*',
36
+ # Ad / promo lines
37
+ r'🚀.*',
38
+ r'📚\s*教程目录.*',
39
+ r'━━+',
40
+ r'🤖.*我们的 Bot.*',
41
+ r'🔥.*邪修频道.*',
42
+ r'VPN推荐.*',
43
+ r'NanoGPT.*',
44
+ r'免费赠送.*',
45
+ r'快来体验.*',
46
+ r'Dubis.*',
47
+ r'Bot 机器人.*',
48
+ # Model name prefixes in titles
49
+ r'^(✨|🔥|🧩|🖼️|🎞️|🎬|🏮|🎨|📷|📸|🌟|💡|🎭|🎪|🎬|🌙|🌅|🌸|🎭|🖌️)\s*',
50
+ r'^GPT-?Image[-\s]*2?[||]',
51
+ r'^GPTImage2?[||]',
52
+ # Title lines (Chinese titles with emoji)
53
+ r'^.*?[||].*?(prompt|模板|技巧|构图|写真|人像|海报|封面).*?$',
54
+ ]
55
+
56
+ # Fields that contain prompt-relevant information
57
+ PROMPT_FIELDS = [
58
+ '任务', '主体', '服装', '场景', '光线', '镜头', '风格', '构图',
59
+ '约束', '画幅', '关键特征', '变体', '重点', '角色感', '妆造',
60
+ '动作', '调色', '反差', '结构', '适用', '示例',
61
+ 'Task', 'Subject', 'Style', 'Lighting', 'Camera', 'Composition',
62
+ 'Prompt skeleton',
63
+ ]
64
+
65
+ # Chinese field labels to English mapping
66
+ FIELD_MAP = {
67
+ '任务': 'task',
68
+ '主体': 'subject',
69
+ '服装': 'clothing',
70
+ '场景': 'scene',
71
+ '光线': 'lighting',
72
+ '镜头': 'camera',
73
+ '风格': 'style',
74
+ '构图': 'composition',
75
+ '约束': 'avoid',
76
+ '画幅': 'aspect_ratio',
77
+ '关键特征': 'key_features',
78
+ '变体': 'variants',
79
+ '重点': 'focus',
80
+ '角色感': 'character',
81
+ '妆造': 'makeup',
82
+ '动作': 'pose',
83
+ '调色': 'color_grading',
84
+ '反差': 'contrast',
85
+ '结构': 'layout',
86
+ '适用': 'use_case',
87
+ '示例': 'examples',
88
+ 'Task': 'task',
89
+ 'Subject': 'subject',
90
+ 'Style': 'style',
91
+ 'Lighting': 'lighting',
92
+ 'Camera': 'camera',
93
+ 'Composition': 'composition',
94
+ 'Prompt skeleton': 'prompt_skeleton',
95
+ }
96
+
97
+
98
+ def clean_text(text: str) -> str:
99
+ """Remove ads, links, hashtags, model names, and other noise."""
100
+ if not text or pd.isna(text):
101
+ return ''
102
+ text = str(text)
103
+
104
+ # Apply strip patterns
105
+ for pattern in STRIP_PATTERNS:
106
+ text = re.sub(pattern, '', text, flags=re.MULTILINE | re.IGNORECASE)
107
+
108
+ # Remove lines that are just emojis or very short
109
+ lines = text.split('\n')
110
+ cleaned_lines = []
111
+ for line in lines:
112
+ line = line.strip()
113
+ if not line:
114
+ continue
115
+ # Skip very short lines (likely noise)
116
+ if len(line) < 3:
117
+ continue
118
+ # Skip lines that are mostly emojis
119
+ emoji_chars = len(re.findall(r'[\U0001F300-\U0001F9FF]', line))
120
+ if emoji_chars > len(line) * 0.5:
121
+ continue
122
+ cleaned_lines.append(line)
123
+
124
+ return '\n'.join(cleaned_lines).strip()
125
+
126
+
127
+ def extract_structured_fields(text: str) -> dict:
128
+ """Extract structured prompt fields from Chinese text."""
129
+ if not text:
130
+ return {}
131
+
132
+ fields = {}
133
+ # Match patterns like "字段名:值" or "字段名: value"
134
+ field_names = '|'.join(re.escape(f) for f in PROMPT_FIELDS)
135
+ field_pattern = re.compile(
136
+ rf'^(?:[-•]\s*)?({field_names})[::]\s*(.+?)(?:\n|$)',
137
+ re.MULTILINE
138
+ )
139
+
140
+ for match in field_pattern.finditer(text):
141
+ field_name = match.group(1).strip()
142
+ value = match.group(2).strip()
143
+ if value and len(value) > 2:
144
+ eng_name = FIELD_MAP.get(field_name, field_name)
145
+ fields[eng_name] = value
146
+
147
+ return fields
148
+
149
+
150
+ def extract_prompt_skeleton(text: str) -> str:
151
+ """Extract 'Prompt skeleton' section if present."""
152
+ if not text:
153
+ return ''
154
+ match = re.search(r'Prompt skeleton[:\s]*\n(.+?)(?:\n\n|\n备注|\Z)', text, re.DOTALL)
155
+ if match:
156
+ return match.group(1).strip()
157
+ return ''
158
+
159
+
160
+ def build_prompt(text: str) -> str:
161
+ """Build a clean prompt from the structured fields."""
162
+ if not text:
163
+ return ''
164
+
165
+ # Try to get prompt skeleton first (most direct)
166
+ skeleton = extract_prompt_skeleton(text)
167
+ if skeleton and len(skeleton) > 20:
168
+ return skeleton
169
+
170
+ # Extract structured fields
171
+ fields = extract_structured_fields(text)
172
+
173
+ if not fields:
174
+ # Fallback: try to extract any English prompt-like content
175
+ lines = text.split('\n')
176
+ prompt_parts = []
177
+ for line in lines:
178
+ line = line.strip()
179
+ # Skip Chinese-only lines
180
+ chinese_chars = len(re.findall(r'[\u4e00-\u9fff]', line))
181
+ if chinese_chars > len(line) * 0.3:
182
+ continue
183
+ # Skip very short lines
184
+ if len(line) < 10:
185
+ continue
186
+ # Skip known noise
187
+ if any(skip in line.lower() for skip in ['bot', 'http', '#', '来源', '作者', 'source', 'author']):
188
+ continue
189
+ prompt_parts.append(line)
190
+ if prompt_parts:
191
+ return '; '.join(prompt_parts)
192
+ return ''
193
+
194
+ # Build prompt from fields in logical order
195
+ order = ['task', 'subject', 'character', 'makeup', 'clothing', 'pose',
196
+ 'scene', 'lighting', 'camera', 'composition', 'aspect_ratio',
197
+ 'key_features', 'style', 'color_grading', 'contrast', 'layout',
198
+ 'avoid', 'use_case', 'prompt_skeleton']
199
+
200
+ parts = []
201
+ for key in order:
202
+ if key in fields:
203
+ parts.append(fields[key])
204
+
205
+ # Add any remaining fields not in order
206
+ for key, val in fields.items():
207
+ if key not in order and val:
208
+ parts.append(val)
209
+
210
+ return '; '.join(parts) if parts else ''
211
+
212
+
213
+ def group_images(df: pd.DataFrame) -> list:
214
+ """Group consecutive images by prompt (same dimensions = same generation)."""
215
+ groups = []
216
+ current_group = None
217
+
218
+ for idx, row in df.iterrows():
219
+ has_text = row['text'] and str(row['text']).strip()
220
+ has_image = row['image'] is not None and isinstance(row['image'], bytes) and len(row['image']) > 100
221
+
222
+ if has_text and has_image:
223
+ # Start new group
224
+ if current_group:
225
+ groups.append(current_group)
226
+ current_group = {
227
+ 'message_id': row['message_id'],
228
+ 'datetime': row['datetime'],
229
+ 'raw_text': row['text'],
230
+ 'images': [{
231
+ 'row_idx': idx,
232
+ 'message_id': row['message_id'],
233
+ 'width': row['width'],
234
+ 'height': row['height'],
235
+ 'image_bytes': row['image'],
236
+ }]
237
+ }
238
+ elif current_group and has_image:
239
+ # Check if dimensions match (same generation batch)
240
+ last_img = current_group['images'][-1]
241
+ if row['width'] == last_img['width'] and row['height'] == last_img['height']:
242
+ current_group['images'].append({
243
+ 'row_idx': idx,
244
+ 'message_id': row['message_id'],
245
+ 'width': row['width'],
246
+ 'height': row['height'],
247
+ 'image_bytes': row['image'],
248
+ })
249
+
250
+ if current_group:
251
+ groups.append(current_group)
252
+
253
+ return groups
254
+
255
+
256
+ def main():
257
+ parser = argparse.ArgumentParser(description='Clean Telegram AI image dataset')
258
+ parser.add_argument('--input', '-i', required=True, help='Input parquet file')
259
+ parser.add_argument('--output', '-o', default=None, help='Output JSONL file')
260
+ parser.add_argument('--parquet', default=None, help='Output cleaned parquet (with only useful columns)')
261
+ parser.add_argument('--min-images', type=int, default=1, help='Min images per group')
262
+ parser.add_argument('--min-prompt-len', type=int, default=10, help='Min prompt length')
263
+ parser.add_argument('--stats', action='store_true', help='Print stats only')
264
+ args = parser.parse_args()
265
+
266
+ # Read parquet
267
+ print(f"Reading {args.input}...")
268
+ df = pq.read_table(args.input).to_pandas()
269
+ print(f" Total rows: {len(df)}")
270
+
271
+ # Optionally output cleaned parquet (strip noise columns)
272
+ if args.parquet:
273
+ KEEP = ['message_id', 'datetime', 'media_type', 'text', 'width', 'height', 'image']
274
+ available = [c for c in KEEP if c in df.columns]
275
+ clean = df[available].copy()
276
+ if 'media_type' in clean.columns:
277
+ clean = clean[clean['media_type'] == 'photo'].copy()
278
+ clean.reset_index(drop=True, inplace=True)
279
+ pq.write_table(pa.Table.from_pandas(clean), args.parquet)
280
+ print(f" Cleaned parquet: {len(clean)} rows, {len(clean.columns)} cols -> {args.parquet}")
281
+
282
+ # Group images
283
+ groups = group_images(df)
284
+ print(f" Prompt groups: {len(groups)}")
285
+
286
+ # Clean and filter
287
+ cleaned = []
288
+ for group in groups:
289
+ prompt = build_prompt(group['raw_text'])
290
+ if len(prompt) < args.min_prompt_len:
291
+ continue
292
+ if len(group['images']) < args.min_images:
293
+ continue
294
+
295
+ cleaned.append({
296
+ 'prompt': prompt,
297
+ 'raw_text': group['raw_text'],
298
+ 'num_images': len(group['images']),
299
+ 'message_id': group['message_id'],
300
+ 'datetime': group['datetime'],
301
+ 'images': group['images'],
302
+ })
303
+
304
+ print(f" Cleaned groups: {len(cleaned)}")
305
+ print(f" Total images: {sum(g['num_images'] for g in cleaned)}")
306
+
307
+ if args.stats:
308
+ # Print distribution
309
+ from collections import Counter
310
+ sizes = Counter(g['num_images'] for g in cleaned)
311
+ print("\n Group size distribution:")
312
+ for size, count in sorted(sizes.items()):
313
+ print(f" {size} images: {count} groups")
314
+
315
+ # Show sample prompts
316
+ print("\n Sample prompts:")
317
+ for g in cleaned[:5]:
318
+ print(f" [{g['num_images']} imgs] {g['prompt'][:120]}...")
319
+ return
320
+
321
+ # Output
322
+ if args.output:
323
+ output_path = Path(args.output)
324
+ output_path.parent.mkdir(parents=True, exist_ok=True)
325
+
326
+ with open(output_path, 'w', encoding='utf-8') as f:
327
+ for group in cleaned:
328
+ record = {
329
+ 'prompt': group['prompt'],
330
+ 'num_images': group['num_images'],
331
+ 'message_id': group['message_id'],
332
+ 'datetime': group['datetime'],
333
+ 'image_paths': [
334
+ f"images/msg_{img['message_id']}_row_{img['row_idx']}.webp"
335
+ for img in group['images']
336
+ ],
337
+ }
338
+ f.write(json.dumps(record, ensure_ascii=False) + '\n')
339
+
340
+ print(f"\n Written to {output_path}")
341
+
342
+ # Also save images
343
+ img_dir = output_path.parent / 'images'
344
+ img_dir.mkdir(exist_ok=True)
345
+
346
+ from PIL import Image
347
+ import io
348
+
349
+ print(" Extracting images...")
350
+ saved = 0
351
+ for group in cleaned:
352
+ for img_data in group['images']:
353
+ try:
354
+ img = Image.open(io.BytesIO(img_data['image_bytes']))
355
+ img_path = img_dir / f"msg_{img_data['message_id']}_row_{img_data['row_idx']}.webp"
356
+ img.save(img_path, format='WEBP', quality=90)
357
+ saved += 1
358
+ except Exception as e:
359
+ print(f" Warning: Failed to save image {img_data['message_id']}: {e}")
360
+
361
+ print(f" Saved {saved} images to {img_dir}")
362
+ else:
363
+ # Just print stats
364
+ from collections import Counter
365
+ sizes = Counter(g['num_images'] for g in cleaned)
366
+ print("\n Group size distribution:")
367
+ for size, count in sorted(sizes.items()):
368
+ print(f" {size} images: {count} groups")
369
+
370
+ print("\n Sample prompts:")
371
+ for g in cleaned[:10]:
372
+ print(f" [{g['num_images']} imgs] {g['prompt'][:150]}...")
373
+
374
+
375
+ if __name__ == '__main__':
376
+ main()
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")
static/app.js ADDED
@@ -0,0 +1,527 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ (() => {
2
+ const $ = (sel) => document.querySelector(sel);
3
+ const $$ = (sel) => document.querySelectorAll(sel);
4
+
5
+ let currentFile = null;
6
+ let galleryOffset = 0;
7
+ let tableOffset = 0;
8
+ const PER_PAGE = 60;
9
+ let compareSet = new Map();
10
+ let searchText = '';
11
+ let dataCache = null;
12
+ let drawerRowIdx = null;
13
+ let drawerNavList = [];
14
+
15
+ function showLoading() { $('#loading').classList.remove('hidden'); }
16
+ function hideLoading() { $('#loading').classList.add('hidden'); }
17
+
18
+ function fmtSize(b) {
19
+ if (!b) return '—';
20
+ if (b < 1024) return b + ' B';
21
+ if (b < 1048576) return (b / 1024).toFixed(1) + ' KB';
22
+ if (b < 1073741824) return (b / 1048576).toFixed(1) + ' MB';
23
+ return (b / 1073741824).toFixed(2) + ' GB';
24
+ }
25
+
26
+ function fmtNum(n) {
27
+ if (n == null) return '—';
28
+ return Number.isInteger(n) ? n.toLocaleString() : n.toLocaleString(undefined, { maximumFractionDigits: 2 });
29
+ }
30
+
31
+ function esc(s) {
32
+ const d = document.createElement('div');
33
+ d.textContent = s;
34
+ return d.innerHTML;
35
+ }
36
+
37
+ function trunc(s, len) {
38
+ if (!s) return '';
39
+ return s.length > len ? s.slice(0, len) + '…' : s;
40
+ }
41
+
42
+ function imgSrc(fid, rowIdx, col) {
43
+ return `/api/image/${fid}/${rowIdx}/${col}`;
44
+ }
45
+
46
+ // ── Folder browser ───────────────────────────────────────────────
47
+ function openSidebar(path) {
48
+ $('#sidebar').classList.add('open');
49
+ $('#sidebar-backdrop').classList.add('open');
50
+ loadFolder(path || '');
51
+ }
52
+
53
+ function closeSidebar() {
54
+ $('#sidebar').classList.remove('open');
55
+ $('#sidebar-backdrop').classList.remove('open');
56
+ }
57
+
58
+ async function loadFolder(path) {
59
+ try {
60
+ const res = await fetch(`/api/browse?path=${encodeURIComponent(path)}`);
61
+ if (!res.ok) throw new Error();
62
+ const data = await res.json();
63
+ renderBreadcrumb(data.path);
64
+ renderFolderList(data);
65
+ } catch (e) { console.error(e); }
66
+ }
67
+
68
+ function renderBreadcrumb(path) {
69
+ const parts = path.split('/').filter(Boolean);
70
+ let h = '<span class="breadcrumb-item" data-path="/">/</span>';
71
+ let acc = '';
72
+ parts.forEach((p) => {
73
+ acc += '/' + p;
74
+ h += '<span class="breadcrumb-sep">/</span>';
75
+ h += '<span class="breadcrumb-item" data-path="' + esc(acc) + '">' + esc(p) + '</span>';
76
+ });
77
+ $('#breadcrumb').innerHTML = h;
78
+ $$('.breadcrumb-item').forEach((el) => el.addEventListener('click', () => loadFolder(el.dataset.path)));
79
+ }
80
+
81
+ function renderFolderList(data) {
82
+ let h = '';
83
+ if (data.parent) {
84
+ h += '<div class="folder-entry is-parent" data-path="' + esc(data.parent) + '"><span class="fe-icon">..</span><span class="fe-name">Up</span></div>';
85
+ }
86
+ data.entries.forEach((e) => {
87
+ let icon = '📄', cls = 'is-file';
88
+ if (e.is_dir) { icon = '📁'; cls = 'is-dir'; }
89
+ else if (e.is_dataset) { icon = '◉'; cls = 'is-dataset'; }
90
+ h += '<div class="folder-entry ' + cls + '" data-path="' + esc(e.path) + '" data-dir="' + e.is_dir + '" data-ds="' + e.is_dataset + '">';
91
+ h += '<span class="fe-icon">' + icon + '</span>';
92
+ h += '<span class="fe-name">' + esc(e.name) + '</span>';
93
+ if (!e.is_dir) h += '<span class="fe-meta">' + fmtSize(e.size) + '</span>';
94
+ h += '</div>';
95
+ });
96
+ if (!data.entries.length) h = '<div style="padding:24px;text-align:center;color:var(--text-tertiary);font-size:12px">Empty directory</div>';
97
+ $('#folder-list').innerHTML = h;
98
+ $$('.folder-entry').forEach((el) => el.addEventListener('click', () => {
99
+ if (el.dataset.dir === 'true') loadFolder(el.dataset.path);
100
+ else if (el.dataset.ds === 'true') {
101
+ $('#file-path').value = el.dataset.path;
102
+ closeSidebar();
103
+ openFile(el.dataset.path);
104
+ }
105
+ }));
106
+ }
107
+
108
+ $('#btn-browse').addEventListener('click', () => openSidebar(''));
109
+ $('#btn-close-sidebar').addEventListener('click', closeSidebar);
110
+ $('#sidebar-backdrop').addEventListener('click', closeSidebar);
111
+
112
+ // ── Open file ────────────────────────────────────────────────────
113
+ async function openFile(path) {
114
+ showLoading();
115
+ try {
116
+ const res = await fetch('/api/open', {
117
+ method: 'POST',
118
+ headers: { 'Content-Type': 'application/json' },
119
+ body: JSON.stringify({ path }),
120
+ });
121
+ if (!res.ok) { const e = await res.json(); alert(e.detail || 'Failed to open file'); return; }
122
+ currentFile = await res.json();
123
+ renderInfoBar();
124
+ renderColumnSelects();
125
+ galleryOffset = 0;
126
+ tableOffset = 0;
127
+ compareSet.clear();
128
+ updateCompareBadge();
129
+ closeDrawer();
130
+ $('#main').classList.remove('hidden');
131
+ $('#welcome').classList.add('hidden');
132
+ switchView('gallery');
133
+ } finally { hideLoading(); }
134
+ }
135
+
136
+ function renderInfoBar() {
137
+ $('#pill-file').textContent = currentFile.path.split('/').pop();
138
+ $('#pill-rows').textContent = fmtNum(currentFile.num_rows) + ' rows';
139
+ $('#pill-cols').textContent = currentFile.columns.length + ' cols';
140
+ }
141
+
142
+ function renderColumnSelects() {
143
+ const imgCols = currentFile.columns.filter((c) => c.is_image);
144
+ const textCols = currentFile.columns.filter((c) => !c.is_image);
145
+ $('#sel-img-col').innerHTML = imgCols.map((c) => '<option value="' + c.name + '">' + c.name + '</option>').join('');
146
+ $('#sel-txt-col').innerHTML = '<option value="">None</option>' + textCols.map((c) => '<option value="' + c.name + '">' + c.name + '</option>').join('');
147
+ const prefer = textCols.find((c) => c.name === 'text') || textCols[0];
148
+ if (prefer) {
149
+ const sel = $('#sel-txt-col');
150
+ for (let i = 0; i < sel.options.length; i++) {
151
+ if (sel.options[i].value === prefer.name) { sel.selectedIndex = i; break; }
152
+ }
153
+ }
154
+ }
155
+
156
+ // ── View switching ───────────────────────────────────────────────
157
+ function switchView(name) {
158
+ $$('.vs-btn').forEach((b) => b.classList.toggle('active', b.dataset.view === name));
159
+ $$('.view').forEach((v) => v.classList.add('hidden'));
160
+ $('#view-' + name).classList.remove('hidden');
161
+ if (name === 'gallery') loadGallery();
162
+ else if (name === 'table') loadTable();
163
+ else if (name === 'compare') renderCompare();
164
+ }
165
+
166
+ $$('.vs-btn').forEach((b) => b.addEventListener('click', () => switchView(b.dataset.view)));
167
+
168
+ // ── Search ───────────────────────────────────────────────────────
169
+ let searchTimer;
170
+ $('#search-input').addEventListener('input', (e) => {
171
+ clearTimeout(searchTimer);
172
+ searchTimer = setTimeout(() => {
173
+ searchText = e.target.value.trim().toLowerCase();
174
+ galleryOffset = 0;
175
+ tableOffset = 0;
176
+ const active = $('.vs-btn.active');
177
+ if (active) {
178
+ const v = active.dataset.view;
179
+ if (v === 'gallery') loadGallery();
180
+ else if (v === 'table') loadTable();
181
+ }
182
+ }, 200);
183
+ });
184
+
185
+ // ── Gallery ──────────────────────────────────────────────────────
186
+ async function loadGallery() {
187
+ if (!currentFile) return;
188
+ showLoading();
189
+ try {
190
+ const imgCol = $('#sel-img-col').value;
191
+ const txtCol = $('#sel-txt-col').value;
192
+ if (!imgCol) { hideLoading(); return; }
193
+ const cols = [imgCol];
194
+ if (txtCol) cols.push(txtCol);
195
+ const res = await fetch('/api/data/' + currentFile.id + '?offset=' + galleryOffset + '&limit=' + PER_PAGE + '&columns=' + cols.join(','));
196
+ if (!res.ok) throw new Error();
197
+ const data = await res.json();
198
+ dataCache = data;
199
+ drawerNavList = data.data.map((_, ri) => data.offset + ri);
200
+ renderGallery(data, imgCol, txtCol);
201
+ } finally { hideLoading(); }
202
+ }
203
+
204
+ function renderGallery(data, imgCol, txtCol) {
205
+ const totalPages = Math.ceil(data.total / PER_PAGE);
206
+ const page = Math.floor(data.offset / PER_PAGE) + 1;
207
+ $('#gallery-page').textContent = page + '/' + totalPages + ' (' + fmtNum(data.total) + ')';
208
+ $('#gallery-prev').disabled = data.offset === 0;
209
+ $('#gallery-next').disabled = data.offset + PER_PAGE >= data.total;
210
+
211
+ const fid = currentFile.id;
212
+ let h = '';
213
+ data.data.forEach((row, ri) => {
214
+ const rowIdx = data.offset + ri;
215
+ const caption = txtCol ? (row[txtCol] || '') : '';
216
+ const w = row.width || '';
217
+ const hm = row.height || '';
218
+ const sel = compareSet.has(rowIdx);
219
+ const isOpen = drawerRowIdx === rowIdx;
220
+
221
+ h += '<div class="card' + (sel ? ' selected' : '') + (isOpen ? ' card-open' : '') + '" data-row="' + rowIdx + '">';
222
+ h += '<span class="card-row">#' + (rowIdx + 1) + '</span>';
223
+ h += '<span class="card-check">&#10003;</span>';
224
+ h += '<img class="card-img" src="' + imgSrc(fid, rowIdx, imgCol) + '" loading="lazy" data-row="' + rowIdx + '" data-col="' + imgCol + '">';
225
+ if (w && hm) h += '<span class="card-dims">' + w + '&times;' + hm + '</span>';
226
+ if (caption) h += '<div class="card-caption">' + esc(trunc(caption, 140)) + '</div>';
227
+ h += '</div>';
228
+ });
229
+ if (!data.data.length) {
230
+ h = '<p style="color:var(--text-tertiary);padding:48px;text-align:center;grid-column:1/-1">No matching rows</p>';
231
+ }
232
+ $('#gallery-grid').innerHTML = h;
233
+ }
234
+
235
+ // Gallery event delegation
236
+ $('#gallery-grid').addEventListener('click', (e) => {
237
+ const img = e.target.closest('.card-img');
238
+ const card = e.target.closest('.card');
239
+ if (!card) return;
240
+ const rowIdx = parseInt(card.dataset.row);
241
+
242
+ if (e.shiftKey || e.metaKey || e.ctrlKey) {
243
+ toggleCompare(rowIdx);
244
+ return;
245
+ }
246
+ if (img) openDrawer(rowIdx);
247
+ });
248
+
249
+ $('#sel-img-col').addEventListener('change', () => { galleryOffset = 0; loadGallery(); });
250
+ $('#sel-txt-col').addEventListener('change', () => { galleryOffset = 0; loadGallery(); });
251
+ $('#sel-thumb-size').addEventListener('change', (e) => {
252
+ $('#gallery-grid').style.gridTemplateColumns = 'repeat(auto-fill, minmax(' + e.target.value + 'px, 1fr))';
253
+ });
254
+ $('#gallery-prev').addEventListener('click', () => { galleryOffset = Math.max(0, galleryOffset - PER_PAGE); loadGallery(); });
255
+ $('#gallery-next').addEventListener('click', () => { galleryOffset += PER_PAGE; loadGallery(); });
256
+
257
+ // ── Compare ──────────────────────────────────────────────────────
258
+ function toggleCompare(rowIdx) {
259
+ const imgCol = $('#sel-img-col').value;
260
+ if (compareSet.has(rowIdx)) {
261
+ compareSet.delete(rowIdx);
262
+ } else {
263
+ if (compareSet.size >= 4) {
264
+ const oldest = compareSet.keys().next().value;
265
+ compareSet.delete(oldest);
266
+ const oldCard = document.querySelector('.card[data-row="' + oldest + '"]');
267
+ if (oldCard) oldCard.classList.remove('selected');
268
+ }
269
+ compareSet.set(rowIdx, { src: imgSrc(currentFile.id, rowIdx, imgCol), rowIdx });
270
+ }
271
+ updateCompareBadge();
272
+ const card = document.querySelector('.card[data-row="' + rowIdx + '"]');
273
+ if (card) card.classList.toggle('selected', compareSet.has(rowIdx));
274
+ }
275
+
276
+ function updateCompareBadge() {
277
+ const badge = $('#compare-badge');
278
+ const n = compareSet.size;
279
+ badge.textContent = n;
280
+ badge.classList.toggle('hidden', n === 0);
281
+ }
282
+
283
+ function renderCompare() {
284
+ const content = $('#compare-content');
285
+ const empty = $('#compare-empty');
286
+ if (compareSet.size < 2) {
287
+ content.classList.add('hidden');
288
+ empty.classList.remove('hidden');
289
+ return;
290
+ }
291
+ content.classList.remove('hidden');
292
+ empty.classList.add('hidden');
293
+ const txtCol = $('#sel-txt-col').value;
294
+ let h = '';
295
+ let idx = 0;
296
+ for (const [rowIdx, item] of compareSet) {
297
+ const label = String.fromCharCode(65 + idx);
298
+ h += '<div class="compare-card">';
299
+ h += '<div class="cc-head"><span class="cc-label">' + label + ' &middot; Row ' + (rowIdx + 1) + '</span>';
300
+ h += '<button class="cc-remove" data-row="' + rowIdx + '">&times;</button></div>';
301
+ h += '<img src="' + item.src + '" alt="Row ' + (rowIdx + 1) + '">';
302
+ if (txtCol && dataCache) {
303
+ const row = dataCache.data.find((_, ri) => dataCache.offset + ri === rowIdx);
304
+ if (row && row[txtCol]) {
305
+ h += '<div class="cc-prompt">' + esc(row[txtCol]) + '</div>';
306
+ }
307
+ }
308
+ h += '<div class="cc-meta">';
309
+ currentFile.columns.forEach((col) => {
310
+ if (col.is_image) return;
311
+ const row = dataCache?.data?.find((_, ri) => dataCache.offset + ri === rowIdx);
312
+ const val = row ? row[col.name] : null;
313
+ if (val === null || val === undefined) return;
314
+ const s = String(val);
315
+ if (s.length > 200) return;
316
+ h += '<div class="cc-meta-row"><span class="cc-meta-key">' + esc(col.name) + '</span><span class="cc-meta-val">' + esc(s) + '</span></div>';
317
+ });
318
+ h += '</div></div>';
319
+ idx++;
320
+ }
321
+ content.innerHTML = h;
322
+ content.querySelectorAll('.cc-remove').forEach((btn) => {
323
+ btn.addEventListener('click', () => {
324
+ const r = parseInt(btn.dataset.row);
325
+ compareSet.delete(r);
326
+ updateCompareBadge();
327
+ renderCompare();
328
+ const card = document.querySelector('.card[data-row="' + r + '"]');
329
+ if (card) card.classList.remove('selected');
330
+ });
331
+ });
332
+ }
333
+
334
+ // ── Table ────────────────────────────────────────────────────────
335
+ async function loadTable() {
336
+ if (!currentFile) return;
337
+ showLoading();
338
+ try {
339
+ const limit = parseInt($('#sel-page-size').value);
340
+ const res = await fetch('/api/data/' + currentFile.id + '?offset=' + tableOffset + '&limit=' + limit);
341
+ if (!res.ok) throw new Error();
342
+ const data = await res.json();
343
+ renderTable(data);
344
+ } finally { hideLoading(); }
345
+ }
346
+
347
+ function renderTable(data) {
348
+ const limit = parseInt($('#sel-page-size').value);
349
+ const totalPages = Math.ceil(data.total / limit);
350
+ const page = Math.floor(data.offset / limit) + 1;
351
+ $('#table-page').textContent = page + '/' + totalPages + ' (' + fmtNum(data.total) + ')';
352
+ $('#table-prev').disabled = data.offset === 0;
353
+ $('#table-next').disabled = data.offset + limit >= data.total;
354
+
355
+ const imgCols = currentFile.columns.filter((c) => c.is_image).map((c) => c.name);
356
+ const cols = currentFile.columns.map((c) => c.name);
357
+ const fid = currentFile.id;
358
+
359
+ let h = '<table><thead><tr><th style="width:36px">#</th>';
360
+ cols.forEach((c) => { h += '<th>' + esc(c) + '</th>'; });
361
+ h += '</tr></thead><tbody>';
362
+
363
+ data.data.forEach((row, ri) => {
364
+ const rowIdx = data.offset + ri;
365
+ h += '<tr><td class="row-num">' + (rowIdx + 1) + '</td>';
366
+ cols.forEach((col) => {
367
+ const val = row[col];
368
+ if (val === null || val === undefined) {
369
+ h += '<td class="cell-null">—</td>';
370
+ } else if (typeof val === 'object' && val._type === 'image') {
371
+ if (imgCols.includes(col)) {
372
+ h += '<td><img class="cell-thumb" src="' + imgSrc(fid, rowIdx, col) + '" loading="lazy" data-row="' + rowIdx + '" data-col="' + col + '"></td>';
373
+ } else {
374
+ h += '<td class="cell-null">' + fmtSize(val.size) + '</td>';
375
+ }
376
+ } else if (typeof val === 'string' && val.length > 120) {
377
+ h += '<td title="' + esc(val) + '">' + esc(trunc(val, 120)) + '</td>';
378
+ } else {
379
+ h += '<td>' + esc(String(val)) + '</td>';
380
+ }
381
+ });
382
+ h += '</tr>';
383
+ });
384
+ h += '</tbody></table>';
385
+ $('#table-container').innerHTML = h;
386
+
387
+ $('#table-container').querySelectorAll('.cell-thumb').forEach((img) => {
388
+ img.addEventListener('click', () => {
389
+ const rowIdx = parseInt(img.dataset.row);
390
+ openDrawer(rowIdx);
391
+ });
392
+ });
393
+ }
394
+
395
+ $('#sel-page-size').addEventListener('change', () => { tableOffset = 0; loadTable(); });
396
+ $('#table-prev').addEventListener('click', () => { tableOffset = Math.max(0, tableOffset - parseInt($('#sel-page-size').value)); loadTable(); });
397
+ $('#table-next').addEventListener('click', () => { tableOffset += parseInt($('#sel-page-size').value); loadTable(); });
398
+
399
+ // ── Drawer ───────────────────────────────────────────────────────
400
+ function openDrawer(rowIdx) {
401
+ if (!currentFile || !dataCache) return;
402
+ const row = dataCache.data.find((_, ri) => dataCache.offset + ri === rowIdx);
403
+ if (!row) return;
404
+
405
+ drawerRowIdx = rowIdx;
406
+ const imgCol = $('#sel-img-col').value;
407
+ const txtCol = $('#sel-txt-col').value;
408
+ const fid = currentFile.id;
409
+
410
+ $('#drawer-title').textContent = 'Row ' + (rowIdx + 1);
411
+ $('#drawer-img').src = imgSrc(fid, rowIdx, imgCol);
412
+
413
+ const prompt = txtCol ? (row[txtCol] || '') : '';
414
+ $('#drawer-prompt').textContent = prompt || 'No prompt text';
415
+
416
+ let meta = '';
417
+ currentFile.columns.forEach((col) => {
418
+ if (col.is_image) return;
419
+ const val = row[col.name];
420
+ if (val === null || val === undefined) return;
421
+ meta += '<div class="drawer-meta-row"><span class="drawer-meta-key">' + esc(col.name) + '</span><span class="drawer-meta-val">' + esc(String(val)) + '</span></div>';
422
+ });
423
+ $('#drawer-meta').innerHTML = meta;
424
+ $('#drawer-meta-section').classList.toggle('hidden', !meta);
425
+
426
+ updateDrawerNav();
427
+ $('#drawer').classList.add('open');
428
+ $('#drawer-backdrop').classList.add('open');
429
+ highlightOpenCard();
430
+ }
431
+
432
+ function closeDrawer() {
433
+ drawerRowIdx = null;
434
+ $('#drawer').classList.remove('open');
435
+ $('#drawer-backdrop').classList.remove('open');
436
+ $$('.card.card-open').forEach((c) => c.classList.remove('card-open'));
437
+ }
438
+
439
+ function highlightOpenCard() {
440
+ $$('.card.card-open').forEach((c) => c.classList.remove('card-open'));
441
+ if (drawerRowIdx != null) {
442
+ const card = document.querySelector('.card[data-row="' + drawerRowIdx + '"]');
443
+ if (card) card.classList.add('card-open');
444
+ }
445
+ }
446
+
447
+ function updateDrawerNav() {
448
+ if (drawerRowIdx == null) return;
449
+ const idx = drawerNavList.indexOf(drawerRowIdx);
450
+ $('#drawer-prev').disabled = idx <= 0;
451
+ $('#drawer-next').disabled = idx < 0 || idx >= drawerNavList.length - 1;
452
+ }
453
+
454
+ function drawerNavigate(dir) {
455
+ if (drawerRowIdx == null) return;
456
+ const idx = drawerNavList.indexOf(drawerRowIdx);
457
+ const newIdx = idx + dir;
458
+ if (newIdx < 0 || newIdx >= drawerNavList.length) return;
459
+ openDrawer(drawerNavList[newIdx]);
460
+ }
461
+
462
+ $('#btn-close-drawer').addEventListener('click', closeDrawer);
463
+ $('#drawer-backdrop').addEventListener('click', closeDrawer);
464
+ $('#drawer-prev').addEventListener('click', () => drawerNavigate(-1));
465
+ $('#drawer-next').addEventListener('click', () => drawerNavigate(1));
466
+
467
+ $('#drawer-zoom').addEventListener('click', () => {
468
+ if (drawerRowIdx == null) return;
469
+ const imgCol = $('#sel-img-col').value;
470
+ openLightbox(imgSrc(currentFile.id, drawerRowIdx, imgCol));
471
+ });
472
+
473
+ $('#drawer-img').addEventListener('click', () => {
474
+ if (drawerRowIdx == null) return;
475
+ const imgCol = $('#sel-img-col').value;
476
+ openLightbox(imgSrc(currentFile.id, drawerRowIdx, imgCol));
477
+ });
478
+
479
+ // ── Lightbox ─────────────────────────────────────────────────────
480
+ const lightbox = $('#lightbox');
481
+ const lbImg = $('#lb-img');
482
+
483
+ function openLightbox(src) {
484
+ lbImg.src = src;
485
+ lightbox.classList.add('active');
486
+ }
487
+
488
+ function closeLightbox() {
489
+ lightbox.classList.remove('active');
490
+ }
491
+
492
+ lightbox.addEventListener('click', (e) => {
493
+ if (e.target === lightbox || e.target.classList.contains('lb-close')) closeLightbox();
494
+ });
495
+
496
+ // ── Keyboard shortcuts ───────────────────────────────────────────
497
+ document.addEventListener('keydown', (e) => {
498
+ if (lightbox.classList.contains('active')) {
499
+ if (e.key === 'Escape') closeLightbox();
500
+ return;
501
+ }
502
+ if ($('#drawer').classList.contains('open')) {
503
+ if (e.key === 'Escape') closeDrawer();
504
+ if (e.key === 'ArrowLeft') drawerNavigate(-1);
505
+ if (e.key === 'ArrowRight') drawerNavigate(1);
506
+ return;
507
+ }
508
+ });
509
+
510
+ // ── Init ─────────────────────────────────────────────────────────
511
+ $('#btn-open').addEventListener('click', () => {
512
+ const path = $('#file-path').value.trim();
513
+ if (path) openFile(path);
514
+ });
515
+ $('#file-path').addEventListener('keydown', (e) => {
516
+ if (e.key === 'Enter') {
517
+ const path = $('#file-path').value.trim();
518
+ if (path) openFile(path);
519
+ }
520
+ });
521
+
522
+ if (window.location.hash) {
523
+ const path = decodeURIComponent(window.location.hash.slice(1));
524
+ $('#file-path').value = path;
525
+ openFile(path);
526
+ }
527
+ })();
static/index.html ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>DataView</title>
7
+ <link rel="preconnect" href="https://fonts.googleapis.com">
8
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
9
+ <link href="https://fonts.googleapis.com/css2?family=DM+Sans:ital,wght@0,400;0,500;0,600;0,700;1,400&family=Newsreader:ital,opsz,wght@0,6..72,400;0,6..72,500;1,6..72,400&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
10
+ <link rel="stylesheet" href="/static/style.css">
11
+ </head>
12
+ <body>
13
+
14
+ <!-- Folder browser panel -->
15
+ <aside id="sidebar" class="sidebar">
16
+ <div class="sidebar-head">
17
+ <span class="sidebar-label">Browse files</span>
18
+ <button id="btn-close-sidebar" class="btn-icon" aria-label="Close">&times;</button>
19
+ </div>
20
+ <div id="breadcrumb" class="breadcrumb"></div>
21
+ <div id="folder-list" class="folder-list"></div>
22
+ </aside>
23
+ <div id="sidebar-backdrop" class="backdrop"></div>
24
+
25
+ <!-- Header -->
26
+ <header class="header">
27
+ <button id="btn-browse" class="header-btn" title="Browse folders">
28
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>
29
+ Browse
30
+ </button>
31
+ <div class="path-wrap">
32
+ <input id="file-path" type="text" placeholder="Paste a file path to open" spellcheck="false">
33
+ <button id="btn-open" class="path-open-btn">Open</button>
34
+ </div>
35
+ <span class="wordmark">data<span class="wordmark-accent">view</span></span>
36
+ </header>
37
+
38
+ <!-- Main content (hidden until file opened) -->
39
+ <main id="main" class="main hidden">
40
+
41
+ <!-- Toolbar -->
42
+ <div class="toolbar">
43
+ <div class="toolbar-left">
44
+ <span class="pill" id="pill-file"></span>
45
+ <span class="pill pill-accent" id="pill-rows"></span>
46
+ <span class="pill" id="pill-cols"></span>
47
+ </div>
48
+ <div class="toolbar-right">
49
+ <div class="search-box">
50
+ <svg class="search-icon" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="11" cy="11" r="7"/><line x1="16.5" y1="16.5" x2="21" y2="21"/></svg>
51
+ <input id="search-input" type="text" placeholder="Search prompts..." spellcheck="false">
52
+ <span id="search-count" class="search-count"></span>
53
+ </div>
54
+ <div class="view-switch">
55
+ <button class="vs-btn active" data-view="gallery" title="Gallery view">
56
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/></svg>
57
+ </button>
58
+ <button class="vs-btn" data-view="table" title="Table view">
59
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="9" y1="3" x2="9" y2="21"/></svg>
60
+ </button>
61
+ <button class="vs-btn" data-view="compare" title="Compare selected">
62
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="3" width="8" height="18" rx="1"/><rect x="14" y="3" width="8" height="18" rx="1"/></svg>
63
+ <span id="compare-badge" class="vs-badge hidden">0</span>
64
+ </button>
65
+ </div>
66
+ </div>
67
+ </div>
68
+
69
+ <!-- Gallery view -->
70
+ <section id="view-gallery" class="view">
71
+ <div class="gallery-toolbar">
72
+ <label class="gt-label">Image
73
+ <select id="sel-img-col" class="gt-select"></select>
74
+ </label>
75
+ <label class="gt-label">Caption
76
+ <select id="sel-txt-col" class="gt-select">
77
+ <option value="">None</option>
78
+ </select>
79
+ </label>
80
+ <label class="gt-label">Size
81
+ <select id="sel-thumb-size" class="gt-select">
82
+ <option value="160">S</option>
83
+ <option value="220" selected>M</option>
84
+ <option value="320">L</option>
85
+ </select>
86
+ </label>
87
+ <span class="gt-hint">Shift+click to select for compare</span>
88
+ <span class="spacer"></span>
89
+ <span id="gallery-page" class="page-label"></span>
90
+ <button id="gallery-prev" class="page-btn" disabled>
91
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="15 18 9 12 15 6"/></svg>
92
+ </button>
93
+ <button id="gallery-next" class="page-btn" disabled>
94
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="9 18 15 12 9 6"/></svg>
95
+ </button>
96
+ </div>
97
+ <div id="gallery-grid" class="gallery-grid"></div>
98
+ </section>
99
+
100
+ <!-- Table view -->
101
+ <section id="view-table" class="view hidden">
102
+ <div class="gallery-toolbar">
103
+ <label class="gt-label">Rows
104
+ <select id="sel-page-size" class="gt-select">
105
+ <option value="25">25</option>
106
+ <option value="50" selected>50</option>
107
+ <option value="100">100</option>
108
+ </select>
109
+ </label>
110
+ <span class="spacer"></span>
111
+ <span id="table-page" class="page-label"></span>
112
+ <button id="table-prev" class="page-btn" disabled>
113
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="15 18 9 12 15 6"/></svg>
114
+ </button>
115
+ <button id="table-next" class="page-btn" disabled>
116
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="9 18 15 12 9 6"/></svg>
117
+ </button>
118
+ </div>
119
+ <div id="table-container" class="table-wrap"></div>
120
+ </section>
121
+
122
+ <!-- Compare view -->
123
+ <section id="view-compare" class="view hidden">
124
+ <div id="compare-empty" class="empty-state">
125
+ <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="2" y="3" width="8" height="18" rx="1"/><rect x="14" y="3" width="8" height="18" rx="1"/></svg>
126
+ <p>Select images to compare</p>
127
+ <p class="empty-hint">Shift+click images in the gallery, then return here</p>
128
+ </div>
129
+ <div id="compare-content" class="compare-grid hidden"></div>
130
+ </section>
131
+ </main>
132
+
133
+ <!-- Welcome -->
134
+ <div id="welcome" class="welcome">
135
+ <div class="welcome-inner">
136
+ <div class="welcome-icon">
137
+ <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/></svg>
138
+ </div>
139
+ <h2>Open a dataset</h2>
140
+ <p>Browse or paste a <code>.parquet</code> file path to begin exploring.</p>
141
+ </div>
142
+ </div>
143
+
144
+ <!-- Detail drawer -->
145
+ <aside id="drawer" class="drawer">
146
+ <div class="drawer-head">
147
+ <span id="drawer-title" class="drawer-title"></span>
148
+ <div class="drawer-head-actions">
149
+ <button id="drawer-prev" class="drawer-nav-btn" title="Previous">
150
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="15 18 9 12 15 6"/></svg>
151
+ </button>
152
+ <button id="drawer-next" class="drawer-nav-btn" title="Next">
153
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="9 18 15 12 9 6"/></svg>
154
+ </button>
155
+ <button id="drawer-zoom" class="drawer-nav-btn" title="Fullscreen">
156
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/></svg>
157
+ </button>
158
+ <button id="btn-close-drawer" class="drawer-close" title="Close">&times;</button>
159
+ </div>
160
+ </div>
161
+ <div class="drawer-body">
162
+ <div class="drawer-image-wrap">
163
+ <img id="drawer-img" class="drawer-image" alt="">
164
+ </div>
165
+ <div class="drawer-content">
166
+ <div class="drawer-section">
167
+ <span class="drawer-section-label">Prompt</span>
168
+ <p id="drawer-prompt" class="drawer-prompt"></p>
169
+ </div>
170
+ <div class="drawer-section" id="drawer-meta-section">
171
+ <span class="drawer-section-label">Metadata</span>
172
+ <div id="drawer-meta" class="drawer-meta"></div>
173
+ </div>
174
+ </div>
175
+ </div>
176
+ </aside>
177
+ <div id="drawer-backdrop" class="backdrop"></div>
178
+
179
+ <!-- Loading -->
180
+ <div id="loading" class="loading hidden">
181
+ <div class="spinner"></div>
182
+ </div>
183
+
184
+ <!-- Lightbox (fullscreen image) -->
185
+ <div id="lightbox" class="lightbox">
186
+ <img id="lb-img" alt="">
187
+ <button class="lb-close" aria-label="Close">&times;</button>
188
+ </div>
189
+
190
+ <script src="/static/app.js"></script>
191
+ </body>
192
+ </html>
static/style.css ADDED
@@ -0,0 +1,871 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ═══════════════════════════════════════════════════════════════════════
2
+ DataView — "Light Table"
3
+ A dataset explorer for AI image-prompt pairs.
4
+ Warm parchment palette, editorial typography, image-forward cards.
5
+ ═══════════════════════════════════════════════════════════════════════ */
6
+
7
+ :root {
8
+ --bg: #F7F4EE;
9
+ --surface: #FFFFFF;
10
+ --surface-raised: #FDFCFA;
11
+ --border: #E6E0D6;
12
+ --border-light: #EFE9DF;
13
+ --text: #2D2A26;
14
+ --text-secondary: #8C8478;
15
+ --text-tertiary: #B5AEA4;
16
+ --accent: #8B5C3C;
17
+ --accent-hover: #A06A45;
18
+ --accent-soft: #F0E6DA;
19
+ --accent-softer: #F8F2EB;
20
+ --danger: #B54A4A;
21
+ --sans: 'DM Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
22
+ --serif: 'Newsreader', Georgia, 'Times New Roman', serif;
23
+ --mono: 'JetBrains Mono', 'SF Mono', 'Fira Code', monospace;
24
+ --radius: 8px;
25
+ --radius-sm: 5px;
26
+ --drawer-w: 480px;
27
+ --shadow-sm: 0 1px 3px rgba(45,42,38,0.06);
28
+ --shadow-md: 0 4px 16px rgba(45,42,38,0.08);
29
+ --shadow-lg: 0 8px 32px rgba(45,42,38,0.12);
30
+ --transition: 180ms ease;
31
+ }
32
+
33
+ *, *::before, *::after { margin: 0; padding: 0; box-sizing: border-box; }
34
+
35
+ body {
36
+ font-family: var(--sans);
37
+ background: var(--bg);
38
+ color: var(--text);
39
+ min-height: 100vh;
40
+ -webkit-font-smoothing: antialiased;
41
+ -moz-osx-font-smoothing: grayscale;
42
+ }
43
+
44
+ ::-webkit-scrollbar { width: 5px; height: 5px; }
45
+ ::-webkit-scrollbar-track { background: transparent; }
46
+ ::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; }
47
+ ::-webkit-scrollbar-thumb:hover { background: var(--text-tertiary); }
48
+
49
+ .hidden { display: none !important; }
50
+ .spacer { flex: 1; }
51
+
52
+ /* ── Header ───────────────────────────────────────────────────────── */
53
+ .header {
54
+ display: flex;
55
+ align-items: center;
56
+ gap: 10px;
57
+ padding: 10px 20px;
58
+ background: var(--surface);
59
+ border-bottom: 1px solid var(--border);
60
+ position: sticky;
61
+ top: 0;
62
+ z-index: 100;
63
+ }
64
+
65
+ .header-btn {
66
+ display: flex;
67
+ align-items: center;
68
+ gap: 5px;
69
+ padding: 6px 12px;
70
+ background: var(--bg);
71
+ color: var(--text-secondary);
72
+ border: 1px solid var(--border);
73
+ border-radius: var(--radius-sm);
74
+ cursor: pointer;
75
+ font-size: 12.5px;
76
+ font-family: var(--sans);
77
+ font-weight: 500;
78
+ transition: all var(--transition);
79
+ white-space: nowrap;
80
+ }
81
+ .header-btn:hover { color: var(--text); border-color: var(--text-tertiary); background: var(--surface); }
82
+
83
+ .path-wrap {
84
+ flex: 1;
85
+ display: flex;
86
+ max-width: 640px;
87
+ position: relative;
88
+ }
89
+
90
+ .path-wrap input {
91
+ width: 100%;
92
+ padding: 6px 60px 6px 10px;
93
+ background: var(--bg);
94
+ border: 1px solid var(--border);
95
+ border-radius: var(--radius-sm);
96
+ color: var(--text);
97
+ font-family: var(--mono);
98
+ font-size: 12px;
99
+ outline: none;
100
+ transition: border-color var(--transition);
101
+ }
102
+ .path-wrap input:focus { border-color: var(--accent); }
103
+ .path-wrap input::placeholder { color: var(--text-tertiary); }
104
+
105
+ .path-open-btn {
106
+ position: absolute;
107
+ right: 1px; top: 1px; bottom: 1px;
108
+ padding: 0 14px;
109
+ background: var(--accent);
110
+ color: #fff;
111
+ border: none;
112
+ border-radius: 0 var(--radius-sm) var(--radius-sm) 0;
113
+ cursor: pointer;
114
+ font-size: 12px;
115
+ font-weight: 600;
116
+ font-family: var(--sans);
117
+ transition: background var(--transition);
118
+ }
119
+ .path-open-btn:hover { background: var(--accent-hover); }
120
+
121
+ .wordmark {
122
+ font-family: var(--mono);
123
+ font-size: 13px;
124
+ font-weight: 500;
125
+ color: var(--text-tertiary);
126
+ letter-spacing: -0.3px;
127
+ flex-shrink: 0;
128
+ }
129
+ .wordmark-accent { color: var(--accent); }
130
+
131
+ /* ── Toolbar ──────────────────────────────────────────────────────── */
132
+ .toolbar {
133
+ display: flex;
134
+ align-items: center;
135
+ justify-content: space-between;
136
+ gap: 12px;
137
+ padding: 8px 20px;
138
+ background: var(--surface);
139
+ border-bottom: 1px solid var(--border);
140
+ flex-wrap: wrap;
141
+ }
142
+
143
+ .toolbar-left, .toolbar-right { display: flex; align-items: center; gap: 6px; }
144
+
145
+ .pill {
146
+ display: inline-flex;
147
+ align-items: center;
148
+ padding: 2px 10px;
149
+ background: var(--bg);
150
+ border: 1px solid var(--border);
151
+ border-radius: 100px;
152
+ font-size: 11px;
153
+ font-family: var(--mono);
154
+ color: var(--text-secondary);
155
+ white-space: nowrap;
156
+ line-height: 1.6;
157
+ }
158
+ .pill-accent { color: var(--accent); border-color: var(--accent-soft); background: var(--accent-softer); font-weight: 500; }
159
+
160
+ .search-box {
161
+ display: flex;
162
+ align-items: center;
163
+ gap: 6px;
164
+ background: var(--bg);
165
+ border: 1px solid var(--border);
166
+ border-radius: var(--radius-sm);
167
+ padding: 0 8px;
168
+ transition: border-color var(--transition);
169
+ }
170
+ .search-box:focus-within { border-color: var(--accent); }
171
+
172
+ .search-icon { color: var(--text-tertiary); flex-shrink: 0; }
173
+
174
+ #search-input {
175
+ background: none;
176
+ border: none;
177
+ color: var(--text);
178
+ font-family: var(--mono);
179
+ font-size: 12px;
180
+ padding: 5px 0;
181
+ outline: none;
182
+ width: 160px;
183
+ }
184
+ #search-input::placeholder { color: var(--text-tertiary); }
185
+
186
+ .search-count {
187
+ font-size: 10px;
188
+ font-family: var(--mono);
189
+ color: var(--text-tertiary);
190
+ }
191
+
192
+ .view-switch {
193
+ display: flex;
194
+ gap: 2px;
195
+ background: var(--bg);
196
+ border: 1px solid var(--border);
197
+ border-radius: var(--radius-sm);
198
+ padding: 2px;
199
+ }
200
+
201
+ .vs-btn {
202
+ display: flex;
203
+ align-items: center;
204
+ justify-content: center;
205
+ gap: 4px;
206
+ padding: 5px 8px;
207
+ background: none;
208
+ border: none;
209
+ border-radius: 3px;
210
+ color: var(--text-tertiary);
211
+ cursor: pointer;
212
+ transition: all var(--transition);
213
+ position: relative;
214
+ }
215
+ .vs-btn:hover { color: var(--text-secondary); }
216
+ .vs-btn.active { color: var(--accent); background: var(--surface); box-shadow: var(--shadow-sm); }
217
+
218
+ .vs-badge {
219
+ background: var(--accent);
220
+ color: #fff;
221
+ font-size: 9px;
222
+ font-weight: 600;
223
+ font-family: var(--mono);
224
+ padding: 0 4px;
225
+ border-radius: 6px;
226
+ min-width: 14px;
227
+ text-align: center;
228
+ line-height: 16px;
229
+ }
230
+
231
+ /* ── Main ─────────────────────────────────────────────────────────── */
232
+ .main { display: flex; flex-direction: column; height: calc(100vh - 93px); }
233
+ .view { flex: 1; overflow: auto; }
234
+
235
+ .gallery-toolbar {
236
+ display: flex;
237
+ align-items: center;
238
+ gap: 10px;
239
+ padding: 6px 20px;
240
+ border-bottom: 1px solid var(--border-light);
241
+ background: var(--surface-raised);
242
+ position: sticky;
243
+ top: 0;
244
+ z-index: 10;
245
+ }
246
+
247
+ .gt-label {
248
+ display: flex;
249
+ align-items: center;
250
+ gap: 5px;
251
+ font-size: 11px;
252
+ color: var(--text-secondary);
253
+ font-weight: 500;
254
+ }
255
+
256
+ .gt-select {
257
+ background: var(--surface);
258
+ color: var(--text);
259
+ border: 1px solid var(--border);
260
+ padding: 3px 6px;
261
+ border-radius: var(--radius-sm);
262
+ font-size: 12px;
263
+ font-family: var(--mono);
264
+ cursor: pointer;
265
+ }
266
+
267
+ .gt-hint {
268
+ font-size: 10.5px;
269
+ color: var(--text-tertiary);
270
+ font-style: italic;
271
+ }
272
+
273
+ .page-label {
274
+ font-size: 11px;
275
+ font-family: var(--mono);
276
+ color: var(--text-secondary);
277
+ }
278
+
279
+ .page-btn {
280
+ display: inline-flex;
281
+ align-items: center;
282
+ justify-content: center;
283
+ width: 26px;
284
+ height: 26px;
285
+ background: var(--surface);
286
+ color: var(--text-secondary);
287
+ border: 1px solid var(--border);
288
+ border-radius: var(--radius-sm);
289
+ cursor: pointer;
290
+ transition: all var(--transition);
291
+ }
292
+ .page-btn:hover:not(:disabled) { color: var(--text); border-color: var(--text-tertiary); }
293
+ .page-btn:disabled { opacity: 0.3; cursor: default; }
294
+
295
+ /* ── Gallery ──────────────────────────────────────────────────────── */
296
+ .gallery-grid {
297
+ display: grid;
298
+ grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
299
+ gap: 12px;
300
+ padding: 16px 20px;
301
+ }
302
+
303
+ .card {
304
+ position: relative;
305
+ background: var(--surface);
306
+ border: 1px solid var(--border);
307
+ border-radius: var(--radius);
308
+ overflow: hidden;
309
+ cursor: pointer;
310
+ transition: border-color var(--transition), box-shadow var(--transition), transform var(--transition);
311
+ }
312
+ .card:hover { border-color: var(--text-tertiary); box-shadow: var(--shadow-md); transform: translateY(-1px); }
313
+ .card.selected { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent), var(--shadow-md); }
314
+ .card.card-open { border-color: var(--accent); background: var(--accent-softer); }
315
+
316
+ .card-img {
317
+ width: 100%;
318
+ aspect-ratio: 1;
319
+ object-fit: cover;
320
+ display: block;
321
+ background: var(--bg);
322
+ }
323
+
324
+ .card-row {
325
+ position: absolute;
326
+ top: 6px;
327
+ left: 6px;
328
+ background: rgba(255,255,255,0.92);
329
+ backdrop-filter: blur(6px);
330
+ color: var(--text-secondary);
331
+ padding: 1px 6px;
332
+ border-radius: 3px;
333
+ font-size: 10px;
334
+ font-family: var(--mono);
335
+ font-weight: 500;
336
+ pointer-events: none;
337
+ }
338
+
339
+ .card-dims {
340
+ position: absolute;
341
+ bottom: 6px;
342
+ right: 6px;
343
+ background: rgba(255,255,255,0.92);
344
+ backdrop-filter: blur(6px);
345
+ color: var(--text-tertiary);
346
+ padding: 1px 6px;
347
+ border-radius: 3px;
348
+ font-size: 9px;
349
+ font-family: var(--mono);
350
+ pointer-events: none;
351
+ }
352
+
353
+ .card-check {
354
+ position: absolute;
355
+ top: 6px;
356
+ right: 6px;
357
+ width: 20px;
358
+ height: 20px;
359
+ border-radius: 50%;
360
+ background: var(--accent);
361
+ color: #fff;
362
+ display: none;
363
+ align-items: center;
364
+ justify-content: center;
365
+ font-size: 11px;
366
+ font-weight: 700;
367
+ pointer-events: none;
368
+ box-shadow: var(--shadow-sm);
369
+ }
370
+ .card.selected .card-check { display: flex; }
371
+
372
+ .card-caption {
373
+ padding: 8px 10px;
374
+ font-size: 12px;
375
+ font-family: var(--serif);
376
+ color: var(--text-secondary);
377
+ line-height: 1.45;
378
+ max-height: 60px;
379
+ overflow: hidden;
380
+ border-top: 1px solid var(--border-light);
381
+ }
382
+
383
+ /* ── Table ────────────────────────────────────────────────────────── */
384
+ .table-wrap {
385
+ overflow: auto;
386
+ flex: 1;
387
+ }
388
+
389
+ .table-wrap table {
390
+ width: 100%;
391
+ border-collapse: collapse;
392
+ font-size: 12px;
393
+ font-family: var(--mono);
394
+ }
395
+
396
+ .table-wrap th {
397
+ padding: 7px 12px;
398
+ background: var(--surface);
399
+ color: var(--text-secondary);
400
+ font-weight: 500;
401
+ text-align: left;
402
+ border-bottom: 1px solid var(--border);
403
+ position: sticky;
404
+ top: 0;
405
+ z-index: 5;
406
+ white-space: nowrap;
407
+ text-transform: uppercase;
408
+ font-size: 10px;
409
+ letter-spacing: 0.4px;
410
+ }
411
+
412
+ .table-wrap td {
413
+ padding: 5px 12px;
414
+ border-bottom: 1px solid var(--border-light);
415
+ max-width: 360px;
416
+ overflow: hidden;
417
+ text-overflow: ellipsis;
418
+ white-space: nowrap;
419
+ vertical-align: middle;
420
+ }
421
+
422
+ .table-wrap tbody tr:hover td { background: var(--accent-softer); }
423
+ .table-wrap .cell-null { color: var(--text-tertiary); }
424
+ .table-wrap .row-num { color: var(--text-tertiary); font-size: 10px; user-select: none; }
425
+
426
+ .cell-thumb {
427
+ width: 36px;
428
+ height: 36px;
429
+ object-fit: cover;
430
+ border-radius: 3px;
431
+ display: block;
432
+ cursor: pointer;
433
+ border: 1px solid var(--border);
434
+ transition: transform var(--transition);
435
+ }
436
+ .cell-thumb:hover { transform: scale(1.12); }
437
+
438
+ /* ── Compare ──────────────────────────────────────────────────────── */
439
+ .empty-state {
440
+ display: flex;
441
+ flex-direction: column;
442
+ align-items: center;
443
+ justify-content: center;
444
+ height: 55vh;
445
+ color: var(--text-tertiary);
446
+ gap: 10px;
447
+ text-align: center;
448
+ }
449
+ .empty-state p { font-size: 13px; color: var(--text-secondary); }
450
+ .empty-hint { font-size: 11.5px !important; color: var(--text-tertiary) !important; }
451
+
452
+ .compare-grid {
453
+ display: grid;
454
+ grid-template-columns: repeat(auto-fit, minmax(380px, 1fr));
455
+ gap: 16px;
456
+ padding: 20px;
457
+ align-items: start;
458
+ }
459
+
460
+ .compare-card {
461
+ background: var(--surface);
462
+ border: 1px solid var(--border);
463
+ border-radius: var(--radius);
464
+ overflow: hidden;
465
+ }
466
+
467
+ .cc-head {
468
+ display: flex;
469
+ align-items: center;
470
+ justify-content: space-between;
471
+ padding: 8px 12px;
472
+ border-bottom: 1px solid var(--border-light);
473
+ }
474
+
475
+ .cc-label {
476
+ font-size: 11px;
477
+ font-weight: 600;
478
+ text-transform: uppercase;
479
+ letter-spacing: 0.4px;
480
+ color: var(--accent);
481
+ font-family: var(--mono);
482
+ }
483
+
484
+ .cc-remove {
485
+ background: none;
486
+ border: none;
487
+ color: var(--text-tertiary);
488
+ cursor: pointer;
489
+ font-size: 16px;
490
+ padding: 2px 6px;
491
+ border-radius: 3px;
492
+ line-height: 1;
493
+ }
494
+ .cc-remove:hover { color: var(--danger); background: rgba(181,74,74,0.06); }
495
+
496
+ .compare-card img {
497
+ width: 100%;
498
+ max-height: 45vh;
499
+ object-fit: contain;
500
+ display: block;
501
+ background: var(--bg);
502
+ cursor: zoom-in;
503
+ }
504
+
505
+ .cc-prompt {
506
+ padding: 12px 14px;
507
+ font-family: var(--serif);
508
+ font-size: 13.5px;
509
+ line-height: 1.55;
510
+ color: var(--text);
511
+ border-top: 1px solid var(--border-light);
512
+ max-height: 140px;
513
+ overflow-y: auto;
514
+ }
515
+
516
+ .cc-meta {
517
+ padding: 8px 14px 12px;
518
+ border-top: 1px solid var(--border-light);
519
+ }
520
+
521
+ .cc-meta-row {
522
+ display: flex;
523
+ gap: 8px;
524
+ font-size: 11px;
525
+ line-height: 1.6;
526
+ }
527
+ .cc-meta-key { color: var(--text-tertiary); font-family: var(--mono); font-size: 10px; min-width: 80px; flex-shrink: 0; }
528
+ .cc-meta-val { color: var(--text-secondary); font-family: var(--mono); font-size: 10px; word-break: break-all; }
529
+
530
+ /* ── Drawer ───────────────────────────────────────────────────────── */
531
+ .drawer {
532
+ position: fixed;
533
+ top: 0;
534
+ right: 0;
535
+ bottom: 0;
536
+ width: var(--drawer-w);
537
+ background: var(--surface);
538
+ border-left: 1px solid var(--border);
539
+ z-index: 200;
540
+ display: flex;
541
+ flex-direction: column;
542
+ transform: translateX(100%);
543
+ transition: transform 250ms cubic-bezier(0.4, 0, 0.2, 1);
544
+ box-shadow: -4px 0 24px rgba(45,42,38,0.06);
545
+ }
546
+ .drawer.open { transform: translateX(0); }
547
+
548
+ .drawer-head {
549
+ display: flex;
550
+ align-items: center;
551
+ justify-content: space-between;
552
+ padding: 10px 16px;
553
+ border-bottom: 1px solid var(--border);
554
+ flex-shrink: 0;
555
+ }
556
+
557
+ .drawer-title {
558
+ font-size: 12px;
559
+ font-family: var(--mono);
560
+ font-weight: 500;
561
+ color: var(--text-secondary);
562
+ }
563
+
564
+ .drawer-head-actions {
565
+ display: flex;
566
+ align-items: center;
567
+ gap: 4px;
568
+ }
569
+
570
+ .drawer-nav-btn {
571
+ display: flex;
572
+ align-items: center;
573
+ justify-content: center;
574
+ width: 26px;
575
+ height: 26px;
576
+ background: none;
577
+ border: 1px solid transparent;
578
+ border-radius: var(--radius-sm);
579
+ color: var(--text-tertiary);
580
+ cursor: pointer;
581
+ transition: all var(--transition);
582
+ }
583
+ .drawer-nav-btn:hover { color: var(--text); background: var(--bg); border-color: var(--border); }
584
+
585
+ .drawer-close {
586
+ display: flex;
587
+ align-items: center;
588
+ justify-content: center;
589
+ width: 26px;
590
+ height: 26px;
591
+ background: none;
592
+ border: none;
593
+ border-radius: var(--radius-sm);
594
+ color: var(--text-tertiary);
595
+ cursor: pointer;
596
+ font-size: 18px;
597
+ transition: all var(--transition);
598
+ margin-left: 2px;
599
+ }
600
+ .drawer-close:hover { color: var(--text); background: var(--bg); }
601
+
602
+ .drawer-body {
603
+ display: flex;
604
+ flex-direction: column;
605
+ height: calc(100vh - 45px);
606
+ overflow: hidden;
607
+ }
608
+
609
+ .drawer-image-wrap {
610
+ flex-shrink: 0;
611
+ background: var(--bg);
612
+ display: flex;
613
+ align-items: center;
614
+ justify-content: center;
615
+ max-height: 50vh;
616
+ overflow: hidden;
617
+ border-bottom: 1px solid var(--border-light);
618
+ }
619
+
620
+ .drawer-image {
621
+ max-width: 100%;
622
+ max-height: 50vh;
623
+ object-fit: contain;
624
+ display: block;
625
+ cursor: zoom-in;
626
+ }
627
+
628
+ .drawer-content {
629
+ flex: 1;
630
+ overflow-y: auto;
631
+ padding: 16px;
632
+ display: flex;
633
+ flex-direction: column;
634
+ gap: 20px;
635
+ }
636
+
637
+ .drawer-section-label {
638
+ display: block;
639
+ font-size: 10px;
640
+ font-family: var(--mono);
641
+ font-weight: 500;
642
+ text-transform: uppercase;
643
+ letter-spacing: 0.5px;
644
+ color: var(--text-tertiary);
645
+ margin-bottom: 6px;
646
+ }
647
+
648
+ .drawer-prompt {
649
+ font-family: var(--serif);
650
+ font-size: 14.5px;
651
+ line-height: 1.6;
652
+ color: var(--text);
653
+ }
654
+
655
+ .drawer-meta {
656
+ display: flex;
657
+ flex-direction: column;
658
+ gap: 1px;
659
+ }
660
+
661
+ .drawer-meta-row {
662
+ display: flex;
663
+ gap: 10px;
664
+ font-size: 12px;
665
+ line-height: 1.7;
666
+ padding: 2px 0;
667
+ border-bottom: 1px solid var(--border-light);
668
+ }
669
+ .drawer-meta-row:last-child { border-bottom: none; }
670
+ .drawer-meta-key { color: var(--text-tertiary); font-family: var(--mono); font-size: 11px; min-width: 90px; flex-shrink: 0; }
671
+ .drawer-meta-val { color: var(--text-secondary); font-family: var(--mono); font-size: 11px; word-break: break-all; }
672
+
673
+ /* ── Sidebar ──────────────────────────────────────────────────────── */
674
+ .sidebar {
675
+ position: fixed;
676
+ left: 0; top: 0; bottom: 0;
677
+ width: 340px;
678
+ background: var(--surface);
679
+ border-right: 1px solid var(--border);
680
+ z-index: 200;
681
+ display: flex;
682
+ flex-direction: column;
683
+ transform: translateX(-100%);
684
+ transition: transform 0.22s ease;
685
+ }
686
+ .sidebar.open { transform: translateX(0); }
687
+
688
+ .backdrop {
689
+ position: fixed;
690
+ inset: 0;
691
+ background: rgba(45,42,38,0.18);
692
+ z-index: 199;
693
+ display: none;
694
+ backdrop-filter: blur(1px);
695
+ }
696
+ .backdrop.open { display: block; }
697
+
698
+ .sidebar-head {
699
+ display: flex;
700
+ align-items: center;
701
+ justify-content: space-between;
702
+ padding: 10px 14px;
703
+ border-bottom: 1px solid var(--border);
704
+ }
705
+
706
+ .sidebar-label {
707
+ font-size: 11.5px;
708
+ font-weight: 600;
709
+ color: var(--text-secondary);
710
+ }
711
+
712
+ .btn-icon {
713
+ display: flex;
714
+ align-items: center;
715
+ justify-content: center;
716
+ width: 26px;
717
+ height: 26px;
718
+ background: none;
719
+ border: 1px solid transparent;
720
+ border-radius: var(--radius-sm);
721
+ color: var(--text-tertiary);
722
+ cursor: pointer;
723
+ font-size: 18px;
724
+ }
725
+ .btn-icon:hover { color: var(--text); background: var(--bg); border-color: var(--border); }
726
+
727
+ .breadcrumb {
728
+ display: flex;
729
+ align-items: center;
730
+ gap: 2px;
731
+ padding: 6px 14px;
732
+ font-size: 11px;
733
+ font-family: var(--mono);
734
+ color: var(--text-secondary);
735
+ border-bottom: 1px solid var(--border-light);
736
+ overflow-x: auto;
737
+ white-space: nowrap;
738
+ flex-shrink: 0;
739
+ }
740
+
741
+ .breadcrumb-item { cursor: pointer; padding: 2px 4px; border-radius: 3px; }
742
+ .breadcrumb-item:hover { background: var(--bg); color: var(--text); }
743
+ .breadcrumb-sep { color: var(--text-tertiary); margin: 0 1px; }
744
+
745
+ .folder-list { flex: 1; overflow-y: auto; padding: 4px 0; }
746
+
747
+ .folder-entry {
748
+ display: flex;
749
+ align-items: center;
750
+ gap: 8px;
751
+ padding: 5px 14px;
752
+ cursor: pointer;
753
+ transition: background var(--transition);
754
+ }
755
+ .folder-entry:hover { background: var(--bg); }
756
+
757
+ .folder-entry .fe-icon { width: 16px; text-align: center; flex-shrink: 0; font-size: 13px; }
758
+ .folder-entry .fe-name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: var(--mono); font-size: 12px; }
759
+ .folder-entry .fe-meta { font-size: 10px; font-family: var(--mono); color: var(--text-tertiary); flex-shrink: 0; }
760
+
761
+ .folder-entry.is-dir .fe-name { color: var(--text); }
762
+ .folder-entry.is-dataset .fe-name { color: var(--accent); font-weight: 500; }
763
+ .folder-entry.is-file .fe-name { color: var(--text-secondary); }
764
+ .folder-entry.is-dataset .fe-icon { color: var(--accent); }
765
+ .folder-entry.is-dir .fe-icon { color: var(--text-secondary); }
766
+ .folder-entry.is-file .fe-icon { color: var(--text-tertiary); }
767
+ .folder-entry.is-parent { color: var(--text-secondary); border-bottom: 1px solid var(--border-light); margin-bottom: 4px; }
768
+ .folder-entry.is-parent .fe-icon { color: var(--text-tertiary); }
769
+
770
+ /* ── Welcome ──────────────────────────────────────────────────────── */
771
+ .welcome {
772
+ display: flex;
773
+ justify-content: center;
774
+ align-items: center;
775
+ min-height: calc(100vh - 52px);
776
+ padding: 40px 20px;
777
+ }
778
+ .welcome-inner { text-align: center; }
779
+ .welcome-icon { color: var(--text-tertiary); margin-bottom: 16px; opacity: 0.35; }
780
+ .welcome-inner h2 { font-size: 20px; font-weight: 600; color: var(--text); margin-bottom: 6px; }
781
+ .welcome-inner p { font-size: 14px; color: var(--text-secondary); }
782
+ .welcome-inner code {
783
+ padding: 1px 5px;
784
+ background: var(--bg);
785
+ border: 1px solid var(--border);
786
+ border-radius: 3px;
787
+ font-family: var(--mono);
788
+ font-size: 12px;
789
+ color: var(--text-secondary);
790
+ }
791
+
792
+ /* ── Lightbox ─────────────────────────────────────────────────────── */
793
+ .lightbox {
794
+ display: none;
795
+ position: fixed;
796
+ inset: 0;
797
+ background: rgba(45,42,38,0.92);
798
+ z-index: 300;
799
+ justify-content: center;
800
+ align-items: center;
801
+ cursor: zoom-out;
802
+ backdrop-filter: blur(4px);
803
+ }
804
+ .lightbox.active { display: flex; }
805
+
806
+ .lightbox img {
807
+ max-width: 92vw;
808
+ max-height: 92vh;
809
+ object-fit: contain;
810
+ border-radius: var(--radius);
811
+ box-shadow: 0 12px 48px rgba(0,0,0,0.25);
812
+ }
813
+
814
+ .lb-close {
815
+ position: absolute;
816
+ top: 14px;
817
+ right: 14px;
818
+ width: 34px;
819
+ height: 34px;
820
+ background: rgba(255,255,255,0.1);
821
+ border: 1px solid rgba(255,255,255,0.15);
822
+ border-radius: 50%;
823
+ color: rgba(255,255,255,0.7);
824
+ font-size: 18px;
825
+ cursor: pointer;
826
+ display: flex;
827
+ align-items: center;
828
+ justify-content: center;
829
+ transition: all var(--transition);
830
+ backdrop-filter: blur(8px);
831
+ }
832
+ .lb-close:hover { background: rgba(255,255,255,0.18); color: #fff; }
833
+
834
+ /* ── Loading ──────────────────────────────────────────────────────── */
835
+ .loading {
836
+ position: fixed;
837
+ inset: 0;
838
+ background: rgba(247,244,238,0.6);
839
+ display: flex;
840
+ justify-content: center;
841
+ align-items: center;
842
+ z-index: 400;
843
+ backdrop-filter: blur(2px);
844
+ }
845
+
846
+ .spinner {
847
+ width: 24px;
848
+ height: 24px;
849
+ border: 2px solid var(--border);
850
+ border-top-color: var(--accent);
851
+ border-radius: 50%;
852
+ animation: spin 0.65s linear infinite;
853
+ }
854
+
855
+ @keyframes spin { to { transform: rotate(360deg); } }
856
+
857
+ /* ── Responsive ───────────────────────────────────────────────────── */
858
+ @media (max-width: 768px) {
859
+ .sidebar { width: 100%; }
860
+ .gallery-grid { grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 8px; padding: 12px; }
861
+ .compare-grid { grid-template-columns: 1fr; }
862
+ .drawer { width: 100%; }
863
+ .toolbar { padding: 6px 12px; }
864
+ .gallery-toolbar { padding: 6px 12px; }
865
+ .gt-hint { display: none; }
866
+ #search-input { width: 120px; }
867
+ }
868
+
869
+ @media (prefers-reduced-motion: reduce) {
870
+ *, *::before, *::after { transition-duration: 0ms !important; animation-duration: 0ms !important; }
871
+ }