Josedcape commited on
Commit
b7f2518
·
verified ·
1 Parent(s): d5c5ccb

Upload app (5).py

Browse files
Files changed (1) hide show
  1. app (5).py +256 -0
app (5).py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ import openai
4
+ from utils.data_manager import (
5
+ extraer_texto_pdf,
6
+ preprocesar_texto,
7
+ obtener_respuesta,
8
+ flujo_laboratorio,
9
+ flujo_insumos,
10
+ buscar_datos_guardados,
11
+ generar_notificaciones_pendientes,
12
+ flujo_presupuestos,
13
+ flujo_radiografias
14
+ )
15
+ import tempfile
16
+ from dotenv import load_dotenv
17
+ from flask import Flask, request, jsonify
18
+ import threading
19
+
20
+ # Cargar las claves API desde el archivo .env
21
+ load_dotenv()
22
+ openai_api_key = os.getenv("OPENAI_API_KEY")
23
+
24
+ # Verifica que las claves API están configuradas
25
+ if not openai_api_key:
26
+ st.error("No API key provided for OpenAI. Please set your API key in the .env file.")
27
+ else:
28
+ openai.api_key = openai_api_key
29
+
30
+ # Crear la aplicación Flask
31
+ app = Flask(__name__)
32
+
33
+ @app.route('/process_audio', methods=['POST'])
34
+ def process_audio():
35
+ data = request.json
36
+ transcription = data['transcription']
37
+ return jsonify({'transcription': transcription})
38
+
39
+ def run_flask_app():
40
+ app.run(port=5000, debug=True)
41
+
42
+ # Ejecutar Flask en un hilo separado
43
+ flask_thread = threading.Thread(target=run_flask_app)
44
+ flask_thread.start()
45
+
46
+ def inicializar_estado():
47
+ """Inicializa el estado de la sesión si no está ya inicializado."""
48
+ if 'modelo' not in st.session_state:
49
+ st.session_state['modelo'] = "gpt-3.5-turbo-16k"
50
+ if 'temperatura' not in st.session_state:
51
+ st.session_state['temperatura'] = 0.5
52
+ if 'mensajes_chat' not in st.session_state:
53
+ st.session_state['mensajes_chat'] = []
54
+ if 'transcripcion_voz' not in st.session_state:
55
+ st.session_state['transcripcion_voz'] = ""
56
+
57
+ def barra_lateral():
58
+ ruta_logo = os.path.join("assets", "Logo Omardent.png")
59
+ if os.path.exists(ruta_logo):
60
+ st.sidebar.image(ruta_logo, use_column_width=True)
61
+ else:
62
+ st.sidebar.warning(f"Error: No se pudo encontrar la imagen en la ruta: {ruta_logo}")
63
+
64
+ st.sidebar.title("🤖 Galatea OMARDENT")
65
+ st.sidebar.markdown("---")
66
+ st.sidebar.subheader("🧠 Configuración del Modelo")
67
+ st.session_state['modelo'] = st.sidebar.selectbox(
68
+ "Selecciona el modelo:",
69
+ ["gpt-3.5-turbo", "gpt-4", "gpt-4-32k", "gpt-4o"],
70
+ index=0,
71
+ key='modelo_selectbox', # Clave única
72
+ help="Elige el modelo de lenguaje de OpenAI que prefieras."
73
+ )
74
+ st.sidebar.markdown("---")
75
+ st.session_state['temperatura'] = st.sidebar.slider(
76
+ "🌡️ Temperatura",
77
+ min_value=0.0, max_value=1.0,
78
+ value=st.session_state['temperatura'],
79
+ step=0.1,
80
+ key='temperatura_slider' # Clave única
81
+ )
82
+ assistant_id = st.sidebar.text_input("Assistant ID", key="assistant_id", help="Introduce el Assistant ID del playground de OpenAI")
83
+ if assistant_id:
84
+ st.session_state['assistant_id'] = assistant_id
85
+
86
+ def mostrar_mensajes_chat():
87
+ for mensaje in st.session_state['mensajes_chat']:
88
+ with st.chat_message(mensaje["role"]):
89
+ st.markdown(mensaje["content"])
90
+
91
+ def manejar_pregunta_usuario(pregunta_usuario, archivo_pdf):
92
+ st.session_state['mensajes_chat'].append({"role": "user", "content": pregunta_usuario})
93
+ with st.chat_message("user"):
94
+ st.markdown(pregunta_usuario)
95
+
96
+ texto_preprocesado = ""
97
+ if archivo_pdf:
98
+ texto_pdf = extraer_texto_pdf(archivo_pdf)
99
+ texto_preprocesado = preprocesar_texto(texto_pdf)
100
+
101
+ respuesta = obtener_respuesta(
102
+ pregunta_usuario,
103
+ texto_preprocesado,
104
+ st.session_state['modelo'],
105
+ st.session_state['temperatura'],
106
+ st.session_state.get('assistant_id', '')
107
+ )
108
+ st.session_state['mensajes_chat'].append({"role": "assistant", "content": respuesta})
109
+ with st.chat_message("assistant"):
110
+ st.markdown(respuesta)
111
+
112
+ def capturar_voz():
113
+ st.markdown(
114
+ """
115
+ <style>
116
+ .assistant-button {
117
+ display: flex;
118
+ align-items: center;
119
+ justify-content: center;
120
+ background-color: #4CAF50;
121
+ color: white;
122
+ padding: 10px;
123
+ border: none;
124
+ border-radius: 5px;
125
+ cursor: pointer;
126
+ font-size: 16px;
127
+ margin-top: 10px;
128
+ }
129
+ .assistant-button img {
130
+ margin-right: 10px;
131
+ }
132
+ </style>
133
+ <button class="assistant-button" onclick="startRecording()">
134
+ <img src='https://img2.gratispng.com/20180808/cxq/kisspng-robotics-science-computer-icons-robot-technology-robo-to-logo-svg-png-icon-free-download-45527-5b6baa46a5e322.4713113715337825986795.jpg' alt='icon' width='20' height='20'/>
135
+ Capturar Voz
136
+ </button>
137
+ <script>
138
+ function startRecording() {
139
+ const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
140
+ recognition.lang = 'es-ES';
141
+ recognition.interimResults = false;
142
+ recognition.maxAlternatives = 1;
143
+
144
+ recognition.start();
145
+
146
+ recognition.onresult = (event) => {
147
+ const lastResult = event.results.length - 1;
148
+ const text = event.results[lastResult][0].transcript;
149
+ const customEvent = new CustomEvent('audioTranscription', { detail: text });
150
+ document.dispatchEvent(customEvent);
151
+ };
152
+
153
+ recognition.onspeechend = () => {
154
+ recognition.stop();
155
+ };
156
+
157
+ recognition.onerror = (event) => {
158
+ console.error(event.error);
159
+ };
160
+ }
161
+
162
+ document.addEventListener('audioTranscription', (event) => {
163
+ fetch('/process_audio', {
164
+ method: 'POST',
165
+ headers: {
166
+ 'Content-Type': 'application/json'
167
+ },
168
+ body: JSON.stringify({ transcription: event.detail })
169
+ }).then(response => response.json())
170
+ .then(data => {
171
+ document.querySelector("input[name='unique_chat_input_key']").value = data.transcription;
172
+ });
173
+ });
174
+ </script>
175
+ """,
176
+ unsafe_allow_html=True
177
+ )
178
+
179
+ def mostrar_paginas():
180
+ st.sidebar.title("Navegación")
181
+ page = st.sidebar.radio("Ir a", ["Página Principal", "Gestión de Trabajos", "Gestión de Insumos", "Registro de Radiografías", "Buscar Datos", "Notificaciones", "Recomendaciones", "Asistente de Presupuestos", "Comunicación"])
182
+
183
+ if page == "Página Principal":
184
+ from pages import home
185
+ home.show()
186
+ elif page == "Gestión de Trabajos":
187
+ from pages import trabajos
188
+ trabajos.show()
189
+ elif page == "Gestión de Insumos":
190
+ from pages import insumos
191
+ insumos.show()
192
+ elif page == "Registro de Radiografías":
193
+ from pages import radiografias
194
+ radiografias.show()
195
+ elif page == "Buscar Datos":
196
+ from pages import buscar_datos
197
+ buscar_datos.show()
198
+ elif page == "Notificaciones":
199
+ from pages import notificaciones
200
+ notificaciones.show()
201
+ elif page == "Recomendaciones":
202
+ from pages import recomendaciones
203
+ recomendaciones.show()
204
+ elif page == "Asistente de Presupuestos":
205
+ from pages import presupuesto
206
+ presupuesto.show()
207
+ elif page == "Comunicación":
208
+ from pages import comunicacion
209
+ comunicacion.show()
210
+
211
+ def main():
212
+ inicializar_estado()
213
+ barra_lateral()
214
+ mostrar_paginas()
215
+
216
+ st.title("VIRTUAL OMARDENT AI-BOTIDINAMIX")
217
+ st.markdown(
218
+ f"""
219
+ <style>
220
+ #video-container {{
221
+ position: relative;
222
+ width: 100%;
223
+ padding-bottom: 56.25%;
224
+ background-color: lightblue;
225
+ overflow: hidden;
226
+ }}
227
+ #background-video {{
228
+ position: absolute;
229
+ top: 0;
230
+ left: 0;
231
+ width: 100%;
232
+ height: 100%;
233
+ }}
234
+ </style>
235
+ <div id="video-container">
236
+ <video id="background-video" autoplay loop muted playsinline>
237
+ <source src="https://cdn.leonardo.ai/users/645c3d5c-ca1b-4ce8-aefa-a091494e0d09/generations/0c4f0fe7-5937-4644-b984-bdbd95018990/0c4f0fe7-5937-4644-b984-bdbd95018990.mp4" type="video/mp4">
238
+ </video>
239
+ </div>
240
+ """,
241
+ unsafe_allow_html=True
242
+ )
243
+
244
+ archivo_pdf = st.file_uploader("📂 Cargar PDF", type='pdf', key='chat_pdf')
245
+
246
+ col1, col2 = st.columns([3, 1])
247
+ with col1:
248
+ pregunta_usuario = st.text_input("Pregunta:", key='unique_chat_input_key', value=st.session_state['transcripcion_voz'])
249
+ with col2:
250
+ capturar_voz()
251
+
252
+ if pregunta_usuario:
253
+ manejar_pregunta_usuario(pregunta_usuario, archivo_pdf)
254
+
255
+ if __name__ == "__main__":
256
+ main()