chatbots / chatbot.py
rahulmolasi's picture
Create chatbot.py
54fa61f verified
Raw History Blame Contribute Delete
5.41 kB
import streamlit as st
import json
import difflib
import random
from datetime import datetime
# -----------------------------
# Load secrets from Hugging Face Secrets
# -----------------------------
USER_CREDENTIALS = st.secrets["general"]["user_credentials"]
PRODUCT_DATA = json.loads(st.secrets["general"]["product_data_json"])
QUIZ_DATA = json.loads(st.secrets["general"]["quiz_data_json"])
# -----------------------------
# Initialize session state
# -----------------------------
if "chat_history" not in st.session_state:
st.session_state.chat_history = []
if "quiz_score" not in st.session_state:
st.session_state.quiz_score = 0
if "quiz_attempts" not in st.session_state:
st.session_state.quiz_attempts = 0
if "logged_in" not in st.session_state:
st.session_state.logged_in = False
if "username" not in st.session_state:
st.session_state.username = ""
# -----------------------------
# Login function
# -----------------------------
def login():
st.title("πŸ” Sales Mentor Chatbot Login")
username = st.text_input("Username")
password = st.text_input("Password", type="password")
if st.button("Login"):
if username in USER_CREDENTIALS and USER_CREDENTIALS[username] == password:
st.session_state.logged_in = True
st.session_state.username = username
st.success("Login successful!")
else:
st.error("Invalid credentials")
# -----------------------------
# Fuzzy match for NLP queries
# -----------------------------
def get_best_match(query, data_keys):
return difflib.get_close_matches(query, data_keys, n=1, cutoff=0.6)
# -----------------------------
# Respond to product query
# -----------------------------
def respond_to_query(query):
match = get_best_match(query.lower(), PRODUCT_DATA.keys())
if match:
product = PRODUCT_DATA[match[0]]
response = f"**{match[0]}**:\n- Composition: {product['composition']}\n- Indication: {product['indication']}\n- Dosage: {product['dosage']}\n- Warnings: {product['warnings']}"
return response
else:
return "Sorry, I couldn't find that product. Try checking the spelling or ask about another."
# -----------------------------
# Start quiz for a product
# -----------------------------
def start_quiz(product_name):
questions = QUIZ_DATA.get(product_name, [])
if not questions:
st.warning("No quiz available for this product.")
return
question = random.choice(questions)
st.markdown(f"**Quiz:** {question['question']}")
selected = st.radio("Choose your answer:", question["options"])
if st.button("Submit Answer"):
st.session_state.quiz_attempts += 1
if selected == question["answer"]:
st.success("Correct!")
st.session_state.quiz_score += 1
else:
st.error(f"Incorrect. Correct answer: {question['answer']}")
# -----------------------------
# Show quiz summary
# -----------------------------
def show_quiz_summary():
st.markdown(f"**Quiz Summary**")
st.write(f"Attempts: {st.session_state.quiz_attempts}")
st.write(f"Score: {st.session_state.quiz_score}")
# -----------------------------
# Admin dashboard
# -----------------------------
def admin_dashboard():
st.title("πŸ“Š Admin Dashboard")
st.write(f"User: {st.session_state.username}")
st.write(f"Login Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
st.write(f"Questions Asked: {len(st.session_state.chat_history)}")
st.write("πŸ“˜ Quiz Performance")
st.write(f"Total Attempts: {st.session_state.quiz_attempts}")
st.write(f"Total Score: {st.session_state.quiz_score}")
for q, a in st.session_state.chat_history:
st.markdown(f"- **Q:** {q}\n **A:** {a}")
# -----------------------------
# Chatbot UI
# -----------------------------
def chat_ui():
st.title("πŸ’¬ Sales Mentor Bot")
st.markdown("Hello! I'm your sales mentor. Choose a topic or type your question:")
tiles = ["1. Product Info", "2. FAQs", "3. Objections", "4. Quiz", "5. Recall History"]
selected_tile = st.selectbox("Select an option:", tiles)
if selected_tile.startswith("1"):
user_input = st.text_input("Ask about a product:")
if user_input:
response = respond_to_query(user_input)
st.session_state.chat_history.append((user_input, response))
st.markdown(f"**You:** {user_input}")
st.markdown(f"**Bot:** {response}")
elif selected_tile.startswith("2"):
faqs = PRODUCT_DATA["Dytor"]["faq"]
st.markdown("**FAQs for Dytor:**")
for faq in faqs:
st.markdown(f"- {faq}")
elif selected_tile.startswith("3"):
objections = PRODUCT_DATA["Dytor"]["objections"]
st.markdown("**Common Objections for Dytor:**")
for obj in objections:
st.markdown(f"- {obj}")
elif selected_tile.startswith("4"):
start_quiz("Dytor")
show_quiz_summary()
elif selected_tile.startswith("5"):
st.markdown("**Conversation History:**")
for q, a in st.session_state.chat_history:
st.markdown(f"- **You:** {q}\n **Bot:** {a}")
# -----------------------------
# App flow
# -----------------------------
if not st.session_state.logged_in:
login()
elif st.session_state.username == "admin":
admin_dashboard()
else:
chat_ui()