File size: 23,909 Bytes
8fa5f35
 
 
 
 
 
 
 
 
417b020
8fa5f35
 
 
 
 
 
417b020
8fa5f35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
417b020
8fa5f35
 
 
 
 
 
 
 
 
 
417b020
 
 
 
 
 
8fa5f35
 
417b020
8fa5f35
 
 
 
 
 
 
 
 
 
 
417b020
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fa5f35
417b020
8fa5f35
417b020
 
 
 
 
 
 
8fa5f35
 
 
417b020
8fa5f35
 
 
417b020
8fa5f35
 
 
 
 
 
 
417b020
8fa5f35
 
 
 
 
 
417b020
8fa5f35
417b020
 
8fa5f35
417b020
 
 
 
 
 
 
8fa5f35
 
417b020
 
8fa5f35
417b020
8fa5f35
 
 
 
 
417b020
8fa5f35
417b020
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fa5f35
417b020
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fa5f35
417b020
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fa5f35
417b020
 
 
 
 
 
8fa5f35
417b020
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fa5f35
 
417b020
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fa5f35
417b020
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fa5f35
 
417b020
 
 
 
 
 
 
 
 
 
 
 
 
8fa5f35
 
 
 
 
417b020
 
8fa5f35
 
 
417b020
 
 
 
 
 
 
8fa5f35
 
 
 
 
 
417b020
 
8fa5f35
 
417b020
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fa5f35
417b020
 
 
 
 
 
 
 
8fa5f35
 
417b020
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fa5f35
417b020
8fa5f35
417b020
 
 
 
 
8fa5f35
 
 
 
 
417b020
 
23a4340
8fa5f35
 
 
417b020
 
23a4340
8fa5f35
 
 
23a4340
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
import time
import spaces
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import librosa
import gradio as gr
from huggingface_hub import hf_hub_download
from transformers import AutoModelForCausalLM, AutoTokenizer

# ==========================================
# 1. VOCABULARY & MODEL ARCHITECTURE (56.88M)
# ==========================================
REPO_ID = "Monster-Code/Jalapeno-ASR-preview"
FILENAME = "jalapeno_asr_preview.pt"
CORRECTOR_ID = "Qwen/Qwen2.5-0.5B-Instruct"

VOCAB = ["<pad>", "<blank>"] + list("abcdefghijklmnopqrstuvwxyz '-,.")
ID2CHAR = {i: c for i, c in enumerate(VOCAB)}


class RotaryPositionalEmbedding(nn.Module):
    def __init__(self, dim, max_seq_len=4096, base=10000.0):
        super().__init__()
        inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
        self.register_buffer("inv_freq", inv_freq, persistent=False)
        t = torch.arange(max_seq_len, dtype=torch.float32)
        freqs = torch.outer(t, inv_freq)
        emb = torch.cat((freqs, freqs), dim=-1)
        self.register_buffer("cos_cached", emb.cos(), persistent=False)
        self.register_buffer("sin_cached", emb.sin(), persistent=False)

    def forward(self, x):
        seq_len = x.size(2)
        cos = self.cos_cached[:seq_len].unsqueeze(0).unsqueeze(0)
        sin = self.sin_cached[:seq_len].unsqueeze(0).unsqueeze(0)
        x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
        rotated = torch.cat((-x2, x1), dim=-1)
        return (x * cos) + (rotated * sin)


