Josedcape commited on
Commit
45a3c45
·
verified ·
1 Parent(s): a631ab9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +137 -1
app.py CHANGED
@@ -84,4 +84,140 @@ def obtener_respuesta(pregunta, modelo="gpt-4", temperatura=0.5):
84
  def text_to_speech(text):
85
  client = texttospeech.TextToSpeechClient()
86
  synthesis_input = texttospeech.SynthesisInput(text=text)
87
- voice = texttospeech.VoiceSelection
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  def text_to_speech(text):
85
  client = texttospeech.TextToSpeechClient()
86
  synthesis_input = texttospeech.SynthesisInput(text=text)
87
+ voice = texttospeech.VoiceSelectionParams(language_code="es-ES", ssml_gender=texttospeech.SsmlVoiceGender.NEUTRAL)
88
+ audio_config = texttospeech.AudioConfig(audio_encoding=texttospeech.AudioEncoding.MP3)
89
+ response = client.synthesize_speech(input=synthesis_input, voice=voice, audio_config=audio_config)
90
+ audio_path = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3").name
91
+ with open(audio_path, "wb") as out:
92
+ out.write(response.audio_content)
93
+ return audio_path
94
+
95
+ # Clase para procesar audio
96
+ class AudioProcessor(AudioProcessorBase):
97
+ def __init__(self):
98
+ self.audio_bytes = b''
99
+
100
+ def recv(self, frame):
101
+ self.audio_bytes += frame.to_ndarray().tobytes()
102
+ return frame
103
+
104
+ # Función para transcribir audio a texto usando Google Cloud Speech-to-Text
105
+ def transcribir_audio(audio_bytes):
106
+ client = speech.SpeechClient()
107
+ audio = speech.RecognitionAudio(content=audio_bytes)
108
+ config = speech.RecognitionConfig(
109
+ encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
110
+ sample_rate_hertz=16000,
111
+ language_code="es-ES",
112
+ )
113
+ response = client.recognize(config=config, audio=audio)
114
+ for result in response.results:
115
+ return result.alternatives[0].transcript
116
+ return ""
117
+
118
+ # Configuración de Streamlit
119
+ st.set_page_config(page_title="Asistente Teológico", page_icon="📖")
120
+
121
+ # Estilos CSS personalizados
122
+ st.markdown(
123
+ """
124
+ <style>
125
+ body {
126
+ background: #f2f3f5;
127
+ color: #333;
128
+ }
129
+ .stButton>button {
130
+ background-color: #4CAF50;
131
+ color: white;
132
+ border-radius: 10px;
133
+ }
134
+ .stTextInput>div>div>input {
135
+ border: 1px solid #4CAF50;
136
+ border-radius: 10px;
137
+ }
138
+ .stMarkdown>div>p {
139
+ color: #4CAF50;
140
+ font-weight: bold;
141
+ }
142
+ .stAudio {
143
+ margin-top: 20px;
144
+ border: 2px solid #4CAF50;
145
+ border-radius: 10px;
146
+ }
147
+ .stFileUploader>div>div>input {
148
+ border: 1px solid #4CAF50;
149
+ border-radius: 10px;
150
+ }
151
+ </style>
152
+ """,
153
+ unsafe_allow_html=True,
154
+ )
155
+
156
+ # Encabezado
157
+ st.image("biblia.jpg")
158
+ st.title("📖 Asistente Teológico - BOTIDINAMIX AI")
159
+ st.markdown("Bienvenido al Asistente Teológico, donde puedes preguntar sobre interpretaciones y reflexiones bíblicas.")
160
+
161
+ # Chat
162
+ st.subheader("🗣️ Chat con el Asistente")
163
+ if 'mensajes' not in st.session_state:
164
+ st.session_state.mensajes = []
165
+
166
+ for mensaje in st.session_state.mensajes:
167
+ with st.chat_message(mensaje["role"]):
168
+ st.markdown(mensaje["content"])
169
+
170
+ pregunta_usuario = st.text_input("Escribe tu pregunta sobre la Biblia:")
171
+ if st.button("Enviar"):
172
+ if pregunta_usuario:
173
+ st.session_state.mensajes.append({"role": "user", "content": pregunta_usuario, "timestamp": time.time()})
174
+ with st.chat_message("user"):
175
+ st.markdown(pregunta_usuario)
176
+
177
+ with st.spinner("Generando respuesta..."):
178
+ respuesta = obtener_respuesta(pregunta_usuario)
179
+ st.session_state.mensajes.append({"role": "assistant", "content": respuesta, "timestamp": time.time()})
180
+ with st.chat_message("assistant"):
181
+ st.markdown(respuesta)
182
+
183
+ # Convertir texto a voz
184
+ audio_path = text_to_speech(respuesta)
185
+ st.audio(audio_path, format="audio/mp3", start_time=0)
186
+ else:
187
+ st.warning("Por favor, ingresa una pregunta antes de enviar.")
188
+
189
+ # Gestión de pedidos
190
+ st.subheader("📋 Gestión de Pedidos")
191
+ menu_csv_path = "menu.csv" # Ruta al archivo CSV del menú
192
+ if 'pedidos' not in st.session_state:
193
+ st.session_state.pedidos = []
194
+
195
+ pedido_agent = PedidoAgent(menu_csv_path)
196
+ calculo_pedido_agent = CalculoPedidoAgent()
197
+
198
+ pedido_agent.realizar_pedido(st.session_state)
199
+ calculo_pedido_agent.calcular_total(st.session_state)
200
+
201
+ # Captura de audio y transcripción
202
+ st.subheader("🎤 Captura de voz y transcripción")
203
+ if st.button("Grabar 🎙️"):
204
+ webrtc_ctx = webrtc_streamer(
205
+ key="example",
206
+ mode=WebRtcMode.SENDONLY,
207
+ audio_receiver_size=256,
208
+ rtc_configuration={"iceServers": [{"urls": ["stun:stun.l.google.com:19302"]}]},
209
+ media_stream_constraints={"audio": True},
210
+ audio_processor_factory=AudioProcessor,
211
+ )
212
+
213
+ if webrtc_ctx.audio_receiver:
214
+ audio_frames = webrtc_ctx.audio_receiver.get_frames(timeout=1)
215
+ for audio_frame in audio_frames:
216
+ audio_bytes = audio_frame.to_ndarray().tobytes()
217
+ transcripcion = transcribir_audio(audio_bytes)
218
+ if transcripcion:
219
+ st.session_state.mensajes.append({"role": "user", "content": transcripcion, "timestamp": time.time()})
220
+ with st.chat_message("user"):
221
+ st.markdown(transcripcion)
222
+ break # Solo capturamos una vez por grabación
223
+