206 lines
7.8 KiB
Python
206 lines
7.8 KiB
Python
import datetime
|
|
import os
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
|
|
import diskcache
|
|
import pytz
|
|
import tqdm
|
|
import timezonefinder
|
|
from pymediainfo import MediaInfo
|
|
|
|
DIRECTORY = "recordings"
|
|
CACHE = diskcache.Cache("validation_cache")
|
|
|
|
|
|
def remux_to_mp4(input_path, output_path=None):
|
|
if not os.path.isfile(input_path):
|
|
print(f"Error: File '{input_path}' not found.")
|
|
return
|
|
|
|
if output_path is None:
|
|
base, _ = os.path.splitext(input_path)
|
|
output_path = base + ".mp4"
|
|
if os.path.isfile(output_path):
|
|
return output_path
|
|
cmd = ["ffmpeg", "-y", "-i", input_path, "-c", "copy", "-map", "0", "-movflags", "faststart", output_path]
|
|
subprocess.run(cmd, capture_output=True, text=True)
|
|
return output_path
|
|
|
|
|
|
def remux_dataset():
|
|
cameras = [os.path.join(DIRECTORY, city, cam) for city in os.listdir(DIRECTORY) for cam in os.listdir(os.path.join(DIRECTORY, city))]
|
|
print("Cameras: " + str(len(cameras)))
|
|
days = [os.path.join(camera, day) for camera in cameras for day in os.listdir(camera)]
|
|
days = [day for day in days if os.path.isdir(day)]
|
|
videos = [os.path.join(day, video) for day in days for video in os.listdir(day)]
|
|
print("Videos: " + str(len(videos)))
|
|
for video in (pbar := tqdm.tqdm(videos)):
|
|
if video.endswith(".mkv"):
|
|
pbar.set_description(f"Remuxing {video}")
|
|
remux_to_mp4(video)
|
|
os.remove(video)
|
|
|
|
|
|
def delete_empty_dirs(start=DIRECTORY):
|
|
if not os.path.isdir(os.path.join(start)):
|
|
return
|
|
children = os.listdir(start)
|
|
for child in children:
|
|
delete_empty_dirs(os.path.join(start, child))
|
|
if len(os.listdir(start)) == 0:
|
|
print(f"Deleting {os.path.join(start)}")
|
|
os.rmdir(start)
|
|
|
|
|
|
def extract_timestamps(video_path, scene_threshold=0.001):
|
|
if f"split_{video_path}" in CACHE:
|
|
return []
|
|
if video_path in CACHE:
|
|
return CACHE[video_path]
|
|
cmd = ["ffmpeg", "-i", str(video_path), "-filter:v", f"select='gt(scene,{scene_threshold})',showinfo", "-f", "null", "-"]
|
|
|
|
# print(f"Processing: {video_path}")
|
|
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
|
|
|
# Extract pts_time values using regex
|
|
timestamps = re.findall(r'pts_time:([0-9]+\.[0-9]+)', result.stderr)
|
|
timestamps = [float(ts) for ts in timestamps]
|
|
CACHE[video_path] = timestamps
|
|
return timestamps
|
|
|
|
|
|
def is_valid(timestamps, print_errors=False, recheck_cache=False):
|
|
if str(timestamps) in CACHE and not recheck_cache:
|
|
if not CACHE[str(timestamps)][0] and print_errors:
|
|
print(CACHE[str(timestamps)][1])
|
|
return CACHE[str(timestamps)][0]
|
|
if len(timestamps) < 2:
|
|
if print_errors:
|
|
print(f"Error: Invalid timestamps: {timestamps}")
|
|
CACHE[str(timestamps)] = (False, f"Error: Invalid timestamps: {timestamps}")
|
|
return False
|
|
for i in range(1, len(timestamps)):
|
|
time_before = timestamps[i - 1]
|
|
time_after = timestamps[i]
|
|
if time_before >= time_after or time_after > time_before + 10:
|
|
if print_errors:
|
|
print(f"Error: Invalid timestamps: {timestamps}")
|
|
print(f"Error: Invalid timestamps at {i}: {timestamps[i-1]}, {timestamps[i]}")
|
|
CACHE[str(timestamps)] = (False, f"Error: Invalid timestamps: {timestamps}\nError: Invalid timestamps at {i}: {timestamps[i-1]}, {timestamps[i]}")
|
|
return False
|
|
CACHE[str(timestamps)] = (True, "")
|
|
return True
|
|
|
|
|
|
def split_video(video, timestamps, pbar):
|
|
if f"split_{video}" in CACHE:
|
|
return
|
|
if not os.path.isfile(video):
|
|
return
|
|
new_videos = []
|
|
current_video = [0]
|
|
last_timestamp = 0
|
|
for timestamp in timestamps:
|
|
if timestamp < last_timestamp:
|
|
new_path = f"broken_{video}"
|
|
os.makedirs(os.path.split(new_path)[0], exist_ok=True)
|
|
shutil.move(video, new_path)
|
|
return
|
|
if timestamp == last_timestamp:
|
|
new_videos.append(current_video)
|
|
current_video = []
|
|
if timestamp > last_timestamp + 2:
|
|
new_videos.append(current_video)
|
|
current_video = []
|
|
current_video.append(timestamp)
|
|
last_timestamp = timestamp
|
|
if len(new_videos) == 0:
|
|
return
|
|
if not os.path.isfile(video):
|
|
return
|
|
new_videos.append(current_video)
|
|
new_videos = [vid for vid in new_videos if len(vid) >= 2 and vid[len(vid)-1] - vid[0] > 150]
|
|
timestamp = os.path.split(video)[1]
|
|
timestamp = timestamp.split(".")[0]
|
|
dt_part = timestamp[:-4]
|
|
tz_part = timestamp[-4:]
|
|
dt = datetime.datetime.strptime(dt_part, '%Y%m%d%H%M%S%f')
|
|
tz = datetime.timezone(-datetime.timedelta(hours=int(tz_part[:2]), minutes=int(tz_part[2:])))
|
|
dt = dt.replace(tzinfo=tz)
|
|
new_video_files = []
|
|
pbar.set_description(f"Splitting {video}")
|
|
for new_video in new_videos:
|
|
new_video_start = dt + datetime.timedelta(seconds=new_video[0])
|
|
filename = ''.join([c for c in str(new_video_start) if c.isalnum()])
|
|
extension = os.path.split(video)[1].split(".")[-1]
|
|
tmp_file = f"tmp_{filename}.{extension}"
|
|
target_file = f"{filename}.{extension}"
|
|
path = os.path.normpath(os.path.split(video)[0]).split(os.path.sep)
|
|
full_tmp_path = os.path.join(*path, tmp_file)
|
|
full_target_path = os.path.join(*path, target_file)
|
|
cmd = ["ffmpeg", "-y",
|
|
"-i", str(video),
|
|
"-ss", str(new_video[0]),
|
|
"-to", str(new_video[len(new_video)-1]),
|
|
"-c", "copy",
|
|
str(full_tmp_path)]
|
|
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
|
new_video_files.append((full_tmp_path, full_target_path))
|
|
os.remove(video)
|
|
for tmp, target in new_video_files:
|
|
shutil.move(tmp, target)
|
|
CACHE.pop(target)
|
|
CACHE[f"split_{target}"] = True
|
|
|
|
|
|
def cut_broken_videos():
|
|
cameras = [os.path.join(DIRECTORY, city, cam) for city in os.listdir(DIRECTORY) for cam in
|
|
os.listdir(os.path.join(DIRECTORY, city)) if city != "Las Vegas"]
|
|
days = [os.path.join(camera, day) for camera in cameras for day in os.listdir(camera)]
|
|
days = [day for day in days if os.path.isdir(day)]
|
|
videos = [os.path.join(day, video) for day in days for video in os.listdir(day)]
|
|
for video in (pbar := tqdm.tqdm(videos)):
|
|
pbar.set_description(f"Checking {video}")
|
|
timestamps = extract_timestamps(video)
|
|
split_video(video, timestamps, pbar)
|
|
|
|
|
|
def delete_short_videos():
|
|
cameras = [os.path.join(DIRECTORY, city, cam) for city in os.listdir(DIRECTORY) for cam in
|
|
os.listdir(os.path.join(DIRECTORY, city)) if city != "Las Vegas"]
|
|
days = [os.path.join(camera, day) for camera in cameras for day in os.listdir(camera)]
|
|
days = [day for day in days if os.path.isdir(day)]
|
|
videos = [os.path.join(day, video) for day in days for video in os.listdir(day)]
|
|
for video in (pbar := tqdm.tqdm(videos)):
|
|
pbar.set_description(f"Checking {video}")
|
|
media_info = MediaInfo.parse(video)
|
|
duration = max([t.duration for t in media_info.tracks])
|
|
duration /= 1000
|
|
if duration < 60:
|
|
new_path = f"broken_{video}"
|
|
os.makedirs(os.path.split(new_path)[0], exist_ok=True)
|
|
shutil.move(video, new_path)
|
|
|
|
|
|
def main():
|
|
# remux_dataset()
|
|
# cut_broken_videos()
|
|
delete_short_videos()
|
|
delete_empty_dirs()
|
|
|
|
|
|
def timezone_test():
|
|
tf = timezonefinder.TimezoneFinder()
|
|
timezone_str = tf.certain_timezone_at(lat=37.64111, lng=-118.91848)
|
|
print("timezone_str", timezone_str)
|
|
timezone = pytz.timezone(timezone_str)
|
|
print("timezone", timezone)
|
|
print(datetime.datetime.now(timezone))
|
|
print(''.join([c for c in str(datetime.datetime.now(timezone)) if c.isalnum()]))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
# CACHE.clear()
|
|
main() |