# app.py — DEBUG con lazy load + diagnóstico (ASCII limpio) import os, json, time, traceback import numpy as np import pandas as pd import joblib from typing import Optional, List, Dict, Any from fastapi import FastAPI, Body from pydantic import BaseModel, Field import gradio as gr # ========================= # Config # ========================= MODEL_PATH = os.getenv("MODEL_PATH", "bull_trading_btc.pkl") META_PATH = os.getenv("META_PATH", "bull_trading_btc_meta.json") # opcional DEFAULT_THRESHOLD = float(os.getenv("THRESHOLD", "0.70")) TP_PCT_DEFAULT = 0.01 SL_PCT_DEFAULT = 0.02 # ========================= # Estado global (lazy) # ========================= _model = None _model_err: Optional[str] = None FEATURES: Optional[List[str]] = None TP_PCT = TP_PCT_DEFAULT SL_PCT = SL_PCT_DEFAULT # Diagnóstico básico del entorno/archivos def _startup_diagnostics(): print("===== STARTUP DIAGNOSTICS =====") try: cwd = os.getcwd() print("CWD:", cwd) print("FILES:", os.listdir(cwd)) if os.path.exists(MODEL_PATH): sz = os.path.getsize(MODEL_PATH) print(f"✔ Modelo encontrado: {MODEL_PATH} | tamaño={sz} bytes") else: print(f"✖ Modelo NO encontrado en ruta: {MODEL_PATH}") if os.path.exists(META_PATH): print(f"✔ Meta encontrado: {META_PATH}") else: print(f"ℹ Meta opcional no encontrado: {META_PATH}") except Exception as e: print("Diag error:", repr(e)) print("================================") _startup_diagnostics() def _load_meta_if_any(): global FEATURES, TP_PCT, SL_PCT if os.path.exists(META_PATH): try: with open(META_PATH, "r") as f: meta = json.load(f) FEATURES = meta.get("FEATURES") TP_PCT = float(meta.get("TP_PCT", TP_PCT_DEFAULT)) SL_PCT = float(meta.get("SL_PCT", SL_PCT_DEFAULT)) print(f"Meta leída -> FEATURES={len(FEATURES) if FEATURES else 0}, TP={TP_PCT}, SL={SL_PCT}") except Exception as e: print("⚠ No se pudo leer meta:", repr(e)) def _get_model(): """Carga perezosa del modelo: nunca tumba el proceso; guarda el error en _model_err.""" global _model, _model_err, FEATURES if _model is not None or _model_err is not None: return _model try: print(f"Intentando cargar modelo desde: {MODEL_PATH}") _model = joblib.load(MODEL_PATH) print("✅ Modelo cargado OK") if not FEATURES: try: fn = getattr(_model, "feature_names_in_", None) FEATURES = list(fn) if fn is not None else [] except Exception: FEATURES = [] print(f"FEATURES finales ({len(FEATURES)}): {FEATURES if FEATURES else 'no especificadas'}") except Exception as e: _model_err = f"{type(e).__name__}: {e}" print("❌ Error cargando modelo:", _model_err) traceback.print_exc() return _model # Carga meta en frío (no carga el modelo aún) _load_meta_if_any() # ========================= # Utilidades # ========================= def _coerce_numeric_series(d: Dict[str, Any]) -> Dict[str, float]: out: Dict[str, float] = {} for k, v in d.items(): try: out[str(k)] = float(v) except Exception: out[str(k)] = 0.0 return out def build_row_from_payload( features_map: Optional[Dict[str, Any]] = None, vector: Optional[List[float]] = None, feature_order: Optional[List[str]] = None ): if features_map is not None: fm = _coerce_numeric_series(features_map) if FEATURES: row = {c: float(fm.get(c, 0.0)) for c in FEATURES} used = FEATURES else: used = sorted(fm.keys()) row = {c: float(fm.get(c, 0.0)) for c in used} df = pd.DataFrame([row], columns=used) return df, used if vector is not None: vec = [float(x) for x in vector] if feature_order: used = [str(c) for c in feature_order] if len(used) != len(vec): raise ValueError("feature_order y vector tienen longitudes distintas.") elif FEATURES and len(FEATURES) == len(vec): used = FEATURES else: used = [f"f{i}" for i in range(len(vec))] df = pd.DataFrame([vec], columns=used) if FEATURES: for c in FEATURES: if c not in df.columns: df[c] = 0.0 df = df[FEATURES] used = FEATURES return df, used raise ValueError("Debes enviar 'features' (mapa) o 'vector' (lista).") def _predict_proba_safe(m, X): if hasattr(m, "predict_proba"): p = m.predict_proba(X) if p.ndim == 2 and p.shape[1] >= 2: return p[:, 1] return np.clip(p.ravel(), 0, 1) if hasattr(m, "decision_function"): z = m.decision_function(X).ravel() return 1 / (1 + np.exp(-z)) yhat = m.predict(X).ravel() return yhat.astype(float) def predict_signal(X_one: pd.DataFrame, threshold: float) -> Dict[str, Any]: Xp = X_one.replace([np.inf, -np.inf], np.nan).fillna(0.0) m = _get_model() if m is None: return { "probability": 0.0, "signal": "ERROR", "threshold": float(threshold), "tp_pct": TP_PCT, "sl_pct": SL_PCT, "timestamp": int(time.time()), "error": _model_err or "Modelo no disponible" } proba = float(_predict_proba_safe(m, Xp)[0]) signal = "CALL" if proba >= threshold else "NO-TRADE" return { "probability": round(proba, 6), "signal": signal, "threshold": float(threshold), "tp_pct": TP_PCT, "sl_pct": SL_PCT, "timestamp": int(time.time()) } # ========================= # FastAPI # ========================= class SignalRequest(BaseModel): features: Optional[Dict[str, Any]] = Field(default=None) vector: Optional[List[float]] = Field(default=None) feature_order: Optional[List[str]] = Field(default=None) threshold: Optional[float] = Field(default=None) class SignalResponse(BaseModel): probability: float signal: str threshold: float tp_pct: float sl_pct: float timestamp: int used_features: Optional[List[str]] = None error: Optional[str] = None fastapi_app = FastAPI(title="Bull Trading BTC — Signals API (DEBUG)") @fastapi_app.get("/health") def health(): exists = os.path.exists(MODEL_PATH) size = os.path.getsize(MODEL_PATH) if exists else 0 status = "loaded" if _model is not None else ("error" if _model_err else "lazy") return { "status": status, "model_path": MODEL_PATH, "model_exists": exists, "model_size": size, "model_error": _model_err, "features_count": len(FEATURES) if FEATURES else 0, "threshold_default": DEFAULT_THRESHOLD } @fastapi_app.post("/signal", response_model=SignalResponse) def signal_endpoint(req: SignalRequest = Body(...)): try: thr = float(req.threshold) if req.threshold is not None else DEFAULT_THRESHOLD X_one, used = build_row_from_payload(req.features, req.vector, req.feature_order) out = predict_signal(X_one, thr) out["used_features"] = used return out except Exception as e: traceback.print_exc() return SignalResponse( probability=0.0, signal="ERROR", threshold=float(req.threshold or DEFAULT_THRESHOLD), tp_pct=TP_PCT, sl_pct=SL_PCT, timestamp=int(time.time()), used_features=[], error=str(e) ) @fastapi_app.get("/") def root_info(): return { "status": "running", "ui": "mounted at / (if Gradio mount succeeded)", "api_endpoints": ["/health", "/signal"] } # ========================= # Gradio UI # ========================= def gradio_predict(json_features: str, threshold: float): try: payload = json.loads(json_features) X_one, used = build_row_from_payload( features_map=payload.get("features"), vector=payload.get("vector"), feature_order=payload.get("feature_order") ) out = predict_signal(X_one, threshold) out["used_features"] = used return json.dumps(out, ensure_ascii=False, indent=2) except Exception as e: return json.dumps({"error": str(e)}, ensure_ascii=False, indent=2) with gr.Blocks() as gr_app: gr.Markdown("## 🧠 Bull Trading BTC — Señales (DEBUG)\nPega un JSON de features o vector") with gr.Row(): json_in = gr.Textbox( label="Payload JSON", value='{"features": {"rsi14": 55.2, "ema9": 69000, "ema20": 68850, "ret1": 0.001, "ret5": 0.004}}', lines=8 ) thr_in = gr.Slider(minimum=0.5, maximum=0.99, step=0.01, value=DEFAULT_THRESHOLD, label="Threshold") btn = gr.Button("Predecir señal") out = gr.Textbox(label="Respuesta", lines=10) btn.click(fn=gradio_predict, inputs=[json_in, thr_in], outputs=[out]) # ========================= # Exportación para Spaces # ========================= # Exporta el UI principal (Blocks) como 'demo' demo = gr_app # También exporta la API para uso local o pruebas app = fastapi_app __all__ = ["demo", "app"] print("✅ Configurado para Hugging Face Spaces (modo Gradio)")