JUAN DE DIOS DEL ANGEL ARRIAGA commited on
Commit
2866c09
1 Parent(s): 2862e5d

Upload 2 files

Browse files
Files changed (2) hide show
  1. Digital_mentor.py +407 -0
  2. README.md +1 -1
Digital_mentor.py ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding: utf-8
3
+
4
+ # # Digital Mentor
5
+ #
6
+ #
7
+
8
+ # In[ ]:
9
+
10
+
11
+ import os
12
+ from base64 import b64encode
13
+ import time
14
+ import torch
15
+ import utils
16
+ import api_utils
17
+ from openai import OpenAI
18
+ from moviepy.editor import VideoFileClip
19
+ from IPython.display import display, HTML, clear_output
20
+ import elevenlabs as elevlabs
21
+
22
+
23
+ # ## Set paths to media files
24
+
25
+ # In[ ]:
26
+
27
+
28
+ def seleccion(personaje='Albert', verbose=False):
29
+ # What character to use
30
+ clone_to_use = personaje # "Steve"
31
+ global input_video,presentation_video,goodbye_video,results_path,w_vid,h_vid
32
+ # Path to the media directory containing
33
+ # the avatar image, welcome video and goodbye videos
34
+ path = f"./media/"
35
+
36
+ input_video = path + f"{clone_to_use}/image.jpg"
37
+ presentation_video = path + f"{clone_to_use}/presentation.mp4"
38
+ goodbye_video = path + f"{clone_to_use}/goodbye.mp4"
39
+ results_path = path + f"{clone_to_use}/results/result.mp4"
40
+ w_vid = h_vid = "90%"
41
+
42
+ if verbose:
43
+ print(w_vid,h_vid,results_path)
44
+
45
+ print(clone_to_use)
46
+ if os.path.isfile(input_video):
47
+ print(f"Clone image found: {input_video}")
48
+ else:
49
+ print(f"CLONE IMAGE NOT FOUND: {input_video}")
50
+
51
+ if os.path.isfile(presentation_video):
52
+ print(f"Clone video found: {presentation_video}")
53
+ else:
54
+ print(f"CLONE VIDEO NOT FOUND: {presentation_video}")
55
+
56
+ if os.path.isfile(goodbye_video):
57
+ print(f"Clone goodbye video found: {goodbye_video}")
58
+ else:
59
+ print(f"CLONE GOODBYE NOT FOUND: {goodbye_video}")
60
+
61
+
62
+ seleccion(verbose=True)
63
+
64
+
65
+ # ## Set GPT API
66
+
67
+ # In[ ]:
68
+
69
+
70
+ def api_gpt(personaje='Albert'):
71
+ global openai_client,openai_model
72
+ clone_to_use=personaje
73
+ openai_api_key = os.environ.get('OPENAI_API_KEY')
74
+ openai_client = OpenAI(api_key=openai_api_key)
75
+
76
+ openai_model = "gpt-3.5-turbo-16k" #"gpt-3.5-turbo-16k" or"gpt-4"
77
+
78
+ system_steve = """You are a digital clone of Steve Jobs, I have put you his voice.
79
+ People will ask you questions and you will respond as if you were steve jobs
80
+ Please speak as if you were Steve Jobs. You are not a large language model but
81
+ a Steve Jobs digital clone. Try to be brief with your responses."""
82
+ system_albert = """You are a digital clone of Albert Einstein, I have put you his voice.
83
+ People will ask you questions and you will respond as if you were Albert Einstein
84
+ Please speak as if you were Albert Einstein. You are NOT a large language model but
85
+ an Albert Einstein digital clone. Try to be brief with your responses."""
86
+ global messages,system_to_use
87
+ if clone_to_use == "Steve":
88
+ system_to_use = system_steve
89
+ chat ="Hola, soy Steve ¿En que puedo ayudarte?" # Inicializar la cadena de chat
90
+ elif clone_to_use == "Albert":
91
+ system_to_use = system_albert
92
+ chat ="Hola, soy Albert ¿En que puedo ayudarte?" # Inicializar la cadena de chat
93
+
94
+ messages = []
95
+ #print(openai_client,openai_model,chat)
96
+
97
+ def set_gpt_system(messages, system_msg):
98
+ messages.append({"role": "system", "content": system_to_use})
99
+ return messages
100
+ # Set GPT
101
+ messages = set_gpt_system(messages, system_to_use)
102
+ return messages
103
+ messages=api_gpt()
104
+
105
+
106
+ # ## Set text-to-audio motor (Eleven labs)
107
+
108
+ # In[ ]:
109
+
110
+
111
+ eleven_api_key = os.environ.get('ELEVEN_LABS_KEY')
112
+
113
+ def text_audio(clone_to_use='Albert', verbose=False):
114
+
115
+ eleven_api_key = os.environ.get('ELEVEN_LABS_KEY')
116
+
117
+ # Configure GPT and Text-to-speech API keys
118
+ elevlabs.set_api_key(eleven_api_key)
119
+
120
+ # Configure voice
121
+ voice_list = elevlabs.voices()
122
+ voice_labels = [voice.category + " voice: " + voice.name for voice in voice_list]
123
+
124
+ if verbose:
125
+ print("Existing voices:")
126
+ print(voice_labels)
127
+
128
+ # Select voice to use
129
+ if clone_to_use == "Steve":
130
+ voice_id = f"cloned voice: {clone_to_use}"
131
+ else:
132
+ voice_id = f"generated voice: {clone_to_use}"
133
+ selected_voice_index = voice_labels.index(voice_id)
134
+ selected_voice_id = voice_list[selected_voice_index].voice_id
135
+
136
+ if verbose:
137
+ print(f"\nSelected voice: {voice_id}")
138
+ return selected_voice_id
139
+
140
+ selected_voice_id = text_audio(verbose = True)
141
+
142
+
143
+ # ## Load Input image and wav2lip model
144
+
145
+ # In[ ]:
146
+
147
+
148
+ def load_input():
149
+
150
+ global frames,fps,model,device
151
+
152
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
153
+ #print(f"Using {device}")
154
+ frames, fps = utils.load_input_image_or_video(input_video)
155
+
156
+ # Loading lip model
157
+ model = utils.load_lip_model(device=device)
158
+
159
+
160
+ load_input()
161
+
162
+
163
+ # ## Increase size of input prompt/Aumentar el tamaño del mensaje de entrada
164
+
165
+ # In[ ]:
166
+
167
+
168
+ display(HTML("""
169
+ <style>
170
+ div.input_prompt {
171
+ font-size: 10px; /* Adjust as needed */
172
+ }
173
+ </style>
174
+ """))
175
+
176
+
177
+ def displaychat(chat_html):
178
+ display(HTML(chat_html))
179
+
180
+ # Ejemplo de cómo llamar a la función con un mensaje específico
181
+ mensaje += chat_html
182
+ codigo_html = f"""
183
+ <label for="w3review">Chat:</label>
184
+ <textarea id="w3review" name="w3review" rows="4" cols="50">
185
+ {mensaje}
186
+ </textarea>
187
+ """
188
+
189
+ displaychat(codigo_html)
190
+
191
+
192
+ # In[ ]:
193
+
194
+
195
+ chat=''
196
+ memoria=''
197
+ def response_chat(response_text, peticion=''):
198
+ #contateno las respuesta para una mejor presentacion en el HTML
199
+ global chat # Acceder a la variable global
200
+ global memoria
201
+ peticion=peticion.capitalize()
202
+
203
+ if peticion =='' or peticion!='Albert' or peticion!='Steve':
204
+ if memoria != peticion and peticion != "exit":
205
+ # Agregar salto de línea si ya hay contenido en chat
206
+ chat += f"\n"
207
+ # Mentor: Aplicar color a la respuesta del mentor (por ejemplo, verde)
208
+ chat_rigth = f"Tu: {peticion}\n \n"
209
+ chat_left = f"Mentor: {response_text}\n \n"
210
+
211
+ chat += chat_rigth + chat_left
212
+ memoria = peticion
213
+ return chat
214
+
215
+ return chat
216
+
217
+
218
+ def display_image(image_path, width="55%", height="55%"):
219
+ with open(image_path,'rb') as f:
220
+ image = f.read()
221
+ data_url = "data:image/jpg;base64," + b64encode(image).decode()
222
+ html = HTML(f'<img src="{data_url}" style="width:{width}; height:{height}" />')
223
+ display(html)
224
+
225
+
226
+ def get_video_duration(video_path):
227
+ clip = VideoFileClip(video_path)
228
+ duration = clip.duration # duration is in seconds
229
+ return duration
230
+
231
+
232
+ def display_video(results_path, response_text,peticion="", autoplay=False, width="100%", height="100%"):
233
+ global resp
234
+ mp4 = open(results_path,'rb').read()
235
+ data_url = "data:video/mp4;base64," + b64encode(mp4).decode()
236
+ resp=response_chat(response_text, peticion)
237
+ autoplay_attr = "autoplay" if autoplay else ""
238
+ html = HTML(f"""
239
+ <div style="background-color: rgb(240, 240, 240); display: grid; grid-template-columns: 1fr 1fr; margin: 10px;">
240
+ <div style="text-align: center; position: relative; margin: 10px;">
241
+ <video width={width} height={height} controls {autoplay_attr} >
242
+ <source src="{data_url}" type="video/mp4">
243
+ </video>
244
+ </div>
245
+ <div style="position: relative; margin: 10px;">
246
+ <p style="text-align: center; right: 0; top: 0;">
247
+ <h1>Conversación</h1>
248
+ </p>
249
+ <textarea id="cuadro-dialogo" class="cuadro-de-dialogo" style="width: 100%; height: 60%; resize: none; font-weight: bold;" readonly>
250
+ {resp}
251
+ </textarea>
252
+ </div>
253
+ </div>
254
+ <script>
255
+ // Asegurarse de que el contenido de textarea esté siempre en la parte inferior
256
+ var textarea = document.getElementById('cuadro-dialogo');
257
+ textarea.scrollTop = textarea.scrollHeight;
258
+ </script>
259
+ """)
260
+ display(html)
261
+
262
+ if autoplay:
263
+ # Get video duration
264
+ video_duration = get_video_duration(results_path) + 1
265
+
266
+ # Pause the cell execution until the video finishes
267
+ time.sleep(video_duration)
268
+
269
+
270
+
271
+ # Function to continuously interact with GPT-4
272
+ def interaction(prompt):
273
+ global messages, selected_voice_id,response_text
274
+
275
+
276
+ #selected_voice_id=text_audio()
277
+
278
+ if prompt.lower() == 'exit':
279
+ #asigno una respuesta para no mostrar la respuesta anterior
280
+ response_text=f'Hasta la proxima'
281
+
282
+ else:
283
+
284
+
285
+ personaje=prompt.lower().capitalize()
286
+ if personaje=='Steve' or personaje=='Albert':
287
+ #recargo todas las dependencias y paso al personaje en uso
288
+ seleccion(personaje.capitalize())
289
+ messages=api_gpt(personaje)
290
+ selected_voice_id=text_audio(personaje)
291
+ load_input()
292
+
293
+ #asigno los valores para que no repita la respuesta anterior
294
+ prompt=personaje
295
+ response_text=f'Hola soy: {personaje} ¿En que puedo ayudarte?'
296
+
297
+ else:
298
+
299
+ response_text, messages = api_utils.get_text_response(openai_client,
300
+ openai_model,
301
+ prompt, messages)
302
+
303
+ # Convert text response to audio file
304
+ #audio_file = api_utils.text_to_audio(eleven_api_key, selected_voice_id,
305
+ #response_text)
306
+ #comentar esta linea y regresar la anterior a la normalidad
307
+ audio_file = "C:/Users/arria/Documents/digital_mentor/media/Albert/results"
308
+ audio, audio_file = utils.load_input_audio(file_path=audio_file, fps=fps, results_path=results_path)
309
+ utils.animate_input(frames, audio, audio_file, fps, model, device, results_path)
310
+
311
+
312
+
313
+ return results_path,response_text
314
+
315
+
316
+
317
+
318
+ # # Mentor Digital
319
+
320
+ # In[ ]:
321
+
322
+
323
+ import firebase_admin
324
+ from firebase_admin import credentials, firestore, storage
325
+ from datetime import datetime, timedelta
326
+
327
+ def subir_firebase():
328
+
329
+ if not firebase_admin._apps:
330
+ # Inicializar la aplicación Firebase
331
+ cred = credentials.Certificate('credenciales/credenciales.json')
332
+ firebase_admin.initialize_app(cred, {'storageBucket': 'mentores-c1064.appspot.com'})
333
+
334
+
335
+ # Inicializa Firestore
336
+ db = firestore.client()
337
+ coleccion_ref = db.collection('Pruebas')
338
+
339
+ # Lógica para subir el archivo y obtener la URL con token
340
+ archivo_ruta = results_path.lstrip('./')
341
+ bucket = storage.bucket()
342
+ blob = bucket.blob(archivo_ruta)
343
+ blob.upload_from_filename(archivo_ruta)
344
+ hora_expiracion = datetime.utcnow() + timedelta(minutes=5)
345
+ token = blob.generate_signed_url(expiration=hora_expiracion, method='GET')
346
+ archivo_url_con_token = token
347
+
348
+ datos = {
349
+ 'respuesta': chat,
350
+ 'archivo_url': archivo_url_con_token,
351
+ # Agrega más campos según sea necesario
352
+ }
353
+ coleccion_ref.add(datos)
354
+
355
+ # Imprime la respuesta
356
+ return archivo_url_con_token
357
+
358
+
359
+ # In[ ]:
360
+
361
+
362
+ import gradio as gr
363
+
364
+ # URL fija del video
365
+
366
+
367
+ def mostrar_video_con_texto(propmt):
368
+ if not propmt:
369
+ return "Por favor, completa ambos campos."
370
+ url,respuesta=interaction(propmt)
371
+
372
+ URL_VIDEO =subir_firebase()
373
+ print(URL_VIDEO)
374
+ reproductor_video = """<video width="640" height="480" controls autoplay>
375
+ <source src="{}" type="video/mp4">
376
+ Your browser does not support the video tag.
377
+ </video>""".format(URL_VIDEO)
378
+
379
+ # Alineación del texto a la derecha del video con un poco de separación
380
+ propmt = '<div style="float:left; padding-right:20px;">{}</div>'.format(propmt.replace("\n", "<br>"))
381
+ respuesta = '<div style="float:right; padding-left:20px;">{}</div>'.format(respuesta.replace("\n", "<br>"))
382
+
383
+ # Combinar el reproductor de video y el texto
384
+ contenido = '<div style="overflow:auto;">{}<br>{}<br>{}</div>'.format(reproductor_video, propmt, respuesta)
385
+ return contenido
386
+
387
+ interfaz = gr.Interface(fn=mostrar_video_con_texto, inputs="text", outputs="html", title="Mentores Digitales", allow_flagging=False)
388
+ interfaz.launch()
389
+
390
+
391
+ # In[ ]:
392
+
393
+
394
+
395
+
396
+
397
+ # In[ ]:
398
+
399
+
400
+
401
+
402
+
403
+ # In[ ]:
404
+
405
+
406
+
407
+
README.md CHANGED
@@ -5,7 +5,7 @@ colorFrom: "red"
5
  colorTo: "green"
6
  sdk: "gradio"
7
  sdk_version: "4.23.0"
8
- app_file: "Digital_mentor.ipynb"
9
  pinned: false
10
  ---
11
 
 
5
  colorTo: "green"
6
  sdk: "gradio"
7
  sdk_version: "4.23.0"
8
+ app_file: "Digital_mentor.py"
9
  pinned: false
10
  ---
11