coderdecoder01 commited on
Commit
f04cbc6
·
verified ·
1 Parent(s): 6d0b2e0

Fix Devanagari font URL, add auto-fit text safeguard, add vignette

Browse files
Files changed (1) hide show
  1. render_invitation.py +119 -147
render_invitation.py CHANGED
@@ -21,7 +21,7 @@ SOFT = (244, 229, 203)
21
  # ----------------------------------------------------------------- event text
22
  EV = dict(
23
  name="Mamta",
24
- hindi="\u0936\u0941\u092d \u0938\u0947\u0935\u093e\u0928\u093f\u0935\u0943\u0924\u094d\u0924\u093f", # शुभ सेवानिवृत्ति
25
  kicker1_en="WITH GREAT JOY",
26
  script1="You\u2019re Invited",
27
  sub1="a celebration of a beautiful journey",
@@ -46,16 +46,13 @@ EV = dict(
46
  )
47
 
48
  # ----------------------------------------------------------------- fonts
 
49
  FONT_URLS = {
50
- "script": ["https://raw.githubusercontent.com/google/fonts/main/ofl/greatvibes/GreatVibes-Regular.ttf"],
51
- "serif": ["https://raw.githubusercontent.com/google/fonts/main/ofl/playfairdisplay/PlayfairDisplay%5Bwght%5D.ttf",
52
- "https://raw.githubusercontent.com/google/fonts/main/ofl/playfairdisplay/static/PlayfairDisplay-Regular.ttf"],
53
- "body": ["https://raw.githubusercontent.com/google/fonts/main/ofl/cormorantgaramond/CormorantGaramond%5Bwght%5D.ttf",
54
- "https://raw.githubusercontent.com/google/fonts/main/ofl/cormorantgaramond/static/CormorantGaramond-Regular.ttf"],
55
- "bodyi": ["https://raw.githubusercontent.com/google/fonts/main/ofl/cormorantgaramond/CormorantGaramond-Italic%5Bwght%5D.ttf",
56
- "https://raw.githubusercontent.com/google/fonts/main/ofl/cormorantgaramond/static/CormorantGaramond-Italic.ttf"],
57
- "hindi": ["https://raw.githubusercontent.com/google/fonts/main/ofl/notoserifdevanagari/NotoSerifDevanagari%5Bwght%5D.ttf",
58
- "https://raw.githubusercontent.com/google/fonts/main/ofl/notoserifdevanagari/static/NotoSerifDevanagari-Regular.ttf"],
59
  }
60
  FPATH = {}
61
  for key, urls in FONT_URLS.items():
@@ -63,7 +60,7 @@ for key, urls in FONT_URLS.items():
63
  dest = os.path.join(FDIR, "%s_%d.ttf" % (key, i))
64
  try:
65
  req = urllib.request.Request(u, headers={"User-Agent": "Mozilla/5.0"})
66
- with urllib.request.urlopen(req, timeout=60) as r, open(dest, "wb") as fh:
67
  fh.write(r.read())
68
  FPATH[key] = dest
69
  print("FONT OK %-7s %8d %s" % (key, os.path.getsize(dest), u.split("/")[-1]))
@@ -71,22 +68,31 @@ for key, urls in FONT_URLS.items():
71
  except Exception as e:
72
  print("FONT FAIL %-7s %s" % (key, repr(e)[:90]))
73
  HAS_RAQM = bool(features.check("raqm"))
74
- print("RAQM (complex text shaping):", HAS_RAQM)
 
75
 
76
  _fc = {}
77
- def F(kind, size):
78
- key = (kind, size)
79
  if key in _fc:
80
  return _fc[key]
81
  path = FPATH.get(kind) or FPATH.get("serif") or FPATH.get("body")
82
  f = ImageFont.truetype(path, size)
 
 
 
 
 
 
 
 
83
  _fc[key] = f
84
  return f
85
 
86
  # ----------------------------------------------------------------- text helper
87
- def text_layer(lines, kind, size, color, tracking=0, line_h=None):
88
- """Render ink-cropped RGBA layer of centred text."""
89
- f = F(kind, size)
90
  tmp = Image.new("RGBA", (8, 8)); td = ImageDraw.Draw(tmp)
91
  lh = line_h or int(size * 1.30)
92
  widths = []
@@ -98,20 +104,30 @@ def text_layer(lines, kind, size, color, tracking=0, line_h=None):
98
  pad = int(size * 0.9) + 14
99
  lw = int(max(widths)) + 2 * pad
100
  lht = int(lh * len(lines)) + 2 * pad
101
- lay = Image.new("RGBA", (lw, lht), (0, 0, 0, 0))
102
  d = ImageDraw.Draw(lay)
103
  for i, ln in enumerate(lines):
104
- base = pad + lh * i + lh * 0.80
105
  if tracking:
106
  x = (lw - widths[i]) / 2.0
107
  for ch in ln:
108
- d.text((x, base), ch, font=f, fill=color + (255,), anchor="ls")
109
  x += td.textlength(ch, font=f) + tracking
110
  else:
111
  d.text((lw / 2.0, pad + lh * i + lh / 2.0), ln, font=f, fill=color + (255,), anchor="mm")
112
  bb = lay.getbbox()
113
  return lay.crop(bb) if bb else lay
114
 
 
 
 
 
 
 
 
 
 
 
 
115
  def alpha_scale(sprite, a):
116
  if a >= 0.999:
117
  return sprite
@@ -128,22 +144,20 @@ def alpha_variants(sprite, n=12):
128
  out.append(Image.fromarray(arr.astype(np.uint8), "RGBA"))
129
  return out
130
 
131
- def paste(dst, lay, cx, cy, alpha, dx=0.0, dy=0.0, anchor="c"):
132
- if alpha <= 0.004:
133
  return
134
  im = alpha_scale(lay, alpha) if alpha < 0.999 else lay
135
- if anchor == "c":
136
- x = int(cx - lay.size[0] / 2 + dx); y = int(cy - lay.size[1] / 2 + dy)
137
- else: # top-left
138
- x = int(cx + dx); y = int(cy + dy)
139
- if x + im.size[0] < 0 or y + im.size[1] < 0 or x > W or y > H:
140
  return
141
  dst.alpha_composite(im, (x, y))
142
 
143
  def rule_strip(w, alpha, thickness=2):
144
- ramp = np.linspace(0.0, 1.0, max(2, w))
 
145
  a = (np.sin(np.pi * ramp) ** 1.4 * 255 * alpha).astype(np.uint8)
146
- st = np.zeros((thickness, max(2, w), 4), dtype=np.uint8)
147
  st[..., 0], st[..., 1], st[..., 2] = GOLD[0], GOLD[1], GOLD[2]
148
  st[..., 3] = a
149
  return Image.fromarray(st, "RGBA")
@@ -155,8 +169,9 @@ def build_bg():
155
  bg = np.repeat(bg, W, axis=1).astype(np.float32)
156
  yy, xx = np.mgrid[0:H, 0:W].astype(np.float32)
157
  d = np.sqrt(((xx - W * 0.5) / (W * 0.80)) ** 2 + ((yy - H * 0.40) / (H * 0.52)) ** 2)
158
- glow = np.clip(1 - d, 0, 1) ** 2.3
159
- bg += glow[..., None] * np.array([118, 58, 18], dtype=np.float32)[None, None, :]
 
160
  return Image.fromarray(np.clip(bg, 0, 255).astype(np.uint8), "RGB")
161
 
162
  def build_frame():
@@ -188,8 +203,8 @@ def build_toran(height=210):
188
  col = MARIGOLD if i % 2 == 0 else ORANGE
189
  d.ellipse([x - r, yy - r, x + r, yy + r], fill=col + (238,))
190
  d.ellipse([x - r * 0.34, yy - r * 0.55, x + r * 0.18, yy - r * 0.12], fill=(255, 236, 196, 130))
191
- jx = x1 if k < 3 else None
192
- if jx:
193
  d.polygon([(jx, 108), (jx - 13, 92), (jx, 74), (jx + 13, 92)], fill=(58, 122, 74, 210))
194
  for x in (W * 0.25, W * 0.5, W * 0.75):
195
  d.line([x, 118, x, 176], fill=GOLD_L + (170,), width=2)
@@ -211,9 +226,8 @@ def build_mandala(size=1040):
211
  ImageDraw.Draw(p).ellipse([0, 0, pw - 1, ph - 1], outline=GOLD_L + (85,), width=int(1.5 * S))
212
  p = p.rotate(-ang, expand=True, resample=Image.BICUBIC)
213
  r = s * 0.368 / 2.0
214
- x = c + r * math.cos(math.radians(ang)) - p.size[0] / 2.0
215
- y = c + r * math.sin(math.radians(ang)) - p.size[1] / 2.0
216
- im.alpha_composite(p, (int(x), int(y)))
217
  for i in range(48):
218
  ang = 360.0 * i / 48
219
  r = s * 0.248 / 2.0
@@ -233,11 +247,10 @@ def build_diya(size=200):
233
  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))
