-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfolder.py
More file actions
317 lines (292 loc) · 10.9 KB
/
Copy pathfolder.py
File metadata and controls
317 lines (292 loc) · 10.9 KB
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
import functools
import json
import logging
import os
import time
from importlib import import_module
from typing import Any, Callable, Dict, Generator, List, Optional, Type
from base.folder import BaseFolder
from base.media import BaseMedia
from config import CONFIG
from src.mixins.db import SqlAlchemyFolderMixin
from utils import decorator, exceptions, executor
from utils.command import CommandExecutor
from utils.tools import Dict2Obj
logger = logging.getLogger()
class Folder(
BaseFolder,
SqlAlchemyFolderMixin,
):
def __init__(self, path: str, media_type: str = "video"):
super().__init__(path)
self.media_type: str = media_type
self.MEDIA_CLS: Type[BaseMedia] = self.media_cls(media_type)
@staticmethod
def media_cls(media_type: str = "video"):
try:
module = import_module(f"base.{media_type}")
except ModuleNotFoundError:
raise NotImplementedError(f"{media_type} is not in base.")
try:
return getattr(module, media_type.capitalize())
except AttributeError:
raise NotImplementedError(f"{media_type.capitalize()} is not in {module}.")
@functools.cached_property
def medias(self):
return self.medias_(self.path, media_type=self.MEDIA_CLS.__name__.lower())
@classmethod
# @functools.cache
def medias_(cls, path: str, media_type: str = "video") -> Generator[BaseMedia, Any, None]:
MEDIA_CLS: Type[BaseMedia] = cls.media_cls(media_type)
for file in cls.get_files(path):
try:
media = MEDIA_CLS(file)
yield media
except exceptions.NotMediaException:
continue
except Exception as err:
logger.exception(err)
continue
# try:
# while True:
# file = next(cls.get_files(path))
# try:
# media = MEDIA_CLS(file)
# logger.warning(media, file)
# yield media
# except exceptions.NotMediaException:
# continue
# except Exception as err:
# logger.exception(err)
# continue
# except StopIteration:
# pass
def run(self, media_method: str):
return self.run_(
media_method,
path=self.path,
media_type=self.media_type,
)
@classmethod
def run_(
cls,
media_method: str,
*args: Any,
path: str = CONFIG.MEDIA_FILE_FOLDER,
media_type: str = "video",
max_workers: int = CONFIG.MAX_WORKERS,
callback_list: List[Callable[..., Any]] = [],
**kwargs: Dict[str, Any],
):
"""Run the specified method of all media in the folder.
Arguments:
media_method {str} -- [media method name]
path {str} -- [folder path] (default: {CONFIG.MEDIA_FILE_FOLDER})
media_type {str} -- [media type] (default: {'video'})
max_workers {int} -- [max_workers] (default: {CONFIG.MAX_WORKERS})
callback_list {List[Callable[..., Any]]} -- [callback function list] (default: {[]})
Returns:
[list] -- [The return value of each media method]
e.g.: [
{
code: <ResultStatus.SUCCESS: 200>,
msg: 'Success',
data: {},
},
]
Usage:
e.g.:
Folder.run_(
'compress',
*args,
callback_list=[callback, ],
**kwargs,
)
"""
MEDIA_CLS: Type[BaseMedia] = cls.media_cls(media_type)
_media_method = getattr(MEDIA_CLS, media_method, None)
if _media_method is None:
raise NotImplementedError(f"{MEDIA_CLS} has not implemented {media_method} method.")
if not isinstance(_media_method, Callable):
raise TypeError(f"{MEDIA_CLS} has not implemented {_media_method} method.")
medias = cls.medias_(path, media_type)
logger.debug(("run_", MEDIA_CLS, medias, type(medias), path, media_type, callback_list))
return cls.run__(
media_method,
*args,
medias=medias,
max_workers=max_workers,
callback_list=callback_list,
**kwargs,
)
@classmethod
def run__(
cls,
media_method: str,
*args: Any,
medias: Optional[Generator[BaseMedia, None, None]] = None,
max_workers: int = CONFIG.MAX_WORKERS,
callback_list: List[Callable[..., Any]] = [],
**kwargs: Any,
):
if medias is None:
raise TypeError("medias is None.")
tasks = [getattr(media, media_method) for media in medias]
return cls.run___(
*args,
tasks=tasks,
max_workers=max_workers,
callback_list=callback_list,
**kwargs,
)
@staticmethod
def run___(
*args: Any,
tasks: List[Callable] = [],
max_workers: int = CONFIG.MAX_WORKERS,
callback_list: List[Callable[..., Any]] = [],
**kwargs: Dict[str, Any],
):
task_manager = executor.TaskManager(max_workers)
_ = list(task_manager.submit_all(tasks, *args, callback_list=callback_list, **kwargs))
return [future.result() for future in task_manager.futures]
@property
def meta(self):
return Dict2Obj(self.read_meta(self.path))
@staticmethod
def read_meta(path: str) -> Dict[str, str]:
"""Read media meta from meta.json under the folder.
Arguments:
path {str} -- [folder path]
Returns:
[dict] -- [media meta]
e.g.: {
"video": {
"path": "20210831_ProRes-444_BT2020L_OriRes_25_UHQ_mb05.mov",
"title": "20210831_中国北京天坛祈年殿",
"artist": "aQuantum,一枚量子",
"category": "time_lapse",
"camera": "sony_a7r2",
"lens": "laowa_12mm_f2.8",
"keywords": "天坛,祈年殿,北京,中国,中国北京,中国"
},
"resolution": "4k",
"reverse": False,
"crop": {
"w": 4096,
"h": 2160,
"x": 0,
"y": 100
},
"audio": {
"path": "/Users/nut/Downloads/Illuminate (Trailer Music) - Dirk Leupolz.mp3",
"defer": 15.3,
"fade_duration": 1
},
"watermark": {
"path": "/Users/nut/Dropbox/pic/logo/aQuantum/aQuantum_white.png",
"transparent": 0.3
}
}
"""
if not os.listdir(path).count("meta.json"):
raise FileNotFoundError(f"File not found: {path}/meta.json")
try:
with open(os.path.join(path, "meta.json"), "r", encoding="utf-8") as fd:
content = fd.read()
return json.loads(content).get("video", {})
except Exception as err:
logger.exception(err)
raise err
@decorator.timer
def trim(
self,
files: List[Dict[str, Any]],
callback_list: List[Callable[..., Any]] = [],
max_workers: int = CONFIG.MAX_WORKERS,
):
self._trim(files, callback_list, max_workers)
@classmethod
def _trim(
cls,
files: List[Dict[str, Any]] = [],
callback_list: List[Callable[..., Any]] = [],
max_workers: int = CONFIG.MAX_WORKERS,
):
"""Multi-process batch file trim.
Arguments:
files {[list]} -- [A list of dictionaries containing the path and trim_times of the file to be trimmed]
e.g.: [
{
'path': '/usr/media/1.mp4',
'trim_times': (
("00:50:22", "01:03:27"),
("01:19:39", "01:37:04"), ...
)
},
]
callback_list {[list]} -- [A list of callback function names after the file is trimmed] (default: {None})
"""
callback_list = callback_list or []
task_manager = executor.TaskManager(max_workers)
# TODO: use task_manager.submit_all
with task_manager.executor:
for file in files:
suffix_number = 0
for _time in file.get("trim_times"):
suffix_number += 1
try:
media = cls(file.get("path"))
task_manager.submit(
getattr(media, "trim"),
time=_time,
suffix_number=suffix_number,
)
except exceptions.NotMediaException as err:
logger.error(err)
continue
except Exception as err:
logger.exception(err)
logger.info("Waiting for all subprocesses done...")
@decorator.timer
def convert_images_to_video(self, image_format: str, bit_rate="5000k"):
"""Convert images to video.
Arguments:
image_format {[str]} -- [Image format] (default: {'jpg'})
e.g.: 'jpg', 'png', ...
bit_rate {[str]} -- [Video bitrate] (default: {'5000k'})
e.g.: '5000k', '10000k', ...
TODO: delete image_format
"""
self._convert_images_to_video(self.path, image_format, bit_rate)
@classmethod
def _convert_images_to_video(cls, images_path: str, image_format: str, bit_rate="5000k", media_type="image"):
create_time = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
new_file_path = f"{images_path}/output_{bit_rate}_1920_{create_time}.mp4"
MEDIA_CLS: Type[BaseMedia] = BaseMedia._SUBCLASS_MAPPER.get(media_type, BaseMedia)
command = MEDIA_CLS._FFMPEG_PREFIX + [
# 关闭每帧都提醒是否overwrite
"-pattern_type",
"glob",
# 设置帧率
"-r",
"24",
# 设置images文件路径,
"-i",
images_path + "/*." + image_format,
# 码率
# '-b:v', bit_rate,
# 线程(待验证)
# '-threads', '4',
# 画面缩放比率
"-vf",
"scale=1920:-1",
# 对video类型文件设置编码类型
# '-c:v', 'libx264',
# '-c:v', 'libx265',
# 时长取最短的media
# '-shortest',
new_file_path,
]
CommandExecutor.run(command)
return cls, command, new_file_path