File size: 20,766 Bytes
91651eb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 | """
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://<space>.hf.space (Streamlit UI โ public)
:7861 โ https://<space>-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("""
<style>
#MainMenu, header, footer,
[data-testid="stToolbar"],
[data-testid="stDecoration"],
[data-testid="stStatusWidget"] { visibility: hidden !important; height: 0 !important; }
.block-container { padding: 0 !important; margin: 0 !important; max-width: 100% !important; }
section.main > div { padding: 0 !important; }
section.main { overflow: hidden !important; }
iframe { display: block !important; border: none !important; }
[data-testid="stAppViewContainer"] { overflow: hidden !important; }
[data-testid="stVerticalBlock"] { gap: 0 !important; }
</style>
""", 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"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>CAMS Assistant</title>
<style>
* {{ box-sizing: border-box; margin: 0; padding: 0; }}
:root {{
--bg: #0f1117;
--surface: #1a1d27;
--border: #2d3148;
--accent: #4f8ef7;
--accent2: #7c6af7;
--text: #e8eaf6;
--sub: #8892b0;
--user-bg: #1e2a4a;
--bot-bg: #1a1d27;
--green: #43d49e;
--red: #e05a5a;
--orange: #f7a94f;
}}
body {{ font-family: 'Segoe UI', system-ui, sans-serif; background: var(--bg); color: var(--text);
height: {iframe_height}px; display: flex; flex-direction: column; overflow: hidden; }}
/* โโ Header โโ */
.header {{ display:flex; align-items:center; gap:12px; padding:14px 20px;
background:var(--surface); border-bottom:1px solid var(--border);
flex-shrink:0; }}
.header-icon {{ font-size:26px; }}
.header-info h1 {{ font-size:16px; font-weight:700; color:var(--text); }}
.header-info p {{ font-size:12px; color:var(--sub); }}
.status-dot {{ width:8px; height:8px; border-radius:50%; background:var(--green);
box-shadow:0 0 8px var(--green); margin-left:auto; flex-shrink:0; }}
#lang-badge {{ margin-left:8px; padding:3px 10px; border-radius:20px;
background:#1e2a4a; font-size:11px; }}
#lang-badge span {{ color:var(--accent); font-weight:600; }}
/* โโ Chat area โโ */
#chat {{ flex:1; overflow-y:auto; padding:20px; display:flex;
flex-direction:column; gap:16px; scroll-behavior:smooth; }}
#chat::-webkit-scrollbar {{ width:4px; }}
#chat::-webkit-scrollbar-thumb {{ background:var(--border); border-radius:4px; }}
.msg {{ display:flex; gap:10px; align-items:flex-start; max-width:85%; }}
.msg.user {{ flex-direction:row-reverse; margin-left:auto; }}
.avatar {{ width:32px; height:32px; border-radius:50%; display:flex;
align-items:center; justify-content:center; font-size:16px;
flex-shrink:0; background:var(--border); }}
.msg.user .avatar {{ background:var(--user-bg); }}
.bubble {{ padding:12px 16px; border-radius:16px; font-size:14px;
line-height:1.6; max-width:100%; word-wrap:break-word; }}
.msg.user .bubble {{ background:var(--user-bg); border-top-right-radius:4px; color:var(--text); }}
.msg.bot .bubble {{ background:var(--bot-bg); border:1px solid var(--border);
border-top-left-radius:4px; color:var(--text); }}
/* โโ Meta badges โโ */
.meta {{ display:flex; flex-wrap:wrap; gap:6px; margin-top:8px; }}
.badge {{ display:inline-flex; align-items:center; gap:5px; padding:3px 10px;
border-radius:20px; font-size:11px; font-weight:500; }}
.badge.intent {{ background:#1e2a4a; color:var(--accent); }}
.badge.sentiment {{ background:#1e2a1e; color:var(--green); }}
.badge.confidence {{ background:#2a1e2a; color:#c084fc; }}
.badge.action-success {{ background:#1a2e1a; color:var(--green); }}
.badge.action-pending {{ background:#2a2a1a; color:var(--orange); }}
.badge.action-blocked {{ background:#2e1a1a; color:var(--red); }}
.badge.escalation {{ background:#3a1a1a; color:var(--red); }}
.badge.action-nr {{ background:var(--border); color:var(--sub); }}
.ref-id {{ font-size:10px; color:var(--sub); margin-top:4px; }}
/* โโ Audio player โโ */
audio {{ width:100%; margin-top:8px; height:32px; filter:invert(1) hue-rotate(180deg); }}
/* โโ Typing indicator โโ */
.typing {{ display:flex; gap:5px; padding:8px 0; align-items:center; }}
.typing span {{ width:8px; height:8px; border-radius:50%; background:var(--accent);
animation:blink 1.2s infinite; flex-shrink:0; }}
.typing span:nth-child(2) {{ animation-delay: .2s; }}
.typing span:nth-child(3) {{ animation-delay: .4s; }}
@keyframes blink {{ 0%,80%,100% {{ opacity:.2 }} 40% {{ opacity:1 }} }}
/* โโ Input bar โโ */
.input-bar {{ padding:12px 16px; background:var(--surface);
border-top:1px solid var(--border); flex-shrink:0; }}
.input-row {{ display:flex; gap:8px; align-items:center; }}
.input-wrap {{ flex:1; display:flex; align-items:center;
background:var(--bg); border:1px solid var(--border);
border-radius:12px; padding:0 12px; gap:8px;
transition:border-color .2s; }}
.input-wrap:focus-within {{ border-color:var(--accent); }}
textarea#text-input {{ flex:1; background:transparent; border:none; outline:none;
color:var(--text); font-size:14px; padding:10px 0;
resize:none; height:42px; line-height:1.5;
font-family:inherit; }}
textarea#text-input::placeholder {{ color:var(--sub); }}
.icon-btn {{ background:none; border:none; cursor:pointer; font-size:20px;
padding:6px; border-radius:8px; color:var(--sub);
transition:all .2s; flex-shrink:0; }}
.icon-btn:hover {{ background:var(--border); color:var(--text); }}
.icon-btn.recording {{ color:var(--red); animation:pulse 1s infinite; }}
@keyframes pulse {{ 0%,100% {{ transform:scale(1) }} 50% {{ transform:scale(1.1) }} }}
#send-btn {{ background:var(--accent); border:none; cursor:pointer;
font-size:18px; padding:10px 14px; border-radius:12px;
color:#fff; transition:all .2s; flex-shrink:0; }}
#send-btn:hover {{ background:var(--accent2); transform:scale(1.05); }}
#send-btn:disabled {{ opacity:.4; cursor:not-allowed; transform:none; }}
.file-row {{ display:flex; align-items:center; gap:8px; margin-top:8px;
font-size:12px; color:var(--sub); }}
#send-audio-btn {{ display:none; padding:4px 12px; background:var(--accent);
border:none; border-radius:8px; color:#fff;
cursor:pointer; font-size:12px; }}
#mic-status {{ display:none; font-size:11px; color:var(--red); }}
.hint {{ font-size:11px; color:var(--sub); text-align:center; margin-top:6px; }}
</style>
</head>
<body>
<div class="header">
<div class="header-icon">๐ฆ</div>
<div class="header-info">
<h1>CAMS Assistant</h1>
<p>Mutual Fund Support โ Portfolio ยท SIP ยท KYC ยท Compliance</p>
</div>
<div id="lang-badge">๐ <span id="lang-text">EN</span></div>
<div class="status-dot"></div>
</div>
<div id="chat">
<div class="msg bot">
<div class="avatar">๐ค</div>
<div class="bubble">
Namaste! I'm your CAMS Assistant. I can help you with your mutual fund portfolio,
SIP details, redemptions, KYC updates, and SEBI compliance queries.
<br><br>
To get started with account queries, please share your <strong>PAN number</strong>.
For general queries about SEBI rules, KYC documents, or fund information โ just ask!
<div class="meta">
<span class="badge intent">๐ฏ Ready</span>
<span class="badge sentiment">๐ EN / เคนเคฟเค / เฎคเฎฎเฎฟ</span>
</div>
</div>
</div>
</div>
<div class="input-bar">
<div class="input-row">
<div class="input-wrap">
<button class="icon-btn" id="mic-btn" title="Record voice">๐๏ธ</button>
<label class="icon-btn" title="Upload audio file">
๐ <input type="file" id="file-input" accept="audio/*" style="display:none"/>
</label>
<textarea id="text-input" rows="1"
placeholder="Type your query... e.g. What is my portfolio balance?"
autocomplete="off"
></textarea>
<button id="send-btn" title="Send">โค</button>
</div>
</div>
<div class="file-row">
<span id="mic-status">โ Recording...</span>
<span id="file-name"></span>
<button id="send-audio-btn">Send Audio โค</button>
</div>
<div class="hint">Supports English ยท เคนเคฟเคเคฆเฅ ยท เฎคเฎฎเฎฟเฎดเฏ โ voice or text</div>
</div>
<script>
const API_BASE = "{API_BASE}";
const sessionId = crypto.randomUUID();
const chat = document.getElementById("chat");
const textInput = document.getElementById("text-input");
const sendBtn = document.getElementById("send-btn");
const micBtn = document.getElementById("mic-btn");
const micStatus = document.getElementById("mic-status");
const fileInput = document.getElementById("file-input");
const fileName = document.getElementById("file-name");
const sendAudio = document.getElementById("send-audio-btn");
let mediaRecorder = null;
let audioChunks = [];
let isRecording = false;
let pendingAudioBlob = null;
let conversationHistory = [];
let sessionInvestorId = null;
function extractPAN(text) {{
const m = text && text.match(/\b[A-Z]{{5}}[0-9]{{4}}[A-Z]\b/i);
return m ? m[0].toUpperCase() : null;
}}
function updateSessionPAN(text) {{
const pan = extractPAN(text);
if (pan && pan !== sessionInvestorId) {{
sessionInvestorId = pan;
console.log("Session PAN updated:", pan);
}}
}}
function scrollBottom() {{ chat.scrollTop = chat.scrollHeight; }}
function escHtml(s) {{
return String(s||"")
.replace(/&/g,"&").replace(/</g,"<")
.replace(/>/g,">").replace(/"/g,""");
}}
function addUserMsg(text) {{
const d = document.createElement("div");
d.className = "msg user";
d.innerHTML = `<div class="avatar">๐ค</div><div class="bubble">${{escHtml(text)}}</div>`;
chat.appendChild(d); scrollBottom();
}}
function intentIcon(i) {{
const m = {{
portfolio_enquiry:"๐", account_statement:"๐", redemption_request:"๐ธ",
transaction_status:"๐", sip_enquiry:"๐
", kyc_update:"๐ชช",
compliance_query:"โ๏ธ", dividend_info:"๐ฐ", general_enquiry:"๐ฌ",
escalation:"๐จ", unknown:"โ"
}};
return m[i] || "๐ฏ";
}}
function intentLabel(i) {{
return (i||"unknown").replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());
}}
function sentimentIcon(s) {{
return {{positive:"๐",neutral:"๐",negative:"๐",frustrated:"๐ค",urgent:"โก"}}[s]||"๐";
}}
function actionClass(s) {{
return {{success:"action-success",pending:"action-pending",
blocked_compliance:"action-blocked",failed:"action-blocked",
not_required:"action-nr"}}[s]||"action-nr";
}}
function actionIcon(s) {{
return {{success:"๐ข",pending:"๐ก",blocked_compliance:"๐ด",failed:"๐ด",not_required:"โช"}}[s]||"โช";
}}
function addBotResponse(data) {{
removeTyping();
const d = document.createElement("div");
d.className = "msg bot";
const langMap = {{"en":"EN","hi":"HI","ta":"TA","en-IN":"EN"}};
const lang = langMap[data.detected_language||"en"]||"EN";
document.getElementById("lang-text").textContent = lang;
let audioHtml = "";
if (data.audio_url) {{
const src = data.audio_url.startsWith("data:") ? data.audio_url
: `data:audio/wav;base64,${{data.audio_url}}`;
audioHtml = `<audio controls autoplay src="${{src}}"></audio>`;
}}
const conf = data.confidence ? Math.round(data.confidence * 100) : 0;
const act = data.action_result || {{}};
const ref = act.reference_id || "";
const actionBadge = act.status && act.status !== "not_required"
? `<span class="badge ${{actionClass(act.status)}}">${{actionIcon(act.status)}} Action: ${{act.status}}</span>`
: `<span class="badge action-nr">โช No Action</span>`;
const escBadge = data.requires_escalation
? `<span class="badge escalation">๐จ Escalation Required</span>` : "";
const refHtml = ref ? `<div class="ref-id">Ref: ${{ref.slice(0,12).toUpperCase()}}</div>` : "";
d.innerHTML = `
<div class="avatar">๐ค</div>
<div class="bubble">
${{escHtml(data.response_text)}}
${{audioHtml}}
<div class="meta">
<span class="badge intent">${{intentIcon(data.intent)}} ${{intentLabel(data.intent)}}</span>
<span class="badge sentiment">${{sentimentIcon(data.sentiment)}} ${{(data.sentiment||"neutral").replace(/\b\w/g,c=>c.toUpperCase())}}</span>
<span class="badge confidence">${{conf}}% confident</span>
${{actionBadge}}
${{escBadge}}
</div>
${{refHtml}}
</div>`;
chat.appendChild(d);
scrollBottom();
}}
function addTyping() {{
removeTyping();
const d = document.createElement("div");
d.className = "msg bot"; d.id = "typing-indicator";
d.innerHTML = `<div class="avatar">๐ค</div><div class="bubble"><div class="typing"><span></span><span></span><span></span></div></div>`;
chat.appendChild(d); scrollBottom();
}}
function removeTyping() {{
const t = document.getElementById("typing-indicator");
if (t) t.remove();
}}
function addError(msg) {{
removeTyping();
const d = document.createElement("div");
d.className = "msg bot";
d.innerHTML = `<div class="avatar">๐ค</div><div class="bubble" style="color:var(--red)">โ ${{escHtml(msg)}}</div>`;
chat.appendChild(d); scrollBottom();
}}
// โโ Send text โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
async function sendText() {{
const msg = textInput.value.trim();
if (!msg) return;
addUserMsg(msg);
textInput.value = "";
sendBtn.disabled = true;
addTyping();
conversationHistory.push({{ role: "user", content: msg }});
updateSessionPAN(msg);
try {{
const r = await fetch(`${{API_BASE}}/api/chat`, {{
method: "POST",
headers: {{"Content-Type": "application/json"}},
body: JSON.stringify({{
message: msg,
language: "en-IN",
session_id: sessionId,
investor_id: sessionInvestorId || "",
conversation_history: conversationHistory.slice(-8),
}})
}});
const data = await r.json();
if (!r.ok) throw new Error(data.detail || "API error");
if (data.entities && data.entities.investor_id)
updateSessionPAN(data.entities.investor_id);
conversationHistory.push({{ role: "assistant", content: data.response_text || "" }});
addBotResponse(data);
}} catch(e) {{
addError(e.message);
conversationHistory.pop();
}} finally {{
sendBtn.disabled = false;
}}
}}
// โโ Send audio blob โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
async function sendAudioBlob(blob, filename) {{
addUserMsg(`๐๏ธ ${{filename}}`);
addTyping();
try {{
const form = new FormData();
form.append("audio_file", blob, filename);
form.append("session_id", sessionId);
form.append("investor_id", sessionInvestorId || "");
const r = await fetch(`${{API_BASE}}/api/voice`, {{ method: "POST", body: form }});
const data = await r.json();
if (!r.ok) throw new Error(data.detail || "API error");
if (data.transcribed_text) {{
updateSessionPAN(data.transcribed_text);
conversationHistory.push({{ role: "user", content: data.transcribed_text }});
conversationHistory.push({{ role: "assistant", content: data.response_text || "" }});
}}
if (data.entities && data.entities.investor_id)
updateSessionPAN(data.entities.investor_id);
addBotResponse(data);
}} catch(e) {{
addError(e.message);
}}
}}
// โโ Mic recording โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
micBtn.addEventListener("click", async () => {{
if (isRecording) {{
isRecording = false;
micBtn.classList.remove("recording");
micStatus.style.display = "none";
mediaRecorder && mediaRecorder.stop();
return;
}}
try {{
const stream = await navigator.mediaDevices.getUserMedia({{ audio: true }});
mediaRecorder = new MediaRecorder(stream);
audioChunks = [];
isRecording = true;
micBtn.classList.add("recording");
micStatus.style.display = "inline";
mediaRecorder.ondataavailable = e => audioChunks.push(e.data);
mediaRecorder.onstop = () => {{
stream.getTracks().forEach(t => t.stop());
const blob = new Blob(audioChunks, {{ type: "audio/webm" }});
pendingAudioBlob = blob;
pendingAudioBlob.name = "mic_recording.webm";
fileName.textContent = "mic_recording.webm";
sendAudio.style.display = "inline-block";
}};
mediaRecorder.start();
}} catch(e) {{
addError("Microphone access denied: " + e.message);
}}
}});
sendAudio.addEventListener("click", async () => {{
sendAudio.style.display = "none";
fileName.textContent = "";
await sendAudioBlob(pendingAudioBlob, pendingAudioBlob.name);
}});
fileInput.addEventListener("change", () => {{
if (fileInput.files[0]) {{
pendingAudioBlob = fileInput.files[0];
fileName.textContent = fileInput.files[0].name;
sendAudio.style.display = "inline-block";
}}
}});
// โโ Key + button bindings โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
sendBtn.addEventListener("click", sendText);
textInput.addEventListener("keydown", e => {{
if (e.key === "Enter" && !e.shiftKey) {{ e.preventDefault(); sendText(); }}
}});
textInput.addEventListener("input", () => {{
textInput.style.height = "42px";
textInput.style.height = Math.min(textInput.scrollHeight, 120) + "px";
}});
</script>
</body>
</html>
""", height=iframe_height, scrolling=False)
|