Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| import requests | |
| import plotly.graph_objects as go | |
| import plotly.express as px | |
| import pandas as pd | |
| from fpdf import FPDF | |
| import json | |
| import os | |
| # --- CONFIGURACIÓN DE RUTAS Y RED --- | |
| BACKEND_URL = "https://denisijcu-vertex-risk-engine.hf.space" | |
| WATCHLIST_FILE = "app/watchlist.json" | |
| def load_watchlist(): | |
| try: | |
| if os.path.exists(WATCHLIST_FILE): | |
| with open(WATCHLIST_FILE, "r") as f: | |
| return json.load(f) | |
| except Exception: pass | |
| return ["INTC", "TSLA", "AAPL", "SAVE"] | |
| def save_watchlist(watchlist): | |
| os.makedirs(os.path.dirname(WATCHLIST_FILE), exist_ok=True) | |
| with open(WATCHLIST_FILE, "w") as f: | |
| json.dump(watchlist, f) | |
| # --- MOTOR DE REPORTES PDF --- | |
| class VertexReport(FPDF): | |
| def header(self): | |
| self.set_font('Arial', 'B', 15) | |
| self.cell(0, 10, 'VERTEX CODERS LLC - AUDIT REPORT', 0, 1, 'C') | |
| self.ln(10) | |
| def generate_pdf(data): | |
| pdf = VertexReport() | |
| pdf.set_auto_page_break(auto=True, margin=15) | |
| pdf.add_page() | |
| pdf.set_font("Arial", 'B', 14) | |
| pdf.set_fill_color(151, 231, 225) | |
| pdf.cell(0, 12, f"AUDIT REPORT: {data.get('ticker', 'N/A')}", 1, 1, 'C', fill=True) | |
| pdf.ln(5) | |
| pdf.set_font("Arial", 'B', 12) | |
| pdf.cell(0, 10, f"FINAL STATUS: {data.get('status', 'UNKNOWN')}", 0, 1) | |
| semantic = data.get("semantic_analysis", {}) | |
| msg = str(semantic.get('summary', data.get('msg', 'No data'))).encode('latin-1', 'replace').decode('latin-1') | |
| pdf.ln(5) | |
| pdf.set_font("Arial", 'B', 11) | |
| pdf.cell(0, 10, "1. EXECUTIVE VERDICT", 0, 1) | |
| pdf.set_font("Arial", size=10) | |
| pdf.multi_cell(0, 8, msg) | |
| pdf.ln(5) | |
| pdf.set_font("Arial", 'B', 11) | |
| pdf.cell(0, 10, "2. FINANCIAL METRICS", 0, 1) | |
| z_score = data.get("numeric_analysis", {}).get("altman_z") or data.get("z_score", 0) | |
| pdf.cell(0, 8, f"- Altman Z-Score: {float(z_score):.2f}", 0, 1) | |
| return pdf.output(dest='S') | |
| # --- CONFIGURACIÓN DE LA UI --- | |
| st.set_page_config(page_title="Vertex Risk Terminal | Némesis", page_icon="🛡️", layout="wide") | |
| if "watchlist" not in st.session_state: | |
| st.session_state.watchlist = load_watchlist() | |
| # --- SIDEBAR --- | |
| st.sidebar.title("🏢 Stock Watchlist") | |
| new_ticker = st.sidebar.text_input("Add Ticker").upper() | |
| if st.sidebar.button("➕ Add"): | |
| if new_ticker and new_ticker not in st.session_state.watchlist: | |
| st.session_state.watchlist.append(new_ticker) | |
| save_watchlist(st.session_state.watchlist) | |
| st.sidebar.success(f"✅ {new_ticker} saved!") | |
| st.rerun() | |
| selected_ticker = st.sidebar.selectbox("Analyze Company", st.session_state.watchlist) | |
| st.sidebar.divider() | |
| st.sidebar.subheader("📡 Bunker Status") | |
| def check_health(url): | |
| try: return "🟢 ONLINE" if requests.get(url, timeout=2).status_code == 200 else "🔴 OFFLINE" | |
| except: return "🔴 OFFLINE" | |
| st.sidebar.write(f"Backend Engine: {check_health(BACKEND_URL + '/docs')}") | |
| # --- CUERPO PRINCIPAL --- | |
| st.title("🛡️ Vertex Risk Terminal") | |
| st.caption("Quantum Risk Analysis Platform | Enterprise Edition") | |
| # REPARACIÓN DE TABS: Declaración única de las 4 pestañas | |
| tab1, tab2, tab3, tab4, tab5 = st.tabs(["📈 Stock Audit", "🔗 Web3 Audit", "🔍 Auditoría Individual", "📊 Comparativa Vertex", "⚙️ Settings"]) | |
| with tab1: | |
| if st.button("🚀 RUN FULL STOCK AUDIT", type="primary", use_container_width=True): | |
| with st.spinner(f"Auditing {selected_ticker} through Némesis Engine..."): | |
| try: | |
| r = requests.get(f"{BACKEND_URL}/audit/{selected_ticker}", timeout=25) | |
| r.raise_for_status() | |
| st.session_state.last_audit = r.json() | |
| st.rerun() | |
| except Exception as e: | |
| st.error(f"🔌 Connection Failure: {e}") | |
| if "last_audit" in st.session_state: | |
| res = st.session_state.last_audit | |
| st.divider() | |
| col_l, col_r = st.columns(2) | |
| with col_l: | |
| st.metric("FINAL STATUS", res.get("status", "UNKNOWN")) | |
| z_val = res.get("numeric_analysis", {}).get("altman_z") or res.get("z_score", 0) | |
| fig = go.Figure(go.Indicator( | |
| mode="gauge+number", | |
| value=float(z_val), | |
| gauge={'axis': {'range': [0, 5]}, | |
| 'steps': [{'range': [0, 1.1], 'color': "lightcoral"}, | |
| {'range': [1.1, 2.9], 'color': "lightyellow"}, | |
| {'range': [2.9, 5], 'color': "lightgreen"}]})) | |
| fig.update_layout(height=300) | |
| st.plotly_chart(fig, use_container_width=True) | |
| with col_r: | |
| st.subheader("🧠 Semantic Analysis") | |
| sem = res.get("semantic_analysis", {}) | |
| st.info(sem.get("summary", res.get("msg", "No additional data."))) | |
| st.download_button("📥 DOWNLOAD PDF REPORT", generate_pdf(res), f"Vertex_{selected_ticker}.pdf", "application/pdf", use_container_width=True) | |
| with tab2: | |
| st.subheader("🔗 Web3 Smart Contract Scanner") | |
| contract = st.text_input("Dirección del Token (0x...)") | |
| if st.button("🔍 SCAN WEB3 ASSET", use_container_width=True): | |
| if contract: | |
| with st.spinner("Escaneando seguridad...."): | |
| try: | |
| r = requests.get(f"{BACKEND_URL}/audit_contract/{contract}", timeout=120) | |
| res_w3 = r.json() | |
| st.divider() | |
| status_w3 = res_w3.get("status", "UNKNOWN") | |
| if status_w3 == "SAFE": st.success(f"✅ STATUS: {status_w3}") | |
| elif status_w3 == "DANGER": st.error(f"🚨 STATUS: {status_w3}") | |
| vulns = res_w3.get("vulnerabilities", []) | |
| if vulns: | |
| for v in vulns: st.error(f"**{v['description']}**") | |
| with st.expander("Ver Código Fuente"): | |
| st.code(res_w3.get("source_preview", ""), language='solidity') | |
| except Exception as e: st.error(f"Error: {e}") | |
| with tab3: | |
| st.subheader("🔍 Auditoría Individual") | |
| st.write(f"Vigilancia activa sobre: **{selected_ticker}**") | |
| st.info("Este módulo utiliza análisis heurístico para reportes rápidos.") | |
| with tab4: | |
| st.subheader("📊 Comparativa de Salud Financiera") | |
| comparison_list = st.multiselect("Compañías:", options=st.session_state.watchlist, default=st.session_state.watchlist[:3]) | |
| if st.button("📊 GENERAR COMPARATIVA", use_container_width=True): | |
| comp_data = [] | |
| with st.spinner("Calculando ranking..."): | |
| for t in comparison_list: | |
| try: | |
| r = requests.get(f"{BACKEND_URL}/audit/{t}", timeout=10) | |
| if r.status_code == 200: | |
| res = r.json() | |
| z = res.get("numeric_analysis", {}).get("altman_z") or res.get("z_score", 0) | |
| comp_data.append({"Ticker": t, "Z-Score": float(z)}) | |
| except: continue | |
| if comp_data: | |
| df = pd.DataFrame(comp_data) | |
| fig_bar = px.bar(df, x='Ticker', y='Z-Score', color='Z-Score', color_continuous_scale=['red', 'yellow', 'green'], range_y=[0, 5]) | |
| fig_bar.add_hline(y=1.1, line_dash="dash", line_color="red") | |
| fig_bar.add_hline(y=2.9, line_dash="dash", line_color="green") | |
| st.plotly_chart(fig_bar, use_container_width=True) | |
| with tab5: | |
| st.header("⚙️ Configuración del Sistema") | |
| st.info("Configura las credenciales de Telegram para que Némesis te envíe alertas automáticas.") | |
| # Cargar configuraciones actuales si existen | |
| if "settings" not in st.session_state: | |
| st.session_state.settings = {"bot_token": "", "chat_id": ""} | |
| with st.form("settings_form"): | |
| bot_token = st.text_input("Telegram Bot Token", value=st.session_state.settings["bot_token"], type="password", help="El token que te dio BotFather") | |
| chat_id = st.text_input("Telegram Chat ID", value=st.session_state.settings["chat_id"], help="Tu ID de usuario o el del grupo") | |
| if st.form_submit_button("💾 Guardar Configuración"): | |
| st.session_state.settings = {"bot_token": bot_token, "chat_id": chat_id} | |
| # Aquí guardaríamos en un archivo que n8n vigile | |
| with open("app/settings.json", "w") as f: | |
| json.dump(st.session_state.settings, f) | |
| st.success("✅ Configuración guardada. n8n ahora usará estas credenciales.") |