234
  return im.resize((size, size), Image.LANCZOS)
235
 
236
- def build_glow(size=420, radius=170.0):
237
  yy, xx = np.mgrid[0:size, 0:size]
238
  c = (size - 1) / 2.0
239
- d = np.sqrt((xx - c) ** 2 + (yy - c) ** 2) / radius
240
- g = np.clip(1 - d, 0, 1) ** 2.4
241
  arr = np.zeros((size, size, 4), dtype=np.uint8)
242
  arr[..., 0], arr[..., 1], arr[..., 2] = 255, 176, 70
243
  arr[..., 3] = (g * 195).astype(np.uint8)
@@ -246,8 +259,7 @@ def build_glow(size=420, radius=170.0):
246
  def build_mote(size=26):
247
  yy, xx = np.mgrid[0:size, 0:size]
248
  c = (size - 1) / 2.0
249
- r = np.sqrt((xx - c) ** 2 + (yy - c) ** 2) / c
250
- g = np.clip(1 - r, 0, 1) ** 2.0
251
  arr = np.zeros((size, size, 4), dtype=np.uint8)
252
  arr[..., 0], arr[..., 1], arr[..., 2] = 244, 214, 150
253
  arr[..., 3] = (g * 210).astype(np.uint8)
@@ -261,8 +273,7 @@ def build_lotus(size=124):
261
  ImageDraw.Draw(p).ellipse([0, 0, pw - 1, ph - 1], outline=GOLD_L + (215,), width=3)
262
  p = p.rotate(-(i * 30), expand=True, resample=Image.BICUBIC)
