Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,65 +1,122 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
-
from streamlit_chat import message
|
| 3 |
import requests
|
| 4 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
API_URL = os.getenv("API_URL", "https://livanarzuaga-test.hf.space/api/v1/prediction/2a2e535d-1807-4701-8468-c0ede26bcdbf")
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
|
|
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
try:
|
|
|
|
|
|
|
| 17 |
return response.json()
|
| 18 |
-
except requests.exceptions.
|
| 19 |
-
|
| 20 |
-
return {}
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
"
|
| 26 |
-
"
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
|
|
|
| 35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
if 'history' not in st.session_state:
|
| 37 |
st.session_state['history'] = []
|
| 38 |
|
| 39 |
if 'generated' not in st.session_state:
|
| 40 |
-
st.session_state['generated'] = ["
|
| 41 |
|
| 42 |
if 'past' not in st.session_state:
|
| 43 |
-
st.session_state['past'] = ["
|
| 44 |
-
|
| 45 |
-
#
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
if submit_button and user_input:
|
| 56 |
-
output =
|
| 57 |
-
|
| 58 |
st.session_state['past'].append(user_input)
|
| 59 |
st.session_state['generated'].append(output)
|
|
|
|
| 60 |
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
|
|
|
| 1 |
import streamlit as st
|
|
|
|
| 2 |
import requests
|
| 3 |
import os
|
| 4 |
+
import json
|
| 5 |
+
from dotenv import load_dotenv
|
| 6 |
+
import logging
|
| 7 |
+
from requests.adapters import HTTPAdapter
|
| 8 |
+
from requests.packages.urllib3.util.retry import Retry
|
| 9 |
|
| 10 |
+
# Configurar logging
|
| 11 |
+
logging.basicConfig(level=logging.INFO)
|
| 12 |
+
|
| 13 |
+
# Cargar variables de entorno
|
| 14 |
+
load_dotenv()
|
| 15 |
+
|
| 16 |
+
# Configuraci贸n de la API de Flowise
|
| 17 |
API_URL = os.getenv("API_URL", "https://livanarzuaga-test.hf.space/api/v1/prediction/2a2e535d-1807-4701-8468-c0ede26bcdbf")
|
| 18 |
|
| 19 |
+
#API_URL = os.getenv("API_URL", "https://wilkie-hf-space-tuto.hf.space/api/v1/prediction/037dd3d4-8492-45c4-9c5f-6ff84b8e95ee")
|
| 20 |
+
|
| 21 |
+
#API_URL = os.getenv("API_URL", "https://dsalazarcazanhas-flowise.hf.space/api/v1/prediction/9310432d-f1c9-4194-80a4-84bd3d8ac6af")
|
| 22 |
+
#head = {"Authorization": "Bearer -rejhzEZZ2xaG1P8zGfKYnRBy-wJXpbbE13ld-ZaFEY"}
|
| 23 |
+
|
| 24 |
+
#API_URL = os.getenv("API_URL","https://marie0501-boulder-weather-flowise.hf.space/api/v1/prediction/dd2d1375-8019-4f52-bc23-1d0845b4a0c1")
|
| 25 |
+
#head = {"Authorization": "Bearer o6Xy3bIuPhDJV_z0PefeuvbHO2X3yo3Rt7NSiW-bY4o"}
|
| 26 |
|
| 27 |
+
session = requests.Session()
|
| 28 |
+
|
| 29 |
+
# Configurar reintentos
|
| 30 |
+
retries = Retry(total=5, backoff_factor=1, status_forcelist=[502, 503, 504])
|
| 31 |
+
session.mount('https://', HTTPAdapter(max_retries=retries))
|
| 32 |
+
|
| 33 |
+
def query(payload, api_url=API_URL):
|
| 34 |
try:
|
| 35 |
+
response = session.post(api_url, json=payload)
|
| 36 |
+
response.raise_for_status()
|
| 37 |
return response.json()
|
| 38 |
+
except requests.exceptions.HTTPError as http_err:
|
| 39 |
+
logging.error(f"HTTP error occurred: {http_err}")
|
| 40 |
+
return {"error": "HTTP error occurred. Please try again later."}
|
| 41 |
+
except requests.exceptions.ConnectionError as conn_err:
|
| 42 |
+
logging.error(f"Connection error occurred: {conn_err}")
|
| 43 |
+
return {"error": "Connection error occurred. Please try again later."}
|
| 44 |
+
except requests.exceptions.Timeout as timeout_err:
|
| 45 |
+
logging.error(f"Timeout error occurred: {timeout_err}")
|
| 46 |
+
return {"error": "Timeout error occurred. Please try again later."}
|
| 47 |
+
except requests.exceptions.RequestException as req_err:
|
| 48 |
+
logging.error(f"An error occurred: {req_err}")
|
| 49 |
+
return {"error": "An error occurred. Please try again later."}
|
| 50 |
+
|
| 51 |
+
def validate_input(user_input):
|
| 52 |
+
if not user_input or len(user_input.strip()) == 0:
|
| 53 |
+
return False, "Input cannot be empty."
|
| 54 |
+
return True, ""
|
| 55 |
+
|
| 56 |
+
def get_response(user_input, history, api_url=API_URL):
|
| 57 |
+
is_valid, error_message = validate_input(user_input)
|
| 58 |
+
if not is_valid:
|
| 59 |
+
return error_message
|
| 60 |
|
| 61 |
+
# Incluir el historial completo en el payload
|
| 62 |
+
payload = {"question": user_input, "history": history, "overrideConfig": {"sessionId": "user1"}}
|
| 63 |
+
response = query(payload, api_url)
|
| 64 |
+
return response.get('text', "Error: No API response.")
|
| 65 |
|
| 66 |
+
def export_conversation(past, generated, file_path="conversation.json"):
|
| 67 |
+
try:
|
| 68 |
+
conversation = {
|
| 69 |
+
"past": past,
|
| 70 |
+
"generated": generated
|
| 71 |
+
}
|
| 72 |
+
with open(file_path, "w") as f:
|
| 73 |
+
json.dump(conversation, f)
|
| 74 |
+
return True
|
| 75 |
+
except Exception as e:
|
| 76 |
+
logging.error(f"Error exporting conversation: {e}")
|
| 77 |
+
return str(e)
|
| 78 |
+
|
| 79 |
+
# Inicializar claves en st.session_state
|
| 80 |
if 'history' not in st.session_state:
|
| 81 |
st.session_state['history'] = []
|
| 82 |
|
| 83 |
if 'generated' not in st.session_state:
|
| 84 |
+
st.session_state['generated'] = ["Hi I can answer your weather related questions"]
|
| 85 |
|
| 86 |
if 'past' not in st.session_state:
|
| 87 |
+
st.session_state['past'] = ["Hello"]
|
| 88 |
+
|
| 89 |
+
# Sidebar con opciones
|
| 90 |
+
st.sidebar.title("Opciones")
|
| 91 |
+
if st.sidebar.button("Nueva conversaci贸n"):
|
| 92 |
+
st.session_state['past'] = ["Hello"]
|
| 93 |
+
st.session_state['generated'] = ["Hi I can answer your weather related questions"]
|
| 94 |
+
st.session_state['history'] = []
|
| 95 |
+
st.sidebar.success("Nueva conversaci贸n iniciada")
|
| 96 |
+
|
| 97 |
+
if st.sidebar.button("Exportar conversaci贸n"):
|
| 98 |
+
result = export_conversation(st.session_state['past'], st.session_state['generated'])
|
| 99 |
+
if result is True:
|
| 100 |
+
st.sidebar.success("Conversaci贸n exportada como conversation.json")
|
| 101 |
+
else:
|
| 102 |
+
st.sidebar.error(f"Error al exportar la conversaci贸n: {result}")
|
| 103 |
+
|
| 104 |
+
# Contenedor para el historial del chat
|
| 105 |
+
chat_container = st.container()
|
| 106 |
+
|
| 107 |
+
# Contenedor para la entrada de texto del usuario
|
| 108 |
+
with st.form(key='my_form', clear_on_submit=True):
|
| 109 |
+
user_input = st.text_input("Chat:", placeholder="Type here to chat", key='input')
|
| 110 |
+
submit_button = st.form_submit_button(label='Send')
|
| 111 |
+
|
| 112 |
if submit_button and user_input:
|
| 113 |
+
output = get_response(user_input, st.session_state['history'])
|
|
|
|
| 114 |
st.session_state['past'].append(user_input)
|
| 115 |
st.session_state['generated'].append(output)
|
| 116 |
+
st.session_state['history'].append({"user": user_input, "bot": output})
|
| 117 |
|
| 118 |
+
# Mostrar el historial del chat
|
| 119 |
+
with chat_container.container():
|
| 120 |
+
for i in range(len(st.session_state['generated'])):
|
| 121 |
+
st.write(f"**User:** {st.session_state['past'][i]}")
|
| 122 |
+
st.write(f"**Bot:** {st.session_state['generated'][i]}")
|