silueta-studio 0.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. silueta_studio-0.1.1/LICENSE +21 -0
  2. silueta_studio-0.1.1/PKG-INFO +121 -0
  3. silueta_studio-0.1.1/README.md +101 -0
  4. silueta_studio-0.1.1/pyproject.toml +34 -0
  5. silueta_studio-0.1.1/setup.cfg +4 -0
  6. silueta_studio-0.1.1/silueta_studio/__init__.py +16 -0
  7. silueta_studio-0.1.1/silueta_studio/__main__.py +3 -0
  8. silueta_studio-0.1.1/silueta_studio/alinhar.py +84 -0
  9. silueta_studio-0.1.1/silueta_studio/audio.py +118 -0
  10. silueta_studio-0.1.1/silueta_studio/camara.py +72 -0
  11. silueta_studio-0.1.1/silueta_studio/canvas.py +143 -0
  12. silueta_studio-0.1.1/silueta_studio/cenas.py +22 -0
  13. silueta_studio-0.1.1/silueta_studio/cli.py +115 -0
  14. silueta_studio-0.1.1/silueta_studio/config.py +47 -0
  15. silueta_studio-0.1.1/silueta_studio/efeitos.py +133 -0
  16. silueta_studio-0.1.1/silueta_studio/figuras.py +65 -0
  17. silueta_studio-0.1.1/silueta_studio/historia.py +75 -0
  18. silueta_studio-0.1.1/silueta_studio/karaoke.py +93 -0
  19. silueta_studio-0.1.1/silueta_studio/modelo/cenas.py +104 -0
  20. silueta_studio-0.1.1/silueta_studio/modelo/historia.json +9 -0
  21. silueta_studio-0.1.1/silueta_studio/montagem.py +236 -0
  22. silueta_studio-0.1.1/silueta_studio/palavras.py +90 -0
  23. silueta_studio-0.1.1/silueta_studio/qa.py +204 -0
  24. silueta_studio-0.1.1/silueta_studio/texto.py +52 -0
  25. silueta_studio-0.1.1/silueta_studio.egg-info/PKG-INFO +121 -0
  26. silueta_studio-0.1.1/silueta_studio.egg-info/SOURCES.txt +29 -0
  27. silueta_studio-0.1.1/silueta_studio.egg-info/dependency_links.txt +1 -0
  28. silueta_studio-0.1.1/silueta_studio.egg-info/entry_points.txt +2 -0
  29. silueta_studio-0.1.1/silueta_studio.egg-info/requires.txt +6 -0
  30. silueta_studio-0.1.1/silueta_studio.egg-info/top_level.txt +1 -0
  31. silueta_studio-0.1.1/tests/test_kit.py +138 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Silueta Studio contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,121 @@
