178 lines
6.9 KiB
Python
178 lines
6.9 KiB
Python
import base64
|
|
from io import BytesIO
|
|
from sys import platform as PLATFORM
|
|
|
|
import vlc
|
|
from PIL import Image, ImageOps
|
|
import PySimpleGUI as sg
|
|
import requests
|
|
import time
|
|
import diskcache
|
|
|
|
from camera import Camera
|
|
|
|
CACHE = diskcache.Cache("gui-cache")
|
|
|
|
|
|
def show_gui(cameras):
|
|
instance = vlc.Instance()
|
|
list_player = None
|
|
media_list = None
|
|
player = None
|
|
|
|
locations = set()
|
|
camera_names_by_location = dict()
|
|
cameras_by_name = dict()
|
|
max_name = ""
|
|
|
|
for camera in cameras:
|
|
locations.add(camera.place)
|
|
if camera.place not in camera_names_by_location:
|
|
camera_names_by_location[camera.place] = set()
|
|
camera_names_by_location[camera.place].add(camera.name)
|
|
if len(camera.name) > len(max_name):
|
|
max_name = camera.name
|
|
if camera.name in cameras_by_name:
|
|
raise RuntimeError('Duplicate camera name: ' + camera.name)
|
|
cameras_by_name[camera.name] = camera
|
|
buttons = {'locations': sorted([[sg.Button(name, key=f"location-{name}")]
|
|
for name in locations], key=lambda b: b[0].key)}
|
|
for location in locations:
|
|
buttons[location] = sorted([[sg.Button(name, key=f"camera-{name}")]
|
|
for name in camera_names_by_location[location]],
|
|
key=lambda b: b[0].key)
|
|
buttons[location].insert(0, [sg.Button("Back")])
|
|
button_columns = []
|
|
current_location = "locations"
|
|
for key in buttons.keys():
|
|
button_columns.append(sg.Column(buttons[key], scrollable=True, vertical_scroll_only=True, size=(512, 640),
|
|
key=f"buttons-{key}", visible=key == current_location))
|
|
layout = [[sg.Column([[sg.Image(key="VIDEO", size=(640, 640))]]),
|
|
sg.VSeparator(),
|
|
sg.Column([button_columns])]]
|
|
window = sg.Window("Traffic Camera Analyzer", layout, finalize=True)
|
|
|
|
recording_proc = None
|
|
|
|
while True:
|
|
event, values = window.read(timeout=10)
|
|
if event == sg.WIN_CLOSED:
|
|
break
|
|
event = str(event)
|
|
if event.startswith("Back"):
|
|
window[f"buttons-{current_location}"].update(visible=False)
|
|
window["VIDEO"].update(None, visible=True)
|
|
current_location = "locations"
|
|
window[f"buttons-{current_location}"].update(visible=True)
|
|
if event.startswith("location-"):
|
|
location = event[len("location-"):]
|
|
window[f"buttons-{current_location}"].update(visible=False)
|
|
current_location = location
|
|
window[f"buttons-{current_location}"].update(visible=True)
|
|
if event.startswith("camera-"):
|
|
if recording_proc:
|
|
recording_proc.terminate()
|
|
camera = event[len("camera-"):]
|
|
camera = cameras_by_name[camera]
|
|
im = Image.open(requests.get(camera.images[0], stream=True).raw)
|
|
im = ImageOps.contain(im, (640, 640))
|
|
im_file = BytesIO()
|
|
im.save(im_file, format="PNG")
|
|
im_bytes = im_file.getvalue()
|
|
im_b64 = base64.b64encode(im_bytes)
|
|
window["VIDEO"].update(im_b64, visible=True)
|
|
if not camera.stream_url:
|
|
print(f"camera {camera.name} has no stream")
|
|
else:
|
|
# video_dir = os.path.join("recordings", ''.join([c for c in str(camera.name) if c.isalnum() or c == " "]))
|
|
# if not os.path.isdir(video_dir):
|
|
# os.makedirs(video_dir)
|
|
# if recording_proc:
|
|
# recording_proc.terminate()
|
|
# recording_proc = start_recording(camera.stream_url,
|
|
# os.path.join(video_dir,
|
|
# ''.join([c for c in str(datetime.datetime.now())
|
|
# if c.isalnum()]) + ".mkv"))
|
|
if list_player:
|
|
list_player.release()
|
|
if media_list:
|
|
media_list.release()
|
|
if player:
|
|
player.release()
|
|
list_player = instance.media_list_player_new()
|
|
media_list = instance.media_list_new()
|
|
list_player.set_media_list(media_list)
|
|
player = list_player.get_media_player()
|
|
media = None
|
|
if PLATFORM.startswith('linux'):
|
|
player.set_xwindow(window['VIDEO'].Widget.winfo_id())
|
|
else:
|
|
player.set_hwnd(window['VIDEO'].Widget.winfo_id())
|
|
try:
|
|
media = instance.media_new(camera.stream_url)
|
|
media.set_meta(0, camera.name)
|
|
media.set_meta(1, 'California Street Camera') # Default author value for local media
|
|
except Exception as e:
|
|
raise e
|
|
finally:
|
|
media.set_meta(10, camera.stream_url)
|
|
media_list.add_media(media)
|
|
print(f'Loaded: {media.get_meta(0)}')
|
|
window.read(1)
|
|
list_player.play()
|
|
# if recording_proc:
|
|
# if recording_proc.poll() is not None:
|
|
# print("recording_proc has exited")
|
|
# if recording_proc:
|
|
# recording_proc.terminate()
|
|
if list_player:
|
|
list_player.release()
|
|
if media_list:
|
|
media_list.release()
|
|
if player:
|
|
player.release()
|
|
|
|
|
|
def parse_cameras(data):
|
|
cameras = []
|
|
data = data['data']
|
|
for camera in data:
|
|
cctv = camera['cctv']
|
|
cam = Camera(cctv)
|
|
print("Parsed camera: " + str(cam))
|
|
cameras.append(cam)
|
|
return cameras
|
|
|
|
|
|
def load_cameras():
|
|
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 = []
|
|
# CACHE.clear()
|
|
for api_url in api_urls:
|
|
# log(f"loading cameras from {api_url}")
|
|
if api_url in CACHE:
|
|
# log("using cache")
|
|
cameras_for_url = 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()
|
|
cameras_for_url = parse_cameras(data)
|
|
CACHE.add(api_url, cameras_for_url, expire=7200)
|
|
cameras.extend(cameras_for_url)
|
|
cameras = sorted([c for c in cameras if c.stream_url], key=lambda c: c.index)
|
|
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
|
|
|
|
|
|
if __name__ == '__main__':
|
|
cameras = load_cameras()
|
|
show_gui(cameras)
|