Update app.py
Browse files7 unmodified lines89101112132 unmodified lines16171819202122232425262728293019 unmodified lines5051525354555657585960614 unmodified lines6667686970717273747576777879808182838485868788892 unmodified lines92939495969798991001011026 unmodified lines1091101111121131141151161171181191201211221233 unmodified lines1271281291301311321331 unmodified line1351361371381391401411421431441451461471481496 unmodified lines1561571581591601611621631641651661671681691701711721731741751761771781791801811823 unmodified lines1861871881891901911921931941951962 unmodified lines19920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331432 unmodified lines34734834935035135235335435535628 unmodified lines3853863873883893903913923933943953963973983994003 unmodified lines4044054064074084093 unmodified lines4134144154164174184194204214224234247 unmodified lines4324334344357 unmodified linesimport zipfileimport jsonimport randomfrom pathlib import Path2 unmodified lines# ============================================================GITHUB_REPO = "https://github.com/mirdbg/FinTok.git"# El repo se descarga en almacenamiento temporal del Space.REPO_DIR = Path("/tmp/FinTok")def clone_github_repo():# Si ya existe de un arranque anterior, lo eliminamos.# AsΓ siempre usamos la versiΓ³n actual de GitHub.if REPO_DIR.exists():subprocess.run(["rm", "-rf", str(REPO_DIR)],19 unmodified linesclone_github_repo()# Permite importar mΓ³dulos del proyecto.sys.path.insert(0, str(REPO_DIR))# ============================================================# PATHS# ============================================================CORPUS_ZIP = REPO_DIR / "data" / "corpus_miax_2026.zip"4 unmodified lines)# ============================================================# ITEM LABELS# ============================================================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",}# ============================================================# LOAD CORPUS# ============================================================with zipfile.ZipFile(CORPUS_ZIP, "r") as z:jsonl_files = [namefor name in z.namelist()2 unmodified linesif not jsonl_files:raise FileNotFoundError("chunks.jsonl was not found inside corpus_miax_2026.zip")with z.open(jsonl_files[0]) as f:records = [json.loads(line.decode("utf-8"))for line in f6 unmodified linesdf["item"] = df["item"].astype(str)print(f"Corpus loaded: {len(df)} chunks")print(f"Companies: {sorted(df['ticker'].dropna().unique())}")# ============================================================# DATA HELPERS# ============================================================def get_companies():return sorted(df["ticker"].dropna()3 unmodified linesdef get_years(company):years = (df[df["ticker"] == company]["fiscal_year"].dropna()1 unmodified line.tolist())return sorted(years,reverse=True)def get_items(company, year):available_items = (df[(df["ticker"] == company)& (df["fiscal_year"] == year)6 unmodified lineschoices = []for item in ["1A", "7", "7A", "8"]:if item in available_items:label = (f"Item {item} β "f"{ITEM_NAMES[item]}")choices.append((label, item))return choices# ============================================================# DYNAMIC DROPDOWNS# ============================================================def update_years(company):years = get_years(company)return gr.Dropdown(3 unmodified linesdef update_items(company, year):items = get_items(company,year)return gr.Dropdown(choices=items,2 unmodified lines# ============================================================# RANDOM CHUNK# ============================================================def select_random_chunk(company, year, item):if not all([company,year,item]):return "β οΈ Please complete the selection."filtered = df[(df["ticker"] == company)& (df["fiscal_year"] == year)& (df["item"] == str(item))].copy()if filtered.empty:return "β οΈ No chunks found."filtered = (filtered.sort_values("posicion").reset_index(drop=True))# --------------------------------------------------------# RANDOM CENTRAL CHUNK# --------------------------------------------------------selected_index = random.randrange(len(filtered))selected = filtered.iloc[selected_index]# --------------------------------------------------------# NEIGHBOURING CONTEXT# --------------------------------------------------------start = max(0,selected_index - 1)end = min(len(filtered),selected_index + 2)context = filtered.iloc[start:end]# --------------------------------------------------------# TEMPORARY OUTPUT# --------------------------------------------------------result = f"""## π² Story selected**Company:** {company}**Fiscal year:** {year}**10-K Section:** Item {item} β {ITEM_NAMES[item]}---### π― Random chunk{selected["texto"]}---### Context that will be sent to FinTok"""for _, row in context.iterrows():if row["posicion"] == selected["posicion"]:marker = "π― SELECTED"else:marker = "Context"result += f"""#### {marker} β position {row["posicion"]}{row["texto"]}---"""return result# ============================================================# ZEROGPU PLACEHOLDER# ============================================================@spaces.GPU(duration=60)def gpu_placeholder():if torch.cuda.is_available():return "ZeroGPU ready"return "GPU unavailable"# ============================================================32 unmodified lines### Financial intelligence, made for social.Select a company and a section of its 10-K.FinTok will randomly discover a story inside that sectionand turn it into a short AI-generated video.""")28 unmodified linesresult = gr.Markdown()# --------------------------------------------------------# DROPDOWN EVENTS# --------------------------------------------------------company.change(fn=update_years,inputs=company,outputs=year)company.change(fn=update_items,inputs=[3 unmodified linesoutputs=item)year.change(fn=update_items,inputs=[3 unmodified linesoutputs=item)# --------------------------------------------------------# GENERATION# --------------------------------------------------------generate_button.click(fn=select_random_chunk,inputs=[company,year,7 unmodified lines# START# ============================================================demo.launch()7 unmodified lines8910111213141516172 unmodified lines2021222324252627282919 unmodified lines4950515253545556575859606162636465666768697071724 unmodified lines777879808182832 unmodified lines868788899091929394956 unmodified lines1021031041051061071081091101111121131141151161171181191201211221231241251263 unmodified lines1301311321331341351 unmodified line1371381391401411421431441451461476 unmodified lines1541551561571581591601611621631641651661671681691701713 unmodified lines1751761771781791801812 unmodified lines18418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558632 unmodified lines61962062162262362462562662762828 unmodified lines6576586596606616626636646656666676686696703 unmodified lines6746756766776786796803 unmodified lines6846856866876886896906916927 unmodified lines7007017027037 unmodified linesimport zipfileimport jsonimport randomimport osimport gcimport timefrom pathlib import Path2 unmodified lines# ============================================================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)],19 unmodified linesclone_github_repo()sys.path.insert(0, str(REPO_DIR))# ============================================================# IMPORT REAL FINTOK PIPELINE# ============================================================from src.text.chunk_selector import get_contextfrom src.text.fact_extractor import extract_factsfrom src.text.fact_checker import select_factfrom src.text.script_generator import (generate_script,build_video_json,)# ============================================================# CORPUS# ============================================================CORPUS_ZIP = REPO_DIR / "data" / "corpus_miax_2026.zip"4 unmodified lines)with zipfile.ZipFile(CORPUS_ZIP, "r") as z:jsonl_files = [namefor name in z.namelist()2 unmodified linesif 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 f6 unmodified linesdf["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",}# ============================================================# DROPDOWN DATA# ============================================================def get_companies():return sorted(df["ticker"].dropna()3 unmodified linesdef get_years(company):years = (df[df["ticker"] == company]["fiscal_year"].dropna()1 unmodified line.tolist())return sorted(years, reverse=True)def get_items(company, year):available = (df[(df["ticker"] == company)& (df["fiscal_year"] == year)6 unmodified lineschoices = []for item in ["1A", "7", "7A", "8"]:if item in available:choices.append((f"Item {item} β {ITEM_NAMES[item]}",item))return choicesdef update_years(company):years = get_years(company)return gr.Dropdown(3 unmodified linesdef update_items(company, year):items = get_items(company, year)return gr.Dropdown(choices=items,2 unmodified lines# ============================================================# 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() - startgenerated_tokens = output[0,inputs["input_ids"].shape[1]:]text = tokenizer.decode(generated_tokens,skip_special_tokens=True)return text, latencyreturn generate_fn# ============================================================# FINTOK TEXT PIPELINE# ============================================================@spaces.GPU(duration=180)def generate_fintok(company,year,item,progress=gr.Progress()):from transformers import (AutoTokenizer,AutoModelForCausalLM,BitsAndBytesConfig,)if not company or year is None or not item:raise gr.Error("Select company, fiscal year and 10-K section.")# --------------------------------------------------------# SELECT SECTION# --------------------------------------------------------progress(0.05,desc="Preparing FinTok...")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.")# --------------------------------------------------------# 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.12,desc="Loading Gemma 3...")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 = 5try:for attempt in range(1, MAX_ATTEMPTS + 1):print(f"FinTok story attempt "f"{attempt}/{MAX_ATTEMPTS}")progress(0.20,desc=(f"Choosing a random story "f"({attempt}/{MAX_ATTEMPTS})..."))# Random central chunkselected = section_df.sample(n=1).iloc[0]selected_chunk_id = selected["chunk_id"]print(f"Selected chunk: "f"{selected_chunk_id}")# ----------------------------------------------# REAL FINTOK CONTEXT# ----------------------------------------------context_df = get_context(df,selected_chunk_id,window_size=3)print("Context:",context_df["chunk_id"].tolist())# ----------------------------------------------# EXTRACT FACTS# ----------------------------------------------progress(0.35,desc="Extracting financial facts...")extraction = extract_facts(context_df,generate_fn)ideas = extraction["data"].get("ideas",[])print(f"Extracted ideas: {len(ideas)}")if not ideas:print("No ideas. Trying another chunk.")continue# ----------------------------------------------# FACT CHECKER / EDITOR# ----------------------------------------------progress(0.52,desc="Checking whether the story is interesting...")selection = select_fact(context_df,extraction,generate_fn)decision = (str(selection["data"].get("decision","")).strip().upper())print(f"Editorial decision: {decision}")if decision != "KEEP":print("Story discarded. ""Trying another random chunk.")continue# ----------------------------------------------# SCRIPT# ----------------------------------------------progress(0.68,desc="Writing the FinTok script...")script = generate_script(context_df,selection,generate_fn)if script is None:print("No script generated. ""Trying another chunk.")continue# ----------------------------------------------# FINAL VIDEO JSON# ----------------------------------------------progress(0.85,desc="Building FinTok scenes...")video_data = build_video_json(context_df,script)if video_data is None:continue# ----------------------------------------------# SUCCESS# ----------------------------------------------progress(1.0,desc="FinTok script ready!")scenes = video_data["scenes"]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"]}---### SourceRandom starting chunk: `{selected_chunk_id}`Context:`{", ".join(context_df["chunk_id"].tolist())}`Story accepted after **{attempt} attempt(s)**."""return output# ----------------------------------------------------# NOTHING PASSED EDITORIAL CHECK# ----------------------------------------------------raise gr.Error("FinTok tried 5 random stories but none passed ""the editorial check. Press Generate FinTok again.")finally:# ----------------------------------------------------# FREE GPU# ----------------------------------------------------del modeldel tokenizergc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()# ============================================================32 unmodified lines### Financial intelligence, made for social.Choose a company, fiscal year and 10-K section.FinTok randomly discovers an interesting financial storyinside the filing and transforms it into short-form content.""")28 unmodified linesresult = gr.Markdown()# Company -> update yearcompany.change(fn=update_years,inputs=company,outputs=year)# Company -> update itemcompany.change(fn=update_items,inputs=[3 unmodified linesoutputs=item)# Year -> update itemyear.change(fn=update_items,inputs=[3 unmodified linesoutputs=item)# Generategenerate_button.click(fn=generate_fintok,inputs=[company,year,7 unmodified lines# START# ============================================================demo.queue().launch()
app.py+397-129