263
  im.alpha_composite(p, (size // 2 - p.size[0] // 2, size // 2 - p.size[1] // 2))
264
- d = ImageDraw.Draw(im)
265
- d.ellipse([size / 2 - 8, size / 2 - 8, size / 2 + 8, size / 2 + 8], fill=MARIGOLD + (235,))
266
  return im
267
 
268
  def build_monogram(D=600):
@@ -273,20 +284,18 @@ def build_monogram(D=600):
273
  d.ellipse([34, 34, D - 34, D - 34], outline=GOLD_L + (70,), width=1)
274
  for i in range(14):
275
  ang = 360.0 * i / 14
276
- pw, ph = int(D * 0.19), int(D * 0.075)
277
- p = Image.new("RGBA", (pw, ph), (0, 0, 0, 0))
278
- ImageDraw.Draw(p).ellipse([0, 0, pw - 1, ph - 1], outline=GOLD_L + (120,), width=2)
279
  p = p.rotate(-ang, expand=True, resample=Image.BICUBIC)
280
  r = D * 0.415
281
- x = c + r * math.cos(math.radians(ang)) - p.size[0] / 2.0
282
- y = c + r * math.sin(math.radians(ang)) - p.size[1] / 2.0
283
- im.alpha_composite(p, (int(x), int(y)))
284
  lay = text_layer([EV["name"][0].upper()], "script", int(D * 0.60), CREAM)
285
  im.alpha_composite(lay, (int(c - lay.size[0] / 2), int(c - lay.size[1] / 2)))
286
  return im
287
 
288
  def make_card(width, title, sections, title_size=66, label_size=26, value_size=46, alpha=205):
289
- Hc = 1400
290
  card = Image.new("RGBA", (width, Hc), (0, 0, 0, 0))
291
  S = 2
292
  tmp = Image.new("RGBA", (width * S, Hc * S), (0, 0, 0, 0))
@@ -295,7 +304,7 @@ def make_card(width, title, sections, title_size=66, label_size=26, value_size=4
295
  card.alpha_composite(tmp.resize((width, Hc), Image.LANCZOS), (0, 0))
296
  y = 74
297
  if title:
298
- tl = text_layer([title], "script", title_size, GOLD)
299
  card.alpha_composite(tl, (int(width / 2 - tl.size[0] / 2), int(y)))
300
  y += tl.size[1] + 30
301
  rw = int(width * 0.44)
@@ -310,13 +319,12 @@ def make_card(width, title, sections, title_size=66, label_size=26, value_size=4
310
  card.alpha_composite(ll, (int(width / 2 - ll.size[0] / 2), int(y)))
311
  y += ll.size[1] + 22
312
  for v in sec["values"]:
313
- vl = text_layer([v], "body", value_size, CREAM)
314
  card.alpha_composite(vl, (int(width / 2 - vl.size[0] / 2), int(y)))
315
  y += vl.size[1] + 12
316
  y += 18
317
  used = y + 40
318
- tl2 = build_lotus(64)
319
- card.alpha_composite(tl2, (int(width / 2 - 32), int(used - 20)))
320
  return card.crop((0, 0, width, min(Hc, used + 54)))
321
 
322
  # ----------------------------------------------------------------- build assets
@@ -337,52 +345,49 @@ MOTES = [dict(x=random.uniform(70, W - 70), y=random.uniform(0, H), sp=random.un
337
  sw=random.uniform(0.25, 0.7), ph=random.uniform(0, 6.28), big=random.random() < 0.45)
338
  for _ in range(16)]
339
 
340
- kicker1 = text_layer([EV["hindi"]], "hindi", 44, GOLD) if HAS_RAQM else \
 
341
  text_layer([EV["kicker1_en"]], "serif", 34, GOLD, tracking=13)
342
- if HAS_RAQM:
343
- k1_extra = text_layer([EV["kicker1_en"]], "serif", 26, GOLD, tracking=11)
344
- else:
345
- k1_extra = None
346
 
347
- L_script1 = text_layer([EV["script1"]], "script", 158, GOLD)
348
- L_sub1 = text_layer([EV["sub1"]], "bodyi", 46, SOFT)
349
  L_kick2 = text_layer([EV["kicker2"]], "serif", 32, GOLD, tracking=15)
350
- L_name = text_layer([EV["name"]], "script", 248, CREAM)
351
- L_name_glow = alpha_scale(text_layer([EV["name"]], "script", 248, GOLD).filter(ImageFilter.GaussianBlur(16)), 0.55)
352
- L_body2 = text_layer([EV["body2"]], "bodyi", 47, SOFT)
353
  L_small2 = text_layer([EV["small2"]], "serif", 28, GOLD, tracking=10)
354
  CARD_D = make_card(832, EV["card_title"], [
355
  dict(label=EV["when_label"], values=[EV["when_1"], EV["when_2"]]),
356
  dict(label=EV["where_label"], values=[EV["where_1"]]),
357
  ])
358
- L_sub3 = text_layer([EV["sub3"]], "bodyi", 42, SOFT)
359
  MONO = build_monogram(600)
360
- L_quote = text_layer(EV["quote"], "bodyi", 47, SOFT, line_h=76)
361
  L_kick3 = text_layer(["THE CELEBRATION"], "serif", 32, GOLD, tracking=15)
362
- L_script5 = text_layer([EV["script5"]], "script", 104, GOLD)
363
- L_body5 = text_layer([EV["body5"]], "bodyi", 43, SOFT)
364
- L_name5 = text_layer([EV["name"]], "script", 152, CREAM)
365
  CARD_R = make_card(700, None, [dict(label=EV["rsvp_label"], values=[EV["rsvp_value"]])],
366
  label_size=28, value_size=44)
367
  L_kick6 = text_layer([EV["kicker6"]], "serif", 32, GOLD, tracking=15)
368
- L_script6 = text_layer([EV["script6"]], "script", 136, GOLD)
369
- L_sig = text_layer([EV["sig"]], "script", 80, CREAM)
370
 
371
  # ----------------------------------------------------------------- timeline
372
  DUR = [4.0, 5.0, 6.5, 5.5, 5.5, 5.5]
373
- OV, HOLD = 0.55, 2.0
374
- start = []
375
- acc = 0.0
376
  for d in DUR:
377
  start.append(acc); acc += d - OV
378
  LAST_END = start[-1] + DUR[-1]
379
  TOTAL = LAST_END + HOLD
380
- FADES = 0.75
381
  NF = int(round(TOTAL * FPS))
382
- print("timeline:", [round(s, 2) for s in start], "last end", round(LAST_END, 2), "total", round(TOTAL, 2), "frames", NF)
383
 
384
  def scene_alpha(i, t):
385
- s, e = start[i], (TOTAL if i == len(DUR) - 1 else start[i] + DUR[i])
 
386
  if t < s or t > e:
387
  return 0.0
388
  if i + 1 < len(DUR) and t >= start[i + 1]:
@@ -397,44 +402,21 @@ def ease(t, delay, dur=0.95):
397
  return 1.0
398
  return 1.0 - (1.0 - x) ** 3
399
 
400
- # item = (layer, xf, yf, delay, dy, dur, anchor)
401
  ITEMS = [
402
- [(kicker1, 0.5, 0.278, 0.10, 40, 0.9, "c"),
403
- (k1_extra, 0.5, 0.325, 0.28, 34, 0.9, "c"),
404
- (L_script1, 0.5, 0.408, 0.48, 62, 1.05, "c"),
405
- (LOTUS, 0.5, 0.497, 0.88, 18, 0.8, "c"),
406
- (L_sub1, 0.5, 0.556, 1.05, 40, 0.9, "c")],
407
-
408
- [(L_kick2, 0.5, 0.297, 0.10, 38, 0.9, "c"),
409
- (L_name_glow, 0.5, 0.415, 0.42, 58, 1.1, "c"),
410
- (L_name, 0.5, 0.415, 0.42, 58, 1.1, "c"),
411
- (LOTUS, 0.5, 0.525, 0.88, 18, 0.8, "c"),
412
- (L_body2, 0.5, 0.588, 1.00, 40, 0.9, "c"),
413
- (L_small2, 0.5, 0.650, 1.20, 30, 0.9, "c")],
414
-
415
- [(L_kick3, 0.5, 0.252, 0.10, 38, 0.9, "c"),
416
- (CARD_D, 0.5, 0.488, 0.40, 56, 1.05, "c"),
417
- (L_sub3, 0.5, 0.732, 1.05, 40, 0.9, "c")],
418
-
419
- [(MONO, 0.5, 0.400, 0.20, 50, 1.05, "c"),
420
- (LOTUS_S, 0.5, 0.548, 0.90, 18, 0.8, "c"),
421
- (L_quote, 0.5, 0.648, 1.05, 44, 1.0, "c")],
422
-
423
- [(L_script5, 0.5, 0.286, 0.15, 50, 1.0, "c"),
424
- (L_body5, 0.5, 0.362, 0.52, 40, 0.9, "c"),
425
- (L_name5, 0.5, 0.441, 0.80, 56, 1.05, "c"),
426
- (CARD_R, 0.5, 0.615, 1.10, 50, 1.0, "c")],
427
-
428
- [(L_kick6, 0.5, 0.336, 0.15, 36, 0.9, "c"),
429
- (L_script6, 0.5, 0.428, 0.45, 58, 1.05, "c"),
430
- (LOTUS, 0.5, 0.515, 0.88, 18, 0.8, "c"),
431
- (L_sig, 0.5, 0.578, 1.08, 44, 0.95, "c")],
432
  ]
433
 
434
- def rgba_layer_to_box(lay):
435
- return lay
436
-
437
- def render(t, poster=False):
438
  img = BG.copy()
439
  mand = MANDALA.rotate((t * 7.5) % 360.0, resample=Image.BICUBIC)
440
  img.alpha_composite(mand, (int(W / 2 - mand.size[0] / 2), int(H * 0.455 - mand.size[1] / 2)))
@@ -442,63 +424,55 @@ def render(t, poster=False):
442
  img.alpha_composite(FRAME, (0, 0))
443
  for ph_i, cx in enumerate((148, W - 148)):
444
  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)
445
- fl = max(0.30, min(1.0, fl))
446
- g = GLOWS[int(fl * 11)]
447
- cy = H - 168
448
- img.alpha_composite(g, (int(cx - g.size[0] / 2), int(cy - g.size[1] / 2 - 46)))
449
- img.alpha_composite(DIYA, (int(cx - DIYA.size[0] / 2), int(cy - DIYA.size[1] / 2 - 46)))
450
  for m in MOTES:
451
  yy = (m["y"] - m["sp"] * t) % (H + 240) - 120
452
  xx = m["x"] + 26 * math.sin(t * m["sw"] + m["ph"])
453
  al = 0.22 + 0.62 * max(0.0, math.sin(t * 0.85 + m["ph"]))
454
- idx = max(0, min(11, int(al * 11)))
455
- sp = MOTE_V[idx] if m["big"] else MOTE_S[idx]
456
  px, py = int(xx - sp.size[0] / 2), int(yy - sp.size[1] / 2)
457
- if -sp.size[0] < px < W and -sp.size[1] < py < H:
458
- img.alpha_composite(sp, (max(0, px), max(0, py)) if (px >= 0 and py >= 0) else (px, py))
459
  for i in range(len(DUR)):
460
  sa = scene_alpha(i, t)
461
  if sa <= 0.004:
462
  continue
463
  tl = t - start[i]
464
- for (lay, xf, yf, delay, dy, dur, an) in ITEMS[i]:
465
- a = ease(tl, delay, dur) * sa
466
- if an == "c":
467
- paste(img, lay, W * xf, H * yf, a, dy=(1 - ease(tl, delay, dur)) * dy)
468
- else:
469
- paste(img, lay, W * xf, H * yf, a, dy=(1 - ease(tl, delay, dur)) * dy, anchor="tl")
470
- if poster:
471
- return img.convert("RGB")
472
  if t < FADES:
473
  k = t / FADES
474
  elif t > TOTAL - FADES:
475
  k = max(0.0, (TOTAL - t) / FADES)
476
- else:
477
- k = 1.0
478
- rgb = img.convert("RGB")
479
  if k < 1.0:
480
- arr = np.asarray(rgb, dtype=np.float32) * k
481
- return Image.fromarray(arr.astype(np.uint8), "RGB")
482
  return rgb
483
 
484
  # ----------------------------------------------------------------- encode
485
  from imageio_ffmpeg import get_ffmpeg_exe
486
  FFMPEG = get_ffmpeg_exe()
487
  print("ffmpeg:", FFMPEG)
488
- cmd = [FFMPEG, "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24",
489
- "-s", "%dx%d" % (W, H), "-r", str(FPS), "-i", "-",
490
- "-c:v", "libx264", "-preset", "medium", "-crf", "20", "-pix_fmt", "yuv420p",
491
- "-movflags", "+faststart", "-an", OUT]
492
- proc = subprocess.Popen(cmd, stdin=subprocess.PIPE)
493
 
494
  poster_t = start[1] + 2.6
495
  for n in range(NF):
496
  t = n / float(FPS)
497
- fr = render(t, poster=(abs(t - poster_t) < 0.5 / FPS))
498
  if abs(t - poster_t) < 0.5 / FPS:
499
  fr.save(POSTER, quality=92)
500
  proc.stdin.write(np.asarray(fr, dtype=np.uint8).tobytes())
501
- if n % 120 == 0:
502
  print("frame %4d / %d (t=%.1fs)" % (n, NF, t), flush=True)
503
  proc.stdin.close()
504
  proc.wait()
@@ -507,11 +481,9 @@ print("encoded:", OUT, os.path.getsize(OUT), "bytes")
507
  # ----------------------------------------------------------------- upload
508
  from huggingface_hub import HfApi
509
  REPO = os.environ.get("REPO_ID", "coderdecoder01/retirement-invitation-mamta")
510
- tok = os.environ.get("HF_TOKEN")
511
- api = HfApi(token=tok)
512
  api.create_repo(repo_id=REPO, repo_type="dataset", private=False, exist_ok=True)
513
- api.upload_file(path_or_fileobj=OUT, path_in_repo="mamta-retirement-invitation.mp4",
514
- repo_id=REPO, repo_type="dataset")
515
  api.upload_file(path_or_fileobj=POSTER, path_in_repo="poster.jpg", repo_id=REPO, repo_type="dataset")
516
- print("UPLOADED https://huggingface.co/datasets/%s/resolve/main/mamta-retirement-invitation.mp4" % REPO)
517
- print("POSTER https://huggingface.co/datasets/%s/resolve/main/poster.jpg" % REPO)
 
21
  # ----------------------------------------------------------------- event text
22
  EV = dict(
23
  name="Mamta",
24
+ hindi="\u0936\u0941\u092d \u0938\u0947\u0935\u093e\u0928\u093f\u0935\u0943\u0924\u094d\u0924\u093f", # shubh sevanivrutti
25
  kicker1_en="WITH GREAT JOY",
26
  script1="You\u2019re Invited",
27
  sub1="a celebration of a beautiful journey",
 
46
  )
47
 
48
  # ----------------------------------------------------------------- fonts
49
+ GH = "https://raw.githubusercontent.com/google/fonts/main/ofl/"
50
  FONT_URLS = {
51
+ "script": [GH + "greatvibes/GreatVibes-Regular.ttf"],
52
+ "serif": [GH + "playfairdisplay/PlayfairDisplay%5Bwght%5D.ttf"],
53
+ "body": [GH + "cormorantgaramond/CormorantGaramond%5Bwght%5D.ttf"],
54
+ "bodyi": [GH + "cormorantgaramond/CormorantGaramond-Italic%5Bwght%5D.ttf"],
55
+ "hindi": [GH + "notoserifdevanagari/NotoSerifDevanagari%5Bwdth%2Cwght%5D.ttf"],
 
 
 
 
56
  }
57
  FPATH = {}
58
  for key, urls in FONT_URLS.items():
 
60
  dest = os.path.join(FDIR, "%s_%d.ttf" % (key, i))
61
  try:
62
  req = urllib.request.Request(u, headers={"User-Agent": "Mozilla/5.0"})
63
+ with urllib.request.urlopen(req, timeout=90) as r, open(dest, "wb") as fh:
64
  fh.write(r.read())
65
  FPATH[key] = dest
66
  print("FONT OK %-7s %8d %s" % (key, os.path.getsize(dest), u.split("/")[-1]))
 
68
  except Exception as e:
69
  print("FONT FAIL %-7s %s" % (key, repr(e)[:90]))
70
  HAS_RAQM = bool(features.check("raqm"))
71
+ HAS_HINDI = HAS_RAQM and "hindi" in FPATH
72
+ print("RAQM:", HAS_RAQM, "| Devanagari usable:", HAS_HINDI)
73
 
74
  _fc = {}
75
+ def F(kind, size, weight=None):
76
+ key = (kind, size, weight)
77
  if key in _fc:
78
  return _fc[key]
79
  path = FPATH.get(kind) or FPATH.get("serif") or FPATH.get("body")
80
  f = ImageFont.truetype(path, size)
81
+ if weight and hasattr(f, "set_variation_by_name"):
82
+ try:
83
+ f.set_variation_by_name(str(weight))
84
+ except Exception:
85
+ try:
86
+ f.set_variation_by_axes([weight] * len(f.get_variation_axes()))
87
+ except Exception:
88
+ pass
89
  _fc[key] = f
90
  return f
91
 
92
  # ----------------------------------------------------------------- text helper
93
+ def text_layer(lines, kind, size, color, tracking=0, line_h=None, weight=None):
94
+ """Ink-cropped RGBA layer of centred text."""
95
+ f = F(kind, size, weight)
96
  tmp = Image.new("RGBA", (8, 8)); td = ImageDraw.Draw(tmp)
97
  lh = line_h or int(size * 1.30)
98
  widths = []
 
104
  pad = int(size * 0.9) + 14
105
  lw = int(max(widths)) + 2 * pad
106
  lht = int(lh * len(lines)) + 2 * pad
107
+ lay = Image.new("RGBA", (max(8, lw), max(8, lht)), (0, 0, 0, 0))
108
  d = ImageDraw.Draw(lay)
109
  for i, ln in enumerate(lines):
 
110
  if tracking:
111
  x = (lw - widths[i]) / 2.0
112
  for ch in ln:
113
+ d.text((x, pad + lh * i + lh * 0.80), ch, font=f, fill=color + (255,), anchor="ls")
114
  x += td.textlength(ch, font=f) + tracking
115
  else:
116
  d.text((lw / 2.0, pad + lh * i + lh / 2.0), ln, font=f, fill=color + (255,), anchor="mm")
117
  bb = lay.getbbox()
118
  return lay.crop(bb) if bb else lay
119
 
120
+ def fit_layer(lines, kind, size, color, max_w, tracking=0, line_h=None, weight=None):
121
+ """Shrink the point size until the rendered ink fits inside max_w pixels."""
122
+ s = size
123
+ lay = None
124
+ while s > 18:
125
+ lay = text_layer(lines, kind, s, color, tracking=tracking, line_h=line_h, weight=weight)
126
+ if lay.size[0] <= max_w:
127
+ return lay
128
+ s = int(s * 0.94)
129
+ return lay
130
+
131
  def alpha_scale(sprite, a):
132
  if a >= 0.999:
133
  return sprite
 
144
  out.append(Image.fromarray(arr.astype(np.uint8), "RGBA"))
145
  return out
146
 
147
+ def paste(dst, lay, cx, cy, alpha, dy=0.0):
148
+ if lay is None or alpha <= 0.004:
149
  return
150
  im = alpha_scale(lay, alpha) if alpha < 0.999 else lay
151
+ x = int(cx - lay.size[0] / 2.0); y = int(cy - lay.size[1] / 2.0 + dy)
152
+ if x >= W or y >= H or x + im.size[0] <= 0 or y + im.size[1] <= 0:
 
 
 
153
  return
154
  dst.alpha_composite(im, (x, y))
155
 
156
  def rule_strip(w, alpha, thickness=2):
157
+ w = max(2, int(w))
158
+ ramp = np.linspace(0.0, 1.0, w)
159
  a = (np.sin(np.pi * ramp) ** 1.4 * 255 * alpha).astype(np.uint8)
160
+ st = np.zeros((thickness, w, 4), dtype=np.uint8)
161
  st[..., 0], st[..., 1], st[..., 2] = GOLD[0], GOLD[1], GOLD[2]
162
  st[..., 3] = a
163
  return Image.fromarray(st, "RGBA")
 
169
  bg = np.repeat(bg, W, axis=1).astype(np.float32)
170
  yy, xx = np.mgrid[0:H, 0:W].astype(np.float32)
171
  d = np.sqrt(((xx - W * 0.5) / (W * 0.80)) ** 2 + ((yy - H * 0.40) / (H * 0.52)) ** 2)
172
+ bg += (np.clip(1 - d, 0, 1) ** 2.3)[..., None] * np.array([118, 58, 18], dtype=np.float32)[None, None, :]
173
+ v = np.sqrt(((xx - W * 0.5) / (W * 0.56)) ** 2 + ((yy - H * 0.5) / (H * 0.60)) ** 2)
174
+ bg *= (1.0 - 0.42 * np.clip(v, 0, 1) ** 2.4)[..., None]
175
  return Image.fromarray(np.clip(bg, 0, 255).astype(np.uint8), "RGB")
176
 
177
  def build_frame():
 
203
  col = MARIGOLD if i % 2 == 0 else ORANGE
204
  d.ellipse([x - r, yy - r, x + r, yy + r], fill=col + (238,))
205
  d.ellipse([x - r * 0.34, yy - r * 0.55, x + r * 0.18, yy - r * 0.12], fill=(255, 236, 196, 130))
206
+ if k < 3:
207
+ jx = x1
208
  d.polygon([(jx, 108), (jx - 13, 92), (jx, 74), (jx + 13, 92)], fill=(58, 122, 74, 210))
209
  for x in (W * 0.25, W * 0.5, W * 0.75):
210
  d.line([x, 118, x, 176], fill=GOLD_L + (170,), width=2)
 
226
  ImageDraw.Draw(p).ellipse([0, 0, pw - 1, ph - 1], outline=GOLD_L + (85,), width=int(1.5 * S))
227
  p = p.rotate(-ang, expand=True, resample=Image.BICUBIC)
228
  r = s * 0.368 / 2.0
229
+ im.alpha_composite(p, (int(c + r * math.cos(math.radians(ang)) - p.size[0] / 2),
230
+ int(c + r * math.sin(math.radians(ang)) - p.size[1] / 2)))
 
231
  for i in range(48):
232
  ang = 360.0 * i / 48
233
  r = s * 0.248 / 2.0
 
247
  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))
248
  return im.resize((size, size), Image.LANCZOS)
249
 
250
+ def build_glow(size=430, radius=175.0):
251
  yy, xx = np.mgrid[0:size, 0:size]
252
  c = (size - 1) / 2.0
253
+ g = np.clip(1 - np.sqrt((xx - c) ** 2 + (yy - c) ** 2) / radius, 0, 1) ** 2.4
 
254
  arr = np.zeros((size, size, 4), dtype=np.uint8)
255
  arr[..., 0], arr[..., 1], arr[..., 2] = 255, 176, 70
256
  arr[..., 3] = (g * 195).astype(np.uint8)
 
259
  def build_mote(size=26):
260
  yy, xx = np.mgrid[0:size, 0:size]
261
  c = (size - 1) / 2.0
262
+ g = np.clip(1 - np.sqrt((xx - c) ** 2 + (yy - c) ** 2) / c, 0, 1) ** 2.0
 
263
  arr = np.zeros((size, size, 4), dtype=np.uint8)
264
  arr[..., 0], arr[..., 1], arr[..., 2] = 244, 214, 150
265
  arr[..., 3] = (g * 210).astype(np.uint8)
 
273
  ImageDraw.Draw(p).ellipse([0, 0, pw - 1, ph - 1], outline=GOLD_L + (215,), width=3)
274
  p = p.rotate(-(i * 30), expand=True, resample=Image.BICUBIC)
275
  im.alpha_composite(p, (size // 2 - p.size[0] // 2, size // 2 - p.size[1] // 2))
276
+ ImageDraw.Draw(im).ellipse([size / 2 - 8, size / 2 - 8, size / 2 + 8, size / 2 + 8], fill=MARIGOLD + (235,))
 
277
  return im
278
 
279
  def build_monogram(D=600):
 
284
  d.ellipse([34, 34, D - 34, D - 34], outline=GOLD_L + (70,), width=1)
285
  for i in range(14):
286
  ang = 360.0 * i / 14
287
+ p = Image.new("RGBA", (int(D * 0.19), int(D * 0.075)), (0, 0, 0, 0))
288
+ ImageDraw.Draw(p).ellipse([0, 0, p.size[0] - 1, p.size[1] - 1], outline=GOLD_L + (120,), width=2)
 
289
  p = p.rotate(-ang, expand=True, resample=Image.BICUBIC)
290
  r = D * 0.415
291
+ im.alpha_composite(p, (int(c + r * math.cos(math.radians(ang)) - p.size[0] / 2),
292
+ int(c + r * math.sin(math.radians(ang)) - p.size[1] / 2)))
 
293
  lay = text_layer([EV["name"][0].upper()], "script", int(D * 0.60), CREAM)
294
  im.alpha_composite(lay, (int(c - lay.size[0] / 2), int(c - lay.size[1] / 2)))
295
  return im
296
 
297
  def make_card(width, title, sections, title_size=66, label_size=26, value_size=46, alpha=205):
298
+ Hc = 1500
299
  card = Image.new("RGBA", (width, Hc), (0, 0, 0, 0))
300
  S = 2
301
  tmp = Image.new("RGBA", (width * S, Hc * S), (0, 0, 0, 0))
 
304
  card.alpha_composite(tmp.resize((width, Hc), Image.LANCZOS), (0, 0))
305
  y = 74
306
  if title:
307
+ tl = fit_layer([title], "script", title_size, GOLD, width - 110)
308
  card.alpha_composite(tl, (int(width / 2 - tl.size[0] / 2), int(y)))
309
  y += tl.size[1] + 30
310
  rw = int(width * 0.44)
 
319
  card.alpha_composite(ll, (int(width / 2 - ll.size[0] / 2), int(y)))
320
  y += ll.size[1] + 22
321
  for v in sec["values"]:
322
+ vl = fit_layer([v], "body", value_size, CREAM, width - 96)
323
  card.alpha_composite(vl, (int(width / 2 - vl.size[0] / 2), int(y)))
324
  y += vl.size[1] + 12
325
  y += 18
326
  used = y + 40
327
+ card.alpha_composite(build_lotus(64), (int(width / 2 - 32), int(used - 20)))
 
328
  return card.crop((0, 0, width, min(Hc, used + 54)))
329
 
330
  # ----------------------------------------------------------------- build assets
 
345
  sw=random.uniform(0.25, 0.7), ph=random.uniform(0, 6.28), big=random.random() < 0.45)
346
  for _ in range(16)]
347
 
348
+ MAXW = 880 # keep clear of the gold frame
349
+ kicker1 = text_layer([EV["hindi"]], "hindi", 46, GOLD) if HAS_HINDI else \
350
  text_layer([EV["kicker1_en"]], "serif", 34, GOLD, tracking=13)
351
+ k1_extra = text_layer([EV["kicker1_en"]], "serif", 26, GOLD, tracking=11) if HAS_HINDI else None
 
 
 
352
 
353
+ L_script1 = fit_layer([EV["script1"]], "script", 158, GOLD, MAXW)
354
+ L_sub1 = fit_layer([EV["sub1"]], "bodyi", 46, SOFT, MAXW)
355
  L_kick2 = text_layer([EV["kicker2"]], "serif", 32, GOLD, tracking=15)
356
+ L_name = fit_layer([EV["name"]], "script", 250, CREAM, MAXW)
357
+ L_name_glow = alpha_scale(fit_layer([EV["name"]], "script", 250, GOLD, MAXW).filter(ImageFilter.GaussianBlur(16)), 0.55)
358
+ L_body2 = fit_layer([EV["body2"]], "bodyi", 47, SOFT, MAXW)
359
  L_small2 = text_layer([EV["small2"]], "serif", 28, GOLD, tracking=10)
360
  CARD_D = make_card(832, EV["card_title"], [
361
  dict(label=EV["when_label"], values=[EV["when_1"], EV["when_2"]]),
362
  dict(label=EV["where_label"], values=[EV["where_1"]]),
363
  ])
364
+ L_sub3 = fit_layer([EV["sub3"]], "bodyi", 42, SOFT, MAXW)
365
  MONO = build_monogram(600)
366
+ L_quote = fit_layer(EV["quote"], "bodyi", 47, SOFT, MAXW - 60, line_h=76)
367
  L_kick3 = text_layer(["THE CELEBRATION"], "serif", 32, GOLD, tracking=15)
368
+ L_script5 = fit_layer([EV["script5"]], "script", 104, GOLD, MAXW)
369
+ L_body5 = fit_layer([EV["body5"]], "bodyi", 43, SOFT, MAXW)
370
+ L_name5 = fit_layer([EV["name"]], "script", 152, CREAM, MAXW)
371
  CARD_R = make_card(700, None, [dict(label=EV["rsvp_label"], values=[EV["rsvp_value"]])],
372
  label_size=28, value_size=44)
373
  L_kick6 = text_layer([EV["kicker6"]], "serif", 32, GOLD, tracking=15)
374
+ L_script6 = fit_layer([EV["script6"]], "script", 136, GOLD, MAXW)
375
+ L_sig = fit_layer([EV["sig"]], "script", 80, CREAM, MAXW)
376
 
377
  # ----------------------------------------------------------------- timeline
378
  DUR = [4.0, 5.0, 6.5, 5.5, 5.5, 5.5]
379
+ OV, HOLD, FADES = 0.55, 2.0, 0.75
380
+ start, acc = [], 0.0
 
381
  for d in DUR:
382
  start.append(acc); acc += d - OV
383
  LAST_END = start[-1] + DUR[-1]
384
  TOTAL = LAST_END + HOLD
 
385
  NF = int(round(TOTAL * FPS))
386
+ print("timeline start:", [round(s, 2) for s in start], "total %.2fs %d frames" % (TOTAL, NF))
387
 
388
  def scene_alpha(i, t):
389
+ s = start[i]
390
+ e = TOTAL if i == len(DUR) - 1 else start[i] + DUR[i]
391
  if t < s or t > e:
392
  return 0.0
393
  if i + 1 < len(DUR) and t >= start[i + 1]:
 
402
  return 1.0
403
  return 1.0 - (1.0 - x) ** 3
404
 
 
405
  ITEMS = [
406
+ [(kicker1, 0.278, 0.10, 40, 0.9), (k1_extra, 0.325, 0.28, 34, 0.9),
407
+ (L_script1, 0.408, 0.48, 62, 1.05), (LOTUS, 0.497, 0.88, 18, 0.8),
408
+ (L_sub1, 0.556, 1.05, 40, 0.9)],
409
+ [(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),
410
+ (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)],
411
+ [(L_kick3, 0.252, 0.10, 38, 0.9), (CARD_D, 0.488, 0.40, 56, 1.05), (L_sub3, 0.732, 1.05, 40, 0.9)],
412
+ [(MONO, 0.400, 0.20, 50, 1.05), (LOTUS_S, 0.548, 0.90, 18, 0.8), (L_quote, 0.648, 1.05, 44, 1.0)],
413
+ [(L_script5, 0.286, 0.15, 50, 1.0), (L_body5, 0.362, 0.52, 40, 0.9), (L_name5, 0.441, 0.80, 56, 1.05),
414
+ (CARD_R, 0.615, 1.10, 50, 1.0)],
415
+ [(L_kick6, 0.336, 0.15, 36, 0.9), (L_script6, 0.428, 0.45, 58, 1.05), (LOTUS, 0.515, 0.88, 18, 0.8),
416
+ (L_sig, 0.578, 1.08, 44, 0.95)],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
417
  ]
418
 
419
+ def render(t):
 
 
 
420
  img = BG.copy()
421
  mand = MANDALA.rotate((t * 7.5) % 360.0, resample=Image.BICUBIC)
422
  img.alpha_composite(mand, (int(W / 2 - mand.size[0] / 2), int(H * 0.455 - mand.size[1] / 2)))
 
424
  img.alpha_composite(FRAME, (0, 0))
425
  for ph_i, cx in enumerate((148, W - 148)):
426
  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)
