File size: 33,158 Bytes
6d0b2e0
 
fa0a5bf
8946a99
fa0a5bf
6d0b2e0
fa0a5bf
6d0b2e0
 
 
 
fa0a5bf
6d0b2e0
fa0a5bf
6d0b2e0
 
 
 
 
 
 
d7eebff
6d0b2e0
 
 
 
8946a99
6d0b2e0
 
 
 
 
 
8946a99
d7eebff
 
 
 
 
 
8946a99
 
754fb9f
6d0b2e0
 
 
8946a99
 
6d0b2e0
8946a99
6d0b2e0
fa0a5bf
8946a99
6d0b2e0
8946a99
6d0b2e0
 
 
f04cbc6
8946a99
 
 
 
6d0b2e0
f04cbc6
 
 
 
 
6d0b2e0
8946a99
 
 
 
 
 
 
6d0b2e0
 
 
 
 
8946a99
6d0b2e0
 
 
8946a99
 
6d0b2e0
f04cbc6
8946a99
6d0b2e0
d7eebff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d0b2e0
d7eebff
 
6d0b2e0
 
 
 
d7eebff
6d0b2e0
 
 
8946a99
d7eebff
8946a99
 
 
754fb9f
8946a99
754fb9f
8946a99
d7eebff
754fb9f
8946a99
 
 
 
 
 
d7eebff
8946a99
d7eebff
8946a99
 
 
754fb9f
 
8946a99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d0b2e0
d7eebff
 
6d0b2e0
d7eebff
6d0b2e0
 
 
 
 
 
 
 
 
f04cbc6
6d0b2e0
 
 
 
 
f04cbc6
6d0b2e0
 
 
 
 
 
d7eebff
8946a99
f04cbc6
d7eebff
f04cbc6
 
 
 
 
6d0b2e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f04cbc6
 
6d0b2e0
 
f04cbc6
 
6d0b2e0
 
 
 
f04cbc6
8946a99
f04cbc6
6d0b2e0
 
 
 
 
 
 
 
 
 
 
f04cbc6
 
d7eebff
6d0b2e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8946a99
6d0b2e0
f04cbc6
 
6d0b2e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8946a99
 
6d0b2e0
 
f04cbc6
 
6d0b2e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f04cbc6
6d0b2e0
 
f04cbc6
6d0b2e0
 
 
 
 
 
 
 
f04cbc6
6d0b2e0
 
 
 
 
 
 
 
8946a99
 
6d0b2e0
 
f04cbc6
6d0b2e0
 
 
 
 
 
 
 
 
 
f04cbc6
 
6d0b2e0
 
f04cbc6
 
6d0b2e0
 
 
 
d7eebff
8946a99
6d0b2e0
8946a99
 
 
 
 
 
d7eebff
 
8946a99
6d0b2e0
 
f04cbc6
6d0b2e0
 
 
 
 
 
 
 
 
d7eebff
 
6d0b2e0
d7eebff
6d0b2e0
d7eebff
6d0b2e0
 
d7eebff
6d0b2e0
f04cbc6
6d0b2e0
 
d7eebff
 
8946a99
d7eebff
8946a99
 
d7eebff
 
8946a99
d7eebff
8946a99
d7eebff
8946a99
 
d7eebff
8946a99
fa0a5bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d0b2e0
8946a99
6d0b2e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8946a99
d7eebff
 
 
6d0b2e0
f04cbc6
d7eebff
 
f04cbc6
 
d7eebff
 
8946a99
754fb9f
 
8946a99
 
 
 
 
d7eebff
 
8946a99
 
6d0b2e0
 
d7eebff
 
6d0b2e0
d7eebff
 
f04cbc6
d7eebff
754fb9f
6d0b2e0
 
d7eebff
f04cbc6
 
6d0b2e0
 
 
 
 
8946a99
6d0b2e0
fa0a5bf
 
6d0b2e0
f04cbc6
 
6d0b2e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f04cbc6
 
 
 
 
d7eebff
 
 
8946a99
 
 
6d0b2e0
 
f04cbc6
6d0b2e0
 
 
 
 
 
 
f04cbc6
 
 
 
6d0b2e0
 
 
 
f04cbc6
6d0b2e0
8946a99
f04cbc6
6d0b2e0
 
 
 
 
f04cbc6
 
 
 
 
 
 
6d0b2e0
 
 
 
 
f04cbc6
6d0b2e0
 
fa0a5bf
6d0b2e0
 
8946a99
fa0a5bf
 
 
 
 
d7eebff
fa0a5bf
 
6d0b2e0
 
 
 
f04cbc6
6d0b2e0
 
 
f04cbc6
6d0b2e0
 
 
8946a99
 
 
 
d7eebff
8946a99
 
 
 
d7eebff
8946a99
 
6d0b2e0
 
 
 
d7eebff
6d0b2e0
d7eebff
 
 
 
f04cbc6
fa0a5bf
6d0b2e0
8946a99
 
f04cbc6
 
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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
#!/usr/bin/env python3
"""
Indian-style animated retirement invitation for Mamta: 1080x1920, 30fps, H.264 + AAC MP4.
Maroon/gold palette, rotating mandala, marigold toran, flickering diyas, colour emoji.
v5: her exact quote wording + original synthesised soundtrack (tanpura, sitar melody, bells).
"""
import os, math, subprocess, urllib.request, random, wave
import numpy as np
from PIL import Image, ImageDraw, ImageFont, ImageFilter, features

W, H, FPS = 1080, 1920, 30
SR = 44100
OUT = "/tmp/mamta_retirement_invitation.mp4"
WAV = "/tmp/soundtrack.wav"
POSTER = "/tmp/poster.jpg"
FDIR = "/tmp/fonts"
os.makedirs(FDIR, exist_ok=True)

BG_TOP, BG_BOT = (78, 15, 36), (44, 7, 20)
GOLD, GOLD_D, GOLD_L = (232, 193, 115), (201, 150, 47), (245, 222, 166)
CREAM, MARIGOLD, ORANGE = (253, 243, 224), (240, 160, 42), (226, 112, 28)
SOFT = (246, 234, 212)

