Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -6,33 +6,33 @@ from llama_cpp import Llama
|
|
6 |
from huggingface_hub import hf_hub_download
|
7 |
import chromadb
|
8 |
from sentence_transformers import SentenceTransformer
|
9 |
-
|
10 |
-
import os
|
11 |
-
from huggingface_hub import login
|
12 |
|
13 |
# Charger le token depuis les secrets
|
14 |
hf_token = os.getenv("HF_TOKEN") # Assurez-vous que 'HF_TOKEN' est bien le nom du secret Hugging Face
|
15 |
|
16 |
# Connecte-toi à Hugging Face
|
17 |
login(hf_token)
|
18 |
-
# Charger le dataset
|
19 |
-
dataset = load_dataset("Maryem2025/dataset-train") # Changez le nom si nécessaire
|
20 |
|
21 |
-
#
|
|
|
|
|
|
|
22 |
llm = Llama(
|
23 |
model_path=hf_hub_download(
|
24 |
repo_id="TheBloke/CapybaraHermes-2.5-Mistral-7B-GGUF",
|
25 |
filename="capybarahermes-2.5-mistral-7b.Q2_K.gguf",
|
26 |
),
|
27 |
-
n_ctx=
|
28 |
n_gpu_layers=50, # Ajustez selon votre VRAM
|
29 |
)
|
30 |
|
31 |
# Initialisation de ChromaDB Vector Store
|
32 |
class VectorStore:
|
33 |
-
def __init__(self, collection_name):
|
34 |
self.embedding_model = SentenceTransformer('sentence-transformers/multi-qa-MiniLM-L6-cos-v1')
|
35 |
self.chroma_client = chromadb.Client()
|
|
|
36 |
|
37 |
# Supprimer la collection existante si elle existe
|
38 |
if collection_name in self.chroma_client.list_collections():
|
@@ -46,35 +46,48 @@ class VectorStore:
|
|
46 |
names = dataset['train']['name'][:200]
|
47 |
ingredients = dataset['train']['ingredients'][:200]
|
48 |
instructions = dataset['train']['instructions'][:200]
|
49 |
-
|
50 |
-
|
51 |
-
#total_time = dataset['train']['total_time'][:200]
|
52 |
|
53 |
# Concaténer les textes à partir des colonnes sélectionnées
|
54 |
texts = [
|
55 |
-
|
56 |
-
|
57 |
-
f"Name: {name}. Ingredients: {ingr}. Instructions: {instr}."
|
58 |
-
for name, ingr, instr in zip(names, ingredients, instructions)
|
59 |
]
|
60 |
|
61 |
-
|
|
|
|
|
62 |
for i, item in enumerate(texts):
|
63 |
embeddings = self.embedding_model.encode(item).tolist()
|
64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
|
66 |
def search_context(self, query, n_results=1):
|
67 |
query_embedding = self.embedding_model.encode([query]).tolist()
|
68 |
results = self.collection.query(query_embeddings=query_embedding, n_results=n_results)
|
69 |
return results['documents']
|
70 |
|
71 |
-
|
72 |
-
|
73 |
vector_store = VectorStore("embedding_vector")
|
74 |
vector_store.populate_vectors(dataset)
|
75 |
|
76 |
# Fonction pour générer du texte
|
77 |
def generate_text(message, max_tokens, temperature, top_p):
|
|
|
|
|
|
|
78 |
# Récupérer le contexte depuis le store de vecteurs
|
79 |
context_results = vector_store.search_context(message, n_results=1)
|
80 |
context = context_results[0] if context_results else ""
|
@@ -90,19 +103,24 @@ def generate_text(message, max_tokens, temperature, top_p):
|
|
90 |
# Générer le texte avec le modèle de langue
|
91 |
output = llm(
|
92 |
prompt_template,
|
93 |
-
temperature=
|
94 |
-
top_p=
|
95 |
top_k=40,
|
96 |
repeat_penalty=1.1,
|
97 |
-
max_tokens=
|
98 |
)
|
99 |
|
100 |
# Traiter la sortie
|
101 |
input_string = output['choices'][0]['text'].strip()
|
102 |
cleaned_text = input_string.strip("[]'").replace('\\n', '\n')
|
103 |
continuous_text = '\n'.join(cleaned_text.split('\n'))
|
|
|
|
|
|
|
|
|
104 |
return continuous_text
|
105 |
|
|
|
106 |
# Définir l'interface Gradio
|
107 |
demo = gr.Interface(
|
108 |
fn=generate_text,
|
@@ -110,8 +128,9 @@ demo = gr.Interface(
|
|
110 |
gr.Textbox(lines=2, placeholder="Enter your message here...", label="Message"),
|
111 |
],
|
112 |
outputs=gr.Textbox(label="Generated Text"),
|
113 |
-
title="Chatbot - Your Personal Culinary Advisor
|
114 |
description="Running LLM with context retrieval from ChromaDB",
|
|
|
115 |
examples=[
|
116 |
["I have leftover rice, what can I make out of it?"],
|
117 |
["I just have some milk and chocolate, what dessert can I make?"],
|
@@ -119,8 +138,7 @@ demo = gr.Interface(
|
|
119 |
["Can you suggest a vegan breakfast recipe?"],
|
120 |
["How do I make a perfect scrambled egg?"],
|
121 |
["Can you guide me through making a soufflé?"],
|
122 |
-
],
|
123 |
-
cache_examples=False,
|
124 |
)
|
125 |
|
126 |
if __name__ == "__main__":
|
|
|
6 |
from huggingface_hub import hf_hub_download
|
7 |
import chromadb
|
8 |
from sentence_transformers import SentenceTransformer
|
9 |
+
import time
|
|
|
|
|
10 |
|
11 |
# Charger le token depuis les secrets
|
12 |
hf_token = os.getenv("HF_TOKEN") # Assurez-vous que 'HF_TOKEN' est bien le nom du secret Hugging Face
|
13 |
|
14 |
# Connecte-toi à Hugging Face
|
15 |
login(hf_token)
|
|
|
|
|
16 |
|
17 |
+
# Charger le dataset une seule fois
|
18 |
+
dataset = load_dataset("Maryem2025/dataset-test") # Chargez le dataset une fois
|
19 |
+
|
20 |
+
# Initialisation du modèle Llama avec une taille de contexte réduite
|
21 |
llm = Llama(
|
22 |
model_path=hf_hub_download(
|
23 |
repo_id="TheBloke/CapybaraHermes-2.5-Mistral-7B-GGUF",
|
24 |
filename="capybarahermes-2.5-mistral-7b.Q2_K.gguf",
|
25 |
),
|
26 |
+
n_ctx=1024, # Réduire la taille du contexte
|
27 |
n_gpu_layers=50, # Ajustez selon votre VRAM
|
28 |
)
|
29 |
|
30 |
# Initialisation de ChromaDB Vector Store
|
31 |
class VectorStore:
|
32 |
+
def __init__(self, collection_name, batch_size=10):
|
33 |
self.embedding_model = SentenceTransformer('sentence-transformers/multi-qa-MiniLM-L6-cos-v1')
|
34 |
self.chroma_client = chromadb.Client()
|
35 |
+
self.batch_size = batch_size
|
36 |
|
37 |
# Supprimer la collection existante si elle existe
|
38 |
if collection_name in self.chroma_client.list_collections():
|
|
|
46 |
names = dataset['train']['name'][:200]
|
47 |
ingredients = dataset['train']['ingredients'][:200]
|
48 |
instructions = dataset['train']['instructions'][:200]
|
49 |
+
cuisine = dataset['train']['cuisine'][:200]
|
50 |
+
total_time = dataset['train']['total_time'][:200]
|
|
|
51 |
|
52 |
# Concaténer les textes à partir des colonnes sélectionnées
|
53 |
texts = [
|
54 |
+
f"Name: {name}. Ingredients: {ingr}. Instructions: {instr}. Cuisine: {cui}. Total time: {total} minutes."
|
55 |
+
for name, ingr, instr, cui, total in zip(names, ingredients, instructions, cuisine, total_time)
|
|
|
|
|
56 |
]
|
57 |
|
58 |
+
embeddings_batch = []
|
59 |
+
documents_batch = []
|
60 |
+
|
61 |
for i, item in enumerate(texts):
|
62 |
embeddings = self.embedding_model.encode(item).tolist()
|
63 |
+
embeddings_batch.append(embeddings)
|
64 |
+
documents_batch.append(item)
|
65 |
+
|
66 |
+
# Quand le batch est plein, on ajoute les embeddings
|
67 |
+
if len(embeddings_batch) >= self.batch_size:
|
68 |
+
self.collection.add(embeddings=embeddings_batch, documents=documents_batch, ids=[str(i) for i in range(i - self.batch_size + 1, i + 1)])
|
69 |
+
embeddings_batch = []
|
70 |
+
documents_batch = []
|
71 |
+
|
72 |
+
# Ajouter les derniers items restants s'il y en a
|
73 |
+
if embeddings_batch:
|
74 |
+
self.collection.add(embeddings=embeddings_batch, documents=documents_batch, ids=[str(i) for i in range(len(texts) - len(embeddings_batch), len(texts))])
|
75 |
|
76 |
def search_context(self, query, n_results=1):
|
77 |
query_embedding = self.embedding_model.encode([query]).tolist()
|
78 |
results = self.collection.query(query_embeddings=query_embedding, n_results=n_results)
|
79 |
return results['documents']
|
80 |
|
81 |
+
|
82 |
+
# Initialisation du store de vecteurs et peuplement du dataset
|
83 |
vector_store = VectorStore("embedding_vector")
|
84 |
vector_store.populate_vectors(dataset)
|
85 |
|
86 |
# Fonction pour générer du texte
|
87 |
def generate_text(message, max_tokens, temperature, top_p):
|
88 |
+
# Profiler le temps d'exécution de la génération de texte
|
89 |
+
start_time = time.time()
|
90 |
+
|
91 |
# Récupérer le contexte depuis le store de vecteurs
|
92 |
context_results = vector_store.search_context(message, n_results=1)
|
93 |
context = context_results[0] if context_results else ""
|
|
|
103 |
# Générer le texte avec le modèle de langue
|
104 |
output = llm(
|
105 |
prompt_template,
|
106 |
+
temperature=temperature,
|
107 |
+
top_p=top_p,
|
108 |
top_k=40,
|
109 |
repeat_penalty=1.1,
|
110 |
+
max_tokens=max_tokens,
|
111 |
)
|
112 |
|
113 |
# Traiter la sortie
|
114 |
input_string = output['choices'][0]['text'].strip()
|
115 |
cleaned_text = input_string.strip("[]'").replace('\\n', '\n')
|
116 |
continuous_text = '\n'.join(cleaned_text.split('\n'))
|
117 |
+
|
118 |
+
# Afficher le temps d'exécution
|
119 |
+
print(f"Temps d'exécution pour générer du texte : {time.time() - start_time} secondes")
|
120 |
+
|
121 |
return continuous_text
|
122 |
|
123 |
+
|
124 |
# Définir l'interface Gradio
|
125 |
demo = gr.Interface(
|
126 |
fn=generate_text,
|
|
|
128 |
gr.Textbox(lines=2, placeholder="Enter your message here...", label="Message"),
|
129 |
],
|
130 |
outputs=gr.Textbox(label="Generated Text"),
|
131 |
+
title="Chatbot - Your Personal Culinary Advisor",
|
132 |
description="Running LLM with context retrieval from ChromaDB",
|
133 |
+
cache_examples=False, # Désactivez le cache
|
134 |
examples=[
|
135 |
["I have leftover rice, what can I make out of it?"],
|
136 |
["I just have some milk and chocolate, what dessert can I make?"],
|
|
|
138 |
["Can you suggest a vegan breakfast recipe?"],
|
139 |
["How do I make a perfect scrambled egg?"],
|
140 |
["Can you guide me through making a soufflé?"],
|
141 |
+
], # Réduire le nombre d'exemples pour accélérer
|
|
|
142 |
)
|
143 |
|
144 |
if __name__ == "__main__":
|