#!/usr/bin/env python3 """Reel KA v4 — mini-clip vertical MULTI-SCÈNES (1080x1920) + musique procédurale. Le reel n'est plus une seule carte animée de 10 s : c'est une séquence de scènes (~20-32 s) qui couvre plusieurs facettes de l'insight : intro → stat géante (count-up) / donut % → tuiles chiffres → palmarès animé → photos réelles (Ken Burns) → « le saviez-vous » → outro CTA. Les scènes disponibles dépendent des données (tiles/bars/list/product/fact). Musique : music_engine.py (6 styles, mélodie/progression/tonalité par graine) — deux reels n'ont jamais la même musique. Style en rotation via `variant`. Pipeline : HTML animé -> Playwright (Chromium, enregistrement vidéo) -> ffmpeg. Sortie : chemin du mp4 sur stdout. Env : KA_REEL_H (défaut 1920). """ import json, sys, os, re, base64, datetime, urllib.request, ssl, subprocess, glob, hashlib sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import music_engine CTX = ssl.create_default_context(); CTX.check_hostname=False; CTX.verify_mode=ssl.CERT_NONE FFMPEG = "/opt/homebrew/bin/ffmpeg" MOIS=["janvier","février","mars","avril","mai","juin","juillet","août","septembre","octobre","novembre","décembre"] FONT="'Avenir Next','SF Pro Display','Helvetica Neue',Helvetica,Arial,sans-serif" H=int(os.environ.get("KA_REEL_H","1920")) STYLES_ORDER=["house","synthwave","lofi","funk","epic","trap"] PALETTES={ "lou-ka":{"a":"#ff6a00","b":"#ff9d4d","g1":"#2a1403","g2":"#0d0b09"}, "immo-ka":{"a":"#e23744","b":"#ff6b76","g1":"#2a0c10","g2":"#0d0a0b"}, "food-ka":{"a":"#1f9d55","b":"#5fd08a","g1":"#07230f","g2":"#0a0d0b"}, "fabri-ka":{"a":"#c4532e","b":"#e8895f","g1":"#241009","g2":"#0d0a09"}, "auto-ka":{"a":"#ff5a2a","b":"#ff8f6b","g1":"#26100a","g2":"#0d0a09"}, "vrai-prix":{"a":"#d9f26b","b":"#b8e04a","g1":"#16230a","g2":"#0b0d08"}, "sorti-ka":{"a":"#d9f26b","b":"#ff8fd0","g1":"#210a1c","g2":"#0c090c"}, "job-ka":{"a":"#d9f26b","b":"#7ab8ff","g1":"#0a1522","g2":"#080b0d"}, } def pal(s): return PALETTES.get(s, PALETTES["vrai-prix"]) def data_uri(url): try: req=urllib.request.Request(url, headers={"User-Agent":"Mozilla/5.0 (Macintosh)"}) with urllib.request.urlopen(req, timeout=15, context=CTX) as r: raw=r.read() mime="image/jpeg" if url.lower().endswith(".png"): mime="image/png" elif url.lower().endswith(".webp"): mime="image/webp" return "data:"+mime+";base64,"+base64.b64encode(raw).decode() except Exception: return None def esc(s): return str(s).replace("&","&").replace("<","<").replace(">",">") def today(): t=datetime.date.today(); return f"{t.day} {MOIS[t.month-1]} {t.year}" def parse_pct(h): m=re.match(r'^\+?(\d+(?:[.,]\d+)?)\s*%$', str(h or "").strip()) return float(m.group(1).replace(",",".")) if m else None NUMRE = re.compile(r'\d[\d\u00a0\u202f ,\.]*%?\$?') # ---------- scènes ---------- # chaque constructeur renvoie (html, css, dur, hook_js_ou_None) def sc_intro(ins,p,i): css=""" #S .mid{flex:1;display:flex;flex-direction:column;justify-content:center} #S .kick{font-size:30px;font-weight:800;letter-spacing:.22em;color:__A__;text-transform:uppercase;opacity:0} .scene.on #S_ .kick{animation:fu .6s ease .15s forwards} #S .big{font-size:150px;font-weight:900;letter-spacing:-.03em;line-height:1;margin-top:26px;opacity:0;transform:scale(.8)} .scene.on #S_ .big{animation:zoomin .8s cubic-bezier(.2,1.2,.3,1) .35s forwards} #S .bar{width:0;height:10px;border-radius:6px;background:linear-gradient(90deg,__A__,__B__);margin-top:34px} .scene.on #S_ .bar{animation:grow .7s ease .8s forwards} #S .tag{font-size:42px;font-weight:600;color:#ffffffc8;margin-top:30px;max-width:880px;line-height:1.2;opacity:0} .scene.on #S_ .tag{animation:fu .7s ease 1.05s forwards} @keyframes zoomin{to{opacity:1;transform:scale(1)}} @keyframes grow{to{width:280px}} """ html=('
Le pouls du jour
' '
'+esc(ins["label"])+'
' + (('
'+esc(ins.get("tagline",""))+'
') if ins.get("tagline") else '') + '
') return html, css, 2.8, None def _num_parts(headline): """-> (int_digits, dec, suffix) pour le count-up ; None si non numérique.""" hl=str(headline).strip() m=re.match(r'^\+?([\d\s  ]+)(?:[.,](\d+))?\s*(.*)$', hl) if not m: return None digits=re.sub(r'\D','',m.group(1)) if not digits: return None return digits, (m.group(2) or ""), m.group(3) or "" def sc_stat(ins,p,i): parts=_num_parts(ins["headline"]); hl=str(ins["headline"]) L=len(hl); fs=170 if L>=9 else (215 if L>=7 else 260) css=""" #S .mid{flex:1;display:flex;flex-direction:column;justify-content:center} #S .lab0{font-size:34px;font-weight:800;letter-spacing:.14em;text-transform:uppercase;color:__A__;opacity:0} .scene.on #S_ .lab0{animation:fu .5s ease .1s forwards} #S .num{font-size:__FS__px;font-weight:900;line-height:.95;letter-spacing:-.03em;white-space:nowrap;margin-top:24px; background:linear-gradient(180deg,#fff,__A__ 135%);-webkit-background-clip:text;-webkit-text-fill-color:transparent; filter:drop-shadow(0 18px 55px __A__55);opacity:0;transform:translateY(36px)} .scene.on #S_ .num{animation:fu .7s cubic-bezier(.2,1,.3,1) .3s forwards} #S .lab{font-size:56px;font-weight:700;margin-top:30px;max-width:900px;line-height:1.14;opacity:0} .scene.on #S_ .lab{animation:fu .7s ease .8s forwards} """.replace("__FS__",str(fs)) hook=None if parts and len(parts[0])>=3 and not parts[1]: hook="cuInt('S_num',"+parts[0]+","+json.dumps(" "+parts[2] if parts[2] else "")+",1500,400);" html=('
'+esc(ins["label"])+' · en direct
' '
'+esc(hl)+'
' '
'+esc(ins["headline_label"])+'
') return html, css, 4.2, hook def sc_donut(ins,p,i): pct=parse_pct(ins["headline"]) or 0.0 C=2*3.14159*300; off=C*(1-min(100.0,pct)/100.0) dec=1 if re.search(r'[.,]\d',str(ins["headline"])) else 0 css=""" #S .mid{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center} #S .dw{position:relative;width:740px;height:740px;opacity:0;transform:scale(.88)} .scene.on #S_ .dw{animation:zoomin .7s cubic-bezier(.2,1.2,.4,1) .15s forwards} #S .arc{stroke-dasharray:__C__;stroke-dashoffset:__C__} .scene.on #S_ .arc{animation:draw 1.7s cubic-bezier(.3,1,.4,1) .5s forwards} @keyframes draw{to{stroke-dashoffset:__OFF__}} @keyframes zoomin{to{opacity:1;transform:scale(1)}} #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)} #S .dl{font-size:48px;font-weight:700;line-height:1.16;text-align:center;max-width:900px;margin-top:34px;opacity:0} .scene.on #S_ .dl{animation:fu .7s ease 1.2s forwards} """.replace("__C__",str(round(C,1))).replace("__OFF__",str(round(off,1))) svg=('' '' '' '' '') html=('
'+svg+'
0 %
' '
'+esc(ins["headline_label"])+'
') hook="cuPct('S_dp',"+str(pct)+","+str(dec)+",1700,500);" return html, css, 4.4, hook def sc_tiles(ins,p,i): tiles=(ins.get("tiles") or [])[:3] rows="" for k,(v,l) in enumerate(tiles): rows+=('
'+esc(v)+'
' '
'+esc(l)+'
') css=""" #S .mid{flex:1;display:flex;flex-direction:column;justify-content:center;gap:26px} #S .h{font-size:40px;font-weight:800;letter-spacing:.12em;text-transform:uppercase;color:__A__;opacity:0;margin-bottom:8px} .scene.on #S_ .h{animation:fu .5s ease .1s forwards} #S .trow{background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.15);border-radius:30px; padding:40px 44px;backdrop-filter:blur(6px);opacity:0;transform:translateX(-60px)} .scene.on #S_ .trow{animation:slidein .6s cubic-bezier(.2,.9,.3,1) forwards} .scene.on #S_ .trow:nth-child(2){animation-delay:.25s} .scene.on #S_ .trow:nth-child(3){animation-delay:.5s} .scene.on #S_ .trow:nth-child(4){animation-delay:.75s} @keyframes slidein{to{opacity:1;transform:none}} #S .tv{font-size:82px;font-weight:900;color:__A__;line-height:1;white-space:nowrap} #S .tl{font-size:34px;font-weight:600;color:#ffffffb0;margin-top:10px} """ html='
En chiffres
'+rows+'
' return html, css, 3.6, None def sc_ranking(ins,p,i): bars=(ins.get("bars") or [])[:4] maxv=max([b[1] for b in bars] or [1]) rows="" for k,b in enumerate(bars): w=max(10,int(100*b[1]/maxv)) rows+=('
'+esc(b[0])+''+esc(b[2])+'
' '
') css=""" #S .mid{flex:1;display:flex;flex-direction:column;justify-content:center;gap:40px} #S .h{font-size:46px;font-weight:800;line-height:1.15;max-width:900px;opacity:0;margin-bottom:6px} .scene.on #S_ .h{animation:fu .5s ease .1s forwards} #S .rrow{opacity:0} .scene.on #S_ .rrow{animation:fu .5s ease forwards} .scene.on #S_ .rrow:nth-child(2){animation-delay:.2s} .scene.on #S_ .rrow:nth-child(3){animation-delay:.4s} .scene.on #S_ .rrow:nth-child(4){animation-delay:.6s} .scene.on #S_ .rrow:nth-child(5){animation-delay:.8s} #S .rl{display:flex;justify-content:space-between;align-items:baseline;margin-bottom:14px;font-size:40px;font-weight:700} #S .rv{font-weight:900;color:__A__;font-size:44px} #S .tr2{height:26px;border-radius:14px;background:rgba(255,255,255,.09);overflow:hidden} #S .fl{height:100%;width:0;border-radius:14px;background:linear-gradient(90deg,__A__,__B__);box-shadow:0 4px 18px __A__55} .scene.on #S_ .fl{animation:growb 1s cubic-bezier(.2,.9,.3,1) forwards} @keyframes growb{to{width:var(--w)}} """ html='
'+esc(ins["headline_label"])+'
'+rows+'
' return html, css, 4.6, None def sc_photo(item,p,i,idx,total): img=item.get("image_data") or "" kb = "kbA" if idx%2==0 else "kbB" css=""" #S{padding:0} #S .ph{position:absolute;inset:0;background:url('__IMG__') center/cover} .scene.on #S_ .ph{animation:__KB__ 3.4s ease-out forwards} @keyframes kbA{from{transform:scale(1)}to{transform:scale(1.14) translate(-1.5%,-1%)}} @keyframes kbB{from{transform:scale(1.14)}to{transform:scale(1) translate(1%,1%)}} #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%)} #S .idx{position:absolute;top:200px;left:90px;background:__A__;color:#0d0d0d;font-weight:900;font-size:40px; padding:10px 26px;border-radius:16px;transform:rotate(-3deg) scale(.5);opacity:0} .scene.on #S_ .idx{animation:pop2 .5s cubic-bezier(.2,1.4,.4,1) .25s forwards} @keyframes pop2{to{opacity:1;transform:rotate(-3deg) scale(1)}} #S .inf{position:absolute;left:90px;right:90px;bottom:300px} #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)} .scene.on #S_ .pt{animation:fu .6s ease .35s forwards} #S .ps{font-size:34px;font-weight:600;color:#ffffffd0;margin-top:14px;opacity:0} .scene.on #S_ .ps{animation:fu .6s ease .55s forwards} #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)} .scene.on #S_ .pp{animation:popc2 .6s cubic-bezier(.2,1.3,.4,1) .75s forwards} @keyframes popc2{to{opacity:1;transform:scale(1)}} """.replace("__IMG__",img).replace("__KB__",kb) html=('
' '
'+str(idx+1)+' / '+str(total)+'
' '
'+esc(item.get("title",""))+'
' + (('
'+esc(item.get("subtitle",""))+'
') if item.get("subtitle") else '') + (('
'+esc(item.get("price",""))+'
') if item.get("price") else '') + '
') return html, css, 3.0, None def sc_quote(ins,p,i): fact=str(ins.get("fact") or "") words=fact.split() delay=min(0.11, 4.6/max(1,len(words))) spans="" for k,w in enumerate(words): cls="w hl" if NUMRE.search(w) else "w" spans+=''+esc(w)+' ' L=len(fact); fs=60 if L<170 else (53 if L<240 else 46) dur=min(6.0, 1.6+len(words)*delay+2.2) css=""" #S .mid{flex:1;display:flex;flex-direction:column;justify-content:center} #S .qm{font-size:260px;line-height:.5;color:__A__;font-weight:900;font-family:Georgia,serif;height:140px;opacity:0} .scene.on #S_ .qm{animation:fu .5s ease .1s forwards} #S .qt{font-size:__FS__px;font-weight:800;line-height:1.35;letter-spacing:-.01em;max-width:920px} #S .w{display:inline-block;opacity:0;transform:translateY(24px)} .scene.on #S_ .w{animation:fu .45s ease forwards} #S .hl{color:__A__;filter:drop-shadow(0 6px 20px __A__44)} """.replace("__FS__",str(fs)) html='
“
'+spans+'
' return html, css, round(dur,1), None def sc_outro(ins,p,i): css=""" #S .mid{flex:1;display:flex;flex-direction:column;justify-content:center;align-items:center;text-align:center} #S .kb2{background:__A__;color:#0d0d0d;font-weight:900;font-size:96px;padding:18px 46px;border-radius:32px; transform:rotate(-4deg) scale(.4);opacity:0;box-shadow:0 20px 60px __A__66} .scene.on #S_ .kb2{animation:pop3 .7s cubic-bezier(.2,1.4,.4,1) .15s forwards} @keyframes pop3{to{opacity:1;transform:rotate(-4deg) scale(1)}} #S .go{font-size:62px;font-weight:900;color:__A__;margin-top:60px;opacity:0} .scene.on #S_ .go{animation:fu .6s ease .7s forwards} #S .br{font-size:34px;font-weight:700;color:#ffffff8c;letter-spacing:.14em;margin-top:16px;opacity:0} .scene.on #S_ .br{animation:fu .6s ease .95s forwards} #S .sg{font-size:26px;color:#ffffff6a;font-weight:600;margin-top:56px;opacity:0} .scene.on #S_ .sg{animation:fu .6s ease 1.2s forwards} """ html=('
KA
' '
\U0001f449 www.'+ins["site"]+'.com
' '
GROUPE ·KA
' '
✦ Rédigé et publié par l\'Agent KA
') return html, css, 3.2, None # ---------- plan des scènes ---------- def plan_scenes(ins,p): photos=[it for it in (ins.get("list") or []) if it.get("image_data")] if not photos and (ins.get("product") or {}).get("image_data"): pr=ins["product"] photos=[{"title":pr.get("title",""),"subtitle":pr.get("subtitle",""), "price":pr.get("price",""),"image_data":pr["image_data"]}] has_pct=parse_pct(ins.get("headline")) is not None genre=ins.get("genre","hero") photo_led=genre in ("spotlight","list","grid") and photos def stat_block(): out=[] if has_pct: out.append(("donut",sc_donut)) else: out.append(("stat",sc_stat)) if ins.get("tiles"): out.append(("tiles",sc_tiles)) if ins.get("bars") and len(ins["bars"])>=3: out.append(("ranking",sc_ranking)) return out has_quote=len(str(ins.get("fact") or ""))>=40 # budget photos AVANT construction (les numéros « k / n » restent exacts) : # base ≈ intro 2.8 + stat/donut 4.3 + tuiles 3.6 + palmarès 4.6 + quote 4.5 + outro 3.2 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) \ + (4.5 if has_quote else 0) + 3.2 maxp=4 if photo_led else 3 nphotos=max(0,min(len(photos),maxp,int((34.0-base_est)//3.0))) tot_p=nphotos photo_scenes=[("photo%d"%k,(lambda it,k2: (lambda ins2,p2,i: sc_photo(it,p2,i,k2,tot_p)))(it,k)) for k,it in enumerate(photos[:nphotos])] builders=[("intro",sc_intro)] if photo_led: builders+=photo_scenes+stat_block() else: builders+=stat_block()+photo_scenes if has_quote: builders.append(("quote",sc_quote)) builders.append(("outro",sc_outro)) scenes=[] for i,(name,fn) in enumerate(builders): html,css,dur,hook=fn(ins,p,i) scenes.append(dict(name=name,html=html,css=css,dur=dur,hook=hook,i=i)) return scenes # ---------- assemblage HTML ---------- def build_html(ins): p=pal(ins["site"]) scenes=plan_scenes(ins,p) tot=round(sum(s["dur"] for s in scenes),2) shell=""" *{margin:0;padding:0;box-sizing:border-box;-webkit-font-smoothing:antialiased} html,body{width:1080px;height:__H__px;overflow:hidden;font-family:__FONT__;color:#fff;background:__G2__} .stage{position:relative;width:1080px;height:__H__px;overflow:hidden; background:radial-gradient(1300px 900px at 78% -5%, __A__50,transparent 55%), radial-gradient(1100px 1000px at -12% 105%, __B__36,transparent 55%), linear-gradient(160deg,__G1__,__G2__);background-size:150% 150%;animation:drift 18s ease-in-out infinite alternate} @keyframes drift{0%{background-position:0% 0%}100%{background-position:100% 100%}} .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} .eyeb{position:absolute;top:104px;left:90px;right:250px;display:flex;align-items:center;gap:14px;font-weight:800; letter-spacing:.16em;font-size:25px;text-transform:uppercase;color:__A__;z-index:8;opacity:0;animation:fu .7s ease .2s forwards} .eyeb .dot{width:46px;height:6px;border-radius:3px;background:__A__;flex:0 0 46px} .kabadge{position:absolute;top:92px;right:90px;background:__A__;color:#0d0d0d;font-weight:900;font-size:48px; padding:10px 24px;border-radius:20px;transform:rotate(-4deg) scale(.4);opacity:0;z-index:8; animation:pop .7s cubic-bezier(.2,1.4,.4,1) .35s forwards;box-shadow:0 16px 46px __A__66} .wm{position:absolute;left:90px;bottom:96px;font-size:27px;font-weight:800;color:#ffffff9a;z-index:8} .wm b{color:__A__} .prog{position:absolute;left:0;bottom:0;height:9px;background:linear-gradient(90deg,__A__,__B__);width:0;z-index:9; animation:prog __TOT__s linear .1s forwards;box-shadow:0 0 20px __A__} @keyframes prog{to{width:100%}} @keyframes fu{to{opacity:1;transform:translateY(0)}} @keyframes pop{to{opacity:1;transform:rotate(-4deg) scale(1)}} .scene{position:absolute;inset:0;padding:220px 90px 210px;display:flex;flex-direction:column;z-index:4; opacity:0;pointer-events:none;transform:translateY(46px) scale(.985); transition:opacity .5s ease,transform .62s cubic-bezier(.2,.8,.2,1)} .scene.on{opacity:1;transform:none} .scene.off{opacity:0;transform:translateY(-46px) scale(1.012)} .fadeout{position:absolute;inset:0;background:#000;opacity:0;z-index:20;pointer-events:none; animation:fo .7s ease __FOT__s forwards} @keyframes fo{to{opacity:1}} """ shell=(shell.replace("__H__",str(H)).replace("__FONT__",FONT).replace("__A__",p["a"]) .replace("__B__",p["b"]).replace("__G1__",p["g1"]).replace("__G2__",p["g2"]) .replace("__TOT__",str(tot)).replace("__FOT__",str(round(tot-0.7,2)))) css_all=[shell]; body=[]; sc_list=[]; hooks={} for s in scenes: sid="sc"+str(s["i"]) css=(s["css"].replace(".scene.on #S_","#"+sid+".on").replace("#S_","#"+sid).replace("#S","#"+sid) .replace("__A__",p["a"]).replace("__B__",p["b"]).replace("__G2__",p["g2"])) # les hooks référencent des ids préfixés S_ -> remplacer par l'id de scène html=s["html"].replace('id="S_','id="'+sid+'_') hook=(s["hook"] or "").replace("'S_","'"+sid+"_") css_all.append(css) body.append('
'+html+'
') sc_list.append([sid, s["dur"]]) if hook: hooks[sid]=hook hooks_js="{"+",".join('"'+k+'":function(){'+v+'}' for k,v in hooks.items())+"}" script="""""".replace("__SC__",json.dumps(sc_list)).replace("__HOOKS__",hooks_js) eyeb='
'+esc(ins["label"].upper())+' · '+today().upper()+'
' wm='
www.'+ins["site"]+'.com · Agent KA
' html=("" '
'+eyeb+'
KA
'+"".join(body) +wm+'
'+script+"") return html, tot # ---------- enregistrement + musique + mux ---------- def record_webm(html_path, out_webm, tmpdir, dur): from playwright.sync_api import sync_playwright with sync_playwright() as pw: b=pw.chromium.launch(args=["--no-sandbox"]) ctx=b.new_context(viewport={"width":1080,"height":H}, device_scale_factor=2, record_video_dir=tmpdir, record_video_size={"width":1080,"height":H}) pg=ctx.new_page() pg.goto("file://"+html_path) pg.wait_for_timeout(int((dur+0.3)*1000)) vid=pg.video ctx.close(); b.close() path=vid.path() os.replace(path, out_webm) def render(ins, out_dir): os.makedirs(out_dir,exist_ok=True) prod=ins.get('product') if prod and prod.get('image') and not prod.get('image_data'): du=data_uri(prod['image']) if du: prod['image_data']=du for it in (ins.get('list') or []): if it.get('image') and not it.get('image_data'): du=data_uri(it['image']) if du: it['image_data']=du key=hashlib.md5((ins['site']+str(ins.get('insight_id',''))+str(ins.get('genre',''))+'reelv4').encode()).hexdigest()[:8] tmp=os.path.join(out_dir,"_reeltmp_"+key); os.makedirs(tmp,exist_ok=True) html,dur=build_html(ins) html_path=os.path.join(tmp,"reel.html"); open(html_path,"w",encoding="utf-8").write(html) webm=os.path.join(tmp,"reel.webm"); record_webm(html_path,webm,tmp,dur) # musique : style en rotation via variant, contenu par graine (unique) variant=ins.get('variant') seed=ins['site']+"|"+str(ins.get('insight_id',''))+"|"+str(variant)+"|"+datetime.date.today().isoformat() style=STYLES_ORDER[int(variant)%len(STYLES_ORDER)] if variant is not None else None wav=os.path.join(tmp,"bed.wav") used=music_engine.compose(dur+0.2, seed, wav, style) sys.stderr.write("musique: style=%s seed=%s dur=%.1fs\n"%(used,seed,dur)) out=os.path.join(out_dir,f"reel-{ins['site']}-{ins.get('insight_id','x')}.mp4") subprocess.run([FFMPEG,"-y","-i",webm,"-i",wav, "-filter_complex","[0:v]scale=1080:"+str(H)+":force_original_aspect_ratio=increase,crop=1080:"+str(H)+",fps=30,format=yuv420p[v];" "[1:a]acompressor=threshold=-16dB:ratio=3:attack=8:release=180,alimiter=limit=0.95[a]", "-map","[v]","-map","[a]","-c:v","libx264","-preset","slow","-crf","18", "-c:a","aac","-b:a","192k","-pix_fmt","yuv420p","-movflags","+faststart","-shortest",out], capture_output=True) for f in glob.glob(os.path.join(tmp,"*")): try: os.remove(f) except: pass try: os.rmdir(tmp) except: pass if not os.path.exists(out): raise SystemExit("mp4 non produit") return out if __name__=="__main__": ins=json.load(sys.stdin) out_dir=sys.argv[1] if len(sys.argv)>1 else "/tmp/ka-reels" print(render(ins,out_dir))