Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bca721bb9b | ||
|
|
410564a0f0 | ||
|
|
773eca8040 | ||
|
|
5c8c40fa95 | ||
|
|
7cfd533cd7 | ||
|
|
6b155f6c0a | ||
|
|
f7569a4b78 |
+11
@@ -8,3 +8,14 @@ gui-cache/
|
|||||||
recordings*/
|
recordings*/
|
||||||
*.prof
|
*.prof
|
||||||
*.pt
|
*.pt
|
||||||
|
record_checker_cache/
|
||||||
|
analyzer_cache/
|
||||||
|
validation_cache/
|
||||||
|
broken_recordings/
|
||||||
|
second_analyzer_cache/
|
||||||
|
jam_log.csv
|
||||||
|
road_mask.png
|
||||||
|
images/
|
||||||
|
analyzer_cache3/
|
||||||
|
metadata/
|
||||||
|
evaluation_cache/
|
||||||
|
|||||||
@@ -49,10 +49,14 @@ class NevadaCamera:
|
|||||||
raise ValueError()
|
raise ValueError()
|
||||||
self.id = data["id"]
|
self.id = data["id"]
|
||||||
self.area_id = data["areaId"]
|
self.area_id = data["areaId"]
|
||||||
self.area_name = data["area"]["areaName"]["text"]
|
area = data["area"]
|
||||||
if data["area"]["areaId"] != self.area_id:
|
self.area_name = ""
|
||||||
raise ValueError()
|
self.parent_area_id = -1
|
||||||
self.parent_area_id = data["area"]["parentArea_AreaId"]
|
if area is not None:
|
||||||
|
self.area_name = data["area"]["areaName"]["text"]
|
||||||
|
if data["area"]["areaId"] != self.area_id:
|
||||||
|
raise ValueError()
|
||||||
|
self.parent_area_id = data["area"]["parentArea_AreaId"]
|
||||||
self.roadway = data["roadway"]
|
self.roadway = data["roadway"]
|
||||||
self.direction = data["direction"]
|
self.direction = data["direction"]
|
||||||
self.location = data["location"]
|
self.location = data["location"]
|
||||||
@@ -62,7 +66,9 @@ class NevadaCamera:
|
|||||||
self.longitude = float(coordinates[0])
|
self.longitude = float(coordinates[0])
|
||||||
self.region = data["region"]
|
self.region = data["region"]
|
||||||
self.state = data["state"]
|
self.state = data["state"]
|
||||||
self.country = data["country"]
|
self.country = ""
|
||||||
|
if "country" in data.keys():
|
||||||
|
self.country = data["country"]
|
||||||
|
|
||||||
self.stream_url = self.video_url
|
self.stream_url = self.video_url
|
||||||
self.index = self.id
|
self.index = self.id
|
||||||
|
|||||||
@@ -0,0 +1,314 @@
|
|||||||
|
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("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)))
|
||||||
|
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 geocode(location):
|
||||||
|
if f"nominatim_response_{location}" in CACHE:
|
||||||
|
return CACHE[f"nominatim_response_{location}"]
|
||||||
|
last_call = geocode.last_call or 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 = split_cameras(cameras)
|
||||||
|
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()
|
||||||
|
|
||||||
|
|
||||||
|
def get_cctv_statistics():
|
||||||
|
all_cameras = load_cameras_california()
|
||||||
|
no_stream, stream_available, stream_working = split_cameras(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 main():
|
||||||
|
# get_cctv_statistics()
|
||||||
|
# analyze_own_dataset()
|
||||||
|
# print()
|
||||||
|
analyze_brnospeedcomp()
|
||||||
|
print()
|
||||||
|
# analyze_cadp()
|
||||||
|
analyze_tudat()
|
||||||
|
print()
|
||||||
|
analyze_aau()
|
||||||
|
print()
|
||||||
|
analyze_streets()
|
||||||
|
print()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,352 @@
|
|||||||
|
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()
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
import datetime
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
|
||||||
|
import cv2
|
||||||
|
import diskcache
|
||||||
|
import pandas as pd
|
||||||
|
import pytz
|
||||||
|
import tqdm
|
||||||
|
from pymediainfo import MediaInfo
|
||||||
|
from timezonefinder import TimezoneFinder
|
||||||
|
from astral import LocationInfo
|
||||||
|
from astral.sun import sun
|
||||||
|
|
||||||
|
CACHE = diskcache.Cache("analyzer_cache3")
|
||||||
|
|
||||||
|
tf = TimezoneFinder()
|
||||||
|
|
||||||
|
def get_daytime(lat: float, lon: float, dt: datetime.datetime):
|
||||||
|
tz_name = tf.timezone_at(lat=lat, lng=lon)
|
||||||
|
if tz_name is None:
|
||||||
|
raise ValueError("No timezone found")
|
||||||
|
dt = pytz.timezone(tz_name).localize(dt)
|
||||||
|
location = LocationInfo(latitude=lat, longitude=lon, timezone=tz_name)
|
||||||
|
s = sun(location.observer, date=dt.date(), tzinfo=location.timezone)
|
||||||
|
|
||||||
|
dawn = s['dawn']
|
||||||
|
sunrise = s['sunrise']
|
||||||
|
sunset = s['sunset']
|
||||||
|
dusk = s['dusk']
|
||||||
|
if dawn <= dt < sunrise:
|
||||||
|
return "Dawn"
|
||||||
|
elif sunrise <= dt < sunset:
|
||||||
|
return "Day"
|
||||||
|
elif sunset <= dt < dusk:
|
||||||
|
return "Dusk"
|
||||||
|
else:
|
||||||
|
return "Night"
|
||||||
|
|
||||||
|
|
||||||
|
def get_video_info(video):
|
||||||
|
media_info: MediaInfo = CACHE.get(f"mediainfo_{video}", None)
|
||||||
|
if not media_info:
|
||||||
|
media_info = MediaInfo.parse(video)
|
||||||
|
CACHE[f"mediainfo_{video}"] = media_info
|
||||||
|
|
||||||
|
camera_info_path = os.path.join(os.path.dirname(os.path.dirname(video)), "camera_info.txt")
|
||||||
|
camera_info = dict()
|
||||||
|
if os.path.exists(camera_info_path):
|
||||||
|
with open(camera_info_path, "r") as f:
|
||||||
|
camera_info = f.read()
|
||||||
|
camera_info = camera_info.replace("'", '"').replace('""', 'null').replace("True", "true").replace("False", "false")
|
||||||
|
camera_info = camera_info[camera_info.find("{"):camera_info.rfind("}")+1]
|
||||||
|
if "datetime.datetime" in camera_info:
|
||||||
|
start = camera_info.find("datetime.datetime(")
|
||||||
|
end = camera_info.find(")", start)
|
||||||
|
camera_info = camera_info[:end] + '"' + camera_info[end + 1:]
|
||||||
|
camera_info = camera_info.replace("datetime.datetime(", '"')
|
||||||
|
camera_info = json.loads(camera_info)
|
||||||
|
duration = float(max([t.duration for t in media_info.tracks])) / 1000.0 # seconds
|
||||||
|
bitrate = int(max([t.bit_rate for t in media_info.tracks if t.bit_rate is not None])) # b/s
|
||||||
|
resolution = [(t.width, t.height) for t in media_info.video_tracks]
|
||||||
|
if len(resolution) != 1:
|
||||||
|
raise ValueError()
|
||||||
|
resolution = resolution[0] # (w, h)
|
||||||
|
basename = os.path.basename(video)
|
||||||
|
date = datetime.datetime(int(basename[0:4]), int(basename[4:6]),
|
||||||
|
int(basename[6:8]), int(basename[8:10]),
|
||||||
|
int(basename[10:12]),int(basename[12:14]))
|
||||||
|
fps = float(max([t.frame_rate for t in media_info.video_tracks]))
|
||||||
|
cap = cv2.VideoCapture(video)
|
||||||
|
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
||||||
|
cap.release()
|
||||||
|
return {"filename": video, "camera_info": camera_info, "length": duration,
|
||||||
|
"bitrate": bitrate, "resolution": resolution, "time": date, "fps": fps, "frames": frame_count}
|
||||||
|
|
||||||
|
|
||||||
|
def analyze_static_information():
|
||||||
|
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)]
|
||||||
|
videos = [os.path.join(day, video) for day in days for video in os.listdir(day)]
|
||||||
|
infos = []
|
||||||
|
for video in tqdm.tqdm(videos, desc="creating mediainfo of videos"):
|
||||||
|
info = CACHE.get(f"info_{video}", None)
|
||||||
|
if not info:
|
||||||
|
info = get_video_info(video)
|
||||||
|
CACHE.set(f"info_{video}", info)
|
||||||
|
infos.append(info)
|
||||||
|
os.makedirs("metadata", exist_ok=True)
|
||||||
|
with open(os.path.join("metadata", "video_info.csv"), "w") as f:
|
||||||
|
f.write("filename;duration;bitrate;resolution;time;fps;frames\n")
|
||||||
|
for info in infos:
|
||||||
|
f.write(f"{info["filename"]};{info["length"]};{info["bitrate"]};"
|
||||||
|
f"{info["resolution"][0]}x{info["resolution"][1]};{info["time"]};{info["fps"]};{info["frames"]}\n")
|
||||||
|
os.makedirs(os.path.join("metadata", "resolution"), exist_ok=True)
|
||||||
|
resolutions = set([i["resolution"] for i in infos])
|
||||||
|
for r in resolutions:
|
||||||
|
videos = [i["filename"] for i in infos if i["resolution"] == r]
|
||||||
|
with open(os.path.join("metadata", "resolution", f"{r[0]}x{r[1]}.txt"), "w") as f:
|
||||||
|
for video in videos:
|
||||||
|
f.write(f"{video}\n")
|
||||||
|
fps_groups = dict()
|
||||||
|
fps_groups["30"] = [i["filename"] for i in infos if int(round(i["fps"], 0)) == 30]
|
||||||
|
fps_groups["24"] = [i["filename"] for i in infos if int(round(i["fps"], 0)) == 24]
|
||||||
|
fps_groups["15"] = [i["filename"] for i in infos if int(round(i["fps"], 0)) == 15]
|
||||||
|
fps_groups["low"] = [i["filename"] for i in infos if int(round(i["fps"], 0)) < 15]
|
||||||
|
fps_groups["high"] = [i["filename"] for i in infos if int(round(i["fps"], 0)) > 30]
|
||||||
|
grouped_videos = set(fps_groups["30"]) | set(fps_groups["24"]) | set(fps_groups["15"]) | set(fps_groups["low"]) | set(fps_groups["high"])
|
||||||
|
fps_groups["medium"] = [i["filename"] for i in infos if i["filename"] not in grouped_videos]
|
||||||
|
os.makedirs(os.path.join("metadata", "fps"), exist_ok=True)
|
||||||
|
for fg in fps_groups.keys():
|
||||||
|
with open(os.path.join("metadata", "fps", f"{fg}.txt"), "w") as f:
|
||||||
|
for video in fps_groups[fg]:
|
||||||
|
f.write(f"{video}\n")
|
||||||
|
|
||||||
|
bitrates = [(i["filename"], int(i["bitrate"])) for i in infos]
|
||||||
|
df = pd.DataFrame(bitrates, columns=["filename", "bitrate"])
|
||||||
|
df["quartil"] = pd.qcut(df["bitrate"], q=4, labels=["Q1", "Q2", "Q3", "Q4"])
|
||||||
|
bitrate_groups = {group: list(videos["filename"])
|
||||||
|
for group, videos in df.groupby("quartil", observed=False)}
|
||||||
|
os.makedirs(os.path.join("metadata", "bitrate"), exist_ok=True)
|
||||||
|
for key in bitrate_groups:
|
||||||
|
with open(os.path.join("metadata", "bitrate", f"{key}.txt"), "w") as f:
|
||||||
|
for video in bitrate_groups[key]:
|
||||||
|
f.write(f"{video}\n")
|
||||||
|
duration_groups = dict()
|
||||||
|
duration_groups["short"] = [i["filename"] for i in infos if i["length"] < 300]
|
||||||
|
duration_groups["medium"] = [i["filename"] for i in infos if 300 <= i["length"] <= 600]
|
||||||
|
duration_groups["long"] = [i["filename"] for i in infos if int(round(i["fps"], 0)) > 600]
|
||||||
|
os.makedirs(os.path.join("metadata", "duration"), exist_ok=True)
|
||||||
|
for d in duration_groups.keys():
|
||||||
|
with open(os.path.join("metadata", "duration", f"{d}.txt"), "w") as f:
|
||||||
|
for video in duration_groups[d]:
|
||||||
|
f.write(f"{video}\n")
|
||||||
|
|
||||||
|
frame_counts = [(i["filename"], int(i["frames"])) for i in infos]
|
||||||
|
df = pd.DataFrame(frame_counts, columns=["filename", "frames"])
|
||||||
|
df["quartil"] = pd.qcut(df["frames"], q=4, labels=["Q1", "Q2", "Q3", "Q4"])
|
||||||
|
frame_groups = {group: list(videos["filename"])
|
||||||
|
for group, videos in df.groupby("quartil", observed=False)}
|
||||||
|
os.makedirs(os.path.join("metadata", "frame_count"), exist_ok=True)
|
||||||
|
for key in frame_groups:
|
||||||
|
with open(os.path.join("metadata", "frame_count", f"{key}.txt"), "w") as f:
|
||||||
|
for video in frame_groups[key]:
|
||||||
|
f.write(f"{video}\n")
|
||||||
|
|
||||||
|
daytime_groups = dict()
|
||||||
|
for info in infos:
|
||||||
|
filename = info["filename"]
|
||||||
|
time = info["time"]
|
||||||
|
camera_info = info["camera_info"]
|
||||||
|
if len(camera_info) == 0:
|
||||||
|
continue
|
||||||
|
lat = camera_info["latitude"]
|
||||||
|
lon = camera_info["longitude"]
|
||||||
|
daytime = get_daytime(lat, lon, time)
|
||||||
|
if daytime not in daytime_groups.keys():
|
||||||
|
daytime_groups[daytime] = []
|
||||||
|
daytime_groups[daytime].append(filename)
|
||||||
|
os.makedirs(os.path.join("metadata", "times"), exist_ok=True)
|
||||||
|
times = daytime_groups.keys()
|
||||||
|
for t in times:
|
||||||
|
videos = daytime_groups[t]
|
||||||
|
with open(os.path.join("metadata", "times", f"{t}.txt"), "w") as f:
|
||||||
|
for video in videos:
|
||||||
|
f.write(f"{video}\n")
|
||||||
|
|
||||||
|
# count = dict()
|
||||||
|
# for b in bitrate:
|
||||||
|
# count[str(b)] = count.get(str(b), 0) + 1
|
||||||
|
# values = [(i[0], i[1]) for i in count.items()]
|
||||||
|
# values = sorted(values, key=lambda x: x[1], reverse=True)
|
||||||
|
# print(values)
|
||||||
|
# keys = infos[0].keys()
|
||||||
|
# keys -= {"camera_info"}
|
||||||
|
# for k in keys:
|
||||||
|
# distinct = set([i[k] for i in infos])
|
||||||
|
# print(f"{k}: {len(distinct)}")
|
||||||
|
|
||||||
|
|
||||||
|
def analyze_car_density():
|
||||||
|
pass # TODO
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
analyze_static_information()
|
||||||
|
analyze_car_density()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
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()
|
||||||
+226
@@ -0,0 +1,226 @@
|
|||||||
|
import datetime
|
||||||
|
import os
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
import cv2
|
||||||
|
import diskcache
|
||||||
|
import psutil
|
||||||
|
from matplotlib import pyplot as plt
|
||||||
|
import matplotlib.dates as mdates
|
||||||
|
from tqdm import tqdm
|
||||||
|
|
||||||
|
from detection import YoloDetector
|
||||||
|
|
||||||
|
CACHE = diskcache.Cache("evaluation_cache")
|
||||||
|
DETECTOR = YoloDetector()
|
||||||
|
DEBUG_MODE = False
|
||||||
|
SCALE = 1
|
||||||
|
sample_interval_sec = 120.0
|
||||||
|
|
||||||
|
|
||||||
|
plt.rcParams.update({
|
||||||
|
'font.size': 14, # Basisgröße
|
||||||
|
'axes.titlesize': 16, # Titel
|
||||||
|
'axes.labelsize': 16, # Achsenbeschriftungen
|
||||||
|
'xtick.labelsize': 14, # X-Achsen-Beschriftungen
|
||||||
|
'ytick.labelsize': 14, # Y-Achsen-Beschriftungen
|
||||||
|
'legend.fontsize': 14, # Legende
|
||||||
|
# 'text.usetex': True,
|
||||||
|
'font.family': 'serif'
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
def count_cars(frame):
|
||||||
|
if SCALE != 1:
|
||||||
|
frame = cv2.resize(frame, (0, 0), fx=SCALE, fy=SCALE)
|
||||||
|
cars_list = DETECTOR.detect(frame)
|
||||||
|
if DEBUG_MODE:
|
||||||
|
img = frame.copy()
|
||||||
|
centers = [((x1 + x2) // 2, (y1 + y2) // 2) for (x1, y1, x2, y2) in cars_list]
|
||||||
|
for cx, cy in centers:
|
||||||
|
cv2.circle(img, (cx, cy), 3, (255, 0, 0), -1)
|
||||||
|
cv2.imshow('Detected Cars', img)
|
||||||
|
cv2.waitKey(1)
|
||||||
|
return len(cars_list)
|
||||||
|
|
||||||
|
|
||||||
|
def clear_crashed_process(key):
|
||||||
|
count = 0
|
||||||
|
for pid in psutil.pids():
|
||||||
|
try:
|
||||||
|
p = psutil.Process(pid)
|
||||||
|
if "python" in p.name().lower():
|
||||||
|
cmd = p.cmdline()
|
||||||
|
script = cmd[1]
|
||||||
|
if script.endswith(os.path.basename(__file__)):
|
||||||
|
count += 1
|
||||||
|
except psutil.NoSuchProcess:
|
||||||
|
pass
|
||||||
|
if count > 1:
|
||||||
|
return
|
||||||
|
if key in CACHE:
|
||||||
|
print(f"no other processes are running, clearing {key}")
|
||||||
|
CACHE.pop(key, None)
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate_camera(city, camera, camera_name, videos):
|
||||||
|
print(city, camera)
|
||||||
|
filename = os.path.join("results", city, f"{camera}_graph.png")
|
||||||
|
if os.path.isfile(filename):
|
||||||
|
return
|
||||||
|
|
||||||
|
videos_per_day = dict()
|
||||||
|
for video in videos:
|
||||||
|
day = os.path.basename(os.path.dirname(video))
|
||||||
|
videos_day = videos_per_day.get(day, [])
|
||||||
|
videos_day = list(videos_day)
|
||||||
|
videos_day.append(video)
|
||||||
|
videos_per_day[day] = sorted(videos_day)
|
||||||
|
|
||||||
|
for day in videos_per_day.keys():
|
||||||
|
if f"{city}/{camera}/{day}" not in CACHE or len(CACHE[f"{city}/{camera}/{day}"]) == 0:
|
||||||
|
clear_crashed_process(f"{city}/{camera}/{day}")
|
||||||
|
|
||||||
|
for day in videos_per_day.keys():
|
||||||
|
if f"{city}/{camera}/{day}" in CACHE:
|
||||||
|
continue
|
||||||
|
CACHE[f"{city}/{camera}/{day}"] = []
|
||||||
|
videos = sorted(videos_per_day[day])
|
||||||
|
car_timeline = []
|
||||||
|
for video in videos:
|
||||||
|
name = os.path.basename(video)
|
||||||
|
date = datetime.datetime(int(name[0:4]), int(name[4:6]), int(name[6:8]), int(name[8:10]), int(name[10:12]),
|
||||||
|
int(name[12:14]))
|
||||||
|
cap = cv2.VideoCapture(video)
|
||||||
|
length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
||||||
|
fps = cap.get(cv2.CAP_PROP_FPS)
|
||||||
|
if fps == 0 or fps is None:
|
||||||
|
raise IOError(f"Could not get fps from video {video}")
|
||||||
|
if not cap.isOpened():
|
||||||
|
raise IOError("Error opening video stream or file")
|
||||||
|
if length > 0:
|
||||||
|
pbar = tqdm(total=length, desc=f"Processing {camera}, recorded on {date}")
|
||||||
|
else:
|
||||||
|
pbar = tqdm(desc=f"Processing {camera}, recorded on {date}")
|
||||||
|
frame_count = 0
|
||||||
|
video_timeline = []
|
||||||
|
last_sample_time = None
|
||||||
|
while cap.isOpened():
|
||||||
|
ret, frame = cap.read()
|
||||||
|
if not ret:
|
||||||
|
break
|
||||||
|
ms = cap.get(cv2.CAP_PROP_POS_MSEC)
|
||||||
|
if ms < 0:
|
||||||
|
raise IOError("Error reading frame timestamp")
|
||||||
|
frame_timestamp = date + datetime.timedelta(milliseconds=ms)
|
||||||
|
if (last_sample_time is None) or (
|
||||||
|
(frame_timestamp - last_sample_time).total_seconds() >= sample_interval_sec):
|
||||||
|
cars = count_cars(frame)
|
||||||
|
video_timeline.append((frame_timestamp, cars))
|
||||||
|
last_sample_time = frame_timestamp
|
||||||
|
pbar.update(1)
|
||||||
|
frame_count += 1
|
||||||
|
cap.release()
|
||||||
|
car_timeline.extend(video_timeline)
|
||||||
|
CACHE[f"{city}/{camera}/{day}"] = car_timeline
|
||||||
|
|
||||||
|
data = dict()
|
||||||
|
for day in videos_per_day.keys():
|
||||||
|
if f"{city}/{camera}/{day}" not in CACHE or len(CACHE[f"{city}/{camera}/{day}"]) == 0:
|
||||||
|
return
|
||||||
|
data[day] = CACHE[f"{city}/{camera}/{day}"]
|
||||||
|
all_values = [item for values in data.values() for item in values]
|
||||||
|
df = pd.DataFrame(all_values, columns=["datetime", "value"])
|
||||||
|
print(df)
|
||||||
|
df["time_slot"] = df["datetime"].apply(round_datetime)
|
||||||
|
agg_df = df.groupby("time_slot").agg(
|
||||||
|
min_val=("value", "min"),
|
||||||
|
mean_val=("value", "mean"),
|
||||||
|
max_val=("value", "max"),
|
||||||
|
std_val=("value", "std"),
|
||||||
|
)
|
||||||
|
full_slots = [datetime.time(h, m) for h in range(24) for m in [0]] # , 30)]
|
||||||
|
agg_df = agg_df.reindex(full_slots)
|
||||||
|
agg_df = agg_df.fillna(0)
|
||||||
|
print(agg_df)
|
||||||
|
|
||||||
|
time_index = [datetime.datetime.combine(datetime.date(1900, 1, 1), t) for t in agg_df.index]
|
||||||
|
|
||||||
|
plt.figure(figsize=(12, 6))
|
||||||
|
|
||||||
|
mean = agg_df["mean_val"]
|
||||||
|
std = agg_df["std_val"]
|
||||||
|
|
||||||
|
plt.plot(time_index, mean, label="avg", color="blue")
|
||||||
|
# plt.plot(time_index, agg_df["min_val"], label="min", color="green", linestyle="--")
|
||||||
|
plt.plot(time_index, agg_df["max_val"], label="max", color="red", linestyle="--")
|
||||||
|
|
||||||
|
plt.fill_between(time_index, mean - std, mean + std, color="blue", alpha=0.2, label=r"$\sigma$")
|
||||||
|
|
||||||
|
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%H"))
|
||||||
|
plt.xlim(time_index[0], time_index[-1])
|
||||||
|
|
||||||
|
# Layout
|
||||||
|
plt.xlabel("Hour")
|
||||||
|
plt.ylabel("Cars")
|
||||||
|
plt.title(f"Cars counted at {camera_name}")
|
||||||
|
plt.legend(
|
||||||
|
loc="upper left",
|
||||||
|
bbox_to_anchor=(1.02, 1)
|
||||||
|
)
|
||||||
|
plt.grid(True)
|
||||||
|
plt.tight_layout()
|
||||||
|
filename = os.path.join("results", city, f"{camera}_graph.png")
|
||||||
|
os.makedirs(os.path.dirname(filename), exist_ok=True)
|
||||||
|
plt.savefig(filename)
|
||||||
|
|
||||||
|
|
||||||
|
def round_datetime(dt):
|
||||||
|
return datetime.time(dt.hour, 0)
|
||||||
|
# minute = 0 if dt.minute < 30 else 30
|
||||||
|
# return datetime.time(dt.hour, minute)
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate(city, camera, videos):
|
||||||
|
name = camera
|
||||||
|
camera_info = os.path.join("recordings", city, camera, 'camera_info.txt')
|
||||||
|
if os.path.isfile(camera_info):
|
||||||
|
with open(camera_info, 'r') as f:
|
||||||
|
camera_str = f.read()
|
||||||
|
start = camera_str.find("'", camera_str.find(':', camera_str.find('name'))) + 1
|
||||||
|
end = camera_str.find("'", start)
|
||||||
|
name = camera_str[start:end]
|
||||||
|
print("Evaluating", city, camera)
|
||||||
|
print(name)
|
||||||
|
evaluate_camera(city, camera, name, videos)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
# if DEBUG_MODE:
|
||||||
|
# CACHE.clear()
|
||||||
|
all_cameras = {}
|
||||||
|
cities = os.listdir("recordings")
|
||||||
|
for city in cities:
|
||||||
|
all_cameras[city] = {}
|
||||||
|
cameras = os.listdir(os.path.join("recordings", city))
|
||||||
|
for camera in cameras:
|
||||||
|
days = [d for d in os.listdir(os.path.join("recordings", city, camera))
|
||||||
|
if os.path.isdir(os.path.join("recordings", city, camera, d))]
|
||||||
|
days = sorted(days)
|
||||||
|
videos = []
|
||||||
|
for day in days:
|
||||||
|
videos_of_day = sorted(os.listdir(os.path.join("recordings", city, camera, day)))
|
||||||
|
videos.extend([os.path.join("recordings", city, camera, day, f) for f in videos_of_day])
|
||||||
|
all_cameras[city][camera] = videos
|
||||||
|
cameras_to_analyze = [# ("San Francisco", "TV403 -- US-101 Just North of Lagoon Way"),
|
||||||
|
# ("San Francisco", "TV521 -- I-580 Cutting Blvd"),
|
||||||
|
# ("Sacramento", "Hwy 5 At Arena Blvd 2"),
|
||||||
|
# ("Sacramento", "Hwy 5 at Pocket"),
|
||||||
|
("Los Angeles", "I-405 336 Carson St"),
|
||||||
|
("Los Angeles", "I-10 81 Overland Ave On-Ramp")]
|
||||||
|
for city, camera in cameras_to_analyze:
|
||||||
|
evaluate(city, camera, all_cameras[city][camera])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
+14
-8
@@ -1,6 +1,7 @@
|
|||||||
import datetime
|
import datetime
|
||||||
import multiprocessing
|
import multiprocessing
|
||||||
import os
|
import os
|
||||||
|
import subprocess
|
||||||
import time
|
import time
|
||||||
from typing import Union
|
from typing import Union
|
||||||
import psutil
|
import psutil
|
||||||
@@ -10,7 +11,7 @@ def log(msg):
|
|||||||
print(f"{datetime.datetime.now()} - Process {os.getpid()}: {msg}")
|
print(f"{datetime.datetime.now()} - Process {os.getpid()}: {msg}")
|
||||||
|
|
||||||
|
|
||||||
def stop_process(process: psutil.Process, camera):
|
def stop_process(process: psutil.Process, camera, fail=False):
|
||||||
if not process.is_running():
|
if not process.is_running():
|
||||||
log("process already stopped")
|
log("process already stopped")
|
||||||
return
|
return
|
||||||
@@ -26,6 +27,8 @@ def stop_process(process: psutil.Process, camera):
|
|||||||
log(f"process not stopped after terminate: {pid} - {name}")
|
log(f"process not stopped after terminate: {pid} - {name}")
|
||||||
if camera is not None:
|
if camera is not None:
|
||||||
log(f"camera that could not be stopped: {camera.name}")
|
log(f"camera that could not be stopped: {camera.name}")
|
||||||
|
if fail:
|
||||||
|
raise IOError("process could not be stopped")
|
||||||
proc_dir = "processes_to_close"
|
proc_dir = "processes_to_close"
|
||||||
if not os.path.isdir(proc_dir):
|
if not os.path.isdir(proc_dir):
|
||||||
os.makedirs(proc_dir)
|
os.makedirs(proc_dir)
|
||||||
@@ -36,10 +39,13 @@ def stop_process(process: psutil.Process, camera):
|
|||||||
file.write(f"{pid} {name} \"{cmd}\"")
|
file.write(f"{pid} {name} \"{cmd}\"")
|
||||||
|
|
||||||
|
|
||||||
def stop_processing(process: Union[multiprocessing.Process, psutil.Process], camera):
|
def stop_processing(process: Union[multiprocessing.Process, psutil.Process, subprocess.Popen], camera, fail=False):
|
||||||
parent = psutil.Process(process.pid)
|
try:
|
||||||
for child in parent.children(recursive=True):
|
parent = psutil.Process(process.pid)
|
||||||
log(f"stopping child process {child.pid} - {child.name()}")
|
for child in parent.children(recursive=True):
|
||||||
stop_process(child, camera)
|
log(f"stopping child process {child.pid} - {child.name()}")
|
||||||
log(f"stopping process {parent.pid} - {parent.name()}")
|
stop_process(child, camera, fail)
|
||||||
stop_process(parent, camera)
|
log(f"stopping process {parent.pid} - {parent.name()}")
|
||||||
|
stop_process(parent, camera, fail)
|
||||||
|
except psutil.NoSuchProcess:
|
||||||
|
pass
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
import datetime
|
||||||
|
import pickle
|
||||||
|
import time
|
||||||
|
from difflib import SequenceMatcher
|
||||||
|
|
||||||
|
import diskcache
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from camera import NevadaCamera, CaliforniaCamera
|
||||||
|
|
||||||
|
|
||||||
|
CACHE = diskcache.Cache('record_checker_cache')
|
||||||
|
|
||||||
|
|
||||||
|
def log(text):
|
||||||
|
pass
|
||||||
|
# print(f"{datetime.datetime.now()} - {text}")
|
||||||
|
|
||||||
|
|
||||||
|
def parse_cameras_nevada(data):
|
||||||
|
cameras = []
|
||||||
|
data = data["data"]
|
||||||
|
for camera in data:
|
||||||
|
cam = NevadaCamera(camera)
|
||||||
|
log(f"Parsed camera: {cam}")
|
||||||
|
cameras.append(cam)
|
||||||
|
return cameras
|
||||||
|
|
||||||
|
|
||||||
|
def parse_cameras_california(data):
|
||||||
|
cameras = []
|
||||||
|
data = data['data']
|
||||||
|
for camera in data:
|
||||||
|
cctv = camera['cctv']
|
||||||
|
cam = CaliforniaCamera(cctv)
|
||||||
|
log("Parsed camera: " + str(cam))
|
||||||
|
cameras.append(cam)
|
||||||
|
return cameras
|
||||||
|
|
||||||
|
|
||||||
|
def request_camera_api(api_url, parse):
|
||||||
|
log(f"Requesting camera API at {api_url}")
|
||||||
|
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()
|
||||||
|
cameras_for_url = parse(data)
|
||||||
|
cameras = sorted(cameras_for_url, key=lambda c: c.index)
|
||||||
|
return cameras
|
||||||
|
|
||||||
|
|
||||||
|
def load_cameras_nevada():
|
||||||
|
log("Loading nevada cameras...")
|
||||||
|
base_url = "https://www.nvroads.com/List/GetData/Cameras"
|
||||||
|
|
||||||
|
response = requests.get(base_url)
|
||||||
|
if response.status_code != 200:
|
||||||
|
raise RuntimeError(f"Request to {base_url} failed with status code {response.status_code}")
|
||||||
|
data = response.json()
|
||||||
|
total = int(data["recordsTotal"])
|
||||||
|
cameras = []
|
||||||
|
length = 50
|
||||||
|
for start in range(0, total, length):
|
||||||
|
query_params = ('{"columns":[{"data":null,"name":""},'
|
||||||
|
'{"name":"sortOrder","s":true},'
|
||||||
|
'{"name":"region","s":true},'
|
||||||
|
'{"name":"roadway","s":true},'
|
||||||
|
'{"data":4,"name":""}],'
|
||||||
|
f'"start":{start},"length":{length}}}')
|
||||||
|
query = f"query={query_params}"
|
||||||
|
url = f"{base_url}?{query}"
|
||||||
|
cameras_for_url = request_camera_api(url, parse_cameras_nevada)
|
||||||
|
cameras.extend(cameras_for_url)
|
||||||
|
return cameras
|
||||||
|
|
||||||
|
|
||||||
|
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)]
|
||||||
|
cameras = []
|
||||||
|
for api_url in api_urls:
|
||||||
|
cameras_for_url = request_camera_api(api_url, parse_cameras_california)
|
||||||
|
cameras.extend(cameras_for_url)
|
||||||
|
return cameras
|
||||||
|
|
||||||
|
|
||||||
|
def get_changes(str1, str2):
|
||||||
|
x = SequenceMatcher(None, str1, str2)
|
||||||
|
s2_new = ""
|
||||||
|
i = 0
|
||||||
|
for m in x.get_matching_blocks():
|
||||||
|
if m.b > i:
|
||||||
|
s2_new += f"\033[91m{str2[i:m.b]}\033[0m"
|
||||||
|
s2_new += str2[m.b:m.b + m.size]
|
||||||
|
i = m.b + m.size
|
||||||
|
return s2_new
|
||||||
|
|
||||||
|
|
||||||
|
def compare_cameras(cameras, new_cameras):
|
||||||
|
cameras = {("C" if type(c) == CaliforniaCamera else "N") + str(c.index): c for c in cameras}
|
||||||
|
new_cameras = {("C" if type(c) == CaliforniaCamera else "N") + str(c.index): c for c in new_cameras}
|
||||||
|
|
||||||
|
for key, cam in cameras.items():
|
||||||
|
if key not in new_cameras.keys():
|
||||||
|
print(f"Camera {cam.name} not in new_cameras")
|
||||||
|
else:
|
||||||
|
if str(cam) != str(new_cameras[key]):
|
||||||
|
print(f"camera {cam.name} changed!")
|
||||||
|
print(f"Before: {str(cam)}")
|
||||||
|
print(f"After: {str(new_cameras[key])}")
|
||||||
|
print(f"Changes: {get_changes(str(cam), str(new_cameras[key]))}")
|
||||||
|
for key, cam in new_cameras.items():
|
||||||
|
if key not in cameras.keys():
|
||||||
|
print(f"Camera {cam.name} not in cameras")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
if "cameras" in CACHE:
|
||||||
|
cameras = CACHE["cameras"]
|
||||||
|
else:
|
||||||
|
cameras = []
|
||||||
|
cameras.extend(load_cameras_nevada())
|
||||||
|
cameras.extend(load_cameras_california())
|
||||||
|
while True:
|
||||||
|
print(f"{datetime.datetime.now()} - found {len(cameras)} cameras")
|
||||||
|
new_cameras = []
|
||||||
|
new_cameras.extend(load_cameras_nevada())
|
||||||
|
new_cameras.extend(load_cameras_california())
|
||||||
|
compare_cameras(cameras, new_cameras)
|
||||||
|
cameras = new_cameras
|
||||||
|
CACHE["cameras"] = cameras
|
||||||
|
time.sleep(900)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
Reference in New Issue
Block a user