Hook in pylint to the pre-commit hook and start to fix some of its
[python_utils.git] / camera_utils.py
1 #!/usr/bin/env python3
2
3 """Utilities for dealing with webcam images."""
4
5 import logging
6 import platform
7 import subprocess
8 import warnings
9 from typing import NamedTuple, Optional
10
11 import cv2  # type: ignore
12 import numpy as np
13 import requests
14
15 import decorator_utils
16 import exceptions
17
18 logger = logging.getLogger(__name__)
19
20
21 class RawJpgHsv(NamedTuple):
22     """Raw image bytes, the jpeg image and the HSV (hue saturation value) image."""
23
24     raw: Optional[bytes]
25     jpg: Optional[np.ndarray]
26     hsv: Optional[np.ndarray]
27
28
29 class SanityCheckImageMetadata(NamedTuple):
30     """Is a Blue Iris image bad (big grey borders around it) or infrared?"""
31
32     is_bad_image: bool
33     is_infrared_image: bool
34
35
36 def sanity_check_image(hsv: np.ndarray) -> SanityCheckImageMetadata:
37     """See if a Blue Iris or Shinobi image is bad and infrared."""
38
39     def is_near(a, b) -> bool:
40         return abs(a - b) < 3
41
42     rows, cols, _ = hsv.shape
43     num_pixels = rows * cols
44     weird_orange_count = 0
45     hs_zero_count = 0
46     for r in range(rows):
47         for c in range(cols):
48             pixel = hsv[(r, c)]
49             if is_near(pixel[0], 16) and is_near(pixel[1], 117) and is_near(pixel[2], 196):
50                 weird_orange_count += 1
51             elif is_near(pixel[0], 0) and is_near(pixel[1], 0):
52                 hs_zero_count += 1
53     logger.debug("hszero#=%d, weird_orange=%d", hs_zero_count, weird_orange_count)
54     return SanityCheckImageMetadata(
55         hs_zero_count > (num_pixels * 0.75),
56         weird_orange_count > (num_pixels * 0.75),
57     )
58
59
60 @decorator_utils.retry_if_none(tries=2, delay_sec=1, backoff=1.1)
61 def fetch_camera_image_from_video_server(
62     camera_name: str, *, width: int = 256, quality: int = 70
63 ) -> Optional[bytes]:
64     """Fetch the raw webcam image from the video server."""
65     camera_name = camera_name.replace(".house", "")
66     camera_name = camera_name.replace(".cabin", "")
67     url = (
68         f"http://10.0.0.226:8080/Umtxxf1uKMBniFblqeQ9KRbb6DDzN4/jpeg/GKlT2FfiSQ/{camera_name}/s.jpg"
69     )
70     logger.debug('Fetching image from %s', url)
71     try:
72         response = requests.get(url, stream=False, timeout=10.0)
73         if response.ok:
74             raw = response.content
75             logger.debug('Read %d byte image from HTTP server', len(response.content))
76             tmp = np.frombuffer(raw, dtype="uint8")
77             logger.debug(
78                 'Translated raw content into %s %s with element type %s',
79                 tmp.shape, type(tmp), type(tmp[0]),
80             )
81             jpg = cv2.imdecode(tmp, cv2.IMREAD_COLOR)
82             logger.debug(
83                 'Decoded into %s jpeg %s with element type %s',
84                 jpg.shape, type(jpg), type(jpg[0][0])
85             )
86             hsv = cv2.cvtColor(jpg, cv2.COLOR_BGR2HSV)
87             logger.debug(
88                 'Converted JPG into %s HSV HSV %s with element type %s',
89                 hsv.shape, type(hsv), type(hsv[0][0])
90             )
91             (_, is_bad_image) = sanity_check_image(hsv)
92             if not is_bad_image:
93                 return raw
94     except Exception as e:
95         logger.exception(e)
96     msg = f"Got a bad image or HTTP error from {url}; returning None."
97     logger.warning(msg)
98     warnings.warn(msg, stacklevel=2)
99     return None
100
101
102 def camera_name_to_hostname(camera_name: str) -> str:
103     """Map a camera name to a hostname
104
105     >>> camera_name_to_hostname('driveway')
106     'driveway.house'
107
108     >>> camera_name_to_hostname('cabin_driveway')
109     'driveway.cabin'
110
111     """
112     mapping = {
113         "driveway": "driveway.house",
114         "backyard": "backyard.house",
115         "frontdoor": "frontdoor.house",
116         "cabin_driveway": "driveway.cabin",
117     }
118     camera_name = mapping.get(camera_name, camera_name)
119     if "." not in camera_name:
120         hostname = platform.node()
121         suffix = hostname.split(".")[-1]
122         camera_name += f".{suffix}"
123     return camera_name
124
125
126 @decorator_utils.retry_if_none(tries=2, delay_sec=1, backoff=1.1)
127 def fetch_camera_image_from_rtsp_stream(camera_name: str, *, width: int = 256) -> Optional[bytes]:
128     """Fetch the raw webcam image straight from the webcam's RTSP stream."""
129     hostname = camera_name_to_hostname(camera_name)
130     stream = f"rtsp://camera:IaLaIok@{hostname}:554/live"
131     logger.debug('Fetching image from RTSP stream %s', stream)
132     try:
133         cmd = [
134             "/usr/bin/timeout",
135             "-k 9s",
136             "8s",
137             "/usr/local/bin/ffmpeg",
138             "-y",
139             "-i",
140             f"{stream}",
141             "-f",
142             "singlejpeg",
143             "-vframes",
144             "1",
145             "-vf",
146             f"scale={width}:-1",
147             "-",
148         ]
149         with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) as proc:
150             out, _ = proc.communicate(timeout=10)
151             return out
152     except Exception as e:
153         logger.exception(e)
154     msg = f"Failed to retrieve image via RTSP {stream}, returning None."
155     logger.warning(msg)
156     warnings.warn(msg, stacklevel=2)
157     return None
158
159
160 @decorator_utils.timeout(seconds=30, use_signals=False)
161 def _fetch_camera_image(camera_name: str, *, width: int = 256, quality: int = 70) -> RawJpgHsv:
162     """Fetch a webcam image given the camera name."""
163     logger.debug("Trying to fetch camera image from video server")
164     raw = fetch_camera_image_from_video_server(camera_name, width=width, quality=quality)
165     if raw is None:
166         logger.debug("Reading from video server failed; trying direct RTSP stream")
167         raw = fetch_camera_image_from_rtsp_stream(camera_name, width=width)
168     if raw is not None and len(raw) > 0:
169         tmp = np.frombuffer(raw, dtype="uint8")
170         jpg = cv2.imdecode(tmp, cv2.IMREAD_COLOR)
171         hsv = cv2.cvtColor(jpg, cv2.COLOR_BGR2HSV)
172         return RawJpgHsv(
173             raw=raw,
174             jpg=jpg,
175             hsv=hsv,
176         )
177     msg = "Failed to retieve image from both video server and direct RTSP stream"
178     logger.warning(msg)
179     warnings.warn(msg, stacklevel=2)
180     return RawJpgHsv(None, None, None)
181
182
183 def fetch_camera_image(camera_name: str, *, width: int = 256, quality: int = 70) -> RawJpgHsv:
184     try:
185         return _fetch_camera_image(camera_name, width=width, quality=quality)
186     except exceptions.TimeoutError:
187         logger.warning('Fetching camera image operation timed out.')
188         return RawJpgHsv(None, None, None)
189
190
191 if __name__ == '__main__':
192     import doctest
193
194     doctest.testmod()