~warmwaffles/gopro-utils

ref: 02fee7ace414632306cce20330396e6165ed1109 gopro-utils/gopro -rwxr-xr-x 8.3 KiB
02fee7acMatthew Johnston Adds jpegoptim to the organize step 5 months ago
                                                                                
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
#!/usr/bin/env python3

import argparse
import re
import subprocess
from pathlib import Path


FORMATS = {
    "hero7": {
        "timelapse": re.compile(r"(G(\d{3})(\d{4}))\.(\w{3})"),
        "video": re.compile(r"(GH(\d{2})(\d{4}))\.(\w{3})"),
        "lowres": re.compile(r"(GL(\d{2})(\d{4}))\.(\w{3})"),
    },
}

def parse_video_name(model, format, path):
    regex = FORMATS[model][format]
    match = regex.match(path.name)
    if not match:
        return None

    return {
        "filename": match.group(1),
        "chapter": match.group(2),
        "number": match.group(3),
        "ext": match.group(4),
    }


def parse_timelapse_name(model, path):
    regex = FORMATS[model]["timelapse"]
    match = regex.match(path.name)
    if not match:
        return None

    return {
        "group_number": match.group(2),
        "file_number": match.group(3),
        "ext": match.group(4),
    }


def str_to_bool(v):
    if isinstance(v, bool):
        return v
    if v.lower() in ("yes", "true", "t", "y", "1"):
        return True
    elif v.lower() in ("no", "false", "f", "n", "0"):
        return False
    else:
        raise argparse.ArgumentTypeError("Boolean value expected.")


def organize(args):
    video_dir = Path(args.video_dir).resolve()
    hi_res_dir = Path(video_dir, "hi-res").resolve()
    low_res_dir = Path(video_dir, "low-res").resolve()
    thumb_dir = Path(video_dir, "thumbnails").resolve()
    timelapse_dir = Path(args.timelapse_dir).resolve()

    print(f"model:         {args.model}")
    print(f"video dir:     {video_dir}")
    print(f"timelapse dir: {timelapse_dir}")

    if not FORMATS.get(args.model):
        sys.exit(f"Unsupported go pro model \"{model}\"")

    video_dir.mkdir(exist_ok=True)
    hi_res_dir.mkdir(exist_ok=True)
    low_res_dir.mkdir(exist_ok=True)
    thumb_dir.mkdir(exist_ok=True)
    timelapse_dir.mkdir(exist_ok=True)

    directories = [Path(d).resolve() for d in args.directory]
    print("Organizing the following directories")
    for directory in directories:
        print(directory)

    for directory in directories:
        for path in directory.glob("*.MP4"):
            match = parse_video_name(args.model, "video", path)
            if match:
                new_path = Path(
                    hi_res_dir, f"{match['number']} {match['chapter']}.{match['ext']}"
                )
                print(f"RENAME {path} => {new_path}")
                new_path.parent.mkdir(parents=True, exist_ok=True)
                path.rename(new_path)

        for path in directory.glob("*.LRV"):
            match = parse_video_name(args.model, "lowres", path)
            if match:
                new_path = Path(
                    low_res_dir,
                    f"{match['number']} {match['chapter']}.{match['ext']}"
                )
                print(f"RENAME {path} => {new_path}")
                new_path.parent.mkdir(parents=True, exist_ok=True)
                path.rename(new_path)

        for path in directory.glob("*.THM"):
            match = parse_video_name(args.model, "video", path)
            if match:
                new_path = Path(
                    thumb_dir,
                    f"{match['number']} {match['chapter']}.{match['ext']}"
                )
                print(f"RENAME {path} => {new_path}")
                new_path.parent.mkdir(parents=True, exist_ok=True)
                path.rename(new_path)

        for path in directory.glob("*.JPG"):
            match = parse_timelapse_name(args.model, path)
            if not match:
                continue

            group_dir = Path(timelapse_dir, match['group_number'])
            new_path = Path(group_dir, f"{match['file_number']}.{match['ext']}")
            print(f"RENAME {path} => {new_path}")
            group_dir.mkdir(exist_ok=True)
            path.rename(Path(group_dir, path.name))

        # Delete all empty directories
        if len([f for f in directory.iterdir()]) == 0:
            print(f"DELETE {directory}")
            directory.rmdir()

    # Run jpegoptim on all of the gopro timelapse jpegs. I usually see a 6%
    # optimization in size reduction. In my eyes it is worth the extra
    # processing.
    if args.optimize:
        for path in list(timelapse_dir.glob("*")):
            if path.is_dir():
                subprocess.run(
                    [
                        "jpegoptim",
                        f"{path}/*.JPG"
                    ],
                    check=True,
                )

    # Archive all of the timelapse images into a single tar file. Makes moving
    # an entire set of files easier.
    if args.archive:
        for path in list(timelapse_dir.glob("*")):
            if path.is_dir():
                parent_path = path.parent
                outfile = Path(timelapse_dir, f"{path.name}.tar.zst")
                print(f"Archiving {path} => {outfile}")
                subprocess.run(
                    [
                        "tar",
                        "--directory",
                        parent_path,
                        "--zstd",
                        "-cf",
                        outfile,
                        path.name
                    ],
                    check=True,
                )


