Spaces:
Sleeping
Sleeping
File size: 5,715 Bytes
b4e5268 8f64959 55a8b20 dd507bb 4f4aca6 b4e5268 c6bf6d7 07c1c70 f2450be c6bf6d7 492e3f4 c6bf6d7 a55ea14 7ceafd3 cd35be5 7ceafd3 c6bf6d7 f2450be 7ceafd3 c6bf6d7 1fe0c9e 6a7d03a f2450be b4c9e55 b956157 b4e5268 b4c9e55 c6bf6d7 b4e5268 c6bf6d7 1fe0c9e b4e5268 ae054a7 4f4aca6 b4c9e55 b4e5268 f2450be b4e5268 fc390a9 b4c9e55 f2450be b4e5268 b4c9e55 b4e5268 6812dc5 7ceafd3 d0f636a 3e67ebc 7ceafd3 d0f636a 3e67ebc 7199998 f2450be c6bf6d7 f2450be c6bf6d7 f2450be c6bf6d7 f2450be c6bf6d7 0eec04d c6bf6d7 fc390a9 492e3f4 c6bf6d7 7199998 fc390a9 7199998 ab39ce5 fc390a9 7199998 3f54657 7199998 fc390a9 3f54657 fc390a9 ab39ce5 7199998 ab39ce5 7199998 ab39ce5 0e4838c |
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 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 |
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
# Load Google service account credentials from Hugging Face secrets
GOOGLE_SERVICE_ACCOUNT_JSON = st.secrets["GOOGLE_SERVICE_ACCOUNT_JSON"]
# Google Sheets API v4 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)
spreadsheet_id = '1Jf1k7Q71ihsxBf-XQYyucamMy14q7IjhUDlU8ZzR_Nc' # Replace with your actual spreadsheet ID
sheet = client.open_by_key(spreadsheet_id).sheet1
# 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
# Session state to hold user input and chatbot response
if 'user_input' not in st.session_state:
st.session_state.user_input = ""
if 'bot_response' not in st.session_state:
st.session_state.bot_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;
}
.centered-orange-text {
text-align: center;
color: darkorange;
}
</style>
""", unsafe_allow_html=True)
# Use CSS classes to style the text
st.markdown('<h3 class="centered-text">🤖 AlteriaChat 🤖 </h3>', unsafe_allow_html=True)
st.markdown('<p class="centered-orange-text">"Votre Réponse à Chaque Défi Méthodologique "</p>', unsafe_allow_html=True)
# Input form for user interaction
with st.form(key='interaction_form'):
st.session_state.user_input = st.text_input("You:", key="user_input_input")
ask_button = st.form_submit_button("Ask 📨") # Button to submit the question
if ask_button and st.session_state.user_input.strip():
st.session_state.bot_response = chatbot_response(st.session_state.user_input)
# Display the bot response if available
if st.session_state.bot_response:
st.markdown("### Bot:")
st.text_area("", value=st.session_state.bot_response, height=600)
# Separate form for feedback submission
with st.form(key='feedback_form'):
st.markdown("### Rate the response:")
rating = st.slider("Select a rating:", min_value=1, max_value=5, value=1, key="rating")
st.markdown("### Leave a comment:")
comment = st.text_area("", key="comment")
# Separate submit button for feedback
feedback_submit_button = st.form_submit_button("Submit Feedback")
if feedback_submit_button:
if comment.strip():
save_feedback(st.session_state.user_input, st.session_state.bot_response, rating, comment)
st.success("Thank you for your feedback!")
# Clear the session state after submission
st.session_state.user_input = ""
st.session_state.bot_response = ""
else:
st.warning("Please provide a comment before submitting feedback.")
st.markdown("---")
st.markdown("Collaboration is the key to success. Each question finds its answer, each challenge becomes an opportunity.")
|