427
+ g = GLOWS[int(max(0.30, min(1.0, fl)) * 11)]
428
+ cy = H - 214
429
+ img.alpha_composite(g, (int(cx - g.size[0] / 2), int(cy - g.size[1] / 2)))
430
+ img.alpha_composite(DIYA, (int(cx - DIYA.size[0] / 2), int(cy - DIYA.size[1] / 2)))
 
431
  for m in MOTES:
432
  yy = (m["y"] - m["sp"] * t) % (H + 240) - 120
433
  xx = m["x"] + 26 * math.sin(t * m["sw"] + m["ph"])
434
  al = 0.22 + 0.62 * max(0.0, math.sin(t * 0.85 + m["ph"]))
435
+ sp = (MOTE_V if m["big"] else MOTE_S)[max(0, min(11, int(al * 11)))]
 
436
  px, py = int(xx - sp.size[0] / 2), int(yy - sp.size[1] / 2)
437
+ if px >= 0 and py >= 0 and px < W and py < H:
438
+ img.alpha_composite(sp, (px, py))
439
  for i in range(len(DUR)):
440
  sa = scene_alpha(i, t)
441
  if sa <= 0.004:
442
  continue
443
  tl = t - start[i]
444
+ for (lay, yf, delay, dy, dur) in ITEMS[i]:
445
+ if lay is None:
446
+ continue
447
+ e = ease(tl, delay, dur)
448
+ paste(img, lay, W / 2.0, H * yf, e * sa, dy=(1.0 - e) * dy)
449
+ rgb = img.convert("RGB")
450
+ k = 1.0
 
