File size: 7,058 Bytes
29f86be
 
f3cdbdc
bbbee26
 
4596138
 
29f86be
 
5929ef8
4596138
29f86be
 
 
 
4596138
 
 
 
 
 
3ccfbcb
4596138
 
29f86be
 
cfc3ad2
29f86be
 
cfc3ad2
e0e4152
cfc3ad2
29f86be
 
 
 
 
9d18995
29f86be
3ccfbcb
 
29f86be
 
 
 
 
 
 
9d18995
7ab19f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29f86be
cfc3ad2
4596138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ccfbcb
4596138
 
 
 
 
 
 
3ccfbcb
 
 
 
4596138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ccfbcb
 
4596138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c7c82a
 
4596138
 
 
 
 
 
 
 
 
 
3ccfbcb
4596138
 
 
 
3ccfbcb
4596138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfc3ad2
bbbee26
 
9d18995
cfc3ad2
 
 
 
 
 
 
 
 
 
6431157
 
cfc3ad2
9d18995
 
bbbee26
 
 
9d18995
f3cdbdc
 
930c751
7ab19f6
930c751
 
 
 
 
 
5929ef8
 
 
7ab19f6
 
5929ef8
a2c5114
4596138
 
 
f3cdbdc
 
 
 
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
import subprocess
import os
from typing import List, Optional, Union
from PIL import Image
import numpy as np
from dataclasses import dataclass
import re

from modules.logger_util import get_logger
from modules.constants import SOUND_FILE_EXT, VIDEO_FILE_EXT, IMAGE_FILE_EXT
from modules.paths import TEMP_DIR, TEMP_OUT_DIR

logger = get_logger()


@dataclass
class VideoInfo:
    num_frames: Optional[int] = None
    frame_rate: Optional[int] = None
    duration: Optional[float] = None
    has_sound: Optional[bool] = None
    codec: Optional[str] = None


def extract_frames(
    vid_input: str,
    output_temp_dir: str = TEMP_DIR,
    start_number: int = 0
):
    """
    Extract frames as jpg files and save them into output_temp_dir. This needs FFmpeg installed.
    """
    os.makedirs(output_temp_dir, exist_ok=True)
    output_path = os.path.join(output_temp_dir, "%05d.jpg")

    command = [
        'ffmpeg',
        '-y',  # Enable overwriting
        '-i', vid_input,
        '-qscale:v', '2',
        '-vf', f'scale=iw:ih',
        '-start_number', str(start_number),
        f'{output_path}'
    ]

    try:
        subprocess.run(command, check=True)
    except subprocess.CalledProcessError as e:
        logger.exception("Error occurred while extracting frames from the video")
        raise RuntimeError(f"An error occurred: {str(e)}")

    return get_frames_from_dir(output_temp_dir)


def extract_sound(
    vid_input: str,
    output_temp_dir: str = TEMP_DIR,
):
    """
    Extract audio from a video file and save it as a separate sound file. This needs FFmpeg installed.
    """
    os.makedirs(output_temp_dir, exist_ok=True)
    output_path = os.path.join(output_temp_dir, "sound.mp3")

    command = [
        'ffmpeg',
        '-y',  # Enable overwriting
        '-i', vid_input,
        '-vn',
        output_path
    ]

    try:
        subprocess.run(command, check=True)
    except subprocess.CalledProcessError as e:
        logger.exception("Error occurred while extracting sound from the video")

    return output_path


