Update app.py
Browse files7 unmodified lines891011121314151617181920213 unmodified lines25262728293031323334353637383 unmodified lines4243444546474849505152535455565758596061623 unmodified lines666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441455 unmodified lines1511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841 unmodified line1861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472487 unmodified lines# ============================================================# LOAD CORPUS# ============================================================CORPUS_ZIP = "data/corpus_miax_2026.zip"with zipfile.ZipFile(CORPUS_ZIP, "r") as z:jsonl_files = [name for name in z.namelist()if name.endswith("chunks.jsonl")]3 unmodified lines)with z.open(jsonl_files[0]) as f:records = [json.loads(line.decode("utf-8"))for line in fif line.strip()]df = pd.DataFrame(records)print(f"Corpus loaded: {len(df)} chunks")print("Columns:", df.columns.tolist())3 unmodified lines# ============================================================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):items = (df[(df["ticker"] == company)& (df["fiscal_year"] == year)3 unmodified lines.tolist())return sorted(items, key=str)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] if items else None)# ============================================================# RANDOM CHUNK# ============================================================def select_random_chunk(company, year, item):filtered = df[(df["ticker"] == company)& (df["fiscal_year"] == year)& (df["item"] == item)].copy()if filtered.empty:return "No chunks found for this selection."# Orden real dentro del documentofiltered = filtered.sort_values("posicion").reset_index(drop=True)# Seleccionamos uno aleatoriamenteselected_index = random.randrange(len(filtered))selected = filtered.iloc[selected_index]# Contexto: anterior + seleccionado + siguientestart = max(0, selected_index - 1)end = min(len(filtered), selected_index + 2)context = filtered.iloc[start:end]result = f"""## 🎲 Random chunk selected**Company:** {company}**Fiscal year:** {year}**Item:** {item}**Position:** {selected["posicion"]}---### Selected chunk{selected["texto"]}---### Context sent to FinTok"""for _, row in context.iterrows():marker = "🎯 SELECTED" if row["posicion"] == selected["posicion"] else "Context"result += f"""**{marker} — position {row["posicion"]}**{row["texto"]}5 unmodified lines# ============================================================# ZEROGPU# Keep this because the Space uses ZeroGPU hardware.# ============================================================@spaces.GPU(duration=60)def test_gpu():if torch.cuda.is_available():return f"✅ ZeroGPU: {torch.cuda.get_device_name(0)}"return "❌ GPU not available"# ============================================================# UI# ============================================================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]with gr.Blocks(title="FinTok") as demo:gr.Markdown("""1 unmodified line### Financial intelligence, made for social.Select a company and a section of its 10-K.FinTok will discover a story and turn it into a short video.""")with gr.Row():company = gr.Dropdown(choices=companies,value=default_company,label="Company")year = gr.Dropdown(choices=years,value=default_year,label="Fiscal year")item = gr.Dropdown(choices=items,value=default_item,label="10-K Item")generate_button = gr.Button("Generate FinTok",variant="primary")result = gr.Markdown()# Company changes -> update yearscompany.change(fn=update_years,inputs=company,outputs=year)# Company/year changes -> update itemscompany.change(fn=update_items,inputs=[company, year],outputs=item)year.change(fn=update_items,inputs=[company, year],outputs=item)generate_button.click(fn=select_random_chunk,inputs=[company, year, item],outputs=result)demo.launch()7 unmodified lines89101112131415161718192021222324252627282930313233343536373 unmodified lines414243444546474849505152535455565758593 unmodified lines636465666768697071727374757677787980818283848586878889909192939495963 unmodified lines1001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602615 unmodified lines2672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503511 unmodified line3533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484497 unmodified lines# ============================================================# CONFIG# ============================================================CORPUS_ZIP = "data/corpus_miax_2026.zip"# El usuario ve el nombre completo,# pero internamente trabajamos con 1A, 7, 7A y 8.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()if name.endswith("chunks.jsonl")]3 unmodified lines)with z.open(jsonl_files[0]) as f:records = [json.loads(line.decode("utf-8"))for line in fif line.strip()]df = pd.DataFrame(records)# Nos aseguramos de que item sea siempre string.df["item"] = df["item"].astype(str)print(f"Corpus loaded: {len(df)} chunks")print("Columns:", df.columns.tolist())3 unmodified lines# ============================================================def get_companies():companies = (df["ticker"].dropna().unique().tolist())return sorted(companies)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_items = (df[(df["ticker"] == company)& (df["fiscal_year"] == year)3 unmodified lines.tolist())# Solo mostramos los cuatro Items que usamos en FinTok.# Cada choice es:# (texto que ve el usuario, valor que recibe Python)choices = []for item in ["1A", "7", "7A", "8"]:if item in available_items:label = f"Item {item} — {ITEM_NAMES[item]}"choices.append((label, item))return choices# ============================================================# DROPDOWN UPDATES# ============================================================def update_years(company):years = get_years(company)if not years:return gr.Dropdown(choices=[],value=None)return gr.Dropdown(choices=years,value=years[0])def update_items(company, year):items = get_items(company, year)if not items:return gr.Dropdown(choices=[],value=None)# items[0][1] = valor interno del primer Itemreturn gr.Dropdown(choices=items,value=items[0][1])# ============================================================# RANDOM CHUNK SELECTION# ============================================================def select_random_chunk(company, year, item):if company is None or year is None or item is None:return "⚠️ Please select a company, fiscal year and 10-K section."filtered = df[(df["ticker"] == company)& (df["fiscal_year"] == year)& (df["item"] == str(item))].copy()if filtered.empty:return "⚠️ No chunks found for this selection."# Ordenamos los chunks como aparecen en el documento.filtered = (filtered.sort_values("posicion").reset_index(drop=True))# ========================================================# RANDOM SELECTION# ========================================================selected_index = random.randrange(len(filtered))selected = filtered.iloc[selected_index]# ========================================================# CONTEXT## chunk anterior# chunk seleccionado# chunk siguiente# ========================================================start = max(0,selected_index - 1)end = min(len(filtered),selected_index + 2)context = filtered.iloc[start:end]# ========================================================# DISPLAY RESULT## Esto es TEMPORAL.# Después este contexto irá directamente a Gemma.# ========================================================item_name = ITEM_NAMES.get(str(item),"")result = f"""## 🎲 Random chunk selected**Company:** {company}**Fiscal year:** {year}**10-K Section:** Item {item} — {item_name}**Selected position:** {selected["posicion"]}---### 🎯 Selected 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"]}5 unmodified lines# ============================================================# ZEROGPU TEST## El Space está configurado como ZeroGPU.# Hugging Face necesita detectar al menos una función# @spaces.GPU durante el arranque.## Más adelante esta función será sustituida por# Gemma / TTS / vídeo.# ============================================================@spaces.GPU(duration=60)def test_gpu():if torch.cuda.is_available():gpu_name = torch.cuda.get_device_name(0)memory = (torch.cuda.get_device_properties(0).total_memory/ 1024**3)return (f"✅ ZeroGPU connected — "f"{gpu_name} ({memory:.1f} GB VRAM)")return "❌ GPU not available"# ============================================================# INITIAL VALUES# ============================================================companies = get_companies()if not companies:raise ValueError("No companies found in corpus.")default_company = companies[0]years = get_years(default_company)if not years:raise ValueError(f"No fiscal years found for {default_company}.")default_year = years[0]items = get_items(default_company,default_year)if not items:raise ValueError(f"No supported 10-K items found for "f"{default_company} {default_year}.")default_item = items[0][1]# ============================================================# GRADIO UI# ============================================================with gr.Blocks(title="FinTok") as demo:gr.Markdown("""1 unmodified line### 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.""")# --------------------------------------------------------# SELECTORS# --------------------------------------------------------with gr.Row():company = gr.Dropdown(choices=companies,value=default_company,label="Company",interactive=True)year = gr.Dropdown(choices=years,value=default_year,label="Fiscal year",interactive=True)item = gr.Dropdown(choices=items,value=default_item,label="10-K Section",interactive=True)# --------------------------------------------------------# GENERATE# --------------------------------------------------------generate_button = gr.Button("Generate FinTok",variant="primary",size="lg")result = gr.Markdown()# --------------------------------------------------------# DYNAMIC DROPDOWNS# --------------------------------------------------------company.change(fn=update_years,inputs=company,outputs=year)company.change(fn=update_items,inputs=[company,year],outputs=item)year.change(fn=update_items,inputs=[company,year],outputs=item)# --------------------------------------------------------# GENERATE EVENT# --------------------------------------------------------generate_button.click(fn=select_random_chunk,inputs=[company,year,item],outputs=result)# ============================================================# START APP# ============================================================demo.launch()
app.py+250-49