-
Notifications
You must be signed in to change notification settings - Fork 0
/
_util.py
executable file
·138 lines (113 loc) · 5.23 KB
/
_util.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
#!/usr/bin/env python3
# The MIT License (MIT)
# Copyright (c) Kiyo Chinzei ([email protected])
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import sys
import os
import re
import subprocess
from datetime import datetime, timedelta
from exiftool import ExifToolHelper
from typing import Any, Container, Iterable, List, Dict, Optional, Union
#import logging
#logging.basicConfig(level=logging.DEBUG)
EXIF_KEY_HINTS = ['CreateDate', 'ModifyDate', 'DateTimeOriginal', 'OffsetTime', 'Aperture', 'Gain', 'Exposure', 'WhiteBalance', 'ISO', 'ImageStabilization', 'FNumber', 'Shutter', 'FrameRate', 'Rotation', 'GPS', 'Make', 'Model', 'MajorBrand', 'MinorVersion', 'CompatibleBrands', 'FileFunctionFlags', 'UserComment']
def get_mediainfo(path: str, field: str) -> str:
'''
Run mediainfo to get information of the movie in path.
'''
p = subprocess.run(['mediainfo', f'--Output={field}', path], check=True, text=True, stdout=subprocess.PIPE)
return p.stdout.split('\n')[0]
def get_exifdata(path: str, field: str) -> str|None:
with ExifToolHelper() as etool:
data = etool.get_tags(path, field)
tags = [val for key,val in data[0].items() if field in key]
if len(tags) > 0:
return tags[0]
return None
def set_exifdata(path: str, field: str, val: str):
with ExifToolHelper() as etool:
etool.set_tags(path, {field: val})
def copy_exifdata(pathfrom: str, pathto:str):
with ExifToolHelper() as etool:
data = etool.get_metadata(pathfrom)
datatocopy = {key:val for key, val in data[0].items() for keypart in EXIF_KEY_HINTS if keypart in key}
etool.set_tags(pathto, datatocopy)
def append_exifcomment(pathto: str, text:str):
comment = get_exifdata(pathto, 'UserComment')
if comment is None:
comment = ''
set_exifdata(pathto, 'UserComment', f'{text}\n{comment}')
def get_datetime_fromstr(datetime_str: str, datetime_pattern: Optional[str] = None) -> datetime|None:
if datetime_pattern is None:
datetime_pattern = r'^(\d\d\d\d)[-|:](\d\d)[-|:](\d\d)( (\d\d):(\d\d)(:(\d\d))?)?'
m = re.match(datetime_pattern, datetime_str)
if m is None:
return None
year_s = m.group(1)
month_s = m.group(2)
day_s = m.group(3)
hh_s = m.group(5)
mm_s = m.group(6)
ss_s = m.group(8)
if hh_s is None:
hh_s = '12'
if mm_s is None:
mm_s = '00'
if ss_s is None:
ss_s = '00'
return datetime(int(year_s), int(month_s), int(day_s), int(hh_s), int(mm_s), int(ss_s))
def get_datetime_fromfile(path: str, offset: Optional[str] = None) -> datetime|None:
datetime_str = get_mediainfo(path, 'General;%Recorded_Date%')
dt = get_datetime_fromstr(datetime_str)
if dt is None:
datetime_str = get_exifdata(path, 'DateTimeOriginal')
dt = get_datetime_fromstr(datetime_str)
if dt is None:
return None
if offset is not None:
m = re.fullmatch(r'([+|-]?)(\d?\d):(\d\d)(:(\d\d))?', offset.strip())
if m is not None:
polarity = m.group(1)
hh_s = m.group(2)
mm_s = m.group(3)
ss_s = m.group(5)
if ss_s is None:
ss_s = '00'
delta = timedelta(hours = int(hh_s), minutes = int(mm_s), seconds = int(ss_s))
if polarity == '-':
dt -= delta
else:
dt += delta
return dt
fname_format = '{}-{}-{}_{}{}_{}' # replaced by yyyy, mm, dd, HH, MM, SS
fname_regexp = r'(\d\d\d\d)-(\d\d)-(\d\d)(_(\d\d)(\d\d)(_(\d\d))?)?'
def datetime2strs(dt: datetime) -> tuple[str, str, str, str, str, str]:
return f'{dt.year}', f'{dt.month:02}', f'{dt.day:02}', f'{dt.hour:02}', f'{dt.minute:02}', f'{dt.second:02}'
def datetime2fname(dt: datetime) -> str:
y0, m0, d0, hh0, mm0, ss0 = datetime2strs(dt)
return fname_format.format(y0, m0, d0, hh0, mm0, ss0)
def guess_offset(path: str) -> timedelta|None:
'''
Find difference between embedded recording time and filename.
'''
dt_filename = get_datetime_fromstr(os.path.basename(path), fname_regexp)
dt_embedded = get_datetime_fromfile(path)
if dt_filename is None or dt_embedded is None:
return None
else:
return dt_filename - dt_embedded