import datetime import os import random import time import diskcache import geopy.distance import requests from geopy.geocoders import Nominatim from requests import Response from suntime import Sun import pytz import timezonefinder import ffmpeg from process_helper import stop_processing def log(msg): print(f"{datetime.datetime.now()} - Process {os.getpid()}: {msg}") def remove_spaces(s): return " ".join(s.split()) def geocode(location): if not hasattr(geocode, "cache"): geocode.cache = diskcache.Cache('cache') geocode.cache["nominatim_last_update"] = 0 if f"nominatim_response_{location}" in geocode.cache: log(f"Found {location} in cache") return geocode.cache[f"nominatim_response_{location}"] while geocode.cache["nominatim_last_update"] + 5 >= time.time(): log("cannot request Nominatim right now, please wait") time.sleep(5) geocode.cache["nominatim_last_update"] = time.time() geolocator = Nominatim(user_agent="TrafficCameraAnalyzer") location_descriptor = geolocator.geocode(location) geocode.cache[f"nominatim_response_{location}"] = location_descriptor return geocode.cache[f"nominatim_response_{location}"] def filter_cameras_by_location(cameras, boundingbox): min_lat, max_lat, min_lon, max_lon = [float(coordinate) for coordinate in boundingbox] filtered = [] for camera in cameras: if min_lat < camera.latitude < max_lat and min_lon < camera.longitude < max_lon: filtered.append(camera) return filtered def filter_cameras_by_distance(cameras, latitude, longitude, distance): filtered = [] for camera in cameras: print(camera.latitude, camera.longitude, distance) if geopy.distance.distance((latitude, longitude), (camera.latitude, camera.longitude)).mi < distance: filtered.append(camera) return filtered def filter_cameras_by_street(cameras, location): filtered = [] for camera in cameras: if camera.route == location: filtered.append(camera) return filtered def get_cache_key(camera): return f"{camera.name} disabled until" class MockProcess: def __init__(self): self.start_time = time.time() def poll(self): if random.randint(0, 4) == 0: return None return 0 def create_dir_name(name): return remove_spaces(''.join([c for c in str(name) if c.isalnum() or c.isspace() or c == "-"])) def filter_cameras(cameras): filtered = set() for camera in cameras: cam = camera for name in ["US-101 Just North of Candlestick Park", "US-101 At Alemany Bl", "I-280 At Alemany Bl", "US-101 Candlesticks Offramp", "I-80 SFOBB at Incline" # ----- # "US-101 At Hospital Curve", # "I-280 John Daly Blvd", # "US-101 AT AIRPORT BL", # "I-580 Cutting Blvd", # "I-280 At Indiana St", # "I-280 Just South Of Cesar Chavez", # "US-101 Marin SR-1" ]: if name in create_dir_name(camera.name): # log(f"camera {camera.name} does not work") cam = None if cam is not None: filtered.add(cam) return list(filtered) class Recorder: def __init__(self, cameras, location, distance=0, max_recording_time=0): """ :param cameras: all cameras available :param location: the location, where cameras should be used. Can be city/area or street :param distance: if 0, consider all cameras at location. If > 0, consider all cameras in distance miles around location. If < 0, interpret location as street and consider all cameras on this street :param max_recording_time: maximum number of seconds to keep recording. If <= 0, keep recording forever """ self.location_name = location self.max_recording_time = max_recording_time self.cache = diskcache.Cache('cache') preposition_for_log = "at" if distance >= 0 else "on" if f"{self.location_name}+{distance}" not in self.cache: if distance > 0: location = geocode(location) cameras = filter_cameras_by_distance(cameras, location.latitude, location.longitude, distance) elif distance < 0: cameras = filter_cameras_by_street(cameras, location) else: location = geocode(location) if 'boundingbox' not in location.raw.keys(): raise ValueError("no boundingbox found") cameras = filter_cameras_by_location(cameras, location.raw['boundingbox']) if len(cameras) == 0: raise ValueError(f"no cameras found {preposition_for_log} {location}") log(f"found {len(cameras)} cameras {preposition_for_log} {location}") cameras = filter_cameras(cameras) self.cache.add(f"{self.location_name}+{distance}", cameras, expire=3600) else: log(f"loading cameras {preposition_for_log} {location} from cache") cameras = self.cache[f"{self.location_name}+{distance}"] avaliable_cameras = [] for camera in cameras: key = get_cache_key(camera) if key not in self.cache or self.cache[key] < time.time(): avaliable_cameras.append(camera) self.cache["cameras_available"] = len(avaliable_cameras) if len(avaliable_cameras) == 0: log("No camera available") self.camera = None return log(f"{len(avaliable_cameras)} cameras available") self.camera = random.choice(avaliable_cameras) self.cache[get_cache_key(self.camera)] = time.time() + 86400 def start_recording(self, skip_time_checks=False, debug_mode=False): if self.camera is None: return active_cameras = set([cam for cam, t in self.cache.get("active_cameras", set())]) if self.camera in active_cameras: raise ValueError("camera already active") self.cache[get_cache_key(self.camera)] = time.time() + 86400 log(f"checking {self.camera.stream_url}") try: r: Response = requests.head(self.camera.stream_url, timeout=60) log(f"camera {self.camera.name} returned status code {r.status_code}") if r.status_code != 200: return except requests.ConnectionError: log(f"camera {self.camera.name} ConnectionError") return except requests.Timeout: log(f"Timeout for camera {self.camera.name}") return sun = Sun(self.camera.latitude, self.camera.longitude) tf = timezonefinder.TimezoneFinder() timezone_str = tf.certain_timezone_at(lat=self.camera.latitude, lng=self.camera.longitude) if timezone_str is None: raise ValueError("Could not determine the time zone") timezone = pytz.timezone(timezone_str) sunrise = sun.get_sunrise_time(time_zone=timezone) sunset = sun.get_sunset_time(time_zone=timezone) if not skip_time_checks: if not (sunrise.timestamp() < datetime.datetime.now(timezone).timestamp() < sunset.timestamp()): if sunrise.timestamp() > datetime.datetime.now(timezone).timestamp(): log(f"It is night right now, please wait until {sunrise} ({sunrise.astimezone()} local time)") else: tomorrow = datetime.datetime.now() + datetime.timedelta(days=1) next_sunrise = sun.get_sunrise_time(at_date=tomorrow,time_zone=timezone) log(f"It is night right now, please wait until {next_sunrise} ({next_sunrise.astimezone()} local time)") self.cache["cameras_available"] = 0 self.cache[get_cache_key(self.camera)] = 0 return log(f"Recording {self.camera.name} until {sunset} ({sunset.astimezone()} local time)") location_dir = create_dir_name(self.location_name) camera_dir = create_dir_name(self.camera.name) date_dir = ''.join([c for c in str(datetime.datetime.now(timezone)) if c.isalnum()])[:8] video_dir = os.path.join("recordings", location_dir, camera_dir, date_dir) if not os.path.isdir(video_dir) and not debug_mode: os.makedirs(video_dir) filename = ''.join([c for c in str(datetime.datetime.now(timezone)) if c.isalnum()]) output_file = os.path.join(video_dir, f"{filename}.mkv") if not debug_mode: # see https://askubuntu.com/questions/436956/stop-the-recording-after-some-period-of-time recording_process = ffmpeg.input(self.camera.stream_url, t=self.max_recording_time).output(output_file, c="copy").run_async(quiet=True) else: recording_process = MockProcess() log("wait for recording to start") start_time = time.time() while recording_process.poll() is None and not os.path.isfile(output_file) and time.time() - 120 < start_time: time.sleep(10) if not os.path.isfile(output_file): log(f"Recording {self.camera.name} failed, disabling for 1h") self.cache[get_cache_key(self.camera)] = time.time() + 3600 if not debug_mode: check_dir = video_dir while os.path.isdir(check_dir) and len(os.listdir(check_dir)) == 0: os.rmdir(check_dir) check_dir = os.path.dirname(check_dir) log("recording stopped") if recording_process.poll() is None: stop_processing(recording_process, self.camera) return info_file = os.path.join("recordings", self.location_name, camera_dir, "camera_info.txt") if not os.path.isfile(info_file): with open(info_file, "w") as f: f.write(f"{str(self.camera)}\n") last_log = 0 log("recording started") recording_started = time.time() active_camera_cache_element = (self.camera.name, recording_started) self.cache["active_cameras"] |= {active_camera_cache_element} while (recording_process.poll() is None # 60 seconds time for ffmpeg to stop itself and (self.max_recording_time <= 0 or recording_started + self.max_recording_time + 60 > time.time())): if not skip_time_checks: if not (sunrise.timestamp() < datetime.datetime.now(timezone).timestamp() < sunset.timestamp()): log("it is night right now, please wait again until sunrise") break if last_log + 300 < time.time(): log(f"{datetime.datetime.now(timezone)}: Recording {self.camera.name} until {sunset} ({sunset.astimezone()} local time)") last_log = time.time() else: if last_log + 300 < time.time(): log(f"{datetime.datetime.now(timezone)}: Recording {self.camera.name}") last_log = time.time() time.sleep(30) if recording_process.poll() is None: log("ffmpeg did not terminate correctly") stop_processing(recording_process, self.camera) log(f"Recording {self.camera.name} stopped, disabling for 15min") self.cache[get_cache_key(self.camera)] = time.time() + 900 if not debug_mode: check_dir = video_dir while len(os.listdir(check_dir)) == 0: os.rmdir(check_dir) check_dir = os.path.dirname(check_dir) log("recording stopped") self.cache["active_cameras"] -= {active_camera_cache_element}