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