File size: 7,677 Bytes
4655dd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# Safetensors Studio & Bench

> **Run, test, and benchmark local Safetensors models with surgical VRAM observability.**

[![Next.js](https://img.shields.io/badge/Next.js-14-black?logo=next.js)](https://nextjs.org/)
[![FastAPI](https://img.shields.io/badge/FastAPI-0.110-009688?logo=fastapi)](https://fastapi.tiangolo.com/)
[![Python](https://img.shields.io/badge/Python-3.12-3776AB?logo=python)](https://www.python.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](./LICENSE)
[![Hugging Face](https://img.shields.io/badge/🤗-Hugging%20Face-FFD21E)](./docs/HUGGINGFACE.md)

**Safetensors Studio & Bench** is a full-stack, local-first platform to **load any `*.safetensors` + `config.json` + `tokenizer.json` folder, stream chat with real TPS/TTFT, run automated benchmarks (Reasoning/Coding/Arabic/Summarization), and profile GPU/CPU/RAM live** — no cloud required.

📖 **Arabic README:** [`README_AR.md`](./README_AR.md) | 📚 **Docs:** [`docs/`](./docs/) | 🤝 **Contribute:** [`CONTRIBUTING.md`](./CONTRIBUTING.md)

---

## ✨ Key Features

| Area | What you get |
|------|--------------|
| **Safetensors Loader** | Local folder picker • `Float16 / Bfloat16 / Float32``4-bit NF4 / 8-bit` via `bitsandbytes``device_map: auto / balanced / cpu / cuda:0` + offloading |
| **Live Playground** | Token Streaming (SSE) • Real `Tokens/sec` & `TTFT` • Temperature / Top-P / Max Tokens • Copy & clear |
| **Automated Benchmark** | 15 preset tasks: Reasoning (4), Coding (4), Arabic Quality (4), Summarization (3) • `Exact / Regex / LLM-as-Judge`**Custom datasets:** drop any folder with `.csv/.json/.jsonl/.txt/.md` → auto-detects language (Arabic/English) & category |
| **Hardware Profiling** | `pynvml + psutil` → live VRAM/CPU/RAM/Power via `Recharts` • VRAM peak timeline • TPS vs VRAM scatter • 600-point history |
| **Reports & Sharing** | Export `PDF (Arabic-capable)` / `JSON` / `CSV` • Shareable link `/share/{token}` • Full tables + `by_category` insights |

---

## 🌍 Supported Languages

| Language | Coverage |
|----------|----------|
| **English** | UI, prompts, docs, code, benchmarks (`Reasoning`, `Coding`, `Summarization`) |
| **Arabic (العربية)** | Full UI RTL, benchmarks (`Arabic Quality`, `Summarization`), PDF with `tahoma.ttf` + `arabic-reshaper`, auto-detection `\u0600-\u06FF` for custom datasets |
| **Mixed** | Auto `language_counts: {ar, en}` per folder, per report |

> Add a new language: add prompts to `backend/app/benchmark.py:14` and categories to `dataset_parser.py:11`. See [`SUPPORTED_LANGUAGES.md`](./SUPPORTED_LANGUAGES.md).

---

## 🚀 Quick Start

### 1. Requirements
- Node 22+ / Python 3.12+
- 8GB RAM minimum (CPU mode), 12GB+ VRAM recommended for 7B models on GPU

### 2. Backend
```bash
cd backend
pip install -r requirements.txt          # torch CPU + transformers are included
# optional GPU: pip install torch --index-url https://download.pytorch.org/whl/cu121
uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
# → http://localhost:8000/docs
```

### 3. Frontend
```bash
cd frontend
npm install
npm run dev
# → http://localhost:3000
# env: frontend/.env.local → NEXT_PUBLIC_API_URL=http://localhost:8000
```

### 4. Docker (alternative)
```bash
docker compose up --build
# frontend http://localhost:3000  backend http://localhost:8000
```

### 5. Load a model
- Place a HF-style folder anywhere, e.g. `C:\models\mistral-7b` containing `model.safetensors`, `config.json`, `tokenizer.json`
- In UI `/` or `/models` or **new:** top bar of `/benchmark` → paste path → `Validate` → `Load`
- Or via API: `POST /api/model/load {"model_path":"C:\\models\\my-model","dtype":"float16","quantization":"4bit","device_map":"auto"}`

> **No GPU?** The platform auto-enters **Demo Mode** (simulated generation) so you can still test all features.

---

## 📁 Project Structure

```
backend/app/
  main.py                 # FastAPI + CORS + routers
  model_manager.py        # Safetensors loader (torch dtype/quant/device_map)
  telemetry.py            # pynvml/psutil + 600-point history
  benchmark.py            # 15 tasks + evaluate_answer()
  dataset_parser.py       # CSV/JSON/JSONL/TXT/MD → BenchmarkTask + lang detect
  schemas.py
  routers/{model,inference,telemetry,benchmark,custom_benchmark,share,export}.py
frontend/src/
  app/{page, playground, benchmark, hardware, models, share/[token]}
  components/{ModelLoader, ModelPathSelector, Playground, BenchmarkPanel, CustomDatasetPanel, TelemetryCharts}
  lib/{api.ts, utils.ts}
example_dataset/          # 9-task mixed sample (AR/EN)
docs/                     # English developer docs
```

---

## 🔌 API Reference (core)

| Method | Path | Description |
|--------|------|-------------|
| `POST` | `/api/model/load` | Load Safetensors folder |
| `GET`  | `/api/model/status` | Loaded info |
| `GET`  | `/api/model/validate?path=` | Check `*.safetensors + config.json` |
| `POST` | `/api/generate` (SSE) | Stream tokens with `ttft_ms`, `tokens_per_sec` |
| `GET`  | `/api/telemetry/` | Snapshot (VRAM/GPU/CPU/RAM) |
| `WS`   | `/ws/telemetry` | Live push (fallback to HTTP polling) |
| `POST` | `/api/benchmark/run` | Sync benchmark (blocking) |
| `POST` | `/api/benchmark/run-stream` | **SSE progress** (`type: progress/task_done/done`) |
| `POST` | `/api/benchmark/custom/scan?folder_path=` | Scan custom folder |
| `POST` | `/api/benchmark/custom/run-from-folder` | Run on custom folder |
| `POST` | `/api/benchmark/custom/upload` | Multipart upload |
| `POST` | `/api/share/{report_id}` | Create share token |
| `GET`  | `/api/share/{token}` | Fetch shared report |
| `GET`  | `/api/export/{json,csv,pdf}?report_id=` | Export |

Full spec: http://localhost:8000/docs

---

## 🧪 Benchmark Suites

| Suite | Tasks | Judge |
|-------|-------|-------|
| `reasoning` | arithmetic, sequence, logic puzzle, fraction | Regex `\b7\b` |
| `coding` | fibonacci, loop output, reverse_string, sorted | Regex `def\s+` |
| `arabic` | spelling, synonym, i'rab, summarization | Regex `ذهبت`, `فرح` |
| `summarization` | tech text, Transformer, bullet points | Regex `7 مليار` |

Custom folder example (`CSV`):
```
prompt,expected,expected_regex,category,name
"ما مرادف سعيد؟",فرح,فرح,arabic,syn
```

---

## 📊 Hardware Profiling

- `telemetry.py:19` polls `pynvml.nvmlDeviceGetMemoryInfo` + `psutil.virtual_memory` every 1.2s
- `Recharts` Area/Line/Scatter: VRAM timeline, CPU/RAM %, Power vs VRAM, TPS vs VRAM
- `vram_peak_mb` tracked per task and globally

---

## 📄 Export & Sharing

- **PDF:** Unicode via `tahoma.ttf` + `arabic-reshaper` + `python-bidi` (fallback to `?` sanitization)
- **Share:** in-memory `share_store[token]=report_id``/share/{token}` page

---

## 🛠️ Development

See [`docs/DEVELOPMENT.md`](./docs/DEVELOPMENT.md) and [`docs/ARCHITECTURE.md`](./docs/ARCHITECTURE.md).

```bash
# Frontend
npm run build   # production
npm run lint

# Backend
python -m pytest  # (add tests)
pip install -r requirements.txt
```

---

## 🤗 Hugging Face

- Use any HF model: download `snapshots` and point `model_path` to it.
- Model card template: [`docs/HUGGINGFACE.md`](./docs/HUGGINGFACE.md)
- Dataset parser auto-handles HF `datasets` exported as JSONL/CSV.

---

## 🤝 Contributing

Please read [`CONTRIBUTING.md`](./CONTRIBUTING.md) and [`CODE_OF_CONDUCT.md`](./CODE_OF_CONDUCT.md). PRs for new languages, benchmarks, and quant backends are welcome!

## 🔒 Security

See [`SECURITY.md`](./SECURITY.md).

## 📝 License

MIT — see [`LICENSE`](./LICENSE).

---

Built with ❤️ for local AI — no cloud, full control.