Spaces:
Runtime error
Runtime error
fcernafukuzaki
commited on
Commit
•
c9fe7c4
1
Parent(s):
14b4ed5
Conexión base de datos y feedback.
Browse files- app.py +136 -11
- requirements.txt +1 -0
app.py
CHANGED
@@ -5,6 +5,8 @@ import os
|
|
5 |
import pandas as pd
|
6 |
import time
|
7 |
import random
|
|
|
|
|
8 |
|
9 |
import openai
|
10 |
from llama_index import GPTSimpleVectorIndex, SimpleDirectoryReader, LLMPredictor, ServiceContext
|
@@ -19,11 +21,19 @@ from langchain.text_splitter import CharacterTextSplitter
|
|
19 |
from openai.embeddings_utils import get_embedding
|
20 |
from openai.embeddings_utils import cosine_similarity
|
21 |
|
|
|
|
|
22 |
|
23 |
# API KEY OPENAI
|
24 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
25 |
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
|
26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
# CONSTANTES
|
28 |
DATASET_JSON = "demo-inmobiliaria.json"
|
29 |
|
@@ -31,6 +41,8 @@ DATASET_JSON = "demo-inmobiliaria.json"
|
|
31 |
carpeta_actual = os.getcwd()
|
32 |
print(f"Nombre de la carpeta actual: {carpeta_actual}")
|
33 |
PATH_FILE = f"{os.getcwd()}/{DATASET_JSON}"
|
|
|
|
|
34 |
|
35 |
class ChatBotInmobiliaria():
|
36 |
def __init__(self):
|
@@ -95,39 +107,152 @@ examples = [["¿Cuánto está una casa en San Isidro?"],["Hay precios más barat
|
|
95 |
|
96 |
gpt_bot = ChatBotInmobiliaria()
|
97 |
gpt_bot.load_dataset(PATH_FILE)
|
98 |
-
chat_history = []
|
99 |
|
100 |
-
def chat(pregunta):
|
101 |
-
bot_message = str(gpt_bot.ask(question=pregunta))
|
102 |
-
chat_history.append((pregunta, bot_message))
|
103 |
-
time.sleep(1)
|
104 |
-
return chat_history
|
105 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
106 |
|
107 |
-
|
|
|
108 |
gr.Markdown(f"""
|
109 |
{title}
|
110 |
{description}
|
111 |
""")
|
112 |
|
113 |
out1 = gr.Chatbot(label="Respuesta").style(height=300)
|
|
|
114 |
with gr.Row():
|
115 |
in2 = gr.Textbox(label="Pregunta")
|
116 |
enter = gr.Button("Enviar mensaje")
|
117 |
|
118 |
-
|
|
|
|
|
|
|
|
|
|
|
119 |
|
120 |
gr.Markdown(article)
|
121 |
|
|
|
122 |
def respond(message, chat_history):
|
123 |
-
|
124 |
-
chat_history
|
|
|
|
|
|
|
125 |
time.sleep(1)
|
126 |
return "", chat_history
|
127 |
|
|
|
128 |
enter.click(fn=respond, inputs=[in2, out1], outputs=[in2, out1])
|
129 |
in2.submit(respond, [in2, out1], [in2, out1])
|
130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
131 |
|
132 |
# in1 = gr.inputs.Textbox(label="Pregunta")
|
133 |
# out1 = gr.outputs.Chatbot(label="Respuesta").style(height=350)
|
|
|
5 |
import pandas as pd
|
6 |
import time
|
7 |
import random
|
8 |
+
from datetime import datetime
|
9 |
+
import pytz
|
10 |
|
11 |
import openai
|
12 |
from llama_index import GPTSimpleVectorIndex, SimpleDirectoryReader, LLMPredictor, ServiceContext
|
|
|
21 |
from openai.embeddings_utils import get_embedding
|
22 |
from openai.embeddings_utils import cosine_similarity
|
23 |
|
24 |
+
from pymongo import MongoClient
|
25 |
+
|
26 |
|
27 |
# API KEY OPENAI
|
28 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
29 |
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
|
30 |
|
31 |
+
# DATABASE CONNECTION
|
32 |
+
CONNECTION = os.getenv("CONNECTION")
|
33 |
+
DATABASE = os.getenv("DATABASE")
|
34 |
+
COLLECTION = os.getenv("COLLECTION")
|
35 |
+
|
36 |
+
|
37 |
# CONSTANTES
|
38 |
DATASET_JSON = "demo-inmobiliaria.json"
|
39 |
|
|
|
41 |
carpeta_actual = os.getcwd()
|
42 |
print(f"Nombre de la carpeta actual: {carpeta_actual}")
|
43 |
PATH_FILE = f"{os.getcwd()}/{DATASET_JSON}"
|
44 |
+
print(f"Ubicación del archivo: {PATH_FILE}")
|
45 |
+
|
46 |
|
47 |
class ChatBotInmobiliaria():
|
48 |
def __init__(self):
|
|
|
107 |
|
108 |
gpt_bot = ChatBotInmobiliaria()
|
109 |
gpt_bot.load_dataset(PATH_FILE)
|
|
|
110 |
|
|
|
|
|
|
|
|
|
|
|
111 |
|
112 |
+
# Conexión a la base de datos MongoDB
|
113 |
+
client = MongoClient(CONNECTION)
|
114 |
+
db = client[DATABASE]
|
115 |
+
collection = db[COLLECTION]
|
116 |
+
|
117 |
+
|
118 |
+
def get_datetime():
|
119 |
+
# Obtener la hora actual
|
120 |
+
hora_actual = datetime.now()
|
121 |
+
# Obtener la zona horaria de la hora actual
|
122 |
+
zona_horaria_actual = pytz.timezone('America/Argentina/Buenos_Aires')
|
123 |
+
# Aplicar la zona horaria a la hora actual
|
124 |
+
hora_actual_con_zona_horaria = hora_actual.astimezone(zona_horaria_actual)
|
125 |
+
return hora_actual_con_zona_horaria
|
126 |
+
|
127 |
+
|
128 |
+
def insert_chat(data):
|
129 |
+
return collection.insert_one({"conversacion": data})
|
130 |
+
|
131 |
+
|
132 |
+
def update_chat(id, data):
|
133 |
+
collection.update_one({"_id": id}, {"$set": {"conversacion": data}})
|
134 |
+
|
135 |
+
|
136 |
+
def add_chat_history(chat_history, message, answer, calificacion=None):
|
137 |
+
global json_chat_history
|
138 |
+
global id_chat
|
139 |
+
|
140 |
+
json_chat = {"message": message,
|
141 |
+
"answer": answer,
|
142 |
+
"datetime": get_datetime(),
|
143 |
+
"calificacion": calificacion}
|
144 |
+
if len(chat_history) > 0:
|
145 |
+
# Si chat_history no está vacía, significa que es una continuación de la conversación anterior
|
146 |
+
json_chat_history.append(json_chat)
|
147 |
+
# chat_history.append([message, answer])
|
148 |
+
|
149 |
+
update_chat(id_chat, json_chat_history)
|
150 |
+
else:
|
151 |
+
# Si chat_history está vacía, es una nueva conversación
|
152 |
+
json_chat_history = []
|
153 |
+
json_chat_history.append(json_chat)
|
154 |
+
# chat_history.append([message, answer])
|
155 |
+
|
156 |
+
# Almacenar la nueva conversación en la base de datos
|
157 |
+
db_result = insert_chat(json_chat_history)
|
158 |
+
id_chat = db_result.inserted_id
|
159 |
|
160 |
+
|
161 |
+
with gr.Blocks() as demo:
|
162 |
gr.Markdown(f"""
|
163 |
{title}
|
164 |
{description}
|
165 |
""")
|
166 |
|
167 |
out1 = gr.Chatbot(label="Respuesta").style(height=300)
|
168 |
+
|
169 |
with gr.Row():
|
170 |
in2 = gr.Textbox(label="Pregunta")
|
171 |
enter = gr.Button("Enviar mensaje")
|
172 |
|
173 |
+
with gr.Row():
|
174 |
+
upvote_btn = gr.Button(value="👍 Conforme", interactive=True)
|
175 |
+
downvote_btn = gr.Button(value="👎 No conforme", interactive=True)
|
176 |
+
flag_btn = gr.Button(value="⚠️ Alertar", interactive=True)
|
177 |
+
# regenerate_btn = gr.Button(value="🔄 Regenerar", interactive=False)
|
178 |
+
clear_btn = gr.Button(value="🗑️ Nuevo chat", interactive=True)
|
179 |
|
180 |
gr.Markdown(article)
|
181 |
|
182 |
+
|
183 |
def respond(message, chat_history):
|
184 |
+
answer = str(gpt_bot.ask(question=message))
|
185 |
+
add_chat_history(chat_history=chat_history,
|
186 |
+
message=message,
|
187 |
+
answer=answer)
|
188 |
+
chat_history.append([message, answer])
|
189 |
time.sleep(1)
|
190 |
return "", chat_history
|
191 |
|
192 |
+
|
193 |
enter.click(fn=respond, inputs=[in2, out1], outputs=[in2, out1])
|
194 |
in2.submit(respond, [in2, out1], [in2, out1])
|
195 |
+
|
196 |
+
|
197 |
+
def upvote_last_response(message, chat_history):
|
198 |
+
"""
|
199 |
+
Obtener el último objeto JSON de la lista
|
200 |
+
Actualizar el valor del atributo "calificacion"
|
201 |
+
"""
|
202 |
+
if len(json_chat_history) > 0:
|
203 |
+
json_chat_history[-1]["calificacion"] = "Conforme"
|
204 |
+
update_chat(id_chat, json_chat_history)
|
205 |
+
|
206 |
+
return message, chat_history
|
207 |
+
|
208 |
+
|
209 |
+
def downvote_last_response(message, chat_history):
|
210 |
+
"""
|
211 |
+
Obtener el último objeto JSON de la lista
|
212 |
+
Actualizar el valor del atributo "calificacion"
|
213 |
+
"""
|
214 |
+
if len(json_chat_history) > 0:
|
215 |
+
json_chat_history[-1]["calificacion"] = "No conforme"
|
216 |
+
update_chat(id_chat, json_chat_history)
|
217 |
+
|
218 |
+
return message, chat_history
|
219 |
+
|
220 |
+
def flag_last_response(message, chat_history):
|
221 |
+
"""
|
222 |
+
Obtener el último objeto JSON de la lista
|
223 |
+
Actualizar el valor del atributo "calificacion"
|
224 |
+
"""
|
225 |
+
if len(json_chat_history) > 0:
|
226 |
+
json_chat_history[-1]["calificacion"] = "Alertar"
|
227 |
+
update_chat(id_chat, json_chat_history)
|
228 |
+
|
229 |
+
return message, chat_history
|
230 |
+
|
231 |
+
|
232 |
+
# def regenerate_answer(message, chat_history):
|
233 |
+
# """
|
234 |
+
# Obtener el último objeto JSON de la lista
|
235 |
+
# Actualizar el valor del atributo "calificacion"
|
236 |
+
# """
|
237 |
+
# if len(json_chat_history) > 0:
|
238 |
+
# pregunta = json_chat_history[-1]["message"]
|
239 |
+
# answer = str(gpt_bot.ask(question=pregunta))
|
240 |
+
# add_chat_history(chat_history=chat_history,
|
241 |
+
# message=pregunta,
|
242 |
+
# answer=answer,
|
243 |
+
# calificacion="Regenerado")
|
244 |
+
# chat_history.pop(-1)
|
245 |
+
# chat_history.append([message, answer])
|
246 |
+
# time.sleep(1)
|
247 |
+
# return message, chat_history
|
248 |
+
|
249 |
+
|
250 |
+
upvote_btn.click(upvote_last_response, inputs=[in2, out1], outputs=[in2, out1])
|
251 |
+
downvote_btn.click(downvote_last_response, inputs=[in2, out1], outputs=[in2, out1])
|
252 |
+
flag_btn.click(flag_last_response, inputs=[in2, out1], outputs=[in2, out1])
|
253 |
+
# regenerate_btn.click(regenerate_answer, inputs=[in2, out1], outputs=[in2, out1])
|
254 |
+
clear_btn.click(lambda: None, None, out1, queue=False)
|
255 |
+
|
256 |
|
257 |
# in1 = gr.inputs.Textbox(label="Pregunta")
|
258 |
# out1 = gr.outputs.Chatbot(label="Respuesta").style(height=350)
|
requirements.txt
CHANGED
@@ -5,3 +5,4 @@ PyPDF2
|
|
5 |
openai
|
6 |
langchain
|
7 |
llama-index==0.5.25
|
|
|
|
5 |
openai
|
6 |
langchain
|
7 |
llama-index==0.5.25
|
8 |
+
pymongo
|