451
  if t < FADES:
452
  k = t / FADES
453
  elif t > TOTAL - FADES:
454
  k = max(0.0, (TOTAL - t) / FADES)
 
 
 
455
  if k < 1.0:
456
+ return Image.fromarray((np.asarray(rgb, dtype=np.float32) * k).astype(np.uint8), "RGB")
 
457
  return rgb
458
 
459
  # ----------------------------------------------------------------- encode
460
  from imageio_ffmpeg import get_ffmpeg_exe
461
  FFMPEG = get_ffmpeg_exe()
462
  print("ffmpeg:", FFMPEG)
463
+ proc = subprocess.Popen([FFMPEG, "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24",
464
+ "-s", "%dx%d" % (W, H), "-r", str(FPS), "-i", "-",
465
+ "-c:v", "libx264", "-preset", "medium", "-crf", "20", "-pix_fmt", "yuv420p",
466
+ "-movflags", "+faststart", "-an", OUT], stdin=subprocess.PIPE)
 
467
 
468
  poster_t = start[1] + 2.6
469
  for n in range(NF):
470
  t = n / float(FPS)
471
+ fr = render(t)
472
  if abs(t - poster_t) < 0.5 / FPS:
473
  fr.save(POSTER, quality=92)
474
  proc.stdin.write(np.asarray(fr, dtype=np.uint8).tobytes())
475
+ if n % 100 == 0:
476
  print("frame %4d / %d (t=%.1fs)" % (n, NF, t), flush=True)
477
  proc.stdin.close()
478
  proc.wait()
 
481
  # ----------------------------------------------------------------- upload
482
  from huggingface_hub import HfApi
483
  REPO = os.environ.get("REPO_ID", "coderdecoder01/retirement-invitation-mamta")
484
+ api = HfApi(token=os.environ.get("HF_TOKEN"))
 
485
  api.create_repo(repo_id=REPO, repo_type="dataset", private=False, exist_ok=True)
486
+ api.upload_file(path_or_fileobj=OUT, path_in_repo="mamta-retirement-invitation.mp4", repo_id=REPO, repo_type="dataset")
 
487
  api.upload_file(path_or_fileobj=POSTER, path_in_repo="poster.jpg", repo_id=REPO, repo_type="dataset")
488
+ print("VIDEO https://huggingface.co/datasets/%s/resolve/main/mamta-retirement-invitation.mp4" % REPO)
489
+ print("POSTER https://huggingface.co/datasets/%s/resolve/main/poster.jpg" % REPO)