Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +18 -49
src/streamlit_app.py
CHANGED
|
@@ -1,60 +1,30 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
import os
|
| 3 |
-
import gdown
|
| 4 |
from llama_cpp import Llama
|
| 5 |
from langchain_community.vectorstores import FAISS
|
| 6 |
from langchain_community.embeddings import HuggingFaceEmbeddings
|
|
|
|
| 7 |
|
| 8 |
# --- Configuration de la page Streamlit ---
|
| 9 |
st.set_page_config(page_title="Votre Coach RAG", layout="wide")
|
| 10 |
st.title("Votre Coach Expert")
|
| 11 |
st.write("Posez une question sur vos documents, et je vous répondrai en me basant sur leur contenu.")
|
| 12 |
|
| 13 |
-
|
| 14 |
-
# --- Chemins et URL ---
|
| 15 |
-
# MODIFICATION : On cible un dossier dans /tmp, qui est toujours accessible en écriture
|
| 16 |
-
DOSSIER_MODELE_TMP = "/tmp/downloaded_model"
|
| 17 |
-
NOM_FICHIER_MODELE = "Meta-Llama-3-8B-Instruct.Q4_K_M.gguf"
|
| 18 |
-
CHEMIN_MODELE_LOCAL = os.path.join(DOSSIER_MODELE_TMP, NOM_FICHIER_MODELE)
|
| 19 |
-
ID_DRIVE_MODELE = "1LujSBXb8LTgbLdj27klizQJB-M7p0Oob" # Votre ID de fichier Google Drive
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
def download_model_from_drive(output_path):
|
| 23 |
-
"""
|
| 24 |
-
Télécharge le modèle depuis Google Drive dans le dossier /tmp si le fichier n'existe pas.
|
| 25 |
-
"""
|
| 26 |
-
# Crée le dossier de destination dans /tmp s'il n'existe pas
|
| 27 |
-
# Cela va maintenant fonctionner car on a le droit d'écrire dans /tmp
|
| 28 |
-
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
| 29 |
-
|
| 30 |
-
if not os.path.exists(output_path):
|
| 31 |
-
with st.spinner(f"Téléchargement du modèle depuis Google Drive vers {output_path}... (une seule fois par session)"):
|
| 32 |
-
try:
|
| 33 |
-
gdown.download(id=ID_DRIVE_MODELE, output=output_path, quiet=False)
|
| 34 |
-
st.success("Modèle téléchargé avec succès !")
|
| 35 |
-
except Exception as e:
|
| 36 |
-
st.error(f"Échec du téléchargement depuis Google Drive : {e}")
|
| 37 |
-
st.stop()
|
| 38 |
-
return output_path
|
| 39 |
-
|
| 40 |
# --- Fonctions de chargement mises en cache ---
|
| 41 |
@st.cache_resource
|
| 42 |
def load_llm():
|
| 43 |
-
""
|
| 44 |
-
|
| 45 |
-
"""
|
| 46 |
-
# Étape 1: S'assurer que le fichier est bien là en utilisant notre nouvelle fonction
|
| 47 |
-
model_path = download_model_from_drive(CHEMIN_MODELE_LOCAL)
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
n_ctx=4096,
|
| 55 |
-
verbose=False,
|
| 56 |
-
chat_format="llama-3"
|
| 57 |
)
|
|
|
|
|
|
|
|
|
|
| 58 |
return llm
|
| 59 |
|
| 60 |
@st.cache_resource
|
|
@@ -64,15 +34,15 @@ def load_retriever(faiss_path, embeddings_path):
|
|
| 64 |
vectorstore = FAISS.load_local(faiss_path, embeddings_model, allow_dangerous_deserialization=True)
|
| 65 |
return vectorstore.as_retriever(search_kwargs={"k": 5})
|
| 66 |
|
| 67 |
-
# --- Chemins d'accès (relatifs)
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
|
|
|
| 71 |
|
| 72 |
-
# --- Chargement
|
| 73 |
try:
|
| 74 |
llm = load_llm()
|
| 75 |
-
# On suppose que les autres fichiers (FAISS, embeddings) sont bien dans votre dépôt Git
|
| 76 |
retriever = load_retriever(CHEMIN_INDEX_FAISS, CHEMIN_MODELE_EMBEDDINGS)
|
| 77 |
st.success("Les modèles sont chargés et prêts !")
|
| 78 |
except Exception as e:
|
|
@@ -89,7 +59,7 @@ for message in st.session_state.messages:
|
|
| 89 |
st.markdown(message["content"])
|
| 90 |
|
| 91 |
# --- Logique de Chat ---
|
| 92 |
-
if prompt := st.chat_input("Posez votre question ici
|
| 93 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 94 |
with st.chat_message("user"):
|
| 95 |
st.markdown(prompt)
|
|
@@ -98,7 +68,6 @@ if prompt := st.chat_input("Posez votre question ici...."):
|
|
| 98 |
with st.spinner("Je réfléchis..."):
|
| 99 |
docs = retriever.invoke(prompt)
|
| 100 |
context = "\n".join([doc.page_content for doc in docs])
|
| 101 |
-
|
| 102 |
system_prompt = "Vous êtes Un coach expert. Répondez à la question en vous basant uniquement sur le contexte fourni."
|
| 103 |
full_prompt = f"""<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n{system_prompt}\nContexte : {context}<|eot_id|><|start_header_id|>user<|end_header_id|>\nQuestion : {prompt}<|eot_id|><|start_header_id|>assistant<|end_header_id|>"""
|
| 104 |
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import os
|
|
|
|
| 3 |
from llama_cpp import Llama
|
| 4 |
from langchain_community.vectorstores import FAISS
|
| 5 |
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 6 |
+
from huggingface_hub import hf_hub_download
|
| 7 |
|
| 8 |
# --- Configuration de la page Streamlit ---
|
| 9 |
st.set_page_config(page_title="Votre Coach RAG", layout="wide")
|
| 10 |
st.title("Votre Coach Expert")
|
| 11 |
st.write("Posez une question sur vos documents, et je vous répondrai en me basant sur leur contenu.")
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
# --- Fonctions de chargement mises en cache ---
|
| 14 |
@st.cache_resource
|
| 15 |
def load_llm():
|
| 16 |
+
model_repo_id = "QuantFactory/Meta-Llama-3-8B-Instruct-GGUF"
|
| 17 |
+
model_filename = "Meta-Llama-3-8B-Instruct.Q4_K_M.gguf"
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
+
with st.spinner(f"Téléchargement du modèle '{model_filename}'... (Cette étape est longue et n'a lieu qu'une seule fois)"):
|
| 20 |
+
model_path = hf_hub_download(
|
| 21 |
+
repo_id=model_repo_id,
|
| 22 |
+
filename=model_filename,
|
| 23 |
+
cache_dir='/tmp/hf_cache'
|
|
|
|
|
|
|
|
|
|
| 24 |
)
|
| 25 |
+
|
| 26 |
+
with st.spinner("Chargement du modèle LLM en mémoire..."):
|
| 27 |
+
llm = Llama(model_path=model_path, n_gpu_layers=0, n_ctx=4096, verbose=False, chat_format="llama-3")
|
| 28 |
return llm
|
| 29 |
|
| 30 |
@st.cache_resource
|
|
|
|
| 34 |
vectorstore = FAISS.load_local(faiss_path, embeddings_model, allow_dangerous_deserialization=True)
|
| 35 |
return vectorstore.as_retriever(search_kwargs={"k": 5})
|
| 36 |
|
| 37 |
+
# --- Chemins d'accès (relatifs) ---
|
| 38 |
+
# ✅ MODIFICATION : On s'assure que les chemins sont à la racine de l'application '/app'
|
| 39 |
+
# au lieu de '/app/src'. C'est plus simple à gérer.
|
| 40 |
+
CHEMIN_INDEX_FAISS = "faiss_index_wize"
|
| 41 |
+
CHEMIN_MODELE_EMBEDDINGS = "embedding_model"
|
| 42 |
|
| 43 |
+
# --- Chargement des modèles via Streamlit ---
|
| 44 |
try:
|
| 45 |
llm = load_llm()
|
|
|
|
| 46 |
retriever = load_retriever(CHEMIN_INDEX_FAISS, CHEMIN_MODELE_EMBEDDINGS)
|
| 47 |
st.success("Les modèles sont chargés et prêts !")
|
| 48 |
except Exception as e:
|
|
|
|
| 59 |
st.markdown(message["content"])
|
| 60 |
|
| 61 |
# --- Logique de Chat ---
|
| 62 |
+
if prompt := st.chat_input("Posez votre question ici..."):
|
| 63 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 64 |
with st.chat_message("user"):
|
| 65 |
st.markdown(prompt)
|
|
|
|
| 68 |
with st.spinner("Je réfléchis..."):
|
| 69 |
docs = retriever.invoke(prompt)
|
| 70 |
context = "\n".join([doc.page_content for doc in docs])
|
|
|
|
| 71 |
system_prompt = "Vous êtes Un coach expert. Répondez à la question en vous basant uniquement sur le contexte fourni."
|
| 72 |
full_prompt = f"""<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n{system_prompt}\nContexte : {context}<|eot_id|><|start_header_id|>user<|end_header_id|>\nQuestion : {prompt}<|eot_id|><|start_header_id|>assistant<|end_header_id|>"""
|
| 73 |
|