File size: 20,476 Bytes
93d7c21
579a758
8c19e54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a83c683
c449593
579a758
6036cd8
8c19e54
 
a83c683
8c19e54
 
cfd1f34
ed60b39
8c19e54
 
 
 
 
 
af26267
8c19e54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7cd9d2
8c19e54
 
 
 
6d6c7a1
 
 
8c19e54
 
 
358991e
 
 
4290815
 
60d3a1b
2c89aa0
8c19e54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e37406
c9c856d
9e37406
8c19e54
febd078
8c19e54
 
 
d1a37a7
8c19e54
 
 
 
 
 
 
 
 
ed60b39
 
8c19e54
 
 
d1a37a7
8c19e54
 
 
 
f52006b
 
8c19e54
 
 
f52006b
d1a37a7
f52006b
8c19e54
 
 
 
 
 
 
 
 
 
 
 
 
febd078
8c19e54
 
 
febd078
 
 
 
 
 
 
 
 
8c19e54
e703756
 
 
 
 
579a758
8c19e54
 
 
 
 
 
 
cc75e44
8c19e54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc75e44
8c19e54
 
 
 
 
 
 
 
 
 
 
e703756
 
8c19e54
e703756
8c19e54
 
 
c639632
 
9e37406
dd6f240
8c19e54
 
 
18c0bae
8c19e54
 
 
 
 
18c0bae
febd078
 
 
 
 
 
 
 
 
 
 
 
 
f52006b
e703756
8c19e54
 
e703756
 
 
8c19e54
e703756
 
8c19e54
 
e703756
 
8c19e54
 
e703756
7e1d2db
8c19e54
e703756
 
352f55d
 
 
 
8c19e54
352f55d
4c64658
bdf3460
9118691
352f55d
 
 
116013b
579a758
352f55d
116013b
352f55d
 
 
 
c4d5428
4c64658
 
5c3a99b
f1cbe8a
 
 
 
 
352f55d
 
 
 
116013b
 
 
 
393af81
116013b
352f55d
6d6c7a1
 
 
 
 
 
 
 
8c19e54
 
2c89aa0
60d3a1b
8c19e54
 
 
4290815
579a758
8c19e54
 
 
 
be190bc
8c19e54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af26267
8c19e54
be190bc
 
8c19e54
 
 
 
 
 
e703756
8c19e54
 
 
 
 
 
579a758
 
2c89aa0
 
 
 
 
 
 
 
579a758
 
 
4290815
d2691f9
579a758
 
8c19e54
 
 
af26267
579a758
358991e
e2c4695
358991e
4c64658
358991e
 
 
9118691
657d14d
9118691
 
5972846
579a758
 
 
 
 
 
 
 
3942c98
 
 
 
579a758
 
 
 
 
3942c98
 
 
579a758
8c19e54
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
from flask import Flask, request, jsonify, stream_with_context, send_file, send_from_directory, Response
import asyncio
import torch
import shutil
import os
import sys
from time import strftime
from src.utils.preprocess import CropAndExtract
from src.test_audio2coeff import Audio2Coeff
from src.facerender.animate import AnimateFromCoeff
from src.generate_batch import get_data
from src.generate_facerender_batch import get_facerender_data
# from src.utils.init_path import init_path
import tempfile
from openai import OpenAI
import elevenlabs
from elevenlabs import set_api_key, generate, play, clone, Voice, VoiceSettings
import uuid
import time
from PIL import Image
import moviepy.editor as mp
import requests
import json
import pickle
# from dotenv import load_dotenv
from concurrent.futures import ProcessPoolExecutor, as_completed, ThreadPoolExecutor
from stream_server import add_video,HLS_DIR, generate_m3u8
import math

# Load environment variables from .env file
# load_dotenv()

# Initialize ProcessPoolExecutor for parallel processing
executor = ThreadPoolExecutor(max_workers=2)
torch.cuda.empty_cache()

