chatbot / app.py
kartavya17's picture
Upload 10 files
5b748d5 verified
Raw History Blame Contribute Delete
5.1 kB
import json
from PyPDF2 import PdfReader
import requests
import streamlit as st
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import nltk
# Load the corpus PDF
def load_corpus(pdf_path):
reader = PdfReader(pdf_path)
corpus_text = ""
for page in reader.pages:
corpus_text += page.extract_text()
return corpus_text
# Load sample question-answers
def load_sample_qa(json_path):
with open(json_path, 'r') as file:
sample_qa = json.load(file)
return sample_qa
# Function to query the Gemini model
def query_gemini_model(prompt, api_key):
url = "https://api.gemini-model.com/v1/query"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
data = {
"prompt": prompt,
"max_tokens": 150
}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
return response.json().get("choices")[0].get("text").strip()
else:
return "Error querying the Gemini model."
# Load data
corpus = load_corpus('Corpus.pdf')
sample_qa = load_sample_qa('Sample Question Answers.json')
# Tokenize sentences
nltk.download('punkt')
sentences = nltk.sent_tokenize(corpus)
# Vectorize sentences
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(sentences)
# Initialize Streamlit app
st.set_page_config(page_title="Wine Chatbot", page_icon="🍷")
# Sidebar with company details
st.sidebar.image("idealwines.jpg",use_column_width=True)
st.sidebar.title("Jessup Cellars")
st.sidebar.write("""
**Jessup Cellars** is a premier wine company known for its exceptional selection of wines from around the world. Our mission is to provide wine enthusiasts with the finest wines and an unparalleled tasting experience. Visit our tasting room or explore our virtual wine tastings to discover your next favorite wine.
""")
st.sidebar.write("### Contact Us")
st.sidebar.write("""
- **Phone:** +1-800-555-WINE
- **Email:** info@idealwine.com
- **Address:** 123 Vineyard Lane, Napa Valley, CA
""")
# Main app
st.title("Jessup Cellars Chatbot 🍾")
st.image("idealwine.jpeg", width=250)
st.header("Ask me anything about wines :)")
# Chatbot history
if 'chat_history' not in st.session_state:
st.session_state['chat_history'] = []
def get_response(user_message):
# First check in sample Q&A
for qa in sample_qa:
if qa['question'].lower() in user_message.lower():
return qa['answer']
# Vectorize user input
Y = vectorizer.transform([user_message])
# Compute similarity
similarity_scores = cosine_similarity(Y, X)
# Get the sentence with the highest similarity score
highest_similarity_score_sentence = sentences[similarity_scores.argmax()]
# If the highest score is very low, it means the user input is out of the corpus
if similarity_scores.max() < 0.1: # You can adjust this threshold
return "I'm sorry, I cannot answer that. Please contact the business directly for more information."
else:
return highest_similarity_score_sentence
# Input and button
user_input = st.text_input("You:", key="user_input")
if st.button("Send"):
if user_input:
st.session_state['chat_history'].append({"user": user_input})
response_message = get_response(user_input)
st.session_state['chat_history'].append({"bot": response_message})
# Display chat history
for message in st.session_state['chat_history']:
if "user" in message:
st.write(f"**You:** {message['user']}")
else:
st.write(f"**Bot:** {message['bot']}")
# Custom CSS for styling
st.markdown(
"""
<style>
.chat-container {
max-width: 600px;
margin: 0 auto;
padding: 10px;
border-radius: 10px;
background-color: #f0f0f5;
}
.message {
margin: 10px 0;
}
.user {
color: #004d99;
}
.bot {
color: #009933;
}
</style>
""",
unsafe_allow_html=True
)
# Add extra features and widgets
st.sidebar.header("Additional Features")
if st.sidebar.button("About Us"):
st.sidebar.write("""
**Ideal Wine** was established in 1990 by a group of passionate wine enthusiasts. Over the past three decades, we have grown to become a leading name in the wine industry, known for our exceptional quality and commitment to customer satisfaction.
""")
if st.sidebar.button("Special Offers"):
st.sidebar.write("""
- **10% off** your first purchase
- **Free shipping** on orders over \$100
- **Exclusive wine tastings** for members
""")
st.sidebar.header("Newsletter Signup")
email = st.sidebar.text_input("Email Address")
if st.sidebar.button("Subscribe"):
if email:
st.sidebar.write(f"Thank you for subscribing, {email}!")
else:
st.sidebar.write("Please enter a valid email address.")