# ----------------------------------------------------------------- event text
EV = dict(
    name="Mamta",
    hindi="\u0936\u0941\u092d \u0938\u0947\u0935\u093e\u0928\u093f\u0935\u0943\u0924\u094d\u0924\u093f",
    kicker1_en="WITH GREAT JOY",
    script1="You\u2019re Invited",
    sub1="a celebration of a beautiful journey",
    kicker2="IN HONOUR OF",
    body2="on the joyous occasion of her retirement",
    small2="30 SEPTEMBER 2026",
    message=[
        dict(kind="bodyi", size=54, color=CREAM, weight=600,
             lines=["\u201cThe bell is ringing one last time\u2026\u201d"]),
        dict(kind="serif", size=48, color=CREAM, weight=500,
             lines=["It is now time to say goodbye", "to my teaching profession."]),
        dict(kind="serif", size=46, color=CREAM, weight=500,
             lines=["To seek your good wishes & blessings,", "a party has been organised."]),
    ],
    msg_sig="\u2014 Mamta",
    msg_foot="A LIFETIME OF TEACHING",
    card_title="Celebratory Lunch",
    when_label="WHEN",
    when_1="Wednesday, 30 September 2026",
    time_label="TIME",
    time_1="13.30 hrs (1:30 pm)",
    where_label="WHERE",
    where_1="New Ros Common, Kasauli",
    sub3="Your presence will make it complete",
    quote=["The bell has rung,", "but the lessons will echo on."],
    kicker6="WITH LOVE AND BLESSINGS",
    script6="Celebrate With You",
    sig="Mamta & family",
)

# ----------------------------------------------------------------- fonts
GH = "https://raw.githubusercontent.com/google/fonts/main/ofl/"
EMOJI_URLS = [
    "https://raw.githubusercontent.com/googlefonts/noto-emoji/main/fonts/NotoColorEmoji.ttf",
    "https://raw.githubusercontent.com/googlefonts/noto-emoji/main/fonts/Noto-COLRv1-emojicompat.ttf",
]
FONT_URLS = {
    "script": [GH + "greatvibes/GreatVibes-Regular.ttf"],
    "serif": [GH + "playfairdisplay/PlayfairDisplay%5Bwght%5D.ttf"],
    "body": [GH + "cormorantgaramond/CormorantGaramond%5Bwght%5D.ttf"],
    "bodyi": [GH + "cormorantgaramond/CormorantGaramond-Italic%5Bwght%5D.ttf"],
    "hindi": [GH + "notoserifdevanagari/NotoSerifDevanagari%5Bwdth%2Cwght%5D.ttf"],
}

def fetch(url, dest):
    req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
    with urllib.request.urlopen(req, timeout=120) as r, open(dest, "wb") as fh:
        fh.write(r.read())
    return os.path.getsize(dest)

FPATH = {}
for key, urls in FONT_URLS.items():
    for i, u in enumerate(urls):
        dest = os.path.join(FDIR, "%s_%d.ttf" % (key, i))
        try:
            print("FONT OK  %-7s %8d  %s" % (key, fetch(u, dest), u.split("/")[-1]), flush=True)
            FPATH[key] = dest
            break
        except Exception as e:
            print("FONT FAIL %-7s %s" % (key, repr(e)[:90]), flush=True)

HAS_RAQM = bool(features.check("raqm"))
HAS_HINDI = HAS_RAQM and "hindi" in FPATH
print("RAQM:", HAS_RAQM, "| Devanagari usable:", HAS_HINDI, flush=True)

def _set_weight(f, weight):
    if not weight:
        return
    try:
        axes = f.get_variation_axes()
    except Exception:
        return
    vals = []
    for ax in axes:
        name = ax.get("name", "") if isinstance(ax, dict) else getattr(ax, "name", "")
        dflt = ax.get("default", 0) if isinstance(ax, dict) else getattr(ax, "default", 0)
        vals.append(weight if "eight" in str(name) else dflt)
    try:
        f.set_variation_by_axes(vals)
    except Exception as e:
        print("   weight FAIL %s" % repr(e)[:80], flush=True)

_fc = {}
def F(kind, size, weight=None):
    key = (kind, size, weight)
    if key in _fc:
        return _fc[key]
    path = FPATH.get(kind) or FPATH.get("serif") or FPATH.get("body")
    f = ImageFont.truetype(path, size)
    _set_weight(f, weight)
    _fc[key] = f
    return f

# ----------------------------------------------------------------- colour emoji
EMOJI_PATH, EMOJI_SIZE = None, 109
for i, u in enumerate(EMOJI_URLS):
    dest = os.path.join(FDIR, "emoji_%d.ttf" % i)
    try:
        fetch(u, dest)
    except Exception as e:
        print("EMOJI download failed: %s" % repr(e)[:80], flush=True)
        continue
    for size in (109, 137, 128, 96, 160, 72, 48):
        ok = False
        try:
            f = ImageFont.truetype(dest, size)
            probe = Image.new("RGBA", (size * 2, size * 2), (0, 0, 0, 0))
            ImageDraw.Draw(probe).text((size, size), "\U0001F339", font=f,
                                       embedded_color=True, anchor="mm")
            bb = probe.getbbox()
            cov = float((np.array(probe.crop(bb))[..., 3] > 30).mean()) if bb else 0.0
            if bb and cov > 0.25:
                EMOJI_PATH, EMOJI_SIZE, ok = dest, size, True
                print("EMOJI OK %s size=%d coverage=%.2f" % (u.split("/")[-1], size, cov), flush=True)
        except Exception as e:
            print("EMOJI size %d failed: %s" % (size, repr(e)[:70]), flush=True)
        if ok:
            break
    if EMOJI_PATH:
        break