class AnimationConfig:
    def __init__(self, driven_audio_path, source_image_path, result_folder,pose_style,expression_scale,enhancer,still,preprocess,ref_pose_video_path, image_hardcoded):
        self.driven_audio = driven_audio_path
        self.source_image = source_image_path
        self.ref_eyeblink = None
        self.ref_pose = None
        self.checkpoint_dir = './checkpoints'
        self.result_dir = result_folder
        self.pose_style = pose_style
        self.batch_size = 2
        self.expression_scale = expression_scale
        self.input_yaw = None
        self.input_pitch = None
        self.input_roll = None
        self.enhancer = enhancer
        self.background_enhancer = None
        self.cpu = False
        self.face3dvis = False
        self.still = still  
        self.preprocess = preprocess
        self.verbose = False
        self.old_version = False
        self.net_recon = 'resnet50'
        self.init_path = None
        self.use_last_fc = False
        self.bfm_folder = './checkpoints/BFM_Fitting/'
        self.bfm_model = 'BFM_model_front.mat'
        self.focal = 1015.
        self.center = 112.
        self.camera_d = 10.
        self.z_near = 5.
        self.z_far = 15.
        self.device = 'cuda'
        self.image_hardcoded = image_hardcoded


app = Flask(__name__)

from flask_cors import CORS
CORS(app,origins=["*"])

TEMP_DIR = None
start_time = None
audio_chunks = []
preprocessed_data = None
args = None
unique_id  = None
m3u8_path = None
audio_duration = None
driven_audio_path = None

app.config['temp_response'] = None
app.config['generation_thread'] = None
app.config['text_prompt'] = None
app.config['final_video_path'] = None
app.config['final_video_duration'] = None

# Global paths
dir_path = os.path.dirname(os.path.realpath(__file__))
current_root_path = dir_path

path_of_lm_croper = os.path.join(current_root_path, 'checkpoints', 'shape_predictor_68_face_landmarks.dat')
path_of_net_recon_model = os.path.join(current_root_path, 'checkpoints', 'epoch_20.pth')
dir_of_BFM_fitting = os.path.join(current_root_path, 'checkpoints', 'BFM_Fitting')
wav2lip_checkpoint = os.path.join(current_root_path, 'checkpoints', 'wav2lip.pth')
audio2pose_checkpoint = os.path.join(current_root_path, 'checkpoints', 'auido2pose_00140-model.pth')
audio2pose_yaml_path = os.path.join(current_root_path, 'src', 'config', 'auido2pose.yaml')
audio2exp_checkpoint = os.path.join(current_root_path, 'checkpoints', 'auido2exp_00300-model.pth')
audio2exp_yaml_path = os.path.join(current_root_path, 'src', 'config', 'auido2exp.yaml')
free_view_checkpoint = os.path.join(current_root_path, 'checkpoints', 'facevid2vid_00189-model.pth.tar')


# Function for running the actual task (using preprocessed data)
def process_chunk(audio_chunk, preprocessed_data, args):
    print("Entered Process Chunk Function")
    global audio2pose_checkpoint, audio2pose_yaml_path, audio2exp_checkpoint, audio2exp_yaml_path, wav2lip_checkpoint
    global free_view_checkpoint
    if args.preprocess == 'full':
        mapping_checkpoint = os.path.join(current_root_path, 'checkpoints', 'mapping_00109-model.pth.tar')
        facerender_yaml_path = os.path.join(current_root_path, 'src', 'config', 'facerender_still.yaml')
    else:
        mapping_checkpoint = os.path.join(current_root_path, 'checkpoints', 'mapping_00229-model.pth.tar')
        facerender_yaml_path = os.path.join(current_root_path, 'src', 'config', 'facerender.yaml')

    first_coeff_path = preprocessed_data["first_coeff_path"]
    crop_pic_path = preprocessed_data["crop_pic_path"]
    crop_info_path = "/home/user/app/preprocess_data/crop_info.json"
    with open(crop_info_path , "rb") as f:
            crop_info = json.load(f)

    print(f"Loaded existing preprocessed data")
    print("first_coeff_path",first_coeff_path)
    print("crop_pic_path",crop_pic_path)
    print("crop_info",crop_info)
    torch.cuda.empty_cache()
    batch = get_data(first_coeff_path, audio_chunk, args.device, ref_eyeblink_coeff_path=None, still=args.still)
    audio_to_coeff = Audio2Coeff(audio2pose_checkpoint, audio2pose_yaml_path, 
                                audio2exp_checkpoint, audio2exp_yaml_path, 
                                wav2lip_checkpoint, args.device)
    coeff_path = audio_to_coeff.generate(batch, args.result_dir, args.pose_style, ref_pose_coeff_path=None)
    
    # Further processing with animate_from_coeff using the coeff_path
    animate_from_coeff = AnimateFromCoeff(free_view_checkpoint, mapping_checkpoint, 
                                            facerender_yaml_path, args.device)

    torch.cuda.empty_cache()
    data = get_facerender_data(coeff_path, crop_pic_path, first_coeff_path, audio_chunk, 
                                args.batch_size, args.input_yaw, args.input_pitch, args.input_roll, 
                                expression_scale=args.expression_scale, still_mode=args.still, preprocess=args.preprocess)
    torch.cuda.empty_cache()
    print("Will Enter Animation")
    result, base64_video, temp_file_path, _ = animate_from_coeff.generate(data, args.result_dir, args.source_image, crop_info, 
                                    enhancer=args.enhancer, background_enhancer=args.background_enhancer, preprocess=args.preprocess)

    # video_clip = mp.VideoFileClip(temp_file_path)
    # duration = video_clip.duration
    
    app.config['temp_response'] = base64_video
    app.config['final_video_path'] = temp_file_path
    # app.config['final_video_duration'] = duration
    torch.cuda.empty_cache()
    return base64_video, temp_file_path


