import gradio as gr
import spaces
import torch
import pandas as pd
import subprocess
import sys
import zipfile
import json
import os
import gc
import time
import tempfile
from pathlib import Path
# ============================================================
# GITHUB
# ============================================================
GITHUB_REPO = "https://github.com/mirdbg/FinTok.git"
REPO_DIR = Path("/tmp/FinTok")
def clone_github_repo():
if REPO_DIR.exists():
subprocess.run(
["rm", "-rf", str(REPO_DIR)],
check=True
)
print("Cloning FinTok from GitHub...")
subprocess.run(
[
"git",
"clone",
"--depth",
"1",
GITHUB_REPO,
str(REPO_DIR)
],
check=True
)
print("FinTok repository cloned successfully.")
clone_github_repo()
sys.path.insert(0, str(REPO_DIR))
# ============================================================
# IMPORT REAL FINTOK TEXT PIPELINE
# ============================================================
from src.text.chunk_selector import get_context
from src.text.fact_extractor import extract_facts
from src.text.fact_checker import select_fact
from src.text.script_generator import (
generate_script,
build_video_json,
)
# ============================================================
# CORPUS
# ============================================================
CORPUS_ZIP = REPO_DIR / "data" / "corpus_miax_2026.zip"
if not CORPUS_ZIP.exists():
raise FileNotFoundError(
f"Corpus not found at: {CORPUS_ZIP}"
)
with zipfile.ZipFile(CORPUS_ZIP, "r") as z:
jsonl_files = [
name
for name in z.namelist()
if name.endswith("chunks.jsonl")
]
if not jsonl_files:
raise FileNotFoundError(
"chunks.jsonl not found inside corpus ZIP."
)
with z.open(jsonl_files[0]) as f:
records = [
json.loads(line.decode("utf-8"))
for line in f
if line.strip()
]
df = pd.DataFrame(records)
df["item"] = df["item"].astype(str)
print(f"Corpus loaded: {len(df)} chunks")
# ============================================================
# ITEMS
# ============================================================
ITEM_NAMES = {
"1A": "Risk Factors",
"7": "Management's Discussion and Analysis (MD&A)",
"7A": "Quantitative and Qualitative Disclosures About Market Risk",
"8": "Financial Statements and Supplementary Data",
}
# ============================================================
# DROPDDOWN DATA
# ============================================================
def get_companies():
return sorted(
df["ticker"]
.dropna()
.unique()
.tolist()
)
def get_years(company):
years = (
df[df["ticker"] == company]["fiscal_year"]
.dropna()
.unique()
.tolist()
)
return sorted(
years,
reverse=True
)
def get_items(company, year):
available = (
df[
(df["ticker"] == company)
& (df["fiscal_year"] == year)
]["item"]
.dropna()
.unique()
.tolist()
)
choices = []
for item in ["1A", "7", "7A", "8"]:
if item in available:
choices.append(
(
f"Item {item} โ {ITEM_NAMES[item]}",
item
)
)
return choices
def update_years(company):
years = get_years(company)
return gr.Dropdown(
choices=years,
value=years[0] if years else None
)
def update_items(company, year):
items = get_items(
company,
year
)
return gr.Dropdown(
choices=items,
value=items[0][1] if items else None
)
# ============================================================
# GEMMA
# ============================================================
MODEL_ID = "google/gemma-3-4b-it"
def build_generate_fn(model, tokenizer):
def generate_fn(
system_prompt,
user_prompt,
max_new_tokens=512
):
"""
Interface expected by FinTok:
generate_fn(
system_prompt,
user_prompt,
max_new_tokens
)
-> (text, latency)
"""
messages = [
{
"role": "system",
"content": system_prompt
},
{
"role": "user",
"content": user_prompt
}
]
prompt = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True
)
inputs = tokenizer(
prompt,
return_tensors="pt"
).to(model.device)
start = time.perf_counter()
with torch.inference_mode():
output = model.generate(
**inputs,
max_new_tokens=max_new_tokens,
do_sample=False,
)
latency = (
time.perf_counter()
- start
)
generated_tokens = output[
0,
inputs["input_ids"].shape[1]:
]
text = tokenizer.decode(
generated_tokens,
skip_special_tokens=True
)
return text, latency
return generate_fn
# ============================================================
# HELPER: EMPTY OUTPUT
# ============================================================
def status_output(message):
return (
message,
"",
None,
None,
None,
None,
None,
None,
)
# ============================================================
# FINTOK PIPELINE
# TEXT + AUDIO
# ============================================================
@spaces.GPU(duration=120)
def generate_fintok(
company,
year,
item,
progress=gr.Progress()
):
from transformers import (
AutoTokenizer,
AutoModelForCausalLM,
BitsAndBytesConfig,
)
# Keep references so finally can clean safely
model = None
tokenizer = None
# ========================================================
# VALIDATION
# ========================================================
if not company or year is None or not item:
raise gr.Error(
"Select company, fiscal year and 10-K section."
)
# ========================================================
# START
# ========================================================
progress(
0.02,
desc="Starting FinTok..."
)
yield status_output(
"""
### ๐ Starting FinTok...
Preparing the selected 10-K section.
"""
)
section_df = df[
(df["ticker"] == company)
& (df["fiscal_year"] == year)
& (df["item"] == str(item))
].copy()
if section_df.empty:
raise gr.Error(
"No chunks found for this selection."
)
# ========================================================
# HF TOKEN
# ========================================================
hf_token = os.environ.get(
"HF_TOKEN"
)
if not hf_token:
raise gr.Error(
"HF_TOKEN secret is not configured."
)
# ========================================================
# LOAD GEMMA
# ========================================================
progress(
0.08,
desc="Loading AI model..."
)
yield status_output(
"""
### ๐ง Loading AI model...
Loading Gemma 3 4B on ZeroGPU.
"""
)
quantization_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
bnb_4bit_use_double_quant=True,
)
tokenizer = AutoTokenizer.from_pretrained(
MODEL_ID,
token=hf_token
)
model = AutoModelForCausalLM.from_pretrained(
MODEL_ID,
token=hf_token,
quantization_config=quantization_config,
device_map="auto",
torch_dtype=torch.bfloat16,
)
model.eval()
generate_fn = build_generate_fn(
model,
tokenizer
)
# ========================================================
# RANDOM STORY SEARCH
# ========================================================
MAX_ATTEMPTS = 5
try:
for attempt in range(
1,
MAX_ATTEMPTS + 1
):
print(
f"FinTok story attempt "
f"{attempt}/{MAX_ATTEMPTS}"
)
# =================================================
# RANDOM STORY
# =================================================
progress(
0.15,
desc=(
f"Discovering a story "
f"({attempt}/{MAX_ATTEMPTS})..."
)
)
yield status_output(
f"""
### ๐ฒ Discovering a story...
Searching the selected 10-K section.
**Attempt {attempt}/{MAX_ATTEMPTS}**
"""
)
selected = section_df.sample(
n=1
).iloc[0]
selected_chunk_id = (
selected["chunk_id"]
)
print(
f"Selected chunk: "
f"{selected_chunk_id}"
)
# =================================================
# CONTEXT
# =================================================
context_df = get_context(
df,
selected_chunk_id,
window_size=3
)
print(
"Context:",
context_df[
"chunk_id"
].tolist()
)
# =================================================
# FACT EXTRACTION
# =================================================
progress(
0.25,
desc="Extracting financial facts..."
)
yield status_output(
"""
### ๐ Extracting financial facts...
Gemma is reading the source context and identifying relevant facts.
"""
)
extraction = extract_facts(
context_df,
generate_fn
)
ideas = (
extraction["data"]
.get(
"ideas",
[]
)
)
print(
f"Extracted ideas: "
f"{len(ideas)}"
)
if not ideas:
print(
"No ideas. "
"Trying another chunk."
)
yield status_output(
"""
### ๐ No strong story found
Trying another part of the 10-K...
"""
)
continue
# =================================================
# EDITORIAL CHECK
# =================================================
progress(
0.38,
desc="Editorial review..."
)
yield status_output(
"""
### ๐ง Editorial review...
Checking whether the facts are supported, relevant and interesting enough for a FinTok.
"""
)
selection = select_fact(
context_df,
extraction,
generate_fn
)
decision = (
str(
selection[
"data"
].get(
"decision",
""
)
)
.strip()
.upper()
)
print(
f"Editorial decision: "
f"{decision}"
)
if decision != "KEEP":
print(
"Story discarded. "
"Trying another random chunk."
)
yield status_output(
"""
### ๐ Story discarded
The story didn't pass the editorial check.
Looking for a more interesting one...
"""
)
continue
# =================================================
# SCRIPT
# =================================================
progress(
0.50,
desc="Writing FinTok script..."
)
yield status_output(
"""
### โ๏ธ Writing the FinTok script...
A story passed the editorial check.
Now turning it into short-form content.
"""
)
script = generate_script(
context_df,
selection,
generate_fn
)
if script is None:
print(
"No script generated. "
"Trying another chunk."
)
yield status_output(
"""
### ๐ Script generation failed
Trying another story...
"""
)
continue
# =================================================
# BUILD SCENES
# =================================================
progress(
0.60,
desc="Building scenes..."
)
yield status_output(
"""
### ๐ฌ Building the scenes...
Creating the Hook, Intro, Explanation and Outro.
"""
)
video_data = build_video_json(
context_df,
script
)
if video_data is None:
yield status_output(
"""
### ๐ Scene generation failed
Trying another story...
"""
)
continue
scenes = video_data["scenes"]
print(
"Scenes ready:",
[
(
scene["scene_type"],
scene["speaker"]
)
for scene in scenes
]
)
# =================================================
# SCRIPT READY
# =================================================
progress(
0.66,
desc="Script ready..."
)
yield status_output(
"""
### โ
Script ready!
All four scenes have been created.
Preparing the voice generation pipeline...
"""
)
# =================================================
# IMPORTANT:
# FREE GEMMA BEFORE LOADING F5-TTS
# =================================================
print(
"Releasing Gemma before loading F5-TTS..."
)
del generate_fn
del model
model = None
del tokenizer
tokenizer = None
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
# =================================================
# PREPARE AUDIO JSON
# =================================================
progress(
0.70,
desc="Preparing voice generation..."
)
yield status_output(
"""
### ๐๏ธ Preparing voices...
Gemma has been released from the GPU.
Preparing **Andrea** and **Miriam** for F5-TTS.
"""
)
audio_work_dir = Path(
tempfile.mkdtemp(
prefix="fintok_audio_"
)
)
input_json = (
audio_work_dir
/ "script.json"
)
output_json = (
audio_work_dir
/ "script_with_audio.json"
)
audio_output_dir = (
audio_work_dir
/ "wav"
)
with input_json.open(
"w",
encoding="utf-8"
) as f:
json.dump(
video_data,
f,
ensure_ascii=False,
indent=2
)
# =================================================
# LOAD REAL PROJECT AUDIO PIPELINE
# =================================================
progress(
0.74,
desc="Loading F5-TTS..."
)
yield status_output(
"""
### ๐๏ธ Loading F5-TTS...
Loading the voice cloning model.
The first generation can take longer because the model weights may need to be downloaded.
"""
)
from src.audio.audio_generator import (
generate_audio_from_json,
)
# =================================================
# GENERATE FOUR SCENE AUDIOS
# =================================================
progress(
0.78,
desc="Generating all four voices..."
)
yield status_output(
"""
### ๐ Generating the four voice tracks...
**1/4** Hook โ Andrea
**2/4** Intro โ Miriam
**3/4** Explanation โ Miriam
**4/4** Outro โ Andrea
F5-TTS is cloning the appropriate voice for each scene.
"""
)
audio_payload = (
generate_audio_from_json(
input_json=input_json,
output_dir=audio_output_dir,
output_json=output_json,
speed=1.0,
repo_root=REPO_DIR,
)
)
# =================================================
# COLLECT GENERATED WAV FILES
# =================================================
progress(
0.94,
desc="Collecting generated audio..."
)
generated_scenes = (
audio_payload["scenes"]
)
if len(generated_scenes) != 4:
raise RuntimeError(
"Expected exactly 4 scenes "
f"after audio generation, "
f"but got {len(generated_scenes)}."
)
audio_paths = []
for scene in generated_scenes:
audio_path = Path(
scene["audio_path"]
)
# audio_generator may return either
# absolute paths or paths relative to repo root
if not audio_path.is_absolute():
audio_path = (
REPO_DIR
/ audio_path
)
audio_path = (
audio_path.resolve()
)
if not audio_path.exists():
raise FileNotFoundError(
"Generated audio not found: "
f"{audio_path}"
)
audio_paths.append(
str(audio_path)
)
(
audio_hook,
audio_intro,
audio_explanation,
audio_outro,
) = audio_paths
# =================================================
# FINAL TEXT OUTPUT
# =================================================
output = f"""
# ๐ฌ FinTok ready
**Company:** {video_data["company"]}
**Fiscal year:** {video_data["year"]}
**10-K section:** Item {item} โ {ITEM_NAMES[item]}
---
## ๐ฏ Hook โ Andrea
{scenes[0]["text"]}
**On screen:** {scenes[0]["key_figure"]}
---
## ๐๏ธ Intro โ Miriam
{scenes[1]["text"]}
---
## ๐ Explanation โ Miriam
{scenes[2]["text"]}
**On screen:** {scenes[2]["key_figure"]}
---
## ๐ Outro โ Andrea
{scenes[3]["text"]}
---
### Source
Random starting chunk: `{selected_chunk_id}`
Context:
`{", ".join(context_df["chunk_id"].tolist())}`
Story accepted after **{attempt} attempt(s)**.
---
### ๐ Audio
All four voice tracks were generated successfully with F5-TTS.
"""
# =================================================
# CLEAN GPU AFTER AUDIO
# =================================================
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
# =================================================
# SUCCESS
# =================================================
progress(
1.0,
desc="FinTok audio ready!"
)
# =================================================
# DOWNLOADABLE OUTPUTS
# =================================================
downloadable_json = audio_work_dir / "fintok.json"
with downloadable_json.open(
"w",
encoding="utf-8"
) as f:
json.dump(
audio_payload,
f,
ensure_ascii=False,
indent=2
)
audio_zip = audio_work_dir / "fintok_audio.zip"
with zipfile.ZipFile(
audio_zip,
"w",
compression=zipfile.ZIP_DEFLATED
) as z:
archive_names = [
"01_hook_andrea.wav",
"02_intro_miriam.wav",
"03_explanation_miriam.wav",
"04_outro_andrea.wav",
]
for audio_path, archive_name in zip(
audio_paths,
archive_names
):
z.write(
audio_path,
arcname=archive_name
)
yield (
"""
### โจ Your FinTok is ready
The financial story has been researched, written and voiced.
Listen to each scene below or download the complete **JSON** and **audio pack**.
""",
output,
audio_hook,
audio_intro,
audio_explanation,
audio_outro,
str(downloadable_json),
str(audio_zip),
)
return
# ====================================================
# NOTHING PASSED EDITORIAL CHECK
# ====================================================
raise gr.Error(
"FinTok tried 5 random stories "
"but none passed the editorial check. "
"Press Generate FinTok again."
)
finally:
# ====================================================
# SAFE GPU CLEANUP
# ====================================================
if model is not None:
del model
if tokenizer is not None:
del tokenizer
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
# ============================================================
# INITIAL VALUES
# ============================================================
companies = get_companies()
default_company = companies[0]
years = get_years(
default_company
)
default_year = years[0]
items = get_items(
default_company,
default_year
)
default_item = items[0][1]
# ============================================================
# UI
# ============================================================
FINTOK_CSS = """
:root {
--fintok-pink: #c85d91;
--fintok-pink-dark: #a94e7d;
--fintok-blush: #fff4f8;
--fintok-lilac: #f5f0ff;
--fintok-ink: #302735;
--fintok-muted: #756b78;
--fintok-border: #eadde6;
}
.gradio-container {
background:
radial-gradient(circle at 8% 2%, rgba(240, 189, 214, .30), transparent 26rem),
radial-gradient(circle at 94% 8%, rgba(210, 197, 246, .30), transparent 25rem),
#fffafb !important;
}
#fintok-shell {
max-width: 1120px;
margin: 0 auto;
}
#hero {
border: 1px solid var(--fintok-border);
border-radius: 28px;
padding: 38px 42px 34px;
margin: 14px 0 22px;
background: linear-gradient(
135deg,
rgba(255,255,255,.97),
rgba(255,244,248,.96) 55%,
rgba(246,241,255,.96)
);
box-shadow: 0 16px 45px rgba(86, 55, 75, .08);
}
#hero h1 {
margin: 0 0 6px;
font-size: clamp(2.6rem, 7vw, 4.7rem);
line-height: .98;
letter-spacing: -0.055em;
color: var(--fintok-ink);
}
#hero .accent {
color: var(--fintok-pink-dark);
}
#hero .tagline {
margin-top: 13px;
font-size: 1.22rem;
font-weight: 600;
color: #584c5c;
}
#hero .description {
max-width: 850px;
margin-top: 18px;
color: var(--fintok-muted);
line-height: 1.65;
font-size: 1rem;
}
#hero .chips {
display: flex;
flex-wrap: wrap;
gap: 9px;
margin-top: 22px;
}
#hero .chip {
padding: 8px 13px;
border-radius: 999px;
background: rgba(255,255,255,.82);
border: 1px solid #eadbe4;
color: #665866;
font-size: .88rem;
font-weight: 600;
}
#poc-note {
margin-top: 22px;
padding: 16px 18px;
border-radius: 16px;
background: rgba(255,255,255,.66);
border: 1px solid #eadde6;
color: #746774;
line-height: 1.55;
font-size: .9rem;
}
#poc-note strong {
color: #5b4b58;
}
.section-card {
border: 1px solid var(--fintok-border) !important;
border-radius: 22px !important;
background: rgba(255,255,255,.88) !important;
box-shadow: 0 8px 26px rgba(78, 54, 71, .055) !important;
padding: 12px !important;
}
.section-heading {
margin: 12px 3px 14px !important;
}
.section-heading h2 {
color: var(--fintok-ink);
letter-spacing: -.025em;
margin-bottom: 3px;
}
.section-heading p {
color: var(--fintok-muted);
}
#generate-btn {
min-height: 52px;
border-radius: 15px !important;
border: 0 !important;
font-weight: 700 !important;
font-size: 1rem !important;
background: linear-gradient(135deg, #c85d91, #a95b9c) !important;
box-shadow: 0 8px 20px rgba(184, 79, 130, .22) !important;
}
#generate-btn:hover {
transform: translateY(-1px);
box-shadow: 0 10px 24px rgba(184, 79, 130, .28) !important;
}
#status-box {
border-radius: 18px;
overflow: hidden;
}
#story-output {
border: 1px solid var(--fintok-border);
border-radius: 22px;
padding: 18px 22px;
background: rgba(255,255,255,.90);
}
.audio-card {
border-radius: 18px !important;
overflow: hidden;
}
.download-card {
border: 1px solid var(--fintok-border) !important;
border-radius: 18px !important;
background: linear-gradient(145deg, #ffffff, #fff8fb) !important;
}
.footer-note {
text-align: center;
color: #918590;
font-size: .84rem;
margin: 26px 0 8px;
}
@media (max-width: 700px) {
#hero {
padding: 28px 24px;
border-radius: 22px;
}
}
"""
with gr.Blocks(
title="FinTok",
theme=gr.themes.Soft(),
css=FINTOK_CSS,
) as demo:
with gr.Column(elem_id="fintok-shell"):
# ========================================================
# HERO
# ========================================================
gr.HTML(
"""
Finance, but make it
FinTok.
The goal is to bridge the gap between
financial intelligence and
accessible social content while preserving
traceability to the original filing.