Animation · project 36 of 37

Energy after a stroke.

A one-minute narrated short on tiredness after a stroke, and five ways to get more energy, in English and in Persian.

Open the project ↗Get the skill and the code
After: A one-minute short with the main advice, narrated and captioned in English and in Persian, on one page. Before: A twelve-minute English video on tiredness after a stroke, and a family where not everyone is at home in English.

BeforeA twelve-minute English video on tiredness after a stroke, and a family where not everyone is at home in English.

AfterA one-minute short with the main advice, narrated and captioned in English and in Persian, on one page.

What it is worthThe five ways in a minute, in the language each person hears best, easy to pass on. Instead of long videos, one language, advice nobody remembers.

More like this: explain hard things in a minute ›

How to use it

  1. Pick English or فارسی at the top. The page remembers your choice, and links ending in #en or #fa open that version.
  2. Turn the sound on and press play. It plays even when an iPhone is on silent, and every sentence is also on screen.
  3. Read the five ways in short under the film, or download the MP4 to send it in a family chat.
  4. Talk to your doctor or therapist before you start any new exercise routine.

Where it helps most

  • Sharing with a family after a stroke, including relatives who are more at home in Persian.
  • A one-minute reminder for a survivor or caregiver of how to pace the day.
  • A pattern for turning any long health or how-to video into a short, captioned film in two languages.

The idea

A close relative of mine had a stroke recently, and this idea came from there. I found a clear video on post-stroke fatigue, but it was twelve minutes long and only in English. I wanted the main advice in one short clip our family could watch together and pass on, in English and in Persian.

The build

Claude read the source video's transcript (Post Stroke channel on YouTube), summarized it into eight short scenes in its own words, and drew each scene as a web page that is filmed frame by frame, so every picture appears on the sentence that names it. The English voice is Kokoro (Heart); every sentence was checked with Whisper and came back word for word. The Persian voice took three rounds: the first two open voices sounded robotic, so the final one is Gooya Bozorg v1.5, a Persian fine-tune of the Chatterbox model, run on GitHub's free servers, with three or more takes per line and the clearest kept. I caught two vowels by ear (badan and chort); a phoneme recognizer confirmed them, and vowel marks fixed them. Limits: it is a summary of one video, not medical advice; the Persian voice model is licensed for non-commercial use only; the voices are synthetic and can still slip on a rare word.

Free to take

Build your own.

Copy the skill, paste it into your own AI, and say what you want different. How to use a skill, step by step ›

Get the skillThe instructions your AI follows. Works in Claude, ChatGPT, Gemini or any other

# Master prompt: Energy after a stroke

You are a health-video editor, a narration producer and a creative coder. Turn one good English video on post-stroke fatigue into a one-minute vertical short (1080×1920, 30 fps) in English and in Persian, with natural voices, captions on screen, and a page that plays both.

Source and script:
- Read the source video's transcript (YouTube's own transcript panel). Summarize it in your own words; never copy it.
- 8 scenes: hook (how common: up to 70% of survivors), why (brain healing, moving less, disrupted sleep, medications, low mood), five ways (body, brain, social, sleep, aerobic exercise) and an end line. 2–5 short sentences per scene, numbers written as words for the voice.
- Keep every number from the source: 10–15 minute mental blocks, naps of 30–90 minutes, exercise from 5–10 up to 15–30 minutes, 3 days a week. End with "talk to your doctor before a new exercise routine".
- Keep titles light: "after a stroke", not a clinical name.

Voices:
- English: Kokoro v1.0, voice af_heart, speed 1.0. Check every sentence with Whisper; aim for zero word errors.
- Persian: Gooya Bozorg v1.5 (a Persian fine-tune of the 500M Chatterbox model, CC BY-NC 4.0), reference voice samples/canonical.wav, exaggeration 0.5, cfg 0.5. Run it on GitHub Actions. Make 3 takes per line and keep the clearest by Whisper character error rate.
- Persian vowels: Whisper cannot hear them, so check risky words with a phoneme recognizer (wav2vec2-lv-60-espeak) and add vowel marks where the voice guesses wrong: بَدَن (badan, not bedan), چُرتِ (chort, not chert), ezafe kasra in phrases such as ساعتِ اَوجِ انرژی. Rule out the robotic voices (Piper, Matcha).
- Gaps: 0.3 s between sentences, 0.65 s between scenes. Soft music pad under the voice at about −23 dB.

Picture:
- One web page drawn from a time value, render(t), driven by the sentence timings, so every picture appears on the sentence that names it.
- A battery in the corner drains while the causes appear and charges with each of the five ways; five progress dots; a caption box with the sentence being spoken; the source credited at the bottom.
- Scenes: 7 of 10 people lighting up for 70%; five cause cards; work/rest blocks and a day energy curve with the peak marked; a brain in a 10–15 minute timer and a muted speaker; a big crowd shrinking to three around a coffee table; seven moons at the same bedtime and a 30–90 minute nap bar; exercise bars growing over 12 weeks and 3 of 7 days marked; a full battery and the doctor line.
- Persian runs right to left (Vazirmatn, Persian digits); English runs left to right (Inter). Film it with Playwright, one MP4 per scene, joined with ffmpeg.