def create_temp_dir():
    return tempfile.TemporaryDirectory()

def save_uploaded_file(file, filename,TEMP_DIR):
    print("Entered save_uploaded_file")
    unique_filename = str(uuid.uuid4()) + "_" + filename
    file_path = os.path.join(TEMP_DIR.name, unique_filename)
    file.save(file_path)
    return file_path


def custom_cleanup(temp_dir):
    # Iterate over the files and directories in TEMP_DIR
    for filename in os.listdir(temp_dir):
        file_path = os.path.join(temp_dir, filename)
        if os.path.isdir(file_path):
            shutil.rmtree(file_path)
        else:
            os.remove(file_path)
        print(f"Deleted: {file_path}")
    
    torch.cuda.empty_cache()
    import gc
    gc.collect()

# def get_audio_duration(audio_path):
#     audio_clip = mp.AudioFileClip(audio_path)
#     duration_in_seconds = audio_clip.duration
#     audio_clip.close()  # Don't forget to close the clip
#     return duration_in_seconds


def generate_audio(voice_cloning, voice_gender, text_prompt):
    print("generate_audio")
    if voice_cloning == 'no':
        if voice_gender == 'male':
            voice = 'echo'
            print('Entering Audio creation using elevenlabs')
            set_api_key('92e149985ea2732b4359c74346c3daee')

            audio = generate(text = text_prompt, voice = "Daniel", model = "eleven_multilingual_v2",stream=True, latency=4)
            with tempfile.NamedTemporaryFile(suffix=".mp3", prefix="text_to_speech_",dir=TEMP_DIR.name, delete=False) as temp_file:
                for chunk in audio:
                    temp_file.write(chunk)
                driven_audio_path = temp_file.name
                print('driven_audio_path',driven_audio_path)
                print('Audio file saved using elevenlabs')
                    
        else:
            voice = 'nova'

            print('Entering Audio creation using whisper')
            response = client.audio.speech.create(model="tts-1-hd",
                                            voice=voice,
                                            input = text_prompt)

            print('Audio created using whisper')
            with tempfile.NamedTemporaryFile(suffix=".wav", prefix="text_to_speech_",dir=TEMP_DIR.name, delete=False) as temp_file:
                driven_audio_path = temp_file.name
            
            response.write_to_file(driven_audio_path)
            print('Audio file saved using whisper')
    
    elif voice_cloning == 'yes':
        set_api_key('92e149985ea2732b4359c74346c3daee')
        # voice = clone(name = "User Cloned Voice",
        #             files = [user_voice_path] )
        voice = Voice(voice_id="CEii8R8RxmB0zhAiloZg",name="Marc",settings=VoiceSettings(
                        stability=0.71, similarity_boost=0.5, style=0.0, use_speaker_boost=True),)

        audio = generate(text = text_prompt, voice = voice, model = "eleven_multilingual_v2",stream=True, latency=4)
        with tempfile.NamedTemporaryFile(suffix=".mp3", prefix="cloned_audio_",dir=TEMP_DIR.name, delete=False) as temp_file:
            for chunk in audio:
                temp_file.write(chunk)
            driven_audio_path = temp_file.name
            print('driven_audio_path',driven_audio_path)
            # audio_duration = get_audio_duration(driven_audio_path)
            # print('Total Audio Duration in seconds',audio_duration)

    return driven_audio_path

