Spanicin commited on
Commit
ab2500f
·
verified ·
1 Parent(s): eafe07d

Update app_concurrent.py

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