""" app.py — Hugging Face Spaces (Streamlit SDK) --------------------------------------------- Streamlit SDK = single process. FastAPI runs as a background thread on :7861. Streamlit serves the UI on :7860 (HF's public port). HF Spaces proxies both ports: :7860 → https://.hf.space (Streamlit UI — public) :7861 → https://-7861.hf.space (FastAPI — called by JS) Secrets (set in HF Space → Settings → Secrets): SARVAM_API_KEY, GROQ_API_KEY """ import os import sys import time import threading import streamlit as st import streamlit.components.v1 as components from streamlit_javascript import st_javascript # ── Start FastAPI in a background daemon thread ─────────────────────────────── # Streamlit reruns this file on every interaction — use a flag to start only once if "api_started" not in st.session_state: st.session_state.api_started = True def _run_api(): # Run setup_data first if data files are missing if not os.path.exists("data/investors.json"): import setup_data setup_data.run() import uvicorn from main import app as fastapi_app uvicorn.run(fastapi_app, host="0.0.0.0", port=7861, log_level="warning", reload=False) t = threading.Thread(target=_run_api, daemon=True) t.start() time.sleep(3) # Give FastAPI time to be ready before first render # ── API_BASE: HF proxies port 7861 as a sibling subdomain ──────────────────── SPACE_ID = os.environ.get("SPACE_ID", "") # Auto-set by HF: "username/space-name" if SPACE_ID: slug = SPACE_ID.replace("/", "-").lower() API_BASE = f"https://{slug}-7861.hf.space" else: API_BASE = "http://localhost:7861" # local dev fallback # ── Streamlit page setup ────────────────────────────────────────────────────── st.set_page_config( page_title = "CAMS Voice & Chat Assistant", page_icon = "🎙️", layout = "wide", initial_sidebar_state = "collapsed", ) st.markdown(""" """, unsafe_allow_html=True) win_height = st_javascript("window.innerHeight") iframe_height = int(win_height) - 80 if win_height and int(win_height) > 100 else 720 # ── Full chat UI — same HTML/JS as local version ────────────────────────────── components.html(f""" CAMS Assistant
🏦

CAMS Assistant

Mutual Fund Support — Portfolio · SIP · KYC · Compliance

🌐 EN
🤖
Namaste! I'm your CAMS Assistant. I can help you with your mutual fund portfolio, SIP details, redemptions, KYC updates, and SEBI compliance queries.

To get started with account queries, please share your PAN number. For general queries about SEBI rules, KYC documents, or fund information — just ask!
🎯 Ready 🌐 EN / हिं / தமி
● Recording...
Supports English · हिंदी · தமிழ் — voice or text
""", height=iframe_height, scrolling=False)