def timelapse(args):
    working_dir = Path(args.dir).resolve()
    file_glob = Path(working_dir, "*.JPG")
    output_dir = Path(args.output_dir).resolve()

    total = int(args.rotate / 90)

    width = args.width
    height = args.height
    scale = f"{width}x{height}"

    outfilename = working_dir.name
    if args.name:
        outfilename = args.name

    rotation = ""

    if total:
        rotation = ",".join(["transpose=2" for i in range(0, total)])
        rotation = f"-vf \"{rotation}\""

    command = [
        "ffmpeg",
        "-f",
        "image2",
        "-pattern_type",
        "glob",
        "-r",
        f"{args.fps}",
        "-i",
        f"{file_glob}",
        "-s",
        f"{scale}",
        "-c:v",
        "libx264",
        "-q:v",
        "10",
        "-an",
    ]

    if rotation:
        command.append("rotation")

    command.append(str(Path(output_dir, f"{outfilename}.mp4")))

    subprocess.run(command, check=True)


parser = argparse.ArgumentParser(
    description="A utility to help facilitate GoPro file management.",
)

subparsers = parser.add_subparsers(
    help="sub-command help",
    dest="command",
)

organize_parser = subparsers.add_parser(
    "organize",
    aliases=["o"],
    help="Organize the GoPro files",
)
organize_parser.add_argument(
    "directory",
    type=str,
    nargs="+",
    help="the directory that needs files to be organized",
    default=".",
)
organize_parser.add_argument(
    "--timelapse-dir",
    type=str,
    help="the directory to store timelapse files",
    default="./timelapse",
)
organize_parser.add_argument(
    "--video-dir",
    type=str,
    help="the directory to store video files",
    default="./videos",
)
organize_parser.add_argument(
    "--model",
    type=str,
    help="the model of go pro used",
    default="hero7",
)
organize_parser.add_argument(
    "--archive",
    type=str_to_bool,
    help="Enable or disable archiving the timelapse files",
    default=True,
)
organize_parser.add_argument(
    "--optimize",
    type=str_to_bool,
    help="Enable or disable jpeg optimization",
    default=True,
)

timelapse_parser = subparsers.add_parser(
    "timelapse",
    help="Compile timelapse",
)
timelapse_parser.add_argument(
    "dir",
    type=str,
    help="the directory where the timelapse frames are",
    default=".",
)
timelapse_parser.add_argument(
    "--output-dir",
    type=str,
    help="the directory to store the file",
    default=".",
)
timelapse_parser.add_argument(
    "--rotate",
    type=int,
    help="the amount to rotate the video by",
    default=0,
)
timelapse_parser.add_argument(
    "--width",
    type=int,
    help="the final width of the video",
    default=4000,
)
timelapse_parser.add_argument(
    "--height",
    type=int,
    help="the final height of the video",
    default=3000,
)
timelapse_parser.add_argument(
    "--fps",
    type=int,
    help="the frame rate of the video",
    default=6,
)
timelapse_parser.add_argument(
    "--name",
    type=str,
    help="the output file without the extension",
    default=None,
)

args = parser.parse_args()

COMMANDS = {
    "organize": organize,
    "timelapse": timelapse,
}

if args.command:
    COMMANDS[args.command](args)
else:
    parser.print_help()