Created
April 20, 2025 08:14
-
-
Save me-suzy/053e5f1714f2634e137667d2ca680dae to your computer and use it in GitHub Desktop.
Pasul 3. Combina si compreseaza toate video-urile si imaginile intr-un singur video - final - fara melodii.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import os | |
import sys | |
from moviepy.editor import VideoFileClip, ImageClip, AudioFileClip, concatenate_videoclips, concatenate_audioclips | |
import re | |
import gc | |
import tempfile | |
import shutil | |
def get_video_info(clip): | |
return { | |
'durată': f"{clip.duration:.2f} secunde", | |
'dimensiune': f"{os.path.getsize(clip.filename)/(1024*1024):.1f} MB", | |
'rezoluție': f"{clip.size[0]}x{clip.size[1]}", | |
'fps': f"{clip.fps}" | |
} | |
def process_video_compression(video_clip, output_file, target_bitrate, original_size): | |
try: | |
video_clip.write_videofile( | |
output_file, | |
fps=24, | |
codec='libx264', | |
audio_codec='aac', | |
temp_audiofile='temp-audio.m4a', | |
remove_temp=True, | |
bitrate=f"{target_bitrate/1000:.0f}k", | |
preset="medium", | |
threads=4, | |
audio_bitrate="128k", | |
ffmpeg_params=[ | |
"-crf", "28", | |
"-movflags", "+faststart", | |
"-profile:v", "high", | |
"-level", "4.1", | |
"-pix_fmt", "yuv420p", | |
"-tune", "film", | |
"-maxrate", f"{target_bitrate*1.5/1000:.0f}k", | |
"-bufsize", f"{target_bitrate*2/1000:.0f}k", | |
"-max_muxing_queue_size", "9999" | |
] | |
) | |
final_size = os.path.getsize(output_file) | |
compression_ratio = (1 - final_size/original_size) * 100 | |
print("\n=== Rezultate Compresie ===") | |
print(f"Dimensiune originală: {original_size/(1024*1024):.1f} MB") | |
print(f"Dimensiune după compresie: {final_size/(1024*1024):.1f} MB") | |
print(f"Rata de compresie: {compression_ratio:.1f}%") | |
return True | |
except Exception as e: | |
print(f"\n❌ Eroare la compresie: {str(e)}") | |
return False | |
finally: | |
if os.path.exists('temp-audio.m4a'): | |
os.remove('temp-audio.m4a') | |
gc.collect() | |
def process_file_individually(file_path, output_dir, index, width=720): | |
"""Procesează fiecare fișier separat pentru a economisi memorie""" | |
temp_output = os.path.join(output_dir, f"temp_processed_{index}.mp4") | |
try: | |
if file_path.lower().endswith(('.mp4')): | |
clip = VideoFileClip(file_path, target_resolution=(720, width)) | |
else: | |
img = ImageClip(file_path) | |
clip = img.resize(width=width).set_duration(5).set_fps(24) | |
clip.write_videofile( | |
temp_output, | |
fps=24, | |
codec='libx264', | |
audio_codec='aac', | |
preset="medium", | |
ffmpeg_params=[ | |
"-crf", "28", | |
"-max_muxing_queue_size", "9999" | |
] | |
) | |
clip.close() | |
gc.collect() | |
return temp_output | |
except Exception as e: | |
print(f"\n❌ Eroare la procesarea fișierului: {str(e)}") | |
return None | |
def combine_and_compress_media(input_directory, output_file, audio_files=None, image_duration=5): | |
try: | |
media_files = [ | |
f for f in os.listdir(input_directory) | |
if f.lower().endswith(('.mp4', '.jpg', '.jpeg', '.png')) | |
] | |
if not media_files: | |
print("❌ Nu s-au găsit fișiere media în director!") | |
return False | |
media_files.sort(key=lambda s: [ | |
int(t) if t.isdigit() else t.lower() | |
for t in re.split('([0-9]+)', s) | |
]) | |
print("\nFișiere găsite:", ", ".join(media_files)) | |
temp_dir = tempfile.mkdtemp() | |
processed_files = [] | |
total_size = 0 | |
for idx, file in enumerate(media_files): | |
print(f"\nProcesez: {file}") | |
full_path = os.path.join(input_directory, file) | |
total_size += os.path.getsize(full_path) | |
temp_file = process_file_individually(full_path, temp_dir, idx, width=720) | |
if temp_file: | |
processed_files.append(temp_file) | |
else: | |
print(f"Eroare la procesarea {file}, continui cu următorul...") | |
if not processed_files: | |
print("Nu s-au putut procesa fișierele media!") | |
return False | |
concat_file = os.path.join(temp_dir, "concat_list.txt") | |
with open(concat_file, 'w') as f: | |
for file in processed_files: | |
f.write(f"file '{file}'\n") | |
temp_combined = os.path.join(temp_dir, "combined_video.mp4") | |
os.system(f'ffmpeg -f concat -safe 0 -i "{concat_file}" -c copy "{temp_combined}"') | |
# Verificăm dacă fișierul combinat a fost creat | |
if not os.path.exists(temp_combined): | |
print("❌ Nu s-a putut crea fișierul combinat!") | |
return False | |
# Procesăm audio dacă există fișiere audio valide | |
has_audio = False | |
if audio_files: | |
valid_audio = [a for a in audio_files if a and os.path.exists(a)] | |
if valid_audio: | |
has_audio = True | |
video_with_audio = VideoFileClip(temp_combined) | |
audio_clips = [] | |
current_duration = 0 | |
while current_duration < video_with_audio.duration: | |
for audio_file in valid_audio: | |
if current_duration >= video_with_audio.duration: | |
break | |
audio = AudioFileClip(audio_file) | |
remaining = video_with_audio.duration - current_duration | |
if audio.duration > remaining: | |
audio = audio.subclip(0, remaining) | |
audio_clips.append(audio) | |
current_duration += audio.duration | |
if audio_clips: | |
final_audio = concatenate_audioclips(audio_clips) | |
video_with_audio = video_with_audio.set_audio(final_audio) | |
success = process_video_compression(video_with_audio, output_file, 2000*1000, total_size) | |
video_with_audio.close() | |
return success | |
video_with_audio.close() | |
# Dacă nu există audio sau fișiere audio valide, comprimăm și salvăm direct videoclipul combinat | |
if not has_audio: | |
video_without_audio = VideoFileClip(temp_combined) | |
success = process_video_compression(video_without_audio, output_file, 2000*1000, total_size) | |
video_without_audio.close() | |
return success | |
return True | |
except Exception as e: | |
print(f"❌ Eroare: {str(e)}") | |
return False | |
finally: | |
try: | |
shutil.rmtree(temp_dir, ignore_errors=True) | |
except: | |
pass | |
gc.collect() | |
def main(): | |
INPUT_PATH = r"g:\Dubai Nou\METRO DUBAI" | |
AUDIO_FILES = [ | |
r"", | |
r"" | |
] | |
# Elimină fișierele audio goale | |
AUDIO_FILES = [af for af in AUDIO_FILES if af] | |
output_file = os.path.join(INPUT_PATH, "FISIER-SALVAT.mp4") | |
success = combine_and_compress_media(INPUT_PATH, output_file, AUDIO_FILES, image_duration=5) | |
if success: | |
print("\n✅ Procesul s-a finalizat cu succes!") | |
else: | |
print("\n❌ Procesul a eșuat!") | |
if __name__ == "__main__": | |
gc.collect() | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment