File size: 3,936 Bytes
5a89f5c
 
 
3c2ac6b
 
 
 
 
 
 
 
 
 
 
 
 
5a89f5c
3c2ac6b
5a89f5c
3c2ac6b
 
 
2f0696c
5a89f5c
3c2ac6b
 
 
 
 
 
5a89f5c
3c2ac6b
 
 
5a89f5c
 
3c2ac6b
 
 
5a89f5c
 
 
 
 
3c2ac6b
5a89f5c
3c2ac6b
 
 
 
5a89f5c
3c2ac6b
 
 
5a89f5c
3c2ac6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a89f5c
 
3c2ac6b
 
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
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}")