anuj-inavlabs commited on
Commit
ce09413
·
verified ·
1 Parent(s): 103d10d

Add kupe-tts code, DhVaani benchmark outputs, and Hindi TTS corpus

Browse files
README.md ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ task_categories:
4
+ - text-to-speech
5
+ language:
6
+ - hi
7
+ - en
8
+ tags:
9
+ - hindi
10
+ - hinglish
11
+ - tts
12
+ - corpus
13
+ - kupe
14
+ pretty_name: kupe-tts
15
+ size_categories:
16
+ - 10K<n<100K
17
+ ---
18
+
19
+ # kupe-tts
20
+
21
+ Kupe TTS workspace: DhVaani-0.5 local CPU benchmark + Hindi/Hinglish TTS text corpus generation.
22
+
23
+ ## Contents
24
+
25
+ - `benchmark.py` — DhVaani-0.5 CPU latency benchmark
26
+ - `reference.wav` / `outputs/` — clone reference + sample outputs
27
+ - `tts_data_gen/` — Sarvam (`gemma4`) corpus generator, costs CSV, EDA
28
+ - `hindi_tts_corpus.jsonl` — ~25k utterance corpus
29
+ - `generation_costs.csv` — per-batch token/cost log
30
+ - `cost_eda_report.html` — cost EDA dashboard
31
+
32
+ ## Secrets
33
+
34
+ Set env vars locally (do **not** commit keys):
35
+
36
+ ```bash
37
+ export SARVAM_API_KEY=...
38
+ export HF_TOKEN=...
39
+ ```
benchmark.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ DhVaani-0.5 local CPU benchmark.
3
+
4
+ Loads ARTPARK-IISc/DhVaani-0.5 via transformers AutoModel, runs a few
5
+ synthesis calls, and records wall-clock latency + real-time factor (RTF)
6
+ for each. Writes .wav (native) and .mp3 (via ffmpeg/pydub) outputs, plus
7
+ a latency.json summary.
8
+
9
+ Usage:
10
+ source venv/bin/activate
11
+ python benchmark.py
12
+ """
13
+ import json
14
+ import os
15
+ import time
16
+
17
+ os.environ.setdefault("HF_TOKEN", os.environ.get("HF_TOKEN", ""))
18
+
19
+ import torch
20
+ import soundfile as sf
21
+ from transformers import AutoModel
22
+
23
+ HERE = os.path.dirname(os.path.abspath(__file__))
24
+ OUT_DIR = os.path.join(HERE, "outputs")
25
+ os.makedirs(OUT_DIR, exist_ok=True)
26
+
27
+ DEV = "cuda" if torch.cuda.is_available() else "cpu"
28
+ REFERENCE_WAV = os.path.join(HERE, "reference.wav")
29
+ # We don't have a ground-truth transcript for samples/malayalam.wav from the
30
+ # model repo, so this is an approximate placeholder — good enough to prove
31
+ # the pipeline runs and to measure latency, not tuned for max clone fidelity.
32
+ REFERENCE_TEXT = "ഇത് ഒരു മാതൃകാ ശബ്ദമാണ്."
33
+
34
+ TEST_CASES = [
35
+ {"name": "malayalam_greeting", "text": "നമസ്‌കാരം, സുഖമാണോ?"},
36
+ {"name": "malayalam_longer", "text": "ഇന്ന് കാലാവസ്ഥ വളരെ നല്ലതാണ്. നമുക്ക് പുറത്തു പോകാം."},
37
+ ]
38
+
39
+
40
+ def main():
41
+ print(f"[info] device = {DEV}")
42
+ print("[info] loading ARTPARK-IISc/DhVaani-0.5 (AutoModel, trust_remote_code=True) ...")
43
+
44
+ t0 = time.perf_counter()
45
+ model = AutoModel.from_pretrained(
46
+ "ARTPARK-IISc/DhVaani-0.5", trust_remote_code=True
47
+ ).to(DEV).eval()
48
+ load_s = time.perf_counter() - t0
49
+ print(f"[info] model loaded in {load_s:.2f}s")
50
+
51
+ sr = model.sampling_rate
52
+ results = {
53
+ "device": DEV,
54
+ "model": "ARTPARK-IISc/DhVaani-0.5",
55
+ "model_load_seconds": round(load_s, 3),
56
+ "sampling_rate": sr,
57
+ "runs": [],
58
+ }
59
+
60
+ for case in TEST_CASES:
61
+ name, text = case["name"], case["text"]
62
+ print(f"\n[run] {name!r}: {text!r}")
63
+
64
+ t0 = time.perf_counter()
65
+ audio = model.synthesize(
66
+ text=text,
67
+ prompt_wav=REFERENCE_WAV,
68
+ prompt_text=REFERENCE_TEXT,
69
+ )
70
+ gen_s = time.perf_counter() - t0
71
+
72
+ audio_duration_s = len(audio) / sr
73
+ rtf = gen_s / audio_duration_s if audio_duration_s > 0 else float("nan")
74
+
75
+ wav_path = os.path.join(OUT_DIR, f"{name}.wav")
76
+ sf.write(wav_path, audio, sr)
77
+
78
+ mp3_path = os.path.join(OUT_DIR, f"{name}.mp3")
79
+ try:
80
+ from pydub import AudioSegment
81
+
82
+ AudioSegment.from_wav(wav_path).export(mp3_path, format="mp3", bitrate="192k")
83
+ mp3_ok = True
84
+ except Exception as e:
85
+ print(f"[warn] mp3 export failed: {e}")
86
+ mp3_ok = False
87
+
88
+ print(
89
+ f"[result] gen_time={gen_s:.3f}s audio_len={audio_duration_s:.3f}s "
90
+ f"RTF={rtf:.3f} (RTF<1 means faster than real-time)"
91
+ )
92
+
93
+ results["runs"].append(
94
+ {
95
+ "name": name,
96
+ "text": text,
97
+ "generation_seconds": round(gen_s, 3),
98
+ "audio_duration_seconds": round(audio_duration_s, 3),
99
+ "real_time_factor": round(rtf, 4),
100
+ "wav_path": os.path.relpath(wav_path, HERE),
101
+ "mp3_path": os.path.relpath(mp3_path, HERE) if mp3_ok else None,
102
+ }
103
+ )
104
+
105
+ summary_path = os.path.join(OUT_DIR, "latency.json")
106
+ with open(summary_path, "w") as f:
107
+ json.dump(results, f, indent=2, ensure_ascii=False)
108
+
109
+ print(f"\n[done] summary written to {summary_path}")
110
+
111
+
112
+ if __name__ == "__main__":
113
+ main()
outputs/latency.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "device": "cpu",
3
+ "model": "ARTPARK-IISc/DhVaani-0.5",
4
+ "model_load_seconds": 11.677,
5
+ "sampling_rate": 24000,
6
+ "runs": [
7
+ {
8
+ "name": "malayalam_greeting",
9
+ "text": "നമസ്‌കാരം, സുഖമാണോ?",
10
+ "generation_seconds": 43.043,
11
+ "audio_duration_seconds": 3.328,
12
+ "real_time_factor": 12.9337,
13
+ "wav_path": "outputs/malayalam_greeting.wav",
14
+ "mp3_path": "outputs/malayalam_greeting.mp3"
15
+ },
16
+ {
17
+ "name": "malayalam_longer",
18
+ "text": "ഇന്ന് കാലാവസ്ഥ വളരെ നല്ലതാണ്. നമുക്ക് പുറത്തു പോകാം.",
19
+ "generation_seconds": 69.043,
20
+ "audio_duration_seconds": 9.12,
21
+ "real_time_factor": 7.5705,
22
+ "wav_path": "outputs/malayalam_longer.wav",
23
+ "mp3_path": "outputs/malayalam_longer.mp3"
24
+ }
25
+ ]
26
+ }
outputs/malayalam_greeting.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:21e045114a46928d578c537fb5521eea2fe65df912c9e4aacc3f37b428a572f0
3
+ size 68204
outputs/malayalam_greeting.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4a381afe7622dc5e1351e62ba1ac366ae1af719132aec395b8f4e50da3909269
3
+ size 159788
outputs/malayalam_longer.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:021df74b91909a88f0e859937afd7d2afd5c2117bcc920f4d97b92e3a9bc721b
3
+ size 183884
outputs/malayalam_longer.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7133da9823cdb78dcf9d185e8e7450d61ebc838dfeaac83f67335fa10efce164
3
+ size 437804
reference.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cec481b61ddbd033f8a6ff2d91576459672deb61403d8be58619634061978179
3
+ size 385424
requirements.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DhVaani-0.5 CPU inference — pinned to what was actually installed/tested.
2
+ # Install torch/torchaudio for your machine FIRST (CPU wheels shown):
3
+ # pip install torch torchaudio
4
+ # then:
5
+ # pip install -r requirements.txt
6
+
7
+ transformers>=4.40,<5
8
+ torch
9
+ torchaudio
10
+ numpy
11
+ soundfile
12
+ safetensors
13
+ einops
14
+ vocos
15
+ huggingface_hub
16
+ pydub # only needed for the mp3 export step (uses system ffmpeg)
run_log.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [info] device = cpu
2
+ [info] loading ARTPARK-IISc/DhVaani-0.5 (AutoModel, trust_remote_code=True) ...
3
+
4
+ WARNING:root:Failed import k2 with error No module named 'k2'. Swoosh functions will fallback to PyTorch implementation, leading to slower speed and higher memory consumption.
5
+ [info] model loaded in 11.68s
6
+
7
+ [run] 'malayalam_greeting': 'നമസ്\u200cകാരം, സുഖമാണോ?'
8
+ [result] gen_time=43.043s audio_len=3.328s RTF=12.934 (RTF<1 means faster than real-time)
9
+
10
+ [run] 'malayalam_longer': 'ഇന്ന് കാലാവസ്ഥ വളരെ നല്ലതാണ്. നമുക്ക് പുറത്തു പോകാം.'
11
+ [result] gen_time=69.043s audio_len=9.120s RTF=7.571 (RTF<1 means faster than real-time)
12
+
13
+ [done] summary written to /Users/pengu/Documents/kupe/kupe-tts/outputs/latency.json
tts_data_gen/build_cost_eda_html.py ADDED
@@ -0,0 +1,451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build a self-contained HTML EDA report from generation_costs.csv."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import csv
7
+ import json
8
+ from collections import defaultdict
9
+ from datetime import datetime, timezone
10
+ from pathlib import Path
11
+
12
+ DIR = Path(__file__).resolve().parent
13
+ CSV_PATH = DIR / "generation_costs.csv"
14
+ OUT_PATH = DIR / "cost_eda_report.html"
15
+
16
+ CATEGORY_TARGETS = {
17
+ "pure_hindi": 13750,
18
+ "hinglish": 5000,
19
+ "numeric_entity": 2500,
20
+ "prosody": 2500,
21
+ "named_entity": 1250,
22
+ }
23
+ TOTAL_TARGET = sum(CATEGORY_TARGETS.values())
24
+
25
+
26
+ def fnum(v, d=0.0) -> float:
27
+ try:
28
+ return float(v)
29
+ except (TypeError, ValueError):
30
+ return d
31
+
32
+
33
+ def inum(v, d=0) -> int:
34
+ try:
35
+ return int(float(v))
36
+ except (TypeError, ValueError):
37
+ return d
38
+
39
+
40
+ def load_rows(path: Path) -> list[dict]:
41
+ with path.open("r", encoding="utf-8", newline="") as f:
42
+ return list(csv.DictReader(f))
43
+
44
+
45
+ def build(rows: list[dict]) -> dict:
46
+ by_cat = defaultdict(lambda: {
47
+ "batches": 0, "items": 0, "prompt": 0, "cached": 0,
48
+ "completion": 0, "cost": 0.0,
49
+ })
50
+ prompt = cached = completion = items = 0
51
+ sum_cost = 0.0
52
+ cum = 0.0
53
+ req_costs = []
54
+
55
+ clean_rows = []
56
+ for r in rows:
57
+ cat = r.get("category") or "unknown"
58
+ it = inum(r.get("items"))
59
+ pt = inum(r.get("prompt_tokens"))
60
+ ct = inum(r.get("cached_tokens"))
61
+ ot = inum(r.get("completion_tokens"))
62
+ cost = fnum(r.get("cost_inr"))
63
+ cum = fnum(r.get("cum_cost_inr"), cum)
64
+ hit = fnum(r.get("cache_hit_pct"))
65
+
66
+ items += it
67
+ prompt += pt
68
+ cached += ct
69
+ completion += ot
70
+ sum_cost += cost
71
+ req_costs.append(cost)
72
+
73
+ b = by_cat[cat]
74
+ b["batches"] += 1
75
+ b["items"] += it
76
+ b["prompt"] += pt
77
+ b["cached"] += ct
78
+ b["completion"] += ot
79
+ b["cost"] += cost
80
+
81
+ clean_rows.append({
82
+ "ts": r.get("timestamp_utc") or "",
83
+ "batch": inum(r.get("batch_num")),
84
+ "category": cat,
85
+ "topic": r.get("topic") or "",
86
+ "items": it,
87
+ "prompt": pt,
88
+ "cached": ct,
89
+ "uncached": inum(r.get("uncached_input_tokens")),
90
+ "completion": ot,
91
+ "total": inum(r.get("total_tokens")) or (pt + ot),
92
+ "kv_pct": hit,
93
+ "cost": round(cost, 6),
94
+ "cum": round(fnum(r.get("cum_cost_inr")), 6),
95
+ "per_item": fnum(r.get("cost_per_item_inr")),
96
+ "corpus": inum(r.get("corpus_items")),
97
+ "left": inum(r.get("corpus_left")),
98
+ })
99
+
100
+ if cum <= 0:
101
+ cum = sum_cost
102
+
103
+ recent = rows[-20:] if rows else []
104
+ r_prompt = sum(inum(r.get("prompt_tokens")) for r in recent)
105
+ r_cached = sum(inum(r.get("cached_tokens")) for r in recent)
106
+
107
+ cats = []
108
+ for name, target in CATEGORY_TARGETS.items():
109
+ b = by_cat[name]
110
+ cats.append({
111
+ "category": name,
112
+ "target": target,
113
+ "have": b["items"],
114
+ "left": max(target - b["items"], 0),
115
+ "pct": round(100.0 * b["items"] / target, 1) if target else 0,
116
+ "batches": b["batches"],
117
+ "prompt": b["prompt"],
118
+ "cached": b["cached"],
119
+ "completion": b["completion"],
120
+ "cost": round(b["cost"], 4),
121
+ "kv_pct": round(100.0 * b["cached"] / b["prompt"], 1) if b["prompt"] else 0,
122
+ })
123
+ # any unexpected categories
124
+ for name, b in by_cat.items():
125
+ if name in CATEGORY_TARGETS:
126
+ continue
127
+ cats.append({
128
+ "category": name,
129
+ "target": 0,
130
+ "have": b["items"],
131
+ "left": 0,
132
+ "pct": 0,
133
+ "batches": b["batches"],
134
+ "prompt": b["prompt"],
135
+ "cached": b["cached"],
136
+ "completion": b["completion"],
137
+ "cost": round(b["cost"], 4),
138
+ "kv_pct": round(100.0 * b["cached"] / b["prompt"], 1) if b["prompt"] else 0,
139
+ })
140
+
141
+ done = items # from CSV item sums; may exceed target slightly
142
+ left = max(TOTAL_TARGET - done, 0)
143
+ per_utt = cum / done if done else 0
144
+ per_req = (sum(req_costs) / len(req_costs)) if req_costs else 0
145
+
146
+ return {
147
+ "generated_at": datetime.now(timezone.utc).isoformat(),
148
+ "source": str(CSV_PATH.name),
149
+ "batches": len(rows),
150
+ "items": done,
151
+ "target": TOTAL_TARGET,
152
+ "left": left,
153
+ "pct": round(100.0 * done / TOTAL_TARGET, 1) if TOTAL_TARGET else 0,
154
+ "spent": round(cum, 4),
155
+ "sum_cost": round(sum_cost, 4),
156
+ "est_left": round(per_utt * left, 4),
157
+ "est_total": round(cum + per_utt * left, 4),
158
+ "per_utt": round(per_utt, 6),
159
+ "per_req": round(per_req, 4),
160
+ "last_req": round(req_costs[-1], 4) if req_costs else 0,
161
+ "prompt": prompt,
162
+ "cached": cached,
163
+ "completion": completion,
164
+ "kv_all": round(100.0 * cached / prompt, 1) if prompt else 0,
165
+ "kv_recent": round(100.0 * r_cached / r_prompt, 1) if r_prompt else 0,
166
+ "categories": cats,
167
+ "rows": clean_rows,
168
+ }
169
+
170
+
171
+ HTML = r"""<!DOCTYPE html>
172
+ <html lang="en">
173
+ <head>
174
+ <meta charset="utf-8"/>
175
+ <meta name="viewport" content="width=device-width, initial-scale=1"/>
176
+ <title>Corpus Cost EDA</title>
177
+ <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
178
+ <style>
179
+ :root {
180
+ --bg: #0f1419;
181
+ --panel: #1a222c;
182
+ --line: #2a3542;
183
+ --text: #e7eef6;
184
+ --muted: #8b9aab;
185
+ --accent: #3dd6c6;
186
+ --warn: #f0b429;
187
+ --danger: #ff6b6b;
188
+ --ok: #6bcb77;
189
+ }
190
+ * { box-sizing: border-box; }
191
+ body {
192
+ margin: 0; font-family: "IBM Plex Sans", "Segoe UI", system-ui, sans-serif;
193
+ background: radial-gradient(1200px 600px at 10% -10%, #1b2a33 0%, var(--bg) 55%);
194
+ color: var(--text); line-height: 1.45;
195
+ }
196
+ header {
197
+ padding: 28px 32px 12px; border-bottom: 1px solid var(--line);
198
+ }
199
+ header h1 { margin: 0 0 6px; font-size: 1.6rem; letter-spacing: -0.02em; }
200
+ header p { margin: 0; color: var(--muted); font-size: 0.92rem; }
201
+ main { padding: 24px 32px 48px; max-width: 1400px; margin: 0 auto; }
202
+ .grid { display: grid; gap: 14px; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); margin: 18px 0 28px; }
203
+ .card {
204
+ background: var(--panel); border: 1px solid var(--line); border-radius: 12px;
205
+ padding: 14px 16px;
206
+ }
207
+ .card .label { color: var(--muted); font-size: 0.78rem; text-transform: uppercase; letter-spacing: 0.06em; }
208
+ .card .value { font-size: 1.45rem; font-weight: 650; margin-top: 4px; }
209
+ .card .sub { color: var(--muted); font-size: 0.82rem; margin-top: 2px; }
210
+ .accent { color: var(--accent); }
211
+ .warn { color: var(--warn); }
212
+ .danger { color: var(--danger); }
213
+ .ok { color: var(--ok); }
214
+ h2 { font-size: 1.05rem; margin: 28px 0 12px; }
215
+ .charts { display: grid; gap: 16px; grid-template-columns: 1.2fr 1fr; }
216
+ @media (max-width: 900px) { .charts { grid-template-columns: 1fr; } }
217
+ .panel {
218
+ background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 16px;
219
+ }
220
+ table { width: 100%; border-collapse: collapse; font-size: 0.84rem; }
221
+ th, td { padding: 8px 10px; border-bottom: 1px solid var(--line); text-align: left; white-space: nowrap; }
222
+ th { color: var(--muted); font-weight: 600; position: sticky; top: 0; background: #1e2833; z-index: 1; }
223
+ tr:hover td { background: rgba(61,214,198,0.06); }
224
+ .table-wrap { max-height: 520px; overflow: auto; border: 1px solid var(--line); border-radius: 10px; }
225
+ .toolbar { display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 10px; align-items: center; }
226
+ input, select {
227
+ background: #12181f; color: var(--text); border: 1px solid var(--line);
228
+ border-radius: 8px; padding: 8px 10px; font: inherit;
229
+ }
230
+ .bar {
231
+ height: 8px; background: #243040; border-radius: 99px; overflow: hidden; min-width: 80px;
232
+ }
233
+ .bar > span { display: block; height: 100%; background: linear-gradient(90deg, #2bbbad, #6bcb77); }
234
+ .pill {
235
+ display: inline-block; padding: 2px 8px; border-radius: 999px; font-size: 0.75rem;
236
+ background: #243040; color: var(--muted);
237
+ }
238
+ </style>
239
+ </head>
240
+ <body>
241
+ <header>
242
+ <h1>Corpus generation — cost EDA</h1>
243
+ <p id="meta">Loading…</p>
244
+ </header>
245
+ <main>
246
+ <div class="grid" id="cards"></div>
247
+
248
+ <h2>Progress by category</h2>
249
+ <div class="panel table-wrap" style="max-height:none; overflow:visible">
250
+ <table id="catTable">
251
+ <thead>
252
+ <tr>
253
+ <th>Category</th><th>Have</th><th>Target</th><th>Left</th><th>Progress</th>
254
+ <th>Batches</th><th>Prompt</th><th>Cached</th><th>KV%</th><th>Cost ₹</th>
255
+ </tr>
256
+ </thead>
257
+ <tbody></tbody>
258
+ </table>
259
+ </div>
260
+
261
+ <h2>Charts</h2>
262
+ <div class="charts">
263
+ <div class="panel"><canvas id="costByCat" height="160"></canvas></div>
264
+ <div class="panel"><canvas id="kvByCat" height="160"></canvas></div>
265
+ </div>
266
+ <div class="panel" style="margin-top:16px"><canvas id="cumCost" height="90"></canvas></div>
267
+
268
+ <h2>All batches</h2>
269
+ <div class="toolbar">
270
+ <input id="q" placeholder="Filter topic / category…" style="min-width:220px"/>
271
+ <select id="catFilter"><option value="">All categories</option></select>
272
+ <span class="pill" id="rowCount"></span>
273
+ </div>
274
+ <div class="table-wrap">
275
+ <table id="allTable">
276
+ <thead>
277
+ <tr>
278
+ <th>#</th><th>UTC</th><th>Cat</th><th>Topic</th><th>Items</th>
279
+ <th>Prompt</th><th>Cached</th><th>Out</th><th>KV%</th>
280
+ <th>Cost ₹</th><th>Cum ₹</th><th>Corpus</th>
281
+ </tr>
282
+ </thead>
283
+ <tbody></tbody>
284
+ </table>
285
+ </div>
286
+ </main>
287
+ <script>
288
+ const DATA = __DATA__;
289
+
290
+ function fmt(n, d=2) {
291
+ if (n == null || Number.isNaN(n)) return "—";
292
+ return Number(n).toLocaleString(undefined, { maximumFractionDigits: d, minimumFractionDigits: d });
293
+ }
294
+ function fmtInt(n) {
295
+ return Number(n || 0).toLocaleString();
296
+ }
297
+
298
+ document.getElementById("meta").textContent =
299
+ `${DATA.source} · ${DATA.batches} batches · generated ${DATA.generated_at}`;
300
+
301
+ const cards = [
302
+ ["Spent so far", `₹${fmt(DATA.spent)}`, "warn", `sum of rows ₹${fmt(DATA.sum_cost)}`],
303
+ ["Est. left", `₹${fmt(DATA.est_left)}`, "danger", `at ₹${fmt(DATA.per_utt, 5)} / utterance`],
304
+ ["Est. total", `₹${fmt(DATA.est_total)}`, "ok", "spent + est. left"],
305
+ ["Done", `${fmtInt(DATA.items)} / ${fmtInt(DATA.target)}`, "accent", `${DATA.pct}% · left ${fmtInt(DATA.left)}`],
306
+ ["Per request", `₹${fmt(DATA.per_req, 4)}`, "", `last ₹${fmt(DATA.last_req, 4)}`],
307
+ ["KV all-time", `${fmt(DATA.kv_all, 1)}%`, "accent", `${fmtInt(DATA.cached)} / ${fmtInt(DATA.prompt)}`],
308
+ ["KV recent 20", `${fmt(DATA.kv_recent, 1)}%`, "", "last 20 batches"],
309
+ ["Tokens out", fmtInt(DATA.completion), "", "completion tokens"],
310
+ ];
311
+ document.getElementById("cards").innerHTML = cards.map(([label, value, cls, sub]) => `
312
+ <div class="card">
313
+ <div class="label">${label}</div>
314
+ <div class="value ${cls}">${value}</div>
315
+ <div class="sub">${sub}</div>
316
+ </div>
317
+ `).join("");
318
+
319
+ const catBody = document.querySelector("#catTable tbody");
320
+ catBody.innerHTML = DATA.categories.map(c => `
321
+ <tr>
322
+ <td><strong>${c.category}</strong></td>
323
+ <td>${fmtInt(c.have)}</td>
324
+ <td>${fmtInt(c.target)}</td>
325
+ <td>${fmtInt(c.left)}</td>
326
+ <td>
327
+ <div style="display:flex;gap:8px;align-items:center">
328
+ <div class="bar" style="width:100px"><span style="width:${Math.min(c.pct,100)}%"></span></div>
329
+ ${c.pct}%
330
+ </div>
331
+ </td>
332
+ <td>${fmtInt(c.batches)}</td>
333
+ <td>${fmtInt(c.prompt)}</td>
334
+ <td>${fmtInt(c.cached)}</td>
335
+ <td>${fmt(c.kv_pct,1)}%</td>
336
+ <td>₹${fmt(c.cost,4)}</td>
337
+ </tr>
338
+ `).join("");
339
+
340
+ const catFilter = document.getElementById("catFilter");
341
+ [...new Set(DATA.categories.map(c => c.category))].forEach(c => {
342
+ const o = document.createElement("option");
343
+ o.value = c; o.textContent = c; catFilter.appendChild(o);
344
+ });
345
+
346
+ const allBody = document.querySelector("#allTable tbody");
347
+ function renderRows() {
348
+ const q = document.getElementById("q").value.trim().toLowerCase();
349
+ const cat = catFilter.value;
350
+ const filtered = DATA.rows.filter(r => {
351
+ if (cat && r.category !== cat) return false;
352
+ if (!q) return true;
353
+ return (r.topic + " " + r.category).toLowerCase().includes(q);
354
+ });
355
+ document.getElementById("rowCount").textContent = `${filtered.length} / ${DATA.rows.length} rows`;
356
+ allBody.innerHTML = filtered.map((r, i) => `
357
+ <tr>
358
+ <td>${r.batch}</td>
359
+ <td>${(r.ts || "").replace("T"," ").slice(0,19)}</td>
360
+ <td>${r.category}</td>
361
+ <td title="${r.topic}">${(r.topic || "").slice(0,28)}</td>
362
+ <td>${r.items}</td>
363
+ <td>${r.prompt}</td>
364
+ <td>${r.cached}</td>
365
+ <td>${r.completion}</td>
366
+ <td>${fmt(r.kv_pct,1)}</td>
367
+ <td>${fmt(r.cost,4)}</td>
368
+ <td>${fmt(r.cum,4)}</td>
369
+ <td>${fmtInt(r.corpus)}</td>
370
+ </tr>
371
+ `).join("");
372
+ }
373
+ document.getElementById("q").addEventListener("input", renderRows);
374
+ catFilter.addEventListener("change", renderRows);
375
+ renderRows();
376
+
377
+ new Chart(document.getElementById("costByCat"), {
378
+ type: "bar",
379
+ data: {
380
+ labels: DATA.categories.map(c => c.category),
381
+ datasets: [{ label: "Cost ₹", data: DATA.categories.map(c => c.cost),
382
+ backgroundColor: "#3dd6c6aa", borderColor: "#3dd6c6", borderWidth: 1 }]
383
+ },
384
+ options: {
385
+ plugins: { title: { display: true, text: "Cost by category (₹)", color: "#e7eef6" }, legend: { display: false } },
386
+ scales: {
387
+ x: { ticks: { color: "#8b9aab" }, grid: { color: "#2a3542" } },
388
+ y: { ticks: { color: "#8b9aab" }, grid: { color: "#2a3542" } }
389
+ }
390
+ }
391
+ });
392
+
393
+ new Chart(document.getElementById("kvByCat"), {
394
+ type: "bar",
395
+ data: {
396
+ labels: DATA.categories.map(c => c.category),
397
+ datasets: [{ label: "KV %", data: DATA.categories.map(c => c.kv_pct),
398
+ backgroundColor: "#f0b429aa", borderColor: "#f0b429", borderWidth: 1 }]
399
+ },
400
+ options: {
401
+ plugins: { title: { display: true, text: "KV cache hit % by category", color: "#e7eef6" }, legend: { display: false } },
402
+ scales: {
403
+ x: { ticks: { color: "#8b9aab" }, grid: { color: "#2a3542" } },
404
+ y: { ticks: { color: "#8b9aab" }, grid: { color: "#2a3542" }, max: 100 }
405
+ }
406
+ }
407
+ });
408
+
409
+ const step = Math.max(1, Math.floor(DATA.rows.length / 80));
410
+ const cumLabels = [], cumVals = [];
411
+ DATA.rows.forEach((r, i) => {
412
+ if (i % step === 0 || i === DATA.rows.length - 1) {
413
+ cumLabels.push(String(i + 1));
414
+ cumVals.push(r.cum);
415
+ }
416
+ });
417
+ new Chart(document.getElementById("cumCost"), {
418
+ type: "line",
419
+ data: {
420
+ labels: cumLabels,
421
+ datasets: [{ label: "Cumulative ₹", data: cumVals, borderColor: "#6bcb77",
422
+ backgroundColor: "#6bcb7733", fill: true, tension: 0.25, pointRadius: 0 }]
423
+ },
424
+ options: {
425
+ plugins: { title: { display: true, text: "Cumulative spend over batches", color: "#e7eef6" }, legend: { display: false } },
426
+ scales: {
427
+ x: { ticks: { color: "#8b9aab", maxTicksLimit: 12 }, grid: { color: "#2a3542" }, title: { display: true, text: "batch index", color: "#8b9aab" } },
428
+ y: { ticks: { color: "#8b9aab" }, grid: { color: "#2a3542" } }
429
+ }
430
+ }
431
+ });
432
+ </script>
433
+ </body>
434
+ </html>
435
+ """
436
+
437
+
438
+ def main():
439
+ rows = load_rows(CSV_PATH)
440
+ data = build(rows)
441
+ html = HTML.replace("__DATA__", json.dumps(data, ensure_ascii=False))
442
+ OUT_PATH.write_text(html, encoding="utf-8")
443
+ print(f"Wrote {OUT_PATH}")
444
+ print(
445
+ f"Spent ₹{data['spent']:.4f} · items {data['items']:,}/{data['target']:,} "
446
+ f"· KV {data['kv_all']}% · batches {data['batches']}"
447
+ )
448
+
449
+
450
+ if __name__ == "__main__":
451
+ main()
tts_data_gen/cost_eda.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Live cost/progress monitor — clean, minimal, 1s refresh.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import csv
9
+ import json
10
+ import sys
11
+ import time
12
+ from pathlib import Path
13
+
14
+ from tqdm import tqdm
15
+
16
+ DIR = Path(__file__).resolve().parent
17
+ COST_CSV = DIR / "generation_costs.csv"
18
+ CORPUS_JSONL = DIR / "hindi_tts_corpus.jsonl"
19
+ INTERVAL_SEC = 1.0
20
+
21
+ CATEGORY_TARGETS = {
22
+ "pure_hindi": 13750,
23
+ "hinglish": 5000,
24
+ "numeric_entity": 2500,
25
+ "prosody": 2500,
26
+ "named_entity": 1250,
27
+ }
28
+ TOTAL_TARGET = sum(CATEGORY_TARGETS.values())
29
+
30
+
31
+ class C:
32
+ R = "\033[0m"
33
+ B = "\033[1m"
34
+ D = "\033[2m"
35
+ RED = "\033[91m"
36
+ GRN = "\033[92m"
37
+ YLW = "\033[93m"
38
+ CYN = "\033[96m"
39
+ MAG = "\033[95m"
40
+ WHT = "\033[97m"
41
+ BG = "\033[44m"
42
+
43
+
44
+ CAT_COLOR = {
45
+ "pure_hindi": C.GRN,
46
+ "hinglish": C.CYN,
47
+ "numeric_entity": C.YLW,
48
+ "prosody": C.MAG,
49
+ "named_entity": "\033[94m",
50
+ }
51
+
52
+
53
+ def col(text, *styles):
54
+ return "".join(styles) + str(text) + C.R
55
+
56
+
57
+ def fnum(v, d=0.0):
58
+ try:
59
+ return float(v)
60
+ except (TypeError, ValueError):
61
+ return d
62
+
63
+
64
+ def inum(v, d=0):
65
+ try:
66
+ return int(float(v))
67
+ except (TypeError, ValueError):
68
+ return d
69
+
70
+
71
+ def load_csv(path: Path) -> list[dict]:
72
+ if not path.exists() or path.stat().st_size == 0:
73
+ return []
74
+ with path.open("r", encoding="utf-8", newline="") as f:
75
+ return list(csv.DictReader(f))
76
+
77
+
78
+ def load_counts(path: Path) -> dict[str, int]:
79
+ counts = {k: 0 for k in CATEGORY_TARGETS}
80
+ if not path.exists():
81
+ return counts
82
+ with path.open("r", encoding="utf-8") as f:
83
+ for line in f:
84
+ line = line.strip()
85
+ if not line:
86
+ continue
87
+ try:
88
+ r = json.loads(line)
89
+ except json.JSONDecodeError:
90
+ continue
91
+ t = r.get("type")
92
+ if t in counts:
93
+ counts[t] += 1
94
+ return counts
95
+
96
+
97
+ def summarize(rows: list[dict], counts: dict[str, int]) -> dict:
98
+ prompt = cached = completion = 0
99
+ sum_cost = 0.0
100
+ cum = 0.0
101
+ req_costs = []
102
+ last_ts = ""
103
+
104
+ for r in rows:
105
+ prompt += inum(r.get("prompt_tokens"))
106
+ cached += inum(r.get("cached_tokens"))
107
+ completion += inum(r.get("completion_tokens"))
108
+ cost = fnum(r.get("cost_inr"))
109
+ sum_cost += cost
110
+ req_costs.append(cost)
111
+ cum = fnum(r.get("cum_cost_inr"), cum)
112
+ last_ts = r.get("timestamp_utc") or last_ts
113
+
114
+ if cum <= 0:
115
+ cum = sum_cost
116
+
117
+ # Recent window = last 20 batches (ignore old SSE zeros)
118
+ recent = rows[-20:] if rows else []
119
+ r_prompt = sum(inum(r.get("prompt_tokens")) for r in recent)
120
+ r_cached = sum(inum(r.get("cached_tokens")) for r in recent)
121
+ kv_all = 100.0 * cached / prompt if prompt else 0.0
122
+ kv_recent = 100.0 * r_cached / r_prompt if r_prompt else 0.0
123
+
124
+ done = sum(counts.values())
125
+ left = max(TOTAL_TARGET - done, 0)
126
+ pct = 100.0 * done / TOTAL_TARGET if TOTAL_TARGET else 0.0
127
+
128
+ per_utt = cum / done if done else 0.0
129
+ per_req = (sum(req_costs) / len(req_costs)) if req_costs else 0.0
130
+ last_req = req_costs[-1] if req_costs else 0.0
131
+ est_left = per_utt * left
132
+ est_total = cum + est_left
133
+
134
+ progress = {}
135
+ for cat, target in CATEGORY_TARGETS.items():
136
+ have = counts.get(cat, 0)
137
+ progress[cat] = {
138
+ "have": have,
139
+ "target": target,
140
+ "left": max(target - have, 0),
141
+ "pct": 100.0 * have / target if target else 0.0,
142
+ }
143
+
144
+ return {
145
+ "batches": len(rows),
146
+ "done": done,
147
+ "left": left,
148
+ "pct": pct,
149
+ "kv_all": kv_all,
150
+ "kv_recent": kv_recent,
151
+ "cached": cached,
152
+ "prompt": prompt,
153
+ "r_cached": r_cached,
154
+ "r_prompt": r_prompt,
155
+ "spent": cum,
156
+ "per_utt": per_utt,
157
+ "per_req": per_req,
158
+ "last_req": last_req,
159
+ "est_left": est_left,
160
+ "est_total": est_total,
161
+ "last_ts": last_ts,
162
+ "progress": progress,
163
+ }
164
+
165
+
166
+ def render(s: dict, tick: int) -> str:
167
+ spent = f"₹{s['spent']:.2f}"
168
+ est_left = f"₹{s['est_left']:.2f}"
169
+ est_total = f"₹{s['est_total']:.2f}"
170
+ kv_r = f"{s['kv_recent']:.1f}%"
171
+ kv_a = f"{s['kv_all']:.1f}%"
172
+ lines = [
173
+ col("=" * 64, C.CYN, C.B),
174
+ col(" CORPUS COST ", C.BG, C.WHT, C.B) + col(f" #{tick} · 1s", C.D),
175
+ col("=" * 64, C.CYN),
176
+ "",
177
+ f" {col('SPENT SO FAR', C.B)} {col(spent, C.YLW, C.B)}",
178
+ f" {col('EST. LEFT', C.B)} {col(est_left, C.RED, C.B)}",
179
+ f" {col('EST. TOTAL', C.B)} {col(est_total, C.GRN, C.B)}",
180
+ "",
181
+ f" {col('DONE', C.GRN, C.B)} {s['done']:,} / {TOTAL_TARGET:,} ({s['pct']:.1f}%)"
182
+ f" {col('LEFT', C.RED, C.B)} {s['left']:,}",
183
+ "",
184
+ f" {col('per utterance', C.B)} ₹{s['per_utt']:.5f}",
185
+ f" {col('per request', C.B)} ₹{s['per_req']:.4f} avg"
186
+ f" · last ₹{s['last_req']:.4f}",
187
+ f" {col('requests', C.B)} {s['batches']:,}",
188
+ f" {col('KV recent', C.B)} {col(kv_r, C.CYN, C.B)}"
189
+ f" last 20 ({s['r_cached']:,}/{s['r_prompt']:,})",
190
+ f" {col('KV all-time', C.B)} {kv_a}"
191
+ f" ({s['cached']:,}/{s['prompt']:,})",
192
+ "",
193
+ col("-" * 64, C.D),
194
+ ]
195
+ return "\n".join(lines)
196
+
197
+
198
+ def main():
199
+ cost_path = Path(sys.argv[1]) if len(sys.argv) > 1 else COST_CSV
200
+ corpus_path = Path(sys.argv[2]) if len(sys.argv) > 2 else CORPUS_JSONL
201
+
202
+ overall = tqdm(
203
+ total=TOTAL_TARGET,
204
+ desc=col("total 25k", C.GRN, C.B),
205
+ unit="utt",
206
+ position=0,
207
+ leave=True,
208
+ colour="green",
209
+ dynamic_ncols=True,
210
+ bar_format="{l_bar}{bar}| {n_fmt}/{total_fmt} {percentage:3.0f}%",
211
+ )
212
+ cat_bars = {}
213
+ for i, (cat, target) in enumerate(CATEGORY_TARGETS.items(), start=1):
214
+ cat_bars[cat] = tqdm(
215
+ total=target,
216
+ desc=col(f"{cat:16s}", CAT_COLOR.get(cat, C.WHT)),
217
+ unit="utt",
218
+ position=i,
219
+ leave=True,
220
+ colour="cyan",
221
+ dynamic_ncols=True,
222
+ bar_format="{l_bar}{bar}| {n_fmt}/{total_fmt} {percentage:3.0f}%",
223
+ )
224
+
225
+ tick = 0
226
+ try:
227
+ while True:
228
+ tick += 1
229
+ s = summarize(load_csv(cost_path), load_counts(corpus_path))
230
+ tqdm.write("\033[2J\033[H")
231
+ tqdm.write(render(s, tick))
232
+
233
+ overall.n = min(s["done"], TOTAL_TARGET)
234
+ overall.refresh()
235
+ for cat, bar in cat_bars.items():
236
+ bar.n = min(s["progress"][cat]["have"], bar.total)
237
+ bar.refresh()
238
+
239
+ time.sleep(INTERVAL_SEC)
240
+ except KeyboardInterrupt:
241
+ tqdm.write(col("\nstopped.", C.YLW))
242
+ finally:
243
+ overall.close()
244
+ for bar in cat_bars.values():
245
+ bar.close()
246
+
247
+
248
+ if __name__ == "__main__":
249
+ main()
tts_data_gen/cost_eda_report.html ADDED
The diff for this file is too large to render. See raw diff
 
tts_data_gen/generation_costs.csv ADDED
The diff for this file is too large to render. See raw diff
 
tts_data_gen/hindi_tts_corpus.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
tts_data_gen/text_gen_agent.py ADDED
@@ -0,0 +1,789 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Hindi/Hinglish TTS Text-Corpus Generator
4
+ ==========================================
5
+ Generates diverse text utterances for a single-speaker Hindi streaming TTS
6
+ finetune (Qwen3-TTS-0.6B-Base), to later be synthesized into audio via OmniVoice.
7
+
8
+ Model : gemma4 via Sarvam open-source chat completions (v2)
9
+ https://docs.sarvam.ai/api-reference/open-source/chat-completions
10
+ Output: hindi_tts_corpus.jsonl (one JSON object per line -> crash-safe, resumable)
11
+ Cost : generation_costs.csv (per-batch tokens + INR cost)
12
+
13
+ Features:
14
+ - SSE streaming: tokens printed live as they arrive
15
+ - No reasoning (reasoning_effort=None)
16
+ - Concurrent requests (ThreadPoolExecutor)
17
+ - Per-category waves (stable prompt prefix for KV cache)
18
+ - Flush JSONL after every completed batch
19
+
20
+ Requires Python 3.9+.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import csv
26
+ import itertools
27
+ import json
28
+ import os
29
+ import re
30
+ import sys
31
+ import threading
32
+ import time
33
+ from concurrent.futures import ThreadPoolExecutor, as_completed
34
+ from datetime import datetime, timezone
35
+ from pathlib import Path
36
+
37
+ from openai import OpenAI
38
+
39
+ # Devanagari only for pure_hindi. Reject Gujarati + other Indic scripts + Latin.
40
+ _DEVANAGARI_RE = re.compile(r"[\u0900-\u097F]")
41
+ _FORBIDDEN_SCRIPT_RE = re.compile(
42
+ r"[A-Za-z"
43
+ r"\u0980-\u09FF" # Bengali
44
+ r"\u0A00-\u0A7F" # Gurmukhi
45
+ r"\u0A80-\u0AFF" # Gujarati ← common leak
46
+ r"\u0B00-\u0B7F" # Oriya
47
+ r"\u0B80-\u0BFF" # Tamil
48
+ r"\u0C00-\u0C7F" # Telugu
49
+ r"\u0C80-\u0CFF" # Kannada
50
+ r"\u0D00-\u0D7F" # Malayalam
51
+ r"]"
52
+ )
53
+
54
+ # ----------------------------------------------------------------------------
55
+ # CONFIG
56
+ # ----------------------------------------------------------------------------
57
+
58
+ SARVAM_API_KEY = os.environ.get("SARVAM_API_KEY", "")
59
+ # Open-source models endpoint (gemma4 / glm5.2 / sarvam-105b)
60
+ BASE_URL = "https://api.sarvam.ai/v2"
61
+ MODEL = "gemma4"
62
+
63
+ OUTPUT_FILE = Path("hindi_tts_corpus.jsonl")
64
+ COST_CSV = Path("generation_costs.csv")
65
+
66
+ BATCH_SIZE = 40
67
+ CONTEXT_EXAMPLES = 0 # keep suffix tiny → max KV hits (topics rotate for diversity)
68
+ MAX_RETRIES = 5
69
+ MAX_TOKENS = 4096
70
+ CONCURRENCY = 30
71
+ USE_STREAM = os.environ.get("SARVAM_STREAM", "1") == "1"
72
+ WARM_CACHE_FIRST = True
73
+
74
+ # Gemma-4 31B · INR per 1M tokens (input / cached / output)
75
+ PRICE_INPUT_PER_M = 36.60
76
+ PRICE_CACHED_PER_M = 13.73
77
+ PRICE_OUTPUT_PER_M = 91.50
78
+
79
+ CATEGORY_TARGETS = {
80
+ "pure_hindi": 13750,
81
+ "hinglish": 5000,
82
+ "numeric_entity": 2500,
83
+ "prosody": 2500,
84
+ "named_entity": 1250,
85
+ }
86
+
87
+ CATEGORY_RULES = {
88
+ "pure_hindi": (
89
+ "STRICT Pure Hindi ONLY. Write in Hindi language using Devanagari script "
90
+ "(अ आ इ ई क ख ग …) exclusively. "
91
+ "FORBIDDEN: Gujarati (અ આ ક ખ), Bengali, Tamil, Telugu, Kannada, Malayalam, "
92
+ "Punjabi/Gurmukhi, English/Latin letters, and ASCII digits (spell numbers as "
93
+ "words: बारह, पच्चीस). "
94
+ "If you output any non-Devanagari Indic script the batch is invalid. "
95
+ "Natural spoken Hindi prose. Vary length: short (5-8), medium (10-15), "
96
+ "long (18-25) words. Everyday fluent register. Maximize consonant conjuncts."
97
+ ),
98
+ "hinglish": (
99
+ "Hinglish / code-mixed: Devanagari + Latin mixed in the SAME sentence, with "
100
+ "English loanwords, brands, or English clauses inside Hindi structure "
101
+ "(e.g. 'yaar maine abhi Swiggy pe order kiya, bohot deri ho rahi hai'). "
102
+ "Authentic casual, never forced."
103
+ ),
104
+ "numeric_entity": (
105
+ "Every sentence MUST contain at least one of: number, date, currency "
106
+ "(rupees / Rs. / numeral), phone-style digits, time, or address+pin. "
107
+ "Mix digit-form and spoken-word form across the batch."
108
+ ),
109
+ "prosody": (
110
+ "Short-to-medium sentences with strong emotional shape: questions ending ?, "
111
+ "exclamations ending !, or short interjections. Real conversational reactions."
112
+ ),
113
+ "named_entity": (
114
+ "Every sentence MUST include at least one real-sounding Indian proper noun "
115
+ "(person, place, or brand) in a full sentence - never a bare name list."
116
+ ),
117
+ }
118
+
119
+ TOPICS = {
120
+ "pure_hindi": [
121
+ "सुबह की दिनचर्या", "मानसून का मौसम", "पारिवारिक रिश्ते", "त्योहार और उत्सव",
122
+ "भारतीय व्यंजन", "गांव का जीवन", "शहर की भागदौड़", "स्कूल के दिन", "दोस्ती",
123
+ "यात्रा के अनुभव", "किताबें और पढ़ाई", "संगीत और कला", "स्वास्थ्य और योग",
124
+ "प्रकृति और पर्यावरण", "त्यौहारों की खरीदारी", "क्रिकेट और खेल",
125
+ "बचपन की यादें", "बाजार का माहौल", "मानसिक शांति", "सामाजिक जिम्मेदारी",
126
+ ],
127
+ "hinglish": [
128
+ "food delivery apps par order", "office ki daily chat",
129
+ "college friends ki baatcheet", "Instagram reels par comments",
130
+ "WhatsApp family group", "cab booking Uber/Ola",
131
+ "online shopping Flipkart/Amazon", "gym aur fitness goals",
132
+ "startup aur job interview", "movies aur OTT shows",
133
+ "cricket match commentary", "wedding planning",
134
+ "travel vlogging", "college assignments aur deadlines",
135
+ "relationship advice",
136
+ ],
137
+ "numeric_entity": [
138
+ "bank account aur transactions", "train/flight ticket booking",
139
+ "restaurant bill aur tip", "property ki keemat", "mobile recharge plans",
140
+ "electricity bill", "birthday aur anniversary dates",
141
+ "school admission fees", "online shopping cart total",
142
+ "delivery address aur pin code", "salary aur EMI", "grocery shopping list",
143
+ ],
144
+ "prosody": [
145
+ "अचानक अच्छी खबर", "गुस्से में बहस", "हैरानी भरी घटना", "डर या चिंता",
146
+ "खुशी का पल", "निराशा और अफसोस", "जल्दी में निकलना",
147
+ "किसी को चेतावनी देना", "तारीफ करना", "मदद मांगना",
148
+ "अजनबी से प्रश्न पूछना", "उत्सव में उत्साह",
149
+ ],
150
+ "named_entity": [
151
+ "मशहूर भारतीय हस्तियां", "प्रसिद्ध भारतीय शहर और स्मारक",
152
+ "भारतीय ब्रांड्स और कंपनियां", "बॉलीवुड सितारे", "भारतीय क्रिकेटर",
153
+ "राजनेता और इतिहास", "प्रसिद्ध भारतीय रेस्टोरेंट चेन",
154
+ "टेक कंपनियां भारत में", "प्रसिद्ध पर्यटन स्थल",
155
+ "भारतीय राज्यों की राजधानियां",
156
+ ],
157
+ }
158
+
159
+ SYSTEM_PROMPT = (
160
+ "You generate spoken Hindi/Hinglish TTS training utterances. "
161
+ "Write exactly as spoken. No markdown, bullets, emojis, asterisks, hashtags, URLs. "
162
+ "Spell out ambiguous abbreviations the way a speaker says them. "
163
+ "Each sentence self-contained. Everyday spoken register. "
164
+ "Never repeat near-duplicates inside a batch. "
165
+ "CRITICAL: For category pure_hindi use ONLY Hindi in Devanagari. "
166
+ "Never Gujarati, never any other Indian script. "
167
+ "Return ONLY raw JSON. No prose. No code fences. "
168
+ # Static pad — longer identical system prefix → higher Sarvam prompt-cache hit rate.
169
+ "STYLE: natural conversational TTS lines, varied openings, no lists, no meta talk. "
170
+ "OUTPUT: JSON object with key items; each item has text and notes. "
171
+ "QUALITY: phoneme-rich Hindi where required; authentic code-mix for hinglish; "
172
+ "explicit numbers/dates for numeric_entity; strong ?/! for prosody; "
173
+ "real Indian names/places/brands for named_entity. "
174
+ "REPEAT THIS CONTRACT EVERY CALL: same system instructions, same schema, "
175
+ "only the trailing topic line of the user message may change."
176
+ )
177
+
178
+
179
+ def category_stable_prefix(category: str) -> str:
180
+ return (
181
+ f"Category: {category}\n"
182
+ f"Rules: {CATEGORY_RULES[category]}\n\n"
183
+ f"Return exactly this JSON shape with exactly {BATCH_SIZE} items:\n"
184
+ f'{{"items":[{{"text":"...","notes":"tag"}}, ...]}}\n'
185
+ f'"text" = spoken sentence (prefer <=20 words). "notes" = 1-3 word tag.\n'
186
+ f"Keep JSON compact. Vary openings inside the batch.\n"
187
+ f"Do not copy the topic wording verbatim into every line.\n"
188
+ )
189
+
190
+
191
+ def build_user_message(category: str, topic: str, examples: list[str], salt: int) -> tuple[str, str, str]:
192
+ """Returns (full_user_message, stable_prefix, variable_suffix)."""
193
+ prefix = category_stable_prefix(category)
194
+ suffix = f"\nTopic: {topic}\nGenerate {BATCH_SIZE} now."
195
+ return prefix + suffix, prefix, suffix
196
+
197
+
198
+ _ITEM_PAIR_RE = re.compile(
199
+ r'"text"\s*:\s*"((?:\\.|[^"\\])*)"\s*,\s*"notes"\s*:\s*"((?:\\.|[^"\\])*)"',
200
+ )
201
+ _TEXT_ONLY_RE = re.compile(r'"text"\s*:\s*"((?:\\.|[^"\\])*)"')
202
+
203
+
204
+ def _unescape_json_str(s: str) -> str:
205
+ try:
206
+ return json.loads(f'"{s}"')
207
+ except json.JSONDecodeError:
208
+ return s.replace('\\"', '"').replace("\\n", "\n")
209
+
210
+
211
+ def parse_items_lenient(raw: str) -> list[dict]:
212
+ """Parse items JSON; if truncated mid-string, recover complete text/notes pairs."""
213
+ text = (raw or "").strip()
214
+ if text.startswith("```"):
215
+ text = re.sub(r"^```(?:json)?\s*", "", text)
216
+ text = re.sub(r"\s*```$", "", text)
217
+
218
+ try:
219
+ data = json.loads(text)
220
+ items = data.get("items")
221
+ if isinstance(items, list) and items:
222
+ return items
223
+ except json.JSONDecodeError:
224
+ pass
225
+
226
+ items: list[dict] = []
227
+ for m in _ITEM_PAIR_RE.finditer(text):
228
+ items.append({
229
+ "text": _unescape_json_str(m.group(1)),
230
+ "notes": _unescape_json_str(m.group(2)),
231
+ })
232
+ if not items:
233
+ for m in _TEXT_ONLY_RE.finditer(text):
234
+ items.append({"text": _unescape_json_str(m.group(1)), "notes": ""})
235
+
236
+ if not items:
237
+ raise ValueError(f"no recoverable items (raw_chars={len(text)})")
238
+ return items
239
+
240
+ CSV_FIELDS = [
241
+ "timestamp_utc",
242
+ "batch_num",
243
+ "category",
244
+ "topic",
245
+ "items",
246
+ "prompt_tokens",
247
+ "cached_tokens",
248
+ "uncached_input_tokens",
249
+ "completion_tokens",
250
+ "total_tokens",
251
+ "cache_hit_pct",
252
+ "cache_reported",
253
+ "prefix_share_pct",
254
+ "est_cacheable_tokens",
255
+ "cost_inr",
256
+ "cost_if_prefix_cached_inr",
257
+ "run_cost_inr",
258
+ "cum_cost_inr",
259
+ "cost_per_item_inr",
260
+ "cost_per_1k_out_inr",
261
+ "corpus_items",
262
+ "corpus_left",
263
+ ]
264
+
265
+ print_lock = threading.Lock()
266
+ io_lock = threading.Lock()
267
+
268
+
269
+ def is_valid_text(category: str, text: str) -> bool:
270
+ """Hard reject wrong-script leaks (esp. Gujarati in pure_hindi)."""
271
+ if not text or not text.strip():
272
+ return False
273
+ if category == "pure_hindi":
274
+ if not _DEVANAGARI_RE.search(text):
275
+ return False
276
+ if _FORBIDDEN_SCRIPT_RE.search(text):
277
+ return False
278
+ return True
279
+
280
+
281
+ def usage_to_dict(usage) -> dict:
282
+ if usage is None:
283
+ return {}
284
+ if isinstance(usage, dict):
285
+ return usage
286
+ try:
287
+ return usage.model_dump()
288
+ except Exception:
289
+ return {
290
+ "prompt_tokens": getattr(usage, "prompt_tokens", None),
291
+ "completion_tokens": getattr(usage, "completion_tokens", None),
292
+ "total_tokens": getattr(usage, "total_tokens", None),
293
+ "prompt_tokens_details": getattr(usage, "prompt_tokens_details", None),
294
+ "completion_tokens_details": getattr(usage, "completion_tokens_details", None),
295
+ }
296
+
297
+
298
+ def extract_cached_tokens(usage) -> tuple[int, bool]:
299
+ """
300
+ Return (cached_tokens, reported).
301
+ reported=False means Sarvam left prompt_tokens_details null — cannot meter KV hits.
302
+ """
303
+ dumped = usage_to_dict(usage)
304
+ if not dumped:
305
+ return 0, False
306
+
307
+ # Common OpenAI-style locations
308
+ candidates = []
309
+ ptd = dumped.get("prompt_tokens_details")
310
+ if isinstance(ptd, dict):
311
+ for key in (
312
+ "cached_tokens",
313
+ "cache_read_input_tokens",
314
+ "cached_prompt_tokens",
315
+ "prompt_cache_hit_tokens",
316
+ ):
317
+ if ptd.get(key) is not None:
318
+ candidates.append(int(ptd.get(key) or 0))
319
+ for key in (
320
+ "cached_tokens",
321
+ "cache_read_input_tokens",
322
+ "cached_prompt_tokens",
323
+ ):
324
+ if dumped.get(key) is not None:
325
+ candidates.append(int(dumped.get(key) or 0))
326
+
327
+ if ptd is None and not candidates:
328
+ return 0, False
329
+ if not candidates:
330
+ return 0, True # details present but zero
331
+ return max(candidates), True
332
+
333
+
334
+ def estimate_prefix_cacheable(prompt_tokens: int, stable_chars: int, total_chars: int) -> tuple[int, float]:
335
+ """Heuristic: share of prompt that is our byte-stable prefix (KV-friendly design)."""
336
+ if prompt_tokens <= 0 or total_chars <= 0:
337
+ return 0, 0.0
338
+ share = min(max(stable_chars / total_chars, 0.0), 1.0)
339
+ est = int(round(prompt_tokens * share))
340
+ return est, 100.0 * share
341
+
342
+
343
+ def calc_cost_inr(prompt_tokens: int, cached_tokens: int, completion_tokens: int) -> float:
344
+ """
345
+ Sarvam 105B ₹/1M: input 29.28 / cached 10.98 / output 73.20
346
+ cost = uncached_input * 29.28 + cached * 10.98 + output * 73.20 (per 1M)
347
+ """
348
+ cached = min(max(int(cached_tokens), 0), max(int(prompt_tokens), 0))
349
+ uncached = max(int(prompt_tokens) - cached, 0)
350
+ return (
351
+ uncached * PRICE_INPUT_PER_M
352
+ + cached * PRICE_CACHED_PER_M
353
+ + int(completion_tokens) * PRICE_OUTPUT_PER_M
354
+ ) / 1_000_000.0
355
+
356
+
357
+ def load_existing() -> list:
358
+ if not OUTPUT_FILE.exists():
359
+ return []
360
+ records = []
361
+ with OUTPUT_FILE.open("r", encoding="utf-8") as f:
362
+ for line in f:
363
+ line = line.strip()
364
+ if line:
365
+ records.append(json.loads(line))
366
+ return records
367
+
368
+
369
+ def load_cum_cost_from_csv() -> float:
370
+ if not COST_CSV.exists():
371
+ return 0.0
372
+ last = 0.0
373
+ with COST_CSV.open("r", encoding="utf-8", newline="") as f:
374
+ reader = csv.DictReader(f)
375
+ for row in reader:
376
+ try:
377
+ last = float(row.get("cum_cost_inr") or 0)
378
+ except (TypeError, ValueError):
379
+ continue
380
+ return last
381
+
382
+
383
+ def load_lifetime_completion() -> int:
384
+ if not COST_CSV.exists():
385
+ return 0
386
+ total = 0
387
+ with COST_CSV.open("r", encoding="utf-8", newline="") as f:
388
+ for row in csv.DictReader(f):
389
+ try:
390
+ total += int(float(row.get("completion_tokens") or 0))
391
+ except (TypeError, ValueError):
392
+ continue
393
+ return total
394
+
395
+
396
+ def ensure_cost_csv() -> None:
397
+ """Create CSV or migrate header when new columns are added."""
398
+ if not COST_CSV.exists() or COST_CSV.stat().st_size == 0:
399
+ with COST_CSV.open("w", encoding="utf-8", newline="") as f:
400
+ csv.DictWriter(f, fieldnames=CSV_FIELDS).writeheader()
401
+ return
402
+ with COST_CSV.open("r", encoding="utf-8", newline="") as f:
403
+ reader = csv.DictReader(f)
404
+ old_fields = list(reader.fieldnames or [])
405
+ rows = list(reader)
406
+ if old_fields == CSV_FIELDS:
407
+ return
408
+ with COST_CSV.open("w", encoding="utf-8", newline="") as f:
409
+ writer = csv.DictWriter(f, fieldnames=CSV_FIELDS, extrasaction="ignore")
410
+ writer.writeheader()
411
+ for row in rows:
412
+ writer.writerow({k: row.get(k, "") for k in CSV_FIELDS})
413
+
414
+
415
+ def append_cost_row(row: dict) -> None:
416
+ with COST_CSV.open("a", encoding="utf-8", newline="") as f:
417
+ csv.DictWriter(f, fieldnames=CSV_FIELDS).writerow(row)
418
+ f.flush()
419
+
420
+
421
+ def stream_emit(tag: str, text: str, line_start: list[bool]) -> None:
422
+ """Print SSE tokens live, prefixing each new line with [tag]."""
423
+ with print_lock:
424
+ for ch in text:
425
+ if line_start[0]:
426
+ sys.stdout.write(f"[{tag}] ")
427
+ line_start[0] = False
428
+ sys.stdout.write(ch)
429
+ if ch == "\n":
430
+ line_start[0] = True
431
+ sys.stdout.flush()
432
+
433
+
434
+ def call_model_streaming(
435
+ client: OpenAI,
436
+ batch_id: int,
437
+ category: str,
438
+ topic: str,
439
+ examples: list[str],
440
+ salt: int,
441
+ ):
442
+ user_msg, stable_prefix, _suffix = build_user_message(category, topic, examples, salt)
443
+ messages = [
444
+ {"role": "system", "content": SYSTEM_PROMPT},
445
+ {"role": "user", "content": user_msg},
446
+ ]
447
+ stable_chars = len(SYSTEM_PROMPT) + len(stable_prefix)
448
+ total_chars = len(SYSTEM_PROMPT) + len(user_msg)
449
+ tag = f"b{batch_id}"
450
+ last_err = None
451
+
452
+ for attempt in range(1, MAX_RETRIES + 1):
453
+ try:
454
+ with print_lock:
455
+ print(
456
+ f"\n===== SSE START [{tag}] {category} | {topic} "
457
+ f"(attempt {attempt}) =====",
458
+ flush=True,
459
+ )
460
+
461
+ # Always SSE. reasoning_effort=None → no thinking (gemma4).
462
+ # Docs: https://docs.sarvam.ai/api-reference/open-source/chat-completions
463
+ stream = client.chat.completions.create(
464
+ model=MODEL,
465
+ messages=messages,
466
+ temperature=1.0,
467
+ top_p=0.95,
468
+ max_tokens=MAX_TOKENS,
469
+ response_format={"type": "json_object"},
470
+ stream=True,
471
+ stream_options={"include_usage": True},
472
+ extra_body={"reasoning_effort": None},
473
+ )
474
+ parts: list[str] = []
475
+ usage = None
476
+ line_start = [True]
477
+ for chunk in stream:
478
+ if getattr(chunk, "usage", None) is not None:
479
+ usage = chunk.usage
480
+ if not chunk.choices:
481
+ continue
482
+ delta = chunk.choices[0].delta
483
+ # Ignore reasoning_content if any slips through
484
+ content = getattr(delta, "content", None)
485
+ if content:
486
+ stream_emit(tag, content, line_start)
487
+ parts.append(content)
488
+ raw = "".join(parts).strip()
489
+
490
+ items = parse_items_lenient(raw)
491
+ items = items[:BATCH_SIZE]
492
+ if not items:
493
+ raise ValueError("no items after parse")
494
+
495
+ with print_lock:
496
+ cached, reported = extract_cached_tokens(usage)
497
+ pt = int(getattr(usage, "prompt_tokens", 0) or 0) if usage else 0
498
+ ct = int(getattr(usage, "completion_tokens", 0) or 0) if usage else 0
499
+ hit = (100.0 * cached / pt) if pt else 0.0
500
+ print(
501
+ f"\n===== SSE END [{tag}] items={len(items)}/{BATCH_SIZE} "
502
+ f"prompt={pt} out={ct} cached={cached} ({hit:.0f}%) =====",
503
+ flush=True,
504
+ )
505
+
506
+ return items, usage, stable_chars, total_chars
507
+
508
+ except Exception as e:
509
+ last_err = e
510
+ wait = min(2 ** attempt, 20)
511
+ with print_lock:
512
+ print(
513
+ f" [retry {attempt}/{MAX_RETRIES}] [{tag}] {category}: {e} "
514
+ f"-- retrying in {wait}s",
515
+ flush=True,
516
+ )
517
+ time.sleep(wait)
518
+
519
+ raise RuntimeError(f"Failed after {MAX_RETRIES} retries [{tag}] {category}: {last_err}")
520
+
521
+
522
+ def main():
523
+ if not SARVAM_API_KEY:
524
+ sys.exit("Set SARVAM_API_KEY environment variable first.")
525
+
526
+ # v2 open-source endpoint requires api-subscription-key header
527
+ client = OpenAI(
528
+ api_key=SARVAM_API_KEY,
529
+ base_url=BASE_URL,
530
+ default_headers={"api-subscription-key": SARVAM_API_KEY},
531
+ )
532
+ ensure_cost_csv()
533
+
534
+ records = load_existing()
535
+ by_category = {c: [] for c in CATEGORY_TARGETS}
536
+ for r in records:
537
+ if r.get("type") in by_category:
538
+ by_category[r["type"]].append(r["text"])
539
+
540
+ counts = {c: len(by_category[c]) for c in CATEGORY_TARGETS}
541
+ next_index = (max((r["index"] for r in records), default=-1)) + 1
542
+
543
+ topic_cycles = {c: itertools.cycle(TOPICS[c]) for c in CATEGORY_TARGETS}
544
+ for c in CATEGORY_TARGETS:
545
+ skip = (counts[c] // BATCH_SIZE) % len(TOPICS[c])
546
+ for _ in range(skip):
547
+ next(topic_cycles[c])
548
+
549
+ total_target = sum(CATEGORY_TARGETS.values())
550
+ cum_cost = load_cum_cost_from_csv()
551
+ lifetime_completion = load_lifetime_completion()
552
+ run_prompt = run_cached = run_completion = run_total = 0
553
+ run_cost = 0.0
554
+ batch_num = 0
555
+ start = time.time()
556
+
557
+ print(f"Resuming: {sum(counts.values())} / {total_target} in {OUTPUT_FILE}")
558
+ print(f"Cost log: {COST_CSV} | prior cum cost ₹{cum_cost:.4f}")
559
+ print(f"Model: {MODEL} @ {BASE_URL}")
560
+ print(
561
+ f"Pricing (₹/1M): input={PRICE_INPUT_PER_M} "
562
+ f"cached={PRICE_CACHED_PER_M} output={PRICE_OUTPUT_PER_M}"
563
+ )
564
+ print(
565
+ "SSE live streaming ON. Truncated JSON is recovered (partial items kept). "
566
+ "reasoning_effort=None (no thinking)."
567
+ )
568
+ print(
569
+ f"Batch={BATCH_SIZE} | concurrency={CONCURRENCY} | "
570
+ f"context_examples={CONTEXT_EXAMPLES} | reasoning=off | stream=SSE"
571
+ )
572
+ for c, target in CATEGORY_TARGETS.items():
573
+ print(f" {c:16s} {counts[c]:>6}/{target}")
574
+ print()
575
+
576
+ with OUTPUT_FILE.open("a", encoding="utf-8") as out_f, ThreadPoolExecutor(
577
+ max_workers=CONCURRENCY
578
+ ) as pool:
579
+ for category, target in CATEGORY_TARGETS.items():
580
+ if counts[category] >= target:
581
+ continue
582
+ print(f"--- category {category} ({counts[category]}/{target}) ---", flush=True)
583
+
584
+ while counts[category] < target:
585
+ remaining = target - counts[category]
586
+ n_jobs = min(CONCURRENCY, max(1, (remaining + BATCH_SIZE - 1) // BATCH_SIZE))
587
+ examples_snapshot = list(by_category[category][-CONTEXT_EXAMPLES:]) if CONTEXT_EXAMPLES else []
588
+
589
+ jobs = []
590
+ for i in range(n_jobs):
591
+ batch_num += 1
592
+ topic = next(topic_cycles[category])
593
+ jobs.append({
594
+ "batch_id": batch_num,
595
+ "category": category,
596
+ "topic": topic,
597
+ "examples": examples_snapshot,
598
+ "salt": batch_num,
599
+ })
600
+
601
+ def commit(job, items, usage, stable_chars, total_chars):
602
+ nonlocal next_index, run_cost, cum_cost, lifetime_completion
603
+ nonlocal run_prompt, run_cached, run_completion, run_total
604
+ with io_lock:
605
+ new_records = []
606
+ dropped = 0
607
+ for it in items:
608
+ text = (it.get("text") or "").strip()
609
+ if not text:
610
+ continue
611
+ if not is_valid_text(category, text):
612
+ dropped += 1
613
+ continue
614
+ rec = {
615
+ "index": next_index,
616
+ "type": category,
617
+ "topic": job["topic"],
618
+ "text": text,
619
+ "notes": it.get("notes", ""),
620
+ "word_count": len(text.split()),
621
+ "char_count": len(text),
622
+ }
623
+ next_index += 1
624
+ new_records.append(rec)
625
+ if dropped:
626
+ with print_lock:
627
+ print(
628
+ f" !! dropped {dropped} bad-script items "
629
+ f"[b{job['batch_id']}] {category}",
630
+ flush=True,
631
+ )
632
+
633
+ for rec in new_records:
634
+ out_f.write(json.dumps(rec, ensure_ascii=False) + "\n")
635
+ by_category[category].append(rec["text"])
636
+ out_f.flush()
637
+ os.fsync(out_f.fileno())
638
+
639
+ counts[category] += len(new_records)
640
+
641
+ pt = int(getattr(usage, "prompt_tokens", 0) or 0) if usage else 0
642
+ ct = int(getattr(usage, "completion_tokens", 0) or 0) if usage else 0
643
+ tt = (
644
+ int(getattr(usage, "total_tokens", 0) or (pt + ct))
645
+ if usage
646
+ else (pt + ct)
647
+ )
648
+ cached, cache_reported = extract_cached_tokens(usage)
649
+ uncached = max(pt - cached, 0)
650
+ est_cacheable, prefix_share_pct = estimate_prefix_cacheable(
651
+ pt, stable_chars, total_chars
652
+ )
653
+ cost = calc_cost_inr(pt, cached, ct)
654
+ cost_if_prefix = calc_cost_inr(pt, est_cacheable, ct)
655
+ run_cost += cost
656
+ cum_cost += cost
657
+ cache_pct = (100.0 * cached / pt) if pt else 0.0
658
+
659
+ run_prompt += pt
660
+ run_cached += cached
661
+ run_completion += ct
662
+ run_total += tt
663
+ lifetime_completion += ct
664
+
665
+ corpus_items = sum(counts.values())
666
+ corpus_left = max(total_target - corpus_items, 0)
667
+ cost_per_item = (cum_cost / corpus_items) if corpus_items else 0.0
668
+ cost_per_1k_out = (
669
+ (cum_cost * 1000.0 / lifetime_completion)
670
+ if lifetime_completion
671
+ else 0.0
672
+ )
673
+
674
+ append_cost_row({
675
+ "timestamp_utc": datetime.now(timezone.utc).isoformat(),
676
+ "batch_num": job["batch_id"],
677
+ "category": category,
678
+ "topic": job["topic"],
679
+ "items": len(new_records),
680
+ "prompt_tokens": pt,
681
+ "cached_tokens": cached,
682
+ "uncached_input_tokens": uncached,
683
+ "completion_tokens": ct,
684
+ "total_tokens": tt,
685
+ "cache_hit_pct": f"{cache_pct:.1f}",
686
+ "cache_reported": "1" if cache_reported else "0",
687
+ "prefix_share_pct": f"{prefix_share_pct:.1f}",
688
+ "est_cacheable_tokens": est_cacheable,
689
+ "cost_inr": f"{cost:.6f}",
690
+ "cost_if_prefix_cached_inr": f"{cost_if_prefix:.6f}",
691
+ "run_cost_inr": f"{run_cost:.6f}",
692
+ "cum_cost_inr": f"{cum_cost:.6f}",
693
+ "cost_per_item_inr": f"{cost_per_item:.8f}",
694
+ "cost_per_1k_out_inr": f"{cost_per_1k_out:.6f}",
695
+ "corpus_items": corpus_items,
696
+ "corpus_left": corpus_left,
697
+ })
698
+
699
+ flag = "API" if cache_reported else "no-API-cache-field"
700
+ summary = (
701
+ f"[batch {job['batch_id']:>5}] {category:15s} "
702
+ f"+{len(new_records):<2} ({counts[category]}/{target}) | "
703
+ f"{job['topic'][:24]:24s} | "
704
+ f"in={pt} cached={cached} ({cache_pct:.0f}% {flag}) "
705
+ f"prefix~{prefix_share_pct:.0f}% out={ct} | "
706
+ f"₹{cost:.4f} | cum ₹{cum_cost:.4f}"
707
+ )
708
+
709
+ with print_lock:
710
+ print(summary, flush=True)
711
+
712
+ # Warm KV with 1 sequential request, then fan out the rest.
713
+ parallel_jobs = jobs
714
+ if WARM_CACHE_FIRST and jobs:
715
+ warm = jobs[0]
716
+ parallel_jobs = jobs[1:]
717
+ print(
718
+ f"\n>>> warming KV cache [b{warm['batch_id']}] {category} ...",
719
+ flush=True,
720
+ )
721
+ try:
722
+ items, usage, stable_chars, total_chars = call_model_streaming(
723
+ client,
724
+ warm["batch_id"],
725
+ warm["category"],
726
+ warm["topic"],
727
+ warm["examples"],
728
+ warm["salt"],
729
+ )
730
+ commit(warm, items, usage, stable_chars, total_chars)
731
+ except Exception as e:
732
+ with print_lock:
733
+ print(
734
+ f"!! FAILED warm [b{warm['batch_id']}] {category}: {e}",
735
+ flush=True,
736
+ )
737
+
738
+ if not parallel_jobs:
739
+ continue
740
+
741
+ print(
742
+ f"\n>>> launching {len(parallel_jobs)} concurrent requests "
743
+ f"for {category} ...",
744
+ flush=True,
745
+ )
746
+
747
+ futures = {
748
+ pool.submit(
749
+ call_model_streaming,
750
+ client,
751
+ job["batch_id"],
752
+ job["category"],
753
+ job["topic"],
754
+ job["examples"],
755
+ job["salt"],
756
+ ): job
757
+ for job in parallel_jobs
758
+ }
759
+
760
+ for fut in as_completed(futures):
761
+ job = futures[fut]
762
+ try:
763
+ items, usage, stable_chars, total_chars = fut.result()
764
+ except Exception as e:
765
+ with print_lock:
766
+ print(
767
+ f"!! FAILED [b{job['batch_id']}] {job['category']}: {e}",
768
+ flush=True,
769
+ )
770
+ continue
771
+ commit(job, items, usage, stable_chars, total_chars)
772
+
773
+ elapsed = time.time() - start
774
+ run_cache_pct = (100.0 * run_cached / run_prompt) if run_prompt else 0.0
775
+ print()
776
+ print("=" * 72)
777
+ print(f"DONE. {sum(counts.values())} items in {OUTPUT_FILE}")
778
+ print(f"This run: {batch_num} API calls in {elapsed / 60:.1f} min")
779
+ print(
780
+ f"Tokens — prompt={run_prompt:,} cached={run_cached:,} "
781
+ f"({run_cache_pct:.1f}%) completion={run_completion:,} total={run_total:,}"
782
+ )
783
+ print(f"Cost — this run ₹{run_cost:.4f} | cumulative ₹{cum_cost:.4f}")
784
+ print(f"Cost CSV: {COST_CSV.resolve()}")
785
+ print("=" * 72)
786
+
787
+
788
+ if __name__ == "__main__":
789
+ main()