class CausalConvSubsampling(nn.Module):
    def __init__(self, in_channels, out_channels):
        super().__init__()
        self.conv1 = nn.Conv2d(1, out_channels // 2, kernel_size=3, stride=2, padding=1)
        self.conv2 = nn.Conv2d(out_channels // 2, out_channels, kernel_size=3, stride=2, padding=1)

    def forward(self, x):
        x = x.unsqueeze(1)
        x = F.relu(self.conv1(x))
        x = F.relu(self.conv2(x))
        batch, channels, time_steps, freq = x.size()
        return x.permute(0, 2, 1, 3).contiguous().view(batch, time_steps, channels * freq)


class SoundwhaleEncoderLayer(nn.Module):
    def __init__(self, d_model=512, nhead=8, dim_feedforward=2048, dropout=0.1):
        super().__init__()
        self.d_model = d_model
        self.nhead = nhead
        self.head_dim = d_model // nhead
        self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout, batch_first=True)
        self.rope = RotaryPositionalEmbedding(self.head_dim)
        self.linear1 = nn.Linear(d_model, dim_feedforward)
        self.dropout = nn.Dropout(dropout)
        self.linear2 = nn.Linear(dim_feedforward, d_model)
        self.norm1 = nn.LayerNorm(d_model)
        self.norm2 = nn.LayerNorm(d_model)
        self.dropout1 = nn.Dropout(dropout)
        self.dropout2 = nn.Dropout(dropout)

    def forward(self, src, attn_mask=None):
        B, T, C = src.shape
        src2 = self.norm1(src)
        qkv = F.linear(src2, self.self_attn.in_proj_weight, self.self_attn.in_proj_bias)
        q, k, v = qkv.chunk(3, dim=-1)
        q = self.rope(q.view(B, T, self.nhead, self.head_dim).transpose(1, 2))
        k = self.rope(k.view(B, T, self.nhead, self.head_dim).transpose(1, 2))
        v = v.view(B, T, self.nhead, self.head_dim).transpose(1, 2)
        attn_out = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask)
        attn_out = self.self_attn.out_proj(attn_out.transpose(1, 2).contiguous().view(B, T, C))
        src = src + self.dropout1(attn_out)
        src2 = self.norm2(src)
        return src + self.dropout2(self.linear2(self.dropout(F.relu(self.linear1(src2)))))


class JalapenoASR56M(nn.Module):
    def __init__(self, num_classes=len(VOCAB), d_model=512, num_layers=16, nhead=8, lookahead_frames=4):
        super().__init__()
        self.lookahead_frames = lookahead_frames
        self.subsampling = CausalConvSubsampling(80, d_model)
        self.proj = nn.Linear(d_model * 20, d_model)
        self.layers = nn.ModuleList([
            SoundwhaleEncoderLayer(d_model=d_model, nhead=nhead, dim_feedforward=2048)
            for _ in range(num_layers)
        ])
        self.ctc_head = nn.Linear(d_model, num_classes)

    def forward(self, mel_input, override_lookahead=None):
        x = self.proj(self.subsampling(mel_input))
        seq_len = x.size(1)
        la = self.lookahead_frames if override_lookahead is None else override_lookahead
        mask = torch.triu(
            torch.full((seq_len, seq_len), float("-inf"), device=x.device),
            diagonal=la + 1,
        )
        for layer in self.layers:
            x = layer(x, attn_mask=mask)
        return self.ctc_head(x)


# ==========================================
# 2. LOAD ACOUSTIC MODEL & QWEN2.5-0.5B AT STARTUP
# ==========================================
ckpt_path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME)
ckpt = torch.load(ckpt_path, map_location="cpu")
default_lookahead = ckpt.get("lookahead_frames", 4) if isinstance(ckpt, dict) else 4
state_dict = ckpt["model_state"] if isinstance(ckpt, dict) and "model_state" in ckpt else ckpt

model = JalapenoASR56M(lookahead_frames=default_lookahead)
model.load_state_dict(state_dict, strict=True)
model.eval().to("cuda")

corrector_tokenizer = AutoTokenizer.from_pretrained(CORRECTOR_ID)
corrector_model = AutoModelForCausalLM.from_pretrained(
    CORRECTOR_ID,
    torch_dtype=torch.float16,
).eval().to("cuda")


# ==========================================
# 3. GREEDY CTC ARGMAX & QWEN2.5-0.5B ENHANCER
# ==========================================
def ctc_argmax_decode(token_ids):
    chars = []
    prev = None
    for idx in token_ids:
        if idx != prev and idx not in (0, 1):
            chars.append(ID2CHAR.get(idx, ""))
        prev = idx
    return "".join(chars).strip()


