testing / app.py
mery22's picture
Update app.py
c6bf6d7 verified
raw
history blame
6.78 kB
import os
import streamlit as st
from langchain_community.vectorstores import FAISS
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_huggingface import HuggingFaceEndpoint
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain, RetrievalQA
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import json
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import json
# Load Google service account credentials from Hugging Face secrets
GOOGLE_SERVICE_ACCOUNT_JSON = st.secrets["GOOGLE_SERVICE_ACCOUNT_JSON"]
# Google Sheets setup
scope = ["https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/drive"]
service_account_info = json.loads(GOOGLE_SERVICE_ACCOUNT_JSON)
creds = ServiceAccountCredentials.from_json_keyfile_dict(service_account_info, scope)
client = gspread.authorize(creds)
sheet = client.open("users feedback").sheet1 # Replace with your Google Sheet name
# Function to save user feedback to Google Sheets
def save_feedback(user_input, bot_response, rating, comment):
feedback = [user_input, bot_response, rating, comment]
sheet.append_row(feedback)
# Hugging Face API login
from huggingface_hub import login
login(token=st.secrets["HF_TOKEN"])
# Initialize LangChain components
db = FAISS.load_local("faiss_index", HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L12-v2'), allow_dangerous_deserialization=True)
retriever = db.as_retriever(search_type="mmr", search_kwargs={'k': 1})
prompt_template = """
### [INST]
Instruction: You are a Q&A assistant. Your goal is to answer questions as accurately as possible based on the instructions and context provided without using prior knowledge. You answer in FRENCH.
Analyse carefully the context and provide a direct answer based on the context. If the user says Bonjour or Hello, your only answer will be: Hi! comment puis-je vous aider?
Answer in french only
{context}
Vous devez répondre aux questions en français.
### QUESTION:
{question}
[/INST]
Answer in french only
Vous devez répondre aux questions en français.
"""
repo_id = "mistralai/Mistral-7B-Instruct-v0.3"
mistral_llm = HuggingFaceEndpoint(
repo_id=repo_id, max_length=2048, temperature=0.05, huggingfacehub_api_token=st.secrets["HF_TOKEN"]
)
# Create prompt from prompt template
prompt = PromptTemplate(
input_variables=["question"],
template=prompt_template,
)
# Create llm chain
llm_chain = LLMChain(llm=mistral_llm, prompt=prompt)
# Create RetrievalQA chain
qa = RetrievalQA.from_chain_type(
llm=mistral_llm,
chain_type="stuff",
retriever=retriever,
chain_type_kwargs={"prompt": prompt},
)
# Streamlit interface with improved aesthetics
st.set_page_config(page_title="Alter-IA Chat", page_icon="🤖")
# Define function to handle user input and display chatbot response
def chatbot_response(user_input):
response = qa.run(user_input)
return response
# Create columns for logos
col1, col2, col3 = st.columns([2, 3, 2])
with col1:
st.image("Design 3_22.png", width=150, use_column_width=True) # Adjust image path and size as needed
with col3:
st.image("Altereo logo 2023 original - eau et territoires durables.png", width=150, use_column_width=True) # Adjust image path and size as needed
# Streamlit components
st.markdown("""
<style>
.centered-text {
text-align: center;
}
.stars {
font-size: 24px;
color: lightgray;
cursor: pointer;
}
.stars:hover,
.stars.selected {
color: gold;
}
.stars.filled {
color: gold;
}
</style>
""", unsafe_allow_html=True)
# Star rating system with JavaScript
st.markdown("""
<script>
function setRating(starId) {
const stars = document.querySelectorAll('.stars');
stars.forEach(star => star.classList.remove('filled'));
document.querySelectorAll('.stars').forEach(star => {
if (star.dataset.rating <= starId) {
star.classList.add('filled');
}
});
document.getElementById('rating').value = starId;
}
document.addEventListener('DOMContentLoaded', (event) => {
document.querySelectorAll('.stars').forEach(star => {
star.addEventListener('click', () => {
setRating(star.dataset.rating);
});
});
});
</script>
""", unsafe_allow_html=True)
# Display star rating
st.markdown('<div class="stars" data-rating="1">&#9733;</div>', unsafe_allow_html=True)
st.markdown('<div class="stars" data-rating="2">&#9733;</div>', unsafe_allow_html=True)
st.markdown('<div class="stars" data-rating="3">&#9733;</div>', unsafe_allow_html=True)
st.markdown('<div class="stars" data-rating="4">&#9733;</div>', unsafe_allow_html=True)
st.markdown('<div class="stars" data-rating="5">&#9733;</div>', unsafe_allow_html=True)
# Hidden input field to store the rating value
st.markdown('<input type="hidden" id="rating" value="0">', unsafe_allow_html=True)
# Input and button for user interaction
user_input = st.text_input("You:", "")
submit_button = st.button("Ask 📨")
# Handle user input
if submit_button:
if user_input.strip() != "":
bot_response = chatbot_response(user_input)
st.markdown("### Bot:")
st.text_area("", value=bot_response, height=600)
# Feedback form
st.markdown("### Rate the response:")
st.markdown('<p>Please click on the stars to rate the response.</p>', unsafe_allow_html=True)
st.markdown('<p id="rating-value">Rating: 0</p>', unsafe_allow_html=True)
st.markdown("### Leave a comment:")
comment = st.text_area("")
# Update rating value on star click
st.markdown("""
<script>
document.querySelectorAll('.stars').forEach(star => {
star.addEventListener('click', function() {
document.getElementById('rating-value').innerText = 'Rating: ' + this.dataset.rating;
});
});
</script>
""", unsafe_allow_html=True)
# Feedback submission
if st.button("Submit Feedback"):
rating = st.text_input("Rating", value="0")
if comment.strip() and rating != "0":
save_feedback(user_input, bot_response, rating, comment)
st.success("Thank you for your feedback!")
else:
st.warning("⚠️ Please provide a comment and a rating.")
# Motivational quote at the bottom
st.markdown("---")
st.markdown("La collaboration est la clé du succès. Chaque question trouve sa réponse, chaque défi devient une opportunité.")