Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -52,9 +52,11 @@ def cargar_modelo_embeddings():
|
|
52 |
try:
|
53 |
tokenizer = AutoTokenizer.from_pretrained(EMBEDDING_MODEL)
|
54 |
model = AutoModel.from_pretrained(EMBEDDING_MODEL)
|
|
|
55 |
return tokenizer, model
|
56 |
except Exception as e:
|
57 |
-
|
|
|
58 |
return None, None
|
59 |
|
60 |
def generar_embedding(texto, tokenizer, model):
|
@@ -84,9 +86,11 @@ def crear_vector_store(fragmentos, tokenizer, embedding_model, nombre_coleccion)
|
|
84 |
documents=valid_fragmentos,
|
85 |
ids=[f"frag_{i}" for i in range(len(valid_fragmentos))]
|
86 |
)
|
|
|
87 |
return collection
|
88 |
except Exception as e:
|
89 |
-
|
|
|
90 |
return None
|
91 |
|
92 |
def buscar_en_conocimiento(pregunta, collection, tokenizer, embedding_model, top_n=3):
|
@@ -115,6 +119,7 @@ def cargar_modelo_llm():
|
|
115 |
return None
|
116 |
try:
|
117 |
llm = Llama(model_path=MODEL_LOCAL_PATH)
|
|
|
118 |
return llm
|
119 |
except Exception as e:
|
120 |
error_message = f"Error al cargar el modelo LLM desde {MODEL_LOCAL_PATH}: {e}"
|
@@ -133,7 +138,7 @@ def chatbot(pregunta, historial=[]):
|
|
133 |
return "Cargando recursos. Por favor, espera...", historial
|
134 |
|
135 |
contexto = buscar_en_conocimiento(pregunta, vector_store, embedding_tokenizer, embedding_model)
|
136 |
-
historial_str = "\n".join([f"{
|
137 |
|
138 |
prompt = f"Basado en la siguiente informaci贸n: '{contexto}' y la conversaci贸n anterior: '{historial_str}', responde a la pregunta: '{pregunta}'"
|
139 |
|
@@ -149,8 +154,7 @@ def chatbot(pregunta, historial=[]):
|
|
149 |
except Exception as e:
|
150 |
respuesta = f"Error al generar la respuesta: {e}"
|
151 |
|
152 |
-
historial.append(
|
153 |
-
historial.append({"bot": "Agente", "contenido": respuesta})
|
154 |
return respuesta, historial
|
155 |
|
156 |
# --- Inicializaci贸n Global ---
|
@@ -159,30 +163,29 @@ def inicializar():
|
|
159 |
print("Inicializando recursos...")
|
160 |
llm_instance = cargar_modelo_llm()
|
161 |
if llm_instance:
|
162 |
-
print("Modelo LLM cargado.")
|
163 |
embedding_tokenizer, embedding_model = cargar_modelo_embeddings()
|
164 |
if embedding_tokenizer and embedding_model:
|
165 |
-
print("Modelo de embeddings cargado.")
|
166 |
textos_pdf = cargar_documentos(KNOWLEDGE_BASE_PATH)
|
167 |
fragmentos = dividir_en_fragmentos(textos_pdf)
|
168 |
vector_store = crear_vector_store(fragmentos, embedding_tokenizer, embedding_model, VECTOR_STORE_NAME)
|
169 |
-
if vector_store:
|
170 |
-
print("Base de conocimientos vectorizada.")
|
171 |
-
else:
|
172 |
initialization_error = "Error al crear la base de conocimientos vectorial."
|
173 |
else:
|
174 |
initialization_error = "Error al cargar el modelo de embeddings."
|
175 |
else:
|
176 |
-
|
177 |
|
178 |
# --- Interfaz de Gradio ---
|
179 |
if __name__ == "__main__":
|
180 |
inicializar()
|
181 |
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
|
|
|
|
|
|
|
52 |
try:
|
53 |
tokenizer = AutoTokenizer.from_pretrained(EMBEDDING_MODEL)
|
54 |
model = AutoModel.from_pretrained(EMBEDDING_MODEL)
|
55 |
+
print("Modelo de embeddings cargado.")
|
56 |
return tokenizer, model
|
57 |
except Exception as e:
|
58 |
+
error_message = f"Error al cargar el modelo de embeddings: {e}"
|
59 |
+
print(error_message)
|
60 |
return None, None
|
61 |
|
62 |
def generar_embedding(texto, tokenizer, model):
|
|
|
86 |
documents=valid_fragmentos,
|
87 |
ids=[f"frag_{i}" for i in range(len(valid_fragmentos))]
|
88 |
)
|
89 |
+
print("Base de conocimientos vectorizada.")
|
90 |
return collection
|
91 |
except Exception as e:
|
92 |
+
error_message = f"Error al crear el vector store: {e}"
|
93 |
+
print(error_message)
|
94 |
return None
|
95 |
|
96 |
def buscar_en_conocimiento(pregunta, collection, tokenizer, embedding_model, top_n=3):
|
|
|
119 |
return None
|
120 |
try:
|
121 |
llm = Llama(model_path=MODEL_LOCAL_PATH)
|
122 |
+
print("Modelo LLM cargado.")
|
123 |
return llm
|
124 |
except Exception as e:
|
125 |
error_message = f"Error al cargar el modelo LLM desde {MODEL_LOCAL_PATH}: {e}"
|
|
|
138 |
return "Cargando recursos. Por favor, espera...", historial
|
139 |
|
140 |
contexto = buscar_en_conocimiento(pregunta, vector_store, embedding_tokenizer, embedding_model)
|
141 |
+
historial_str = "\n".join([f"{turn[0]}: {turn[1]}" for turn in historial])
|
142 |
|
143 |
prompt = f"Basado en la siguiente informaci贸n: '{contexto}' y la conversaci贸n anterior: '{historial_str}', responde a la pregunta: '{pregunta}'"
|
144 |
|
|
|
154 |
except Exception as e:
|
155 |
respuesta = f"Error al generar la respuesta: {e}"
|
156 |
|
157 |
+
historial.append([pregunta, respuesta])
|
|
|
158 |
return respuesta, historial
|
159 |
|
160 |
# --- Inicializaci贸n Global ---
|
|
|
163 |
print("Inicializando recursos...")
|
164 |
llm_instance = cargar_modelo_llm()
|
165 |
if llm_instance:
|
|
|
166 |
embedding_tokenizer, embedding_model = cargar_modelo_embeddings()
|
167 |
if embedding_tokenizer and embedding_model:
|
|
|
168 |
textos_pdf = cargar_documentos(KNOWLEDGE_BASE_PATH)
|
169 |
fragmentos = dividir_en_fragmentos(textos_pdf)
|
170 |
vector_store = crear_vector_store(fragmentos, embedding_tokenizer, embedding_model, VECTOR_STORE_NAME)
|
171 |
+
if not vector_store:
|
|
|
|
|
172 |
initialization_error = "Error al crear la base de conocimientos vectorial."
|
173 |
else:
|
174 |
initialization_error = "Error al cargar el modelo de embeddings."
|
175 |
else:
|
176 |
+
initialization_error = "Error al inicializar el modelo LLM."
|
177 |
|
178 |
# --- Interfaz de Gradio ---
|
179 |
if __name__ == "__main__":
|
180 |
inicializar()
|
181 |
|
182 |
+
if initialization_error:
|
183 |
+
print(f"Error durante la inicializaci贸n: {initialization_error}")
|
184 |
+
else:
|
185 |
+
interface = gr.ChatInterface(
|
186 |
+
fn=chatbot,
|
187 |
+
title="Chatbot con Base de Conocimiento",
|
188 |
+
description="Preg煤ntame cualquier cosa basada en los documentos PDF cargados.",
|
189 |
+
examples=["驴De qu茅 trata el documento principal?", "驴Cu谩l es la idea clave del segundo archivo?"]
|
190 |
+
)
|
191 |
+
interface.launch()
|