Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
|
|
| 1 |
import os
|
| 2 |
from huggingface_hub import login
|
| 3 |
from datasets import load_dataset
|
|
@@ -6,33 +7,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 |
|
| 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 |
-
#
|
| 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=
|
| 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
|
| 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,6 +47,7 @@ class VectorStore:
|
|
| 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 |
|
|
@@ -53,41 +55,27 @@ class VectorStore:
|
|
| 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 |
-
|
| 59 |
-
documents_batch = []
|
| 60 |
-
|
| 61 |
for i, item in enumerate(texts):
|
| 62 |
embeddings = self.embedding_model.encode(item).tolist()
|
| 63 |
-
|
| 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 |
-
|
| 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,24 +91,19 @@ def generate_text(message, max_tokens, temperature, top_p):
|
|
| 103 |
# Générer le texte avec le modèle de langue
|
| 104 |
output = llm(
|
| 105 |
prompt_template,
|
| 106 |
-
temperature=
|
| 107 |
-
top_p=
|
| 108 |
top_k=40,
|
| 109 |
repeat_penalty=1.1,
|
| 110 |
-
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,9 +111,8 @@ demo = gr.Interface(
|
|
| 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,7 +120,8 @@ demo = gr.Interface(
|
|
| 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 |
-
],
|
|
|
|
| 142 |
)
|
| 143 |
|
| 144 |
if __name__ == "__main__":
|
|
|
|
| 1 |
+
############ it works , الحمد لله
|
| 2 |
import os
|
| 3 |
from huggingface_hub import login
|
| 4 |
from datasets import load_dataset
|
|
|
|
| 7 |
from huggingface_hub import hf_hub_download
|
| 8 |
import chromadb
|
| 9 |
from sentence_transformers import SentenceTransformer
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
from huggingface_hub import login
|
| 13 |
|
| 14 |
# Charger le token depuis les secrets
|
| 15 |
hf_token = os.getenv("HF_TOKEN") # Assurez-vous que 'HF_TOKEN' est bien le nom du secret Hugging Face
|
| 16 |
|
| 17 |
# Connecte-toi à Hugging Face
|
| 18 |
login(hf_token)
|
| 19 |
+
# Charger le dataset
|
| 20 |
+
dataset = load_dataset("Maryem2025/dataset-train") # Changez le nom si nécessaire
|
| 21 |
|
| 22 |
+
# Initialisation du modèle Llama
|
|
|
|
|
|
|
|
|
|
| 23 |
llm = Llama(
|
| 24 |
model_path=hf_hub_download(
|
| 25 |
repo_id="TheBloke/CapybaraHermes-2.5-Mistral-7B-GGUF",
|
| 26 |
filename="capybarahermes-2.5-mistral-7b.Q2_K.gguf",
|
| 27 |
),
|
| 28 |
+
n_ctx=2048,
|
| 29 |
n_gpu_layers=50, # Ajustez selon votre VRAM
|
| 30 |
)
|
| 31 |
|
| 32 |
# Initialisation de ChromaDB Vector Store
|
| 33 |
class VectorStore:
|
| 34 |
+
def __init__(self, collection_name):
|
| 35 |
self.embedding_model = SentenceTransformer('sentence-transformers/multi-qa-MiniLM-L6-cos-v1')
|
| 36 |
self.chroma_client = chromadb.Client()
|
|
|
|
| 37 |
|
| 38 |
# Supprimer la collection existante si elle existe
|
| 39 |
if collection_name in self.chroma_client.list_collections():
|
|
|
|
| 47 |
names = dataset['train']['name'][:200]
|
| 48 |
ingredients = dataset['train']['ingredients'][:200]
|
| 49 |
instructions = dataset['train']['instructions'][:200]
|
| 50 |
+
|
| 51 |
cuisine = dataset['train']['cuisine'][:200]
|
| 52 |
total_time = dataset['train']['total_time'][:200]
|
| 53 |
|
|
|
|
| 55 |
texts = [
|
| 56 |
f"Name: {name}. Ingredients: {ingr}. Instructions: {instr}. Cuisine: {cui}. Total time: {total} minutes."
|
| 57 |
for name, ingr, instr, cui, total in zip(names, ingredients, instructions, cuisine, total_time)
|
| 58 |
+
#f"Name: {name}. Ingredients: {ingr}. Instructions: {instr}."
|
| 59 |
+
#for name, ingr, instr in zip(names, ingredients, instructions)
|
| 60 |
]
|
| 61 |
|
| 62 |
+
# Ajouter les embeddings au store de vecteurs
|
|
|
|
|
|
|
| 63 |
for i, item in enumerate(texts):
|
| 64 |
embeddings = self.embedding_model.encode(item).tolist()
|
| 65 |
+
self.collection.add(embeddings=[embeddings], documents=[item], ids=[str(i)])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
def search_context(self, query, n_results=1):
|
| 68 |
query_embedding = self.embedding_model.encode([query]).tolist()
|
| 69 |
results = self.collection.query(query_embeddings=query_embedding, n_results=n_results)
|
| 70 |
return results['documents']
|
| 71 |
|
| 72 |
+
# Initialisation du store de vecteurs et peuplement
|
| 73 |
+
dataset = load_dataset('Maryem2025/dataset-test')
|
| 74 |
vector_store = VectorStore("embedding_vector")
|
| 75 |
vector_store.populate_vectors(dataset)
|
| 76 |
|
| 77 |
# Fonction pour générer du texte
|
| 78 |
def generate_text(message, max_tokens, temperature, top_p):
|
|
|
|
|
|
|
|
|
|
| 79 |
# Récupérer le contexte depuis le store de vecteurs
|
| 80 |
context_results = vector_store.search_context(message, n_results=1)
|
| 81 |
context = context_results[0] if context_results else ""
|
|
|
|
| 91 |
# Générer le texte avec le modèle de langue
|
| 92 |
output = llm(
|
| 93 |
prompt_template,
|
| 94 |
+
temperature=0.3,
|
| 95 |
+
top_p=0.95,
|
| 96 |
top_k=40,
|
| 97 |
repeat_penalty=1.1,
|
| 98 |
+
max_tokens=600,
|
| 99 |
)
|
| 100 |
|
| 101 |
# Traiter la sortie
|
| 102 |
input_string = output['choices'][0]['text'].strip()
|
| 103 |
cleaned_text = input_string.strip("[]'").replace('\\n', '\n')
|
| 104 |
continuous_text = '\n'.join(cleaned_text.split('\n'))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
return continuous_text
|
| 106 |
|
|
|
|
| 107 |
# Définir l'interface Gradio
|
| 108 |
demo = gr.Interface(
|
| 109 |
fn=generate_text,
|
|
|
|
| 111 |
gr.Textbox(lines=2, placeholder="Enter your message here...", label="Message"),
|
| 112 |
],
|
| 113 |
outputs=gr.Textbox(label="Generated Text"),
|
| 114 |
+
title="Chatbot - Your Personal Culinary Advisor: Discover What to Cook Next!",
|
| 115 |
description="Running LLM with context retrieval from ChromaDB",
|
|
|
|
| 116 |
examples=[
|
| 117 |
["I have leftover rice, what can I make out of it?"],
|
| 118 |
["I just have some milk and chocolate, what dessert can I make?"],
|
|
|
|
| 120 |
["Can you suggest a vegan breakfast recipe?"],
|
| 121 |
["How do I make a perfect scrambled egg?"],
|
| 122 |
["Can you guide me through making a soufflé?"],
|
| 123 |
+
],
|
| 124 |
+
cache_examples=False,
|
| 125 |
)
|
| 126 |
|
| 127 |
if __name__ == "__main__":
|