Josedcape commited on
Commit
0248bb7
verified
1 Parent(s): 40b158a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -47
app.py CHANGED
@@ -1,19 +1,16 @@
1
  import streamlit as st
2
- import openai
3
  import os
4
  import time
5
  import base64
6
  import random
7
  from dotenv import load_dotenv
8
  from google.cloud import texttospeech
9
- from google.auth import default
10
  import PyPDF2
11
  from fpdf import FPDF
12
  import tempfile
13
 
14
  # Cargar variables de entorno desde el archivo .env
15
  load_dotenv()
16
- openai.api_key = os.getenv("OPENAI_API_KEY")
17
  os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "botidinamix-g.json"
18
 
19
  # Configuraci贸n de Streamlit
@@ -129,29 +126,33 @@ st.markdown("Bienvenido al Asistente Teol贸gico, donde puedes preguntar sobre in
129
  st.sidebar.title("Navegaci贸n")
130
  page = st.sidebar.selectbox("Selecciona una p谩gina", ["P谩gina Principal", "Chat Asistente", "Generador de Frases B铆blicas", "Recibir Reflexi贸n", "La conexi贸n", "Diario Reflexivo"])
131
 
132
- # Funci贸n para generar texto con OpenAI GPT-4
133
- def generar_texto_openai(prompt):
134
- response = openai.ChatCompletion.create(
135
- model="gpt-4",
136
- messages=[{"role": "system", "content": "Eres un asistente teol贸gico."}, {"role": "user", "content": prompt}],
137
- max_tokens=1000
138
- )
139
- return response.choices[0].message['content'].strip()
140
-
141
- # Funci贸n para generar reflexi贸n usando OpenAI
 
142
  def generar_reflexion(keyword):
143
  prompt = f"Genera una reflexi贸n inspiradora sobre {keyword} en el contexto de la espiritualidad y la Biblia."
144
- respuesta = generar_texto_openai(prompt)
145
  return respuesta
146
 
147
  # Funci贸n para convertir texto a voz
148
  def text_to_speech_base64(text):
149
- client = texttospeech.TextToSpeechClient()
150
- input_text = texttospeech.SynthesisInput(text=text)
151
- voice = texttospeech.VoiceSelectionParams(language_code="es-ES", ssml_gender=texttospeech.SsmlVoiceGender.NEUTRAL)
152
- audio_config = texttospeech.AudioConfig(audio_encoding=texttospeech.AudioEncoding.MP3)
153
- response = client.synthesize_speech(input=input_text, voice=voice, audio_config=audio_config)
154
- return base64.b64encode(response.audio_content).decode("utf-8")
 
 
 
155
 
156
  # Funci贸n para obtener una imagen aleatoria de la carpeta "im谩genes"
157
  def obtener_imagen_aleatoria():
@@ -179,10 +180,13 @@ def obtener_audio_aleatorio():
179
  # Funci贸n para extraer texto de un PDF
180
  def extraer_texto_pdf(pdf_path):
181
  text = ""
182
- with open(pdf_path, "rb") as file:
183
- reader = PyPDF2.PdfFileReader(file)
184
- for page_num in range(reader.numPages):
185
- text += reader.getPage(page_num).extract_text()
 
 
 
186
  return text
187
 
188
  # Funci贸n "La conexi贸n" para generar oraciones del PDF
@@ -190,7 +194,7 @@ def generar_oracion_desde_pdf():
190
  pdf_path = "diario-de-oraciones.pdf" # Ruta al PDF
191
  texto_pdf = extraer_texto_pdf(pdf_path)
192
  prompt = f"Genera una oraci贸n inspiradora basada en el siguiente texto: {texto_pdf[:2000]}" # Limitar a los primeros 2000 caracteres
193
- respuesta = generar_texto_openai(prompt)
194
  return respuesta
195
 
196
  # Funci贸n para generar y descargar un PDF con la entrada del diario
@@ -277,12 +281,13 @@ elif page == "Chat Asistente":
277
 
278
  # Convertir texto a voz
279
  audio_base64 = text_to_speech_base64(respuesta)
280
- audio_html = f"""
281
- <audio autoplay>
282
- <source src="data:audio/mp3;base64,{audio_base64}" type="audio/mp3">
283
- </audio>
284
- """
285
- st.markdown(audio_html, unsafe_allow_html=True)
 
286
 
287
  # Mostrar imagen aleatoria
288
  imagen_path = obtener_imagen_aleatoria()
@@ -309,16 +314,17 @@ elif page == "Generador de Frases B铆blicas":
309
  try:
310
  reflexion = generar_reflexion(keyword)
311
  audio_base64 = text_to_speech_base64(reflexion)
312
- imagen_path = obtener_imagen_aleatoria()
313
- if imagen_path:
314
- st.image(imagen_path)
315
- st.markdown(reflexion)
316
- audio_html = f"""
317
- <audio autoplay>
318
- <source src="data:audio/mp3;base64,{audio_base64}" type="audio/mp3">
319
- </audio>
320
- """
321
- st.markdown(audio_html, unsafe_allow_html=True)
 
322
  except Exception as e:
323
  st.error(f"Error al generar la imagen y reflexi贸n: {e}")
324
 
@@ -351,12 +357,13 @@ elif page == "La conexi贸n":
351
  oracion = generar_oracion_desde_pdf()
352
  st.markdown(oracion)
353
  audio_base64 = text_to_speech_base64(oracion)
354
- audio_html = f"""
355
- <audio autoplay>
356
- <source src="data:audio/mp3;base64,{audio_base64}" type="audio/mp3">
357
- </audio>
358
- """
359
- st.markdown(audio_html, unsafe_allow_html=True)
 
360
 
361
  elif page == "Diario Reflexivo":
362
  st.subheader("馃摂 Diario Reflexivo")
@@ -378,3 +385,4 @@ elif page == "Diario Reflexivo":
378
  file_name="diario_reflexivo.pdf",
379
  mime="application/pdf"
380
  )
 
 