def emoji_layer(chars, height, spacing=16):
    if EMOJI_PATH is None:
        return None
    try:
        f = ImageFont.truetype(EMOJI_PATH, EMOJI_SIZE)
    except Exception:
        return None
    imgs = []
    for ch in chars:
        canvas = Image.new("RGBA", (EMOJI_SIZE * 2, EMOJI_SIZE * 2), (0, 0, 0, 0))
        try:
            ImageDraw.Draw(canvas).text((EMOJI_SIZE, EMOJI_SIZE), ch, font=f,
                                        embedded_color=True, anchor="mm")
        except Exception:
            return None
        bb = canvas.getbbox()
        if not bb:
            return None
        imgs.append(canvas.crop(bb))
    out = []
    for g in imgs:
        s = height / float(g.size[1])
        out.append(g.resize((max(1, int(g.size[0] * s)), height), Image.LANCZOS))
    tw = sum(g.size[0] for g in out) + spacing * (len(out) - 1)
    lay = Image.new("RGBA", (tw, height), (0, 0, 0, 0))
    x = 0
    for g in out:
        lay.alpha_composite(g, (x, 0)); x += g.size[0] + spacing
    return lay

# ----------------------------------------------------------------- text helper
def text_layer(lines, kind, size, color, tracking=0, line_h=None, weight=None):
    f = F(kind, size, weight)
    tmp = Image.new("RGBA", (8, 8)); td = ImageDraw.Draw(tmp)
    lh = line_h or int(size * 1.32)
    widths = []
    for ln in lines:
        if tracking:
            widths.append(sum(td.textlength(c, font=f) for c in ln) + tracking * max(0, len(ln) - 1))
        else:
            widths.append(td.textlength(ln, font=f))
    pad = int(size * 0.9) + 14
    lw = int(max(widths)) + 2 * pad
    lht = int(lh * len(lines)) + 2 * pad
    lay = Image.new("RGBA", (max(8, lw), max(8, lht)), (0, 0, 0, 0))
    d = ImageDraw.Draw(lay)
    for i, ln in enumerate(lines):
        if tracking:
            x = (lw - widths[i]) / 2.0
            for ch in ln:
                d.text((x, pad + lh * i + lh * 0.80), ch, font=f, fill=color + (255,), anchor="ls")
                x += td.textlength(ch, font=f) + tracking
        else:
            d.text((lw / 2.0, pad + lh * i + lh / 2.0), ln, font=f, fill=color + (255,), anchor="mm")
    bb = lay.getbbox()
    return lay.crop(bb) if bb else lay

def fit_layer(lines, kind, size, color, max_w, tracking=0, line_h=None, weight=None):
    s, lay = size, None
    while s > 18:
        lay = text_layer(lines, kind, s, color, tracking=tracking, line_h=line_h, weight=weight)
        if lay.size[0] <= max_w:
            return lay
        s = int(s * 0.94)
    return lay

def alpha_scale(sprite, a):
    if a >= 0.999:
        return sprite
    arr = np.array(sprite, dtype=np.uint16)
    arr[..., 3] = (arr[..., 3] * a).astype(np.uint16)
    return Image.fromarray(arr.astype(np.uint8), "RGBA")

def alpha_variants(sprite, n=12):
    base = np.array(sprite, dtype=np.uint16)
    out = []
    for i in range(n):
        arr = base.copy()
        arr[..., 3] = (arr[..., 3] * (i / float(n - 1))).astype(np.uint16)
        out.append(Image.fromarray(arr.astype(np.uint8), "RGBA"))
    return out

def paste(dst, lay, cx, cy, alpha, dy=0.0):
    if lay is None or alpha <= 0.004:
        return
    im = alpha_scale(lay, alpha) if alpha < 0.999 else lay
    x = int(cx - lay.size[0] / 2.0); y = int(cy - lay.size[1] / 2.0 + dy)
    if x >= W or y >= H or x + im.size[0] <= 0 or y + im.size[1] <= 0:
        return
    dst.alpha_composite(im, (x, y))

def rule_strip(w, alpha, thickness=2):
    w = max(2, int(w))
    a = (np.sin(np.pi * np.linspace(0.0, 1.0, w)) ** 1.4 * 255 * alpha).astype(np.uint8)
    st = np.zeros((thickness, w, 4), dtype=np.uint8)
    st[..., 0], st[..., 1], st[..., 2] = GOLD[0], GOLD[1], GOLD[2]
    st[..., 3] = a
    return Image.fromarray(st, "RGBA")

# ----------------------------------------------------------------- furniture
def build_bg():
    y = np.linspace(0, 1, H)[:, None]
    bg = np.array(BG_TOP)[None, None, :] * (1 - y[..., None]) + np.array(BG_BOT)[None, None, :] * y[..., None]
    bg = np.repeat(bg, W, axis=1).astype(np.float32)
    yy, xx = np.mgrid[0:H, 0:W].astype(np.float32)
    d = np.sqrt(((xx - W * 0.5) / (W * 0.80)) ** 2 + ((yy - H * 0.40) / (H * 0.52)) ** 2)
    bg += (np.clip(1 - d, 0, 1) ** 2.3)[..., None] * np.array([118, 58, 18], dtype=np.float32)[None, None, :]
    v = np.sqrt(((xx - W * 0.5) / (W * 0.56)) ** 2 + ((yy - H * 0.5) / (H * 0.60)) ** 2)
    bg *= (1.0 - 0.34 * np.clip(v, 0, 1) ** 2.4)[..., None]
    return Image.fromarray(np.clip(bg, 0, 255).astype(np.uint8), "RGB")

def build_frame():
    S = 2
    im = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); d = ImageDraw.Draw(im)
    for m, col, a, wd in ((38, GOLD, 215, 2.2), (54, GOLD_L, 105, 1.0)):
        d.rectangle([m * S, m * S, (W - m) * S, (H - m) * S], outline=col + (a,), width=int(wd * S))
    for cx, cy, sx, sy in ((72, 72, 1, 1), (W - 72, 72, -1, 1), (72, H - 72, 1, -1), (W - 72, H - 72, -1, -1)):
        L = 44
        d.line([cx * S, cy * S, (cx + L * sx) * S, cy * S], fill=GOLD_L + (170,), width=int(1.5 * S))
        d.line([cx * S, cy * S, cx * S, (cy + L * sy) * S], fill=GOLD_L + (170,), width=int(1.5 * S))
        for k in (1, 2, 3):
            px, py = cx + 11 * k * sx, cy + 11 * k * sy
            d.ellipse([(px - 3) * S, (py - 3) * S, (px + 3) * S, (py + 3) * S], fill=MARIGOLD + (150,))
    return im.resize((W, H), Image.LANCZOS)

