gauravsahu1990's picture
Upload folder using huggingface_hub
2f0696c verified
import streamlit as st
import requests
import pandas as pd
import base64
import logging
import time
# -------------------------------------------------------
# 🧾 Logging Configuration
# -------------------------------------------------------
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s] [%(levelname)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
logger = logging.getLogger("ChatBot-Frontend")
logger.info("πŸš€ Starting ChatBot frontend...")
# -------------------------------------------------------
# βš™οΈ Backend URL (update for your Hugging Face Space)
# -------------------------------------------------------
BACKEND_URL = "https://gauravsahu1990-Chat-Bot-Backend.hf.space/api/ask" # Adjust if hosted elsewhere
# -------------------------------------------------------
# 🧠 Streamlit App Setup
# -------------------------------------------------------
st.set_page_config(page_title="Chat Assistant", page_icon="🧠", layout="wide")
st.title("🧠 Chat Assistant")
st.write("Ask your question β€” I’ll show the result and chart!")
# -------------------------------------------------------
# πŸ’¬ User Input
# -------------------------------------------------------
question = st.text_input("πŸ’¬ Ask your question:", placeholder="e.g., Show total order amount by customer")
# -------------------------------------------------------
# πŸŽ›οΈ Query Submission
# -------------------------------------------------------
if st.button("Ask"):
if not question.strip():
st.warning("Please enter a question.")
else:
with st.spinner("Thinking..."):
start_time = time.time()
try:
logger.info(f"πŸ—¨οΈ Sending question to backend: {question}")
response = requests.post(BACKEND_URL, json={"question": question}, timeout=60)
elapsed = round(time.time() - start_time, 2)
logger.info(f"⏱️ Backend responded in {elapsed}s, status {response.status_code}")
if response.status_code != 200:
st.error(f"❌ Backend returned HTTP {response.status_code}")
logger.error(f"❌ Backend response: {response.text}")
else:
try:
data = response.json()
logger.info(f"βœ… JSON parsed successfully: keys={list(data.keys())}")
st.markdown("### πŸ“Š Result")
st.markdown(data.get("answer", ""), unsafe_allow_html=True)
if data.get("chart"):
st.markdown("### πŸ“ˆ Visualization")
img_bytes = base64.b64decode(data["chart"])
st.image(img_bytes, use_container_width=True)
logger.info("πŸ“ˆ Chart displayed successfully.")
else:
st.info("No chart available for this query.")
logger.info("ℹ️ No chart returned from backend.")
except Exception as json_err:
st.error("⚠️ Failed to parse backend response. Check logs for details.")
logger.exception(f"❌ JSON parsing error: {json_err}")
logger.error(f"Raw response: {response.text}")
except requests.exceptions.ConnectionError as conn_err:
st.error("⚠️ Could not connect to backend. Is it running?")
logger.exception(f"❌ Connection error: {conn_err}")
except requests.exceptions.Timeout:
st.error("⚠️ Backend took too long to respond.")
logger.error("⏰ Request timeout after 60s.")
except Exception as e:
st.error(f"⚠️ Unexpected error: {e}")
logger.exception(f"❌ Unexpected frontend error: {e}")