def enhance_with_qwen(raw_transcript):
    messages = [
        {
            "role": "system",
            "content": (
                "You are an ASR transcript spelling and punctuation corrector. "
                "Fix phonetic spelling errors, merged or split words, capitalization, and punctuation "
                "in the noisy speech-to-text output while keeping the exact original meaning and words. "
                "CRITICAL: Output ONLY the corrected transcript text. Do NOT include any explanations, "
                "prefixes, labels, quotation marks, markdown, or any other text."
            ),
        },
        {
            "role": "user",
            "content": raw_transcript,
        },
    ]
    prompt = corrector_tokenizer.apply_chat_template(
        messages, tokenize=False, add_generation_prompt=True
    )
    inputs = corrector_tokenizer(prompt, return_tensors="pt").to("cuda")

    torch.cuda.synchronize()
    t0 = time.perf_counter()
    with torch.no_grad():
        out_ids = corrector_model.generate(
            **inputs,
            max_new_tokens=max(32, int(inputs["input_ids"].shape[1] * 1.6)),
            do_sample=False,
            pad_token_id=corrector_tokenizer.eos_token_id,
        )
    torch.cuda.synchronize()
    llm_ms = (time.perf_counter() - t0) * 1000.0

    new_tokens = out_ids[0][inputs["input_ids"].shape[1]:]
    cleaned = corrector_tokenizer.decode(new_tokens, skip_special_tokens=True).strip()
    # Strip any accidental surrounding quotes
    if len(cleaned) >= 2 and cleaned[0] == cleaned[-1] and cleaned[0] in ('"', "'"):
        cleaned = cleaned[1:-1].strip()
    return cleaned or raw_transcript, llm_ms


