353 lines
13 KiB
Python
353 lines
13 KiB
Python
import os
|
|
import subprocess
|
|
import time
|
|
|
|
import diskcache
|
|
import ffmpeg
|
|
import requests
|
|
import tqdm
|
|
from geopy import Nominatim
|
|
from pymediainfo import MediaInfo
|
|
from statistics import fmean
|
|
from statistics import quantiles
|
|
import humanize
|
|
|
|
from requests import Response
|
|
|
|
from camera import CaliforniaCamera
|
|
from process_helper import stop_processing
|
|
|
|
CACHE = diskcache.Cache("second_analyzer_cache")
|
|
|
|
|
|
def get_average_duration_and_size(videos):
|
|
durations = []
|
|
size = 0
|
|
for video in (pbar := tqdm.tqdm(videos)):
|
|
pbar.set_description("Analyzing " + str(video))
|
|
if video not in CACHE:
|
|
media_info = MediaInfo.parse(video)
|
|
CACHE[video] = media_info
|
|
else:
|
|
media_info = CACHE[video]
|
|
duration = max([t.duration for t in media_info.tracks])
|
|
durations.append(duration)
|
|
size += os.path.getsize(video)
|
|
durations = sorted(durations)
|
|
avg_duration = fmean(durations)
|
|
avg_duration = time.strftime('%H:%M:%S', time.gmtime(avg_duration/1000))
|
|
# print("Distribution: " + str(quantiles(durations, n=10)))
|
|
return avg_duration, humanize.naturalsize(size)
|
|
|
|
|
|
def analyze_own_dataset():
|
|
print("Analyzing own dataset")
|
|
cameras = [os.path.join("recordings", city, cam) for city in os.listdir("recordings") for cam in
|
|
os.listdir(os.path.join("recordings", city)) if city != "Las Vegas"]
|
|
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)]
|
|
# videos = [video for video in videos if "Las Vegas" not in video]
|
|
print("Videos: " + str(len(videos)))
|
|
print()
|
|
avg_duration, size = get_average_duration_and_size(videos)
|
|
print("Average Duration: " + str(avg_duration))
|
|
print("Size: " + str(size))
|
|
|
|
|
|
def analyze_brnospeedcomp():
|
|
print("Analyzing BrnoSpeedComp dataset")
|
|
root_path = "D:/datasets/BrnoCompSpeed/2016-ITS-BrnoCompSpeed/dataset"
|
|
cameras = [os.path.join(root_path, cam) for cam in os.listdir(root_path)]
|
|
videos = [os.path.join(camera, "video.avi") for camera in cameras]
|
|
print("Cameras: " + str(len(cameras)))
|
|
print("Videos: " + str(len(videos)))
|
|
avg_duration, size = get_average_duration_and_size(videos)
|
|
print("Average Duration: " + str(avg_duration))
|
|
print("Size: " + str(size))
|
|
|
|
|
|
def analyze_cadp():
|
|
print("Analyzing CADP dataset")
|
|
txt_path = "D:/datasets/cadp/Dataset/duration_list.txt"
|
|
durations = []
|
|
with open(txt_path, "r") as f:
|
|
lines = f.readlines()
|
|
print("Videos: " +str(len(lines)))
|
|
for line in lines:
|
|
duration = line.strip().split()[1].strip()
|
|
h, m, s = duration.split(":")
|
|
h, m, s = float(h), float(m), float(s)
|
|
duration = s*1000 + m * 60*1000 + h*60*60*1000
|
|
durations.append(duration)
|
|
avg_duration = fmean(durations)
|
|
print("Average Duration: " + str(avg_duration))
|
|
|
|
|
|
def analyze_tudat():
|
|
print("Analyzing TU-DAT dataset")
|
|
root_path = "D:/datasets/TU-DAT"
|
|
all_files = []
|
|
for path, subdirs, files in os.walk(root_path):
|
|
for name in files:
|
|
all_files.append(os.path.join(path, name))
|
|
all_files = [f for f in all_files if f.endswith(".mp4") or f.endswith(".mov")]
|
|
print("Videos: " + str(len(all_files)))
|
|
avg_duration, size = get_average_duration_and_size(all_files)
|
|
print("Average Duration: " + str(avg_duration))
|
|
print("Size: " + str(size))
|
|
|
|
|
|
def analyze_aau():
|
|
print("Analyzing AAU dataset")
|
|
root_path = "D:/datasets/AAU RainSnow"
|
|
all_files = []
|
|
for path, subdirs, files in os.walk(root_path):
|
|
for name in files:
|
|
all_files.append(os.path.join(path, name))
|
|
all_files = [f for f in all_files if f.endswith(".mkv")]
|
|
print("Videos: " + str(len(all_files)))
|
|
avg_duration, size = get_average_duration_and_size(all_files)
|
|
print("Average Duration: " + str(avg_duration))
|
|
print("Size: " + str(size))
|
|
# extensions = set([f.split(".")[len(f.split("."))-1] for f in all_files])
|
|
# print(extensions)
|
|
|
|
|
|
def analyze_streets():
|
|
print("Analyzing STREETS dataset")
|
|
root_path = "D:/datasets/STREETS/DOI-10-13012-b2idb-3671567_v1"
|
|
dirs = [os.path.join(root_path, d) for d in os.listdir(root_path) if d.startswith("20")]
|
|
days = [os.path.join(d, day) for d in dirs for day in os.listdir(d)]
|
|
cameras = set([c for d in days for c in os.listdir(d)])
|
|
print("Cameras: " + str(len(cameras)))
|
|
|
|
|
|
def parse_cameras(data):
|
|
cameras = []
|
|
data = data['data']
|
|
for camera in data:
|
|
cctv = camera['cctv']
|
|
cam = CaliforniaCamera(cctv)
|
|
print("Parsed camera: " + str(cam))
|
|
cameras.append(cam)
|
|
return cameras
|
|
|
|
|
|
def request_camera_api(api_url):
|
|
if api_url in CACHE:
|
|
data = CACHE[api_url]
|
|
else:
|
|
response = requests.get(api_url)
|
|
if response.status_code != 200:
|
|
raise RuntimeError(f"Request to {api_url} failed with status code {response.status_code}")
|
|
data = response.json()
|
|
CACHE[api_url] = data
|
|
cameras_for_url = parse_cameras(data)
|
|
return sorted(cameras_for_url, key=lambda c: c.index)
|
|
|
|
|
|
def load_cameras_california():
|
|
api_urls = [f"https://cwwp2.dot.ca.gov/data/d{i}/cctv/cctvStatusD{f'0{i}' if i < 10 else f'{i}'}.json"
|
|
for i in range(1, 13)] # 1, 13
|
|
cameras = []
|
|
for api_url in api_urls:
|
|
cameras_for_url = request_camera_api(api_url)
|
|
cameras.extend(cameras_for_url)
|
|
names = set()
|
|
for camera in cameras:
|
|
name = " ".join(str(''.join([c for c in str(camera.name) if c.isalnum() or c.isspace()])).split())
|
|
if name in names:
|
|
raise ValueError(f"found duplicate camera name {camera.name}")
|
|
names.add(name)
|
|
return cameras
|
|
|
|
|
|
def remux_to_mp4(input_path):
|
|
if not os.path.isfile(input_path):
|
|
print(f"Error: File '{input_path}' not found.")
|
|
return ""
|
|
base, _ = os.path.splitext(input_path)
|
|
output_path = base + ".mp4"
|
|
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 test_stream(c):
|
|
cache_key = f"test_camera_{str(c)}"
|
|
if cache_key in CACHE:
|
|
return CACHE[cache_key]
|
|
print(f"Testing {str(c)}")
|
|
if os.path.isfile("tmp.mkv"):
|
|
os.remove("tmp.mkv")
|
|
if os.path.isfile("tmp.mp4"):
|
|
os.remove("tmp.mp4")
|
|
if not c.stream_url:
|
|
raise ValueError
|
|
try:
|
|
r: Response = requests.head(c.stream_url, timeout=60)
|
|
print(f"camera {c.name} returned status code {r.status_code}")
|
|
if r.status_code != 200:
|
|
CACHE[cache_key] = False
|
|
return False
|
|
except requests.ConnectionError:
|
|
print(f"camera {c.name} ConnectionError")
|
|
CACHE[cache_key] = False
|
|
return False
|
|
except requests.Timeout:
|
|
print(f"Timeout for camera {c.name}")
|
|
CACHE[cache_key] = False
|
|
return False
|
|
print("trying to record camera")
|
|
cmd = ["ffmpeg", "-y", "-i", c.stream_url, "-t", "30", "-c", "copy", "tmp.mkv"]
|
|
recording_process = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
start_time = time.time()
|
|
while recording_process.poll() is None and not os.path.isfile("tmp.mkv") and time.time() - 120 < start_time:
|
|
time.sleep(10)
|
|
if not os.path.isfile("tmp.mkv"):
|
|
print(f"Recording {c.name} failed")
|
|
stop_processing(recording_process, c, True)
|
|
CACHE[cache_key] = False
|
|
return False
|
|
recording_started = time.time()
|
|
while recording_process.poll() is None and (recording_started + 90 > time.time()):
|
|
time.sleep(30)
|
|
if recording_process.poll() is None:
|
|
print("ffmpeg did not terminate correctly")
|
|
stop_processing(recording_process, c, True)
|
|
remux_to_mp4("tmp.mkv")
|
|
if not os.path.isfile("tmp.mp4"):
|
|
raise IOError("ffmpeg did not remux the video file")
|
|
media_info = MediaInfo.parse("tmp.mp4")
|
|
duration = max([t.duration for t in media_info.tracks])
|
|
valid = duration > 15000
|
|
CACHE[cache_key] = valid
|
|
print(f"camera {str(c.name)} is valid: {valid}")
|
|
os.remove("tmp.mkv")
|
|
os.remove("tmp.mp4")
|
|
return valid
|
|
|
|
def split_cameras(cameras):
|
|
no_stream = [c for c in cameras if not c.stream_url]
|
|
stream_available = [c for c in cameras if c.stream_url]
|
|
stream_working = []
|
|
for i, c in enumerate(stream_available):
|
|
t = time.time()
|
|
if test_stream(c):
|
|
stream_working.append(c)
|
|
t = time.time() - t
|
|
if t > 5:
|
|
print(f"test took {str(round(t, 2))} seconds ({i+1}/{len(stream_available)})")
|
|
return no_stream, stream_available, stream_working
|
|
|
|
|
|
def remove_spaces(s):
|
|
return " ".join(s.split())
|
|
|
|
|
|
def create_dir_name(name):
|
|
return remove_spaces(''.join([c for c in str(name) if c.isalnum() or c.isspace() or c == "-"]))
|
|
|
|
|
|
def split_cameras2(cameras, city=""):
|
|
no_stream = [c for c in cameras if not c.stream_url]
|
|
stream_available = [c for c in cameras if c.stream_url]
|
|
stream_working = []
|
|
cameras_in_city = []
|
|
if city:
|
|
if os.path.isdir(os.path.join("recordings", city)):
|
|
cameras_in_city = os.listdir(os.path.join("recordings", city))
|
|
for i, c in enumerate(stream_available):
|
|
location_dir = create_dir_name(city)
|
|
camera_dir = create_dir_name(c.name)
|
|
video_dir = os.path.join("recordings", location_dir, camera_dir)
|
|
if os.path.isdir(video_dir):
|
|
cameras_in_city.remove(camera_dir)
|
|
stream_working.append(c)
|
|
return no_stream, stream_available, stream_working, cameras_in_city
|
|
|
|
|
|
def geocode(location):
|
|
if f"nominatim_response_{location}" in CACHE:
|
|
return CACHE[f"nominatim_response_{location}"]
|
|
last_call = geocode.last_call if hasattr(geocode, "last_call") else 0
|
|
if last_call >= time.time() - 10:
|
|
time.sleep(10)
|
|
geocode.last_call = time.time()
|
|
geolocator = Nominatim(user_agent="TrafficCameraAnalyzer")
|
|
location_descriptor = geolocator.geocode(location)
|
|
CACHE[f"nominatim_response_{location}"] = location_descriptor
|
|
return CACHE[f"nominatim_response_{location}"]
|
|
|
|
|
|
def get_cameras_from(city, all_cameras):
|
|
location = geocode(city)
|
|
if 'boundingbox' not in location.raw.keys():
|
|
raise ValueError("no boundingbox found")
|
|
min_lat, max_lat, min_lon, max_lon = [float(coordinate) for coordinate in location.raw['boundingbox']]
|
|
filtered = []
|
|
for camera in all_cameras:
|
|
if min_lat < camera.latitude < max_lat and min_lon < camera.longitude < max_lon:
|
|
filtered.append(camera)
|
|
if len(filtered) == 0:
|
|
raise ValueError(f"no cameras found at {location}")
|
|
return filtered
|
|
|
|
|
|
def print_info(city, all_cameras):
|
|
cameras = get_cameras_from(city, all_cameras)
|
|
no_stream, stream_available, stream_working, cameras_left = split_cameras2(cameras, city)
|
|
|
|
print(f"{city}:")
|
|
print(" Cameras: " + str(len(cameras)))
|
|
print(" No Stream: " + str(len(no_stream)))
|
|
print(" Stream Available: " + str(len(stream_available)))
|
|
print(" Stream Working: " + str(len(stream_working)))
|
|
print(" Recorded Cameras Which Disappeared: " + str(cameras_left))
|
|
print()
|
|
|
|
|
|
def get_cctv_statistics():
|
|
all_cameras = load_cameras_california()
|
|
no_stream, stream_available, stream_working, _ = split_cameras2(all_cameras)
|
|
print("All cameras:")
|
|
print(" Cameras: " + str(len(all_cameras)))
|
|
print(" No Stream: " + str(len(no_stream)))
|
|
print(" Stream Available: " + str(len(stream_available)))
|
|
print(" Stream Working: " + str(len(stream_working)))
|
|
print()
|
|
print_info("San Francisco", all_cameras)
|
|
print_info("Sacramento", all_cameras)
|
|
print_info("Los Angeles", all_cameras)
|
|
|
|
|
|
def get_recording_time():
|
|
cameras = [os.path.join("recordings", city, cam) for city in os.listdir("recordings") for cam in
|
|
os.listdir(os.path.join("recordings", 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)]
|
|
days = set([os.path.split(day)[1] for day in days])
|
|
days = sorted(list(days))
|
|
print(f"{days[0]} - {days[-1]}")
|
|
|
|
|
|
def main():
|
|
get_cctv_statistics()
|
|
# get_recording_time()
|
|
# print()
|
|
# analyze_brnospeedcomp()
|
|
# print()
|
|
# analyze_cadp()
|
|
# analyze_tudat()
|
|
# print()
|
|
# analyze_aau()
|
|
# print()
|
|
# analyze_streets()
|
|
# print()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|