Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -7,12 +7,10 @@ from llama_index.core import Settings
|
|
7 |
import os
|
8 |
import base64
|
9 |
|
10 |
-
#
|
11 |
load_dotenv()
|
12 |
|
13 |
-
#
|
14 |
-
|
15 |
-
# Configure the Llama index settings
|
16 |
Settings.llm = HuggingFaceInferenceAPI(
|
17 |
model_name="mistralai/Mistral-7B-Instruct-v0.3",
|
18 |
tokenizer_name="mistralai/Mistral-7B-Instruct-v0.3",
|
@@ -25,18 +23,18 @@ Settings.embed_model = HuggingFaceEmbedding(
|
|
25 |
model_name="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2" # Modelo en espa帽ol de Hugging Face
|
26 |
)
|
27 |
|
28 |
-
#
|
29 |
PERSIST_DIR = "./db"
|
30 |
DATA_DIR = "data"
|
31 |
|
32 |
-
#
|
33 |
os.makedirs(DATA_DIR, exist_ok=True)
|
34 |
os.makedirs(PERSIST_DIR, exist_ok=True)
|
35 |
|
36 |
-
#
|
37 |
FIXED_PDF_PATH = os.path.join(DATA_DIR, "saved_pdf.pdf")
|
38 |
|
39 |
-
#
|
40 |
@st.cache_data
|
41 |
def load_data():
|
42 |
documents = SimpleDirectoryReader(DATA_DIR).load_data()
|
@@ -45,12 +43,12 @@ def load_data():
|
|
45 |
index.storage_context.persist(persist_dir=PERSIST_DIR)
|
46 |
return index
|
47 |
|
48 |
-
#
|
49 |
def handle_query(query, index):
|
50 |
chat_text_qa_msgs = [
|
51 |
(
|
52 |
"user",
|
53 |
-
"""Responde en espa帽ol con un m谩ximo de 100 palabras y agrega que para m谩s informaci贸n en <https://docs.google.com/document/d/1mab0yt8us-XGugwzAsQ_8K-XLn1_VJ8tlTV7FW3Wv2E/edit?usp=sharing>. Recuerda que Inform谩tica Educativa no es virtual, sino a distancia los fines de semana. Simplifica y resume para ser conciso, preciso y directo. Eres Lobito, asistente de la UPNFM. Proporciona respuestas precisas basadas en el contexto dado sobre la UPNFM y la DFP. Si la pregunta no coincide, sugiere reformularla. Identifica las secciones relevantes del contexto y organiza las respuestas l贸gicamente si abarcan varias secciones.
|
54 |
Contexto:
|
55 |
{context_str}
|
56 |
Pregunta:
|
@@ -70,11 +68,11 @@ def handle_query(query, index):
|
|
70 |
response = answer['response']
|
71 |
else:
|
72 |
return "Lo siento, no pude procesar tu pregunta. 驴Podr铆as reformularla o hacer una pregunta diferente?"
|
73 |
-
|
74 |
# Palabras y frases a evitar en las respuestas
|
75 |
palabras_prohibidas = [
|
76 |
"en el contexto proporcionado no hay informaci贸n",
|
77 |
-
"
|
78 |
"the provided text does not contain",
|
79 |
"en el contexto proporcionado, no hay informaci贸n"
|
80 |
]
|
@@ -85,13 +83,11 @@ def handle_query(query, index):
|
|
85 |
|
86 |
return response
|
87 |
|
88 |
-
|
89 |
-
|
90 |
-
# Initialize session state
|
91 |
if 'messages' not in st.session_state:
|
92 |
st.session_state.messages = [{'role': 'assistant', "content": '隆Hola!, me llamo Lobito. Soy tu asesor personalizado.'}]
|
93 |
|
94 |
-
#
|
95 |
st.title("Chatbot de dudas DFP")
|
96 |
st.markdown("Resuelvo dudas sobre el r茅gimen econ贸mico y admisi贸n de la Direcci贸n de Formaci贸n Permanente.")
|
97 |
st.markdown("""
|
@@ -99,25 +95,30 @@ st.markdown("""
|
|
99 |
<iframe src="https://www.youtube.com/embed/UFqvwF9xvAM?si=4qFqwSpsr5Fh9bd7" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
|
100 |
</div>
|
101 |
""", unsafe_allow_html=True)
|
102 |
-
st.markdown("<small>Toda la informaci贸n en el documento: <https://docs.google.com/document/d/1mab0yt8us-XGugwzAsQ_8K-XLn1_VJ8tlTV7FW3Wv2E/edit?usp=sharing></small>", unsafe_allow_html=True)
|
103 |
|
104 |
-
#
|
|
|
|
|
|
|
|
|
|
|
105 |
if os.path.exists(FIXED_PDF_PATH):
|
106 |
index = load_data()
|
107 |
else:
|
108 |
st.error("No pude cargar la informaci贸n.")
|
109 |
|
110 |
-
#
|
111 |
user_prompt = st.chat_input("驴En qu茅 te puedo ayudar?:")
|
112 |
if user_prompt:
|
113 |
st.session_state.messages.append({'role': 'user', "content": user_prompt})
|
114 |
response = handle_query(user_prompt, index)
|
115 |
st.session_state.messages.append({'role': 'assistant', "content": response})
|
116 |
|
|
|
117 |
for message in st.session_state.messages:
|
118 |
with st.chat_message(message['role']):
|
119 |
st.write(message['content'])
|
|
|
|
|
120 |
st.markdown("<small>Desarrollado por el Profesor Marco Medina Rajo.</small>", unsafe_allow_html=True)
|
121 |
st.markdown('<p style="font-size:10px;">La informaci贸n generada por el chatbot puede ser incorrecta. Revisa el documento.</p>', unsafe_allow_html=True)
|
122 |
-
|
123 |
-
|
|
|
7 |
import os
|
8 |
import base64
|
9 |
|
10 |
+
# Cargar variables de entorno
|
11 |
load_dotenv()
|
12 |
|
13 |
+
# Configurar los modelos de LLM y Embeddings
|
|
|
|
|
14 |
Settings.llm = HuggingFaceInferenceAPI(
|
15 |
model_name="mistralai/Mistral-7B-Instruct-v0.3",
|
16 |
tokenizer_name="mistralai/Mistral-7B-Instruct-v0.3",
|
|
|
23 |
model_name="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2" # Modelo en espa帽ol de Hugging Face
|
24 |
)
|
25 |
|
26 |
+
# Definir los directorios para almacenamiento persistente y datos
|
27 |
PERSIST_DIR = "./db"
|
28 |
DATA_DIR = "data"
|
29 |
|
30 |
+
# Asegurar que los directorios existan
|
31 |
os.makedirs(DATA_DIR, exist_ok=True)
|
32 |
os.makedirs(PERSIST_DIR, exist_ok=True)
|
33 |
|
34 |
+
# Ruta fija para el archivo PDF
|
35 |
FIXED_PDF_PATH = os.path.join(DATA_DIR, "saved_pdf.pdf")
|
36 |
|
37 |
+
# Ingestar datos una vez al inicio
|
38 |
@st.cache_data
|
39 |
def load_data():
|
40 |
documents = SimpleDirectoryReader(DATA_DIR).load_data()
|
|
|
43 |
index.storage_context.persist(persist_dir=PERSIST_DIR)
|
44 |
return index
|
45 |
|
46 |
+
# Manejar consultas de usuario
|
47 |
def handle_query(query, index):
|
48 |
chat_text_qa_msgs = [
|
49 |
(
|
50 |
"user",
|
51 |
+
"""Responde en espa帽ol con un m谩ximo de 100 palabras y agrega que para m谩s informaci贸n en <a href="https://docs.google.com/document/d/1mab0yt8us-XGugwzAsQ_8K-XLn1_VJ8tlTV7FW3Wv2E/edit?usp=sharing">Aqu铆 la informaci贸n</a>. Recuerda que Inform谩tica Educativa no es virtual, sino a distancia los fines de semana. Simplifica y resume para ser conciso, preciso y directo. Eres Lobito, asistente de la UPNFM. Proporciona respuestas precisas basadas en el contexto dado sobre la UPNFM y la DFP. Si la pregunta no coincide, sugiere reformularla. Identifica las secciones relevantes del contexto y organiza las respuestas l贸gicamente si abarcan varias secciones.
|
52 |
Contexto:
|
53 |
{context_str}
|
54 |
Pregunta:
|
|
|
68 |
response = answer['response']
|
69 |
else:
|
70 |
return "Lo siento, no pude procesar tu pregunta. 驴Podr铆as reformularla o hacer una pregunta diferente?"
|
71 |
+
|
72 |
# Palabras y frases a evitar en las respuestas
|
73 |
palabras_prohibidas = [
|
74 |
"en el contexto proporcionado no hay informaci贸n",
|
75 |
+
"empty response",
|
76 |
"the provided text does not contain",
|
77 |
"en el contexto proporcionado, no hay informaci贸n"
|
78 |
]
|
|
|
83 |
|
84 |
return response
|
85 |
|
86 |
+
# Inicializar el estado de la sesi贸n
|
|
|
|
|
87 |
if 'messages' not in st.session_state:
|
88 |
st.session_state.messages = [{'role': 'assistant', "content": '隆Hola!, me llamo Lobito. Soy tu asesor personalizado.'}]
|
89 |
|
90 |
+
# Inicializaci贸n de la aplicaci贸n Streamlit
|
91 |
st.title("Chatbot de dudas DFP")
|
92 |
st.markdown("Resuelvo dudas sobre el r茅gimen econ贸mico y admisi贸n de la Direcci贸n de Formaci贸n Permanente.")
|
93 |
st.markdown("""
|
|
|
95 |
<iframe src="https://www.youtube.com/embed/UFqvwF9xvAM?si=4qFqwSpsr5Fh9bd7" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
|
96 |
</div>
|
97 |
""", unsafe_allow_html=True)
|
|
|
98 |
|
99 |
+
# Actualizaci贸n de la URL en Markdown a un enlace HTML descriptivo
|
100 |
+
st.markdown("""
|
101 |
+
<small>Toda la informaci贸n en el documento: <a href="https://docs.google.com/document/d/1mab0yt8us-XGugwzAsQ_8K-XLn1_VJ8tlTV7FW3Wv2E/edit?usp=sharing">Aqu铆 la informaci贸n</a></small>
|
102 |
+
""", unsafe_allow_html=True)
|
103 |
+
|
104 |
+
# Mostrar el PDF fijo si existe
|
105 |
if os.path.exists(FIXED_PDF_PATH):
|
106 |
index = load_data()
|
107 |
else:
|
108 |
st.error("No pude cargar la informaci贸n.")
|
109 |
|
110 |
+
# Entrada de chat
|
111 |
user_prompt = st.chat_input("驴En qu茅 te puedo ayudar?:")
|
112 |
if user_prompt:
|
113 |
st.session_state.messages.append({'role': 'user', "content": user_prompt})
|
114 |
response = handle_query(user_prompt, index)
|
115 |
st.session_state.messages.append({'role': 'assistant', "content": response})
|
116 |
|
117 |
+
# Mostrar los mensajes de la sesi贸n
|
118 |
for message in st.session_state.messages:
|
119 |
with st.chat_message(message['role']):
|
120 |
st.write(message['content'])
|
121 |
+
|
122 |
+
# Informaci贸n adicional
|
123 |
st.markdown("<small>Desarrollado por el Profesor Marco Medina Rajo.</small>", unsafe_allow_html=True)
|
124 |
st.markdown('<p style="font-size:10px;">La informaci贸n generada por el chatbot puede ser incorrecta. Revisa el documento.</p>', unsafe_allow_html=True)
|
|
|
|