@spaces.GPU(duration=30)
def transcribe_audio(audio_path, lookahead_ms, enable_qwen):
    if not audio_path:
        return (
            "Record from your microphone or upload an audio file to begin.",
            "",
            "—",
            "—",
            "—",
        )

    wav, _ = librosa.load(audio_path, sr=16000, mono=True)
    if len(wav) == 0:
        return "Empty audio clip detected.", "", "—", "—", "—"

    audio_dur = len(wav) / 16000.0

    # 80-bin HTK Log-Mel Spectrogram (10ms hop, 25ms window)
    mel = librosa.feature.melspectrogram(
        y=wav, sr=16000, n_fft=400, hop_length=160, n_mels=80, power=2.0, norm=None, htk=True
    )
    log_mel = torch.tensor(np.log(mel + 1e-5), dtype=torch.float32).transpose(0, 1).unsqueeze(0).to("cuda")

    lookahead_frames = int(lookahead_ms // 40)

    # 1. Acoustic Model Forward + Greedy Argmax Collapse
    torch.cuda.synchronize()
    t0 = time.perf_counter()
    with torch.no_grad():
        logits = model(log_mel, override_lookahead=lookahead_frames)[0]
        pred_ids = torch.argmax(logits, dim=-1).cpu().tolist()
    torch.cuda.synchronize()
    asr_sec = max(time.perf_counter() - t0, 1e-6)

    raw_transcript = ctc_argmax_decode(pred_ids) or "[No speech detected]"
    rtfx = audio_dur / asr_sec

    # 2. Optional Qwen2.5-0.5B Spelling & Punctuation Enhancement
    if enable_qwen and raw_transcript != "[No speech detected]":
        enhanced_transcript, llm_ms = enhance_with_qwen(raw_transcript)
        latency_display = f"{asr_sec * 1000:.1f} ms ASR + {llm_ms:.0f} ms Qwen"
    else:
        enhanced_transcript = raw_transcript
        latency_display = f"{asr_sec * 1000:.1f} ms ASR"

    return (
        enhanced_transcript,
        raw_transcript,
        f"{audio_dur:.2f} s",
        latency_display,
        f"{rtfx:,.0f}x RTFx",
    )


# ==========================================
# 4. CUSTOM OKLCH DESIGN SYSTEM STYLING
# ==========================================
DESIGN_SYSTEM_CSS = """
@import url('https://fonts.googleapis.com/css2?family=Lora:ital,wght@0,500;0,600;1,400&family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=Roboto+Mono:wght@400;500;600&display=swap');

:root {
  --background: oklch(0.9232 0.0026 48.7171);
  --foreground: oklch(0.2795 0.0368 260.0310);
  --card: oklch(0.9699 0.0013 106.4238);
  --card-foreground: oklch(0.2795 0.0368 260.0310);
  --popover: oklch(0.9699 0.0013 106.4238);
  --popover-foreground: oklch(0.2795 0.0368 260.0310);
  --primary: oklch(0.5854 0.2041 277.1173);
  --primary-foreground: oklch(1.0000 0 0);
  --secondary: oklch(0.8687 0.0043 56.3660);
  --secondary-foreground: oklch(0.4461 0.0263 256.8018);
  --muted: oklch(0.9232 0.0026 48.7171);
  --muted-foreground: oklch(0.5510 0.0234 264.3637);
  --accent: oklch(0.9376 0.0260 321.9388);
  --accent-foreground: oklch(0.3729 0.0306 259.7328);
  --destructive: oklch(0.6368 0.2078 25.3313);
  --destructive-foreground: oklch(1.0000 0 0);
  --border: oklch(0.8687 0.0043 56.3660);
  --input: oklch(0.8687 0.0043 56.3660);
  --ring: oklch(0.5854 0.2041 277.1173);
  --font-sans: 'Plus Jakarta Sans', -apple-system, BlinkMacSystemFont, sans-serif;
  --font-serif: 'Lora', Georgia, serif;
  --font-mono: 'Roboto Mono', monospace;
  --radius: 1.25rem;
  --shadow-sm: 2px 2px 10px 4px hsl(240 4% 60% / 0.14), 2px 1px 2px 3px hsl(240 4% 60% / 0.12);
  --shadow-md: 2px 2px 10px 4px hsl(240 4% 60% / 0.18), 2px 2px 4px 3px hsl(240 4% 60% / 0.18);
  --shadow-lg: 2px 2px 10px 4px hsl(240 4% 60% / 0.18), 2px 4px 6px 3px hsl(240 4% 60% / 0.18);
}

.dark, body.dark {
  --background: oklch(0.2244 0.0074 67.4370);
  --foreground: oklch(0.9288 0.0126 255.5078);
  --card: oklch(0.2801 0.0080 59.3379);
  --card-foreground: oklch(0.9288 0.0126 255.5078);
  --popover: oklch(0.2801 0.0080 59.3379);
  --popover-foreground: oklch(0.9288 0.0126 255.5078);
  --primary: oklch(0.6801 0.1583 276.9349);
  --primary-foreground: oklch(0.2244 0.0074 67.4370);
  --secondary: oklch(0.3359 0.0077 59.4197);
  --secondary-foreground: oklch(0.8717 0.0093 258.3382);
  --muted: oklch(0.2287 0.0074 67.4469);
  --muted-foreground: oklch(0.7137 0.0192 261.3246);
  --accent: oklch(0.3896 0.0074 59.4734);
  --accent-foreground: oklch(0.8717 0.0093 258.3382);
  --destructive: oklch(0.6368 0.2078 25.3313);
  --destructive-foreground: oklch(0.2244 0.0074 67.4370);
  --border: oklch(0.3359 0.0077 59.4197);
  --input: oklch(0.3359 0.0077 59.4197);
  --ring: oklch(0.6801 0.1583 276.9349);
  --shadow-sm: 2px 2px 10px 4px hsl(0 0% 0% / 0.18), 2px 1px 2px 3px hsl(0 0% 0% / 0.18);
  --shadow-md: 2px 2px 10px 4px hsl(0 0% 0% / 0.22), 2px 2px 4px 3px hsl(0 0% 0% / 0.20);
  --shadow-lg: 2px 2px 10px 4px hsl(0 0% 0% / 0.26), 2px 4px 6px 3px hsl(0 0% 0% / 0.22);
}

@media (prefers-color-scheme: dark) {
  :root:not(.light) {
    --background: oklch(0.2244 0.0074 67.4370);
    --foreground: oklch(0.9288 0.0126 255.5078);
    --card: oklch(0.2801 0.0080 59.3379);
    --card-foreground: oklch(0.9288 0.0126 255.5078);
    --popover: oklch(0.2801 0.0080 59.3379);
    --popover-foreground: oklch(0.9288 0.0126 255.5078);
    --primary: oklch(0.6801 0.1583 276.9349);
    --primary-foreground: oklch(0.2244 0.0074 67.4370);
    --secondary: oklch(0.3359 0.0077 59.4197);
    --secondary-foreground: oklch(0.8717 0.0093 258.3382);
    --muted: oklch(0.2287 0.0074 67.4469);
    --muted-foreground: oklch(0.7137 0.0192 261.3246);
    --accent: oklch(0.3896 0.0074 59.4734);
    --accent-foreground: oklch(0.8717 0.0093 258.3382);
    --destructive: oklch(0.6368 0.2078 25.3313);
    --destructive-foreground: oklch(0.2244 0.0074 67.4370);
    --border: oklch(0.3359 0.0077 59.4197);
    --input: oklch(0.3359 0.0077 59.4197);
    --ring: oklch(0.6801 0.1583 276.9349);
    --shadow-sm: 2px 2px 10px 4px hsl(0 0% 0% / 0.18), 2px 1px 2px 3px hsl(0 0% 0% / 0.18);
    --shadow-md: 2px 2px 10px 4px hsl(0 0% 0% / 0.22), 2px 2px 4px 3px hsl(0 0% 0% / 0.20);
    --shadow-lg: 2px 2px 10px 4px hsl(0 0% 0% / 0.26), 2px 4px 6px 3px hsl(0 0% 0% / 0.22);
  }
}

/* Global Canvas & Typography */
body, .gradio-container {
  background-color: var(--background) !important;
  color: var(--foreground) !important;
  font-family: var(--font-sans) !important;
}

.gradio-container {
  max-width: 1120px !important;
  margin: 0 auto !important;
  padding: 28px 20px 40px 20px !important;
}

/* Hero Surface Card */
.ds-hero {
  background: var(--card);
  color: var(--card-foreground);
  border: 1px solid var(--border);
  border-radius: var(--radius);
  box-shadow: var(--shadow-md);
  padding: 28px 32px;
  margin-bottom: 22px;
  position: relative;
  overflow: hidden;
}

.ds-hero-eyebrow {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  font-family: var(--font-mono);
  font-size: 0.76rem;
  font-weight: 600;
  letter-spacing: 0.04em;
  text-transform: uppercase;
  padding: 5px 12px;
  border-radius: 999px;
  background: var(--accent);
  color: var(--accent-foreground);
  border: 1px solid var(--border);
  margin-bottom: 14px;
}

.ds-hero h1 {
  font-family: var(--font-sans);
  font-size: 2rem;
  font-weight: 800;
  letter-spacing: -0.025em;
  line-height: 1.2;
  margin: 0 0 8px 0;
  color: var(--foreground);
}

.ds-hero h1 span {
  color: var(--primary);
}

.ds-hero-subtitle {
  font-family: var(--font-serif);
  font-size: 1.02rem;
  line-height: 1.55;
  color: var(--muted-foreground);
  margin: 0 0 18px 0;
  max-width: 760px;
}

.ds-pill-row {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.ds-pill {
  font-family: var(--font-mono);
  font-size: 0.78rem;
  font-weight: 500;
  padding: 6px 13px;
  border-radius: calc(var(--radius) - 6px);
  background: var(--muted);
  color: var(--secondary-foreground);
  border: 1px solid var(--border);
}

/* Elevated Panel Cards */
.ds-panel {
  background: var(--card) !important;
  color: var(--card-foreground) !important;
  border: 1px solid var(--border) !important;
  border-radius: var(--radius) !important;
  box-shadow: var(--shadow-md) !important;
  padding: 20px !important;
}

/* Gradio Block & Input Overrides */
.ds-panel .block,
.ds-panel .form {
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
}

.ds-panel label span,
.ds-panel .label-wrap span {
  font-family: var(--font-sans) !important;
  font-weight: 600 !important;
  font-size: 0.88rem !important;
  color: var(--foreground) !important;
}

.ds-panel .info {
  font-family: var(--font-sans) !important;
  color: var(--muted-foreground) !important;
  font-size: 0.8rem !important;
}

/* Audio Dropzone & Controls */
.ds-audio {
  background: var(--muted) !important;
  border: 1.5px dashed var(--border) !important;
  border-radius: calc(var(--radius) - 2px) !important;
  transition: border-color 0.2s ease, box-shadow 0.2s ease;
}

.ds-audio:hover {
  border-color: var(--primary) !important;
}

/* Enhanced Transcript Textarea */
.ds-transcript textarea {
  background: var(--muted) !important;
  color: var(--foreground) !important;
  border: 1px solid var(--border) !important;
  border-radius: calc(var(--radius) - 2px) !important;
  font-family: var(--font-sans) !important;
  font-size: 1.12rem !important;
  line-height: 1.65 !important;
  padding: 16px !important;
  transition: border-color 0.2s ease, box-shadow 0.2s ease;
}

.ds-transcript textarea:focus {
  border-color: var(--ring) !important;
  box-shadow: 0 0 0 3px color-mix(in oklch, var(--ring) 22%, transparent) !important;
  outline: none !important;
}

/* Raw Greedy Textarea */
.ds-raw textarea {
  background: var(--muted) !important;
  color: var(--muted-foreground) !important;
  border: 1px solid var(--border) !important;
  border-radius: calc(var(--radius) - 4px) !important;
  font-family: var(--font-mono) !important;
  font-size: 0.92rem !important;
  line-height: 1.55 !important;
  padding: 12px 14px !important;
}

/* Monospace Telemetry Boxes */
.ds-metric textarea,
.ds-metric input {
  background: var(--muted) !important;
  color: var(--foreground) !important;
  border: 1px solid var(--border) !important;
  border-radius: calc(var(--radius) - 4px) !important;
  font-family: var(--font-mono) !important;
  font-size: 0.88rem !important;
  font-weight: 600 !important;
  text-align: center !important;
  padding: 10px 8px !important;
}

/* Buttons */
button.ds-btn-primary {
  background: var(--primary) !important;
  color: var(--primary-foreground) !important;
  border: 1px solid var(--primary) !important;
  border-radius: calc(var(--radius) - 4px) !important;
  font-family: var(--font-sans) !important;
  font-weight: 700 !important;
  font-size: 0.94rem !important;
  padding: 11px 20px !important;
  box-shadow: var(--shadow-sm) !important;
  transition: transform 0.12s ease, filter 0.15s ease !important;
}

button.ds-btn-primary:hover {
  filter: brightness(1.07) !important;
  transform: translateY(-1px);
}

button.ds-btn-secondary {
  background: var(--secondary) !important;
  color: var(--secondary-foreground) !important;
  border: 1px solid var(--border) !important;
  border-radius: calc(var(--radius) - 4px) !important;
  font-family: var(--font-sans) !important;
  font-weight: 600 !important;
  font-size: 0.92rem !important;
  padding: 11px 18px !important;
  transition: filter 0.15s ease !important;
}

button.ds-btn-secondary:hover {
  filter: brightness(0.96) !important;
}

/* Checkbox & Slider Accent */
input[type="range"],
input[type="checkbox"] {
  accent-color: var(--primary) !important;
}

/* Footer */
.ds-footer {
  text-align: center;
  margin-top: 22px;
  font-family: var(--font-mono);
  font-size: 0.78rem;
  color: var(--muted-foreground);
}

.ds-footer a {
  color: var(--primary);
  text-decoration: none;
  font-weight: 600;
}

.ds-footer a:hover {
  text-decoration: underline;
}

footer {
  display: none !important;
}
"""

with gr.Blocks(css=DESIGN_SYSTEM_CSS, title="Jalapeno-ASR-preview + Qwen2.5-0.5B") as demo:
    gr.HTML(
        """
        <div class="ds-hero">
            <div class="ds-hero-eyebrow">🌶️ Greedy CTC Argmax • Enhanced by Qwen2.5-0.5B</div>
            <h1>Jalapeno-ASR-<span>preview</span></h1>
            <p class="ds-hero-subtitle">
                56.88M-parameter Causal Transformer CTC with Rotary Position Embeddings (RoPE)
                and chunked lookahead, decoded with Greedy Argmax and enhanced by Qwen2.5-0.5B
                for spelling and punctuation restoration.
            </p>
            <div class="ds-pill-row">
                <span class="ds-pill">56.88M Acoustic Model</span>
                <span class="ds-pill">160ms Default Lookahead</span>
                <span class="ds-pill">Greedy CTC Argmax</span>
                <span class="ds-pill">Enhanced by Qwen2.5-0.5B</span>
            </div>
        </div>
        """
    )

    with gr.Row(equal_height=False):
        with gr.Column(scale=5, elem_classes=["ds-panel"]):
            audio_input = gr.Audio(
                sources=["microphone", "upload"],
                type="filepath",
                label="Audio Input (Microphone or File)",
                elem_classes=["ds-audio"],
            )
            enable_qwen = gr.Checkbox(
                value=True,
                label="Text enhanced by Qwen2.5-0.5B",
                info="Restores spelling, word boundaries, capitalization, and punctuation.",
            )
            lookahead_slider = gr.Slider(
                minimum=0,
                maximum=320,
                value=160,
                step=40,
                label="Streaming Lookahead (ms)",
                info="160ms = 4 subsampled frames. Set to 0ms for strictly causal inference.",
            )
            with gr.Row():
                clear_btn = gr.ClearButton(
                    [audio_input],
                    value="Clear",
                    elem_classes=["ds-btn-secondary"],
                )
                run_btn = gr.Button(
                    "Transcribe Audio",
                    variant="primary",
                    elem_classes=["ds-btn-primary"],
                )

        with gr.Column(scale=6, elem_classes=["ds-panel"]):
            enhanced_output = gr.Textbox(
                label="Transcription (Text enhanced by Qwen2.5-0.5B)",
                lines=5,
                placeholder="Speak into your microphone or upload an audio clip...",
                show_copy_button=True,
                elem_classes=["ds-transcript"],
            )
            raw_output = gr.Textbox(
                label="Raw Acoustic Output (Greedy CTC Argmax)",
                lines=3,
                placeholder="Raw character-level CTC argmax output...",
                show_copy_button=True,
                elem_classes=["ds-raw"],
            )
            with gr.Row():
                dur_box = gr.Textbox(
                    label="Audio Duration",
                    value="—",
                    interactive=False,
                    elem_classes=["ds-metric"],
                )
                lat_box = gr.Textbox(
                    label="Compute Latency",
                    value="—",
                    interactive=False,
                    elem_classes=["ds-metric"],
                )
                rtfx_box = gr.Textbox(
                    label="Acoustic Speed",
                    value="—",
                    interactive=False,
                    elem_classes=["ds-metric"],
                )

    gr.HTML(
        """
        <div class="ds-footer">
            Acoustic Model: <a href="https://huggingface.co/Monster-Code/Jalapeno-ASR-preview" target="_blank">Monster-Code/Jalapeno-ASR-preview</a>
            &nbsp;•&nbsp; Greedy CTC Argmax &nbsp;•&nbsp; Text enhanced by
            <a href="https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct" target="_blank">Qwen/Qwen2.5-0.5B-Instruct</a>
        </div>
        """
    )

    run_btn.click(
        fn=transcribe_audio,
        inputs=[audio_input, lookahead_slider, enable_qwen],
        outputs=[enhanced_output, raw_output, dur_box, lat_box, rtfx_box],
        api_name=False,
    )
    audio_input.stop_recording(
        fn=transcribe_audio,
        inputs=[audio_input, lookahead_slider, enable_qwen],
        outputs=[enhanced_output, raw_output, dur_box, lat_box, rtfx_box],
        api_name=False,
    )

if __name__ == "__main__":
    demo.launch(show_api=False)