Page:
- One page with both films, a language switch (remembered, and #en / #fa links), the five ways in short in both languages, download links, the personal reason for the film, the doctor line and the source credit.
- A <video> element with playsinline and controls, so it plays on an iPhone even on silent. No outside scripts or fonts.

Stress test: switch languages while playing and paused, both ends of each film, 320×568, 393×700, 740×360 and 1366×800, no sideways scroll, no console errors, both files load.
Get the code21 files, exactly as they run on this site · free under the MIT license

The page files are exactly what runs at sghadimi.com/animations/energy-after-stroke, next to the two films (en.mp4, fa.mp4), their posters and the Vazirmatn font (SIL Open Font License). The rest is the kit that made the films: script, voices, checks, picture and render. The voice models are not included: Kokoro from its GitHub release, Gooya Bozorg v1.5 from Hugging Face (CC BY-NC 4.0).

index.html (the page)71 lines

Raw file

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="dark">
<title>Energy after a stroke | Animations | Shahrouz Ghadimi</title>
<meta name="description" content="A one-minute narrated short on post-stroke fatigue, in English and in Persian (Farsi): why the tiredness happens and five simple ways to get more energy.">
<link rel="icon" href="../../favicon.svg" type="image/svg+xml">
<link rel="stylesheet" href="./stroke.css">
</head>
<body>
<header class="top">
  <a class="back" href="../">&larr; Animations</a>
</header>

<main id="main">
  <section class="intro">
    <h1>Energy after a stroke <span class="fa-title" lang="fa" dir="rtl">انرژی بعد از سکته</span></h1>
    <p class="lede">A one-minute short on the tiredness that follows a stroke: why it happens, and five simple ways to get more energy. One film, two languages.</p>
    <p class="why">A close relative of mine had a stroke recently, and this idea came from there. I wanted the main advice on fatigue in a short clip our family can watch together and pass on, in English and in Persian.</p>
  </section>

  <section class="player" aria-label="Film">
    <div class="switch" role="group" aria-label="Language">
      <button type="button" class="lang" data-lang="en" aria-pressed="true">English</button>
      <button type="button" class="lang" data-lang="fa" aria-pressed="false" lang="fa">فارسی</button>
    </div>
    <div class="frame">
      <video id="film" controls playsinline preload="metadata" poster="./poster-en.jpg" src="./en.mp4" aria-label="Energy after a stroke, English version">
        Your browser cannot play this video. <a href="./en.mp4">Download the English film</a>.
      </video>
    </div>
    <p class="hint" id="hint">Sound on. It plays even when an iPhone is on silent. Captions are drawn into the film.</p>
    <p class="dl"><a href="./en.mp4" download="energy-after-stroke-en.mp4">Download English (MP4, 64 s, 4.8 MB)</a><a href="./fa.mp4" download="energy-after-stroke-fa.mp4" lang="fa" dir="rtl">دانلود نسخه‌ی فارسی (MP4، ۷۰ ثانیه، ۴٫۹ مگابایت)</a></p>
  </section>

  <section class="notes" aria-label="The five ways, in short">
    <div class="pane" data-pane="en">
      <h2>The five ways, in short</h2>
      <ol>
        <li><b>Body energy.</b> Split tasks into short chunks and rest before you get tired. Do the hardest jobs at your peak energy time.</li>
        <li><b>Brain energy.</b> Mental work in 10–15 minute blocks, with the TV and music turned down.</li>
        <li><b>Social energy.</b> Short visits, small and quiet groups.</li>
        <li><b>Sleep.</b> The same bedtime every night, and short daytime naps (30–90 minutes), finished a few hours before bed.</li>
        <li><b>Aerobic exercise.</b> Start with 5–10 minutes and build up to 15–30 minutes, 3 days a week, with rest days.</li>
      </ol>
      <p class="care">Talk to your doctor or therapist before you start any new exercise routine.</p>
    </div>
    <div class="pane" data-pane="fa" lang="fa" dir="rtl" hidden>
      <h2>پنج راهکار، به‌طور خلاصه</h2>
      <ol>
        <li><b>انرژی بدن.</b> کار را به بخش‌های کوتاه تقسیم کن و قبل از خستگی استراحت کن. کارهای سنگین را در ساعت اوج انرژی انجام بده.</li>
        <li><b>انرژی ذهن.</b> کار فکری در بازه‌های ۱۰ تا ۱۵ دقیقه، با صدای تلویزیون و موسیقی کم.</li>
        <li><b>انرژی اجتماعی.</b> دیدارهای کوتاه، جمع‌های کوچک و آرام.</li>
        <li><b>خواب.</b> هر شب سر یک ساعت بخواب. چرت روز کوتاه باشد (۳۰ تا ۹۰ دقیقه) و چند ساعت قبل از خواب شب تمام شود.</li>
        <li><b>ورزش هوازی.</b> با ۵ تا ۱۰ دقیقه شروع کن و کم‌کم به ۱۵ تا ۳۰ دقیقه، ۳ روز در هفته برس. روزهای استراحت را فراموش نکن.</li>
      </ol>
      <p class="care">قبل از شروع ورزش جدید، با پزشک یا درمانگر خود مشورت کنید.</p>
    </div>
  </section>

  <footer class="credit">
    <p>Based on the video “You Want More Energy After Stroke - Do This” by the Post Stroke channel on YouTube (<a href="https://www.youtube.com/watch?v=QiliSWMFziE" rel="noopener">watch the original</a>). This short is a summary, not medical advice.</p>
    <p>English voice: Kokoro (Heart). Persian voice: Gooya Bozorg v1.5, a Persian Chatterbox model (CC BY-NC 4.0, non-commercial). <a href="../../cases/energy-after-stroke/">How it was made</a></p>
  </footer>
</main>
<script src="./stroke.js"></script>
</body>
</html>
stroke.js (language switch)43 lines

Raw file

// Energy after a stroke: switch the film and the notes between English and Persian.
{
  const film = document.getElementById('film');
  const hint = document.getElementById('hint');
  const buttons = [...document.querySelectorAll('.lang')];
  const panes = [...document.querySelectorAll('.pane')];
  const TEXT = {
    en: { label: 'Energy after a stroke, English version', hint: 'Sound on. It plays even when an iPhone is on silent. Captions are drawn into the film.' },
    fa: { label: 'انرژی بعد از سکته، نسخه‌ی فارسی', hint: 'صدا را روشن کنید. حتی وقتی آیفون روی بی‌صداست پخش می‌شود. زیرنویس داخل فیلم است.' }
  };
  let cur = 'en';

  function show(lang, keepPlaying) {
    if (!TEXT[lang]) lang = 'en';
    const wasPlaying = keepPlaying && !film.paused;
    if (lang !== cur) {
      film.pause();
      film.setAttribute('poster', './poster-' + lang + '.jpg');
      film.src = './' + lang + '.mp4';
      film.load();
      cur = lang;
    }
    film.setAttribute('aria-label', TEXT[lang].label);
    hint.textContent = TEXT[lang].hint;
    hint.lang = lang; hint.dir = lang === 'fa' ? 'rtl' : 'ltr';
    for (const b of buttons) b.setAttribute('aria-pressed', String(b.dataset.lang === lang));
    for (const p of panes) p.hidden = p.dataset.pane !== lang;
    if (wasPlaying) { const p = film.play(); if (p && p.catch) p.catch(() => {}); }
  }

  for (const b of buttons) b.addEventListener('click', () => {
    show(b.dataset.lang, true);
    try { history.replaceState(null, '', '#' + b.dataset.lang); } catch (e) {}
    try { localStorage.setItem('eas-lang', b.dataset.lang); } catch (e) {}
  });

  let start = (location.hash || '').slice(1);
  if (!TEXT[start]) { try { start = localStorage.getItem('eas-lang') || ''; } catch (e) { start = ''; } }
  if (!TEXT[start]) start = (navigator.language || '').toLowerCase().startsWith('fa') ? 'fa' : 'en';
  show(start, false);
  window.addEventListener('hashchange', () => show((location.hash || '').slice(1), false));
}
stroke.css35 lines

Raw file

/* Energy after a stroke: a film page with an English and a Persian version. */
@font-face{font-family:Vazirmatn;src:url("./fonts/vazirmatn.woff2") format("woff2");font-weight:100 900;font-display:swap}
:root{--bg:#0c1626;--ink:#eef3fb;--mut:#9fb3cc;--card:#13233a;--line:#24405f;--teal:#3ad6b0;--amber:#ffb547}
*{box-sizing:border-box;min-width:0}
html{-webkit-text-size-adjust:100%}
body{margin:0;background:#0a1422 radial-gradient(ellipse 120% 900px at 50% 0%,#1d3557 0%,#0f1c30 55%,#0a1422 100%) no-repeat;color:var(--ink);font:16px/1.6 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;overflow-x:clip}
[lang=fa],.fa-title{font-family:Vazirmatn,Tahoma,sans-serif}
a{color:var(--teal)}
a:focus-visible,button:focus-visible{outline:2px solid var(--teal);outline-offset:3px}
.top{padding:14px max(4vw,16px)}
.back{color:var(--mut);text-decoration:none;font-size:15px}
.back:hover{color:var(--ink)}
main{max-width:620px;margin:0 auto;padding:0 16px 48px}
.intro h1{font-size:clamp(30px,6vw,44px);line-height:1.1;margin:6px 0 10px;text-wrap:balance}
.fa-title{display:block;font-size:.62em;color:var(--teal);margin-top:6px;text-align:left}
.lede{color:var(--mut);margin:0 0 12px}
.why{margin:0 0 22px;padding:14px 16px;border-inline-start:3px solid var(--amber);background:rgba(255,181,71,.08);border-radius:0 12px 12px 0}
.switch{display:flex;gap:8px;margin-bottom:12px}
.lang{flex:1;min-height:46px;border-radius:23px;border:2px solid var(--line);background:transparent;color:var(--ink);font:600 17px/1 system-ui,sans-serif;cursor:pointer}
.lang[lang=fa]{font-family:Vazirmatn,Tahoma,sans-serif}
.lang[aria-pressed=true]{background:var(--teal);border-color:var(--teal);color:#08201a}
.frame{background:#0a1422;border-radius:26px;padding:8px;box-shadow:0 18px 50px rgba(0,0,0,.35);max-width:calc(78vh * 9 / 16 + 16px);margin-inline:auto}
video{display:block;width:100%;max-height:78vh;aspect-ratio:9/16;margin:0 auto;border-radius:20px;background:#0a1422;object-fit:contain}
.hint{color:var(--mut);font-size:14px;margin:10px 0 6px}
.dl{display:flex;flex-wrap:wrap;gap:8px 18px;font-size:14px;margin:0 0 26px}
.notes h2{font-size:22px;margin:0 0 10px}
.notes ol{margin:0;padding-inline-start:22px;display:grid;gap:8px}
.notes li{background:var(--card);border-radius:14px;padding:10px 14px}
.notes li::marker{color:var(--teal);font-weight:800}
.care{margin:14px 0 0;padding:12px 16px;border-radius:12px;background:rgba(255,181,71,.14);color:#ffd894;font-weight:600}
.credit{margin-top:28px;color:var(--mut);font-size:14px;border-top:1px solid var(--line);padding-top:14px}
@media (max-width:380px){.intro h1{font-size:28px}.lang{font-size:16px}}
@media (orientation:landscape) and (max-height:500px){video{max-height:86vh}.frame{max-width:calc(86vh * 9 / 16 + 16px)}}
@media (prefers-reduced-motion:reduce){*{scroll-behavior:auto}}
README.md (rebuild kit)20 lines

Raw file

# Energy after a stroke: rebuild kit

The two films at sghadimi.com/animations/energy-after-stroke/ were made with these files. Each film is a web page drawn frame by frame (`render(t)`), filmed with Playwright and joined with ffmpeg, with a narration track made line by line.

## English (Kokoro, voice af_heart)
1. Write the scenes in `english/script_en.json` (8 scenes: hook, why, 5 ways, end; numbers as words).
2. `python3 english/make_audio_en.py af_heart 1.0` writes `voice_en.wav` and `timing_en.json`. Model files: GitHub release thewh1teagle/kokoro-onnx `model-files-v1.0`.
3. `python3 english/check_en.py voice_en.wav timing_en.json` checks every sentence with Whisper turbo (sherpa-onnx). Target: 0 word errors.

## Persian (Gooya Bozorg v1.5, a Persian Chatterbox fine-tune, CC BY-NC 4.0)
1. Captions in `persian/script.json`; the text the voice reads in `persian/lines_fa.txt` (same order; vowel marks where the voice guesses wrong: بَدَن, چُرتِ, and the ezafe kasra).
2. The model runs on GitHub Actions (`persian/persian-tts.yml`): `run2.py SEED [lines]` makes every line, `run3.py` makes variants and checks each take's vowels with a phoneme recognizer (wav2vec2-lv-60-espeak). Three takes per line, more for weak lines.
3. `persian/pick.py` keeps the clearest take of each line (Whisper turbo, character error rate); `persian/make_audio3.py` joins them into `voice_gooya.wav` and `timing_gooya.json` (hand picks in `OVR`).

## Picture and film
1. `python3 render/build.py english/anim_en.html timing_en.json page.html` (or `persian/anim_fa.html` with the Persian timing).
2. `python3 render/shots.py 5.9 17.6 ...` to look at the busiest moments first.
3. `TM=timing_en.json PD=parts PAGE=page.html python3 render/render.py` renders one MP4 per scene at 1080×1920, 30 fps, and a concat list.
4. `TM=timing_en.json python3 render/music.py` makes the soft pad. Mix: voice (highpass 70 Hz) + music at 0.07 (lowpass 1800 Hz), alimiter 0.95, AAC 160k, `-movflags +faststart`.
english/script_en.json39 lines

Raw file

[
 {"id": "hook", "s": [
  "Fatigue is one of the most common problems after a stroke.",
  "Up to seventy percent of stroke survivors feel it."
 ]},
 {"id": "why", "s": [
  "Why does it happen?",
  "Your brain is busy healing itself.",
  "Your body moves less, and loses fitness.",
  "Sleep gets disrupted.",
  "And medications, stress and low mood drain your energy too."
 ]},
 {"id": "s1", "s": [
  "Strategy one: body energy.",
  "Split tasks into short chunks, and rest before you get tired.",
  "Do your hardest jobs at your peak energy time."
 ]},
 {"id": "s2", "s": [
  "Strategy two: brain energy.",
  "Do mental work in ten to fifteen minute blocks, and turn down background noise."
 ]},
 {"id": "s3", "s": [
  "Strategy three: social energy.",
  "Keep visits short, and keep groups small."
 ]},
 {"id": "s4", "s": [
  "Strategy four: sleep.",
  "Go to bed at the same time every night, and keep daytime naps short."
 ]},
 {"id": "s5", "s": [
  "Strategy five: aerobic exercise.",
  "Start with five to ten minutes, and build up to fifteen to thirty minutes, three days a week."
 ]},
 {"id": "end", "s": [
  "Small, steady steps build more energy.",
  "Talk to your doctor before you start a new exercise routine."
 ]}
]
english/make_audio_en.py (Kokoro Heart)28 lines

Raw file

import json, wave, sys, numpy as np
from kokoro_onnx import Kokoro
voice = sys.argv[1] if len(sys.argv) > 1 else "af_heart"
speed = float(sys.argv[2]) if len(sys.argv) > 2 else 1.0
K = Kokoro("/home/claude/dl/kokoro/kokoro-v1.0.onnx", "/home/claude/dl/kokoro/voices-v1.0.bin")
script = json.load(open("script_en.json"))
LEAD, GAP_S, GAP_SCENE, TAIL = 0.4, 0.3, 0.65, 1.5
out = []; t = 0; timing = []; SR = 24000
def sil(d): return np.zeros(int(d * SR), np.float32)
out.append(sil(LEAD)); t = LEAD
for sc in script:
    sents = []; sc_start = t
    for i, text in enumerate(sc["s"]):
        a, SR = K.create(text, voice=voice, speed=speed, lang="en-us")
        a = np.asarray(a, np.float32)
        idx = np.where(np.abs(a) > 0.01)[0]; a = a[max(0, idx[0] - 300): idx[-1] + 2400]
        sents.append({"text": text, "start": round(t, 3), "dur": round(len(a) / SR, 3)})
        out.append(a); t += len(a) / SR
        g = GAP_S if i < len(sc["s"]) - 1 else GAP_SCENE
        out.append(sil(g)); t += g
    timing.append({"id": sc["id"], "start": round(sc_start, 3), "end": round(t, 3), "s": sents})
out.append(sil(TAIL)); t += TAIL; timing[-1]["end"] = round(t, 3)
a = np.concatenate(out); a = a / np.abs(a).max() * 0.89
with wave.open("voice_en.wav", "wb") as w:
    w.setnchannels(1); w.setsampwidth(2); w.setframerate(SR); w.writeframes((a * 32767).astype(np.int16).tobytes())
json.dump({"total": round(t, 3), "scenes": timing}, open("timing_en.json", "w"), indent=1)
print("total", round(t, 2))
english/check_en.py (Whisper check)24 lines

Raw file

import sys, json, re, numpy as np, soundfile as sf, librosa, sherpa_onnx
d = "/home/claude/dl/sherpa-onnx-whisper-turbo"
rec = sherpa_onnx.OfflineRecognizer.from_whisper(encoder=f"{d}/turbo-encoder.int8.onnx", decoder=f"{d}/turbo-decoder.int8.onnx", tokens=f"{d}/turbo-tokens.txt", language="en", task="transcribe", num_threads=2)
N = {"70": "seventy", "10": "ten", "15": "fifteen", "5": "five", "30": "thirty", "3": "three", "1": "one", "2": "two", "4": "four"}
def words(x):
    x = re.sub(r"\d+%?", lambda m: N.get(m.group().rstrip("%"), m.group()) + (" percent" if m.group().endswith("%") else ""), x.lower())
    return re.findall(r"[a-z']+", x)
def wer(r, h):
    dp = list(range(len(h) + 1))
    for i in range(1, len(r) + 1):
        prev, dp[0] = dp[0], i
        for j in range(1, len(h) + 1):
            cur = dp[j]; dp[j] = min(dp[j] + 1, dp[j - 1] + 1, prev + (r[i - 1] != h[j - 1])); prev = cur
    return dp[-1] / max(1, len(r))
a, sr = sf.read(sys.argv[1], dtype="float32"); tm = json.load(open(sys.argv[2])); e = []
for sc in tm["scenes"]:
    for s in sc["s"]:
        seg = a[int(s["start"] * sr): int((s["start"] + s["dur"]) * sr)]
        a16 = np.concatenate([np.zeros(4000, np.float32), librosa.resample(seg, orig_sr=sr, target_sr=16000), np.zeros(16000, np.float32)])
        st = rec.create_stream(); st.accept_waveform(16000, a16); rec.decode_stream(st); h = st.result.text
        w = wer(words(s["text"]), words(h)); e.append(w)
        if w > 0: print(round(w, 2), "|", s["text"], "->", h)
print("mean WER", round(float(np.mean(e)), 3))
english/anim_en.html (the English picture)298 lines

Raw file

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<style>
@font-face { font-family: Vz; src: url("file:///home/claude/fonts/inter/web/InterVariable.woff2") format("woff2"); font-weight: 100 900; }
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body { width: 1080px; height: 1920px; overflow: hidden; }
body { font-family: Vz, sans-serif; color: #f3f6fb; background: radial-gradient(ellipse at 50% 30%, #1d3557 0%, #0f1c30 60%, #0a1422 100%); position: relative; }
.abs { position: absolute; }
#glow { position:absolute; width:900px; height:900px; left:90px; top:420px; border-radius:50%; background: radial-gradient(circle, rgba(58,214,176,.16), rgba(58,214,176,0) 65%); }
/* header */
#hdr { position:absolute; top:70px; right:60px; left:60px; height:140px; }
#hdrTitle { position:absolute; left:0; top:8px; font-size:44px; font-weight:800; letter-spacing:0; }
#hdrSub { position:absolute; left:0; top:74px; font-size:30px; font-weight:500; color:#9fb3cc; }
#bat { position:absolute; right:0; top:14px; width:190px; height:92px; border:7px solid #e8eef7; border-radius:20px; }
#bat::after { content:""; position:absolute; right:-22px; top:24px; width:13px; height:30px; background:#e8eef7; border-radius:0 5px 5px 0; }
#batFill { position:absolute; left:6px; top:6px; bottom:6px; border-radius:10px; }
#batPct { position:absolute; right:225px; top:28px; font-size:38px; font-weight:800; direction:ltr; }
#dots { position:absolute; top:250px; left:0; right:0; display:flex; justify-content:center; gap:26px; }
.dot { width:30px; height:30px; border-radius:50%; border:4px solid #3c5677; }
/* scenes */
.scene { position:absolute; left:0; top:300px; width:1080px; height:1150px; opacity:0; }
.pop { opacity:0; }
.big { font-weight:900; }
.card { position:absolute; left:70px; right:70px; height:150px; border-radius:34px; background:rgba(255,255,255,.07); border:2px solid rgba(255,255,255,.10); display:flex; align-items:center; gap:34px; padding:0 34px; }
.ico { width:104px; height:104px; flex:none; border-radius:50%; display:flex; align-items:center; justify-content:center; }
.ico svg { width:66px; height:66px; }
.card span { font-size:46px; font-weight:700; }
.sHead { position:absolute; top:40px; left:0; right:0; display:flex; justify-content:center; align-items:center; gap:30px; }
.num { width:120px; height:120px; border-radius:50%; background:#3ad6b0; color:#0b1626; font-size:70px; font-weight:900; display:flex; align-items:center; justify-content:center; }
.sHead .t { font-size:30px; color:#9fb3cc; font-weight:600; }
.sHead .h { font-size:66px; font-weight:900; line-height:1.15; }
.lbl { position:absolute; left:0; right:0; text-align:center; font-size:44px; font-weight:700; }
.chip { display:inline-block; padding:14px 34px; border-radius:40px; background:rgba(255,181,71,.16); color:#ffcf7d; font-weight:700; }
/* caption */
#cap { position:absolute; left:60px; right:60px; bottom:150px; padding:30px 40px; border-radius:36px; background:rgba(6,12,22,.72); border:2px solid rgba(255,255,255,.08); text-align:center; font-size:50px; font-weight:700; line-height:1.4; letter-spacing:-0.01em; }
#src { position:absolute; bottom:70px; left:0; right:0; text-align:center; font-size:26px; color:#7d90aa; }
</style>
</head>
<body>
<div id="glow"></div>

<div id="hdr">
  <div id="hdrTitle">Energy after a stroke</div>
  <div id="hdrSub">5 simple ways to fight fatigue</div>
  <div id="bat"><div id="batFill"></div></div>
  <div id="batPct"></div>
</div>
<div id="dots"><div class="dot"></div><div class="dot"></div><div class="dot"></div><div class="dot"></div><div class="dot"></div></div>

<!-- HOOK -->
<div class="scene" id="sc-hook">
  <div class="lbl pop" data-a="hook:0:0" style="top:40px"><div class="big" style="font-size:150px;color:#ff7a6b;letter-spacing:-0.03em">Fatigue</div>
    <div style="font-size:48px;font-weight:600;color:#c9d6e6;margin-top:6px">The most common problem after a stroke</div></div>
  <div class="lbl pop" data-a="hook:1:0" style="top:380px"><div class="big" id="pct70" style="font-size:190px;color:#ffb547;line-height:1"></div>
    <div style="font-size:44px;font-weight:600;color:#c9d6e6;margin-top:10px">of stroke survivors</div></div>
  <svg class="abs pop" data-a="hook:1:0" id="people" style="left:115px;top:760px" width="850" height="360" viewBox="0 0 850 360"></svg>
</div>

<!-- WHY -->
<div class="scene" id="sc-why">
  <div class="lbl pop big" data-a="why:0:0" style="top:20px;font-size:84px">Why so tired?</div>
  <div class="card pop" data-a="why:1:0" style="top:170px"><div class="ico" style="background:rgba(255,122,107,.18);color:#ff8f82"><svg viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"><path d="M32 12c-5-6-17-4-17 5-7 2-8 12-2 16-3 7 3 14 10 12 2 5 8 6 9 2 1 4 7 3 9-2 7 2 13-5 10-12 6-4 5-14-2-16 0-9-12-11-17-5z"/><path d="M32 12v40M22 26c4 0 6 3 6 6M42 26c-4 0-6 3-6 6M22 42c3-1 6 1 6 4M42 42c-3-1-6 1-6 4"/></svg></div><span>The brain is healing</span></div>
  <div class="card pop" data-a="why:2:0" style="top:345px"><div class="ico" style="background:rgba(255,122,107,.18);color:#ff8f82"><svg viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"><circle cx="36" cy="10" r="5"/><path d="M35 17l-4 18M31 35l-8 17M31 35l8 17M33 23l-11 7M33 23l10 6"/></svg></div><span>Moving less weakens the body</span></div>
  <div class="card pop" data-a="why:3:0" style="top:520px"><div class="ico" style="background:rgba(255,122,107,.18);color:#ff8f82"><svg viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"><path d="M46 40A20 20 0 1 1 26 12a15 15 0 0 0 20 28z"/><path d="M46 12v8M42 16h8"/></svg></div><span>Disrupted sleep</span></div>
  <div class="card pop" data-a="why:4:0" style="top:695px"><div class="ico" style="background:rgba(255,122,107,.18);color:#ff8f82"><svg viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"><g transform="rotate(-40 32 32)"><rect x="8" y="22" width="48" height="20" rx="10"/><path d="M32 22v20"/></g></svg></div><span>Medication side effects</span></div>
  <div class="card pop" data-a="why:4:0.4" style="top:870px"><div class="ico" style="background:rgba(255,122,107,.18);color:#ff8f82"><svg viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"><path d="M18 38a10 10 0 0 1 2-20 13 13 0 0 1 25 2 9 9 0 0 1 1 18z"/><path d="M24 46l-3 7M34 46l-3 7M44 46l-3 7"/></svg></div><span>Depression, anxiety, grief</span></div>
</div>

<!-- S1 -->
<div class="scene" id="sc-s1">
  <div class="sHead pop" data-a="s1:0:0"><div class="num">1</div><div><div class="t">Strategy one</div><div class="h">Body energy</div></div></div>
  <div class="lbl pop" data-a="s1:1:0" style="top:250px">Split tasks into short chunks</div>
  <div class="abs pop" data-a="s1:1:0" id="segs" style="top:340px;right:90px;left:90px;height:110px;display:flex;gap:12px;flex-direction:row"></div>
  <div class="lbl pop" data-a="s1:1:0.45" style="top:475px;font-size:36px;color:#9fe9d6">Rest before you get tired</div>
  <svg class="abs pop" data-a="s1:2:0" style="left:90px;top:590px" width="900" height="470" viewBox="0 0 900 470">
    <line x1="40" y1="400" x2="880" y2="400" stroke="#3c5677" stroke-width="4"/>
    <path id="curve" d="M 40 380 C 140 360, 200 90, 300 90 C 400 90, 450 250, 570 270 C 680 290, 750 340, 840 380" fill="none" stroke="#ffb547" stroke-width="10" stroke-linecap="round"/>
    <circle id="peakDot" cx="300" cy="90" r="20" fill="#3ad6b0"/>
    <text x="60" y="450" fill="#9fb3cc" font-size="34" text-anchor="middle" font-family="Vz">Morning</text>
    <text x="460" y="450" fill="#9fb3cc" font-size="34" text-anchor="middle" font-family="Vz">Noon</text>
    <text x="840" y="450" fill="#9fb3cc" font-size="34" text-anchor="middle" font-family="Vz">Night</text>
    <g id="peakLbl"><text x="330" y="45" fill="#3ad6b0" font-size="40" font-weight="800" text-anchor="middle" font-family="Vz">Peak energy = hard tasks</text></g>
  </svg>
</div>

<!-- S2 -->
<div class="scene" id="sc-s2">
  <div class="sHead pop" data-a="s2:0:0"><div class="num">2</div><div><div class="t">Strategy two</div><div class="h">Brain energy</div></div></div>
  <svg class="abs pop" data-a="s2:1:0" style="left:340px;top:230px" width="400" height="400" viewBox="0 0 400 400">
    <circle cx="200" cy="200" r="170" fill="none" stroke="#24405f" stroke-width="22"/>
    <circle id="timerRing" cx="200" cy="200" r="170" fill="none" stroke="#3ad6b0" stroke-width="22" stroke-linecap="round" transform="rotate(-90 200 200)" stroke-dasharray="1068" stroke-dashoffset="1068"/>
    <g transform="translate(110 110) scale(2.8)" fill="none" stroke="#e8eef7" stroke-width="3.2" stroke-linecap="round" stroke-linejoin="round"><path d="M32 12c-5-6-17-4-17 5-7 2-8 12-2 16-3 7 3 14 10 12 2 5 8 6 9 2 1 4 7 3 9-2 7 2 13-5 10-12 6-4 5-14-2-16 0-9-12-11-17-5z"/><path d="M32 12v40"/></g>
  </svg>
  <div class="lbl pop" data-a="s2:1:0.1" style="top:660px"><span class="chip">10–15 minutes of focus, then a break</span></div>
  <div class="card pop" data-a="s2:1:0.58" style="top:800px;right:150px;left:150px;justify-content:center"><div class="ico" style="background:rgba(255,122,107,.18);color:#ff8f82"><svg viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"><path d="M10 26h10l12-10v32L20 38H10z"/><path d="M42 24l14 16M56 24L42 40"/></svg></div><span>Turn down the noise</span></div>
</div>

<!-- S3 -->
<div class="scene" id="sc-s3">
  <div class="sHead pop" data-a="s3:0:0"><div class="num">3</div><div><div class="t">Strategy three</div><div class="h">Social energy</div></div></div>
  <svg class="abs pop" data-a="s3:1:0" id="crowd" style="left:190px;top:230px" width="700" height="640" viewBox="0 0 700 640"></svg>
  <div class="abs pop" data-a="s3:1:0" style="top:900px;left:0;right:0;display:flex;justify-content:center;gap:30px">
    <span class="chip" style="font-size:42px">Short visits</span>
  </div>
  <div class="abs pop" data-a="s3:1:0.5" style="top:1000px;left:0;right:0;display:flex;justify-content:center">
    <span class="chip" style="font-size:42px;background:rgba(58,214,176,.16);color:#9fe9d6">Small, quiet groups</span>
  </div>
</div>

<!-- S4 -->
<div class="scene" id="sc-s4">
  <div class="sHead pop" data-a="s4:0:0"><div class="num">4</div><div><div class="t">Strategy four</div><div class="h">Sleep</div></div></div>
  <div class="lbl pop" data-a="s4:1:0" style="top:250px">Same bedtime every night</div>
  <div class="abs" id="week" style="top:340px;left:70px;right:70px;height:240px;display:flex;justify-content:space-between"></div>
  <div class="lbl pop" data-a="s4:1:0.5" style="top:650px">Daytime naps: short</div>
  <svg class="abs pop" data-a="s4:1:0.5" style="left:90px;top:740px" width="900" height="200" viewBox="0 0 900 200">
    <rect x="20" y="40" width="860" height="60" rx="30" fill="#24405f"/>
    <rect id="napBar" x="235" y="40" width="0" height="60" rx="30" fill="#3ad6b0"/>
    <text x="20" y="160" fill="#9fb3cc" font-size="32" text-anchor="start" font-family="Vz">0</text>
    <text x="235" y="160" fill="#e8eef7" font-size="36" font-weight="800" text-anchor="middle" font-family="Vz">30 min</text>
    <text x="665" y="160" fill="#e8eef7" font-size="36" font-weight="800" text-anchor="middle" font-family="Vz">90 min</text>
    <text x="880" y="160" fill="#9fb3cc" font-size="32" text-anchor="end" font-family="Vz">2 h</text>
  </svg>
  <div class="lbl pop" data-a="s4:1:0.7" style="top:960px;font-size:36px;color:#9fb3cc">End naps a few hours before bedtime</div>
</div>

<!-- S5 -->
<div class="scene" id="sc-s5">
  <div class="sHead pop" data-a="s5:0:0"><div class="num">5</div><div><div class="t">Strategy five</div><div class="h">Aerobic exercise</div></div></div>
  <svg class="abs pop" data-a="s5:1:0" style="left:90px;top:220px" width="900" height="560" viewBox="0 0 900 560">
    <line x1="40" y1="460" x2="880" y2="460" stroke="#3c5677" stroke-width="4"/>
    <g id="bars"></g>
  </svg>
  <div class="lbl pop" data-a="s5:1:0" style="top:790px;font-size:34px;color:#9fb3cc">Walking, stationary bike, arm bike or swimming</div>
  <div class="abs" id="days" style="top:880px;left:120px;right:120px;height:120px;display:flex;justify-content:space-between"></div>
  <div class="lbl pop" data-a="s5:1:0.62" style="top:1030px;font-size:40px;color:#9fe9d6">3 days a week + rest days</div>
</div>

<!-- END -->
<div class="scene" id="sc-end">
  <svg class="abs pop" data-a="end:0:0" style="left:290px;top:60px" width="500" height="300" viewBox="0 0 500 300">
    <rect x="40" y="40" width="400" height="220" rx="40" fill="none" stroke="#e8eef7" stroke-width="16"/>
    <rect x="440" y="110" width="30" height="80" rx="10" fill="#e8eef7"/>
    <rect id="bigFill" x="62" y="62" width="0" height="176" rx="24" fill="#3ad6b0"/>
  </svg>
  <div class="lbl pop big" data-a="end:0:0.1" style="top:420px;font-size:72px;line-height:1.4">Small, steady steps<br><span style="color:#3ad6b0">More energy</span></div>
  <div class="lbl pop" data-a="end:1:0" style="top:700px"><span class="chip" style="font-size:40px">Talk to your doctor before new exercise</span></div>
  <div class="lbl pop" data-a="end:1:0.5" style="top:830px;font-size:30px;color:#9fb3cc;line-height:1.6">Based on “You Want More Energy After Stroke”<br>by the Post Stroke channel on YouTube</div>
</div>

<div id="cap"></div>
<div id="src">Source: Post Stroke on YouTube</div>

<script>
const TM = __TIMING__;
const S = {}; TM.scenes.forEach(s => S[s.id] = s);
const fa = n => String(n);
const cl = x => x < 0 ? 0 : x > 1 ? 1 : x;
const ease = x => 1 - Math.pow(1 - cl(x), 3);
const prog = (t, t0, d) => ease((t - t0) / d);
const at = (id, si, off = 0) => { const s = S[id].s[si]; return s.start + off * s.dur; };
const lerp = (a, b, k) => a + (b - a) * k;

// build dynamic content
const ppl = document.getElementById('people');
let ph = '';
for (let i = 0; i < 10; i++) {
  const x = 85 + (i % 5) * 170, y = i < 5 ? 80 : 260;
  ph += `<g class="pp" transform="translate(${x} ${y})"><circle cx="0" cy="-40" r="32"/><path d="M-55 70 a55 60 0 0 1 110 0 z"/></g>`;
}
ppl.innerHTML = ph;
const segs = document.getElementById('segs');
['Work','Rest','Work','Rest','Work'].forEach((w, i) => {
  const d = document.createElement('div');
  d.textContent = w;
  d.style.cssText = `flex:${i % 2 ? 0.7 : 1};border-radius:24px;display:flex;align-items:center;justify-content:center;font-size:34px;font-weight:800;opacity:0;` +
    (i % 2 ? 'background:rgba(58,214,176,.22);color:#9fe9d6;border:3px dashed #3ad6b0' : 'background:#ffb547;color:#1b1406');
  segs.appendChild(d);
});
const crowd = document.getElementById('crowd');
const CN = 12; let ch = '<g id="table"><circle cx="350" cy="320" r="62" fill="#24405f"/><path d="M325 300h40v28a20 20 0 0 1-40 0z M365 308h10a9 9 0 0 1 0 18h-10" fill="none" stroke="#ffb547" stroke-width="6" stroke-linejoin="round"/></g>';
for (let i = 0; i < CN; i++) ch += `<g class="cp"><circle cx="0" cy="-22" r="22"/><path d="M-36 36 a36 40 0 0 1 72 0 z"/></g>`;
crowd.innerHTML = ch;
const week = document.getElementById('week');
'M T W T F S S'.split(' ').forEach(d => {
  const e = document.createElement('div');
  e.style.cssText = 'width:118px;display:flex;flex-direction:column;align-items:center;gap:14px;opacity:0';
  e.innerHTML = `<svg width="92" height="92" viewBox="0 0 64 64" fill="none" stroke="#ffcf7d" stroke-width="4" stroke-linecap="round"><path d="M46 40A20 20 0 1 1 26 12a15 15 0 0 0 20 28z" fill="rgba(255,181,71,.18)"/></svg><div style="font-size:30px;font-weight:800;color:#e8eef7">10 pm</div><div style="font-size:30px;color:#9fb3cc">${d}</div>`;
  week.appendChild(e);
});
const bars = document.getElementById('bars');
const BD = [['Week 1', '5–10', 10], ['Week 4', '10–15', 15], ['Week 8', '15–20', 21], ['Week 12', '15–30', 30]];
BD.forEach((b, i) => {
  const x = 140 + i * 210;
  bars.innerHTML += `<rect class="bar" x="${x - 65}" y="460" width="130" height="0" rx="18" fill="#ffb547"/>` +
    `<text class="bv" x="${x}" y="440" fill="#e8eef7" font-size="38" font-weight="800" text-anchor="middle" font-family="Vz">${b[1]} min</text>` +
    `<text x="${x}" y="510" fill="#9fb3cc" font-size="32" text-anchor="middle" font-family="Vz">${b[0]}</text>`;
});
const days = document.getElementById('days');
'M T W T F S S'.split(' ').forEach((d, i) => {
  const on = [0, 2, 4].includes(i);
  const e = document.createElement('div');
  e.dataset.on = on ? 1 : 0;
  e.style.cssText = `width:104px;height:104px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:38px;font-weight:800;opacity:0;` +
    (on ? 'background:#3ad6b0;color:#0b1626' : 'border:4px solid #3c5677;color:#9fb3cc');
  e.textContent = d;
  days.appendChild(e);
});

// timing data for pops
const pops = [...document.querySelectorAll('.pop')].map(el => {
  const [id, si, off] = el.dataset.a.split(':');
  return { el, t0: at(id, +si, +off) };
});
const scenes = TM.scenes.map((s, i) => ({ s, el: document.getElementById('sc-' + s.id), last: i === TM.scenes.length - 1 }));
const sents = TM.scenes.flatMap(s => s.s.map(x => ({ ...x, sid: s.id, send: s.end })));

function battery(t) {
  const k = [[0, 70], [at('hook', 1), 70], [at('hook', 1) + 1.6, 30], [at('why', 1), 30], [at('why', 1) + 0.8, 24], [at('why', 2), 24], [at('why', 2) + 0.8, 18],
    [at('why', 3), 18], [at('why', 3) + 0.8, 13], [at('why', 4), 13], [at('why', 4) + 1.4, 6]];
  let v = 6;
  ['s1', 's2', 's3', 's4', 's5'].forEach((id, i) => { k.push([S[id].start + 0.3, 6 + i * 17]); k.push([S[id].start + 1.5, 6 + (i + 1) * 17]); });
  k.push([S.end.start + 0.2, 91]); k.push([S.end.start + 2.2, 100]);
  for (let i = 0; i < k.length - 1; i++) if (t >= k[i][0] && t < k[i + 1][0]) { const q = (t - k[i][0]) / (k[i + 1][0] - k[i][0]); return lerp(k[i][1], k[i + 1][1], ease(q)); }
  return t < 0 ? 70 : 100;
}
const batColor = v => v < 25 ? '#ff7a6b' : v < 60 ? '#ffb547' : '#3ad6b0';

window.render = function (t) {
  // scenes
  scenes.forEach(({ s, el, last }) => {
    const a = prog(t, s.start - 0.1, 0.45) * (last ? 1 : 1 - prog(t, s.end - 0.32, 0.3));
    el.style.opacity = a;
    el.style.transform = `translateY(${(1 - prog(t, s.start - 0.1, 0.45)) * 40}px)`;
  });
  pops.forEach(({ el, t0 }) => { const p = prog(t, t0, 0.5); el.style.opacity = p; el.style.transform = `translateY(${(1 - p) * 36}px) scale(${0.95 + 0.05 * p})`; });
  // battery
  const v = battery(t);
  const bf = document.getElementById('batFill');
  bf.style.width = (164 * v / 100) + 'px'; bf.style.background = batColor(v);
  const bp = document.getElementById('batPct'); bp.textContent = fa(Math.round(v)) + '%'; bp.style.color = batColor(v);
  document.getElementById('glow').style.background = `radial-gradient(circle, ${v < 25 ? 'rgba(255,122,107,.14)' : v < 60 ? 'rgba(255,181,71,.13)' : 'rgba(58,214,176,.16)'}, rgba(0,0,0,0) 65%)`;
  // strategy dots
  document.querySelectorAll('.dot').forEach((d, i) => {
    const on = prog(t, S['s' + (i + 1)].start, 0.4);
    d.style.background = on > 0 ? `rgba(58,214,176,${on})` : 'transparent';
    d.style.borderColor = on > 0.5 ? '#3ad6b0' : '#3c5677';
    d.style.transform = `scale(${1 + 0.35 * Math.sin(Math.PI * cl((t - S['s' + (i + 1)].start) / 0.6))})`;
  });
  // hook: counter + people
  const c = prog(t, at('hook', 1), 1.4);
  document.getElementById('pct70').textContent = fa(Math.round(70 * c)) + '%';
  document.querySelectorAll('.pp').forEach((g, i) => { const on = c * 7 > i + 0.3; g.setAttribute('fill', on ? '#ffb547' : '#2c4566'); });
  // s1 segments + curve
  [...segs.children].forEach((d, i) => { const p = prog(t, at('s1', 1) + i * 0.28, 0.4); d.style.opacity = p; d.style.transform = `scaleY(${0.6 + 0.4 * p})`; });
  const cv = document.getElementById('curve'); const L = cv.getTotalLength();
  cv.style.strokeDasharray = L; cv.style.strokeDashoffset = L * (1 - prog(t, at('s1', 2), 1.6));
  const pk = prog(t, at('s1', 2) + 1.3, 0.5);
  document.getElementById('peakDot').setAttribute('r', 20 * pk + 6 * pk * Math.sin(t * 6));
  document.getElementById('peakLbl').style.opacity = pk;
  // s2 timer
  document.getElementById('timerRing').setAttribute('stroke-dashoffset', 1068 * (1 - prog(t, at('s2', 1), 3.2)));
  // s3 crowd
  const shrink = prog(t, at('s3', 1, 0.45), 1.2);
  document.querySelectorAll('.cp').forEach((g, i) => {
    const a1 = (i / CN) * Math.PI * 2, R1 = 270;
    const a2 = -Math.PI / 2 + (i % 3) * (Math.PI * 2 / 3), R2 = 150;
    let x = 350 + Math.cos(a1) * R1, y = 320 + Math.sin(a1) * R1;
    if (i < 3) { x = lerp(x, 350 + Math.cos(a2) * R2, shrink); y = lerp(y, 320 + Math.sin(a2) * R2, shrink); }
    g.setAttribute('transform', `translate(${x} ${y})`);
    g.setAttribute('fill', i < 3 ? (shrink > 0.5 ? '#3ad6b0' : '#5f7ea3') : '#5f7ea3');
    g.style.opacity = i < 3 ? 1 : 1 - shrink;
  });
  // s4 week + nap
  [...week.children].forEach((d, i) => { const p = prog(t, at('s4', 1) + i * 0.16, 0.35); d.style.opacity = p; d.style.transform = `translateY(${(1 - p) * 30}px)`; });
  const np = prog(t, at('s4', 1, 0.55), 1.0);
  const nb = document.getElementById('napBar'); nb.setAttribute('width', 430 * np); nb.setAttribute('x', 235);
  // s5 bars + days
  document.querySelectorAll('.bar').forEach((b, i) => { const h = BD[i][2] * 12 * prog(t, at('s5', 1) + i * 0.45, 0.7); b.setAttribute('height', h); b.setAttribute('y', 460 - h); b.setAttribute('fill', i === 3 ? '#3ad6b0' : '#ffb547'); });
  document.querySelectorAll('.bv').forEach((b, i) => { const p = prog(t, at('s5', 1) + i * 0.45 + 0.4, 0.4); b.setAttribute('y', 440 - BD[i][2] * 12); b.style.opacity = p; });
  [...days.children].forEach((d, i) => { const p = prog(t, at('s5', 1, 0.55) + i * 0.1, 0.35); d.style.opacity = p; d.style.transform = `scale(${0.7 + 0.3 * p})`; });
  // end battery
  document.getElementById('bigFill').setAttribute('width', 356 * prog(t, S.end.start + 0.2, 2.4));
  // caption
  let cur = null;
  for (const x of sents) if (t >= x.start - 0.05 && t < x.send) cur = x;
  const cap = document.getElementById('cap');
  if (cur) { if (cap.textContent !== cur.text) cap.textContent = cur.text; cap.style.opacity = prog(t, cur.start - 0.05, 0.2); }
  else cap.style.opacity = 0;
};
const q = new URLSearchParams(location.search).get('t');
document.fonts.ready.then(() => { window.render(q ? +q : 0); window.READY = true; });
</script>
</body>
</html>
persian/script.json (captions)39 lines

Raw file

[
 {"id": "hook", "s": [
  "خستگی بعد از سکته، بسیار شایع است.",
  "تا هفتاد درصد بازماندگان، آن را تجربه می‌کنند."
 ]},
 {"id": "why", "s": [
  "چرا؟",
  "مغز در حال ترمیم خودش است.",
  "بدن کم‌تحرک می‌شود.",
  "خواب به هم می‌ریزد.",
  "و داروها و فشار روحی هم، انرژی را می‌گیرند."
 ]},
 {"id": "s1", "s": [
  "راهکار اول: انرژی بدن.",
  "کار را به بخش‌های کوتاه تقسیم کن، و قبل از خستگی، استراحت کن.",
  "کارهای سنگین را در ساعت اوج انرژی انجام بده."
 ]},
 {"id": "s2", "s": [
  "راهکار دوم: انرژی ذهن.",
  "کار فکری را در بازه‌های ده تا پانزده دقیقه انجام بده، و صداهای مزاحم را کم کن."
 ]},
 {"id": "s3", "s": [
  "راهکار سوم: انرژی اجتماعی.",
  "دیدارها را کوتاه، و جمع‌ها را کوچک نگه دار."
 ]},
 {"id": "s4", "s": [
  "راهکار چهارم: خواب.",
  "هر روز سر یک ساعت بخواب، و چرت روز را کوتاه نگه دار."
 ]},
 {"id": "s5", "s": [
  "راهکار پنجم: ورزش هوازی.",
  "با پنج تا ده دقیقه شروع کن، و کم‌کم به پانزده تا سی دقیقه، سه روز در هفته برس."
 ]},
 {"id": "end", "s": [
  "قدم‌های کوچک و پیوسته، انرژی می‌سازند.",
  "قبل از شروع ورزش جدید، با پزشک خود مشورت کن."
 ]}
]
persian/lines_fa.txt (what the voice reads)21 lines

Raw file

خستگی بعد از سکته‌ی مغزی، بسیار شایع است.
تا هفتاد درصدِ بازماندگان، آن را تجربه می‌کنند.
چرا؟
مغز در حالِ ترمیمِ خودش است.
بدن کم‌تحرک می‌شود.
خواب به هم می‌ریزد.
و داروها و فشارِ روحی هم، انرژی را می‌گیرند.
راهکارِ اول: انرژیِ بدن.
کار را به بخش‌های کوتاه تقسیم کن، و قبل از خستگی، استراحت کن.
کارهایِ سنگین را در ساعتِ اَوجِ انرژی انجام بده.
راهکارِ دوم: انرژیِ ذهن.
کارِ فکری را در بازه‌های ده تا پانزده دقیقه انجام بده، و صداهای مزاحم را کم کن.
راهکارِ سوم: انرژیِ اجتماعی.
دیدارها را کوتاه، و جمع‌ها را کوچک نگه دار.
راهکارِ چهارم: خواب.
هر روز سرِ یک ساعت بخواب، و چرتِ روز را کوتاه نگه دار.
راهکارِ پنجم: ورزشِ هوازی.
با پنج تا ده دقیقه شروع کن، و کم‌کم به پانزده تا سی دقیقه، سه روز در هفته برس.
قدم‌های کوچک و پیوسته، انرژی می‌سازند.
قبل از شروعِ ورزشِ جدید، با پزشکِ خود مشورت کن.
persian/persian-tts.yml (GitHub Actions)38 lines

Raw file

name: persian-tts
on:
  push:
    branches: [persian-tts]
    paths: ["tts/job.txt"]
  workflow_dispatch:
permissions:
  contents: write
jobs:
  tts:
    runs-on: ubuntu-latest
    timeout-minutes: 90
    strategy:
      matrix:
        seed: [21, 22, 23]
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with: { python-version: "3.11" }
      - name: Install
        run: |
          git clone --depth 1 https://github.com/resemble-ai/chatterbox.git /tmp/chatterbox
          pip install -q torch==2.6.0 torchaudio==2.6.0 --index-url https://download.pytorch.org/whl/cpu
          pip install -q -e /tmp/chatterbox
          pip install -q huggingface_hub safetensors soundfile librosa phonemizer
          sudo apt-get install -y -q espeak-ng > /dev/null
      - name: Synthesize
        run: python tts/run3.py ${{ matrix.seed }} 2>&1 | tee tts/log_${{ matrix.seed }}.txt
        continue-on-error: true
      - name: Save results
        if: always()
        run: |
          git config user.name "persian-tts-bot"
          git config user.email "persian-tts-bot@users.noreply.github.com"
          git add -A tts
          git commit -m "TTS output for $(cat tts/job.txt | head -c 40)" || true
          for k in 1 2 3 4 5; do git pull --rebase -q && git push && break; sleep $((RANDOM % 10 + 3)); done
persian/run2.py (all lines)18 lines

Raw file

import sys, os, glob, importlib.util, torch, soundfile as sf
from pathlib import Path
from huggingface_hub import snapshot_download
seed = int(sys.argv[1])
md = Path(snapshot_download("Reza2kn/Gooya-Bozorg-v1.5"))
spec = importlib.util.spec_from_file_location("inf", md / "inference.py"); inf = importlib.util.module_from_spec(spec); spec.loader.exec_module(inf)
torch.set_num_threads(os.cpu_count())
model = inf.load_model(md, "cpu")
lines = [l.strip() for l in open("tts/lines.txt", encoding="utf-8") if l.strip()]
out = Path(f"tts/out/s{seed}"); out.mkdir(parents=True, exist_ok=True)
only = [int(x) for x in sys.argv[2].split(",")] if len(sys.argv) > 2 else None
for i, t in enumerate(lines):
    if only is not None and i not in only: continue
    torch.manual_seed(seed * 100 + i)
    wav = model.generate(text=t, language_id=None, audio_prompt_path=str(md / "samples/canonical.wav"), exaggeration=0.5, cfg_weight=0.5)
    sf.write(out / f"{i:02d}.wav", wav.squeeze().cpu().numpy(), model.sr)
    print("done", seed, i, flush=True)
persian/run3.py (variants + phoneme check)36 lines

Raw file

import sys, os, json, importlib.util, torch, soundfile as sf, gc
from pathlib import Path
from huggingface_hub import snapshot_download
job = int(sys.argv[1])
V = {
 0: ["خستگی بعد از سکته، بسیار شایع است."],
 4: ["بَدَن کم‌تحرک می‌شود.", "بدن کم‌تحرک می‌شود."],
 7: ["راهکار اول: انرژیِ بَدَن.", "راهکار اول: انرژی بَدَن.", "راهکار اول: انرژی بدن."],
 15: ["هر روز سر یک ساعت بخواب، و چُرتِ روز را کوتاه نگه دار.", "هر روز سر یک ساعت بخواب، و چُرت روز را کوتاه نگه دار.", "هر روز سر یک ساعت بخواب، و چرت روز را کوتاه نگه دار."],
}
md = Path(snapshot_download("Reza2kn/Gooya-Bozorg-v1.5"))
spec = importlib.util.spec_from_file_location("inf", md / "inference.py"); inf = importlib.util.module_from_spec(spec); spec.loader.exec_module(inf)
torch.set_num_threads(os.cpu_count())
model = inf.load_model(md, "cpu")
out = Path("tts/out3"); out.mkdir(parents=True, exist_ok=True)
files = []
for line, vs in V.items():
    for vi, t in enumerate(vs):
        for seed in (job, job + 10):
            torch.manual_seed(seed * 1000 + line * 10 + vi)
            wav = model.generate(text=t, language_id=None, audio_prompt_path=str(md / "samples/canonical.wav"), exaggeration=0.5, cfg_weight=0.5)
            f = out / f"{line:02d}_v{vi}_s{seed}.wav"
            sf.write(f, wav.squeeze().cpu().numpy(), model.sr); files.append(str(f)); print("done", f, flush=True)
del model; gc.collect()
from transformers import Wav2Vec2Processor, Wav2Vec2ForCTC
import librosa
name = "facebook/wav2vec2-lv-60-espeak-cv-ft"
proc = Wav2Vec2Processor.from_pretrained(name); asr = Wav2Vec2ForCTC.from_pretrained(name).eval()
ph = {}
for f in files:
    a, sr = sf.read(f, dtype="float32"); a = librosa.resample(a, orig_sr=sr, target_sr=16000)
    with torch.no_grad():
        ids = torch.argmax(asr(proc(a, sampling_rate=16000, return_tensors="pt").input_values).logits, -1)
    ph[os.path.basename(f)] = proc.batch_decode(ids)[0]; print(os.path.basename(f), ph[os.path.basename(f)], flush=True)
json.dump(ph, open(f"tts/out3/ph_{job}.json", "w"), ensure_ascii=False, indent=1)
persian/voices.py (Whisper helpers)56 lines

Raw file

import sherpa_onnx, soundfile as sf, numpy as np, sys, os
D = "/home/claude/dl"

def make_tts(name):
    d = f"{D}/{name}"
    if name.startswith("matcha"):
        m = sherpa_onnx.OfflineTtsModelConfig(matcha=sherpa_onnx.OfflineTtsMatchaModelConfig(
            acoustic_model=f"{d}/model.onnx", vocoder=f"{D}/vocos-22khz-univ.onnx",
            tokens=f"{d}/tokens.txt", data_dir=f"{d}/espeak-ng-data"), num_threads=2)
    else:
        onnx = [f for f in os.listdir(d) if f.endswith(".onnx")][0]
        m = sherpa_onnx.OfflineTtsModelConfig(vits=sherpa_onnx.OfflineTtsVitsModelConfig(
            model=f"{d}/{onnx}", tokens=f"{d}/tokens.txt", data_dir=f"{d}/espeak-ng-data"), num_threads=2)
    return sherpa_onnx.OfflineTts(sherpa_onnx.OfflineTtsConfig(model=m))

def asr():
    d = f"{D}/sherpa-onnx-whisper-turbo"
    return sherpa_onnx.OfflineRecognizer.from_whisper(encoder=f"{d}/turbo-encoder.int8.onnx", decoder=f"{d}/turbo-decoder.int8.onnx",
                                                      tokens=f"{d}/turbo-tokens.txt", language="fa", task="transcribe", num_threads=2)

def transcribe(rec, a, sr):
    s = rec.create_stream(); s.accept_waveform(sr, a); rec.decode_stream(s); return s.result.text

def norm(x):
    import re
    x = re.sub(r"[ً-ْ‌‏،.؟?!:,\s]", "", x)
    return x.replace("ي", "ی").replace("ك", "ک")

def cer(ref, hyp):
    r, h = norm(ref), norm(hyp)
    dp = list(range(len(h) + 1))
    for i in range(1, len(r) + 1):
        prev, dp[0] = dp[0], i
        for j in range(1, len(h) + 1):
            cur = dp[j]
            dp[j] = min(dp[j] + 1, dp[j - 1] + 1, prev + (r[i - 1] != h[j - 1]))
            prev = cur
    return dp[-1] / max(1, len(r))

if __name__ == "__main__":
    texts = [l.strip() for l in open(sys.argv[1]) if l.strip()]
    names = sys.argv[2:]
    rec = asr()
    for n in names:
        tts = make_tts(n); errs = []
        for i, t in enumerate(texts):
            g = tts.generate(t, sid=0, speed=1.0)
            a = np.array(g.samples, dtype=np.float32)
            sf.write(f"v_{n}_{i}.wav", a, g.sample_rate)
            import librosa
            a16 = librosa.resample(a, orig_sr=g.sample_rate, target_sr=16000)
            hyp = transcribe(rec, a16, 16000)
            errs.append(cer(t, hyp))
            if i < 2: print("  ", n, i, "->", hyp)
        print(n, "SR", g.sample_rate, "mean CER", round(float(np.mean(errs)), 3), flush=True)
persian/pick.py (best take per line)22 lines

Raw file

import soundfile as sf, librosa, numpy as np, json, re
from voices import asr, transcribe, cer
rec = asr()
lines = [l.strip() for l in open("/home/claude/agent1/tts/lines.txt", encoding="utf-8") if l.strip()]
D = {'70':'هفتاد','10':'ده','15':'پانزده','5':'پنج','30':'سی','3':'سه','7':'هفت'}
best = []
for i, t in enumerate(lines):
    res = []
    for s in (1, 2, 3, 4, 5, 6):
        import os
        if not os.path.exists(f"/home/claude/agent1/tts/out/s{s}/{i:02d}.wav"): continue
        a, sr = sf.read(f"/home/claude/agent1/tts/out/s{s}/{i:02d}.wav", dtype="float32")
        a16 = librosa.resample(a, orig_sr=sr, target_sr=16000)
        a16 = np.concatenate([np.zeros(4000, np.float32), a16, np.zeros(16000, np.float32)])
        h = re.sub(r'\d+', lambda m: D.get(m.group(), m.group()), transcribe(rec, a16, 16000))
        res.append((round(cer(t, h), 3), round(len(a)/sr, 2), s, h))
    res.sort(key=lambda r: (r[0], r[1]))
    best.append({"i": i, "seed": res[0][2], "cer": res[0][0]})
    print(i, [(r[2], r[0], r[1]) for r in res], "|", res[0][3])
print("mean best CER", round(float(np.mean([b["cer"] for b in best])), 3))
json.dump(best, open("best.json", "w"))
persian/make_audio3.py (narration track)34 lines

Raw file

import json, wave, numpy as np, soundfile as sf
script = json.load(open("script.json"))
best = {b["i"]: b["seed"] for b in json.load(open("best.json"))}
OVR = {0: "out3/00_v0_s31", 4: "out3/04_v0_s22", 7: "out3/07_v0_s31", 15: "out3/15_v0_s23"}
SR = 24000
LEAD, GAP_S, GAP_SCENE, TAIL = 0.4, 0.3, 0.65, 1.5
def sil(d): return np.zeros(int(d * SR), np.float32)
def trim(a):
    env = np.convolve(np.abs(a), np.ones(240) / 240, mode="same")
    idx = np.where(env > 0.012)[0]
    a = a[max(0, idx[0] - 600): idx[-1] + 4800]
    f = int(0.02 * SR); a[:f] *= np.linspace(0, 1, f); a[-f:] *= np.linspace(1, 0, f)
    return a
out = [sil(LEAD)]; t = LEAD; timing = []; k = 0
for sc in script:
    sents = []; sc_start = t
    for i, text in enumerate(sc["s"]):
        src = f"/home/claude/agent1/tts/{OVR[k]}.wav" if k in OVR else f"/home/claude/agent1/tts/out/s{best[k]}/{k:02d}.wav"
        a, sr = sf.read(src, dtype="float32"); k += 1
        assert sr == SR
        a = trim(a)
        a = a / max(1e-6, np.percentile(np.abs(a), 99.5)) * 0.7  # even loudness per line
        sents.append({"text": text, "start": round(t, 3), "dur": round(len(a) / SR, 3)})
        out.append(a); t += len(a) / SR
        g = GAP_S if i < len(sc["s"]) - 1 else GAP_SCENE
        out.append(sil(g)); t += g
    timing.append({"id": sc["id"], "start": round(sc_start, 3), "end": round(t, 3), "s": sents})
out.append(sil(TAIL)); t += TAIL; timing[-1]["end"] = round(t, 3)
a = np.concatenate(out); a = np.clip(a / np.abs(a).max() * 0.89, -1, 1)
with wave.open("voice_gooya.wav", "wb") as w:
    w.setnchannels(1); w.setsampwidth(2); w.setframerate(SR); w.writeframes((a * 32767).astype(np.int16).tobytes())
json.dump({"total": round(t, 3), "scenes": timing}, open("timing_gooya.json", "w"), ensure_ascii=False, indent=1)
print("total", round(t, 2))
persian/anim_fa.html (the Persian picture)298 lines

Raw file

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="utf-8">
<style>
@font-face { font-family: Vz; src: url("file:///home/claude/fonts/vz/fonts/webfonts/Vazirmatn[wght].woff2") format("woff2"); font-weight: 100 900; }
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body { width: 1080px; height: 1920px; overflow: hidden; }
body { font-family: Vz, sans-serif; color: #f3f6fb; background: radial-gradient(ellipse at 50% 30%, #1d3557 0%, #0f1c30 60%, #0a1422 100%); position: relative; }
.abs { position: absolute; }
#glow { position:absolute; width:900px; height:900px; left:90px; top:420px; border-radius:50%; background: radial-gradient(circle, rgba(58,214,176,.16), rgba(58,214,176,0) 65%); }
/* header */
#hdr { position:absolute; top:70px; right:60px; left:60px; height:140px; }
#hdrTitle { position:absolute; right:0; top:8px; font-size:44px; font-weight:800; letter-spacing:0; }
#hdrSub { position:absolute; right:0; top:74px; font-size:30px; font-weight:500; color:#9fb3cc; }
#bat { position:absolute; left:0; top:14px; width:190px; height:92px; border:7px solid #e8eef7; border-radius:20px; }
#bat::after { content:""; position:absolute; left:-22px; top:24px; width:13px; height:30px; background:#e8eef7; border-radius:5px 0 0 5px; }
#batFill { position:absolute; right:6px; top:6px; bottom:6px; border-radius:10px; }
#batPct { position:absolute; left:205px; top:28px; font-size:38px; font-weight:800; direction:ltr; }
#dots { position:absolute; top:250px; left:0; right:0; display:flex; justify-content:center; gap:26px; }
.dot { width:30px; height:30px; border-radius:50%; border:4px solid #3c5677; }
/* scenes */
.scene { position:absolute; left:0; top:300px; width:1080px; height:1150px; opacity:0; }
.pop { opacity:0; }
.big { font-weight:900; }
.card { position:absolute; right:70px; left:70px; height:150px; border-radius:34px; background:rgba(255,255,255,.07); border:2px solid rgba(255,255,255,.10); display:flex; align-items:center; gap:34px; padding:0 34px; }
.ico { width:104px; height:104px; flex:none; border-radius:50%; display:flex; align-items:center; justify-content:center; }
.ico svg { width:66px; height:66px; }
.card span { font-size:46px; font-weight:700; }
.sHead { position:absolute; top:40px; left:0; right:0; display:flex; justify-content:center; align-items:center; gap:30px; }
.num { width:120px; height:120px; border-radius:50%; background:#3ad6b0; color:#0b1626; font-size:70px; font-weight:900; display:flex; align-items:center; justify-content:center; }
.sHead .t { font-size:30px; color:#9fb3cc; font-weight:600; }
.sHead .h { font-size:66px; font-weight:900; line-height:1.15; }
.lbl { position:absolute; left:0; right:0; text-align:center; font-size:44px; font-weight:700; }
.chip { display:inline-block; padding:14px 34px; border-radius:40px; background:rgba(255,181,71,.16); color:#ffcf7d; font-weight:700; }
/* caption */
#cap { position:absolute; left:60px; right:60px; bottom:150px; padding:30px 40px; border-radius:36px; background:rgba(6,12,22,.72); border:2px solid rgba(255,255,255,.08); text-align:center; font-size:50px; font-weight:700; line-height:1.55; }
#src { position:absolute; bottom:70px; left:0; right:0; text-align:center; font-size:26px; color:#7d90aa; }
</style>
</head>
<body>
<div id="glow"></div>

<div id="hdr">
  <div id="hdrTitle">انرژی بعد از سکته</div>
  <div id="hdrSub">۵ راهکار ساده برای خستگی</div>
  <div id="bat"><div id="batFill"></div></div>
  <div id="batPct"></div>
</div>
<div id="dots"><div class="dot"></div><div class="dot"></div><div class="dot"></div><div class="dot"></div><div class="dot"></div></div>

<!-- HOOK -->
<div class="scene" id="sc-hook">
  <div class="lbl pop" data-a="hook:0:0" style="top:40px"><div class="big" style="font-size:150px;color:#ff7a6b">خستگی</div>
    <div style="font-size:48px;font-weight:600;color:#c9d6e6;margin-top:6px">شایع‌ترین مشکل بعد از سکته</div></div>
  <div class="lbl pop" data-a="hook:1:0" style="top:380px"><div class="big" id="pct70" style="font-size:190px;color:#ffb547;line-height:1"></div>
    <div style="font-size:44px;font-weight:600;color:#c9d6e6;margin-top:10px">از بازماندگان سکته</div></div>
  <svg class="abs pop" data-a="hook:1:0" id="people" style="left:115px;top:760px" width="850" height="360" viewBox="0 0 850 360"></svg>
</div>

<!-- WHY -->
<div class="scene" id="sc-why">
  <div class="lbl pop big" data-a="why:0:0" style="top:20px;font-size:84px">چرا خسته‌ایم؟</div>
  <div class="card pop" data-a="why:1:0" style="top:170px"><div class="ico" style="background:rgba(255,122,107,.18);color:#ff8f82"><svg viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"><path d="M32 12c-5-6-17-4-17 5-7 2-8 12-2 16-3 7 3 14 10 12 2 5 8 6 9 2 1 4 7 3 9-2 7 2 13-5 10-12 6-4 5-14-2-16 0-9-12-11-17-5z"/><path d="M32 12v40M22 26c4 0 6 3 6 6M42 26c-4 0-6 3-6 6M22 42c3-1 6 1 6 4M42 42c-3-1-6 1-6 4"/></svg></div><span>مغز در حال ترمیم است</span></div>
  <div class="card pop" data-a="why:2:0" style="top:345px"><div class="ico" style="background:rgba(255,122,107,.18);color:#ff8f82"><svg viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"><circle cx="36" cy="10" r="5"/><path d="M35 17l-4 18M31 35l-8 17M31 35l8 17M33 23l-11 7M33 23l10 6"/></svg></div><span>کم‌تحرکی، بدن را ضعیف‌تر می‌کند</span></div>
  <div class="card pop" data-a="why:3:0" style="top:520px"><div class="ico" style="background:rgba(255,122,107,.18);color:#ff8f82"><svg viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"><path d="M46 40A20 20 0 1 1 26 12a15 15 0 0 0 20 28z"/><path d="M46 12v8M42 16h8"/></svg></div><span>خواب آشفته</span></div>
  <div class="card pop" data-a="why:4:0" style="top:695px"><div class="ico" style="background:rgba(255,122,107,.18);color:#ff8f82"><svg viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"><g transform="rotate(-40 32 32)"><rect x="8" y="22" width="48" height="20" rx="10"/><path d="M32 22v20"/></g></svg></div><span>عوارض داروها</span></div>
  <div class="card pop" data-a="why:4:0.4" style="top:870px"><div class="ico" style="background:rgba(255,122,107,.18);color:#ff8f82"><svg viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"><path d="M18 38a10 10 0 0 1 2-20 13 13 0 0 1 25 2 9 9 0 0 1 1 18z"/><path d="M24 46l-3 7M34 46l-3 7M44 46l-3 7"/></svg></div><span>افسردگی، اضطراب و غم</span></div>
</div>

<!-- S1 -->
<div class="scene" id="sc-s1">
  <div class="sHead pop" data-a="s1:0:0"><div class="num">۱</div><div><div class="t">راهکار اول</div><div class="h">انرژی بدن</div></div></div>
  <div class="lbl pop" data-a="s1:1:0" style="top:250px">کار را به بخش‌های کوتاه تقسیم کن</div>
  <div class="abs pop" data-a="s1:1:0" id="segs" style="top:340px;right:90px;left:90px;height:110px;display:flex;gap:12px;flex-direction:row"></div>
  <div class="lbl pop" data-a="s1:1:0.45" style="top:475px;font-size:36px;color:#9fe9d6">قبل از خستگی، استراحت کن</div>
  <svg class="abs pop" data-a="s1:2:0" style="left:90px;top:590px" width="900" height="470" viewBox="0 0 900 470">
    <line x1="40" y1="400" x2="880" y2="400" stroke="#3c5677" stroke-width="4"/>
    <path id="curve" d="M 860 380 C 760 360, 700 90, 600 90 C 500 90, 450 250, 330 270 C 220 290, 150 340, 60 380" fill="none" stroke="#ffb547" stroke-width="10" stroke-linecap="round"/>
    <circle id="peakDot" cx="600" cy="90" r="20" fill="#3ad6b0"/>
    <text x="860" y="450" fill="#9fb3cc" font-size="34" text-anchor="middle" font-family="Vz">صبح</text>
    <text x="460" y="450" fill="#9fb3cc" font-size="34" text-anchor="middle" font-family="Vz">ظهر</text>
    <text x="70" y="450" fill="#9fb3cc" font-size="34" text-anchor="middle" font-family="Vz">شب</text>
    <g id="peakLbl"><text x="600" y="45" fill="#3ad6b0" font-size="40" font-weight="800" text-anchor="middle" font-family="Vz">اوج انرژی = کار سنگین</text></g>
  </svg>
</div>

<!-- S2 -->
<div class="scene" id="sc-s2">
  <div class="sHead pop" data-a="s2:0:0"><div class="num">۲</div><div><div class="t">راهکار دوم</div><div class="h">انرژی ذهن</div></div></div>
  <svg class="abs pop" data-a="s2:1:0" style="left:340px;top:230px" width="400" height="400" viewBox="0 0 400 400">
    <circle cx="200" cy="200" r="170" fill="none" stroke="#24405f" stroke-width="22"/>
    <circle id="timerRing" cx="200" cy="200" r="170" fill="none" stroke="#3ad6b0" stroke-width="22" stroke-linecap="round" transform="rotate(-90 200 200)" stroke-dasharray="1068" stroke-dashoffset="1068"/>
    <g transform="translate(110 110) scale(2.8)" fill="none" stroke="#e8eef7" stroke-width="3.2" stroke-linecap="round" stroke-linejoin="round"><path d="M32 12c-5-6-17-4-17 5-7 2-8 12-2 16-3 7 3 14 10 12 2 5 8 6 9 2 1 4 7 3 9-2 7 2 13-5 10-12 6-4 5-14-2-16 0-9-12-11-17-5z"/><path d="M32 12v40"/></g>
  </svg>
  <div class="lbl pop" data-a="s2:1:0.1" style="top:660px"><span class="chip">۱۰ تا ۱۵ دقیقه کار فکری، بعد استراحت</span></div>
  <div class="card pop" data-a="s2:1:0.58" style="top:800px;right:150px;left:150px;justify-content:center"><div class="ico" style="background:rgba(255,122,107,.18);color:#ff8f82"><svg viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"><path d="M10 26h10l12-10v32L20 38H10z"/><path d="M42 24l14 16M56 24L42 40"/></svg></div><span>صدای مزاحم را کم کن</span></div>
</div>

<!-- S3 -->
<div class="scene" id="sc-s3">
  <div class="sHead pop" data-a="s3:0:0"><div class="num">۳</div><div><div class="t">راهکار سوم</div><div class="h">انرژی اجتماعی</div></div></div>
  <svg class="abs pop" data-a="s3:1:0" id="crowd" style="left:190px;top:230px" width="700" height="640" viewBox="0 0 700 640"></svg>
  <div class="abs pop" data-a="s3:1:0" style="top:900px;left:0;right:0;display:flex;justify-content:center;gap:30px">
    <span class="chip" style="font-size:42px">دیدار کوتاه</span>
  </div>
  <div class="abs pop" data-a="s3:1:0.5" style="top:1000px;left:0;right:0;display:flex;justify-content:center">
    <span class="chip" style="font-size:42px;background:rgba(58,214,176,.16);color:#9fe9d6">جمع کوچک و آرام</span>
  </div>
</div>

<!-- S4 -->
<div class="scene" id="sc-s4">
  <div class="sHead pop" data-a="s4:0:0"><div class="num">۴</div><div><div class="t">راهکار چهارم</div><div class="h">خواب</div></div></div>
  <div class="lbl pop" data-a="s4:1:0" style="top:250px">هر شب، یک ساعت ثابت</div>
  <div class="abs" id="week" style="top:340px;left:70px;right:70px;height:240px;display:flex;justify-content:space-between"></div>
  <div class="lbl pop" data-a="s4:1:0.5" style="top:650px">چرت روز: کوتاه</div>
  <svg class="abs pop" data-a="s4:1:0.5" style="left:90px;top:740px" width="900" height="200" viewBox="0 0 900 200">
    <rect x="20" y="40" width="860" height="60" rx="30" fill="#24405f"/>
    <rect id="napBar" x="593" y="40" width="0" height="60" rx="30" fill="#3ad6b0"/>
    <text x="880" y="160" fill="#9fb3cc" font-size="32" text-anchor="end" font-family="Vz">۰</text>
    <text x="593" y="160" fill="#e8eef7" font-size="36" font-weight="800" text-anchor="middle" font-family="Vz">۳۰ دقیقه</text>
    <text x="307" y="160" fill="#e8eef7" font-size="36" font-weight="800" text-anchor="middle" font-family="Vz">۹۰ دقیقه</text>
    <text x="20" y="160" fill="#9fb3cc" font-size="32" text-anchor="start" font-family="Vz">۲ ساعت</text>
  </svg>
  <div class="lbl pop" data-a="s4:1:0.7" style="top:960px;font-size:36px;color:#9fb3cc">چرت را چند ساعت قبل از خواب شب تمام کن</div>
</div>

<!-- S5 -->
<div class="scene" id="sc-s5">
  <div class="sHead pop" data-a="s5:0:0"><div class="num">۵</div><div><div class="t">راهکار پنجم</div><div class="h">ورزش هوازی</div></div></div>
  <svg class="abs pop" data-a="s5:1:0" style="left:90px;top:220px" width="900" height="560" viewBox="0 0 900 560">
    <line x1="40" y1="460" x2="880" y2="460" stroke="#3c5677" stroke-width="4"/>
    <g id="bars"></g>
  </svg>
  <div class="lbl pop" data-a="s5:1:0" style="top:790px;font-size:34px;color:#9fb3cc">پیاده‌روی، دوچرخه‌ی ثابت، رکاب دستی یا شنا</div>
  <div class="abs" id="days" style="top:880px;left:120px;right:120px;height:120px;display:flex;justify-content:space-between"></div>
  <div class="lbl pop" data-a="s5:1:0.62" style="top:1030px;font-size:40px;color:#9fe9d6">۳ روز در هفته + روزهای استراحت</div>
</div>

<!-- END -->
<div class="scene" id="sc-end">
  <svg class="abs pop" data-a="end:0:0" style="left:290px;top:60px" width="500" height="300" viewBox="0 0 500 300">
    <rect x="40" y="40" width="400" height="220" rx="40" fill="none" stroke="#e8eef7" stroke-width="16"/>
    <rect x="440" y="110" width="30" height="80" rx="10" fill="#e8eef7"/>
    <rect id="bigFill" x="62" y="62" width="0" height="176" rx="24" fill="#3ad6b0"/>
  </svg>
  <div class="lbl pop big" data-a="end:0:0.1" style="top:420px;font-size:72px;line-height:1.4">قدم‌های کوچک و پیوسته<br><span style="color:#3ad6b0">انرژی بیشتر</span></div>
  <div class="lbl pop" data-a="end:1:0" style="top:700px"><span class="chip" style="font-size:40px">قبل از ورزش جدید، با پزشک مشورت کنید</span></div>
  <div class="lbl pop" data-a="end:1:0.5" style="top:830px;font-size:30px;color:#9fb3cc;line-height:1.6">بر اساس ویدیوی «You Want More Energy After Stroke»<br>از کانال Post Stroke در یوتیوب</div>
</div>

<div id="cap"></div>
<div id="src">منبع: کانال Post Stroke در یوتیوب</div>

<script>
const TM = __TIMING__;
const S = {}; TM.scenes.forEach(s => S[s.id] = s);
const fa = n => String(n).replace(/\d/g, d => '۰۱۲۳۴۵۶۷۸۹'[d]);
const cl = x => x < 0 ? 0 : x > 1 ? 1 : x;
const ease = x => 1 - Math.pow(1 - cl(x), 3);
const prog = (t, t0, d) => ease((t - t0) / d);
const at = (id, si, off = 0) => { const s = S[id].s[si]; return s.start + off * s.dur; };
const lerp = (a, b, k) => a + (b - a) * k;

// build dynamic content
const ppl = document.getElementById('people');
let ph = '';
for (let i = 0; i < 10; i++) {
  const x = 85 + (i % 5) * 170, y = i < 5 ? 80 : 260;
  ph += `<g class="pp" transform="translate(${x} ${y})"><circle cx="0" cy="-40" r="32"/><path d="M-55 70 a55 60 0 0 1 110 0 z"/></g>`;
}
ppl.innerHTML = ph;
const segs = document.getElementById('segs');
['کار','استراحت','کار','استراحت','کار'].forEach((w, i) => {
  const d = document.createElement('div');
  d.textContent = w;
  d.style.cssText = `flex:${i % 2 ? 0.7 : 1};border-radius:24px;display:flex;align-items:center;justify-content:center;font-size:34px;font-weight:800;opacity:0;` +
    (i % 2 ? 'background:rgba(58,214,176,.22);color:#9fe9d6;border:3px dashed #3ad6b0' : 'background:#ffb547;color:#1b1406');
  segs.appendChild(d);
});
const crowd = document.getElementById('crowd');
const CN = 12; let ch = '<g id="table"><circle cx="350" cy="320" r="62" fill="#24405f"/><path d="M325 300h40v28a20 20 0 0 1-40 0z M365 308h10a9 9 0 0 1 0 18h-10" fill="none" stroke="#ffb547" stroke-width="6" stroke-linejoin="round"/></g>';
for (let i = 0; i < CN; i++) ch += `<g class="cp"><circle cx="0" cy="-22" r="22"/><path d="M-36 36 a36 40 0 0 1 72 0 z"/></g>`;
crowd.innerHTML = ch;
const week = document.getElementById('week');
'ش ی د س چ پ ج'.split(' ').forEach(d => {
  const e = document.createElement('div');
  e.style.cssText = 'width:118px;display:flex;flex-direction:column;align-items:center;gap:14px;opacity:0';
  e.innerHTML = `<svg width="92" height="92" viewBox="0 0 64 64" fill="none" stroke="#ffcf7d" stroke-width="4" stroke-linecap="round"><path d="M46 40A20 20 0 1 1 26 12a15 15 0 0 0 20 28z" fill="rgba(255,181,71,.18)"/></svg><div style="font-size:30px;font-weight:800;color:#e8eef7">۲۲:۰۰</div><div style="font-size:30px;color:#9fb3cc">${d}</div>`;
  week.appendChild(e);
});
const bars = document.getElementById('bars');
const BD = [['هفته‌ی ۱', '۵–۱۰', 10], ['هفته‌ی ۴', '۱۰–۱۵', 15], ['هفته‌ی ۸', '۱۵–۲۰', 21], ['هفته‌ی ۱۲', '۱۵–۳۰', 30]];
BD.forEach((b, i) => {
  const x = 760 - i * 210;
  bars.innerHTML += `<rect class="bar" x="${x - 65}" y="460" width="130" height="0" rx="18" fill="#ffb547"/>` +
    `<text class="bv" x="${x}" y="440" fill="#e8eef7" font-size="38" font-weight="800" text-anchor="middle" font-family="Vz">${b[1]} دقیقه</text>` +
    `<text x="${x}" y="510" fill="#9fb3cc" font-size="32" text-anchor="middle" font-family="Vz">${b[0]}</text>`;
});
const days = document.getElementById('days');
'ش ی د س چ پ ج'.split(' ').forEach((d, i) => {
  const on = [0, 2, 4].includes(i);
  const e = document.createElement('div');
  e.dataset.on = on ? 1 : 0;
  e.style.cssText = `width:104px;height:104px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:38px;font-weight:800;opacity:0;` +
    (on ? 'background:#3ad6b0;color:#0b1626' : 'border:4px solid #3c5677;color:#9fb3cc');
  e.textContent = d;
  days.appendChild(e);
});

// timing data for pops
const pops = [...document.querySelectorAll('.pop')].map(el => {
  const [id, si, off] = el.dataset.a.split(':');
  return { el, t0: at(id, +si, +off) };
});
const scenes = TM.scenes.map((s, i) => ({ s, el: document.getElementById('sc-' + s.id), last: i === TM.scenes.length - 1 }));
const sents = TM.scenes.flatMap(s => s.s.map(x => ({ ...x, sid: s.id, send: s.end })));

function battery(t) {
  const k = [[0, 70], [at('hook', 1), 70], [at('hook', 1) + 1.6, 30], [at('why', 1), 30], [at('why', 1) + 0.8, 24], [at('why', 2), 24], [at('why', 2) + 0.8, 18],
    [at('why', 3), 18], [at('why', 3) + 0.8, 13], [at('why', 4), 13], [at('why', 4) + 1.4, 6]];
  let v = 6;
  ['s1', 's2', 's3', 's4', 's5'].forEach((id, i) => { k.push([S[id].start + 0.3, 6 + i * 17]); k.push([S[id].start + 1.5, 6 + (i + 1) * 17]); });
  k.push([S.end.start + 0.2, 91]); k.push([S.end.start + 2.2, 100]);
  for (let i = 0; i < k.length - 1; i++) if (t >= k[i][0] && t < k[i + 1][0]) { const q = (t - k[i][0]) / (k[i + 1][0] - k[i][0]); return lerp(k[i][1], k[i + 1][1], ease(q)); }
  return t < 0 ? 70 : 100;
}
const batColor = v => v < 25 ? '#ff7a6b' : v < 60 ? '#ffb547' : '#3ad6b0';

window.render = function (t) {
  // scenes
  scenes.forEach(({ s, el, last }) => {
    const a = prog(t, s.start - 0.1, 0.45) * (last ? 1 : 1 - prog(t, s.end - 0.32, 0.3));
    el.style.opacity = a;
    el.style.transform = `translateY(${(1 - prog(t, s.start - 0.1, 0.45)) * 40}px)`;
  });
  pops.forEach(({ el, t0 }) => { const p = prog(t, t0, 0.5); el.style.opacity = p; el.style.transform = `translateY(${(1 - p) * 36}px) scale(${0.95 + 0.05 * p})`; });
  // battery
  const v = battery(t);
  const bf = document.getElementById('batFill');
  bf.style.width = (164 * v / 100) + 'px'; bf.style.background = batColor(v);
  const bp = document.getElementById('batPct'); bp.textContent = fa(Math.round(v)) + '٪'; bp.style.color = batColor(v);
  document.getElementById('glow').style.background = `radial-gradient(circle, ${v < 25 ? 'rgba(255,122,107,.14)' : v < 60 ? 'rgba(255,181,71,.13)' : 'rgba(58,214,176,.16)'}, rgba(0,0,0,0) 65%)`;
  // strategy dots
  document.querySelectorAll('.dot').forEach((d, i) => {
    const on = prog(t, S['s' + (i + 1)].start, 0.4);
    d.style.background = on > 0 ? `rgba(58,214,176,${on})` : 'transparent';
    d.style.borderColor = on > 0.5 ? '#3ad6b0' : '#3c5677';
    d.style.transform = `scale(${1 + 0.35 * Math.sin(Math.PI * cl((t - S['s' + (i + 1)].start) / 0.6))})`;
  });
  // hook: counter + people
  const c = prog(t, at('hook', 1), 1.4);
  document.getElementById('pct70').textContent = fa(Math.round(70 * c)) + '٪';
  document.querySelectorAll('.pp').forEach((g, i) => { const on = c * 7 > i + 0.3; g.setAttribute('fill', on ? '#ffb547' : '#2c4566'); });
  // s1 segments + curve
  [...segs.children].forEach((d, i) => { const p = prog(t, at('s1', 1) + i * 0.28, 0.4); d.style.opacity = p; d.style.transform = `scaleY(${0.6 + 0.4 * p})`; });
  const cv = document.getElementById('curve'); const L = cv.getTotalLength();
  cv.style.strokeDasharray = L; cv.style.strokeDashoffset = L * (1 - prog(t, at('s1', 2), 1.6));
  const pk = prog(t, at('s1', 2) + 1.3, 0.5);
  document.getElementById('peakDot').setAttribute('r', 20 * pk + 6 * pk * Math.sin(t * 6));
  document.getElementById('peakLbl').style.opacity = pk;
  // s2 timer
  document.getElementById('timerRing').setAttribute('stroke-dashoffset', 1068 * (1 - prog(t, at('s2', 1), 3.2)));
  // s3 crowd
  const shrink = prog(t, at('s3', 1, 0.45), 1.2);
  document.querySelectorAll('.cp').forEach((g, i) => {
    const a1 = (i / CN) * Math.PI * 2, R1 = 270;
    const a2 = -Math.PI / 2 + (i % 3) * (Math.PI * 2 / 3), R2 = 150;
    let x = 350 + Math.cos(a1) * R1, y = 320 + Math.sin(a1) * R1;
    if (i < 3) { x = lerp(x, 350 + Math.cos(a2) * R2, shrink); y = lerp(y, 320 + Math.sin(a2) * R2, shrink); }
    g.setAttribute('transform', `translate(${x} ${y})`);
    g.setAttribute('fill', i < 3 ? (shrink > 0.5 ? '#3ad6b0' : '#5f7ea3') : '#5f7ea3');
    g.style.opacity = i < 3 ? 1 : 1 - shrink;
  });
  // s4 week + nap
  [...week.children].forEach((d, i) => { const p = prog(t, at('s4', 1) + i * 0.16, 0.35); d.style.opacity = p; d.style.transform = `translateY(${(1 - p) * 30}px)`; });
  const np = prog(t, at('s4', 1, 0.55), 1.0);
  const nb = document.getElementById('napBar'); nb.setAttribute('width', 286 * np); nb.setAttribute('x', 593 - 286 * np);
  // s5 bars + days
  document.querySelectorAll('.bar').forEach((b, i) => { const h = BD[i][2] * 12 * prog(t, at('s5', 1) + i * 0.45, 0.7); b.setAttribute('height', h); b.setAttribute('y', 460 - h); b.setAttribute('fill', i === 3 ? '#3ad6b0' : '#ffb547'); });
  document.querySelectorAll('.bv').forEach((b, i) => { const p = prog(t, at('s5', 1) + i * 0.45 + 0.4, 0.4); b.setAttribute('y', 440 - BD[i][2] * 12); b.style.opacity = p; });
  [...days.children].forEach((d, i) => { const p = prog(t, at('s5', 1, 0.55) + i * 0.1, 0.35); d.style.opacity = p; d.style.transform = `scale(${0.7 + 0.3 * p})`; });
  // end battery
  document.getElementById('bigFill').setAttribute('width', 356 * prog(t, S.end.start + 0.2, 2.4));
  // caption
  let cur = null;
  for (const x of sents) if (t >= x.start - 0.05 && t < x.send) cur = x;
  const cap = document.getElementById('cap');
  if (cur) { if (cap.textContent !== cur.text) cap.textContent = cur.text; cap.style.opacity = prog(t, cur.start - 0.05, 0.2); }
  else cap.style.opacity = 0;
};
const q = new URLSearchParams(location.search).get('t');
document.fonts.ready.then(() => { window.render(q ? +q : 0); window.READY = true; });
</script>
</body>
</html>
render/build.py4 lines

Raw file

import sys
tpl, tm, out = sys.argv[1], sys.argv[2], sys.argv[3]
open(out, "w", encoding="utf-8").write(open(tpl, encoding="utf-8").read().replace("__TIMING__", open(tm, encoding="utf-8").read()))
render/shots.py11 lines

Raw file

import sys, json
from playwright.sync_api import sync_playwright
ts = [float(x) for x in sys.argv[1:]]
with sync_playwright() as p:
    b = p.chromium.launch(); pg = b.new_page(viewport={"width":1080,"height":1920})
    pg.goto("file://" + __import__("os").path.abspath("page.html")); pg.wait_for_function("window.READY===true")
    for t in ts:
        pg.evaluate(f"render({t})"); pg.screenshot(path=f"shot_{t:05.1f}.jpg", type="jpeg", quality=80)
    print(pg.evaluate("1"))
    b.close()
render/render.py (film it)26 lines

Raw file

import json, subprocess, os, time
from playwright.sync_api import sync_playwright
FPS = 30
P = os.environ.get("PD","parts")
tm = json.load(open(__import__("os").environ.get("TM","timing.json")))
sc = tm["scenes"]
bounds = [0] + [round(s["end"] * FPS) for s in sc]
os.makedirs(P+"", exist_ok=True)
t0 = time.time()
with sync_playwright() as p:
    b = p.chromium.launch(); pg = b.new_page(viewport={"width": 1080, "height": 1920})
    pg.goto("file://" + os.path.abspath(os.environ.get("PAGE","page.html"))); pg.wait_for_function("window.READY===true")
    for i, s in enumerate(sc):
        tmp, out = f"{P}/{i:02d}.tmp.mp4", f"{P}/{i:02d}.mp4"
        ff = subprocess.Popen(["ffmpeg", "-y", "-loglevel", "error", "-f", "image2pipe", "-framerate", str(FPS), "-c:v", "mjpeg", "-i", "-",
                               "-c:v", "libx264", "-preset", "veryfast", "-crf", "18", "-pix_fmt", "yuv420p", "-r", str(FPS), tmp], stdin=subprocess.PIPE)
        for f in range(bounds[i], bounds[i + 1]):
            pg.evaluate(f"render({f / FPS})")
            ff.stdin.write(pg.screenshot(type="jpeg", quality=92))
        ff.stdin.close()
        if ff.wait() == 0: os.rename(tmp, out)
        print(s["id"], bounds[i + 1] - bounds[i], "frames", round(time.time() - t0), "s", flush=True)
    b.close()
with open(P+"/list.txt", "w") as f:
    for i in range(len(sc)): f.write(f"file '{i:02d}.mp4'\n")
render/music.py (soft pad)18 lines

Raw file

import numpy as np, wave, json
SR=44100; T=json.load(open(__import__("os").environ.get("TM","timing.json")))["total"]
n=int(T*SR); t=np.arange(n)/SR
chords=[[57,60,64],[53,57,60],[48,52,55],[55,59,62]]  # Am F C G
f=lambda m:440*2**((m-69)/12)
out=np.zeros(n); L=4.0
for k in range(int(T/L)+1):
    s=int(k*L*SR); e=min(n,int((k*L+L+1.5)*SR))
    if s>=n: break
    tt=t[s:e]-k*L
    env=np.minimum(1,tt/1.2)*np.clip((L+1.5-tt)/1.5,0,1)
    for m in chords[k%4]+[chords[k%4][0]-12]:
        out[s:e]+=env*(np.sin(2*np.pi*f(m)*tt)+0.25*np.sin(2*np.pi*2*f(m)*tt+1))*0.2
out*= np.minimum(1,t/2)*np.clip((T-t)/2.5,0,1)
out/=np.abs(out).max()
with wave.open("music.wav","wb") as w:
    w.setnchannels(1);w.setsampwidth(2);w.setframerate(SR);w.writeframes((out*0.9*32767).astype(np.int16).tobytes())

Need an interactive piece for your business or audience?

A product explainer, a training walkthrough, a simulation people can play with. This one is free to take. I can build yours for a fixed price agreed up front, and the first call is free.

How it works and what it costs Book a free call ↗

Or write to me · how to use what is here