def build_toran(height=210):
    im = Image.new("RGBA", (W, height), (0, 0, 0, 0)); d = ImageDraw.Draw(im)
    d.rectangle([0, 0, W, 14], fill=(28, 5, 14, 255))
    for i in range(0, W, 22):
        d.ellipse([i + 3, 10, i + 19, 26], fill=GOLD_D + (230,))
    for k in range(4):
        x0, x1 = W * k / 4.0, W * (k + 1) / 4.0
        for i in range(48):
            t = i / 47.0
            x = x0 + (x1 - x0) * t
            yy = 52 + math.sin(math.pi * t) * 74
            r = 12.5
            d.ellipse([x - r, yy - r, x + r, yy + r], fill=(MARIGOLD if i % 2 == 0 else ORANGE) + (238,))
            d.ellipse([x - r * 0.34, yy - r * 0.55, x + r * 0.18, yy - r * 0.12], fill=(255, 236, 196, 130))
        if k < 3:
            jx = x1
            d.polygon([(jx, 108), (jx - 13, 92), (jx, 74), (jx + 13, 92)], fill=(58, 122, 74, 210))
    for x in (W * 0.25, W * 0.5, W * 0.75):
        d.line([x, 118, x, 176], fill=GOLD_L + (170,), width=2)
        d.ellipse([x - 11, 172, x + 11, 194], fill=ORANGE + (238,))
        d.ellipse([x - 4, 177, x + 2, 183], fill=(255, 236, 196, 150))
    return im

def build_mandala(size=1040):
    S = 2; s = size * S
    im = Image.new("RGBA", (s, s), (0, 0, 0, 0)); d = ImageDraw.Draw(im)
    c = s / 2.0
    for rf, wd, a in ((0.480, 2.4, 90), (0.452, 1.1, 55), (0.300, 1.1, 45), (0.196, 2.0, 70), (0.120, 1.1, 45)):
        r = s * rf / 2.0
        d.ellipse([c - r, c - r, c + r, c + r], outline=GOLD_L + (a,), width=int(wd * S))
    for i in range(24):
        ang = 360.0 * i / 24
        p = Image.new("RGBA", (int(s * 0.115), int(s * 0.038)), (0, 0, 0, 0))
        ImageDraw.Draw(p).ellipse([0, 0, p.size[0] - 1, p.size[1] - 1], outline=GOLD_L + (85,), width=int(1.5 * S))
        p = p.rotate(-ang, expand=True, resample=Image.BICUBIC)
        r = s * 0.368 / 2.0
        im.alpha_composite(p, (int(c + r * math.cos(math.radians(ang)) - p.size[0] / 2),
                               int(c + r * math.sin(math.radians(ang)) - p.size[1] / 2)))
    for i in range(48):
        ang = 360.0 * i / 48
        r = s * 0.248 / 2.0
        x, y = c + r * math.cos(math.radians(ang)), c + r * math.sin(math.radians(ang))
        d.ellipse([x - 3.2 * S, y - 3.2 * S, x + 3.2 * S, y + 3.2 * S], fill=MARIGOLD + (105,))
    return im.resize((size, size), Image.LANCZOS)

def build_diya(size=200):
    S = 2; s = size * S
    im = Image.new("RGBA", (s, s), (0, 0, 0, 0)); d = ImageDraw.Draw(im)
    d.chord([s * 0.10, s * 0.50, s * 0.90, s * 0.98], start=0, end=180, fill=GOLD_D + (255,))
    d.chord([s * 0.10, s * 0.50, s * 0.90, s * 0.98], start=0, end=180, outline=GOLD_L + (255,), width=int(3 * S))
    d.arc([s * 0.10, s * 0.50, s * 0.90, s * 0.98], start=180, end=360, fill=GOLD_L + (220,), width=int(3 * S))
    fx, fy = s * 0.5, s * 0.50
    d.polygon([(fx, fy - s * 0.30), (fx - s * 0.070, fy), (fx + s * 0.070, fy)], fill=(255, 206, 108, 255))
    d.ellipse([fx - s * 0.070, fy - s * 0.085, fx + s * 0.070, fy + s * 0.085], fill=(255, 206, 108, 255))
    d.polygon([(fx, fy - s * 0.175), (fx - s * 0.033, fy - s * 0.005), (fx + s * 0.033, fy - s * 0.005)], fill=(255, 250, 226, 255))
    return im.resize((size, size), Image.LANCZOS)

def build_glow(size=430, radius=175.0):
    yy, xx = np.mgrid[0:size, 0:size]
    c = (size - 1) / 2.0
    g = np.clip(1 - np.sqrt((xx - c) ** 2 + (yy - c) ** 2) / radius, 0, 1) ** 2.4
    arr = np.zeros((size, size, 4), dtype=np.uint8)
    arr[..., 0], arr[..., 1], arr[..., 2] = 255, 176, 70
    arr[..., 3] = (g * 195).astype(np.uint8)
    return Image.fromarray(arr, "RGBA")

def build_mote(size=26):
    yy, xx = np.mgrid[0:size, 0:size]
    c = (size - 1) / 2.0
    g = np.clip(1 - np.sqrt((xx - c) ** 2 + (yy - c) ** 2) / c, 0, 1) ** 2.0
    arr = np.zeros((size, size, 4), dtype=np.uint8)
    arr[..., 0], arr[..., 1], arr[..., 2] = 244, 214, 150
    arr[..., 3] = (g * 210).astype(np.uint8)
    return Image.fromarray(arr, "RGBA")

