SPB Git forge

spb/admin-ka

Public
41commits 1branches 0releases
172.9 MBsize
maindefault branch
19 days agolast push
JavaScript 65.5% Python 17.8% CSS 13% HTML 3.7%
25.5 KB · 452 lines python
Raw Blame History
1#!/usr/bin/env python32"""Reel KA v4 — mini-clip vertical MULTI-SCÈNES (1080x1920) + musique procédurale.34Le reel n'est plus une seule carte animée de 10 s : c'est une séquence de5scènes (~20-32 s) qui couvre plusieurs facettes de l'insight :6  intro → stat géante (count-up) / donut % → tuiles chiffres → palmarès animé7  → photos réelles (Ken Burns) → « le saviez-vous » → outro CTA.8Les scènes disponibles dépendent des données (tiles/bars/list/product/fact).910Musique : music_engine.py (6 styles, mélodie/progression/tonalité par graine)11— deux reels n'ont jamais la même musique. Style en rotation via `variant`.1213Pipeline : HTML animé -> Playwright (Chromium, enregistrement vidéo) -> ffmpeg.14Sortie : chemin du mp4 sur stdout. Env : KA_REEL_H (défaut 1920).15"""16import json, sys, os, re, base64, datetime, urllib.request, ssl, subprocess, glob, hashlib1718sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))19import music_engine2021CTX = ssl.create_default_context(); CTX.check_hostname=False; CTX.verify_mode=ssl.CERT_NONE22FFMPEG = "/opt/homebrew/bin/ffmpeg"23MOIS=["janvier","février","mars","avril","mai","juin","juillet","août","septembre","octobre","novembre","décembre"]24FONT="'Avenir Next','SF Pro Display','Helvetica Neue',Helvetica,Arial,sans-serif"25H=int(os.environ.get("KA_REEL_H","1920"))26STYLES_ORDER=["house","synthwave","lofi","funk","epic","trap"]2728PALETTES={29 "lou-ka":{"a":"#ff6a00","b":"#ff9d4d","g1":"#2a1403","g2":"#0d0b09"},30 "immo-ka":{"a":"#e23744","b":"#ff6b76","g1":"#2a0c10","g2":"#0d0a0b"},31 "food-ka":{"a":"#1f9d55","b":"#5fd08a","g1":"#07230f","g2":"#0a0d0b"},32 "fabri-ka":{"a":"#c4532e","b":"#e8895f","g1":"#241009","g2":"#0d0a09"},33 "auto-ka":{"a":"#ff5a2a","b":"#ff8f6b","g1":"#26100a","g2":"#0d0a09"},34 "vrai-prix":{"a":"#d9f26b","b":"#b8e04a","g1":"#16230a","g2":"#0b0d08"},35 "sorti-ka":{"a":"#d9f26b","b":"#ff8fd0","g1":"#210a1c","g2":"#0c090c"},36 "job-ka":{"a":"#d9f26b","b":"#7ab8ff","g1":"#0a1522","g2":"#080b0d"},37}38def pal(s): return PALETTES.get(s, PALETTES["vrai-prix"])3940def data_uri(url):41    try:42        req=urllib.request.Request(url, headers={"User-Agent":"Mozilla/5.0 (Macintosh)"})43        with urllib.request.urlopen(req, timeout=15, context=CTX) as r: raw=r.read()44        mime="image/jpeg"45        if url.lower().endswith(".png"): mime="image/png"46        elif url.lower().endswith(".webp"): mime="image/webp"47        return "data:"+mime+";base64,"+base64.b64encode(raw).decode()48    except Exception: return None4950def esc(s): return str(s).replace("&","&amp;").replace("<","&lt;").replace(">","&gt;")51def today(): t=datetime.date.today(); return f"{t.day} {MOIS[t.month-1]} {t.year}"52def parse_pct(h):53    m=re.match(r'^\+?(\d+(?:[.,]\d+)?)\s*%$', str(h or "").strip())54    return float(m.group(1).replace(",",".")) if m else None55NUMRE = re.compile(r'\d[\d\u00a0\u202f ,\.]*%?\$?')5657# ---------- scènes ----------58# chaque constructeur renvoie (html, css, dur, hook_js_ou_None)5960def sc_intro(ins,p,i):61    css="""62    #S .mid{flex:1;display:flex;flex-direction:column;justify-content:center}63    #S .kick{font-size:30px;font-weight:800;letter-spacing:.22em;color:__A__;text-transform:uppercase;opacity:0}64    .scene.on #S_ .kick{animation:fu .6s ease .15s forwards}65    #S .big{font-size:150px;font-weight:900;letter-spacing:-.03em;line-height:1;margin-top:26px;opacity:0;transform:scale(.8)}66    .scene.on #S_ .big{animation:zoomin .8s cubic-bezier(.2,1.2,.3,1) .35s forwards}67    #S .bar{width:0;height:10px;border-radius:6px;background:linear-gradient(90deg,__A__,__B__);margin-top:34px}68    .scene.on #S_ .bar{animation:grow .7s ease .8s forwards}69    #S .tag{font-size:42px;font-weight:600;color:#ffffffc8;margin-top:30px;max-width:880px;line-height:1.2;opacity:0}70    .scene.on #S_ .tag{animation:fu .7s ease 1.05s forwards}71    @keyframes zoomin{to{opacity:1;transform:scale(1)}}72    @keyframes grow{to{width:280px}}73    """74    html=('<div class="mid"><div class="kick">Le pouls du jour</div>'75        '<div class="big">'+esc(ins["label"])+'</div><div class="bar"></div>'76        + (('<div class="tag">'+esc(ins.get("tagline",""))+'</div>') if ins.get("tagline") else '')77        + '</div>')78    return html, css, 2.8, None7980def _num_parts(headline):81    """-> (int_digits, dec, suffix) pour le count-up ; None si non numérique."""82    hl=str(headline).strip()83    m=re.match(r'^\+?([\d\s  ]+)(?:[.,](\d+))?\s*(.*)$', hl)84    if not m: return None85    digits=re.sub(r'\D','',m.group(1))86    if not digits: return None87    return digits, (m.group(2) or ""), m.group(3) or ""8889def sc_stat(ins,p,i):90    parts=_num_parts(ins["headline"]); hl=str(ins["headline"])91    L=len(hl); fs=170 if L>=9 else (215 if L>=7 else 260)92    css="""93    #S .mid{flex:1;display:flex;flex-direction:column;justify-content:center}94    #S .lab0{font-size:34px;font-weight:800;letter-spacing:.14em;text-transform:uppercase;color:__A__;opacity:0}95    .scene.on #S_ .lab0{animation:fu .5s ease .1s forwards}96    #S .num{font-size:__FS__px;font-weight:900;line-height:.95;letter-spacing:-.03em;white-space:nowrap;margin-top:24px;97      background:linear-gradient(180deg,#fff,__A__ 135%);-webkit-background-clip:text;-webkit-text-fill-color:transparent;98      filter:drop-shadow(0 18px 55px __A__55);opacity:0;transform:translateY(36px)}99    .scene.on #S_ .num{animation:fu .7s cubic-bezier(.2,1,.3,1) .3s forwards}100    #S .lab{font-size:56px;font-weight:700;margin-top:30px;max-width:900px;line-height:1.14;opacity:0}101    .scene.on #S_ .lab{animation:fu .7s ease .8s forwards}102    """.replace("__FS__",str(fs))103    hook=None104    if parts and len(parts[0])>=3 and not parts[1]:105        hook="cuInt('S_num',"+parts[0]+","+json.dumps(" "+parts[2] if parts[2] else "")+",1500,400);"106    html=('<div class="mid"><div class="lab0">'+esc(ins["label"])+' · en direct</div>'107        '<div class="num" id="S_num">'+esc(hl)+'</div>'108        '<div class="lab">'+esc(ins["headline_label"])+'</div></div>')109    return html, css, 4.2, hook110111def sc_donut(ins,p,i):112    pct=parse_pct(ins["headline"]) or 0.0113    C=2*3.14159*300; off=C*(1-min(100.0,pct)/100.0)114    dec=1 if re.search(r'[.,]\d',str(ins["headline"])) else 0115    css="""116    #S .mid{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center}117    #S .dw{position:relative;width:740px;height:740px;opacity:0;transform:scale(.88)}118    .scene.on #S_ .dw{animation:zoomin .7s cubic-bezier(.2,1.2,.4,1) .15s forwards}119    #S .arc{stroke-dasharray:__C__;stroke-dashoffset:__C__}120    .scene.on #S_ .arc{animation:draw 1.7s cubic-bezier(.3,1,.4,1) .5s forwards}121    @keyframes draw{to{stroke-dashoffset:__OFF__}}122    @keyframes zoomin{to{opacity:1;transform:scale(1)}}123    #S .dp{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;font-size:145px;font-weight:900;color:__A__;letter-spacing:-.02em;filter:drop-shadow(0 10px 34px __A__55)}124    #S .dl{font-size:48px;font-weight:700;line-height:1.16;text-align:center;max-width:900px;margin-top:34px;opacity:0}125    .scene.on #S_ .dl{animation:fu .7s ease 1.2s forwards}126    """.replace("__C__",str(round(C,1))).replace("__OFF__",str(round(off,1)))127    svg=('<svg width="740" height="740" viewBox="0 0 760 760">'128      '<circle cx="380" cy="380" r="300" fill="none" stroke="rgba(255,255,255,.10)" stroke-width="82"/>'129      '<circle class="arc" cx="380" cy="380" r="300" fill="none" stroke="url(#gd'+str(i)+')" stroke-width="82" stroke-linecap="round" transform="rotate(-90 380 380)"/>'130      '<defs><linearGradient id="gd'+str(i)+'" x1="0" y1="0" x2="1" y2="1">'131      '<stop offset="0" stop-color="__A__"/><stop offset="1" stop-color="__B__"/></linearGradient></defs></svg>')132    html=('<div class="mid"><div class="dw">'+svg+'<div class="dp" id="S_dp">0 %</div></div>'133        '<div class="dl">'+esc(ins["headline_label"])+'</div></div>')134    hook="cuPct('S_dp',"+str(pct)+","+str(dec)+",1700,500);"135    return html, css, 4.4, hook136137def sc_tiles(ins,p,i):138    tiles=(ins.get("tiles") or [])[:3]139    rows=""140    for k,(v,l) in enumerate(tiles):141        rows+=('<div class="trow" style="transition-delay:.0s"><div class="tv" data-d="'+str(k)+'">'+esc(v)+'</div>'142               '<div class="tl">'+esc(l)+'</div></div>')143    css="""144    #S .mid{flex:1;display:flex;flex-direction:column;justify-content:center;gap:26px}145    #S .h{font-size:40px;font-weight:800;letter-spacing:.12em;text-transform:uppercase;color:__A__;opacity:0;margin-bottom:8px}146    .scene.on #S_ .h{animation:fu .5s ease .1s forwards}147    #S .trow{background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.15);border-radius:30px;148      padding:40px 44px;backdrop-filter:blur(6px);opacity:0;transform:translateX(-60px)}149    .scene.on #S_ .trow{animation:slidein .6s cubic-bezier(.2,.9,.3,1) forwards}150    .scene.on #S_ .trow:nth-child(2){animation-delay:.25s}151    .scene.on #S_ .trow:nth-child(3){animation-delay:.5s}152    .scene.on #S_ .trow:nth-child(4){animation-delay:.75s}153    @keyframes slidein{to{opacity:1;transform:none}}154    #S .tv{font-size:82px;font-weight:900;color:__A__;line-height:1;white-space:nowrap}155    #S .tl{font-size:34px;font-weight:600;color:#ffffffb0;margin-top:10px}156    """157    html='<div class="mid"><div class="h">En chiffres</div>'+rows+'</div>'158    return html, css, 3.6, None159160def sc_ranking(ins,p,i):161    bars=(ins.get("bars") or [])[:4]162    maxv=max([b[1] for b in bars] or [1])163    rows=""164    for k,b in enumerate(bars):165        w=max(10,int(100*b[1]/maxv))166        rows+=('<div class="rrow"><div class="rl"><span>'+esc(b[0])+'</span><span class="rv">'+esc(b[2])+'</span></div>'167            '<div class="tr2"><div class="fl" style="--w:'+str(w)+'%;animation-delay:'+str(round(0.35+k*0.28,2))+'s"></div></div></div>')168    css="""169    #S .mid{flex:1;display:flex;flex-direction:column;justify-content:center;gap:40px}170    #S .h{font-size:46px;font-weight:800;line-height:1.15;max-width:900px;opacity:0;margin-bottom:6px}171    .scene.on #S_ .h{animation:fu .5s ease .1s forwards}172    #S .rrow{opacity:0}173    .scene.on #S_ .rrow{animation:fu .5s ease forwards}174    .scene.on #S_ .rrow:nth-child(2){animation-delay:.2s}175    .scene.on #S_ .rrow:nth-child(3){animation-delay:.4s}176    .scene.on #S_ .rrow:nth-child(4){animation-delay:.6s}177    .scene.on #S_ .rrow:nth-child(5){animation-delay:.8s}178    #S .rl{display:flex;justify-content:space-between;align-items:baseline;margin-bottom:14px;font-size:40px;font-weight:700}179    #S .rv{font-weight:900;color:__A__;font-size:44px}180    #S .tr2{height:26px;border-radius:14px;background:rgba(255,255,255,.09);overflow:hidden}181    #S .fl{height:100%;width:0;border-radius:14px;background:linear-gradient(90deg,__A__,__B__);box-shadow:0 4px 18px __A__55}182    .scene.on #S_ .fl{animation:growb 1s cubic-bezier(.2,.9,.3,1) forwards}183    @keyframes growb{to{width:var(--w)}}184    """185    html='<div class="mid"><div class="h">'+esc(ins["headline_label"])+'</div>'+rows+'</div>'186    return html, css, 4.6, None187188def sc_photo(item,p,i,idx,total):189    img=item.get("image_data") or ""190    kb = "kbA" if idx%2==0 else "kbB"191    css="""192    #S{padding:0}193    #S .ph{position:absolute;inset:0;background:url('__IMG__') center/cover}194    .scene.on #S_ .ph{animation:__KB__ 3.4s ease-out forwards}195    @keyframes kbA{from{transform:scale(1)}to{transform:scale(1.14) translate(-1.5%,-1%)}}196    @keyframes kbB{from{transform:scale(1.14)}to{transform:scale(1) translate(1%,1%)}}197    #S .sc2{position:absolute;inset:0;background:linear-gradient(180deg,rgba(0,0,0,.25) 0%,transparent 30%,transparent 48%,__G2__e6 78%,__G2__ 92%)}198    #S .idx{position:absolute;top:200px;left:90px;background:__A__;color:#0d0d0d;font-weight:900;font-size:40px;199      padding:10px 26px;border-radius:16px;transform:rotate(-3deg) scale(.5);opacity:0}200    .scene.on #S_ .idx{animation:pop2 .5s cubic-bezier(.2,1.4,.4,1) .25s forwards}201    @keyframes pop2{to{opacity:1;transform:rotate(-3deg) scale(1)}}202    #S .inf{position:absolute;left:90px;right:90px;bottom:300px}203    #S .pt{font-size:64px;font-weight:900;line-height:1.05;letter-spacing:-.01em;text-shadow:0 4px 24px #000c;opacity:0;transform:translateY(30px)}204    .scene.on #S_ .pt{animation:fu .6s ease .35s forwards}205    #S .ps{font-size:34px;font-weight:600;color:#ffffffd0;margin-top:14px;opacity:0}206    .scene.on #S_ .ps{animation:fu .6s ease .55s forwards}207    #S .pp{font-size:84px;font-weight:900;color:__A__;margin-top:20px;letter-spacing:-.02em;filter:drop-shadow(0 8px 26px __A__66);opacity:0;transform:scale(.9)}208    .scene.on #S_ .pp{animation:popc2 .6s cubic-bezier(.2,1.3,.4,1) .75s forwards}209    @keyframes popc2{to{opacity:1;transform:scale(1)}}210    """.replace("__IMG__",img).replace("__KB__",kb)211    html=('<div class="ph"></div><div class="sc2"></div>'212        '<div class="idx">'+str(idx+1)+' / '+str(total)+'</div>'213        '<div class="inf"><div class="pt">'+esc(item.get("title",""))+'</div>'214        + (('<div class="ps">'+esc(item.get("subtitle",""))+'</div>') if item.get("subtitle") else '')215        + (('<div class="pp">'+esc(item.get("price",""))+'</div>') if item.get("price") else '')216        + '</div>')217    return html, css, 3.0, None218219def sc_quote(ins,p,i):220    fact=str(ins.get("fact") or "")221    words=fact.split()222    delay=min(0.11, 4.6/max(1,len(words)))223    spans=""224    for k,w in enumerate(words):225        cls="w hl" if NUMRE.search(w) else "w"226        spans+='<span class="'+cls+'" style="animation-delay:'+str(round(0.35+k*delay,2))+'s">'+esc(w)+'</span> '227    L=len(fact); fs=60 if L<170 else (53 if L<240 else 46)228    dur=min(6.0, 1.6+len(words)*delay+2.2)229    css="""230    #S .mid{flex:1;display:flex;flex-direction:column;justify-content:center}231    #S .qm{font-size:260px;line-height:.5;color:__A__;font-weight:900;font-family:Georgia,serif;height:140px;opacity:0}232    .scene.on #S_ .qm{animation:fu .5s ease .1s forwards}233    #S .qt{font-size:__FS__px;font-weight:800;line-height:1.35;letter-spacing:-.01em;max-width:920px}234    #S .w{display:inline-block;opacity:0;transform:translateY(24px)}235    .scene.on #S_ .w{animation:fu .45s ease forwards}236    #S .hl{color:__A__;filter:drop-shadow(0 6px 20px __A__44)}237    """.replace("__FS__",str(fs))238    html='<div class="mid"><div class="qm">“</div><div class="qt">'+spans+'</div></div>'239    return html, css, round(dur,1), None240241def sc_outro(ins,p,i):242    css="""243    #S .mid{flex:1;display:flex;flex-direction:column;justify-content:center;align-items:center;text-align:center}244    #S .kb2{background:__A__;color:#0d0d0d;font-weight:900;font-size:96px;padding:18px 46px;border-radius:32px;245      transform:rotate(-4deg) scale(.4);opacity:0;box-shadow:0 20px 60px __A__66}246    .scene.on #S_ .kb2{animation:pop3 .7s cubic-bezier(.2,1.4,.4,1) .15s forwards}247    @keyframes pop3{to{opacity:1;transform:rotate(-4deg) scale(1)}}248    #S .go{font-size:62px;font-weight:900;color:__A__;margin-top:60px;opacity:0}249    .scene.on #S_ .go{animation:fu .6s ease .7s forwards}250    #S .br{font-size:34px;font-weight:700;color:#ffffff8c;letter-spacing:.14em;margin-top:16px;opacity:0}251    .scene.on #S_ .br{animation:fu .6s ease .95s forwards}252    #S .sg{font-size:26px;color:#ffffff6a;font-weight:600;margin-top:56px;opacity:0}253    .scene.on #S_ .sg{animation:fu .6s ease 1.2s forwards}254    """255    html=('<div class="mid"><div class="kb2">KA</div>'256        '<div class="go">\U0001f449 www.'+ins["site"]+'.com</div>'257        '<div class="br">GROUPE ·KA</div>'258        '<div class="sg">✦ Rédigé et publié par l\'Agent KA</div></div>')259    return html, css, 3.2, None260261# ---------- plan des scènes ----------262def plan_scenes(ins,p):263    photos=[it for it in (ins.get("list") or []) if it.get("image_data")]264    if not photos and (ins.get("product") or {}).get("image_data"):265        pr=ins["product"]266        photos=[{"title":pr.get("title",""),"subtitle":pr.get("subtitle",""),267                 "price":pr.get("price",""),"image_data":pr["image_data"]}]268    has_pct=parse_pct(ins.get("headline")) is not None269    genre=ins.get("genre","hero")270    photo_led=genre in ("spotlight","list","grid") and photos271272    def stat_block():273        out=[]274        if has_pct: out.append(("donut",sc_donut))275        else: out.append(("stat",sc_stat))276        if ins.get("tiles"): out.append(("tiles",sc_tiles))277        if ins.get("bars") and len(ins["bars"])>=3: out.append(("ranking",sc_ranking))278        return out279    has_quote=len(str(ins.get("fact") or ""))>=40280281    # budget photos AVANT construction (les numéros « k / n » restent exacts) :282    # base ≈ intro 2.8 + stat/donut 4.3 + tuiles 3.6 + palmarès 4.6 + quote 4.5 + outro 3.2283    base_est=2.8+4.4+ (3.6 if ins.get("tiles") else 0) + (4.6 if (ins.get("bars") and len(ins["bars"])>=3) else 0) \284             + (4.5 if has_quote else 0) + 3.2285    maxp=4 if photo_led else 3286    nphotos=max(0,min(len(photos),maxp,int((34.0-base_est)//3.0)))287    tot_p=nphotos288    photo_scenes=[("photo%d"%k,(lambda it,k2: (lambda ins2,p2,i: sc_photo(it,p2,i,k2,tot_p)))(it,k))289                  for k,it in enumerate(photos[:nphotos])]290291    builders=[("intro",sc_intro)]292    if photo_led:293        builders+=photo_scenes+stat_block()294    else:295        builders+=stat_block()+photo_scenes296    if has_quote: builders.append(("quote",sc_quote))297    builders.append(("outro",sc_outro))298299    scenes=[]300    for i,(name,fn) in enumerate(builders):301        html,css,dur,hook=fn(ins,p,i)302        scenes.append(dict(name=name,html=html,css=css,dur=dur,hook=hook,i=i))303    return scenes304305# ---------- assemblage HTML ----------306def build_html(ins):307    p=pal(ins["site"])308    scenes=plan_scenes(ins,p)309    tot=round(sum(s["dur"] for s in scenes),2)310    shell="""311    *{margin:0;padding:0;box-sizing:border-box;-webkit-font-smoothing:antialiased}312    html,body{width:1080px;height:__H__px;overflow:hidden;font-family:__FONT__;color:#fff;background:__G2__}313    .stage{position:relative;width:1080px;height:__H__px;overflow:hidden;314      background:radial-gradient(1300px 900px at 78% -5%, __A__50,transparent 55%),315                 radial-gradient(1100px 1000px at -12% 105%, __B__36,transparent 55%),316                 linear-gradient(160deg,__G1__,__G2__);background-size:150% 150%;animation:drift 18s ease-in-out infinite alternate}317    @keyframes drift{0%{background-position:0% 0%}100%{background-position:100% 100%}}318    .vign{position:absolute;inset:0;pointer-events:none;background:radial-gradient(120% 90% at 50% 45%, transparent 55%, rgba(0,0,0,.5) 100%);z-index:3}319    .eyeb{position:absolute;top:104px;left:90px;right:250px;display:flex;align-items:center;gap:14px;font-weight:800;320      letter-spacing:.16em;font-size:25px;text-transform:uppercase;color:__A__;z-index:8;opacity:0;animation:fu .7s ease .2s forwards}321    .eyeb .dot{width:46px;height:6px;border-radius:3px;background:__A__;flex:0 0 46px}322    .kabadge{position:absolute;top:92px;right:90px;background:__A__;color:#0d0d0d;font-weight:900;font-size:48px;323      padding:10px 24px;border-radius:20px;transform:rotate(-4deg) scale(.4);opacity:0;z-index:8;324      animation:pop .7s cubic-bezier(.2,1.4,.4,1) .35s forwards;box-shadow:0 16px 46px __A__66}325    .wm{position:absolute;left:90px;bottom:96px;font-size:27px;font-weight:800;color:#ffffff9a;z-index:8}326    .wm b{color:__A__}327    .prog{position:absolute;left:0;bottom:0;height:9px;background:linear-gradient(90deg,__A__,__B__);width:0;z-index:9;328      animation:prog __TOT__s linear .1s forwards;box-shadow:0 0 20px __A__}329    @keyframes prog{to{width:100%}}330    @keyframes fu{to{opacity:1;transform:translateY(0)}}331    @keyframes pop{to{opacity:1;transform:rotate(-4deg) scale(1)}}332    .scene{position:absolute;inset:0;padding:220px 90px 210px;display:flex;flex-direction:column;z-index:4;333      opacity:0;pointer-events:none;transform:translateY(46px) scale(.985);334      transition:opacity .5s ease,transform .62s cubic-bezier(.2,.8,.2,1)}335    .scene.on{opacity:1;transform:none}336    .scene.off{opacity:0;transform:translateY(-46px) scale(1.012)}337    .fadeout{position:absolute;inset:0;background:#000;opacity:0;z-index:20;pointer-events:none;338      animation:fo .7s ease __FOT__s forwards}339    @keyframes fo{to{opacity:1}}340    """341    shell=(shell.replace("__H__",str(H)).replace("__FONT__",FONT).replace("__A__",p["a"])342        .replace("__B__",p["b"]).replace("__G1__",p["g1"]).replace("__G2__",p["g2"])343        .replace("__TOT__",str(tot)).replace("__FOT__",str(round(tot-0.7,2))))344345    css_all=[shell]; body=[]; sc_list=[]; hooks={}346    for s in scenes:347        sid="sc"+str(s["i"])348        css=(s["css"].replace(".scene.on #S_","#"+sid+".on").replace("#S_","#"+sid).replace("#S","#"+sid)349             .replace("__A__",p["a"]).replace("__B__",p["b"]).replace("__G2__",p["g2"]))350        # les hooks référencent des ids préfixés S_ -> remplacer par l'id de scène351        html=s["html"].replace('id="S_','id="'+sid+'_')352        hook=(s["hook"] or "").replace("'S_","'"+sid+"_")353        css_all.append(css)354        body.append('<div class="scene" id="'+sid+'">'+html+'</div>')355        sc_list.append([sid, s["dur"]])356        if hook: hooks[sid]=hook357358    hooks_js="{"+",".join('"'+k+'":function(){'+v+'}' for k,v in hooks.items())+"}"359    script="""<script>360    function fmtInt(n){return n.toLocaleString('fr-CA').replace(/[\\u00a0\\u202f,]/g,' ')}361    function cuInt(id,target,suffix,dur,begin){var el=document.getElementById(id);if(!el)return;var s=null;362      function st(ts){if(!s)s=ts;var t=ts-s;if(t<begin){requestAnimationFrame(st);return}363        var k=Math.min(1,(t-begin)/dur);var e=1-Math.pow(1-k,3);364        el.textContent=fmtInt(Math.round(target*e))+suffix;if(k<1)requestAnimationFrame(st)}365      el.textContent=fmtInt(0)+suffix;requestAnimationFrame(st)}366    function cuPct(id,pct,dec,dur,begin){var el=document.getElementById(id);if(!el)return;var s=null;367      function f(n){return n.toFixed(dec).replace('.',',')+' %'}368      function st(ts){if(!s)s=ts;var t=ts-s;if(t<begin){requestAnimationFrame(st);return}369        var k=Math.min(1,(t-begin)/dur);var e=1-Math.pow(1-k,3);370        el.textContent=f(pct*e);if(k<1)requestAnimationFrame(st)}371      requestAnimationFrame(st)}372    var SCENES=__SC__;373    var HOOKS=__HOOKS__;374    (function(){var t=200;375      SCENES.forEach(function(s){376        setTimeout(function(){377          document.querySelectorAll('.scene.on').forEach(function(el){el.classList.remove('on');el.classList.add('off')});378          var el=document.getElementById(s[0]);el.classList.remove('off');el.classList.add('on');379          if(HOOKS[s[0]])try{HOOKS[s[0]]()}catch(e){}380        },t);381        t+=s[1]*1000;382      });383    })();384    </script>""".replace("__SC__",json.dumps(sc_list)).replace("__HOOKS__",hooks_js)385386    eyeb='<div class="eyeb"><span class="dot"></span>'+esc(ins["label"].upper())+' · '+today().upper()+'</div>'387    wm='<div class="wm"><b>www.'+ins["site"]+'.com</b> · Agent KA</div>'388    html=("<!doctype html><html><head><meta charset=\"utf-8\"><style>"+"\n".join(css_all)+"</style></head><body>"389        '<div class="stage">'+eyeb+'<div class="kabadge">KA</div>'+"".join(body)390        +wm+'<div class="prog"></div><div class="vign"></div><div class="fadeout"></div></div>'+script+"</body></html>")391    return html, tot392393# ---------- enregistrement + musique + mux ----------394def record_webm(html_path, out_webm, tmpdir, dur):395    from playwright.sync_api import sync_playwright396    with sync_playwright() as pw:397        b=pw.chromium.launch(args=["--no-sandbox"])398        ctx=b.new_context(viewport={"width":1080,"height":H}, device_scale_factor=2,399                          record_video_dir=tmpdir, record_video_size={"width":1080,"height":H})400        pg=ctx.new_page()401        pg.goto("file://"+html_path)402        pg.wait_for_timeout(int((dur+0.3)*1000))403        vid=pg.video404        ctx.close(); b.close()405        path=vid.path()406    os.replace(path, out_webm)407408def render(ins, out_dir):409    os.makedirs(out_dir,exist_ok=True)410    prod=ins.get('product')411    if prod and prod.get('image') and not prod.get('image_data'):412        du=data_uri(prod['image'])413        if du: prod['image_data']=du414    for it in (ins.get('list') or []):415        if it.get('image') and not it.get('image_data'):416            du=data_uri(it['image'])417            if du: it['image_data']=du418419    key=hashlib.md5((ins['site']+str(ins.get('insight_id',''))+str(ins.get('genre',''))+'reelv4').encode()).hexdigest()[:8]420    tmp=os.path.join(out_dir,"_reeltmp_"+key); os.makedirs(tmp,exist_ok=True)421    html,dur=build_html(ins)422    html_path=os.path.join(tmp,"reel.html"); open(html_path,"w",encoding="utf-8").write(html)423    webm=os.path.join(tmp,"reel.webm"); record_webm(html_path,webm,tmp,dur)424425    # musique : style en rotation via variant, contenu par graine (unique)426    variant=ins.get('variant')427    seed=ins['site']+"|"+str(ins.get('insight_id',''))+"|"+str(variant)+"|"+datetime.date.today().isoformat()428    style=STYLES_ORDER[int(variant)%len(STYLES_ORDER)] if variant is not None else None429    wav=os.path.join(tmp,"bed.wav")430    used=music_engine.compose(dur+0.2, seed, wav, style)431    sys.stderr.write("musique: style=%s seed=%s dur=%.1fs\n"%(used,seed,dur))432433    out=os.path.join(out_dir,f"reel-{ins['site']}-{ins.get('insight_id','x')}.mp4")434    subprocess.run([FFMPEG,"-y","-i",webm,"-i",wav,435        "-filter_complex","[0:v]scale=1080:"+str(H)+":force_original_aspect_ratio=increase,crop=1080:"+str(H)+",fps=30,format=yuv420p[v];"436        "[1:a]acompressor=threshold=-16dB:ratio=3:attack=8:release=180,alimiter=limit=0.95[a]",437        "-map","[v]","-map","[a]","-c:v","libx264","-preset","slow","-crf","18",438        "-c:a","aac","-b:a","192k","-pix_fmt","yuv420p","-movflags","+faststart","-shortest",out],439        capture_output=True)440    for f in glob.glob(os.path.join(tmp,"*")):441        try: os.remove(f)442        except: pass443    try: os.rmdir(tmp)444    except: pass445    if not os.path.exists(out): raise SystemExit("mp4 non produit")446    return out447448if __name__=="__main__":449    ins=json.load(sys.stdin)450    out_dir=sys.argv[1] if len(sys.argv)>1 else "/tmp/ka-reels"451    print(render(ins,out_dir))452