Spanicin commited on
Commit
564fc17
·
verified ·
1 Parent(s): ba68b15

Upload app_concurrent.py

Browse files
Files changed (1) hide show
  1. app_concurrent.py +567 -0
app_concurrent.py ADDED
@@ -0,0 +1,567 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify, Response, stream_with_context
2
+ import torch
3
+ import shutil
4
+ import os
5
+ import sys
6
+ from argparse import ArgumentParser
7
+ from time import strftime
8
+ from argparse import Namespace
9
+ from src.utils.preprocess import CropAndExtract
10
+ from src.test_audio2coeff import Audio2Coeff
11
+ from src.facerender.animate import AnimateFromCoeff
12
+ from src.generate_batch import get_data
13
+ from src.generate_facerender_batch import get_facerender_data
14
+ # from src.utils.init_path import init_path
15
+ import tempfile
16
+ from openai import OpenAI, AsyncOpenAI
17
+ import threading
18
+ import elevenlabs
19
+ from elevenlabs import set_api_key, generate, play, clone, Voice, VoiceSettings
20
+ # from flask_cors import CORS, cross_origin
21
+ # from flask_swagger_ui import get_swaggerui_blueprint
22
+ import uuid
23
+ import time
24
+ from PIL import Image
25
+ import moviepy.editor as mp
26
+ import requests
27
+ import json
28
+ import pickle
29
+ from celery import Celery
30
+ import concurrent.futures
31
+ import multiprocessing
32
+
33
+ # Get the number of CPU cores
34
+ cpu_cores = multiprocessing.cpu_count()
35
+ print(f"Number of available CPU cores: {cpu_cores}")
36
+
37
+
38
+
39
+ class AnimationConfig:
40
+ def __init__(self, driven_audio_path, source_image_path, result_folder,pose_style,expression_scale,enhancer,still,preprocess,ref_pose_video_path, image_hardcoded):
41
+ self.driven_audio = driven_audio_path
42
+ self.source_image = source_image_path
43
+ self.ref_eyeblink = None
44
+ self.ref_pose = ref_pose_video_path
45
+ self.checkpoint_dir = './checkpoints'
46
+ self.result_dir = result_folder
47
+ self.pose_style = pose_style
48
+ self.batch_size = 2
49
+ self.expression_scale = expression_scale
50
+ self.input_yaw = None
51
+ self.input_pitch = None
52
+ self.input_roll = None
53
+ self.enhancer = enhancer
54
+ self.background_enhancer = None
55
+ self.cpu = False
56
+ self.face3dvis = False
57
+ self.still = still
58
+ self.preprocess = preprocess
59
+ self.verbose = False
60
+ self.old_version = False
61
+ self.net_recon = 'resnet50'
62
+ self.init_path = None
63
+ self.use_last_fc = False
64
+ self.bfm_folder = './checkpoints/BFM_Fitting/'
65
+ self.bfm_model = 'BFM_model_front.mat'
66
+ self.focal = 1015.
67
+ self.center = 112.
68
+ self.camera_d = 10.
69
+ self.z_near = 5.
70
+ self.z_far = 15.
71
+ self.device = 'cpu'
72
+ self.image_hardcoded = image_hardcoded
73
+
74
+
75
+ app = Flask(__name__)
76
+
77
+ MAX_WORKERS = cpu_cores-1
78
+ TEMP_DIR = None
79
+ start_time = None
80
+ chunk_tasks = []
81
+ futures = []
82
+
83
+ app.config['temp_response'] = None
84
+ app.config['generation_thread'] = None
85
+ app.config['text_prompt'] = None
86
+ app.config['final_video_path'] = None
87
+ app.config['final_video_duration'] = None
88
+
89
+
90
+
91
+
92
+ def main(args):
93
+ print("Entered main function")
94
+ pic_path = args.source_image
95
+ audio_path = args.driven_audio
96
+ save_dir = args.result_dir
97
+ pose_style = args.pose_style
98
+ device = args.device
99
+ batch_size = args.batch_size
100
+ input_yaw_list = args.input_yaw
101
+ input_pitch_list = args.input_pitch
102
+ input_roll_list = args.input_roll
103
+ ref_eyeblink = args.ref_eyeblink
104
+ ref_pose = args.ref_pose
105
+ preprocess = args.preprocess
106
+ image_hardcoded = args.image_hardcoded
107
+
108
+ dir_path = os.path.dirname(os.path.realpath(__file__))
109
+ current_root_path = dir_path
110
+ print('current_root_path ',current_root_path)
111
+
112
+ # sadtalker_paths = init_path(args.checkpoint_dir, os.path.join(current_root_path, 'src/config'), args.size, args.old_version, args.preprocess)
113
+
114
+ path_of_lm_croper = os.path.join(current_root_path, args.checkpoint_dir, 'shape_predictor_68_face_landmarks.dat')
115
+ path_of_net_recon_model = os.path.join(current_root_path, args.checkpoint_dir, 'epoch_20.pth')
116
+ dir_of_BFM_fitting = os.path.join(current_root_path, args.checkpoint_dir, 'BFM_Fitting')
117
+ wav2lip_checkpoint = os.path.join(current_root_path, args.checkpoint_dir, 'wav2lip.pth')
118
+
119
+ audio2pose_checkpoint = os.path.join(current_root_path, args.checkpoint_dir, 'auido2pose_00140-model.pth')
120
+ audio2pose_yaml_path = os.path.join(current_root_path, 'src', 'config', 'auido2pose.yaml')
121
+
122
+ audio2exp_checkpoint = os.path.join(current_root_path, args.checkpoint_dir, 'auido2exp_00300-model.pth')
123
+ audio2exp_yaml_path = os.path.join(current_root_path, 'src', 'config', 'auido2exp.yaml')
124
+
125
+ free_view_checkpoint = os.path.join(current_root_path, args.checkpoint_dir, 'facevid2vid_00189-model.pth.tar')
126
+
127
+ if preprocess == 'full':
128
+ mapping_checkpoint = os.path.join(current_root_path, args.checkpoint_dir, 'mapping_00109-model.pth.tar')
129
+ facerender_yaml_path = os.path.join(current_root_path, 'src', 'config', 'facerender_still.yaml')
130
+ else:
131
+ mapping_checkpoint = os.path.join(current_root_path, args.checkpoint_dir, 'mapping_00229-model.pth.tar')
132
+ facerender_yaml_path = os.path.join(current_root_path, 'src', 'config', 'facerender.yaml')
133
+
134
+
135
+ # preprocess_model = CropAndExtract(sadtalker_paths, device)
136
+ #init model
137
+ print(path_of_net_recon_model)
138
+ preprocess_model = CropAndExtract(path_of_lm_croper, path_of_net_recon_model, dir_of_BFM_fitting, device)
139
+
140
+ # audio_to_coeff = Audio2Coeff(sadtalker_paths, device)
141
+ audio_to_coeff = Audio2Coeff(audio2pose_checkpoint, audio2pose_yaml_path,
142
+ audio2exp_checkpoint, audio2exp_yaml_path,
143
+ wav2lip_checkpoint, device)
144
+ # animate_from_coeff = AnimateFromCoeff(sadtalker_paths, device)
145
+ animate_from_coeff = AnimateFromCoeff(free_view_checkpoint, mapping_checkpoint,
146
+ facerender_yaml_path, device)
147
+
148
+ first_frame_dir = os.path.join(save_dir, 'first_frame_dir')
149
+ os.makedirs(first_frame_dir, exist_ok=True)
150
+ # first_coeff_path, crop_pic_path, crop_info = preprocess_model.generate(pic_path, first_frame_dir, args.preprocess,\
151
+ # source_image_flag=True, pic_size=args.size)
152
+
153
+
154
+ # fixed_temp_dir = "/tmp/preprocess_data"
155
+ # os.makedirs(fixed_temp_dir, exist_ok=True)
156
+ # preprocessed_data_path = os.path.join(fixed_temp_dir, "preprocessed_data.pkl")
157
+
158
+ # if os.path.exists(preprocessed_data_path) and image_hardcoded == "yes":
159
+ # print("Loading preprocessed data...")
160
+ # with open(preprocessed_data_path, "rb") as f:
161
+ # preprocessed_data = pickle.load(f)
162
+ # first_coeff_new_path = preprocessed_data["first_coeff_path"]
163
+ # crop_pic_new_path = preprocessed_data["crop_pic_path"]
164
+ # crop_info_path = preprocessed_data["crop_info_path"]
165
+ # with open(crop_info_path, "rb") as f:
166
+ # crop_info = pickle.load(f)
167
+
168
+ # print(f"Loaded existing preprocessed data from: {preprocessed_data_path}")
169
+
170
+ # else:
171
+ # print("Running preprocessing...")
172
+ # first_coeff_path, crop_pic_path, crop_info = preprocess_model.generate(pic_path, first_frame_dir, args.preprocess, source_image_flag=True)
173
+ # first_coeff_new_path = os.path.join(fixed_temp_dir, os.path.basename(first_coeff_path))
174
+ # crop_pic_new_path = os.path.join(fixed_temp_dir, os.path.basename(crop_pic_path))
175
+ # crop_info_new_path = os.path.join(fixed_temp_dir, "crop_info.pkl")
176
+ # shutil.move(first_coeff_path, first_coeff_new_path)
177
+ # shutil.move(crop_pic_path, crop_pic_new_path)
178
+
179
+ # with open(crop_info_new_path, "wb") as f:
180
+ # pickle.dump(crop_info, f)
181
+
182
+ # preprocessed_data = {"first_coeff_path": first_coeff_new_path,
183
+ # "crop_pic_path": crop_pic_new_path,
184
+ # "crop_info_path": crop_info_new_path}
185
+
186
+
187
+ # with open(preprocessed_data_path, "wb") as f:
188
+ # pickle.dump(preprocessed_data, f)
189
+ # print(f"Preprocessed data saved to: {preprocessed_data_path}")
190
+
191
+ first_coeff_path, crop_pic_path, crop_info = preprocess_model.generate(pic_path, first_frame_dir, args.preprocess, source_image_flag=True)
192
+
193
+
194
+ print('first_coeff_path ',first_coeff_path)
195
+ print('crop_pic_path ',crop_pic_path)
196
+ print('crop_info ',crop_info)
197
+
198
+ if first_coeff_path is None:
199
+ print("Can't get the coeffs of the input")
200
+ return
201
+
202
+ if ref_eyeblink is not None:
203
+ ref_eyeblink_videoname = os.path.splitext(os.path.split(ref_eyeblink)[-1])[0]
204
+ ref_eyeblink_frame_dir = os.path.join(save_dir, ref_eyeblink_videoname)
205
+ os.makedirs(ref_eyeblink_frame_dir, exist_ok=True)
206
+ # ref_eyeblink_coeff_path, _, _ = preprocess_model.generate(ref_eyeblink, ref_eyeblink_frame_dir, args.preprocess, source_image_flag=False)
207
+ ref_eyeblink_coeff_path, _, _ = preprocess_model.generate(ref_eyeblink, ref_eyeblink_frame_dir)
208
+ else:
209
+ ref_eyeblink_coeff_path=None
210
+ print('ref_eyeblink_coeff_path',ref_eyeblink_coeff_path)
211
+
212
+ if ref_pose is not None:
213
+ if ref_pose == ref_eyeblink:
214
+ ref_pose_coeff_path = ref_eyeblink_coeff_path
215
+ else:
216
+ ref_pose_videoname = os.path.splitext(os.path.split(ref_pose)[-1])[0]
217
+ ref_pose_frame_dir = os.path.join(save_dir, ref_pose_videoname)
218
+ os.makedirs(ref_pose_frame_dir, exist_ok=True)
219
+ # ref_pose_coeff_path, _, _ = preprocess_model.generate(ref_pose, ref_pose_frame_dir, args.preprocess, source_image_flag=False)
220
+ ref_pose_coeff_path, _, _ = preprocess_model.generate(ref_pose, ref_pose_frame_dir)
221
+ else:
222
+ ref_pose_coeff_path=None
223
+ print('ref_eyeblink_coeff_path',ref_pose_coeff_path)
224
+
225
+ batch = get_data(first_coeff_path, audio_path, device, ref_eyeblink_coeff_path, still=args.still)
226
+ coeff_path = audio_to_coeff.generate(batch, save_dir, pose_style, ref_pose_coeff_path)
227
+
228
+
229
+ if args.face3dvis:
230
+ from src.face3d.visualize import gen_composed_video
231
+ gen_composed_video(args, device, first_coeff_path, coeff_path, audio_path, os.path.join(save_dir, '3dface.mp4'))
232
+
233
+ # data = get_facerender_data(coeff_path, crop_pic_path, first_coeff_path, audio_path,
234
+ # batch_size, input_yaw_list, input_pitch_list, input_roll_list,
235
+ # expression_scale=args.expression_scale, still_mode=args.still, preprocess=args.preprocess, size=args.size)
236
+
237
+
238
+ data = get_facerender_data(coeff_path, crop_pic_path, first_coeff_path, audio_path,
239
+ batch_size, input_yaw_list, input_pitch_list, input_roll_list,
240
+ expression_scale=args.expression_scale, still_mode=args.still, preprocess=args.preprocess)
241
+
242
+ # result, base64_video,temp_file_path= animate_from_coeff.generate(data, save_dir, pic_path, crop_info, \
243
+ # enhancer=args.enhancer, background_enhancer=args.background_enhancer, preprocess=args.preprocess, img_size=args.size)
244
+
245
+
246
+ result, base64_video,temp_file_path,new_audio_path = animate_from_coeff.generate(data, save_dir, pic_path, crop_info, \
247
+ enhancer=args.enhancer, background_enhancer=args.background_enhancer, preprocess=args.preprocess)
248
+
249
+
250
+ video_clip = mp.VideoFileClip(temp_file_path)
251
+ duration = video_clip.duration
252
+
253
+ app.config['temp_response'] = base64_video
254
+ app.config['final_video_path'] = temp_file_path
255
+ app.config['final_video_duration'] = duration
256
+
257
+ return base64_video, temp_file_path, duration
258
+
259
+
260
+ def create_temp_dir():
261
+ return tempfile.TemporaryDirectory()
262
+
263
+ def save_uploaded_file(file, filename,TEMP_DIR):
264
+ print("Entered save_uploaded_file")
265
+ unique_filename = str(uuid.uuid4()) + "_" + filename
266
+ file_path = os.path.join(TEMP_DIR.name, unique_filename)
267
+ file.save(file_path)
268
+ return file_path
269
+
270
+ # client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
271
+
272
+ # def openai_chat_avatar(text_prompt):
273
+ # response = client.chat.completions.create(
274
+ # model="gpt-4o-mini",
275
+ # messages=[{"role": "system", "content": "Answer using the minimum words you can ever use."},
276
+ # {"role": "user", "content": f"Hi! I need help with something. Can you assist me with the following: {text_prompt}"},
277
+ # ],
278
+ # max_tokens = len(text_prompt) + 300 # Use the length of the input text
279
+ # # temperature=0.3,
280
+ # # stop=["Translate:", "Text:"]
281
+ # )
282
+ # return response
283
+
284
+ def ryzedb_chat_avatar(question):
285
+ url = "https://inference.dev.ryzeai.ai/chat/stream"
286
+ question = question + ". Summarize and Answer using the minimum words you can ever use."
287
+ payload = json.dumps({
288
+ "input": {
289
+ "chat_history": [],
290
+ "app_id": os.getenv('RYZE_APP_ID'),
291
+ "question": question
292
+ },
293
+ "config": {}
294
+ })
295
+ headers = {
296
+ 'Content-Type': 'application/json'
297
+ }
298
+
299
+ try:
300
+ # Send the POST request
301
+ response = requests.request("POST", url, headers=headers, data=payload)
302
+
303
+ # Check for successful request
304
+ response.raise_for_status()
305
+
306
+ # Return the response JSON
307
+ return response.text
308
+
309
+ except requests.exceptions.RequestException as e:
310
+ print(f"An error occurred: {e}")
311
+ return None
312
+
313
+ def custom_cleanup(temp_dir, exclude_dir):
314
+ # Iterate over the files and directories in TEMP_DIR
315
+ for filename in os.listdir(temp_dir):
316
+ file_path = os.path.join(temp_dir, filename)
317
+ # Skip the directory we want to exclude
318
+ if file_path != exclude_dir:
319
+ try:
320
+ if os.path.isdir(file_path):
321
+ shutil.rmtree(file_path)
322
+ else:
323
+ os.remove(file_path)
324
+ print(f"Deleted: {file_path}")
325
+ except Exception as e:
326
+ print(f"Failed to delete {file_path}. Reason: {e}")
327
+
328
+
329
+ def generate_audio(voice_cloning, voice_gender, text_prompt):
330
+ print("generate_audio")
331
+ if voice_cloning == 'no':
332
+ if voice_gender == 'male':
333
+ voice = 'echo'
334
+ print('Entering Audio creation using elevenlabs')
335
+ set_api_key("92e149985ea2732b4359c74346c3daee")
336
+
337
+ audio = generate(text = text_prompt, voice = "Daniel", model = "eleven_multilingual_v2",stream=True, latency=4)
338
+ with tempfile.NamedTemporaryFile(suffix=".mp3", prefix="text_to_speech_",dir=TEMP_DIR.name, delete=False) as temp_file:
339
+ for chunk in audio:
340
+ temp_file.write(chunk)
341
+ driven_audio_path = temp_file.name
342
+ print('driven_audio_path',driven_audio_path)
343
+ print('Audio file saved using elevenlabs')
344
+
345
+ else:
346
+ voice = 'nova'
347
+
348
+ print('Entering Audio creation using whisper')
349
+ response = client.audio.speech.create(model="tts-1-hd",
350
+ voice=voice,
351
+ input = text_prompt)
352
+
353
+ print('Audio created using whisper')
354
+ with tempfile.NamedTemporaryFile(suffix=".wav", prefix="text_to_speech_",dir=TEMP_DIR.name, delete=False) as temp_file:
355
+ driven_audio_path = temp_file.name
356
+
357
+ response.write_to_file(driven_audio_path)
358
+ print('Audio file saved using whisper')
359
+
360
+ elif voice_cloning == 'yes':
361
+ set_api_key("92e149985ea2732b4359c74346c3daee")
362
+ # voice = clone(name = "User Cloned Voice",
363
+ # files = [user_voice_path] )
364
+ voice = Voice(voice_id="CEii8R8RxmB0zhAiloZg",name="Marc",settings=VoiceSettings(
365
+ stability=0.71, similarity_boost=0.5, style=0.0, use_speaker_boost=True),)
366
+
367
+ audio = generate(text = text_prompt, voice = voice, model = "eleven_multilingual_v2",stream=True, latency=4)
368
+ with tempfile.NamedTemporaryFile(suffix=".mp3", prefix="cloned_audio_",dir=TEMP_DIR.name, delete=False) as temp_file:
369
+ for chunk in audio:
370
+ temp_file.write(chunk)
371
+ driven_audio_path = temp_file.name
372
+ print('driven_audio_path',driven_audio_path)
373
+
374
+ return driven_audio_path
375
+
376
+ def split_audio(audio_path, chunk_duration=5):
377
+ audio_clip = mp.AudioFileClip(audio_path)
378
+ total_duration = audio_clip.duration
379
+
380
+ audio_chunks = []
381
+ for start_time in range(0, int(total_duration), chunk_duration):
382
+ end_time = min(start_time + chunk_duration, total_duration)
383
+ chunk = audio_clip.subclip(start_time, end_time)
384
+ with tempfile.NamedTemporaryFile(suffix=f"_chunk_{start_time}-{end_time}.wav", prefix="audio_chunk_", dir=TEMP_DIR.name, delete=False) as temp_file:
385
+ chunk_path = temp_file.name
386
+ chunk.write_audiofile(chunk_path)
387
+ audio_chunks.append(chunk_path)
388
+
389
+ return audio_chunks
390
+
391
+
392
+ def process_video_for_chunk_sync(audio_chunk_path, args_dict, chunk_index):
393
+ """
394
+ Synchronous function to process a video chunk. This will be submitted to concurrent.futures ProcessPoolExecutor.
395
+ """
396
+ print("Entered process_video_for_chunk_sync")
397
+ args = AnimationConfig(
398
+ driven_audio_path=args_dict['driven_audio_path'],
399
+ source_image_path=args_dict['source_image_path'],
400
+ result_folder=args_dict['result_folder'],
401
+ pose_style=args_dict['pose_style'],
402
+ expression_scale=args_dict['expression_scale'],
403
+ enhancer=args_dict['enhancer'],
404
+ still=args_dict['still'],
405
+ preprocess=args_dict['preprocess'],
406
+ ref_pose_video_path=args_dict['ref_pose_video_path'],
407
+ image_hardcoded=args_dict['image_hardcoded']
408
+ )
409
+ args.driven_audio = audio_chunk_path
410
+ chunk_save_dir = os.path.join(args.result_dir, f"chunk_{chunk_index}")
411
+ os.makedirs(chunk_save_dir, exist_ok=True)
412
+
413
+ try:
414
+ base64_video, video_chunk_path, duration = main(args)
415
+ print(f"Main function returned: {video_chunk_path}, {duration}")
416
+ return video_chunk_path
417
+ except Exception as e:
418
+ print(f"Error in process_video_for_chunk_sync: {str(e)}")
419
+ raise
420
+
421
+
422
+ @app.route("/run", methods=['POST'])
423
+ def generate_video():
424
+ global start_time
425
+ global chunk_tasks
426
+ global futures
427
+ start_time = time.time()
428
+ global TEMP_DIR
429
+ TEMP_DIR = create_temp_dir()
430
+ print('request:',request.method)
431
+ try:
432
+ if request.method == 'POST':
433
+ # source_image = request.files['source_image']
434
+ image_path = '/home/user/app/images/out.jpg'
435
+ source_image = Image.open(image_path)
436
+ text_prompt = request.form['text_prompt']
437
+
438
+ print('Input text prompt: ',text_prompt)
439
+ text_prompt = text_prompt.strip()
440
+ if not text_prompt:
441
+ return jsonify({'error': 'Input text prompt cannot be blank'}), 400
442
+
443
+ voice_cloning = request.form.get('voice_cloning', 'yes')
444
+ image_hardcoded = request.form.get('image_hardcoded', 'yes')
445
+ chat_model_used = request.form.get('chat_model_used', 'openai')
446
+ target_language = request.form.get('target_language', 'original_text')
447
+ print('target_language',target_language)
448
+ pose_style = int(request.form.get('pose_style', 1))
449
+ expression_scale = float(request.form.get('expression_scale', 1))
450
+ enhancer = request.form.get('enhancer', None)
451
+ voice_gender = request.form.get('voice_gender', 'male')
452
+ still_str = request.form.get('still', 'False')
453
+ still = still_str.lower() == 'false'
454
+ print('still', still)
455
+ preprocess = request.form.get('preprocess', 'crop')
456
+ print('preprocess selected: ',preprocess)
457
+ ref_pose_video = request.files.get('ref_pose', None)
458
+
459
+ if chat_model_used == 'ryzedb':
460
+ response = ryzedb_chat_avatar(text_prompt)
461
+ events = response.split('\r\n\r\n')
462
+ content = None
463
+ for event in events:
464
+ # Split each event block by "\r\n" to get the lines
465
+ lines = event.split('\r\n')
466
+ if len(lines) > 1 and lines[0] == 'event: data':
467
+ # Extract the JSON part from the second line and parse it
468
+ json_data = lines[1].replace('data: ', '')
469
+ try:
470
+ data = json.loads(json_data)
471
+ text_prompt = data.get('content')
472
+ app.config['text_prompt'] = text_prompt
473
+ print('Final output text prompt using ryzedb: ',text_prompt)
474
+ break # Exit the loop once content is found
475
+ except json.JSONDecodeError:
476
+ continue
477
+
478
+ else:
479
+ # response = openai_chat_avatar(text_prompt)
480
+ # text_prompt = response.choices[0].message.content.strip()
481
+ app.config['text_prompt'] = text_prompt
482
+ print('Final output text prompt using openai: ',text_prompt)
483
+
484
+ source_image_path = save_uploaded_file(source_image, 'source_image.png',TEMP_DIR)
485
+ print(source_image_path)
486
+
487
+ driven_audio_path = generate_audio(voice_cloning, voice_gender, text_prompt)
488
+ chunk_duration = 5
489
+ print(f"Splitting the audio into {chunk_duration}-second chunks...")
490
+ audio_chunks = split_audio(driven_audio_path, chunk_duration=chunk_duration)
491
+ print(f"Audio has been split into {len(audio_chunks)} chunks: {audio_chunks}")
492
+
493
+ save_dir = tempfile.mkdtemp(dir=TEMP_DIR.name)
494
+ result_folder = os.path.join(save_dir, "results")
495
+ os.makedirs(result_folder, exist_ok=True)
496
+
497
+ ref_pose_video_path = None
498
+ if ref_pose_video:
499
+ with tempfile.NamedTemporaryFile(suffix=".mp4", prefix="ref_pose_",dir=TEMP_DIR.name, delete=False) as temp_file:
500
+ ref_pose_video_path = temp_file.name
501
+ ref_pose_video.save(ref_pose_video_path)
502
+ print('ref_pose_video_path',ref_pose_video_path)
503
+
504
+ except Exception as e:
505
+ app.logger.error(f"An error occurred: {e}")
506
+ return "An error occurred", 500
507
+
508
+ # args = AnimationConfig(driven_audio_path=driven_audio_path, source_image_path=source_image_path, result_folder=result_folder, pose_style=pose_style, expression_scale=expression_scale,enhancer=enhancer,still=still,preprocess=preprocess,ref_pose_video_path=ref_pose_video_path, image_hardcoded=image_hardcoded)
509
+ args_dict = {
510
+ 'driven_audio_path': driven_audio_path,
511
+ 'source_image_path': source_image_path,
512
+ 'result_folder': result_folder,
513
+ 'pose_style': pose_style,
514
+ 'expression_scale': expression_scale,
515
+ 'enhancer': enhancer,
516
+ 'still': still,
517
+ 'preprocess': preprocess,
518
+ 'ref_pose_video_path': ref_pose_video_path,
519
+ 'image_hardcoded': image_hardcoded,
520
+ 'device': 'cuda' if torch.cuda.is_available() else 'cpu'}
521
+
522
+ executor = concurrent.futures.ProcessPoolExecutor(max_workers=MAX_WORKERS)
523
+ try:
524
+ for index, audio_chunk in enumerate(audio_chunks):
525
+ print(f"Submitting chunk {index} with audio_chunk: {audio_chunk}")
526
+ future = executor.submit(process_video_for_chunk_sync, audio_chunk, args_dict, index)
527
+ futures.append(future)
528
+ return jsonify({'status': 'Video generation started'}), 200
529
+
530
+
531
+ except Exception as e:
532
+ return jsonify({'status': 'error', 'message': str(e)}), 500
533
+
534
+ @app.route("/stream", methods=['GET'])
535
+ def stream_video_chunks():
536
+ global futures
537
+ print("futures:", futures)
538
+
539
+ @stream_with_context
540
+ def generate_chunks():
541
+ video_chunk_paths = []
542
+ for future in concurrent.futures.as_completed(futures): # Wait for each future to complete
543
+ try:
544
+ video_chunk_path = future.result() # Get the result (video chunk path)
545
+ video_chunk_paths.append(video_chunk_path)
546
+ yield f'data: {video_chunk_path}\n\n' # Stream the chunk path to frontend
547
+ app.logger.info(f"Chunk generated and sent: {video_chunk_path}")
548
+ os.remove(video_chunk_path) # Optionally delete the chunk after sending
549
+ except Exception as e:
550
+ app.logger.error(f"Error while fetching future result: {str(e)}")
551
+ yield f'data: error\n\n'
552
+
553
+ preprocess_dir = os.path.join("/tmp", "preprocess_data")
554
+ custom_cleanup(TEMP_DIR.name, preprocess_dir)
555
+ app.logger.info("Temporary files cleaned up, but preprocess_data is retained.")
556
+
557
+ # Return the generator that streams the data as it becomes available
558
+ return Response(generate_chunks(), content_type='text/event-stream')
559
+
560
+
561
+
562
+ @app.route("/health", methods=["GET"])
563
+ def health_status():
564
+ response = {"online": "true"}
565
+ return jsonify(response)
566
+ if __name__ == '__main__':
567
+ app.run(debug=True)