1
  import streamlit as st
 
2
  import os
3
  import time
4
  import base64
5
  import random
6
  from dotenv import load_dotenv
7
  from google.cloud import texttospeech
 
8
  import PyPDF2
9
  from fpdf import FPDF
10
  import tempfile
11
 
12
  # Cargar variables de entorno desde el archivo .env
13
  load_dotenv()
 
14
  os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "botidinamix-g.json"
15
 
16
  # Configuraci贸n de Streamlit
 
126
  st.sidebar.title("Navegaci贸n")
127
  page = st.sidebar.selectbox("Selecciona una p谩gina", ["P谩gina Principal", "Chat Asistente", "Generador de Frases B铆blicas", "Recibir Reflexi贸n", "La conexi贸n", "Diario Reflexivo"])
128
 
129
+ # Funci贸n para generar texto con Groq
130
+ def generar_texto_groq(prompt):
131
+ # L贸gica para generar texto usando Groq
132
+ try:
133
+ # Aqu铆 debes incluir la l贸gica para hacer la solicitud a Groq y obtener la respuesta.
134
+ response = "Texto de ejemplo generado por Groq" # Reemplazar con la l贸gica real de Groq
135
+ return response
136
+ except Exception as e:
137
+ return f"Error en la generaci贸n de texto: {e}"
138
+
139
+ # Funci贸n para generar reflexi贸n usando Groq
140
  def generar_reflexion(keyword):
141
  prompt = f"Genera una reflexi贸n inspiradora sobre {keyword} en el contexto de la espiritualidad y la Biblia."
142
+ respuesta = generar_texto_groq(prompt)
143
  return respuesta
144
 
145
  # Funci贸n para convertir texto a voz
146
  def text_to_speech_base64(text):
