-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimestamp.py
More file actions
378 lines (348 loc) · 14.5 KB
/
timestamp.py
File metadata and controls
378 lines (348 loc) · 14.5 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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import subprocess
import os
import datetime
import re
import shutil
from pathlib import Path
from PyQt5.QtCore import QThread, pyqtSignal
import sys
import stat
import signal
def get_resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
if 'exiftool' in relative_path or 'ffmpeg' in relative_path:
return os.path.basename(relative_path)
# Add .exe extension if running on Windows
if sys.platform == "win32" and ('exiftool' in relative_path or 'ffmpeg' in relative_path):
relative_path += '.exe'
# For macOS and Linux, ensure 'exiftool' is in a subdirectory
elif 'exiftool' in relative_path and sys.platform != "win32":
relative_path = os.path.join('exiftool', relative_path)
full_path = os.path.join(base_path, relative_path)
if 'exiftool' in relative_path:
st = os.stat(full_path)
os.chmod(full_path, st.st_mode | stat.S_IEXEC)
return full_path
class Worker(QThread):
progressChanged = pyqtSignal(int)
progressDetail = pyqtSignal(int, int)
fileProcessed = pyqtSignal(str)
finished = pyqtSignal()
def __init__(
self,
files,
output_folder_path,
hwaccel_method,
remove_audio,
manually_adjusted_for_dst,
add_hour,
subtract_hour,
date_format,
skip_panasonic_vx3_timestamp=False,
skip_lawmate_timestamp=False,
append_lawmate_covert_suffix=True,
retain_originals=False,
):
super().__init__()
self.files = files
self.output_folder_path = output_folder_path
self.hwaccel_method = hwaccel_method
self.remove_audio = remove_audio
self.manually_adjusted_for_dst = manually_adjusted_for_dst
self.add_hour = add_hour
self.subtract_hour = subtract_hour
self.date_format = date_format
self.skip_panasonic_vx3_timestamp = skip_panasonic_vx3_timestamp
self.skip_lawmate_timestamp = skip_lawmate_timestamp
self.append_lawmate_covert_suffix = append_lawmate_covert_suffix
self.retain_originals = retain_originals
self.was_cancelled = False
self._stop_requested = False
self._current_process = None
def stop(self):
self._stop_requested = True
self._terminate_current_process()
def _should_stop(self):
return self._stop_requested
def _terminate_current_process(self):
process = self._current_process
if process is None or process.poll() is not None:
return
try:
if sys.platform != "win32":
os.killpg(os.getpgid(process.pid), signal.SIGTERM)
else:
process.terminate()
except Exception:
try:
process.kill()
except Exception:
pass
def run(self):
self.process_videos(self.files, self.set_progress)
self.finished.emit()
def _run_command(self, command, *, shell=False):
if self._should_stop():
return None
kwargs = {
"stdout": subprocess.PIPE,
"stderr": subprocess.PIPE,
"text": True,
"creationflags": (subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0),
}
if sys.platform != "win32":
kwargs["start_new_session"] = True
process = subprocess.Popen(command, shell=shell, **kwargs)
self._current_process = process
try:
stdout, stderr = process.communicate()
finally:
self._current_process = None
return subprocess.CompletedProcess(command, process.returncode, stdout, stderr)
def get_metadata_timestamp(self, file_path):
if sys.platform == "darwin" and getattr(sys, "frozen", False): # If the host machine is macOS
exiftool_path = os.path.join(sys._MEIPASS, 'exiftool', 'exiftool') # Use the bundled exiftool
else:
exiftool_path = get_resource_path('exiftool')
result = self._run_command(
[
exiftool_path,
'-s', '-s', '-s',
'-DateTimeOriginal',
'-CreateDate',
'-MediaCreateDate',
'-TrackCreateDate',
'-CreationDateValue',
'-LastUpdate',
'-ModifyDate',
'-TimeZone',
file_path,
],
)
if result is None:
return "", tz_offset
if result.stderr:
print("Error:", result.stderr)
if result.stdout:
print("Output:", result.stdout)
timestamps = []
tz_offset = None
for line in result.stdout.splitlines():
value = line.strip()
if not value or value == "0000:00:00 00:00:00":
continue
if re.match(r"^[+-]\d{2}:?\d{2}$", value):
tz_offset = value
continue
has_tz = bool(re.search(r"(Z|[+-]\d{2}:?\d{2})$", value))
timestamps.append((value, has_tz))
for value, has_tz in timestamps:
if has_tz:
return value, None
return (timestamps[0][0], tz_offset) if timestamps else ("", tz_offset)
def to_unix_timestamp(self, date_str, tz_offset=None):
date_str = date_str.replace(" DST", "").strip() # Remove ' DST' if present
if date_str.endswith("Z"):
date_str = f"{date_str[:-1]}+0000"
try:
dt = datetime.datetime.strptime(date_str, '%Y:%m:%d %H:%M:%S%z')
except ValueError:
dt = datetime.datetime.strptime(date_str, '%Y:%m:%d %H:%M:%S')
if tz_offset:
tz_match = re.match(r"^([+-])(\d{2}):?(\d{2})$", tz_offset)
if tz_match:
sign, hours, minutes = tz_match.groups()
offset_minutes = int(hours) * 60 + int(minutes)
if sign == "-":
offset_minutes = -offset_minutes
dt = dt.replace(tzinfo=datetime.timezone(datetime.timedelta(minutes=offset_minutes)))
else:
local_tz = datetime.datetime.now().astimezone().tzinfo
dt = dt.replace(tzinfo=local_tz)
else:
local_tz = datetime.datetime.now().astimezone().tzinfo
dt = dt.replace(tzinfo=local_tz)
if self.manually_adjusted_for_dst:
dt = dt - datetime.timedelta(hours=1) # Adjust for DST
if self.add_hour:
dt = dt + datetime.timedelta(hours=1) # Add an hour
if self.subtract_hour:
dt = dt - datetime.timedelta(hours=1) # Subtract an hour
return int(dt.timestamp())
def get_camera_identity(self, file_path):
if sys.platform == "darwin" and getattr(sys, "frozen", False):
exiftool_path = os.path.join(sys._MEIPASS, 'exiftool', 'exiftool')
else:
exiftool_path = get_resource_path('exiftool')
result = self._run_command(
[
exiftool_path,
'-s', '-s', '-s',
'-Make',
'-CameraModelName',
'-Model',
'-Format',
'-Information',
file_path,
],
)
if result is None:
return ""
values = [line.strip() for line in (result.stdout or "").splitlines() if line.strip()]
return " ".join(values)
def is_lawmate_file(self, file_path, camera_identity):
identity_upper = camera_identity.upper()
if "NVT-IM" in identity_upper or "CARDV-TURNKEY" in identity_upper:
return True
if Path(file_path).suffix.lower() == ".mov" and Path(file_path).name.upper().startswith("RECO"):
return True
return False
def should_skip_timestamp_overlay(self, file_path, camera_identity):
identity_upper = camera_identity.upper()
if self.skip_panasonic_vx3_timestamp and "HC-VX3" in identity_upper:
return True
if self.skip_lawmate_timestamp and self.is_lawmate_file(file_path, camera_identity):
return True
return False
def burn_timestamp(self, file_path, start_time_unix, output_file):
if os.path.exists(output_file):
return True
width, height = self.get_video_dimensions(file_path)
if height:
scale = height / 1080.0
font_size = max(16, int(round(48 * scale)))
offset_large = max(20, int(round(85 * scale)))
offset_small = max(12, int(round(40 * scale)))
else:
font_size = 48
offset_large = 85
offset_small = 40
ffmpeg_path = get_resource_path("ffmpeg")
command = (
f'{ffmpeg_path} -hide_banner -i "{file_path}" -vf '
f'"drawtext='
f'text=\'%{{pts\\:localtime\\:{start_time_unix}\\:%X}}\': x=10: y=h-th-{offset_large}: fontsize={font_size}: fontcolor=white: shadowcolor=black: shadowx=2: shadowy=2, '
f'drawtext='
f'text=\'%{{pts\\:localtime\\:{start_time_unix}\\:{self.date_format}}}\': x=10: y=h-th-{offset_small}: fontsize={font_size}: fontcolor=white: shadowcolor=black: shadowx=2: shadowy=2'
)
source_bitrate_kbps = self.get_video_bitrate_kbps(file_path)
command += f'" -c:v {self.hwaccel_method}'
if source_bitrate_kbps:
command += f' -b:v {source_bitrate_kbps}k'
if self.remove_audio:
command += ' -an'
else:
command += ' -map 0:v:0 -map 0:a:0? -c:a aac -b:a 192k -ac 2'
command += f' "{output_file}"'
result = self._run_command(command, shell=True)
if result is None or result.returncode != 0 or self._should_stop():
return False
return True
def transcode_without_timestamp(self, file_path, output_file):
if os.path.exists(output_file):
return True
ffmpeg_path = get_resource_path("ffmpeg")
command = f'{ffmpeg_path} -hide_banner -i "{file_path}" -map 0:v:0 -c:v copy'
if self.remove_audio:
command += ' -an'
else:
command += ' -map 0:a:0? -c:a copy'
command += f' "{output_file}"'
result = self._run_command(
command,
shell=True,
)
if result is None or result.returncode != 0 or self._should_stop():
return False
return True
def get_video_bitrate_kbps(self, file_path):
ffmpeg_path = get_resource_path("ffmpeg")
result = self._run_command(
[ffmpeg_path, "-hide_banner", "-i", file_path],
)
if result is None:
return None
output = (result.stderr or "") + (result.stdout or "")
match = re.search(r"bitrate:\s*([0-9]+(?:\.[0-9]+)?)\s*kb/s", output, flags=re.IGNORECASE)
if not match:
return None
try:
return int(float(match.group(1)))
except ValueError:
return None
def get_video_dimensions(self, file_path):
ffmpeg_path = get_resource_path("ffmpeg")
result = self._run_command(
[ffmpeg_path, "-hide_banner", "-i", file_path],
)
if result is None:
return 0, 0
output = (result.stderr or "") + (result.stdout or "")
for line in output.splitlines():
if " Video: " in line and "x" in line:
match = re.search(r"\b(\d{2,5})x(\d{2,5})\b", line)
if match:
return int(match.group(1)), int(match.group(2))
return 0, 0
def process_videos(self, files, set_progress):
set_progress(0)
total_files = len(self.files)
increment = 100 / total_files if total_files else 0
progress = 0
processed = 0
while self.files:
file_path = self.files.pop(0)
processed += 1
if self._should_stop():
self.was_cancelled = True
break
creation_date, tz_offset = self.get_metadata_timestamp(file_path)
if self._should_stop():
self.was_cancelled = True
break
if creation_date:
start_time_unix = self.to_unix_timestamp(creation_date, tz_offset=tz_offset)
dt = datetime.datetime.fromtimestamp(start_time_unix) # Convert the Unix timestamp back to a datetime
camera_identity = self.get_camera_identity(file_path)
lawmate_suffix = ""
if self.append_lawmate_covert_suffix and self.is_lawmate_file(file_path, camera_identity):
lawmate_suffix = "_COVERT"
output_file_name = (
f"{dt.strftime(self.date_format)}_{dt.strftime('%H-%M-%S')}{lawmate_suffix}.mp4"
)
output_file = os.path.join(self.output_folder_path, output_file_name)
if self.should_skip_timestamp_overlay(file_path, camera_identity):
success = self.transcode_without_timestamp(file_path, output_file)
else:
success = self.burn_timestamp(file_path, start_time_unix, output_file)
if success:
# Handle original file
if self.retain_originals:
originals_dir = os.path.join(self.output_folder_path, "originals")
os.makedirs(originals_dir, exist_ok=True)
shutil.move(file_path, os.path.join(originals_dir, os.path.basename(file_path)))
else:
try:
os.remove(file_path)
except OSError as e:
print(f"Error deleting {file_path}: {e}")
self.fileProcessed.emit(file_path)
else:
# If failed and cancelled, remove partial output file
if self._should_stop() and os.path.exists(output_file):
try:
os.remove(output_file)
except OSError as e:
print(f"Error deleting partial output {output_file}: {e}")
if self._should_stop():
self.was_cancelled = True
break
progress += increment
set_progress(int(progress))
self.progressDetail.emit(processed, total_files)
def set_progress(self, value):
self.progressChanged.emit(value)