Upload 14 files
Browse filesFiles changed (15)
- .gitattributes+4
- assets/avatar/andrea_closed.pngAdded
- assets/avatar/andrea_half.pngAdded
- assets/avatar/andrea_meta.jsonAdded+18
- assets/avatar/andrea_open.pngAdded
- assets/avatar/andrea_preview.gifAdded
- src/audio/__init__.pyAdded+5
- src/audio/audio_generator.pyAdded+274
- src/text/__init__.pyAdded+6
- src/text/chunk_selector.pyAdded+80
- src/text/fact_checker.pyAdded+108
- src/text/fact_extractor.pyAdded+147
- src/text/script_generator.pyAdded+283
- src/video/avatar_echomimic.pyAdded+107
- src/video/compositor.pyAdded+448
41 unmodified lines42434441 unmodified linesdata/audio_samples/04_EN_MIRIAM_SHORT_FAST.wav filter=lfs diff=lfs merge=lfs -textdata/audio_samples/05_EN_MIRIAM_SHORT_FAST.wav filter=lfs diff=lfs merge=lfs -textdata/audio_samples/06_EN_MIRIAM_SHORT_FAST.wav filter=lfs diff=lfs merge=lfs -text41 unmodified lines4243444546474841 unmodified linesdata/audio_samples/04_EN_MIRIAM_SHORT_FAST.wav filter=lfs diff=lfs merge=lfs -textdata/audio_samples/05_EN_MIRIAM_SHORT_FAST.wav filter=lfs diff=lfs merge=lfs -textdata/audio_samples/06_EN_MIRIAM_SHORT_FAST.wav filter=lfs diff=lfs merge=lfs -textassets/avatar/andrea_closed.png filter=lfs diff=lfs merge=lfs -textassets/avatar/andrea_half.png filter=lfs diff=lfs merge=lfs -textassets/avatar/andrea_open.png filter=lfs diff=lfs merge=lfs -textassets/avatar/andrea_preview.gif filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718{
"persona": "andrea",
"model": "stabilityai/sdxl-turbo (img2img)",
"prompt_closed": "Pixar Disney 3D animation style, cartoon character, stylized CGI render, big expressive eyes, smooth skin, young woman with long curly light brown hair and brown eyes, financial analyst wearing a navy blazer, friendly smile with closed mouth, looking at the camera, head and shoulders, soft studio lighting, plain light grey background, 3D cartoon",
"closed": {
"strength": 0.85,
"seed": 0
},
"mouth_detection": "face-alignment (68 landmarks)",
"mouth": {
"cx": 260.0,
"lip_y": 337.5,
"mouth_w": 96.16651916503906,
"tilt": -0.30434781312942505,
"drop_ratio": 0.15
},
"background_removal": "rembg (U2-Net)"
}12345"""FinTok audio pipeline."""
from .audio_generator import generate_audio_from_json
__all__ = ["generate_audio_from_json"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274"""Generate FinTok scene audio with F5-TTS.
Input: JSON produced by the text pipeline. Each scene must contain: - scene_id - text - speaker
The `speaker` field in the JSON is the source of truth. This module does notassign speakers based on scene number.
Output: - One WAV file per scene. - A copy of the JSON with `audio_path` populated."""
from __future__ import annotations
import argparseimport jsonimport osimport subprocessimport tempfilefrom pathlib import Pathfrom typing import Any
import soundfile as sffrom f5_tts.api import F5TTS
# ---------------------------------------------------------------------------# Voice configuration# ---------------------------------------------------------------------------# Keys are lowercase because speaker names from the JSON are normalized# internally with .strip().lower().## IMPORTANT:# ref_text should match exactly what is spoken in the corresponding WAV.# If ref_text is empty, F5-TTS will handle/transcribe the reference internally.SPEAKERS = { "andrea": { "audio": "data/audio_samples/03_EN_ANDREA_SHORT_FAST.wav", "ref_text": ( "Welcome back. Stock prices are moving and investors are asking " "the same question. What happens next? Let's get started." ), }, "miriam": { "audio": "data/audio_samples/06_EN_MIRIAM_SHORT_FAST.wav", "ref_text": "", },}
def _repo_root() -> Path: """Infer the FinTok repository root from src/audio/audio_generator.py.""" return Path(__file__).resolve().parents[2]
def _validate_payload(payload: dict[str, Any]) -> None: """Validate the minimum JSON structure required by the audio pipeline.""" scenes = payload.get("scenes")
if not isinstance(scenes, list) or not scenes: raise ValueError("Input JSON must contain a non-empty `scenes` list.")
for scene in scenes: scene_id = scene.get("scene_id")
if scene_id is None: raise ValueError("Every scene must contain `scene_id`.")
if not str(scene.get("text", "")).strip(): raise ValueError(f"Scene {scene_id} has no `text`.")
if not str(scene.get("speaker", "")).strip(): raise ValueError(f"Scene {scene_id} has no `speaker` assigned.")
speaker_key = str(scene["speaker"]).strip().lower() if speaker_key not in SPEAKERS: raise ValueError( f"Unknown speaker in scene {scene_id}: {scene['speaker']!r}. " f"Available speakers: {', '.join(SPEAKERS)}" )
def _normalise_reference(input_path: Path, output_path: Path) -> Path: """Convert a speaker reference WAV to mono, 24 kHz.""" if not input_path.exists(): raise FileNotFoundError(f"Reference audio not found: {input_path}")
output_path.parent.mkdir(parents=True, exist_ok=True)
subprocess.run( [ "ffmpeg", "-y", "-i", str(input_path), "-ac", "1", "-ar", "24000", "-vn", str(output_path), ], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, )
return output_path
def generate_audio_from_json( input_json: str | Path, output_dir: str | Path | None = None, output_json: str | Path | None = None, speed: float = 1.0, repo_root: str | Path | None = None,) -> dict[str, Any]: """Generate one audio file per scene.
Speaker selection comes exclusively from `scene["speaker"]`.
Example: "speaker": "ANDREA" -> SPEAKERS["andrea"] "speaker": "MIRIAM" -> SPEAKERS["miriam"]
The original speaker string is preserved in the output JSON. """ # Avoid invalid values inherited by subprocesses in some Colab runtimes. os.environ["PYTHONHASHSEED"] = "0"
root = Path(repo_root).resolve() if repo_root else _repo_root() input_json = Path(input_json).resolve()
if not input_json.exists(): raise FileNotFoundError(f"Input JSON not found: {input_json}")
with input_json.open("r", encoding="utf-8") as f: payload = json.load(f)
_validate_payload(payload)
company = str(payload.get("company", "UNKNOWN")) year = str(payload.get("year", "UNKNOWN"))
if output_dir is None: output_dir = root / "data" / "audio_output" / f"{company}_{year}" else: output_dir = Path(output_dir) if not output_dir.is_absolute(): output_dir = root / output_dir
output_dir.mkdir(parents=True, exist_ok=True)
if output_json is None: output_json = output_dir / "script_with_audio.json" else: output_json = Path(output_json) if not output_json.is_absolute(): output_json = root / output_json
output_json.parent.mkdir(parents=True, exist_ok=True)
# Only prepare the speakers that actually appear in this JSON. used_speakers = { str(scene["speaker"]).strip().lower() for scene in payload["scenes"] }
temp_dir = Path(tempfile.mkdtemp(prefix="fintok_refs_")) normalized_refs: dict[str, Path] = {}
for speaker_key in used_speakers: source_path = root / SPEAKERS[speaker_key]["audio"] normalized_refs[speaker_key] = _normalise_reference( source_path, temp_dir / f"{speaker_key}_reference.wav", )
print("Loading F5-TTS...") model = F5TTS()
for scene in payload["scenes"]: scene_id = int(scene["scene_id"]) scene_type = str(scene.get("scene_type", "scene")).strip().lower() text = str(scene["text"]).strip()
# JSON is the source of truth. speaker_original = str(scene["speaker"]).strip() speaker_key = speaker_original.lower()
safe_type = "".join( c if c.isalnum() or c in "-_" else "_" for c in scene_type )
filename = ( f"scene_{scene_id:02d}_{safe_type}_{speaker_key}.wav" ) audio_path = output_dir / filename
print( f"[{scene_id}] {scene_type} | " f"speaker={speaker_original} | " f"{text[:90]}" )
wav, sr, _ = model.infer( ref_file=str(normalized_refs[speaker_key]), ref_text=SPEAKERS[speaker_key]["ref_text"], gen_text=text, speed=speed, )
sf.write(audio_path, wav, sr)
try: stored_path = audio_path.resolve().relative_to(root).as_posix() except ValueError: stored_path = audio_path.resolve().as_posix()
# Keep scene["speaker"] exactly as it came from the text pipeline. scene["audio_path"] = stored_path
with Path(output_json).open("w", encoding="utf-8") as f: json.dump(payload, f, ensure_ascii=False, indent=2)
print(f"\nβ Generated {len(payload['scenes'])} audio files") print(f"β Audio directory: {output_dir}") print(f"β Updated JSON: {output_json}")
return payload
def main() -> None: parser = argparse.ArgumentParser( description=( "Generate one FinTok WAV per JSON scene using the " "speaker specified in each scene." ) ) parser.add_argument("input_json", help="Path to the JSON produced by src/text.") parser.add_argument( "--output-dir", default=None, help="Optional directory for generated WAV files.", ) parser.add_argument( "--output-json", default=None, help="Optional path for the JSON with audio_path populated.", ) parser.add_argument( "--speed", type=float, default=1.0, help="F5-TTS generation speed. Default: 1.0.", )
args = parser.parse_args()
generate_audio_from_json( input_json=args.input_json, output_dir=args.output_dir, output_json=args.output_json, speed=args.speed, )
if __name__ == "__main__": main()123456"""Text pipeline components for FinTok."""
from .chunk_selector import get_context, build_context_groups
from .fact_extractor import extract_facts
from .fact_checker import select_fact
from .script_generator import generate_script, build_video_json1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980"""Selection of consecutive 10-K chunks for the FinTok text pipeline."""
import pandas as pd
def _validate_columns(df: pd.DataFrame) -> None:
required = {"chunk_id", "ticker", "fiscal_year", "item", "posicion", "texto"}
missing = required - set(df.columns)
if missing:
raise ValueError(f"Missing corpus columns: {sorted(missing)}")
def get_context(df: pd.DataFrame, chunk_id: str, window_size: int = 3) -> pd.DataFrame:
"""
Return a context window around one selected chunk.
The returned chunks always belong to the same ticker, fiscal year and
10-K item. For the standard FinTok pipeline, window_size=3.
At section boundaries the window is shifted so that three chunks are
returned whenever the section contains at least three chunks.
"""
_validate_columns(df)
matches = df.loc[df["chunk_id"] == chunk_id]
if matches.empty:
raise ValueError(f"Unknown chunk_id: {chunk_id}")
target = matches.iloc[0]
section = (
df[
(df["ticker"] == target["ticker"])
& (df["fiscal_year"] == target["fiscal_year"])
& (df["item"] == target["item"])
]
.sort_values("posicion")
.reset_index(drop=True)
)
center_idx = int(section.index[section["chunk_id"] == chunk_id][0])
start = min(
max(center_idx - window_size // 2, 0),
max(len(section) - window_size, 0),
)
return section.iloc[start:start + window_size].copy()
def build_context_groups(df: pd.DataFrame, window_size: int = 3):
"""
Split every ticker/year/item section into consecutive non-overlapping
context groups.
This is intended for later full-corpus execution. It avoids processing
nearly identical sliding windows for every overlapping chunk.
"""
_validate_columns(df)
groups = []
ordered = df.sort_values(["ticker", "fiscal_year", "item", "posicion"])
for (ticker, year, item), section in ordered.groupby(
["ticker", "fiscal_year", "item"], sort=False
):
section = section.sort_values("posicion").reset_index(drop=True)
for start in range(0, len(section), window_size):
context_df = section.iloc[start:start + window_size].copy()
groups.append(context_df)
return groups
def context_to_text(context_df: pd.DataFrame) -> str:
"""Serialize a context DataFrame for insertion into an LLM prompt."""
return "\n\n".join(
f"--- CHUNK {row['chunk_id']} ---\n{row['texto']}"
for _, row in context_df.iterrows()
)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108"""Grounding and editorial selection for FinTok candidate ideas."""
import json
import re
from .chunk_selector import context_to_text
SELECT_SYSTEM = """
You are the financial editor of FinTok.
Your task is to decide whether any of the candidate ideas extracted from a
10-K is genuinely worth communicating to a general but financially interested
audience.
A fact being correct does NOT automatically make it interesting.
Good candidates tend to involve:
- substantial changes in the business,
- striking financial figures,
- important growth or declines,
- meaningful risks,
- important dependencies,
- strategic changes,
- information that reveals something useful about how the company operates.
Reject ideas that are mainly:
- administrative,
- routine accounting language,
- legal boilerplate,
- too technical without broader relevance,
- impossible to understand without extensive context,
- repetitive, common knowledge or trivial.
Be selective.
Select AT MOST ONE idea. It is important to select none if none of the candidates are sufficiently interesting.
Use the original excerpts to verify that the selected idea is properly
supported.
Return ONLY valid JSON:
{
"decision": "KEEP or DISCARD",
"selected_idea": "..." or null,
"reason": "..."
}
""".strip()
def parse_json_output(text: str):
text = text.strip()
text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.IGNORECASE)
text = re.sub(r"\s*```$", "", text)
return json.loads(text)
def select_fact(context_df, extraction, generate_fn):
"""
Select at most one candidate idea and verify it against the source context.
"""
context_text = context_to_text(context_df)
extraction_data = (
extraction["data"] if "data" in extraction else extraction
)
if not extraction_data.get("ideas"):
return {
"data": {
"decision": "DISCARD",
"selected_idea": None,
"reason": "No candidate ideas were extracted.",
},
"raw_output": None,
"latency": 0.0,
}
candidate_json = json.dumps(extraction_data, ensure_ascii=False)
user_prompt = f"""
ORIGINAL 10-K EXCERPTS:
----------------
{context_text}
----------------
CANDIDATE IDEAS:
----------------
{candidate_json}
----------------
""".strip()
raw_output, latency = generate_fn(
SELECT_SYSTEM,
user_prompt,
max_new_tokens=300,
)
data = parse_json_output(raw_output)
decision = str(data.get("decision", "")).upper()
if decision not in {"KEEP", "DISCARD"}:
raise ValueError("Invalid SELECT output: decision must be KEEP or DISCARD.")
return {
"data": data,
"raw_output": raw_output,
"latency": latency,
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147"""Factual idea extraction from consecutive 10-K chunks."""
import json
import re
from .chunk_selector import context_to_text
EXTRACT_SYSTEM = """
You are a financial analyst specialized in SEC 10-K filings.
Read the supplied excerpts from three consecutive chunks of the same 10-K section.
Extract up to 3 distinct, self-contained factual ideas that are explicitly
supported by the text.
Prioritize:
- important quantitative results or changes,
- year-over-year developments,
- business drivers,
- strategic developments,
- customer or supplier dependencies,
- material risks,
- unusual or potentially meaningful facts.
Rules:
- Use ONLY information contained in the supplied excerpts.
- Do not use external knowledge.
- Do not speculate.
- Do not exaggerate.
- Combine information across the three chunks when they clearly belong to
the same idea.
- Do not create separate ideas just because the same information appears
across overlapping chunks.
- Return fewer than 3 ideas if necessary.
- If nothing meaningful exists, return an empty list.
- This is factual extraction, NOT social-media copywriting.
- Keep each "idea" concise: maximum 40 words.
- Keep each "evidence" very concise: maximum 30 words.
- NEVER reproduce full tables or long passages in "evidence".
- Evidence should contain only the minimum source text needed to support the idea.
- Be especially careful when reading tables: distinguish values, column labels,
years, gains, losses, fair values and totals correctly.
- Do not infer that a number represents a gain, loss, percentage or total unless
the corresponding row and column labels explicitly support that interpretation.
- "source_chunks" must contain only the exact chunk_id, without adding the word
"CHUNK".
Return ONLY valid JSON:
{
"ideas": [
{
"idea": "...",
"evidence": "...",
"source_chunks": ["chunk_id"]
}
]
}
""".strip()
def parse_json_output(text: str):
"""
Parse JSON returned by the model.
Handles:
- accidental ```json markdown fences;
- text before/after the JSON;
- unescaped control characters generated inside strings.
"""
text = text.strip()
# Remove accidental Markdown fences
text = re.sub(
r"^```(?:json)?\s*",
"",
text,
flags=re.IGNORECASE,
)
text = re.sub(
r"\s*```$",
"",
text,
)
# Keep only the JSON object
start = text.find("{")
end = text.rfind("}")
if start == -1 or end == -1:
raise ValueError(
f"No complete JSON object found in model output:\n{text}"
)
text = text[start:end + 1]
# strict=False tolerates literal control characters
# occasionally produced by the LLM inside JSON strings
return json.loads(text, strict=False)
def extract_facts(context_df, generate_fn):
"""
Extract up to three grounded candidate ideas.
Parameters
----------
context_df:
DataFrame containing the consecutive source chunks.
generate_fn:
Callable(system_prompt, user_prompt, max_new_tokens)
-> (text, latency)
"""
target = context_df.iloc[0]
context_text = context_to_text(context_df)
user_prompt = f"""
COMPANY/TICKER: {target['ticker']}
FISCAL YEAR: {target['fiscal_year']}
10-K ITEM: {target['item']}
CONSECUTIVE 10-K EXCERPTS:
----------------
{context_text}
----------------
""".strip()
raw_output, latency = generate_fn(
EXTRACT_SYSTEM,
user_prompt,
max_new_tokens=700,
)
data = parse_json_output(raw_output)
if "ideas" not in data or not isinstance(data["ideas"], list):
raise ValueError(
"Invalid EXTRACT output: expected an 'ideas' list."
)
return {
"data": data,
"raw_output": raw_output,
"latency": latency,
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283"""FinTok script generation and deterministic final JSON construction."""
import json
import re
from .chunk_selector import context_to_text
INTRO = "This is FinTok β your daily dose of financial knowledge."
OUTRO = "That's your FinTok for today. See you in the next one."
WRITE_SYSTEM = """
You are a financial content writer for FinTok, a platform that transforms
official 10-K filings into short, engaging and easy-to-understand financial content.
Turn the selected financial idea into a natural spoken script for a short video.
Use the original 10-K excerpts as the ONLY factual source.
Your goal is to communicate ONE interesting financial story clearly and naturally.
1. HOOK
Write ONE short and engaging question or surprising factual statement based
on the selected idea.
The hook should make the viewer curious and want to keep watching.
IMPORTANT:
- The hook must contain ONLY the hook.
- Do not explain the full story in the hook.
- Maximum 25 words.
- Make it specific to the selected financial story.
You may use formats such as:
- "Did you know that...?"
- "What if I told you that...?"
- "How much...?"
- "Why did...?"
- "One number in [company]'s latest filing stands out..."
Do NOT use misleading clickbait.
Do NOT exaggerate beyond what is supported by the source.
HOOK HIGHLIGHT
Also create a "hook_highlight".
This is a very short visual summary of the hook that may appear as large
on-screen text.
Rules:
- Ideally 3-6 words.
- Preserve the main idea of the hook.
- It may be a question or statement.
- It does NOT need to contain a number.
- Do not introduce new information.
2. EXPLANATION
Explain the selected idea clearly and naturally.
Write 2-3 concise sentences.
IMPORTANT:
- Maximum 70 words.
- Focus on ONE main financial story.
- Every sentence must add NEW information or context.
- Do not repeat the same idea in different words.
- Stop once the main idea has been explained.
The explanation must:
- identify the company naturally;
- preserve the most relevant figures and context;
- explain the fact in language understandable to a general interested audience;
- sound natural when spoken aloud;
- avoid unnecessary financial jargon;
- avoid simply copying regulatory language;
- avoid investment advice;
- avoid unsupported interpretations;
- use ONLY information supported by the supplied 10-K excerpts;
- simplify regulatory language into natural spoken English while preserving
its factual meaning.
Do not try to summarize everything in the excerpts.
Only include information that directly helps explain the selected story.
EXPLANATION HIGHLIGHT
Also create an "explanation_highlight".
This is ONE short relevant fact from the explanation that may appear as
large on-screen text.
It may be:
- quantitative: a monetary amount, percentage, growth rate, ratio or
other important numerical fact;
OR
- qualitative: an important business fact, risk, dependency, strategic
development or limitation.
Rules:
- Ideally 3-7 words.
- Choose the most relevant or interesting fact from the explanation.
- Prefer a quantitative fact when an important number is central to the story.
- Otherwise use a concise qualitative fact.
- It must refer to information already contained in the explanation.
- Never introduce a new fact.
FINTOK INTRO AND OUTRO
The following two sentences will be added automatically later by Python:
"This is FinTok β your daily dose of financial knowledge."
"That's your FinTok for today. See you in the next one."
Therefore:
- DO NOT generate the FinTok intro.
- DO NOT generate the FinTok outro.
OUTPUT
Return ONLY valid JSON with EXACTLY this structure:
{
"hook": "...",
"hook_highlight": "...",
"explanation": "...",
"explanation_highlight": "..."
}
Do not include markdown.
Do not include ```json.
Do not include any text before or after the JSON.
""".strip()
def parse_json_output(text: str):
text = text.strip()
text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.IGNORECASE)
text = re.sub(r"\s*```$", "", text)
return json.loads(text)
def generate_script(context_df, selection, generate_fn):
"""Generate hook, explanation and visual highlights for a KEEP decision."""
selection_data = selection["data"] if "data" in selection else selection
if str(selection_data.get("decision", "")).upper() != "KEEP":
return None
context_text = context_to_text(context_df)
selected_story = json.dumps(selection_data, ensure_ascii=False)
user_prompt = f"""
SELECTED FINANCIAL STORY:
----------------
{selected_story}
----------------
SOURCE 10-K EXCERPTS:
----------------
{context_text}
----------------
Write the hook, explanation and their visual highlights.
Remember:
- hook: maximum 25 words;
- explanation: maximum 70 words;
- use only information supported by the source.
""".strip()
raw_output, latency = generate_fn(
WRITE_SYSTEM,
user_prompt,
max_new_tokens=350,
)
data = parse_json_output(raw_output)
required = {
"hook",
"hook_highlight",
"explanation",
"explanation_highlight",
}
missing = required - set(data)
if missing:
raise ValueError(f"Invalid WRITE output; missing fields: {sorted(missing)}")
return {
"data": data,
"raw_output": raw_output,
"latency": latency,
}
def build_video_json(context_df, script):
"""
Build the final four-scene FinTok object deterministically.
No LLM call is performed here.
"""
if script is None:
return None
write_data = script["data"] if "data" in script else script
target = context_df.iloc[0]
source_chunk_ids = context_df["chunk_id"].tolist()
video_data = {
"company": str(target["ticker"]),
"year": int(target["fiscal_year"]),
"language": "en",
"scenes": [
{
"scene_id": 1,
"scene_type": "hook",
"speaker": "ANDREA",
"text": write_data["hook"],
"key_figure": write_data["hook_highlight"],
"source_chunk_ids": source_chunk_ids,
"verified": True,
"audio_path": None,
},
{
"scene_id": 2,
"scene_type": "intro",
"speaker": "MIRIAM",
"text": INTRO,
"key_figure": None,
"source_chunk_ids": [],
"verified": True,
"audio_path": None,
},
{
"scene_id": 3,
"scene_type": "explanation",
"speaker": "MIRIAM",
"text": write_data["explanation"],
"key_figure": write_data["explanation_highlight"],
"source_chunk_ids": source_chunk_ids,
"verified": True,
"audio_path": None,
},
{
"scene_id": 4,
"scene_type": "outro",
"speaker": "ANDREA",
"text": OUTRO,
"key_figure": None,
"source_chunk_ids": [],
"verified": True,
"audio_path": None,
},
],
}
# Deterministic structural validation.
assert len(video_data["scenes"]) == 4
assert [s["scene_type"] for s in video_data["scenes"]] == [
"hook", "intro", "explanation", "outro"
]
assert video_data["scenes"][1]["text"] == INTRO
assert video_data["scenes"][3]["text"] == OUTRO
assert video_data["scenes"][1]["key_figure"] is None
assert video_data["scenes"][3]["key_figure"] is None
assert video_data["scenes"][1]["source_chunk_ids"] == []
assert video_data["scenes"][3]["source_chunk_ids"] == []
available_ids = set(context_df["chunk_id"])
for scene in video_data["scenes"]:
assert scene["speaker"] in {"MIRIAM", "ANDREA"}
assert scene["audio_path"] is None
for chunk_id in scene["source_chunk_ids"]:
assert chunk_id in available_ids
return video_data123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107"""
FinTok AI Β· src/video/avatar_echomimic.py
Proveedor de avatar animado: envΓa el retrato y el audio de una escena al
Space pΓΊblico de Hugging Face "fffiloni/EchoMimic" (modelo EchoMimic, lip-sync
guiado por audio) y devuelve un vΓdeo de la cara hablando.
- CachΓ©: si ya se generΓ³ ese mismo avatar + audio + parΓ‘metros, no se vuelve a
llamar al Space (ahorra cuota de GPU y hace la demo instantΓ‘nea).
- Si el Space falla (caΓdo, sin cuota, cola), la escena queda sin vΓdeo y el
montador usa el avatar de 3 bocas como respaldo.
Uso:
from avatar_echomimic import attach_talking_heads
spec = attach_talking_heads(spec, avatar_dir="assets/avatar", token=HF_TOKEN)
render_video(spec, ...)
"""
from __future__ import annotations
import hashlib
import json
import math
import os
import shutil
from PIL import Image
from scipy.io import wavfile
SPACE_ID = "fffiloni/EchoMimic"
API_NAME = "/generate_video"
DEFAULTS = {"width": 512, "height": 512, "seed": 420, "cfg": 2.5, "steps": 30, "fps": 24}
def _flatten_avatar(png_path: str, out_path: str, bg=(225, 233, 245)) -> str:
"""EchoMimic necesita una imagen sin transparencia: ponemos el avatar sobre fondo liso
(el mismo color que la burbuja del montador, para que no se note el borde)."""
im = Image.open(png_path).convert("RGBA")
base = Image.new("RGBA", im.size, bg + (255,))
base.alpha_composite(im)
base.convert("RGB").resize((DEFAULTS["width"], DEFAULTS["height"]), Image.LANCZOS).save(out_path)
return out_path
def _audio_seconds(path: str) -> float:
sr, data = wavfile.read(path)
return len(data) / sr
def _cache_key(*files: str, params: dict) -> str:
h = hashlib.sha1()
for f in files:
with open(f, "rb") as fh:
h.update(fh.read())
h.update(json.dumps(params, sort_keys=True).encode())
return h.hexdigest()[:16]
def generate_talking_head(image_path: str, audio_path: str, cache_dir: str = "outputs/avatar_videos",
token: str | None = None, client=None, **params) -> str:
"""Devuelve la ruta a un MP4 con la cara hablando. Lanza excepciΓ³n si el Space falla."""
os.makedirs(cache_dir, exist_ok=True)
p = {**DEFAULTS, **params}
p["length"] = int(math.ceil(_audio_seconds(audio_path) * p["fps"])) + p["fps"] # nΒΊ de fotogramas + margen
flat = os.path.join(cache_dir, "avatar_flat.png")
_flatten_avatar(image_path, flat)
out = os.path.join(cache_dir, f"{_cache_key(flat, audio_path, params=p)}.mp4")
if os.path.exists(out):
return out # ya generado antes
from gradio_client import Client, handle_file # import aquΓ: solo hace falta si se usa este proveedor
client = client or Client(SPACE_ID, token=token)
result = client.predict(
uploaded_img=handle_file(flat),
uploaded_audio=handle_file(audio_path),
width=p["width"], height=p["height"], length=p["length"], seed=p["seed"],
cfg=p["cfg"], steps=p["steps"], fps=p["fps"],
api_name=API_NAME,
)
video = result.get("video") if isinstance(result, dict) else result
shutil.copy(video, out)
return out
def attach_talking_heads(spec: dict, avatar_dir: str = "assets/avatar", token: str | None = None,
default_speaker: str = "andrea", verbose: bool = True, **params) -> dict:
"""AΓ±ade 'avatar_video_path' a cada escena con audio. Si una escena falla, se deja sin vΓdeo
y el montador usarΓ‘ el avatar de 3 bocas para esa escena."""
client = None
for s in spec["scenes"]:
if not s.get("audio_path") or not s.get("verified", True):
continue
speaker = s.get("speaker") or default_speaker
img = os.path.join(avatar_dir, f"{speaker}_closed.png")
try:
if client is None:
from gradio_client import Client
client = Client(SPACE_ID, token=token)
s["avatar_video_path"] = generate_talking_head(img, s["audio_path"], token=token, client=client, **params)
if verbose:
print(f"β escena {s.get('scene_id')}: {s['avatar_video_path']}")
except Exception as e: # Space caΓdo, sin cuota, cola, etc.
s.pop("avatar_video_path", None)
if verbose:
print(f"β escena {s.get('scene_id')}: EchoMimic no disponible ({type(e).__name__}: {e}). "
f"Se usarΓ‘ el avatar de respaldo.")
return spec123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448"""
FinTok AI Β· src/video/compositor.py
Montador de vΓdeo: recibe el JSON de escenas (guion + audio) y los avatares,
y genera un vΓdeo vertical 1080x1920 listo para redes sociales.
Por cada fotograma:
fondo (con zoom lento) β cabecera + cifra clave β avatar en burbuja
(vΓdeo de EchoMimic si existe; si no, boca segΓΊn el volumen de la voz,
rebote y balanceo) β subtΓtulos palabra
a palabra β fuente + aviso legal.
Uso:
from compositor import render_video
render_video("scenes.json", avatar_dir="assets/avatar", out_path="outputs/video.mp4")
"""
from __future__ import annotations
import json
import math
import os
import subprocess
import tempfile
from dataclasses import dataclass, field
import numpy as np
from PIL import Image, ImageDraw, ImageFilter, ImageFont
from scipy.io import wavfile
# βββββββββββββββββββββββββββββ estilo βββββββββββββββββββββββββββββ
@dataclass
class Style:
width: int = 1080
height: int = 1920
fps: int = 30
bg_top: tuple = (18, 6, 38) # degradado de fondo si no hay imagen (morado oscuro)
bg_bottom: tuple = (58, 18, 96)
accent: tuple = (178, 102, 255) # morado FinTok
accent2: tuple = (255, 92, 205) # rosa para brillos y degradados
text: tuple = (255, 255, 255)
muted: tuple = (214, 196, 240) # lavanda
brand: str = "FinTok"
brand_scenes: tuple = ("intro", "outro") # escenas fijas con ediciΓ³n especial
brand_taglines: dict = field(default_factory=lambda: {
"es": {"intro": "Tu dosis diaria de finanzas", "outro": "Β‘Nos vemos en el prΓ³ximo!"},
"en": {"intro": "Your daily dose of finance", "outro": "See you in the next one!"},
})
bubble_d: int = 560 # diΓ‘metro de la burbuja del avatar
bubble_y: int = 1120 # centro vertical de la burbuja
bubble_bg: tuple = (225, 233, 245)
mouth_thresholds: tuple = (0.12, 0.40) # volumen para boca a medias / abierta
default_speaker: str = "andrea" # si la escena no indica quiΓ©n habla
words_per_second: float = 2.6 # para estimar la duraciΓ³n si no hay audio
labels: dict = field(default_factory=lambda: {
"es": {"source": "Fuente", "disclaimer": "Generado con IA Β· No constituye recomendaciΓ³n de inversiΓ³n"},
"en": {"source": "Source", "disclaimer": "AI-generated Β· Not investment advice"},
})
font_paths: list = field(default_factory=lambda: [
"assets/fonts/Montserrat-Bold.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
"/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
])
def _font(style: Style, size: int) -> ImageFont.FreeTypeFont:
for p in style.font_paths:
if os.path.exists(p):
return ImageFont.truetype(p, size)
return ImageFont.load_default(size=size)
# βββββββββββββββββββββββββββββ audio βββββββββββββββββββββββββββββ
def _read_wav(path: str, target_sr: int = 24000) -> np.ndarray:
"""Lee un WAV, lo pasa a mono float32 [-1, 1] y lo remuestrea a target_sr."""
sr, data = wavfile.read(path)
data = data.astype(np.float32)
if data.ndim > 1:
data = data.mean(axis=1)
peak = np.abs(data).max()
if peak > 1.0: # enteros (int16/int32) β [-1, 1]
data /= 32768.0 if peak <= 32768 else 2147483648.0
if sr != target_sr:
n = int(len(data) * target_sr / sr)
data = np.interp(np.linspace(0, len(data) - 1, n), np.arange(len(data)), data).astype(np.float32)
return data
def _envelope(audio: np.ndarray, sr: int, fps: int) -> np.ndarray:
"""Volumen (RMS) por fotograma, normalizado a [0, 1] y suavizado."""
hop = sr // fps
n = max(1, len(audio) // hop)
rms = np.array([np.sqrt(np.mean(audio[i * hop:(i + 1) * hop] ** 2) + 1e-12) for i in range(n)])
ref = np.percentile(rms, 95) + 1e-9
level = np.clip(rms / ref, 0, 1)
smooth = np.copy(level)
for i in range(1, len(smooth)): # ataque rΓ‘pido, caΓda suave
a = 0.6 if level[i] > smooth[i - 1] else 0.35
smooth[i] = a * level[i] + (1 - a) * smooth[i - 1]
return smooth
# βββββββββββββββββββββββββββββ escenas βββββββββββββββββββββββββββββ
def normalize_spec(spec: dict, style: Style) -> dict:
"""Rellena valores por defecto para aceptar el JSON tal como lo genera la parte de texto."""
spec = dict(spec)
spec.setdefault("language", "es")
for s in spec["scenes"]:
s["speaker"] = (s.get("speaker") or style.default_speaker).strip().lower() # "ANDREA" β "andrea"
if not s.get("source"):
ids = s.get("source_chunk_ids") or []
s["source"] = f"{spec.get('company', '')} 10-K {spec.get('year', '')} Β· {', '.join(ids)}" if ids else None
return spec
def _word_timings(scene: dict, duration: float) -> list[dict]:
"""Usa word_timestamps si existen; si no, reparte el tiempo segΓΊn la longitud de cada palabra."""
if scene.get("word_timestamps"):
return scene["word_timestamps"]
words = scene["text"].split()
weights = np.array([len(w) + 2 for w in words], dtype=float)
ends = np.cumsum(weights) / weights.sum() * duration * 0.97
starts = np.concatenate([[0], ends[:-1]])
return [{"word": w, "start": float(s), "end": float(e)} for w, s, e in zip(words, starts, ends)]
def _load_background(path: str | None, style: Style) -> Image.Image:
w, h = style.width, style.height
if path and os.path.exists(path):
img = Image.open(path).convert("RGB")
scale = max(w / img.width, h / img.height) * 1.15 # margen para el zoom
return img.resize((int(img.width * scale), int(img.height * scale)), Image.LANCZOS)
grad = np.linspace(0, 1, h)[:, None, None]
arr = (1 - grad) * np.array(style.bg_top) + grad * np.array(style.bg_bottom)
return Image.fromarray(np.repeat(arr, w, axis=1).astype(np.uint8))
def _ken_burns(bg: Image.Image, progress: float, style: Style) -> Image.Image:
"""Zoom lento hacia dentro durante la escena."""
w, h = style.width, style.height
if bg.size == (w, h):
return bg.copy()
z = 1.0 + 0.08 * progress
cw, ch = int(w * 1.1 / z), int(h * 1.1 / z)
left, top = (bg.width - cw) // 2, (bg.height - ch) // 2
return bg.crop((left, top, left + cw, top + ch)).resize((w, h), Image.BILINEAR)
# βββββββββββββββββββββββββββββ avatar βββββββββββββββββββββββββββββ
def _load_avatar(avatar_dir: str, speaker: str) -> dict:
states = {}
for state in ("closed", "half", "open"):
p = os.path.join(avatar_dir, f"{speaker}_{state}.png")
if os.path.exists(p):
states[state] = Image.open(p).convert("RGBA")
if "closed" not in states:
raise FileNotFoundError(f"Falta {speaker}_closed.png en {avatar_dir}")
states.setdefault("open", states["closed"])
states.setdefault("half", states["open"])
return states
class _VideoFrames:
"""Lee los fotogramas de un vΓdeo uno a uno (sin cargarlo entero en memoria),
ya recortados en cuadrado al tamaΓ±o de la burbuja y a los fps del montador."""
def __init__(self, path: str, size: int, fps: int):
self.size, self.last = size, None
vf = f"fps={fps},scale={size}:{size}:force_original_aspect_ratio=increase,crop={size}:{size}"
self.proc = subprocess.Popen(["ffmpeg", "-loglevel", "error", "-i", path, "-vf", vf,
"-f", "rawvideo", "-pix_fmt", "rgb24", "-"], stdout=subprocess.PIPE)
def next(self) -> Image.Image | None:
n = self.size * self.size * 3
buf = self.proc.stdout.read(n)
if len(buf) == n:
self.last = Image.frombytes("RGB", (self.size, self.size), buf)
return self.last # si el vΓdeo se acaba antes que el audio, se queda en el ΓΊltimo fotograma
def close(self):
self.proc.kill()
self.proc.wait()
def _bubble(avatar: Image.Image | None, level: float, t: float, appear: float, style: Style,
video_frame: Image.Image | None = None) -> Image.Image:
"""Avatar dentro de un cΓrculo. Con vΓdeo (EchoMimic) se usa el fotograma tal cual;
con imΓ‘genes (respaldo) se aΓ±ade rebote al hablar y balanceo suave."""
d = style.bubble_d
if video_frame is not None:
inner = video_frame.convert("RGBA").resize((d, d), Image.BILINEAR)
else:
inner = Image.new("RGBA", (d, d), style.bubble_bg + (255,))
# rebote (sube y se estira con la voz) + balanceo continuo
sx = 1.0 - 0.02 * level
sy = 1.0 + 0.04 * level
size = int(d * 1.05)
av = avatar.resize((int(size * sx), int(size * sy)), Image.BILINEAR)
av = av.rotate(2.5 * math.sin(t * 1.6), resample=Image.BICUBIC, expand=False)
dy = int(-18 * level + 4 * math.sin(t * 2.2))
inner.alpha_composite(av, ((d - av.width) // 2, d - av.height + int(d * 0.08) + dy))
mask = Image.new("L", (d, d), 0)
ImageDraw.Draw(mask).ellipse((0, 0, d - 1, d - 1), fill=255)
inner.putalpha(mask)
ring = 14
out = Image.new("RGBA", (d + 2 * ring, d + 2 * ring), (0, 0, 0, 0))
g = np.linspace(0, 1, out.height)[:, None, None]
grad = ((1 - g) * np.array(style.accent2) + g * np.array(style.accent)).repeat(out.width, axis=1)
ring_img = Image.fromarray(grad.astype(np.uint8)).convert("RGBA")
rmask = Image.new("L", out.size, 0)
ImageDraw.Draw(rmask).ellipse((0, 0, out.width - 1, out.height - 1), fill=255)
out.paste(ring_img, (0, 0), rmask)
out.alpha_composite(inner, (ring, ring))
# entrada con rebote al inicio del vΓdeo
if appear < 1:
s = max(0.01, 1 + 0.15 * math.sin(appear * math.pi) - (1 - appear) ** 2)
out = out.resize((max(1, int(out.width * s)), max(1, int(out.height * s))), Image.BILINEAR)
return out
# βββββββββββββββββββββββββ escenas de marca βββββββββββββββββββββββββ
def _ease_out_back(x: float) -> float:
x = min(max(x, 0.0), 1.0)
c = 1.70158
return 1 + (c + 1) * (x - 1) ** 3 + c * (x - 1) ** 2
def _brand_background(frame: Image.Image, t_scene: float, style: Style):
"""Fondo de las escenas intro/outro: degradado morado, haz de luz giratorio y destellos."""
W, H = style.width, style.height
over = Image.new("RGBA", (W, H), (0, 0, 0, 0))
d = ImageDraw.Draw(over)
# rayos de luz girando desde el centro de la burbuja
cx, cy = W // 2, style.bubble_y
for k in range(12):
a = t_scene * 0.6 + k * math.pi / 6
a2 = a + math.pi / 24
r = 1600
d.polygon([(cx, cy), (cx + r * math.cos(a), cy + r * math.sin(a)),
(cx + r * math.cos(a2), cy + r * math.sin(a2))], fill=style.accent + (38,))
# destellos (posiciones pseudoaleatorias fijas que parpadean)
rng = np.random.default_rng(7)
for _ in range(40):
x, y = rng.uniform(0, W), rng.uniform(0, H)
ph, sp = rng.uniform(0, 6.28), rng.uniform(1.5, 4)
a = int(200 * max(0.0, math.sin(t_scene * sp + ph)))
r = rng.uniform(3, 8)
col = style.accent2 if rng.random() < 0.4 else (255, 255, 255)
d.ellipse((x - r, y - r, x + r, y + r), fill=col + (a,))
frame.alpha_composite(over)
def _brand_overlay(frame: Image.Image, scene: dict, spec: dict, t_scene: float, dur: float, style: Style):
"""Logo FinTok con efecto pop, eslogan y destello de transiciΓ³n al empezar y al acabar."""
W = style.width
d = ImageDraw.Draw(frame)
lang = spec.get("language", "es")
kind = scene.get("scene_type")
# logo con rebote y ligero "latido"
p = _ease_out_back(t_scene / 0.6)
size = max(10, int(190 * p * (1 + 0.03 * math.sin(t_scene * 5))))
font = _font(style, size)
tw = d.textlength(style.brand, font=font)
y = 300 - size // 2
glow = Image.new("RGBA", frame.size, (0, 0, 0, 0))
ImageDraw.Draw(glow).text(((W - tw) / 2, y), style.brand, font=font, fill=style.accent2 + (255,))
frame.alpha_composite(glow.filter(ImageFilter.GaussianBlur(18)))
d.text(((W - tw) / 2, y), style.brand, font=font, fill=(255, 255, 255),
stroke_width=6, stroke_fill=style.accent)
# eslogan que aparece deslizando
tag = style.brand_taglines.get(lang, style.brand_taglines["es"]).get(kind, "")
if tag:
q = min(1.0, max(0.0, (t_scene - 0.35) / 0.4))
f2 = _font(style, 52)
tw2 = d.textlength(tag, font=f2)
x = (W - tw2) / 2 + (1 - q) * 120
d.rounded_rectangle((x - 30, 470, x + tw2 + 30, 550), 40, fill=style.accent + (int(230 * q),))
d.text((x, 478), tag, font=f2, fill=(255, 255, 255, int(255 * q)))
# destello morado al entrar y al salir de la escena
fl = max(0.0, 1 - t_scene / 0.25) if kind == "intro" else 0.0
fl = max(fl, max(0.0, 1 - (dur - t_scene) / 0.3) if kind == "outro" else 0.0)
if fl > 0:
frame.alpha_composite(Image.new("RGBA", frame.size, style.accent + (int(220 * fl),)))
# βββββββββββββββββββββββββββββ textos βββββββββββββββββββββββββββββ
def _draw_centered(draw, text, y, font, fill, width, stroke=0, stroke_fill=(0, 0, 0)):
tw = draw.textlength(text, font=font)
draw.text(((width - tw) / 2, y), text, font=font, fill=fill, stroke_width=stroke, stroke_fill=stroke_fill)
def _subtitle_group(timings: list[dict], t: float, group: int = 4):
"""Devuelve el grupo de palabras a mostrar y el Γndice de la que se estΓ‘ diciendo."""
idx = 0
for i, w in enumerate(timings):
if t >= w["start"]:
idx = i
g0 = (idx // group) * group
return [w["word"] for w in timings[g0:g0 + group]], idx - g0
def _fit_font(draw, text, style, max_size, max_width):
size = max_size
font = _font(style, size)
while draw.textlength(text, font=font) > max_width and size > 24:
size -= 4
font = _font(style, size)
return font
def _draw_texts(frame, scene, spec, t_scene, duration, timings, fonts, style):
d = ImageDraw.Draw(frame)
W = style.width
lang = style.labels.get(spec.get("language", "es"), style.labels["es"])
# cabecera
header = f"{spec.get('company', '')} Β· {spec.get('source_label', '10-K ' + str(spec.get('year', '')))}"
_draw_centered(d, header.upper(), 120, fonts["small"], style.muted, W)
d.rounded_rectangle((W - 150, 100, W - 50, 150), 14, fill=style.accent)
d.text((W - 128, 106), "IA" if spec.get("language", "es") == "es" else "AI", font=fonts["small"], fill=(255, 255, 255))
# cifra clave con efecto "pop"; "Etiqueta: valor" se separa en dos lΓneas
kf = scene.get("key_figure")
if kf:
label, value = (kf.rsplit(":", 1) + [""])[:2] if ":" in kf else ("", kf)
label, value = label.strip(), value.strip()
p = min(1.0, t_scene / 0.35)
scale = 1 + 0.25 * math.sin(p * math.pi) if p < 1 else 1.0
if label:
_draw_centered(d, label.upper(), 220, _fit_font(d, label.upper(), style, 48, W - 120), style.text, W)
f = _fit_font(d, value, style, int(170 * scale), W - 100)
_draw_centered(d, value, 290 - int(30 * (scale - 1)), f, style.accent, W, stroke=6, stroke_fill=(255, 255, 255))
# subtΓtulos palabra a palabra
words, active = _subtitle_group(timings, t_scene)
font = fonts["sub"]
y = 1500
total = sum(d.textlength(w + " ", font=font) for w in words)
if total > W - 120: # si no cabe, reducir el tamaΓ±o de letra
font = _font(style, int(font.size * (W - 120) / total))
total = sum(d.textlength(w + " ", font=font) for w in words)
x = (W - total) / 2
for i, w in enumerate(words):
color = style.accent if i == active else style.text
d.text((x, y), w, font=font, fill=color, stroke_width=5, stroke_fill=(0, 0, 0))
x += d.textlength(w + " ", font=font)
# fuente y aviso legal
src = scene.get("source")
if src:
sf = _fit_font(d, f"{lang['source']}: {src}", style, 30, W - 80)
_draw_centered(d, f"{lang['source']}: {src}", 1740, sf, style.muted, W)
_draw_centered(d, lang["disclaimer"], 1790, fonts["tiny"], style.muted, W)
# βββββββββββββββββββββββββββββ render βββββββββββββββββββββββββββββ
def render_video(scenes_json: str | dict, avatar_dir: str = "assets/avatar",
out_path: str = "outputs/video.mp4", style: Style | None = None,
sr: int = 24000) -> str:
style = style or Style()
spec = scenes_json if isinstance(scenes_json, dict) else json.load(open(scenes_json, encoding="utf-8"))
spec = normalize_spec(spec, style)
scenes = [s for s in spec["scenes"] if s.get("verified", True)] # las no verificadas no se publican
if not scenes:
raise ValueError("No hay escenas verificadas que renderizar.")
# 1) audio completo + duraciΓ³n real de cada escena (manda el audio)
tracks, durations = [], []
for s in scenes:
p = s.get("audio_path")
if p and os.path.exists(p):
a = _read_wav(p, sr)
else:
est = s.get("duration_s") or max(2.0, len(s["text"].split()) / style.words_per_second)
a = np.zeros(int(sr * float(est)), dtype=np.float32) # sin audio: silencio con duraciΓ³n estimada
a = np.concatenate([a, np.zeros(int(sr * 0.25), dtype=np.float32)]) # pequeΓ±a pausa entre escenas
tracks.append(a)
durations.append(len(a) / sr)
audio = np.concatenate(tracks)
env = _envelope(audio, sr, style.fps)
fonts = {"small": _font(style, 40), "sub": _font(style, 72), "tiny": _font(style, 30)}
avatars = {}
os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True)
tmp = tempfile.mkdtemp()
silent, wav = os.path.join(tmp, "video.mp4"), os.path.join(tmp, "audio.wav")
wavfile.write(wav, sr, (np.clip(audio, -1, 1) * 32767).astype(np.int16))
ffmpeg = subprocess.Popen(
["ffmpeg", "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24",
"-s", f"{style.width}x{style.height}", "-r", str(style.fps), "-i", "-",
"-c:v", "libx264", "-pix_fmt", "yuv420p", "-preset", "veryfast", "-crf", "20", silent],
stdin=subprocess.PIPE)
frame_idx, t_global = 0, 0.0
lo, hi = style.mouth_thresholds
for s, dur in zip(scenes, durations):
speaker = s["speaker"]
if speaker not in avatars:
avatars[speaker] = _load_avatar(avatar_dir, speaker)
av = avatars[speaker]
bg = _load_background(s.get("background_path"), style)
timings = _word_timings(s, dur)
vpath = s.get("avatar_video_path")
reader = _VideoFrames(vpath, style.bubble_d, style.fps) if vpath and os.path.exists(vpath) else None
n = int(round(dur * style.fps))
for i in range(n):
t_scene = i / style.fps
t = frame_idx / style.fps
level = float(env[min(frame_idx, len(env) - 1)])
mouth = av["open"] if level > hi else av["half"] if level > lo else av["closed"]
frame = _ken_burns(bg, t_scene / max(dur, 1e-6), style).convert("RGBA")
shade = Image.new("RGBA", frame.size, (0, 0, 0, 90)) # oscurecer para que se lean los textos
frame.alpha_composite(shade)
is_brand = s.get("scene_type") in style.brand_scenes
if is_brand:
_brand_background(frame, t_scene, style)
vframe = reader.next() if reader else None # None β respaldo con 3 bocas
bub = _bubble(mouth, level, t, min(1.0, t / 0.45), style, video_frame=vframe)
frame.alpha_composite(bub, ((style.width - bub.width) // 2, style.bubble_y - bub.height // 2))
_draw_texts(frame, s, spec, t_scene, dur, timings, fonts, style)
if is_brand:
_brand_overlay(frame, s, spec, t_scene, dur, style)
ffmpeg.stdin.write(frame.convert("RGB").tobytes())
frame_idx += 1
if reader:
reader.close()
ffmpeg.stdin.close()
ffmpeg.wait()
# 2) unir vΓdeo + audio
subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-i", silent, "-i", wav,
"-c:v", "copy", "-c:a", "aac", "-b:a", "160k", "-shortest", out_path], check=True)
return out_path.gitattributes+4
assets/avatar/andrea_closed.pngAdded
Large File Pointer Details
- SHA256: ac0217a55dae43abdab670cdc555ab6edcc0c80903ebb0443c873c19c253c368
- Pointer size: 131 Bytes
- Size of remote file: 459 kB
assets/avatar/andrea_half.pngAdded
Large File Pointer Details
- SHA256: 16779311dc5abd7d02556531aabcb47032e55230cfdd7a3884e2878336a992a7
- Pointer size: 131 Bytes
- Size of remote file: 456 kB
assets/avatar/andrea_meta.jsonAdded+18
assets/avatar/andrea_open.pngAdded
Large File Pointer Details
- SHA256: 90c0ed62d0ffe58909ae20c50a6e9938f2b32f2a15661cca04c6c9a8046e58f6
- Pointer size: 131 Bytes
- Size of remote file: 456 kB
assets/avatar/andrea_preview.gifAdded
Large File Pointer Details
- SHA256: 2545c225c8ec7ea64d14914009b6a177197541e078aca40f24c288aa122fd525
- Pointer size: 132 Bytes
- Size of remote file: 2.64 MB
src/audio/__init__.pyAdded+5
src/audio/audio_generator.pyAdded+274
src/text/__init__.pyAdded+6
src/text/chunk_selector.pyAdded+80
src/text/fact_checker.pyAdded+108
src/text/fact_extractor.pyAdded+147
src/text/script_generator.pyAdded+283
src/video/avatar_echomimic.pyAdded+107
src/video/compositor.pyAdded+448