Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -14,6 +14,9 @@ import requests
|
|
| 14 |
from google.cloud import texttospeech, vision
|
| 15 |
import base64
|
| 16 |
|
|
|
|
|
|
|
|
|
|
| 17 |
# Cargar las claves API desde el archivo .env
|
| 18 |
load_dotenv()
|
| 19 |
openai_api_key = os.getenv("OPENAI_API_KEY")
|
|
@@ -29,9 +32,6 @@ else:
|
|
| 29 |
if not brevo_api_key:
|
| 30 |
st.error("No API key provided for Brevo. Please set your API key in the .env file.")
|
| 31 |
|
| 32 |
-
nltk.download('punkt', quiet=True)
|
| 33 |
-
nltk.download('stopwords', quiet=True)
|
| 34 |
-
|
| 35 |
def extraer_texto_pdf(archivo):
|
| 36 |
texto = ""
|
| 37 |
if archivo:
|
|
@@ -58,16 +58,14 @@ def preprocesar_texto(texto):
|
|
| 58 |
tokens = [stemmer.stem(word) for word in tokens]
|
| 59 |
return " ".join(tokens)
|
| 60 |
|
| 61 |
-
def obtener_respuesta(pregunta, texto_preprocesado, modelo, temperatura=0.5, assistant_id="", contexto=""):
|
| 62 |
try:
|
| 63 |
-
messages = [
|
| 64 |
-
{"role": "system", "content": "Actua como Galatea la asistente de la clinica Odontologica OMARDENT y resuelve las inquietudes"},
|
| 65 |
-
{"role": "user", "content": f"Contexto: {contexto}\n\n{pregunta}\n\nContexto PDF: {texto_preprocesado}"}
|
| 66 |
-
]
|
| 67 |
-
|
| 68 |
response = openai.ChatCompletion.create(
|
| 69 |
model=modelo,
|
| 70 |
-
messages=
|
|
|
|
|
|
|
|
|
|
| 71 |
temperature=temperatura
|
| 72 |
)
|
| 73 |
respuesta = response.choices[0].message['content'].strip()
|
|
@@ -299,14 +297,9 @@ def buscar_datos_guardados():
|
|
| 299 |
datos = cargar_desde_txt(archivo_seleccionado)
|
| 300 |
if datos:
|
| 301 |
st.write(f"### Datos del archivo {archivo_seleccionado}")
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
key, value = dato.split(':', 1)
|
| 306 |
-
st.markdown(f"**{key.strip()}**: {value.strip()}")
|
| 307 |
-
else:
|
| 308 |
-
st.markdown(dato)
|
| 309 |
-
|
| 310 |
# Link to download the file
|
| 311 |
try:
|
| 312 |
with open(os.path.join(carpeta, archivo_seleccionado), 'rb') as file:
|
|
@@ -466,40 +459,41 @@ def mostrar_recomendaciones():
|
|
| 466 |
st.title("⭐ Recomendaciones")
|
| 467 |
st.write("Aquí puedes encontrar recomendaciones y consejos útiles.")
|
| 468 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 469 |
def mostrar_interpretacion_imagen():
|
| 470 |
st.title("🖼️ Interpretación de Imágenes con Google Vision")
|
| 471 |
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
with open(image_path, "rb") as image:
|
| 480 |
-
content = image.read()
|
| 481 |
-
image = vision.Image(content=content)
|
| 482 |
-
response = client.label_detection(image=image)
|
| 483 |
-
labels = response.label_annotations
|
| 484 |
-
|
| 485 |
-
if response.error.message:
|
| 486 |
-
st.error(f"Error al interpretar la imagen: {response.error.message}")
|
| 487 |
-
else:
|
| 488 |
-
st.write("### Etiquetas detectadas")
|
| 489 |
-
for label in labels:
|
| 490 |
-
st.write(f"**{label.description}** (Score: {label.score})")
|
| 491 |
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
|
|
|
| 496 |
|
| 497 |
def main():
|
| 498 |
st.set_page_config(page_title="Galatea OMARDENT", layout="wide")
|
| 499 |
|
| 500 |
# Inicializar el estado de la sesión
|
| 501 |
if 'modelo' not in st.session_state:
|
| 502 |
-
st.session_state['modelo'] = "gpt-
|
| 503 |
if 'temperatura' not in st.session_state:
|
| 504 |
st.session_state['temperatura'] = 0.5
|
| 505 |
if 'mensajes_chat' not in st.session_state:
|
|
@@ -519,6 +513,11 @@ def main():
|
|
| 519 |
if 'memoria' not in st.session_state:
|
| 520 |
st.session_state['memoria'] = {}
|
| 521 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 522 |
# Barra lateral
|
| 523 |
ruta_logo = os.path.join("assets", "Logo Omardent.png")
|
| 524 |
if os.path.exists(ruta_logo):
|
|
@@ -685,22 +684,22 @@ def mostrar_galatea_asistente():
|
|
| 685 |
else:
|
| 686 |
st.warning("No se ha cargado ninguna imagen. Por favor, carga una imagen en la página principal.")
|
| 687 |
|
| 688 |
-
def manejar_pregunta_usuario(pregunta_usuario, contexto=""):
|
| 689 |
st.session_state['mensajes_chat'].append({"role": "user", "content": pregunta_usuario})
|
| 690 |
with st.chat_message("user"):
|
| 691 |
st.markdown(pregunta_usuario)
|
| 692 |
|
| 693 |
texto_preprocesado = ""
|
| 694 |
-
archivo_pdf = st.session_state.get('archivo_pdf')
|
| 695 |
if archivo_pdf:
|
| 696 |
texto_pdf = extraer_texto_pdf(archivo_pdf)
|
| 697 |
texto_preprocesado = preprocesar_texto(texto_pdf)
|
| 698 |
-
|
|
|
|
|
|
|
| 699 |
# Obtener respuesta del modelo usando Assistant ID si está presente
|
| 700 |
assistant_id = st.session_state.get('assistant_id', '')
|
| 701 |
-
contexto_completo = st.session_state['memoria'].get('última_interacción', '') + " " + contexto
|
| 702 |
if assistant_id:
|
| 703 |
-
prompt = f"{
|
| 704 |
response = openai.ChatCompletion.create(
|
| 705 |
model=st.session_state['modelo'],
|
| 706 |
messages=[
|
|
@@ -718,7 +717,7 @@ def manejar_pregunta_usuario(pregunta_usuario, contexto=""):
|
|
| 718 |
st.session_state['modelo'],
|
| 719 |
st.session_state['temperatura'],
|
| 720 |
assistant_id,
|
| 721 |
-
|
| 722 |
)
|
| 723 |
|
| 724 |
st.session_state['mensajes_chat'].append({"role": "assistant", "content": respuesta})
|
|
@@ -752,8 +751,9 @@ def manejar_pregunta_usuario(pregunta_usuario, contexto=""):
|
|
| 752 |
st.markdown(f"<script>document.getElementById('background-video').play();</script>", unsafe_allow_html=True)
|
| 753 |
|
| 754 |
# Almacenar la información importante en la memoria
|
| 755 |
-
|
| 756 |
-
|
|
|
|
| 757 |
|
| 758 |
def capturar_voz():
|
| 759 |
st.markdown(
|
|
|
|
| 14 |
from google.cloud import texttospeech, vision
|
| 15 |
import base64
|
| 16 |
|
| 17 |
+
nltk.download('punkt', quiet=True)
|
| 18 |
+
nltk.download('stopwords', quiet=True)
|
| 19 |
+
|
| 20 |
# Cargar las claves API desde el archivo .env
|
| 21 |
load_dotenv()
|
| 22 |
openai_api_key = os.getenv("OPENAI_API_KEY")
|
|
|
|
| 32 |
if not brevo_api_key:
|
| 33 |
st.error("No API key provided for Brevo. Please set your API key in the .env file.")
|
| 34 |
|
|
|
|
|
|
|
|
|
|
| 35 |
def extraer_texto_pdf(archivo):
|
| 36 |
texto = ""
|
| 37 |
if archivo:
|
|
|
|
| 58 |
tokens = [stemmer.stem(word) for word in tokens]
|
| 59 |
return " ".join(tokens)
|
| 60 |
|
| 61 |
+
def obtener_respuesta(pregunta, texto_preprocesado, modelo, temperatura=0.5, assistant_id="asst_4ZYvBvf4IUVQPjnugSZGLdV2", contexto=""):
|
| 62 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
response = openai.ChatCompletion.create(
|
| 64 |
model=modelo,
|
| 65 |
+
messages=[
|
| 66 |
+
{"role": "system", "content": "Actua como Galatea la asistente de la clinica Odontologica OMARDENT y resuelve las inquietudes"},
|
| 67 |
+
{"role": "user", "content": f"{contexto}\n\n{pregunta}\n\nContexto: {texto_preprocesado}"}
|
| 68 |
+
],
|
| 69 |
temperature=temperatura
|
| 70 |
)
|
| 71 |
respuesta = response.choices[0].message['content'].strip()
|
|
|
|
| 297 |
datos = cargar_desde_txt(archivo_seleccionado)
|
| 298 |
if datos:
|
| 299 |
st.write(f"### Datos del archivo {archivo_seleccionado}")
|
| 300 |
+
for linea in datos.split('\n'):
|
| 301 |
+
if linea.strip(): # Verificar si la línea no está vacía
|
| 302 |
+
st.markdown(f"**{linea.split(':')[0]}:** {linea.split(':')[1]}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 303 |
# Link to download the file
|
| 304 |
try:
|
| 305 |
with open(os.path.join(carpeta, archivo_seleccionado), 'rb') as file:
|
|
|
|
| 459 |
st.title("⭐ Recomendaciones")
|
| 460 |
st.write("Aquí puedes encontrar recomendaciones y consejos útiles.")
|
| 461 |
|
| 462 |
+
def interpretar_imagen(imagen):
|
| 463 |
+
client = vision.ImageAnnotatorClient()
|
| 464 |
+
content = imagen.read()
|
| 465 |
+
image = vision.Image(content=content)
|
| 466 |
+
response = client.document_text_detection(image=image)
|
| 467 |
+
|
| 468 |
+
if response.error.message:
|
| 469 |
+
st.error(f"Error en la interpretación de la imagen: {response.error.message}")
|
| 470 |
+
return None
|
| 471 |
+
|
| 472 |
+
return response.full_text_annotation.text
|
| 473 |
+
|
| 474 |
def mostrar_interpretacion_imagen():
|
| 475 |
st.title("🖼️ Interpretación de Imágenes con Google Vision")
|
| 476 |
|
| 477 |
+
imagen = st.file_uploader("Sube una imagen para interpretar", type=['png', 'jpg', 'jpeg'])
|
| 478 |
+
|
| 479 |
+
if imagen:
|
| 480 |
+
texto_interpretado = interpretar_imagen(imagen)
|
| 481 |
+
if texto_interpretado:
|
| 482 |
+
st.write("### Texto Interpretado:")
|
| 483 |
+
st.write(texto_interpretado)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 484 |
|
| 485 |
+
st.session_state['mensajes_chat'].append({"role": "user", "content": texto_interpretado})
|
| 486 |
+
pregunta_usuario = st.text_input("Haz una pregunta sobre la imagen interpretada:")
|
| 487 |
+
|
| 488 |
+
if st.button("Enviar Pregunta"):
|
| 489 |
+
manejar_pregunta_usuario(pregunta_usuario, archivo_pdf=None, contexto=texto_interpretado)
|
| 490 |
|
| 491 |
def main():
|
| 492 |
st.set_page_config(page_title="Galatea OMARDENT", layout="wide")
|
| 493 |
|
| 494 |
# Inicializar el estado de la sesión
|
| 495 |
if 'modelo' not in st.session_state:
|
| 496 |
+
st.session_state['modelo'] = "gpt-3.5-turbo"
|
| 497 |
if 'temperatura' not in st.session_state:
|
| 498 |
st.session_state['temperatura'] = 0.5
|
| 499 |
if 'mensajes_chat' not in st.session_state:
|
|
|
|
| 513 |
if 'memoria' not in st.session_state:
|
| 514 |
st.session_state['memoria'] = {}
|
| 515 |
|
| 516 |
+
# Cargar y preprocesar el texto del PDF predefinido
|
| 517 |
+
with open("assets/instrucciones.pdf", "rb") as file:
|
| 518 |
+
texto_pdf = extraer_texto_pdf(file)
|
| 519 |
+
st.session_state['texto_preprocesado_pdf'] = preprocesar_texto(texto_pdf)
|
| 520 |
+
|
| 521 |
# Barra lateral
|
| 522 |
ruta_logo = os.path.join("assets", "Logo Omardent.png")
|
| 523 |
if os.path.exists(ruta_logo):
|
|
|
|
| 684 |
else:
|
| 685 |
st.warning("No se ha cargado ninguna imagen. Por favor, carga una imagen en la página principal.")
|
| 686 |
|
| 687 |
+
def manejar_pregunta_usuario(pregunta_usuario, archivo_pdf=None, contexto=""):
|
| 688 |
st.session_state['mensajes_chat'].append({"role": "user", "content": pregunta_usuario})
|
| 689 |
with st.chat_message("user"):
|
| 690 |
st.markdown(pregunta_usuario)
|
| 691 |
|
| 692 |
texto_preprocesado = ""
|
|
|
|
| 693 |
if archivo_pdf:
|
| 694 |
texto_pdf = extraer_texto_pdf(archivo_pdf)
|
| 695 |
texto_preprocesado = preprocesar_texto(texto_pdf)
|
| 696 |
+
else:
|
| 697 |
+
texto_preprocesado = st.session_state['texto_preprocesado_pdf']
|
| 698 |
+
|
| 699 |
# Obtener respuesta del modelo usando Assistant ID si está presente
|
| 700 |
assistant_id = st.session_state.get('assistant_id', '')
|
|
|
|
| 701 |
if assistant_id:
|
| 702 |
+
prompt = f"{contexto}\n\n{pregunta_usuario}"
|
| 703 |
response = openai.ChatCompletion.create(
|
| 704 |
model=st.session_state['modelo'],
|
| 705 |
messages=[
|
|
|
|
| 717 |
st.session_state['modelo'],
|
| 718 |
st.session_state['temperatura'],
|
| 719 |
assistant_id,
|
| 720 |
+
contexto
|
| 721 |
)
|
| 722 |
|
| 723 |
st.session_state['mensajes_chat'].append({"role": "assistant", "content": respuesta})
|
|
|
|
| 751 |
st.markdown(f"<script>document.getElementById('background-video').play();</script>", unsafe_allow_html=True)
|
| 752 |
|
| 753 |
# Almacenar la información importante en la memoria
|
| 754 |
+
if "nombre" in pregunta_usuario.lower() or "teléfono" in pregunta_usuario.lower():
|
| 755 |
+
st.session_state['memoria']['última_interacción'] = pregunta_usuario
|
| 756 |
+
guardar_en_txt('memoria_asistente.txt', f"Última interacción: {pregunta_usuario}")
|
| 757 |
|
| 758 |
def capturar_voz():
|
| 759 |
st.markdown(
|