def build_lotus(size=124):
    im = Image.new("RGBA", (size, size), (0, 0, 0, 0))
    for i in range(6):
        p = Image.new("RGBA", (int(size * 0.86), int(size * 0.26)), (0, 0, 0, 0))
        ImageDraw.Draw(p).ellipse([0, 0, p.size[0] - 1, p.size[1] - 1], outline=GOLD_L + (215,), width=3)
        p = p.rotate(-(i * 30), expand=True, resample=Image.BICUBIC)
        im.alpha_composite(p, (size // 2 - p.size[0] // 2, size // 2 - p.size[1] // 2))
    ImageDraw.Draw(im).ellipse([size / 2 - 8, size / 2 - 8, size / 2 + 8, size / 2 + 8], fill=MARIGOLD + (235,))
    return im

def build_monogram(D=600):
    im = Image.new("RGBA", (D, D), (0, 0, 0, 0)); d = ImageDraw.Draw(im)
    c = D / 2.0
    d.ellipse([5, 5, D - 5, D - 5], outline=GOLD + (215,), width=3)
    d.ellipse([21, 21, D - 21, D - 21], outline=GOLD_L + (120,), width=2)
    d.ellipse([34, 34, D - 34, D - 34], outline=GOLD_L + (70,), width=1)
    for i in range(14):
        ang = 360.0 * i / 14
        p = Image.new("RGBA", (int(D * 0.19), int(D * 0.075)), (0, 0, 0, 0))
        ImageDraw.Draw(p).ellipse([0, 0, p.size[0] - 1, p.size[1] - 1], outline=GOLD_L + (120,), width=2)
        p = p.rotate(-ang, expand=True, resample=Image.BICUBIC)
        r = D * 0.415
        im.alpha_composite(p, (int(c + r * math.cos(math.radians(ang)) - p.size[0] / 2),
                               int(c + r * math.sin(math.radians(ang)) - p.size[1] / 2)))
    lay = text_layer([EV["name"][0].upper()], "script", int(D * 0.60), CREAM)
    im.alpha_composite(lay, (int(c - lay.size[0] / 2), int(c - lay.size[1] / 2)))
    return im

def card_base(width, height, radius=16, fill=(60, 11, 28, 215)):
    card = Image.new("RGBA", (width, height), (0, 0, 0, 0))
    S = 2
    tmp = Image.new("RGBA", (width * S, height * S), (0, 0, 0, 0))
    ImageDraw.Draw(tmp).rounded_rectangle([0, 0, width * S - 1, height * S - 1], radius=int(radius * S),
                                          fill=fill, outline=GOLD + (235,), width=int(2.2 * S))
    card.alpha_composite(tmp.resize((width, height), Image.LANCZOS), (0, 0))
    return card

def make_card(width, title, sections, title_size=66, label_size=28, value_size=48):
    Hc = 1700
    card = card_base(width, Hc)
    y = 74
    if title:
        tl = fit_layer([title], "script", title_size, GOLD, width - 110)
        card.alpha_composite(tl, (int(width / 2 - tl.size[0] / 2), int(y)))
        y += tl.size[1] + 30
        rw = int(width * 0.44)
        card.alpha_composite(rule_strip(rw, 0.9, 2), (int(width / 2 - rw / 2), int(y)))
        y += 46
    for si, sec in enumerate(sections):
        if si:
            rw = int(width * 0.34)
            card.alpha_composite(rule_strip(rw, 0.55, 1), (int(width / 2 - rw / 2), int(y)))
            y += 42
        ll = text_layer([sec["label"]], "serif", label_size, GOLD_L, tracking=12, weight=500)
        card.alpha_composite(ll, (int(width / 2 - ll.size[0] / 2), int(y)))
        y += ll.size[1] + 24
        for v in sec["values"]:
            vl = fit_layer([v], "serif", value_size, CREAM, width - 96, weight=500)
            card.alpha_composite(vl, (int(width / 2 - vl.size[0] / 2), int(y)))
            y += vl.size[1] + 12
        y += 20
    used = y + 40
    card.alpha_composite(build_lotus(64), (int(width / 2 - 32), int(used - 20)))
    return card.crop((0, 0, width, min(Hc, used + 54)))

def make_message_card(width=900, sig=None, sig_size=64):
    Hc = 1700
    card = card_base(width, Hc)
    y = 90
    paras = EV["message"]
    for pi, p in enumerate(paras):
        lay = fit_layer(p["lines"], p["kind"], p["size"], p["color"], width - 100,
                        line_h=int(p["size"] * 1.34), weight=p.get("weight"))
        card.alpha_composite(lay, (int(width / 2 - lay.size[0] / 2), int(y)))
        y += lay.size[1] + (48 if pi < len(paras) - 1 else 32)
    if sig:
        sl = fit_layer([sig], "script", sig_size, GOLD_L, width - 160)
        card.alpha_composite(sl, (int(width / 2 - sl.size[0] / 2), int(y)))
        y += sl.size[1]
    return card.crop((0, 0, width, min(Hc, y + 76)))

# ----------------------------------------------------------------- soundtrack
def ks_pluck(freq, dur, damp=0.9965, bright=0.42, seed=0):
    """Karplus-Strong plucked string (sitar/tanpura-like)."""
    rng = np.random.default_rng(seed)
    N = max(2, int(round(SR / float(freq))))
    buf = rng.uniform(-1.0, 1.0, N).astype(np.float32)
    for _ in range(2):
        buf = 0.5 * (buf + np.roll(buf, 1))
    buf /= (np.abs(buf).max() + 1e-9)
    n = int(dur * SR)
    out = np.empty(n, dtype=np.float32)
    a, b = 0.5 * (1.0 + bright), 0.5 * (1.0 - bright)
    idx = 0
    for i in range(n):
        cur = buf[idx]
        out[i] = cur
        buf[idx] = damp * (a * cur + b * buf[(idx + 1) % N])
        idx = (idx + 1) % N
    return out

def make_bell(dur, base=587.33, decay=1.9):
    t = np.arange(int(dur * SR), dtype=np.float32) / SR
    out = np.zeros_like(t)
    for mult, amp in ((1.0, 1.0), (2.0, 0.34), (2.76, 0.42), (4.07, 0.16), (5.43, 0.09)):
        out += amp * np.sin(2 * np.pi * base * mult * t) * np.exp(-t * (1.6 / decay) * (mult ** 0.4))
    return out / (np.abs(out).max() + 1e-9)

def make_pad(dur, chord=(146.83, 220.0, 293.66), amp=1.0):
    t = np.arange(int(dur * SR), dtype=np.float32) / SR
    out = np.zeros_like(t)
    for i, f in enumerate(chord):
        vib = 1.0 + 0.0016 * np.sin(2 * np.pi * (0.16 + 0.05 * i) * t)
        out += np.sin(2 * np.pi * f * vib * t) / (i + 2.0)
    swell = np.minimum(1.0, t / 4.0)
    return amp * swell * out / (np.abs(out).max() + 1e-9)

def reverb(x, seed, mix=0.34, decay=1.7, sr=SR):
    rng = np.random.default_rng(seed)
    n = int(decay * sr)
    ir = (rng.standard_normal(n) * np.exp(-np.arange(n) / (0.30 * sr))).astype(np.float32)
    ir[0] = 1.0
    ir /= np.abs(ir).sum() ** 0.5
    L = 1
    while L < len(x) + n:
        L *= 2
    y = np.fft.irfft(np.fft.rfft(x, L) * np.fft.rfft(ir, L), L)[:len(x)].astype(np.float32)
    pk = np.abs(x).max() + 1e-9
    y = y / (np.abs(y).max() + 1e-9) * pk
    return (1.0 - mix) * x + mix * y

def build_soundtrack(total):
    S = int((total + 1.2) * SR)
    bus = {k: np.zeros(S, dtype=np.float32) for k in ("drone", "mel", "bell", "pad")}

    def add(which, t0, sig, amp):
        i = int(t0 * SR)
        if i >= S:
            return
        j = min(S, i + len(sig))
        bus[which][i:j] += sig[:j - i] * amp

    SA = 146.83  # D3
    def nf(semi):
        return SA * (2.0 ** (semi / 12.0))

    # tanpura drone: Pa - sa - sa - sa cycle
    cycle = [(7, 0.90), (0, 0.85), (12, 0.72), (12, 0.66)]
    t0, k = 0.0, 0
    while t0 < total:
        semi, amp = cycle[k % len(cycle)]
        add("drone", t0, ks_pluck(nf(semi), 3.4, damp=0.9975, bright=0.30, seed=k * 7 + 1), 0.15 * amp)
        t0 += 2.15
        k += 1

    # sitar-like melody in Raag Bhoopali (Sa Re Ga Pa Dha)
    melody = [(0.80, 0, 3.0, 0.20), (2.30, 4, 2.6, 0.17), (3.70, 7, 2.8, 0.17),
              (5.30, 9, 2.6, 0.17), (6.90, 12, 3.2, 0.18),
              (9.20, 14, 3.0, 0.15), (11.20, 12, 2.8, 0.14), (13.40, 9, 3.0, 0.14),
              (15.20, 7, 3.0, 0.15),
              (17.40, 12, 2.6, 0.17), (19.00, 9, 2.6, 0.16), (20.60, 12, 2.8, 0.16),
              (22.40, 16, 3.2, 0.17), (24.40, 19, 3.2, 0.18), (26.60, 21, 3.4, 0.18),
              (28.60, 24, 3.6, 0.19), (30.80, 19, 3.6, 0.16), (32.20, 12, 4.6, 0.16)]
    for i, (t0, semi, dur, amp) in enumerate(melody):
        if t0 > total:
            continue
        add("mel", t0, ks_pluck(nf(semi), dur, damp=0.9982, bright=0.46, seed=100 + i * 13), amp)

    # temple bells on scene changes
    for i, st in enumerate([0.0, 3.95, 8.4, 16.35, 22.8, 26.75]):
        big = i in (0, 5)
        add("bell", st, make_bell(5.0, base=587.33 if big else 493.88, decay=2.2 if big else 1.7),
            0.16 if big else 0.095)

    # warm sustained pad
    add("pad", 0.4, make_pad(total + 1.0, amp=1.0), 0.085)

    # gentle lowpass to keep it soft
    kernel = np.hanning(9)
    kernel /= kernel.sum()
    def lp(x):
        return np.convolve(x, kernel, mode="same").astype(np.float32)
    for k in bus:
        bus[k] = lp(bus[k])

    L = reverb(bus["drone"] * 0.95 + bus["mel"] + bus["bell"] + bus["pad"], seed=5)
    R = reverb(bus["drone"] * 1.00 + bus["mel"] * 0.94 + bus["bell"] * 0.98 + bus["pad"], seed=9)
    st = np.stack([L, R], axis=1)

    n = st.shape[0]
    fade_in = int(1.2 * SR)
    fade_out = int(3.0 * SR)
    env = np.ones(n, dtype=np.float32)
    env[:fade_in] = np.linspace(0.0, 1.0, fade_in) ** 0.7
    env[n - fade_out:] = np.linspace(1.0, 0.0, fade_out) ** 1.1
    st *= env[:, None]

    peak = np.abs(st).max() + 1e-9
    st = np.tanh(st / peak * 1.15) * 0.72
    st = st[:int(total * SR)]
    data = np.clip(st, -1.0, 1.0)
    with wave.open(WAV, "wb") as w:
        w.setnchannels(2); w.setsampwidth(2); w.setframerate(SR)
        w.writeframes((data * 32767.0).astype("<i2").tobytes())
    print("soundtrack: %s  %.2fs  peak=%.2f" % (WAV, st.shape[0] / float(SR), np.abs(st).max()), flush=True)

# ----------------------------------------------------------------- build assets
print("building assets ...", flush=True)
BG = build_bg().convert("RGBA")
FRAME = build_frame()
TORAN = build_toran()
MANDALA = alpha_scale(build_mandala(1040), 0.19)
DIYA = build_diya(200)
LOTUS = build_lotus(120)
LOTUS_S = build_lotus(64)
GLOWS = alpha_variants(build_glow(430, 175.0), 12)
MOTE_V = alpha_variants(build_mote(26), 12)
MOTE_S = alpha_variants(build_mote(15), 12)

random.seed(11)
MOTES = [dict(x=random.uniform(70, W - 70), y=random.uniform(0, H), sp=random.uniform(58, 132),
              sw=random.uniform(0.25, 0.7), ph=random.uniform(0, 6.28), big=random.random() < 0.45)
         for _ in range(16)]

MAXW = 880
kicker1 = text_layer([EV["hindi"]], "hindi", 48, GOLD_L, weight=500) if HAS_HINDI else \
          text_layer([EV["kicker1_en"]], "serif", 34, GOLD_L, tracking=13, weight=500)
k1_extra = text_layer([EV["kicker1_en"]], "serif", 26, GOLD_L, tracking=11, weight=500) if HAS_HINDI else None

L_script1 = fit_layer([EV["script1"]], "script", 158, GOLD, MAXW)
L_sub1 = fit_layer([EV["sub1"]], "serif", 42, SOFT, MAXW, weight=500)
L_kick2 = text_layer([EV["kicker2"]], "serif", 32, GOLD_L, tracking=15, weight=500)
L_name = fit_layer([EV["name"]], "script", 250, CREAM, MAXW)
L_name_glow = alpha_scale(fit_layer([EV["name"]], "script", 250, GOLD, MAXW).filter(ImageFilter.GaussianBlur(16)), 0.55)
L_body2 = fit_layer([EV["body2"]], "serif", 44, SOFT, MAXW, weight=500)
L_small2 = text_layer([EV["small2"]], "serif", 30, GOLD_L, tracking=10, weight=500)

EMOJI_ROSE = emoji_layer(["\U0001F339"], 62)
EMOJI_ROW = emoji_layer(["\U0001F339", "\U0001F64F", "\U0001F389", "\U0001F38A"], 62)
if EMOJI_ROW is None:
    print("emoji unavailable - falling back to drawn ornaments", flush=True)
    EMOJI_ROW = build_lotus(62)

CARD_MSG = make_message_card(sig=EV["msg_sig"])
L_foot3 = text_layer([EV["msg_foot"]], "serif", 28, GOLD_L, tracking=12, weight=500)
CARD_D = make_card(848, EV["card_title"], [
    dict(label=EV["when_label"], values=[EV["when_1"]]),
    dict(label=EV["time_label"], values=[EV["time_1"]]),
    dict(label=EV["where_label"], values=[EV["where_1"]]),
])
L_sub3 = fit_layer([EV["sub3"]], "serif", 42, SOFT, MAXW, weight=500)
L_kick3 = text_layer(["THE CELEBRATION"], "serif", 32, GOLD_L, tracking=15, weight=500)
MONO = build_monogram(600)
L_quote = fit_layer(EV["quote"], "bodyi", 54, SOFT, MAXW - 60, line_h=82, weight=600)
L_kick6 = text_layer([EV["kicker6"]], "serif", 30, GOLD_L, tracking=13, weight=500)
L_script6 = fit_layer([EV["script6"]], "script", 136, GOLD, MAXW)
L_sig = fit_layer([EV["sig"]], "script", 84, CREAM, MAXW)
print("card sizes: message=%s details=%s emoji=%s" % (CARD_MSG.size, CARD_D.size, EMOJI_PATH is not None), flush=True)

# ----------------------------------------------------------------- timeline
DUR = [4.5, 5.0, 8.5, 7.0, 4.5, 5.5]
OV, HOLD, FADES = 0.55, 2.0, 0.75
start, acc = [], 0.0
for d in DUR:
    start.append(acc); acc += d - OV
LAST_END = start[-1] + DUR[-1]
TOTAL = LAST_END + HOLD
NF = int(round(TOTAL * FPS))
print("timeline start:", [round(s, 2) for s in start], "total %.2fs %d frames" % (TOTAL, NF), flush=True)

build_soundtrack(TOTAL)

def scene_alpha(i, t):
    s = start[i]
    e = TOTAL if i == len(DUR) - 1 else start[i] + DUR[i]
    if t < s or t > e:
        return 0.0
    if i + 1 < len(DUR) and t >= start[i + 1]:
        return max(0.0, 1.0 - (t - start[i + 1]) / OV)
    return 1.0

def ease(t, delay, dur=0.95):
    x = (t - delay) / dur
    if x <= 0:
        return 0.0
    if x >= 1:
        return 1.0
    return 1.0 - (1.0 - x) ** 3

ITEMS = [
    [(kicker1, 0.278, 0.10, 40, 0.9), (k1_extra, 0.325, 0.28, 34, 0.9),
     (L_script1, 0.408, 0.48, 62, 1.05), (LOTUS, 0.497, 0.88, 18, 0.8),
     (L_sub1, 0.556, 1.05, 40, 0.9)],
    [(L_kick2, 0.297, 0.10, 38, 0.9), (L_name_glow, 0.415, 0.42, 58, 1.1), (L_name, 0.415, 0.42, 58, 1.1),
     (LOTUS, 0.525, 0.88, 18, 0.8), (L_body2, 0.588, 1.00, 40, 0.9), (L_small2, 0.650, 1.20, 30, 0.9)],
    [(EMOJI_ROSE, 0.170, 0.15, 30, 0.8), (CARD_MSG, 0.455, 0.45, 54, 1.05),
     (L_foot3, 0.712, 1.10, 34, 0.9)],
    [(L_kick3, 0.246, 0.10, 38, 0.9), (CARD_D, 0.505, 0.40, 56, 1.05), (L_sub3, 0.760, 1.05, 40, 0.9)],
    [(MONO, 0.395, 0.20, 50, 1.05), (LOTUS_S, 0.545, 0.90, 18, 0.8), (L_quote, 0.645, 1.05, 44, 1.0)],
    [(L_kick6, 0.330, 0.15, 36, 0.9), (EMOJI_ROW, 0.392, 0.45, 34, 0.85),
     (L_script6, 0.468, 0.65, 58, 1.05), (LOTUS, 0.545, 0.95, 18, 0.8), (L_sig, 0.612, 1.10, 44, 0.95)],
]

def render(t):
    img = BG.copy()
    mand = MANDALA.rotate((t * 7.5) % 360.0, resample=Image.BICUBIC)
    img.alpha_composite(mand, (int(W / 2 - mand.size[0] / 2), int(H * 0.455 - mand.size[1] / 2)))
    img.alpha_composite(TORAN, (0, 0))
    img.alpha_composite(FRAME, (0, 0))
    for ph_i, cx in enumerate((148, W - 148)):
        fl = 0.68 + 0.24 * math.sin(t * 7.2 + ph_i * 1.9) + 0.10 * math.sin(t * 16.7 + ph_i * 2.4)
        g = GLOWS[int(max(0.30, min(1.0, fl)) * 11)]
        cy = H - 214
        img.alpha_composite(g, (int(cx - g.size[0] / 2), int(cy - g.size[1] / 2)))
        img.alpha_composite(DIYA, (int(cx - DIYA.size[0] / 2), int(cy - DIYA.size[1] / 2)))
    for m in MOTES:
        yy = (m["y"] - m["sp"] * t) % (H + 240) - 120
        xx = m["x"] + 26 * math.sin(t * m["sw"] + m["ph"])
        al = 0.22 + 0.62 * max(0.0, math.sin(t * 0.85 + m["ph"]))
        sp = (MOTE_V if m["big"] else MOTE_S)[max(0, min(11, int(al * 11)))]
        px, py = int(xx - sp.size[0] / 2), int(yy - sp.size[1] / 2)
        if 0 <= px < W and 0 <= py < H:
            img.alpha_composite(sp, (px, py))
    for i in range(len(DUR)):
        sa = scene_alpha(i, t)
        if sa <= 0.004:
            continue
        tl = t - start[i]
        for (lay, yf, delay, dy, dur) in ITEMS[i]:
            if lay is None:
                continue
            e = ease(tl, delay, dur)
            paste(img, lay, W / 2.0, H * yf, e * sa, dy=(1.0 - e) * dy)
    rgb = img.convert("RGB")
    k = 1.0
    if t < FADES:
        k = t / FADES
    elif t > TOTAL - FADES:
        k = max(0.0, (TOTAL - t) / FADES)
    if k < 1.0:
        return Image.fromarray((np.asarray(rgb, dtype=np.float32) * k).astype(np.uint8), "RGB")
    return rgb

# ----------------------------------------------------------------- encode (video + soundtrack)
from imageio_ffmpeg import get_ffmpeg_exe
FFMPEG = get_ffmpeg_exe()
print("ffmpeg:", FFMPEG, flush=True)
proc = subprocess.Popen([FFMPEG, "-y", "-loglevel", "error",
                         "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", "%dx%d" % (W, H),
                         "-r", str(FPS), "-i", "-",
                         "-i", WAV,
                         "-map", "0:v:0", "-map", "1:a:0",
                         "-c:v", "libx264", "-preset", "slow", "-crf", "18", "-pix_fmt", "yuv420p",
                         "-c:a", "aac", "-b:a", "192k", "-ar", str(SR),
                         "-shortest", "-movflags", "+faststart", OUT], stdin=subprocess.PIPE)

poster_t = start[1] + 2.6
for n in range(NF):
    t = n / float(FPS)
    fr = render(t)
    if abs(t - poster_t) < 0.5 / FPS:
        fr.save(POSTER, quality=92)
    proc.stdin.write(np.asarray(fr, dtype=np.uint8).tobytes())
    if n % 100 == 0:
        print("frame %4d / %d  (t=%.1fs)" % (n, NF, t), flush=True)
proc.stdin.close()
proc.wait()
print("encoded:", OUT, os.path.getsize(OUT), "bytes", flush=True)

PREVIEW_DIR = "/tmp/previews"
os.makedirs(PREVIEW_DIR, exist_ok=True)
checks = [("s1", start[0] + 3.4), ("s2", start[1] + 3.2), ("s3", start[2] + 5.8),
          ("s4", start[3] + 5.2), ("s5", start[4] + 3.0), ("s6", start[5] + 3.9)]
previews = []
for name, tt in checks:
    fp = os.path.join(PREVIEW_DIR, "preview_%s.jpg" % name)
    render(tt).save(fp, quality=92)
    previews.append(fp)
    print("preview", name, "t=%.2f" % tt, flush=True)

# ----------------------------------------------------------------- upload
from huggingface_hub import HfApi
REPO = os.environ.get("REPO_ID", "coderdecoder01/retirement-invitation-mamta")
api = HfApi(token=os.environ["HF_TOKEN"])
api.create_repo(repo_id=REPO, repo_type="dataset", private=False, exist_ok=True)
try:
    api.update_repo_settings(repo_id=REPO, repo_type="dataset", private=False)
except Exception as e:
    print("visibility:", repr(e)[:120], flush=True)
api.upload_file(path_or_fileobj=OUT, path_in_repo="mamta-retirement-invitation.mp4", repo_id=REPO, repo_type="dataset")
api.upload_file(path_or_fileobj=WAV, path_in_repo="soundtrack.wav", repo_id=REPO, repo_type="dataset")
api.upload_file(path_or_fileobj=POSTER, path_in_repo="poster.jpg", repo_id=REPO, repo_type="dataset")
for fp in previews:
    api.upload_file(path_or_fileobj=fp, path_in_repo="previews/" + os.path.basename(fp), repo_id=REPO, repo_type="dataset")
print("VIDEO  https://huggingface.co/datasets/%s/resolve/main/mamta-retirement-invitation.mp4" % REPO)
print("POSTER https://huggingface.co/datasets/%s/resolve/main/poster.jpg" % REPO)