-
Notifications
You must be signed in to change notification settings - Fork 0
/
MemMakerWdb.py
executable file
·2541 lines (2105 loc) · 101 KB
/
MemMakerWdb.py
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/home/jack/Desktop/StoryMaker/env/bin/python
from flask import Flask, render_template, request, redirect, url_for, send_from_directory, Response,flash
from flask import send_file, make_response,g
import os
import pygame
from gtts import gTTS
import cv2
import dlib
import numpy as np
from random import randint
from moviepy.editor import VideoFileClip, ImageClip, CompositeVideoClip
from moviepy.editor import concatenate_videoclips, AudioFileClip, TextClip
import moviepy.editor
import subprocess
import shutil
from pathlib import Path as change_ext
import logging
from io import BytesIO
import sqlite3
import random
import glob
import base64
import tempfile
import datetime
import imageio
import time
from werkzeug.utils import secure_filename
import shutil
from search import search
import clean_images
from time import sleep
from pydub import AudioSegment
from PIL import Image, ImageDraw, ImageFont
from logging.handlers import RotatingFileHandler
import moviepy.editor as mp
from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip
import uuid
app = Flask(__name__)
app.secret_key = os.urandom(24)
# Create a logger object
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# Create a formatter for the log messages
formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')
# Create a file handler to write log messages to a file
file_handler = RotatingFileHandler('Logs/app.log', maxBytes=10000, backupCount=1)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
# Add the file handler to the logger
logger.addHandler(file_handler)
# Now you can use the logger to log messages
TExt = "TEXT TEST 12345"
logger.debug('This is a debug message: %s', TExt)
TExt = "TEXT TEST 6789"
logger.debug('This is a debug message: %s', TExt)
TExt = "TEXT TEST abcd"
logger.debug('This is a debug message: %s', TExt)
# Set up logging for the Flask app
app.logger.addHandler(file_handler)
# Create a logger object
logging.basicConfig(level=logging.DEBUG)
app.config['UPLOAD_FOLDER'] = 'static/images/uploads'
app.config['RESULTS_FOLDER'] = 'static/videos/results'
app.config['THUMBNAILS_FOLDER'] = 'static/images/thumbnails'
app.config['CHECKPOINT_PATH'] = 'checkpoints/wav2lip_gan.pth'
app.config['AUDIO_PATH'] = 'sample_data/input_audio.wav'
app.config['video_PATH'] = 'sample_data/input_videio.mp4'
app.config['DATABASE'] = 'code.db' # SQLite database file
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico', mimetype='image/vnd.microsoft.icon')
# use the search function as a route
app.add_url_rule('/search', 'search', search)
def zip_lists(list1, list2):
return zip(list1, list2)
app.jinja_env.filters['zip'] = zip_lists
directory_path = 'temp' # Replace with the desired directory path
# Create the directory if it doesn't exist
os.makedirs(directory_path, exist_ok=True)
@app.route('/')
def index():
image_dir = 'static/images'
image_files = [f for f in os.listdir(image_dir) if f.endswith('.jpg')]
random_image_file = random.choice(image_files)
return render_template('index.html', random_image_file="images/"+random_image_file)
def generate_output():
# Specify the path to your Bash script
bash_script_path = '/home/jack/Desktop/content/MakeVideo'
# Execute the Bash script
subprocess.run(['bash', bash_script_path])
# Backup the result_videoxx.mp4 file
current_datetime = str(int(time.time()))
backup_filename = f"static/{current_datetime}.mp4"
shutil.copyfile("results/result_voice.mp4", backup_filename)
redirect('/final_lipsync')
return "Generated output"
@app.route('/create_avatar', methods=['GET', 'POST'])
def create_avatar():
if request.method == 'POST':
#check_point = os.path.join(app.config['CHECKPOINT_PATH'], 'checkpoints/wav2lip_gan.pth')
return Response(generate_output(), mimetype='text/plain')
else:
return render_template('create_avatar.html')
@app.route('/run_command', methods=['GET'])
def run_command():
# Specify the path to your Bash script
bash_script_path = 'MakeVideo'
# Execute the Bash script
subprocess.run(['bash', bash_script_path])
# Backup the result_videoxx.mp4 file
current_datetime = str(int(time.time()))
backup_filename = f"static/{current_datetime}.mp4"
shutil.copyfile("results/result_voice.mp4", backup_filename)
redirect('/final_lipsync')
@app.route('/result/<filename>')
def result(filename):
return render_template('result.html', filename=filename)
@app.route('/convert_mp3_to_wav', methods=['GET', 'POST'])
def convert_mp3_to_wav():
if request.method == 'POST':
mp3_file = request.files['mp3_file']
mp3_filename = mp3_file.filename
mp3_path = os.path.join(app.static_folder, 'audio_mp3', mp3_filename)
mp3_file.save(mp3_path)
wav_filename = 'input_audio.wav'
wav_path = os.path.join('sample_data', wav_filename)
sound = AudioSegment.from_mp3(mp3_path)
sound.export(wav_path, format='wav')
return 'MP3 file converted to WAV successfully'
else:
return render_template('convert_mp3_to_wav.html')
@app.route('/final_lipsync')
def final_lipsync():
VIDEO = 'result/result_voice.mp4'
return render_template('final_lipsync.html', video=VIDEO)
@app.route('/text_mp3', methods=['GET', 'POST'])
def text_mp3():
if request.method == 'POST':
# Get the text from the textarea
text = request.form['text']
text0 = text
# Remove whitespace from the text
text = text.replace(" ", "")
# Create a filename based on the first 25 characters of the text
filename = "static/audio_mp3/" + text[:25] + ".mp3"
textname = text[:25] + ".txt"
# Save the text to a text file
textname = textname.strip()
with open("static/text/"+textname, 'w') as f:
f.write(text0)
filename = filename.strip() # remove the newline character
# Create a gTTS object and save the audio file
tts = gTTS(text)
filename = filename.strip()
tts.save(filename)
shutil.copy(filename, 'static/TEMP.mp3')
# Play the mp3 file
pygame.mixer.init()
pygame.mixer.music.load(filename)
pygame.mixer.music.play()
# Wait for the audio to finish playing
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
# Stop pygame and exit the program
pygame.mixer.quit()
pygame.quit()
# Return the text and filename to the template
return render_template('text_mp3.html', text=text, filename=filename)
else:
# Render the home page template
return render_template('text_mp3.html')
@app.route('/mp3_upload', methods=['POST'])
def mp3_upload():
if 'file' not in request.files:
return 'No file uploaded', 400
file = request.files['file']
if file.filename == '':
return 'No file selected', 400
if file:
audio_file = 'static/TEMP.mp3'
file.save(audio_file)
return render_template('player.html', audio_file=audio_file)
@app.route('/generate_video', methods=['GET', 'POST'])
def generate_video():
if request.method == 'POST':
# Set the input and output filenames
eyes_filename = 'static/TEMP.png'
input_filename = 'static/TEMP2.mp4'
output_filename = 'static/TEMP2.mp4'
# Set the paths for the video and audio files
audio_file = 'static/TEMP.mp3'
output_filenames = 'static/TEMP.mp4'
# Extract eyes from the uploaded image and save as eyes_test.png
image_path = "static/TEMP.jpg"
shape_predictor_path = "/home/jack/hidden/shape_predictor_68_face_landmarks.dat"
extract_eyes(image_path, eyes_filename, shape_predictor_path)
# Load the image clip
image_clip = ImageClip(image_path, duration=30)
# Set the final clip properties
final_clip = image_clip.set_audio(None)
final_clip = final_clip.set_position('center')
# Write the final video
final_clip.write_videofile(output_filename, codec='libx264', fps=30, audio=False)
# Load the input video without audio
input_clip = VideoFileClip(input_filename, audio=False)
# Load the eye image clip
eyes_clip = ImageClip(eyes_filename)
# Create multiple looping clips
clips = []
for i in range(8):
loop_clip = mkloop(input_clip, eyes_clip)
clips.append(loop_clip)
# Concatenate all the clips
final_clips = concatenate_videoclips(clips)
# Write the final video
final_clips.write_videofile(output_filenames, codec='libx264', fps=input_clip.fps, audio=False)
# Load the video and audio files
video_clip = VideoFileClip(output_filenames)
audio_clip = AudioFileClip(audio_file)
# Set the duration of the final video to match the audio clip's duration
final_duration = audio_clip.duration+.5
# Set the video clip's duration to match the final duration
video_clip = video_clip.set_duration(final_duration)
# Set the audio of the video clip to be the same as the loaded audio clip
video_clip = video_clip.set_audio(audio_clip)
# Write the final video file
output_path = "static/final_video_blinking.mp4"
video_clip.write_videofile(output_path, codec='libx264', audio_codec='aac', fps=24)
shutil.copy(output_path, 'results/final_video_blinking.mp4')
return render_template('generate_video.html', video_path=output_path)
return render_template('generate_video.html')
# Function to extract eyes from an image using dlib
def extract_eyes(image_path, eyes_filename, shape_predictor_path):
# Load the image and shape predictor model
image = cv2.imread(image_path)
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(shape_predictor_path)
# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detect faces in the image
faces = detector(gray)
# Iterate over the detected faces and extract the eye regions
for face in faces:
landmarks = predictor(gray, face)
# Extract the coordinates of the left eye
left_eye_pts = [(landmarks.part(i).x, landmarks.part(i).y) for i in range(36, 42)]
# Extract the coordinates of the right eye
right_eye_pts = [(landmarks.part(i).x, landmarks.part(i).y) for i in range(42, 48)]
# Create a transparent image with an alpha channel
transparent_image = np.zeros((image.shape[0], image.shape[1], 4), dtype=np.uint8)
# Define the skin color (e.g., light brown or tan) in BGR format
#skin_color_bgr = (210, 180, 140)
skin_color_bgr = (80, 80, 40)
# Convert BGR to RGB
skin_color_rgb = (skin_color_bgr[2], skin_color_bgr[1], skin_color_bgr[0])
# Draw the eye regions on the transparent image with the skin color and alpha channel
cv2.fillPoly(transparent_image, [np.array(left_eye_pts)], skin_color_rgb + (200,))
cv2.fillPoly(transparent_image, [np.array(right_eye_pts)], skin_color_rgb + (200,))
blurred_image = cv2.GaussianBlur(transparent_image, (5, 5), 0)
# Save the transparent image with only the eyes as a PNG file
cv2.imwrite(eyes_filename, blurred_image)
# Function to create a looping clip with blinking eyes
def mkloop(input_clip, eyes_clip):
# Set the duration of the eye image clip
eyes_duration = 0.1 # seconds
# Set the position of the eye image clip
eyes_position = 'center'
# Set the start time of the eye image clip
blink_start_time = randint(2, 4)
# Create a CompositeVideoClip with the input video and the eye image clip
final_clip = CompositeVideoClip([input_clip, eyes_clip.set_duration(eyes_duration)
.set_position(eyes_position)
.set_start(blink_start_time)])
# Calculate the duration of the final clip
final_duration = blink_start_time + eyes_duration + randint(2, 4) # 5 to 8 seconds after the blink
# Set the duration of the final clip
final_clip = final_clip.set_duration(final_duration)
return final_clip
def apply_text(mp4_path, text, x, y):
video = moviepy.editor.VideoFileClip(mp4_path)
font = "/home/jack/fonts/OpenSansBold.ttf"
text_clip = moviepy.editor.TextClip(text, font=font, fontsize=24, color="white")
try:
x = int(x)
y = int(y)
except ValueError:
raise ValueError("Invalid position values. Please provide integer values for x and y.")
if not (0 <= x <= video.w):
raise ValueError("Invalid x position. Must be within the width of the video.")
if not (0 <= y <= video.h):
raise ValueError("Invalid y position. Must be within the height of the video.")
text_clip = text_clip.set_position((x, y))
# Check if duration is None and set a default value if necessary
video_duration = video.duration if video.duration is not None else 0
text_clip_duration = text_clip.duration if text_clip.duration is not None else 0
# Set the duration of the video and text clips
duration = max(video_duration, text_clip_duration)
video = video.set_duration(duration)
text_clip = text_clip.set_duration(duration)
# Create the composite video by overlaying the text clip onto the video clip
new_video = moviepy.editor.CompositeVideoClip([video, text_clip])
# Save the new video with the applied text
new_mp4_path = 'static/TTMP.mp4'
new_video.write_videofile(new_mp4_path, codec='libx264', audio_codec='aac', remove_temp=False)
return new_mp4_path
@app.route("/apply_text_to_video", methods=["POST", "GET"])
def apply_text_to_video():
if request.method == "POST":
file = request.files["mp4_file"]
if file.filename == '':
return redirect(request.url)
file.save('static/TTMP.mp4')
mp4_path = 'static/TTMP.mp4'
text = request.form["text"]
x = request.form["x"]
y = request.form["y"]
new_mp4_path = apply_text(mp4_path, text, x, y)
return render_template("apply_text_to_video.html", new_mp4_path=new_mp4_path)
else:
return render_template("apply_text_to_video.html")
# Get a list of existing subdirectories in the video resources directory
existing_subdirectories = [subdir for subdir in os.listdir("static/current_project") if os.path.isdir(os.path.join("static/current_project", subdir))]
@app.route('/uploads', methods=['GET', 'POST'])
def upload_files():
video_resources_dir="static/current_project"
if request.method == 'POST':
# Get the selected subdirectory from the form
selected_subdirectory = request.form.get('subdirectory')
# Check if the selected subdirectory exists
if selected_subdirectory in existing_subdirectories:
# Handle the uploaded file
file = request.files['file']
if file:
# Save the file to the selected subdirectory
file.save(os.path.join(video_resources_dir, selected_subdirectory, file.filename))
# Get the URL for the uploaded image
image_path = url_for('static', filename=os.path.join('current_project', selected_subdirectory, file.filename))
return render_template('upload_files.html', image_path=image_path)
else:
return 'No file selected.'
else:
return 'Invalid subdirectory selected.'
# Render the upload form with the list of existing subdirectories
return render_template('upload_files.html', subdirectories=existing_subdirectories)
@app.route('/get_files', methods=['POST'])
def get_files():
subdirectory = request.form.get('subdirectory')
file_options = []
if subdirectory and subdirectory in existing_subdirectories:
subdirectory_path = os.path.join("static/current_project", subdirectory)
files = os.listdir(subdirectory_path)
file_options = [
f'<option value="{file}">{file}</option>'
for file in files
if os.path.isfile(os.path.join(subdirectory_path, file))
]
return ''.join(file_options)
@app.route('/image_list')
def image_list():
image_directory = 'static/current_project/Narrators'
image_list = [
filename
for filename in os.listdir(image_directory)
if filename.endswith('.jpg')
]
return render_template('image_list.html', image_list=image_list)
@app.route('/upload', methods=['POST','GET'])
def upload():
filename = request.form['filename']
if filename:
src_path = 'static/current_project/Narrators/' + filename
dest_path = 'static/TEMP.jpg'
shutil.copyfile(src_path, dest_path)
return redirect('/')
else:
return 'No file selected.'
@app.route("/mkblend_video", methods=['GET', 'POST'])
def mkblend_video():
directory = request.files.get('directory')
#print("XXXXXXdirectory", directory)
#logger.debug('Selected directory: %s', directory)
# Save the uploaded directory to a temporary location
temp_dir = tempfile.mkdtemp()
#directory_path = os.path.join(temp_dir, directory.filename)
#directory.save(directory_path)
logger.debug('Directory saved to: %s', directory_path)
# Process the directory path as needed
#image_list = glob.glob(directory_path + "/*.jpg")
directory = "static/images/tensor_art/"
logger.debug('Selected directory: %s', directory)
print(directory)
if directory:
image_list = glob.glob(directory + "*.jpg")
logger.debug('IMAGE_LIST: %s', image_list)
# Shuffle and select a subset of images
#random.shuffle(image_list)
image_list = sorted(image_list)
logger.debug('Selected image filenames: %s', image_list)
# Print the number of selected images
print(len(image_list))
logger.debug('Number of files: %s', len(image_list))
def changeImageSize(maxWidth, maxHeight, image):
widthRatio = maxWidth / image.size[0]
heightRatio = maxHeight / image.size[1]
newWidth = int(widthRatio * image.size[0])
newHeight = int(heightRatio * image.size[1])
newImage = image.resize((newWidth, newHeight))
return newImage
# Get the size of the first image
if image_list:
imagesize = Image.open(image_list[0]).size
for i in range(len(image_list) - 1):
imag1 = image_list[i]
imag2 = image_list[i + 1]
image1 = Image.open(imag1)
image2 = Image.open(imag2)
image3 = changeImageSize(imagesize[0], imagesize[1], image1)
image4 = changeImageSize(imagesize[0], imagesize[1], image2)
image5 = image3.convert("RGBA")
image6 = image4.convert("RGBA")
text = "animate/"
for ic in range(0, 100):
inc = ic * 0.01
#inc = ic * 0.08
sleep(0.1)
# Gradually increase opacity
alphaBlended = Image.blend(image5, image6, alpha=inc)
alphaBlended = alphaBlended.convert("RGB")
current_time = datetime.datetime.now()
filename = current_time.strftime('%Y%m%d_%H%M%S%f')[:-3] + '.jpg'
alphaBlended.save(f'{text}{filename}')
if ic % 25 == 0:
print(i, ":", ic, end=" . ")
if ic % 100 == 0:
logger.debug(f'Image Number: %d', inc,ic)
from moviepy.video.io.ImageSequenceClip import ImageSequenceClip
# Get the list of files sorted by creation time
imagelist = sorted(glob.glob('animate/*.jpg'), key=os.path.getmtime)
# Create a clip from the images
clip = ImageSequenceClip(imagelist, fps=30)
# Write the clip to a video file using ffmpeg
current_time = datetime.datetime.now()
filename = "static/animate/TEMP3a.mp4"
clip.write_videofile(filename, fps=24, codec='libx265', preset='medium')
store = "static/videos/" + current_time.strftime('%Y%m%d_%H%M%S%f')[:-3] + 'jul27.mp4'
output_file = "static/animate/TEMP5.mp4" # Replace with the desired path for the converted video file
webm_file = "static/animate/TEMP5.webm" # Replace with the desired path for the converted video file
ffmpeg_cmd = [
'ffmpeg', '-i', filename, '-c:v', 'libx264', '-crf', '23', '-preset', 'medium', '-c:a', 'aac',
'-b:a', '128k', '-movflags', '+faststart', '-y', output_file
]
subprocess.run(ffmpeg_cmd)
ffmpeg_cmd2 = [
'ffmpeg', '-i', filename, '-c:v', 'libx264', '-crf', '23', '-preset', 'medium', '-c:a', 'aac',
'-b:a', '128k', '-movflags', '+faststart', '-y', webm_file
]
subprocess.run(ffmpeg_cmd2)
shutil.copy(filename, store)
return render_template('mkblend_video.html', video=filename)
return render_template('choose_directory.html')
def changeImageSize(maxWidth, maxHeight, image):
widthRatio = maxWidth / image.size[0]
heightRatio = maxHeight / image.size[1]
newWidth = int(widthRatio * image.size[0])
newHeight = int(heightRatio * image.size[1])
newImage = image.resize((newWidth, newHeight))
return newImage
directories = [
"static/images/512x1536-woman",
"static/images/abstract_beauty",
"static/images/beautiful_girl",
"static/images/Beautiful_Warrior"
]
@app.route("/mkblend_videos", methods=['POST'])
def mkblend_videos():
# Get the selected directory from the form data
selected_directory = request.form.get('selected_directory')
logger.debug('Selected Directory: %s', selected_directory)
# Check if the selected directory is valid
if selected_directory and selected_directory in directories:
# Use glob to get the list of files within the selected directory
filelist = glob.glob(os.path.join(selected_directory, '*.jpg'))
logger.debug('Selected directory: %s', selected_directory)
image_list = filelist
# Shuffle and select a subset of images
image_list = filelist
random.shuffle(image_list)
image_list = random.sample(image_list, 29)
# Get the size of the first image
imagesize = Image.open(image_list[0]).size
# Print the number of selected images
print("IMAGE_LIST_length:",len(image_list))
for i in range(len(image_list) - 1):
imag1 = image_list[i]
imag2 = image_list[i + 1]
image1 = Image.open(imag1)
image2 = Image.open(imag2)
image3 = changeImageSize(imagesize[0], imagesize[1], image1)
image4 = changeImageSize(imagesize[0], imagesize[1], image2)
image5 = image3.convert("RGBA")
image6 = image4.convert("RGBA")
text = "animate/"
#for ic in range(0,125):
for ic in range(0,100):
inc = ic*.01
sleep(.1)
#gradually increase opacity
alphaBlended = Image.blend(image5, image6, alpha=inc)
alphaBlended = alphaBlended.convert("RGB")
current_datetime = str(int(time.time()))
filename = current_datetime[:-3] + '.jpg'
alphaBlended.save(f'{text}{filename}')
if ic %25 ==0:print(ic,":",inc, end = " . ")
from moviepy.video.io.ImageSequenceClip import ImageSequenceClip
# Get the list of files sorted by creation time
imagelist2 = sorted(glob.glob('animate/*.jpg'), key=os.path.getmtime)
# Create a clip from the images
clip = ImageSequenceClip(imagelist2, fps=30)
# Write the clip to a video file using ffmpeg
current_datetime = str(int(time.time()))
filename = "static/animate/TEMP3a.mp4"
clip.write_videofile(filename, fps=24, codec='libx265', preset='medium')
store = "static/videos/"+current_datetime[:-3] + 'july27.mp4'
output_file = "static/animate/TEMP5.mp4" # Replace with the desired path for the converted video file
#webm_file = "static/animate/TEMP5.webm" # Replace with the desired path for the converted video file
ffmpeg_cmd = ['ffmpeg', '-i', filename, '-c:v', 'libx264', '-crf', '23', '-preset', 'medium', '-c:a', 'aac', '-b:a', '128k', '-movflags', '+faststart','-y', output_file]
subprocess.run(ffmpeg_cmd)
#ffmpeg_cmd2 = ['ffmpeg', '-i', filename, '-c:v', 'libx264', '-crf', '23', '-preset', 'medium', '-c:a', 'aac', #'-b:a', '128k', '-movflags', '+faststart', '-y', webm_file]
#subprocess.run(ffmpeg_cmd2)
shutil.copy(filename, store)
return render_template('mkblend_videos.html', video=filename)
@app.route('/generate_vid', methods=['GET', 'POST'])
def generate_vid():
current_datetime = str(int(time.time()))
str_current_datetime = str(current_datetime)
logger.debug('Generating video', str_current_datetime)
if request.method == 'POST':
# Load the audio file
audio_file = request.files['audio']
filename = os.path.join(app.config['AUDIO_PATH'])#, 'input_audio.mp3')
logger.info(f'Audio path: {filename}')
audio_file.save(filename)
print("FILENAME:",filename)
# Get the duration of the audio using ffprobe
command = f"ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 {filename}"
duration = subprocess.check_output(command.split())
duration = float(duration.strip().decode())
logger.info(f'Duration: {duration}')
# Load the image file
image_file = request.files['image']
image_path = os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(image_file.filename))
logger.info(f'Image path: {image_path}')
image_file.save(image_path)
# Create the video
#video_path = os.path.join(app.config['VIDEO_PATH'])#, 'sample_data/input_video.mp4')
video_path = 'sample_data/input_video.mp4'
logger.info(f'Video path: {video_path}')
ffmpeg_command = f"ffmpeg -loop 1 -i {image_path} -c:v libx264 -t {duration+ 0.5} -pix_fmt yuv420p -y {video_path}"
subprocess.run(ffmpeg_command, shell=True)
return f'Video created: {video_path}'
return render_template('generate_vid.html')
# Define route to display upload form
@app.route('/upload_file', methods=['POST', 'GET'])
def upload_file():
if request.method == 'POST':
# Check if file was uploaded
if 'file' not in request.files:
app.logger.error('No file was uploaded')
flash('Error: No file was uploaded')
return redirect(request.url)
app.logger.error('request.files[\'file\']')
file = request.files['file']
# Check if file was selected
if file.filename == '':
app.logger.error('No file was selected')
flash('Error: No file was selected')
return redirect(request.url)
# Define allowed file extensions
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
# Define function to check file extension
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
# Check if file is allowed
if not allowed_file(file.filename):
#app.logger.error(f"File '{file.filename}' is not allowed")
app.logger.error("File '" + file.filename + "' is not allowed")
flash("Error: File '" + file.filename + "'close is not allowed")
return redirect(request.url)
# Save the file
try:
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
app.logger.info(f'File {filename} saved')
app.logger.info('FILENAME:',os.path.join(app.config['UPLOAD_FOLDER'], filename))
except Exception as e:
app.logger.error(f'Error saving file: {e}')
flash('Error: Unable to save file')
return redirect(request.url)
# Redirect to the result page
app.logger.info(f'File-Result {filename} SAVED')
return redirect(url_for('result', filename=filename))
# Return the upload form for GET requests
return render_template('upload_file.html')
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
@app.route('/make_text', methods=['GET', 'POST'])
def make_text():
DIR = 'static/text/'
if request.method == 'POST':
# Get the text entered in the textarea
text = request.form.get('text')
# Generate a filename using the first 25 letters of the text
text = text.replace(' ', '_')
filename = text[:25]
# Save the text to a file
with open(f'{DIR}{filename}.txt', 'w') as file:
file.write(text)
return 'Text saved successfully!'
else:
return render_template('make_text.html')
directories = ['static/images','static/images/squares', 'static/final_videos', 'static/Dreamlike_art', 'static/squares', 'static/images/uploads', 'static/Final_Fantasy', 'static/final_images', 'static/thumbnails']
# Route for the home page
@app.route('/')
def home():
return render_template('choose_dir.html', directories=directories)
# Route for choosing a directory
@app.route('/choose_dir', methods=['GET', 'POST'])
def choose_dir():
if request.method == 'POST':
selected_directory = request.form.get('directory', directories)
TExt = "TEXT TEST"
logger.error('No file was selected: %s', TExt)
logger.debug('Debug was selected: %s', TExt)
if selected_directory is None:
# Handle the case where no directory is selected
logger.error('No directory selected')
return 'No directory selected!'
# Rest of the code...
# Use the selected_directory variable in your logic to generate the video
# Make sure to update the paths according to the selected directory
logger.debug('Selected directory: %s', selected_directory)
# Get the list of image files in the selected directory
image_filenames = random.sample(glob.glob(selected_directory + '/*.jpg'), 10)
logger.debug('Selected image filenames: %s', image_filenames)
image_clips = []
for filename in image_filenames:
# Open the image file and resize it to 512x768
logger.debug('Processing image: %s', filename)
image = Image.open(filename)
#image = image.resize((512, 768), Image.ANTIALIAS)
# Convert the PIL Image object to a NumPy array
image_array = np.array(image)
# Create an ImageClip object from the resized image and set its duration to 1 second
image_clip = ImageClip(image_array).set_duration(1)
# Append the image clip to the list
image_clips.append(image_clip)
logger.debug('Number of image clips: %d', len(image_clips))
# Concatenate all the image clips into a single video clip
video_clip = concatenate_videoclips(image_clips, method='compose')
timestr = time.strftime("%Y%m%d-%H%M%S")
# Set the fps value for the video clip
video_clip.fps = 24
# Write the video clip to a file
video_file = f'static/videos/random_images_{timestr}_video.mp4'
output_p = 'static/videos/random_images_video.mp4'
logger.debug('Output video file path: %s', video_file)
logger.debug('Final video file path: %s', output_p)
video_clip.write_videofile(video_file, fps=24)
try:
shutil.copy(video_file, output_p)
except Exception as e:
logger.error('Error occurred while copying file: %s', str(e))
return f"Error occurred while copying file: {str(e)}"
# Return the rendered template with the list of directories and output path
return render_template('choose_dir.html', directories=directories, output_path=output_p)
# If the request method is GET, render the form template with the list of directories
output_p = 'static/videos/random_images_video.mp4'
return render_template('choose_dir.html', directories=directories, output_path=output_p)
@app.route('/convert', methods=['GET', 'POST'])
def convert():
if request.method == 'POST':
try:
audio_file = request.files['audio_file']
audio_file_path = f'static/audio_mp3/{audio_file.filename}' # Path for audio file
audio_file.save(audio_file_path) # Save the audio file to the specified location
formatted_text_file = request.files['formatted_text_file']
formatted_text_file_path = f'static/formatted_text/{formatted_text_file.filename}' # Path for formatted text file
formatted_text_file.save(formatted_text_file_path) # Save the formatted text file to the specified location
output_filename = datetime.datetime.now().strftime('%Y-%m-%d') + '.mp4'
output_path = 'static/videos/' + output_filename
# Define the ffmpeg command
# Create the blank video
#ffmpeg -f lavfi -i color='#470000'@0x0:s=1280x720:rate=60,format=rgba -t 280 -y blank.mp4
command = [
'ffmpeg',
'-i', audio_file_path,
'-f', 'lavfi',
'-i', f"color='#470000'@0.0:s=1280x720:rate=60,format=rgba",
'-vf', f"drawtext=textfile='{os.path.abspath(formatted_text_file_path)}':y=(h-220)-12*t:x=580:fontcolor=orange:fontfile=/home/jack/Arimo-Regular.ttf:fontsize=26",
'-t', '280',
'-y', output_path
]
logger.debug(f"Command: {' '.join(command)}")
subprocess.run([str(arg) for arg in command], check=True)
video = f'{output_filename}'
return render_template('convert.html', video=output_path)
except Exception as e:
logger.exception("An error occurred during video conversion:")
return render_template('error.html', message="An error occurred during video conversion.")
else:
return render_template('convert_form.html')
@app.route('/convert512', methods=['GET', 'POST'])
def convert512():
if request.method == 'POST':
try:
audio_file = request.files['audio_file']
audio_file_path = f'static/audio_mp3/{audio_file.filename}' # Path for audio file
audio_file.save(audio_file_path) # Save the audio file to the specified location
# Get the duration of the audio using ffprobe
command = f"ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 {audio_file_path}"
duration = subprocess.check_output(command.split())
duration = float(duration.strip().decode())
length = int(duration + 5)
logger.info(f'Duration-512: {length}')
formatted_text_file = request.files['formatted_text_file']
formatted_text_file_path = f'static/formatted_text/{formatted_text_file.filename}' # Path for formatted text file
formatted_text_file.save(formatted_text_file_path) # Save the formatted text file to the specified location
output_filename = datetime.datetime.now().strftime('%Y-%m-%d') + '.mp4'
output_path = 'static/videos/' + output_filename
# Define the ffmpeg command
# Create the blank video
#ffmpeg -f lavfi -i color='#470000'@0x0:s=1280x720:rate=60,format=rgba -t 280 -y blank.mp4
#y=(h-120)-12*t:x=24:
command = [
'ffmpeg',
'-i', audio_file_path,
'-f', 'lavfi',
'-i', f"color='#470000'@0.0:s=512x1024:rate=60,format=rgba",
'-vf', f"drawtext=textfile='{os.path.abspath(formatted_text_file_path)}':y=(h-120)-10*t:x=24:fontcolor=orange:fontfile=/home/jack/Arimo-Regular.ttf:fontsize=20",
'-t', f'{length}',
'-y', output_path
]
logger.debug(f"Command: {' '.join(command)}")
subprocess.run([str(arg) for arg in command], check=True)
video = f'{output_filename}'
return render_template('convert512.html', video=output_path)
except Exception as e:
logger.exception("An error occurred during video conversion:")
return render_template('error.html', message="An error occurred during video conversion.")
else:
return render_template('convert_form512.html')
@app.route('/mk_text', methods=['GET', 'POST'])
def mk_text():
DIR = "static/text/"
if request.method == 'POST':
text = request.form.get('text')
tex = text.replace(" ", "_")
filename = tex[:25]
with open(f'{DIR}{filename}.txt', 'w') as file:
file.write(text)
return render_template('mk_text.html', text=text, filename=f'{filename}.txt')
else:
return render_template('mk_text.html')
@app.route('/list_files')
def list_files():
static_text_dir = 'static/text/'
files = os.listdir(static_text_dir)
files = [file for file in files if os.path.isfile(os.path.join(static_text_dir, file))]
return str(files)
@app.route('/format_file', methods=['POST', 'GET'])
def format_file():
static_text_dir = 'static/text/'
static_format_dir = 'static/formatted_text/'
if request.method == 'POST':
filename = request.form.get('filename')
file_path = os.path.join(static_text_dir, filename)
if not os.path.isfile(file_path):
return render_template('error.html', message=f'File "{filename}" does not exist')
with open(file_path, 'r') as file:
content = file.read()
words = content.split()
formatted_content = '\n'.join([' '.join(words[i:i+5]) for i in range(0, len(words), 5)])
modified_filename = filename.replace('.txt', '') + 'FORMATTED.txt'
modified_file_path = os.path.join(static_format_dir, modified_filename)
with open(modified_file_path, 'w') as modified_file:
modified_file.write(formatted_content)
logger.debug('This is Formated Content: %s', formatted_content)
logger.debug('This is Formated file: %s', modified_file_path)
return render_template('success.html', original_file=filename, modified_file=modified_filename)
file_options = []
for file_name in os.listdir(static_text_dir):
if file_name.endswith('.txt'):
file_options.append(file_name)
return render_template('form.html', file_options=file_options)
@app.route('/view_text')
def view_text():
text_files_dir = 'static/text/'
text_files = []
for filename in os.listdir(text_files_dir):
if filename.endswith('.txt'):
text_files.append(filename)
return render_template('select_file.html', text_files=text_files)
@app.route('/view_text/<filename>')
def display_text(filename):
text_file_path = f'static/text/{filename}'
try:
with open(text_file_path, 'r') as file:
file_contents = file.read()
return render_template('view_text.html', file_contents=file_contents, filename=filename)
except FileNotFoundError:
return f'Text file {filename} not found.'
@app.route('/edit_file', methods=['GET', 'POST'])
def edit_file():
if request.method == 'POST':
filename = request.form.get('filename')
text = request.form.get('text')
with open(f'static/text/{filename}', 'w') as file:
file.write(text)
text_files_dir = 'static/text/'
text_files = []
for filename in os.listdir(text_files_dir):
if filename.endswith('.txt'):
text_files.append(filename)
return render_template('edit_file.html', text_files=text_files)
@app.route('/edit_formatted', methods=['GET', 'POST'])
def edit_formatted():
if request.method == 'POST':
filename = request.form.get('filename')
text = request.form.get('text')
with open(f'static/formatted_text/{filename}', 'w') as file:
file.write(text)
text_files_dir = 'static/formatted_text/'
text_files = []
for filename in os.listdir(text_files_dir):
if filename.endswith('.txt'):
text_files.append(filename)
return render_template('edit_formatted.html', text_files=text_files)
@app.route('/get_formatted_content/<filename>')
def get_formatted_content(filename):
file_path = os.path.join('static/formatted_text', filename)
with open(file_path, 'r') as file:
content = file.read()