Update app.py
Browse files7 unmodified lines891011111213141516171819202122232425262728293031323318343536373 unmodified lines414243444546474849505152535455565758593 unmodified lines636465456667686970717273747576777879508081828384858687888990915992939495963 unmodified lines10010110269103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137771381391401411421431441451461471481491501511521531548615515615715815991160161162163164165166167168169170991711721731741031751761771781791801811821831841851861871051061881891901911921931941951961971981992002012022032042052062072081081091102092102112122131121131142142152162171162182192202212222232242252262272282292302312322332341231242352362372382391282402412422432442451342462472482492501392512522532542552562571422582592602615 unmodified lines2672682691541552702712722732742752762772782792802812822831612842852862872882892902912922932942952962972982993003013021673033043053063073083093103113123133141743153163173183193203213223233243253261771783273283293303313323333343353363373383393403411813423433443453463473483493503511 unmodified line3533543551891903563573583593603613623633643653663673683693703711993723733743753763773782053793803813822082092102112123833843853863873883893903913923933943952163963973983994004012214024034044054064074084094104112284124132314144154164174184194204214222374234244254264274284294304314324334344352434364374384394404414424434444454464474484497 unmodified lines
# ============================================================# LOAD CORPUS# 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 = [ name name for name in z.namelist() 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 f if 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(): return sorted(df["ticker"].dropna().unique().tolist())
companies = ( df["ticker"] .dropna() .unique() .tolist() )
return sorted(companies)
def get_years(company):
years = ( df[df["ticker"] == company]["fiscal_year"] df[ df["ticker"] == company ]["fiscal_year"] .dropna() .unique() .tolist() )
return sorted(years, reverse=True)
def get_items(company, year): items = (
available_items = ( df[ (df["ticker"] == company) & (df["fiscal_year"] == year)3 unmodified lines .tolist() )
return sorted(items, key=str) # 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] if years else None 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 Item return gr.Dropdown( choices=items, value=items[0] if items else None value=items[0][1] )
# ============================================================# RANDOM CHUNK# 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"] == item) & (df["item"] == str(item)) ].copy()
if filtered.empty: return "No chunks found for this selection." 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 # ========================================================
# Orden real dentro del documento filtered = filtered.sort_values("posicion").reset_index(drop=True) selected_index = random.randrange( len(filtered) )
selected = filtered.iloc[ selected_index ]
# ======================================================== # CONTEXT # # chunk anterior # chunk seleccionado # chunk siguiente # ========================================================
start = max( 0, selected_index - 1 )
# Seleccionamos uno aleatoriamente selected_index = random.randrange(len(filtered)) selected = filtered.iloc[selected_index] end = min( len(filtered), selected_index + 2 )
# Contexto: anterior + seleccionado + siguiente start = max(0, selected_index - 1) end = min(len(filtered), selected_index + 2) context = filtered.iloc[ start:end ]
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} **Item:** {item} **Position:** {selected["posicion"]}**10-K Section:** Item {item} — {item_name} **Selected position:** {selected["posicion"]}
---
### Selected chunk### 🎯 Selected chunk
{selected["texto"]}
---
### Context sent to FinTok### Context that will be sent to FinTok
"""
for _, row in context.iterrows(): marker = "🎯 SELECTED" if row["posicion"] == selected["posicion"] else "Context"
if row["posicion"] == selected["posicion"]: marker = "🎯 SELECTED" else: marker = "Context"
result += f"""**{marker} — position {row["posicion"]}**#### {marker} — position {row["posicion"]}
{row["texto"]}
5 unmodified lines
# ============================================================# ZEROGPU# Keep this because the Space uses ZeroGPU hardware.# 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(): return f"✅ ZeroGPU: {torch.cuda.get_device_name(0)}"
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"
# ============================================================# UI# INITIAL VALUES# ============================================================
companies = get_companies()
if not companies: raise ValueError( "No companies found in corpus." )
default_company = companies[0]
years = get_years(default_company)
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)default_item = items[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]
with gr.Blocks(title="FinTok") as demo:# ============================================================# 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 discover a story and turn it into a short video.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" label="Company", interactive=True )
year = gr.Dropdown( choices=years, value=default_year, label="Fiscal year" label="Fiscal year", interactive=True )
item = gr.Dropdown( choices=items, value=default_item, label="10-K Item" ) item = gr.Dropdown( choices=items, value=default_item, label="10-K Section", interactive=True )
# -------------------------------------------------------- # GENERATE # --------------------------------------------------------
generate_button = gr.Button( "Generate FinTok", variant="primary" variant="primary", size="lg" )
result = gr.Markdown()
# Company changes -> update years # -------------------------------------------------------- # DYNAMIC DROPDOWNS # --------------------------------------------------------
company.change( fn=update_years, inputs=company, outputs=year )
# Company/year changes -> update items company.change( fn=update_items, inputs=[company, year], inputs=[ company, year ], outputs=item )
year.change( fn=update_items, inputs=[company, year], inputs=[ company, year ], outputs=item )
# -------------------------------------------------------- # GENERATE EVENT # --------------------------------------------------------
generate_button.click( fn=select_random_chunk, inputs=[company, year, item], inputs=[ company, year, item ], outputs=result )
# ============================================================# START APP# ============================================================
demo.launch()app.py+250-49