Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -15,7 +15,8 @@ from streamlit_webrtc import webrtc_streamer, WebRtcMode, AudioProcessorBase
|
|
| 15 |
# Cargar variables de entorno desde el archivo .env
|
| 16 |
load_dotenv()
|
| 17 |
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 18 |
-
|
|
|
|
| 19 |
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "botidinamix-g.json"
|
| 20 |
|
| 21 |
# Configuraci贸n de Streamlit
|
|
@@ -69,7 +70,7 @@ st.markdown(
|
|
| 69 |
)
|
| 70 |
|
| 71 |
# Encabezado
|
| 72 |
-
st.image("
|
| 73 |
st.title("馃摉 LOS C脫DIGOS DE DIOS - BOTIDINAMIX AI")
|
| 74 |
st.markdown("Bienvenido al Asistente Teol贸gico, donde puedes preguntar sobre interpretaciones y reflexiones b铆blicas.")
|
| 75 |
|
|
@@ -80,15 +81,20 @@ page = st.sidebar.selectbox("Selecciona una p谩gina", ["Chat Asistente", "Gesti
|
|
| 80 |
# Cargar el modelo de clasificaci贸n de im谩genes
|
| 81 |
clasificador = pipeline("zero-shot-image-classification")
|
| 82 |
|
| 83 |
-
# Funci贸n para buscar im谩genes en
|
| 84 |
def buscar_imagenes(query):
|
| 85 |
-
search_url = "https://
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
response.raise_for_status()
|
| 90 |
search_results = response.json()
|
| 91 |
-
images = [
|
| 92 |
return images
|
| 93 |
|
| 94 |
# Funci贸n para verificar la adecuaci贸n de la imagen
|
|
@@ -114,7 +120,7 @@ def generar_reflexion_y_consulta(keyword):
|
|
| 114 |
respuesta = response['choices'][0]['message']['content']
|
| 115 |
partes = respuesta.split("Consulta de b煤squeda de imagen:")
|
| 116 |
reflexion = partes[0].strip()
|
| 117 |
-
consulta_imagen = partes[1].strip() if len(partes) > 1 else keyword + " espiritual, religioso, naturaleza, Dios
|
| 118 |
return reflexion, consulta_imagen
|
| 119 |
|
| 120 |
# Funci贸n para obtener un audio aleatorio de la carpeta "reflexiones"
|
|
@@ -202,97 +208,4 @@ elif page == "Generador de Frases B铆blicas":
|
|
| 202 |
try:
|
| 203 |
reflexion, consulta_imagen = generar_reflexion_y_consulta(keyword)
|
| 204 |
image_urls = buscar_imagenes(consulta_imagen)
|
| 205 |
-
for
|
| 206 |
-
if verificar_imagen(image_url, keyword):
|
| 207 |
-
return image_url, reflexion
|
| 208 |
-
st.warning("No se encontraron im谩genes adecuadas. Intenta nuevamente.")
|
| 209 |
-
return None, reflexion
|
| 210 |
-
except Exception as e:
|
| 211 |
-
st.error(f"Error al generar la imagen o reflexi贸n: {e}")
|
| 212 |
-
return None, None
|
| 213 |
-
|
| 214 |
-
# Encabezado
|
| 215 |
-
st.subheader("馃摐 Generador de Frases B铆blicas")
|
| 216 |
-
st.markdown("Escribe un vers铆culo o una palabra y obt茅n una imagen alusiva y una reflexi贸n usando Pexels y OpenAI.")
|
| 217 |
-
|
| 218 |
-
# Entrada de texto para el vers铆culo o palabra
|
| 219 |
-
keyword_usuario = st.text_input("Escribe un vers铆culo o una palabra:")
|
| 220 |
-
|
| 221 |
-
if st.button("Generar"):
|
| 222 |
-
if keyword_usuario:
|
| 223 |
-
with st.spinner("Buscando imagen y generando reflexi贸n..."):
|
| 224 |
-
imagen_url, reflexion = generar_imagen_y_reflexion(keyword_usuario)
|
| 225 |
-
if imagen_url and reflexion:
|
| 226 |
-
st.subheader("Imagen alusiva:")
|
| 227 |
-
st.image(imagen_url)
|
| 228 |
-
st.subheader("Reflexi贸n:")
|
| 229 |
-
st.markdown(reflexion)
|
| 230 |
-
|
| 231 |
-
# Obtener y reproducir un audio aleatorio
|
| 232 |
-
audio_base64 = obtener_audio_aleatorio()
|
| 233 |
-
if audio_base64:
|
| 234 |
-
audio_html = f"""
|
| 235 |
-
<audio autoplay>
|
| 236 |
-
<source src="data:audio/mp3;base64,{audio_base64}" type="audio/mp3">
|
| 237 |
-
</audio>
|
| 238 |
-
"""
|
| 239 |
-
st.markdown(audio_html, unsafe_allow_html=True)
|
| 240 |
-
else:
|
| 241 |
-
st.warning("Por favor, ingresa un vers铆culo o una palabra antes de generar.")
|
| 242 |
-
|
| 243 |
-
# Funci贸n para obtener respuesta de OpenAI
|
| 244 |
-
def obtener_respuesta(pregunta, modelo="gpt-4", temperatura=0.5):
|
| 245 |
-
response = openai.ChatCompletion.create(
|
| 246 |
-
model=modelo,
|
| 247 |
-
messages=[{"role": "system", "content": "You are a knowledgeable theological assistant."},
|
| 248 |
-
{"role": "user", "content": pregunta}],
|
| 249 |
-
temperature=temperatura,
|
| 250 |
-
max_tokens=150,
|
| 251 |
-
)
|
| 252 |
-
respuesta = response['choices'][0]['message']['content']
|
| 253 |
-
return respuesta
|
| 254 |
-
|
| 255 |
-
# Funci贸n para convertir texto a voz usando Google Cloud Text-to-Speech
|
| 256 |
-
def text_to_speech(text):
|
| 257 |
-
client = texttospeech.TextToSpeechClient()
|
| 258 |
-
synthesis_input = texttospeech.SynthesisInput(text=text)
|
| 259 |
-
voice = texttospeech.VoiceSelectionParams(language_code="es-ES", ssml_gender=texttospeech.SsmlVoiceGender.NEUTRAL)
|
| 260 |
-
audio_config = texttospeech.AudioConfig(audio_encoding=texttospeech.AudioEncoding.MP3)
|
| 261 |
-
response = client.synthesize_speech(input=synthesis_input, voice=voice, audio_config=audio_config)
|
| 262 |
-
audio_path = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3").name
|
| 263 |
-
with open(audio_path, "wb") as out:
|
| 264 |
-
out.write(response.audio_content)
|
| 265 |
-
return audio_path
|
| 266 |
-
|
| 267 |
-
# Funci贸n para convertir texto a voz y devolver base64
|
| 268 |
-
def text_to_speech_base64(text):
|
| 269 |
-
client = texttospeech.TextToSpeechClient()
|
| 270 |
-
synthesis_input = texttospeech.SynthesisInput(text=text)
|
| 271 |
-
voice = texttospeech.VoiceSelectionParams(language_code="es-ES", ssml_gender=texttospeech.SsmlVoiceGender.NEUTRAL)
|
| 272 |
-
audio_config = texttospeech.AudioConfig(audio_encoding=texttospeech.AudioEncoding.MP3)
|
| 273 |
-
response = client.synthesize_speech(input=synthesis_input, voice=voice, audio_config=audio_config)
|
| 274 |
-
audio_base64 = base64.b64encode(response.audio_content).decode('utf-8')
|
| 275 |
-
return audio_base64
|
| 276 |
-
|
| 277 |
-
# Clase para procesar audio
|
| 278 |
-
class AudioProcessor(AudioProcessorBase):
|
| 279 |
-
def __init__(self):
|
| 280 |
-
self.audio_bytes = b''
|
| 281 |
-
|
| 282 |
-
def recv(self, frame):
|
| 283 |
-
self.audio_bytes += frame.to_ndarray().tobytes()
|
| 284 |
-
return frame
|
| 285 |
-
|
| 286 |
-
# Funci贸n para transcribir audio a texto usando Google Cloud Speech-to-Text
|
| 287 |
-
def transcribir_audio(audio_bytes):
|
| 288 |
-
client = SpeechClient()
|
| 289 |
-
audio = RecognitionAudio(content=audio_bytes)
|
| 290 |
-
config = RecognitionConfig(
|
| 291 |
-
encoding=RecognitionConfig.AudioEncoding.LINEAR16,
|
| 292 |
-
sample_rate_hertz=16000,
|
| 293 |
-
language_code="es-ES",
|
| 294 |
-
)
|
| 295 |
-
response = client.recognize(config=config, audio=audio)
|
| 296 |
-
for result in response.results:
|
| 297 |
-
return result.alternatives[0].transcript
|
| 298 |
-
return ""
|
|
|
|
| 15 |
# Cargar variables de entorno desde el archivo .env
|
| 16 |
load_dotenv()
|
| 17 |
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 18 |
+
google_api_key = os.getenv("GOOGLE_API_KEY")
|
| 19 |
+
google_cx = os.getenv("GOOGLE_CX")
|
| 20 |
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "botidinamix-g.json"
|
| 21 |
|
| 22 |
# Configuraci贸n de Streamlit
|
|
|
|
| 70 |
)
|
| 71 |
|
| 72 |
# Encabezado
|
| 73 |
+
st.image("biblia.jpg")
|
| 74 |
st.title("馃摉 LOS C脫DIGOS DE DIOS - BOTIDINAMIX AI")
|
| 75 |
st.markdown("Bienvenido al Asistente Teol贸gico, donde puedes preguntar sobre interpretaciones y reflexiones b铆blicas.")
|
| 76 |
|
|
|
|
| 81 |
# Cargar el modelo de clasificaci贸n de im谩genes
|
| 82 |
clasificador = pipeline("zero-shot-image-classification")
|
| 83 |
|
| 84 |
+
# Funci贸n para buscar im谩genes en Google Custom Search
|
| 85 |
def buscar_imagenes(query):
|
| 86 |
+
search_url = "https://www.googleapis.com/customsearch/v1"
|
| 87 |
+
params = {
|
| 88 |
+
"q": query,
|
| 89 |
+
"cx": google_cx,
|
| 90 |
+
"key": google_api_key,
|
| 91 |
+
"searchType": "image",
|
| 92 |
+
"num": 10,
|
| 93 |
+
}
|
| 94 |
+
response = requests.get(search_url, params=params)
|
| 95 |
response.raise_for_status()
|
| 96 |
search_results = response.json()
|
| 97 |
+
images = [item["link"] for item in search_results.get("items", [])]
|
| 98 |
return images
|
| 99 |
|
| 100 |
# Funci贸n para verificar la adecuaci贸n de la imagen
|
|
|
|
| 120 |
respuesta = response['choices'][0]['message']['content']
|
| 121 |
partes = respuesta.split("Consulta de b煤squeda de imagen:")
|
| 122 |
reflexion = partes[0].strip()
|
| 123 |
+
consulta_imagen = partes[1].strip() if len(partes) > 1 else keyword + " espiritual, religioso, naturaleza, Dios"
|
| 124 |
return reflexion, consulta_imagen
|
| 125 |
|
| 126 |
# Funci贸n para obtener un audio aleatorio de la carpeta "reflexiones"
|
|
|
|
| 208 |
try:
|
| 209 |
reflexion, consulta_imagen = generar_reflexion_y_consulta(keyword)
|
| 210 |
image_urls = buscar_imagenes(consulta_imagen)
|
| 211 |
+
for
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|