147
+ try:
148
+ client = texttospeech.TextToSpeechClient()
149
+ input_text = texttospeech.SynthesisInput(text=text)
150
+ voice = texttospeech.VoiceSelectionParams(language_code="es-ES", ssml_gender=texttospeech.SsmlVoiceGender.NEUTRAL)
151
+ audio_config = texttospeech.AudioConfig(audio_encoding=texttospeech.AudioEncoding.MP3)
152
+ response = client.synthesize_speech(input=input_text, voice=voice, audio_config=audio_config)
153
+ return base64.b64encode(response.audio_content).decode("utf-8")
154
+ except Exception as e:
155
+ return f"Error en la conversi贸n de texto a voz: {e}"
156
 
157
  # Funci贸n para obtener una imagen aleatoria de la carpeta "im谩genes"
158
  def obtener_imagen_aleatoria():
 
180
  # Funci贸n para extraer texto de un PDF
181
  def extraer_texto_pdf(pdf_path):
182
  text = ""
183
+ try:
184
+ with open(pdf_path, "rb") as file:
185
+ reader = PyPDF2.PdfFileReader(file)
186
+ for page_num in range(reader.numPages):
187
+ text += reader.getPage(page_num).extract_text()
188
+ except Exception as e:
189
+ text = f"Error al extraer texto del PDF: {e}"
190
  return text
191
 
192
  # Funci贸n "La conexi贸n" para generar oraciones del PDF
 
194
  pdf_path = "diario-de-oraciones.pdf" # Ruta al PDF
195
  texto_pdf = extraer_texto_pdf(pdf_path)
196
  prompt = f"Genera una oraci贸n inspiradora basada en el siguiente texto: {texto_pdf[:2000]}" # Limitar a los primeros 2000 caracteres
197
+ respuesta = generar_texto_groq(prompt)
198
  return respuesta
199
 
200
  # Funci贸n para generar y descargar un PDF con la entrada del diario
 
281
 
282
  # Convertir texto a voz
283
  audio_base64 = text_to_speech_base64(respuesta)
284
+ if "Error" not in audio_base64:
285
+ audio_html = f"""
286
+ <audio autoplay>
287
+ <source src="data:audio/mp3;base64,{audio_base64}" type="audio/mp3">
288
+ </audio>
289
+ """
290
+ st.markdown(audio_html, unsafe_allow_html=True)
291
 
292
  # Mostrar imagen aleatoria
293
  imagen_path = obtener_imagen_aleatoria()
 
314
  try:
315
  reflexion = generar_reflexion(keyword)
316
  audio_base64 = text_to_speech_base64(reflexion)
317
+ if "Error" not in audio_base64:
318
+ imagen_path = obtener_imagen_aleatoria()
319
+ if imagen_path:
320
+ st.image(imagen_path)
321
+ st.markdown(reflexion)
322
+ audio_html = f"""
323
+ <audio autoplay>
324
+ <source src="data:audio/mp3;base64,{audio_base64}" type="audio/mp3">
325
+ </audio>
326
+ """
327
+ st.markdown(audio_html, unsafe_allow_html=True)
328
  except Exception as e:
329
  st.error(f"Error al generar la imagen y reflexi贸n: {e}")
330
 
 
357
  oracion = generar_oracion_desde_pdf()
358
  st.markdown(oracion)
359
  audio_base64 = text_to_speech_base64(oracion)
360
+ if "Error" not in audio_base64:
361
+ audio_html = f"""
362
+ <audio autoplay>
363
+ <source src="data:audio/mp3;base64,{audio_base64}" type="audio/mp3">
364
+ </audio>
365
+ """
366
+ st.markdown(audio_html, unsafe_allow_html=True)
367
 
368
  elif page == "Diario Reflexivo":
369
  st.subheader("馃摂 Diario Reflexivo")
 
385
  file_name="diario_reflexivo.pdf",
386
  mime="application/pdf"
387
  )
388
+