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