def run_preprocessing(args):
    global path_of_lm_croper, path_of_net_recon_model, dir_of_BFM_fitting
    first_frame_dir = os.path.join(args.result_dir, 'first_frame_dir')
    os.makedirs(first_frame_dir, exist_ok=True)
    fixed_temp_dir = "/home/user/app/preprocess_data/"
    os.makedirs(fixed_temp_dir, exist_ok=True)
    preprocessed_data_path = os.path.join(fixed_temp_dir, "preprocessed_data.pkl")

    if os.path.exists(preprocessed_data_path) and args.image_hardcoded == "yes":
        print("Loading preprocessed data...")
        with open(preprocessed_data_path, "rb") as f:
            preprocessed_data = pickle.load(f)
        print("Loaded existing preprocessed data from:", preprocessed_data_path)

    return preprocessed_data
    
client = OpenAI(api_key="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")

def openai_chat_avatar(text_prompt):
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "system", "content": "Ensure answers are concise, human-like, and clear while maintaining quality. Use the fewest possible words, avoiding unnecessary articles, prepositions, and adjectives. Responses should be short but still address the question thoroughly without being verbose.Keep them to one sentence only"},
            {"role": "user", "content": f"Hi! I need help with something. {text_prompt}"},
        ],
        max_tokens = len(text_prompt) + 300 # Use the length of the input text
        # temperature=0.3,
        # stop=["Translate:", "Text:"]
    )
    return response
    
def split_audio(audio_path, TEMP_DIR, chunk_duration):
    audio_clip = mp.AudioFileClip(audio_path)
    total_duration = audio_clip.duration
    print("split_audio duration:",total_duration)
    number_of_chunks = math.ceil(total_duration / chunk_duration)
    print("Number of audio chunks:",number_of_chunks)
    audio_chunks = []
    for i in range(number_of_chunks):
        start_time = i * chunk_duration
        end_time = min(start_time + chunk_duration, total_duration)
        chunk = audio_clip.subclip(start_time, end_time)
        
        # Create a temporary file for the chunk
        with tempfile.NamedTemporaryFile(suffix=f"_chunk_{start_time}-{end_time}.wav", prefix="audio_chunk_", dir=TEMP_DIR.name, delete=False) as temp_file:
            chunk_path = temp_file.name
            chunk.write_audiofile(chunk_path)  # Specify codec if needed
            audio_chunks.append((start_time, chunk_path))
    
    audio_clip.close()  # Close the audio clip to release resources
    return audio_chunks, total_duration
    
# def extract_order_from_path(temp_file_path):
#     match = re.search(r'videostream(\d+)', temp_file_path)
#     return int(match.group(1)) if match else -1  # Return -1 if no match is found, handle appropriately.
# Generator function to yield chunk results as they are processed

def generate_chunks(audio_chunks, preprocessed_data, args, m3u8_path, audio_duration, start_time):
    global TEMP_DIR
    future_to_chunk = {executor.submit(process_chunk, chunk[1], preprocessed_data, args): chunk[0] for chunk in audio_chunks}
    processed_chunks = {chunk[0]: None for chunk in audio_chunks}
    print("processed_chunks:",processed_chunks)
    yielded_count = 1
    try:
        for chunk_idx, future in enumerate(as_completed(future_to_chunk)):
            idx = future_to_chunk[future]
            try:
                base64_video, temp_file_path = future.result()
                processed_chunks[idx] = temp_file_path
                for expected_start_time in sorted(processed_chunks.keys()):
                    if processed_chunks[expected_start_time] is not None:
                        add_video(processed_chunks[expected_start_time], m3u8_path, audio_duration)
                        end_time = time.time()
                        elapsed_time = end_time - start_time
                        event_data = json.dumps({
                            'start_time': expected_start_time,
                            'video_index': yielded_count,
                            'elapsed_time': elapsed_time
                        })
                        yield f"data: {event_data}\n\n"
                        processed_chunks[expected_start_time] = None
                        yielded_count += 1
                    else:
                        break
            except Exception as e:
                yield f"Task for chunk {idx} failed: {e}\n"
    finally:
        if TEMP_DIR:
            #close_m3u8(m3u8_path)
            custom_cleanup(TEMP_DIR.name)

def close_m3u8(m3u8_path: str):
    try:
        with open(m3u8_path, 'a') as m3u8_file:
            m3u8_file.write('#EXT-X-ENDLIST\n')
        print(f"Closed m3u8 file with end tag: {m3u8_path}")
    except Exception as e:
        print(f"Error closing m3u8 file: {e}")
      