def get_video_info(vid_input: str) -> VideoInfo:
    """
    Extract video information using ffmpeg.
    """
    command = [
        'ffmpeg',
        '-i', vid_input,
        '-map', '0:v:0',
        '-c', 'copy',
        '-f', 'null',
        '-'
    ]

    try:
        result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                encoding='utf-8', errors='replace', check=True)
        output = result.stderr

        num_frames = None
        frame_rate = None
        duration = None
        has_sound = False
        codec = None

        for line in output.splitlines():
            if 'Stream #0:0' in line and 'Video:' in line:
                fps_match = re.search(r'(\d+(?:\.\d+)?) fps', line)
                if fps_match:
                    frame_rate = float(fps_match.group(1))

                codec_match = re.search(r'Video: (\w+)', line)
                if codec_match:
                    codec = codec_match.group(1)

            elif 'Duration:' in line:
                duration_match = re.search(r'Duration: (\d{2}):(\d{2}):(\d{2}\.\d{2})', line)
                if duration_match:
                    h, m, s = map(float, duration_match.groups())
                    duration = h * 3600 + m * 60 + s

            elif 'Stream' in line and 'Audio:' in line:
                has_sound = True

        if frame_rate and duration:
            num_frames = int(frame_rate * duration)

        return VideoInfo(
            num_frames=num_frames,
            frame_rate=frame_rate,
            duration=duration,
            has_sound=has_sound,
            codec=codec
        )

    except subprocess.CalledProcessError as e:
        logger.exception("Error occurred while getting info from the video")
        return VideoInfo()


def create_video_from_frames(
    frames_dir: str,
    frame_rate: Optional[int] = None,
    sound_path: Optional[str] = None,
    output_dir: Optional[str] = None,
):
    """
    Create a video from frames and save it to the output_path. This needs FFmpeg installed.
    """
    if not os.path.exists(frames_dir):
        raise "frames_dir does not exist"

    if output_dir is None:
        output_dir = TEMP_OUT_DIR
    os.makedirs(output_dir, exist_ok=True)

    num_files = len(os.listdir(output_dir))
    filename = f"{num_files:05d}.mp4"
    output_path = os.path.join(output_dir, filename)

    if sound_path is None:
        temp_sound = os.path.join(TEMP_DIR, "sound.mp3")
        if os.path.exists(temp_sound):
            sound_path = temp_sound

    if frame_rate is None:
        frame_rate = 25  # Default frame rate for ffmpeg

    command = [
        'ffmpeg',
        '-y',
        '-framerate', str(frame_rate),
        '-i', os.path.join(frames_dir, "%05d.jpg"),
        '-c:v', 'libx264',
        '-pix_fmt', 'yuv420p',
        output_path
    ]

    if sound_path is not None:
        command += [
            '-i', sound_path,
            '-c:a', 'aac',
            '-strict', 'experimental',
            '-b:a', '192k',
            '-shortest'
        ]
    try:
        subprocess.run(command, check=True)
    except subprocess.CalledProcessError as e:
        logger.exception("Error occurred while creating video from frames")
    return output_path


def get_frames_from_dir(vid_dir: str,
                        available_extensions: Optional[Union[List, str]] = None,
                        as_numpy: bool = False) -> List:
    """Get image file paths list from the dir"""
    if available_extensions is None:
        available_extensions = [".jpg", ".jpeg", ".JPG", ".JPEG"]

    if isinstance(available_extensions, str):
        available_extensions = [available_extensions]

    frame_names = [
        p for p in os.listdir(vid_dir)
        if os.path.splitext(p)[-1] in available_extensions
    ]
    if not frame_names:
        return []
    frame_names.sort(key=lambda x: int(os.path.splitext(x)[0]))

    frames = [os.path.join(vid_dir, name) for name in frame_names]
    if as_numpy:
        frames = [np.array(Image.open(frame)) for frame in frames]

    return frames


def clean_temp_dir(temp_dir: Optional[str] = None):
    """Removes media files from the directory."""
    if temp_dir is None:
        temp_dir = TEMP_DIR
        temp_out_dir = TEMP_OUT_DIR
    else:
        temp_out_dir = os.path.join(temp_dir, "out")

    clean_files_with_extension(temp_dir, SOUND_FILE_EXT)
    clean_files_with_extension(temp_dir, IMAGE_FILE_EXT)
    clean_files_with_extension(temp_out_dir, IMAGE_FILE_EXT)


def clean_files_with_extension(dir_path: str, extensions: List):
    """Remove files with the given extensions from the directory."""
    for filename in os.listdir(dir_path):
        if filename.lower().endswith(tuple(extensions)):
            file_path = os.path.join(dir_path, filename)
            try:
                os.remove(file_path)
            except Exception as e:
                logger.exception("Error while removing image files")