1
+ Metadata-Version: 2.4
2
+ Name: silueta-studio
3
+ Version: 0.1.1
4
+ Summary: Vertical story videos with 2D silhouettes, rim light and karaoke captions, built for Claude Code.
5
+ Author: Silueta Studio
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/silueta-studio/silueta-studio
8
+ Project-URL: Repository, https://github.com/silueta-studio/silueta-studio
9
+ Project-URL: Issues, https://github.com/silueta-studio/silueta-studio/issues
10
+ Keywords: video,shorts,animation,silhouette,karaoke,claude-code,whisperx
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: numpy>=1.24
15
+ Requires-Dist: pillow>=10.1
16
+ Requires-Dist: scipy>=1.10
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest>=8; extra == "dev"
19
+ Dynamic: license-file
20
+
21
+ # Silueta Studio
22
+
23
+ [![tests](https://github.com/silueta-studio/silueta-studio/actions/workflows/testes.yml/badge.svg)](https://github.com/silueta-studio/silueta-studio/actions/workflows/testes.yml)
24
+
25
+ **Vertical story videos — 2D silhouettes, rim light, parallax and karaoke captions — drawn in pure Python and directed by Claude Code.**
26
+
27
+ [English](#english) · [Español](#español)
28
+
29
+ <p align="center"><img src="https://raw.githubusercontent.com/silueta-studio/silueta-studio/main/docs/demo.gif" width="270" alt="10-second demo: a lighthouse at sunset, at night and at dawn, with karaoke captions"></p>
30
+
31
+ ---
32
+
33
+ ## English
34
+
35
+ `silueta` turns a shot-by-shot script into a finished 1080×1920 video: original silhouettes drawn in code (no stock images),
36
+ 3–5 parallax layers, rim light, film grain, spring-in title cards, word-by-word karaoke synced to your real voice-over,
37
+ and automatic quality gates. It is the engine behind a faceless "true stories" channel, packaged so that
38
+ [Claude Code](https://claude.com/claude-code) can research, write, draw, render and check a video with you.
39
+
40
+ ### What you get
41
+ - **A Python engine** (numpy + Pillow + SciPy + ffmpeg): camera push/parallax, terrain ridges, skies, sun/moon, light rays,
42
+ embers, people, birds, ships, sprite compositing, transitions (dissolve, fade-to-black, white flash, whip pan).
43
+ - **Karaoke captions** in the safe zone, with the active word popping in yellow; long words shrink to fit.
44
+ - **Forced alignment** with WhisperX: real timings per shot and per word, numbers mapped back to your script ("6" ↔ "seis").
45
+ - **Audio mix**: voice levelling, your music ~20 dB under the voice (+5 dB in pauses), SFX ducking, −14 LUFS loudness.
46
+ - **Parallel, resumable render** to H.264 High (CRF 17, GOP 60) plus a ≤ 30 MB review copy.
47
+ - **QA gates**: seedless randomness, missing glyphs, reading speed, dead air, too-short shots, flashes (> 3/s fails), loudness/true peak.
48
+ - **Claude Code setup**: `CLAUDE.md` with the craft rules, and 4 agents — `researcher`, `scriptwriter`, `scene-designer`, `render-qa`.
49
+
50
+ ### Install (≈ 10 min)
51
+ Needs Python ≥ 3.10 and [ffmpeg](https://ffmpeg.org/download.html) on your PATH.
52
+ ```
53
+ git clone https://github.com/silueta-studio/silueta-studio && cd silueta-studio
54
+ python -m venv .venv
55
+ .venv/Scripts/activate # Linux/macOS: source .venv/bin/activate
56
+ pip install .
57
+ silueta -h
58
+ ```
59
+ Optional, for real voice timings: install [WhisperX](https://github.com/m-bain/whisperX) in its own venv (it brings PyTorch, ~3 GB)
60
+ and pass its Python with `--python`.
61
+
62
+ ### Make a video
63
+ ```
64
+ silueta new my_story # copies the example (historia.json + cenas.py)
65
+ silueta sheet my_story # contact sheet (1 frame per shot) + safe-zone QA -> my_story/prova.png
66
+ # record one voice file per shot: my_story/voz/s01.mp3, s02.mp3, ...
67
+ silueta align my_story --python <whisperx-venv>/Scripts/python
68
+ silueta mix my_story # voice + your licensed music/SFX declared in historia.json
69
+ silueta render my_story # -> final.mp4 + final_revisao.mp4
70
+ silueta qa my_story
71
+ ```
72
+ If Windows blocks `silueta.exe`, run the same commands as `python -m silueta_studio <command>`.
73
+ Without a voice yet, `render --force` uses estimated timings (for tests only).
74
+ With Claude Code, just open the folder and ask: *"make a 90-second video about <story>"* — the agents follow `CLAUDE.md`.
75
+
76
+ <p align="center"><img src="https://raw.githubusercontent.com/silueta-studio/silueta-studio/main/docs/prova.png" width="600" alt="Contact sheet of the example story"></p>
77
+
78
+ ### Rules the kit enforces
79
+ Two independent sources per fact · no photos, logos or third-party characters · music and SFX only from files **you** own a licence for
80
+ (none are bundled) · nothing is published or paid for without your explicit OK.
81
+
82
+ ### Speed
83
+ About 0.85 s per frame on one core; the parallel render uses physical cores − 1 (7 processes: ~0.28 s/frame, so a 2-minute video ≈ 15 min).
84
+
85
+ ### Licence
86
+ MIT — see `LICENSE`. Third-party code and ideas: `THIRD_PARTY.md`.
87
+
88
+ ---
89
+
90
+ ## Español
91
+
92
+ `silueta` convierte un guion por planos en un vídeo vertical terminado (1080×1920): siluetas originales dibujadas en código
93
+ (sin bancos de imágenes), 3–5 capas con paralaje, luz de recorte, grano, carteles con rebote, subtítulos karaoke palabra a palabra
94
+ sincronizados con tu voz real y controles de calidad automáticos. Es el motor de un canal de "historias reales que parecen inventadas",
95
+ empaquetado para que [Claude Code](https://claude.com/claude-code) investigue, escriba, dibuje, renderice y revise un vídeo contigo.
96
+
97
+ ### Qué incluye
98
+ - **Motor en Python** (numpy + Pillow + SciPy + ffmpeg): cámara con paralaje, crestas de terreno, cielos, sol/luna, rayos de luz,
99
+ brasas, personas, aves, barcos, sprites y transiciones (fundido, negro, destello blanco, barrido).
100
+ - **Karaoke** dentro de la zona segura, con la palabra activa en amarillo; las palabras largas se encogen para caber.
101
+ - **Alineación forzada** con WhisperX: tiempos reales por plano y por palabra; los números vuelven al guion ("6" ↔ "seis").
102
+ - **Mezcla**: voz nivelada, tu música ~20 dB bajo la voz (+5 dB en las pausas), efectos con ducking, −14 LUFS.
103
+ - **Render en paralelo y reanudable** a H.264 High (CRF 17, GOP 60) y una copia de revisión de ≤ 30 MB.
104
+ - **Controles de calidad**: aleatoriedad sin semilla, glifos que faltan, velocidad de lectura, huecos muertos, planos demasiado cortos,
105
+ destellos (> 3/s falla), sonoridad y pico real.
106
+ - **Claude Code**: `CLAUDE.md` con las reglas del oficio y 4 agentes — `researcher`, `scriptwriter`, `scene-designer`, `render-qa`.
107
+
108
+ ### Instalación (≈ 10 min)
109
+ Python ≥ 3.10 y [ffmpeg](https://ffmpeg.org/download.html) en el PATH; los comandos son los de arriba.
110
+ Opcional: [WhisperX](https://github.com/m-bain/whisperX) en su propio venv para los tiempos reales de la voz (`--python`).
111
+
112
+ ### Hacer un vídeo
113
+ `new` → `sheet` → grabar `voz/s01.mp3…` → `align` → `mix` → `render` → `qa` (ver arriba).
114
+ Con Claude Code: abre la carpeta y pide *"haz un vídeo de 90 segundos sobre <historia>"*.
115
+
116
+ ### Reglas
117
+ Dos fuentes independientes por dato · nada de fotos, logos ni personajes ajenos · música y efectos solo con licencia tuya
118
+ (el kit no trae ninguno) · nada se publica ni se paga sin tu permiso explícito.
119
+
120
+ ### Licencia
121
+ MIT — ver `LICENSE`. Código e ideas de terceros: `THIRD_PARTY.md`.
@@ -0,0 +1,101 @@
1
+ # Silueta Studio
2
+
3
+ [![tests](https://github.com/silueta-studio/silueta-studio/actions/workflows/testes.yml/badge.svg)](https://github.com/silueta-studio/silueta-studio/actions/workflows/testes.yml)
4
+
5
+ **Vertical story videos — 2D silhouettes, rim light, parallax and karaoke captions — drawn in pure Python and directed by Claude Code.**
6
+
7
+ [English](#english) · [Español](#español)
8
+
9
+ <p align="center"><img src="https://raw.githubusercontent.com/silueta-studio/silueta-studio/main/docs/demo.gif" width="270" alt="10-second demo: a lighthouse at sunset, at night and at dawn, with karaoke captions"></p>
10
+
11
+ ---
12
+
13
+ ## English
14
+
15
+ `silueta` turns a shot-by-shot script into a finished 1080×1920 video: original silhouettes drawn in code (no stock images),
16
+ 3–5 parallax layers, rim light, film grain, spring-in title cards, word-by-word karaoke synced to your real voice-over,
17
+ and automatic quality gates. It is the engine behind a faceless "true stories" channel, packaged so that
18
+ [Claude Code](https://claude.com/claude-code) can research, write, draw, render and check a video with you.
19
+
20
+ ### What you get
21
+ - **A Python engine** (numpy + Pillow + SciPy + ffmpeg): camera push/parallax, terrain ridges, skies, sun/moon, light rays,
22
+ embers, people, birds, ships, sprite compositing, transitions (dissolve, fade-to-black, white flash, whip pan).
23
+ - **Karaoke captions** in the safe zone, with the active word popping in yellow; long words shrink to fit.
24
+ - **Forced alignment** with WhisperX: real timings per shot and per word, numbers mapped back to your script ("6" ↔ "seis").
25
+ - **Audio mix**: voice levelling, your music ~20 dB under the voice (+5 dB in pauses), SFX ducking, −14 LUFS loudness.
26
+ - **Parallel, resumable render** to H.264 High (CRF 17, GOP 60) plus a ≤ 30 MB review copy.
27
+ - **QA gates**: seedless randomness, missing glyphs, reading speed, dead air, too-short shots, flashes (> 3/s fails), loudness/true peak.
28
+ - **Claude Code setup**: `CLAUDE.md` with the craft rules, and 4 agents — `researcher`, `scriptwriter`, `scene-designer`, `render-qa`.
29
+
30
+ ### Install (≈ 10 min)
31
+ Needs Python ≥ 3.10 and [ffmpeg](https://ffmpeg.org/download.html) on your PATH.
32
+ ```
33
+ git clone https://github.com/silueta-studio/silueta-studio && cd silueta-studio
34
+ python -m venv .venv
35
+ .venv/Scripts/activate # Linux/macOS: source .venv/bin/activate
36
+ pip install .
37
+ silueta -h
38
+ ```
39
+ Optional, for real voice timings: install [WhisperX](https://github.com/m-bain/whisperX) in its own venv (it brings PyTorch, ~3 GB)
40
+ and pass its Python with `--python`.
41
+
42
+ ### Make a video
43
+ ```
44
+ silueta new my_story # copies the example (historia.json + cenas.py)
45
+ silueta sheet my_story # contact sheet (1 frame per shot) + safe-zone QA -> my_story/prova.png
46
+ # record one voice file per shot: my_story/voz/s01.mp3, s02.mp3, ...
47
+ silueta align my_story --python <whisperx-venv>/Scripts/python
48
+ silueta mix my_story # voice + your licensed music/SFX declared in historia.json
49
+ silueta render my_story # -> final.mp4 + final_revisao.mp4
50
+ silueta qa my_story
51
+ ```
52
+ If Windows blocks `silueta.exe`, run the same commands as `python -m silueta_studio <command>`.
53
+ Without a voice yet, `render --force` uses estimated timings (for tests only).
54
+ With Claude Code, just open the folder and ask: *"make a 90-second video about <story>"* — the agents follow `CLAUDE.md`.
55
+
56
+ <p align="center"><img src="https://raw.githubusercontent.com/silueta-studio/silueta-studio/main/docs/prova.png" width="600" alt="Contact sheet of the example story"></p>
57
+
58
+ ### Rules the kit enforces
59
+ Two independent sources per fact · no photos, logos or third-party characters · music and SFX only from files **you** own a licence for
60
+ (none are bundled) · nothing is published or paid for without your explicit OK.
61
+
62
+ ### Speed
63
+ About 0.85 s per frame on one core; the parallel render uses physical cores − 1 (7 processes: ~0.28 s/frame, so a 2-minute video ≈ 15 min).
64
+
65
+ ### Licence
66
+ MIT — see `LICENSE`. Third-party code and ideas: `THIRD_PARTY.md`.
67
+
68
+ ---
69
+
70
+ ## Español
71
+
72
+ `silueta` convierte un guion por planos en un vídeo vertical terminado (1080×1920): siluetas originales dibujadas en código
73
+ (sin bancos de imágenes), 3–5 capas con paralaje, luz de recorte, grano, carteles con rebote, subtítulos karaoke palabra a palabra
74
+ sincronizados con tu voz real y controles de calidad automáticos. Es el motor de un canal de "historias reales que parecen inventadas",
75
+ empaquetado para que [Claude Code](https://claude.com/claude-code) investigue, escriba, dibuje, renderice y revise un vídeo contigo.
76
+
77
+ ### Qué incluye
78
+ - **Motor en Python** (numpy + Pillow + SciPy + ffmpeg): cámara con paralaje, crestas de terreno, cielos, sol/luna, rayos de luz,
79
+ brasas, personas, aves, barcos, sprites y transiciones (fundido, negro, destello blanco, barrido).
80
+ - **Karaoke** dentro de la zona segura, con la palabra activa en amarillo; las palabras largas se encogen para caber.
81
+ - **Alineación forzada** con WhisperX: tiempos reales por plano y por palabra; los números vuelven al guion ("6" ↔ "seis").
82
+ - **Mezcla**: voz nivelada, tu música ~20 dB bajo la voz (+5 dB en las pausas), efectos con ducking, −14 LUFS.
83
+ - **Render en paralelo y reanudable** a H.264 High (CRF 17, GOP 60) y una copia de revisión de ≤ 30 MB.
84
+ - **Controles de calidad**: aleatoriedad sin semilla, glifos que faltan, velocidad de lectura, huecos muertos, planos demasiado cortos,
85
+ destellos (> 3/s falla), sonoridad y pico real.
86
+ - **Claude Code**: `CLAUDE.md` con las reglas del oficio y 4 agentes — `researcher`, `scriptwriter`, `scene-designer`, `render-qa`.
87
+
88
+ ### Instalación (≈ 10 min)
89
+ Python ≥ 3.10 y [ffmpeg](https://ffmpeg.org/download.html) en el PATH; los comandos son los de arriba.
90
+ Opcional: [WhisperX](https://github.com/m-bain/whisperX) en su propio venv para los tiempos reales de la voz (`--python`).
91
+
92
+ ### Hacer un vídeo
93
+ `new` → `sheet` → grabar `voz/s01.mp3…` → `align` → `mix` → `render` → `qa` (ver arriba).
94
+ Con Claude Code: abre la carpeta y pide *"haz un vídeo de 90 segundos sobre <historia>"*.
95
+
96
+ ### Reglas
97
+ Dos fuentes independientes por dato · nada de fotos, logos ni personajes ajenos · música y efectos solo con licencia tuya
98
+ (el kit no trae ninguno) · nada se publica ni se paga sin tu permiso explícito.
99
+
100
+ ### Licencia
101
+ MIT — ver `LICENSE`. Código e ideas de terceros: `THIRD_PARTY.md`.
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "silueta-studio"
7
+ version = "0.1.1"
8
+ description = "Vertical story videos with 2D silhouettes, rim light and karaoke captions, built for Claude Code."
9
+ readme = "README.md"
10
+ authors = [{ name = "Silueta Studio" }]
11
+ keywords = ["video", "shorts", "animation", "silhouette", "karaoke", "claude-code", "whisperx"]
12
+ license = { text = "MIT" }
13
+ requires-python = ">=3.10"
14
+ dependencies = ["numpy>=1.24", "pillow>=10.1", "scipy>=1.10"]
15
+
16
+ [project.urls]
17
+ Homepage = "https://github.com/silueta-studio/silueta-studio"
18
+ Repository = "https://github.com/silueta-studio/silueta-studio"
19
+ Issues = "https://github.com/silueta-studio/silueta-studio/issues"
20
+
21
+ [project.optional-dependencies]
22
+ dev = ["pytest>=8"]
23
+
24
+ [project.scripts]
25
+ silueta = "silueta_studio.cli:main"
26
+
27
+ [tool.setuptools]
28
+ packages = ["silueta_studio"]
29
+
30
+ [tool.setuptools.package-data]
31
+ silueta_studio = ["modelo/*"]
32
+
33
+ [tool.pytest.ini_options]
34
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,16 @@
1
+ """Silueta Studio — vertical story videos with 2D silhouettes, rim light and karaoke captions.
2
+
3
+ Use in a story (cenas.py):
4
+ from silueta_studio import cena, push, sky, terr, fg, fin, pessoa, card
5
+ """
6
+ __version__ = "0.1.1"
7
+
8
+ from .camara import Cam, fg, push, ridge, sky, terr
9
+ from .canvas import R, addglow, blank, ease, font, full, grade, mask_full, smooth_noise, spring, vgrad, xf
10
+ from .cenas import cena
11
+ from .config import FPS, H, MARGIN, SAFE_Y0, SAFE_Y1, W
12
+ from .efeitos import brasas, chispas, disco, fin, flashk, grain, haze, rayos, softblob, sombra, temblor
13
+ from .figuras import ave, barco, pessoa, put
14
+ from .texto import card, fit, hud, label, topband
15
+
16
+ __all__ = [n for n in dir() if not n.startswith("_")]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
@@ -0,0 +1,84 @@
1
+ """Forced alignment of the voice-over with WhisperX (wav2vec2, NO transcription): real timings per shot and per word.
2
+
3
+ STANDALONE script (stdlib + numpy + whisperx + ffmpeg only), run with the Python of the venv where WhisperX is installed:
4
+ <python-with-whisperx> alinhar.py <story-folder>
5
+ `silueta align <folder> --python <...>` calls it this way and then maps the spoken words onto the caption text.
6
+
7
+ Input: historia.json + voz/s01.mp3 (or .wav), voz/s02.mp3, ... (one file per shot, name = lower-case shot id).
8
+ Spoken text = shot["fala"] if present (e.g. "GTA seis"), otherwise shot["voz"].
9
+ Output: timing.json [{id,start,dur,voice}], words_whisperx.json {id: [[word, t0, t1], ...]} (absolute time),
10
+ voz.wav (trimmed and joined voice, 48 kHz), alinhamento.txt (report).
11
+ Trim: 0.12 s before the first word and 0.30 s after the last; shot["golpe"] = silence before, shot["cola"] = silence after.
12
+ """
13
+ import difflib
14
+ import json
15
+ import re
16
+ import subprocess
17
+ import sys
18
+ import unicodedata
19
+ from pathlib import Path
20
+
21
+ import numpy as np
22
+
23
+ SR = 48000; ASR = 16000; PAD_IN, PAD_OUT = 0.12, 0.30
24
+
25
+
26
+ def load(path, sr):
27
+ raw = subprocess.check_output(["ffmpeg", "-v", "error", "-i", str(path), "-ac", "1", "-ar", str(sr), "-f", "f32le", "-"])
28
+ return np.frombuffer(raw, np.float32).copy()
29
+
30
+
31
+ def norm(s):
32
+ s = unicodedata.normalize("NFD", s.lower()); s = "".join(c for c in s if unicodedata.category(c) != "Mn")
33
+ return re.sub(r"[^a-z0-9]", "", s)
34
+
35
+
36
+ def voz_de(pasta, sid):
37
+ for ext in (".mp3", ".wav", ".m4a", ".flac"):
38
+ p = pasta / "voz" / (sid.lower() + ext)
39
+ if p.exists(): return p
40
+ raise SystemExit(f"missing voice file for shot {sid}: {pasta / 'voz' / (sid.lower() + '.mp3')}")
41
+
42
+
43
+ def main(pasta):
44
+ for s in (sys.stdout, sys.stderr):
45
+ try: s.reconfigure(encoding="utf-8")
46
+ except Exception: pass
47
+ pasta = Path(pasta).resolve()
48
+ cfg = json.loads((pasta / "historia.json").read_text(encoding="utf-8-sig")); planos = cfg["planos"]
49
+ fontes = {q["id"]: voz_de(pasta, q["id"]) for q in planos} # falha cedo, antes de carregar o modelo
50
+ import torch
51
+ import whisperx
52
+ dev = "cuda" if torch.cuda.is_available() else "cpu"
53
+ model, meta = whisperx.load_align_model(language_code=cfg.get("idioma", "es"), device=dev)
54
+ tracks, timing, spoken, rep = [], [], {}, []; t = 0.0
55
+ for q in planos:
56
+ sid = q["id"]; a = load(fontes[sid], SR); a16 = load(fontes[sid], ASR); ftxt = " ".join((q.get("fala") or q["voz"]).split())
57
+ res = whisperx.align([{"start": 0.0, "end": len(a16) / ASR, "text": ftxt}], model, meta, a16, dev, return_char_alignments=False)
58
+ ws = [w for s in res["segments"] for w in s.get("words", [])]
59
+ if not ws: raise SystemExit(f"{sid}: alignment returned no words (does the voice match the text?)")
60
+ for i, w in enumerate(ws): # palavras sem tempo: interpolar
61
+ if w.get("start") is None:
62
+ pv = next((ws[j]["end"] for j in range(i - 1, -1, -1) if ws[j].get("end") is not None), 0.0)
63
+ nx = next((ws[j]["start"] for j in range(i + 1, len(ws)) if ws[j].get("start") is not None), pv + 0.2)
64
+ w["start"], w["end"] = pv, max(pv, nx)
65
+ elif w.get("end") is None: w["end"] = w["start"] + 0.15
66
+ lead = float(q.get("golpe", 0.0)); cola = float(q.get("cola", 0.0))
67
+ c0 = max(0.0, ws[0]["start"] - PAD_IN); c1 = min(len(a) / SR, ws[-1]["end"] + PAD_OUT)
68
+ clip = np.concatenate([np.zeros(int(lead * SR), np.float32), a[int(c0 * SR):int(c1 * SR)], np.zeros(int(cola * SR), np.float32)])
69
+ dur = round(len(clip) / SR, 3); sh = lead - c0
70
+ timing.append(dict(id=sid, start=round(t, 3), dur=dur, voice=q["voz"]))
71
+ spoken[sid] = [[w["word"], round(t + w["start"] + sh, 3), round(t + w["end"] + sh, 3)] for w in ws]
72
+ heard = " ".join(w["word"] for w in ws); ratio = difflib.SequenceMatcher(None, norm(ftxt), norm(heard)).ratio()
73
+ rep.append(f"{sid} {t:7.2f}s dur {dur:5.2f}s {len(ws)} words ({len(ws) / dur:.2f}/s) match {ratio:.2f}\n {ftxt}")
74
+ print(rep[-1], flush=True); tracks.append(clip); t += dur
75
+ (pasta / "timing.json").write_text(json.dumps(timing, ensure_ascii=False, indent=1), encoding="utf-8")
76
+ (pasta / "words_whisperx.json").write_text(json.dumps(spoken, ensure_ascii=False), encoding="utf-8")
77
+ pcm = (np.clip(np.concatenate(tracks), -1, 1) * 32767).astype("<i2").tobytes()
78
+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "s16le", "-ar", str(SR), "-ac", "1", "-i", "-", str(pasta / "voz.wav")], input=pcm, check=True)
79
+ rep.append(f"TOTAL {t:.2f} s"); (pasta / "alinhamento.txt").write_text("\n".join(rep), encoding="utf-8"); print(f"TOTAL {t:.2f} s")
80
+
81
+
82
+ if __name__ == "__main__":
83
+ if len(sys.argv) != 2: raise SystemExit("usage: python alinhar.py <story-folder>")
84
+ main(sys.argv[1])
@@ -0,0 +1,118 @@
1
+ """Mix: voice (voz.wav from `silueta align`) + music and sound effects YOU PROVIDE (with a licence) -> mistura.wav at -14 LUFS.
2
+
3
+ The kit ships no music or effects. Declare them in historia.json (paths relative to the story folder):
4
+ "musica": {"faixa": "som/my_track.mp3", "entra": "S02", "alinhar": "fim", "gain_db": 0,
5
+ "cortes": [["S06", "inicio"]]} # hard 0.35 s silence right before shot S06 starts
6
+ "sfx": [{"ficheiro": "som/impact.wav", "plano": "S01", "palavra": "cuarenta", "gain_db": -3},
7
+ {"ficheiro": "som/wind.wav", "plano": "S02", "t": 0.0, "gain_db": -12}]
8
+ "entra" = shot id or seconds; "alinhar": "fim" uses the end of the track (its ending lands on the video's end), "inicio" its start.
9
+ Levels: voice -20 dBFS RMS per shot; music ~20 dB under the voice and +5 dB in pauses; effects ducked -8 dB under
10
+ the voice; two-pass loudnorm to -14 LUFS, true peak <= -1.5 dBTP. One long track, never looped.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import re
16
+ import subprocess
17
+ from pathlib import Path
18
+
19
+ import numpy as np
20
+ from scipy.io import wavfile
21
+ from scipy.signal import butter, sosfilt
22
+
23
+ SR = 48000
24
+ LN = "loudnorm=I=-13.7:TP=-1.5:LRA=11"
25
+
26
+
27
+ def ler(path, n=None) -> np.ndarray:
28
+ raw = subprocess.check_output(["ffmpeg", "-v", "error", "-i", str(path), "-ac", "1", "-ar", str(SR), "-f", "f32le", "-"])
29
+ x = np.frombuffer(raw, np.float32).copy()
30
+ return x if n is None else np.pad(x, (0, max(0, n - len(x))))[:n]
31
+
32
+
33
+ def _rms_db(x):
34
+ act = x[np.abs(x) > 0.01 * max(1e-6, np.abs(x).max())]
35
+ return 20 * np.log10(np.sqrt((act ** 2).mean()) + 1e-9) if len(act) else -120.0
36
+
37
+
38
+ def _env(x, att, rel, step=48):
39
+ """Envolvente 0..1 de presença com ataque/libertação (segundos)."""
40
+ n = len(x); h = int(0.02 * SR); e = np.sqrt(np.convolve(x ** 2, np.ones(h) / h, "same")); pres = (e > 0.01).astype(np.float32)
41
+ ka = 1 - np.exp(-step / (att * SR)); kr = 1 - np.exp(-step / (rel * SR)); y = np.zeros(n, np.float32); v = 0.0
42
+ for i in range(0, n, step):
43
+ p = float(pres[i:i + step].max()); v += (ka if p > v else kr) * (p - v); y[i:i + step] = v
44
+ return y
45
+
46
+
47
+ def misturar(pasta) -> Path:
48
+ pasta = Path(pasta).resolve(); cfg = json.loads((pasta / "historia.json").read_text(encoding="utf-8-sig"))
49
+ tp = pasta / "timing.json"; vp = pasta / "voz.wav"
50
+ if not (tp.exists() and vp.exists()): raise SystemExit("missing timing.json/voz.wav: run `silueta align` first")
51
+ T = json.loads(tp.read_text(encoding="utf-8")); S = {x["id"]: x for x in T}
52
+ W = json.loads((pasta / "words_whisperx.json").read_text(encoding="utf-8")) if (pasta / "words_whisperx.json").exists() else {}
53
+ TOT = T[-1]["start"] + T[-1]["dur"]; n = int(round(TOT * SR)); tt = np.arange(n) / SR
54
+
55
+ # voz: −20 dBFS RMS por plano + passa-altos 70 Hz
56
+ voz = ler(vp, n)
57
+ for x in T:
58
+ i, j = int(x["start"] * SR), min(n, int((x["start"] + x["dur"]) * SR)); c = voz[i:j]
59
+ if len(c): voz[i:j] = c * 10 ** ((-20 - _rms_db(c)) / 20)
60
+ voz = sosfilt(butter(2, 70, "highpass", fs=SR, output="sos"), voz).astype(np.float32)
61
+ pres = _env(voz, 0.08, 0.4)
62
+
63
+ def t_de(plano, palavra=None, t=0.0):
64
+ if plano not in S: raise SystemExit(f"unknown shot in historia.json: {plano}")
65
+ if palavra:
66
+ pref = re.sub(r"\W", "", palavra.lower())
67
+ for w, a, _ in W.get(plano, []):
68
+ if re.sub(r"\W", "", w.lower()).startswith(pref): return a + t
69
+ print(f"warning: word {palavra!r} not found in {plano}; using the start of the shot")
70
+ return S[plano]["start"] + t
71
+
72
+ # efeitos: colocados por plano/palavra, ducking −8 dB sob a voz
73
+ sfx = np.zeros(n, np.float32)
74
+ for e in cfg.get("sfx", []):
75
+ x = ler(pasta / e["ficheiro"]) * 10 ** (e.get("gain_db", 0) / 20); i = int(t_de(e["plano"], e.get("palavra"), e.get("t", 0.0)) * SR)
76
+ if i < n: sfx[i:i + len(x)] += x[:n - i]
77
+ duck = 1 - (1 - 10 ** (-8 / 20)) * pres
78
+
79
+ # música: uma faixa longa, RMS ativo −40 dBFS (≈20 dB sob a voz), +5 dB nas pausas, entrada e saída suaves
80
+ mus = np.zeros(n, np.float32); m = cfg.get("musica")
81
+ if m:
82
+ base = ler(pasta / m["faixa"]); ent = m.get("entra", 0.0)
83
+ t_in = max(0.0, (S[ent]["start"] - 0.3) if isinstance(ent, str) else float(ent)); t_out = TOT - 0.05
84
+ need = int((t_out - t_in) * SR)
85
+ if len(base) < need: raise SystemExit("the music track is shorter than the video: pick a longer one (never loop it)")
86
+ seg = base[len(base) - need:] if m.get("alinhar", "fim") == "fim" else base[:need]
87
+ i0 = int(t_in * SR); mus[i0:i0 + need] = seg * 10 ** ((-40 + m.get("gain_db", 0) - _rms_db(seg)) / 20)
88
+ kf = lambda pts: np.interp(tt, [p[0] for p in pts], [p[1] for p in pts])
89
+ g = 5.0 * (1 - pres) + kf([(0, -60), (t_in, -60), (t_in + 1.6, 0), (t_out - 1.6, 0), (t_out, -60), (TOT + 0.01, -60)])
90
+ for plano, onde in m.get("cortes", []):
91
+ tc = S[plano]["start"] if onde == "inicio" else S[plano]["start"] + S[plano]["dur"]
92
+ g += kf([(0, 0), (tc - 0.45, 0), (tc - 0.35, -60), (tc + 0.05, -60), (tc + 0.4, 0), (TOT + 0.01, 0)])
93
+ mus = (mus * 10 ** (g / 20)).astype(np.float32); mus[g < -59] = 0.0
94
+
95
+ mix = voz + sfx * duck + mus
96
+ raw = pasta / "mistura_bruta.wav"; wavfile.write(raw, SR, (np.clip(mix, -1, 1) * 32767).astype(np.int16))
97
+ meas = _loud(raw)
98
+ af = (f"{LN}:measured_I={meas['input_i']}:measured_TP={meas['input_tp']}:measured_LRA={meas['input_lra']}"
99
+ f":measured_thresh={meas['input_thresh']}:offset={meas['target_offset']}:linear=true,volume=-0.5dB,aresample={SR}")
100
+ dst = pasta / "mistura.wav"
101
+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", str(raw), "-af", af, "-ar", str(SR), str(dst)], check=True); raw.unlink()
102
+ c = _loud(dst)
103
+ print(f"mix: {dst} {TOT:.2f} s | {c['input_i']} LUFS | true peak {c['input_tp']} dBTP | music: {'yes' if m else 'no'} | sfx: {len(cfg.get('sfx', []))}")
104
+ return dst
105
+
106
+
107
+ def _loud(path) -> dict:
108
+ out = subprocess.run(["ffmpeg", "-hide_banner", "-i", str(path), "-af", LN + ":print_format=json", "-f", "null", "-"],
109
+ capture_output=True, text=True, encoding="utf-8", errors="replace").stderr
110
+ return json.loads(re.findall(r"\{[^{}]*\}", out)[-1])
111
+
112
+
113
+ def remux(video: Path, audio: Path, dur: float):
114
+ """Troca só o áudio de um vídeo já renderizado (vídeo copiado, sem novo render)."""
115
+ tmp = video.with_suffix(".audio_tmp.mp4")
116
+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", str(video), "-i", str(audio), "-map", "0:v:0", "-map", "1:a:0", "-t", f"{dur:.3f}",
117
+ "-c:v", "copy", "-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-movflags", "+faststart", str(tmp)], check=True)
118
+ tmp.replace(video)
@@ -0,0 +1,72 @@
1
+ """Câmara com paralaxe e camadas de cenário (céu, cristas de terreno, primeiro plano desfocado).
2
+
3
+ Style rule: 3–5 camadas, o longe mais claro, o primeiro plano escuro e desfocado, personagens ENTRE camadas.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import math
8
+
9
+ import numpy as np
10
+ from PIL import Image, ImageDraw
11
+ from scipy.ndimage import gaussian_filter
12
+
13
+ from .canvas import full, vgrad
14
+ from .config import H, W
15
+
16
+
17
+ class Cam:
18
+ """Push-in por camadas: cada camada aproxima (z-1)*par e desloca pan*par. Âncora vertical em ay."""
19
+
20
+ def __init__(s, z=1.0, pan=0.0, ay=1230):
21
+ s.z, s.pan, s.ay = z, pan, ay
22
+
23
+ def ts(s, x, y, par=1.0):
24
+ zl = 1 + (s.z - 1) * par
25
+ return 540 + (x - 540) * zl - s.pan * par, s.ay + (y - s.ay) * zl, zl
26
+
27
+
28
+ def push(tl, z1=0.06, rate=0.6, pan=0.0, ay=1230) -> Cam:
29
+ """Câmara que se aproxima suavemente ao longo do plano (tl = tempo local)."""
30
+ return Cam(1 + z1 * (1 - math.exp(-rate * tl)), pan * tl, ay)
31
+
32
+
33
+ _SK: dict = {}
34
+
35
+
36
+ def sky(f, key, stops):
37
+ """Céu em degradé (em cache por chave)."""
38
+ if key not in _SK: _SK[key] = vgrad(stops)
39
+ f[...] = _SK[key]
40
+
41
+
42
+ def ridge(seed, x, base, amp, freq=1.0):
43
+ rr = np.random.default_rng(seed); ph = rr.uniform(0, 6.3, 4)
44
+ return base - amp * (0.5 * np.sin(x * 0.0021 * freq + ph[0]) + 0.3 * np.sin(x * 0.0057 * freq + ph[1])
45
+ + 0.14 * np.sin(x * 0.013 * freq + ph[2]) + 0.06 * np.sin(x * 0.041 * freq + ph[3]))
46
+
47
+
48
+ def terr(f, C: Cam, par, seed, base, amp, col, freq=1.0, peak=None, a=1.0):
49
+ """Camada de terreno com crista de ruído; peak=(x, altura, largura) ou lista. Devolve a crista y(x)."""
50
+ xs = np.arange(-700, W + 1500, 12, dtype=np.float32); ys = ridge(seed, xs, base, amp, freq)
51
+ for pk in ([peak] if peak and not isinstance(peak, list) else (peak or [])):
52
+ ys = ys - pk[1] * np.exp(-((xs - pk[0]) / pk[2]) ** 2)
53
+ pts = [C.ts(x, y, par)[:2] for x, y in zip(xs, ys)]
54
+ full(f).poly(pts + [(W + 1600, H + 300), (-800, H + 300)], col, a)
55
+ return lambda x: float(np.interp(x, xs, ys))
56
+
57
+
58
+ def fg(f, C: Cam, seed, y=1640, amp=40, blades=0, col=(5, 4, 6), rimk=0.28, rimcol=(255, 168, 84), par=1.7, blur=3.5):
59
+ """Primeiro plano escuro e desfocado que passa à frente de tudo, com um fio de luz de recorte."""
60
+ im = Image.new("L", (W, H), 0); d = ImageDraw.Draw(im); P = lambda a, b: C.ts(a, b, par)[:2]
61
+ xs = np.arange(-600, W + 1400, 20); ys = ridge(seed, xs.astype(np.float32), y, amp, 3.0)
62
+ d.polygon([P(a, b) for a, b in zip(xs, ys)] + [(W + 2000, H + 400), (-800, H + 400)], fill=255)
63
+ rr = np.random.default_rng(seed + 50)
64
+ for _ in range(blades):
65
+ x = rr.uniform(-300, W + 500); hh = rr.uniform(70, 190); ln = rr.uniform(-0.35, 0.35); a = P(x, y + 16)
66
+ d.line([a, (a[0] + ln * hh * 0.5, a[1] - hh * 0.6), (a[0] + ln * hh * 1.3, a[1] - hh)],
67
+ fill=255, width=int(rr.uniform(5, 10)), joint="curve")
68
+ m = gaussian_filter(np.asarray(im, np.float32) / 255, blur)
69
+ f[...] = f * (1 - m[..., None]) + np.array(col, np.float32) * m[..., None]
70
+ if rimk:
71
+ e = np.clip(m - np.roll(np.roll(m, 5, 0), -4, 1), 0, 1)
72
+ f += gaussian_filter(e, 2.0)[..., None] * np.array(rimcol, np.float32) * rimk