@app.route("/run", methods=['POST'])
def parallel_processing():
    global start_time, driven_audio_path
    global audio_chunks, preprocessed_data, args, m3u8_path, audio_duration
    start_time = time.time()
    global TEMP_DIR
    TEMP_DIR = create_temp_dir()
    global unique_id
    unique_id = str(uuid.uuid4())
    print('request:',request.method)
    try:
        if request.method == 'POST':
            # source_image = request.files['source_image']
            image_path = '/home/user/app/images/marc_smile_enhanced.jpg'
            source_image = Image.open(image_path)
            text_prompt = request.form['text_prompt']
            
            print('Input text prompt: ',text_prompt)
            text_prompt = text_prompt.strip()
            if not text_prompt:
                return jsonify({'error': 'Input text prompt cannot be blank'}), 400
                
            voice_cloning = request.form.get('voice_cloning', 'yes')
            image_hardcoded = request.form.get('image_hardcoded', 'no')
            chat_model_used = request.form.get('chat_model_used', 'openai')
            target_language = request.form.get('target_language', 'original_text')
            print('target_language',target_language)
            pose_style = int(request.form.get('pose_style', 1))
            expression_scale = float(request.form.get('expression_scale', 1))
            enhancer = request.form.get('enhancer', None)
            voice_gender = request.form.get('voice_gender', 'male')
            still_str = request.form.get('still', 'False')
            still = still_str.lower() == 'false'
            print('still', still)
            preprocess = request.form.get('preprocess', 'crop')
            print('preprocess selected: ',preprocess)
            # ref_pose_video = request.files.get('ref_pose', None)

            response = openai_chat_avatar(text_prompt)
            text_prompt = response.choices[0].message.content.strip()
            app.config['text_prompt'] = text_prompt
            print('Final output text prompt using openai: ',text_prompt)
    
            source_image_path = save_uploaded_file(source_image, 'source_image.png',TEMP_DIR)
            print(source_image_path)
    
            driven_audio_path = generate_audio(voice_cloning, voice_gender, text_prompt)
        
            save_dir = tempfile.mkdtemp(dir=TEMP_DIR.name)
            result_folder = os.path.join(save_dir, "results")
            os.makedirs(result_folder, exist_ok=True)
    
            ref_pose_video_path = None
            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)
            preprocessed_data = run_preprocessing(args)
            # chunk_duration = 3
            # print(f"Splitting the audio into {chunk_duration}-second chunks...")
            # audio_chunks, audio_duration = split_audio(driven_audio_path, TEMP_DIR, chunk_duration=chunk_duration)
            # print(f"Audio has been split into {len(audio_chunks)} chunks: {audio_chunks}")
            start_time = 0
            audio_clip = mp.AudioFileClip(driven_audio_path)
            audio_duration = audio_clip.duration
            audio_chunks.append((start_time, driven_audio_path))

            os.makedirs('lives', exist_ok=True)
            print("Entering generate m3u8")
            m3u8_path = f'lives/{unique_id}.m3u8'
            #generate_m3u8(audio_duration, m3u8_path)
            
            return jsonify({'video_url': f'{unique_id}.m3u8'}), 200
                    
    except Exception as e:
        app.logger.error(f"An error occurred: {e}")
        return jsonify({'status': 'error', 'message': str(e)}), 500


@app.route("/stream", methods=["GET"])
def stream_results():
    global audio_chunks, preprocessed_data, args, m3u8_path, audio_duration, start_time
    print("audio_chunks",audio_chunks)
    print("preprocessed_data",preprocessed_data)
    print("args",args)
    try:
        return Response(stream_with_context(generate_chunks(audio_chunks, preprocessed_data, args, m3u8_path, audio_duration, start_time)),content_type='text/event-stream')
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 500

@app.route("/live_stream/<string:playlist>", methods=['GET'])
async def get_concatenated_playlist(playlist: str):
    """
    Endpoint to serve the concatenated HLS playlist.

    Returns:
        FileResponse: The concatenated playlist file.
    """
    if playlist.endswith('.ts'):
        playlist_path = os.path.join('hls_videos', playlist)
    else:
        playlist_path = os.path.join('lives', playlist)
    if not os.path.exists(playlist_path):
        return jsonify({'status': 'error', "msg":"Playlist not found"}), 404

    return send_file(playlist_path, mimetype='application/vnd.apple.mpegurl')

# @app.route("/live_stream/<string:filename>", methods=["GET"])
# def live_stream(filename):
#     return send_from_directory(directory="hls_videos", filename=filename)

@app.route("/health", methods=["GET"])
def health_status():
    response = {"online": "true"}
    return jsonify(response)

if __name__ == '__main__':
    app.run(debug=True)