Coverage for src/anpr2mqtt/event_handler.py: 94%

243 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-23 13:55 +0000

1import datetime as dt 

2import re 

3from importlib.resources import files 

4from io import BytesIO 

5from pathlib import Path 

6from typing import TYPE_CHECKING, Any 

7 

8import PIL.ImageOps 

9import pytesseract 

10import structlog 

11import tzlocal 

12from PIL import Image 

13from watchdog.events import DirCreatedEvent, FileClosedEvent, FileCreatedEvent, RegexMatchingEventHandler 

14 

15from anpr2mqtt.const import ImageInfo 

16from anpr2mqtt.handler_common import AutoclearTimer, CameraGatekeeper, build_dvla_client, correct_against_good_read 

17from anpr2mqtt.hass import HomeAssistantPublisher 

18from anpr2mqtt.settings import ( 

19 TARGET_TYPE_PLATE, 

20 CameraSettings, 

21 DVLASettings, 

22 EventSettings, 

23 ImageSettings, 

24 OCRFieldSettings, 

25 OCRSettings, 

26 hik_direction_field, 

27) 

28from anpr2mqtt.tracker import Sighting, Tracker 

29 

30if TYPE_CHECKING: 

31 from anpr2mqtt.api_client import APIClient 

32 

33log = structlog.get_logger() 

34 

35 

36class EventHandler(RegexMatchingEventHandler): 

37 def __init__( 

38 self, 

39 publisher: HomeAssistantPublisher, 

40 state_topic: str, 

41 image_topic: str, 

42 event_config: EventSettings, 

43 camera: CameraSettings, 

44 ocr_config: OCRSettings, 

45 image_config: ImageSettings, 

46 dvla_config: DVLASettings, 

47 tracker: Tracker, 

48 mqtt_topic_root: str = "anpr2mqtt", 

49 ) -> None: 

50 fqre = f"{event_config.watch_path.resolve() / event_config.image_name_re.pattern}" 

51 super().__init__(regexes=[fqre], ignore_directories=True, case_sensitive=True) 

52 log.debug("Listening for images matching %s", fqre) 

53 self.publisher = publisher 

54 self.state_topic: str = state_topic 

55 self.event_config: EventSettings = event_config 

56 self.camera: CameraSettings = camera 

57 self.tracker: Tracker = tracker 

58 self.ocr_config: OCRSettings = ocr_config 

59 self.image_config: ImageSettings = image_config 

60 self.dvla_config: DVLASettings = dvla_config 

61 if event_config.image_url_base: 

62 log.info("Images available from web server with prefix %s", event_config.image_url_base) 

63 self.image_topic: str = image_topic 

64 self.mqtt_topic_root: str = mqtt_topic_root 

65 self.api_client: APIClient | None = build_dvla_client(dvla_config, event_config.target_type) 

66 if self.api_client: 

67 log.info( 

68 "Configured gov API lookup, cache type %s (%s), ttl %s", 

69 dvla_config.cache_type, 

70 dvla_config.cache_dir or "N/A", 

71 dvla_config.cache_ttl, 

72 ) 

73 else: 

74 log.info("No gov API lookup configured") 

75 

76 self._autoclear_timer = AutoclearTimer() 

77 self._camera_gate = CameraGatekeeper() 

78 self._last_good_plate: tuple[str, dt.datetime] | None = None 

79 

80 @property 

81 def ignore_directories(self) -> bool: 

82 return True 

83 

84 def on_created(self, event: DirCreatedEvent | FileCreatedEvent) -> None: 

85 if event.event_type != "created" or event.is_directory: 

86 log.debug("on_created: skipping irrelevant event: %s", event) 

87 return 

88 log.info("New file detected: %s", event.src_path) 

89 

90 def on_closed(self, event: FileClosedEvent) -> None: 

91 if event.event_type != "closed" or event.is_directory: 

92 log.debug("on_closed: skipping irrelevant event: %s", event) 

93 return 

94 log.info("New complete file detected: %s", event.src_path) 

95 

96 file_path = Path(str(event.src_path)) 

97 if file_path.stat().st_size == 0: 

98 log.warning("Empty image file, ignoring, at %s", file_path) 

99 return 

100 url: str | None = ( 

101 f"{self.event_config.image_url_base}/{file_path.name!s}" if self.event_config.image_url_base and file_path else None 

102 ) 

103 if not url: 

104 log.warning( 

105 "No URL available for image, URL base %s, file path name %s", 

106 self.event_config.image_url_base, 

107 file_path.name if file_path else None, 

108 ) 

109 

110 try: 

111 image_info: ImageInfo | None = examine_file(file_path, self.event_config.image_name_re) 

112 if image_info is not None and image_info.target is not None: 

113 target_id: str = image_info.target 

114 log.info("Examining image for %s at %s", target_id, file_path.absolute()) 

115 

116 target_id = correct_against_good_read( 

117 target_id, 

118 self._last_good_plate, 

119 self.event_config.good_read_ttl, 

120 self.event_config.good_read_tolerance, 

121 self.tracker.normalizer, 

122 ) 

123 

124 image: Image.Image | None = process_image( 

125 file_path.absolute(), image_info, jpeg_opts=self.image_config.jpeg_opts, png_opts=self.image_config.png_opts 

126 ) 

127 ocr_fields: dict[str, str | None] = scan_ocr_fields(image, self.event_config, self.ocr_config) 

128 

129 sighting: Sighting = self.tracker.find(target_id) 

130 

131 reg_info: dict[str, Any] | None = None 

132 if ( 

133 sighting.target.lookup 

134 and self.api_client 

135 and image_info.target 

136 and self.event_config.target_type == TARGET_TYPE_PLATE 

137 ): 

138 api_info: dict[str, Any] = self.api_client.lookup(sighting.target.id) 

139 if api_info.get("success"): 139 ↛ 145line 139 didn't jump to line 145 because the condition on line 139 was always true

140 reg_info = api_info.get("plate") 

141 if sighting.target.description is None and api_info and api_info.get("description"): 141 ↛ 143line 141 didn't jump to line 143 because the condition on line 141 was always true

142 sighting.target.description = api_info["description"] 

143 self._last_good_plate = (sighting.target.id, dt.datetime.now(dt.UTC)) 

144 

145 time_analysis: dict[str, Any] = self.tracker.record( 

146 sighting.target.id, self.event_config.target_type, image_info.timestamp 

147 ) 

148 

149 if not time_analysis.get("is_new_visit", True): 149 ↛ 150line 149 didn't jump to line 150 because the condition on line 149 was never true

150 log.info("Skipping duplicate filesystem visit for %s (within gap window)", sighting.target.id) 

151 return 

152 

153 if not self._camera_gate.allow( 153 ↛ 156line 153 didn't jump to line 156 because the condition on line 153 was never true

154 image_info.timestamp, reg_info is not None, self.tracker.tracker_config.min_visit_gap_seconds 

155 ): 

156 log.info("Skipping cross-plate duplicate for %s (plate=%s)", self.event_config.camera, target_id) 

157 return 

158 

159 entity_id: str | None = sighting.target.entity_id 

160 if entity_id: 160 ↛ 161line 160 didn't jump to line 161 because the condition on line 160 was never true

161 target_state_topic = f"{self.mqtt_topic_root}/targets/{self.event_config.target_type}/{entity_id}" 

162 self.publisher.publish_target_state( 

163 state_topic=target_state_topic, 

164 description=sighting.target.description, 

165 time_analysis=time_analysis, 

166 ) 

167 

168 if sighting.ignore: 

169 log.info("Skipping MQTT publication for ignored %s", sighting.target.id) 

170 return 

171 

172 self.publisher.post_state_message( 

173 self.state_topic, 

174 sighting=sighting, 

175 event_config=self.event_config, 

176 camera=self.camera, 

177 image_info=image_info, 

178 extra_info=ocr_fields, 

179 time_analysis=time_analysis, 

180 url=url, 

181 reg_info=reg_info, 

182 file_path=file_path, 

183 source="filesystem", 

184 ) 

185 if image: 

186 img_format = image_info.ext.upper() if image_info.ext else None 

187 img_format = "JPEG" if img_format == "JPG" else img_format 

188 if img_format: 

189 self.publisher.post_image_message(self.image_topic, image, img_format) 

190 else: 

191 log.warn("Unknown image format for %s", file_path) 

192 self._schedule_autoclear() 

193 else: 

194 log.warning("No image found for %s", file_path) 

195 ocr_fields = scan_ocr_fields(None, self.event_config, self.ocr_config) 

196 

197 self.publisher.post_state_message( 

198 self.state_topic, 

199 event_config=self.event_config, 

200 camera=self.camera, 

201 extra_info=ocr_fields, 

202 sighting=None, 

203 url=url, 

204 file_path=file_path, 

205 source="filesystem", 

206 ) 

207 self._schedule_autoclear() 

208 

209 except Exception as e: 

210 log.error("Failed to parse file event %s: %s", event, e, exc_info=1) 

211 self.publisher.post_state_message( 

212 self.state_topic, 

213 event_config=self.event_config, 

214 camera=self.camera, 

215 sighting=None, 

216 error=str(e), 

217 file_path=file_path, 

218 ) 

219 

220 def _schedule_autoclear(self) -> None: 

221 self._autoclear_timer.schedule( 

222 self.event_config, 

223 self._do_autoclear, 

224 f"{self.event_config.event}/{self.event_config.camera}", 

225 ) 

226 

227 def _do_autoclear(self) -> None: 

228 autoclear = self.event_config.autoclear 

229 log.info("Autoclear firing for %s/%s", self.event_config.event, self.event_config.camera) 

230 if autoclear.state: 

231 self.publisher.post_state_message( 

232 self.state_topic, sighting=None, event_config=self.event_config, camera=self.camera 

233 ) 

234 if autoclear.image: 

235 self.publisher.post_image_message(self.image_topic, image=None) 

236 

237 

238def process_image( 

239 file_path: Path, image_info: ImageInfo, jpeg_opts: dict[str, Any], png_opts: dict[str, Any] 

240) -> Image.Image | None: 

241 try: 

242 image: Image.Image | None = Image.open(file_path.absolute()) 

243 if image is None: 243 ↛ 244line 243 didn't jump to line 244 because the condition on line 243 was never true

244 log.error("Unable to open image at %s", file_path.absolute()) 

245 return None 

246 image_format: str | None = image.format.lower() if image.format else image_info.ext 

247 img_args: dict[str, Any] | None = None 

248 

249 if image_format in ("jpg", "jpeg") and jpeg_opts: 

250 img_args = jpeg_opts 

251 elif image_format == "png" and png_opts: 

252 img_args = png_opts 

253 else: 

254 log.info("Unknown image format %s, no tuning available", image_format) 

255 if img_args: 

256 log.debug("Rewriting image to process %s", img_args) 

257 buffer = BytesIO() 

258 image.save(buffer, image_format, **img_args) 

259 size = buffer.getbuffer().nbytes 

260 if image_info.size and size != image_info.size: 

261 log.info( 

262 "Image size %s -> %s, %0.2f%% saving", 

263 image_info.size, 

264 size, 

265 (image_info.size / (image_info.size - size)) * 100, 

266 ) 

267 image_info.size = size 

268 image = Image.open(buffer) 

269 log.debug("Resaved image with %s", img_args) 

270 return image 

271 except Exception as e: 

272 log.warn("Unable to load image at %s: %s", file_path, e) 

273 return None 

274 

275 

276def examine_file(file_path: Path, image_name_re: re.Pattern[str]) -> ImageInfo | None: 

277 try: 

278 match = re.match(image_name_re, file_path.name) 

279 if match: 

280 groups = match.groupdict() 

281 size: int = file_path.stat().st_size 

282 raw_date = match.group("dt") 

283 year, month, day = map(int, (raw_date[:4], raw_date[4:6], raw_date[6:8])) 

284 hours, minutes, seconds, microseconds = map( 

285 int, (raw_date[8:10], raw_date[10:12], raw_date[12:14], raw_date[14:17]) 

286 ) 

287 timestamp = dt.datetime(year, month, day, hours, minutes, seconds, microseconds, tzinfo=tzlocal.get_localzone()) 

288 file_ext: str | None = groups.get("ext") 

289 event: str | None = groups.get("event") 

290 target: str | None = groups.get("target") 

291 if target is None: 

292 log.warning("No target found for match: %s", groups) 

293 return None 

294 if file_ext is None: 

295 file_parts = file_path.name.rsplit(".", 1) 

296 if file_parts: 296 ↛ 298line 296 didn't jump to line 298 because the condition on line 296 was always true

297 file_ext = file_parts[0] 

298 return ImageInfo(target=target, event=event, timestamp=timestamp, ext=file_ext, size=size) 

299 except Exception as e: 

300 log.warning("Unable to parse %s: %s", file_path, e) 

301 return None 

302 

303 

304def scan_ocr_fields(image: Image.Image | None, event_config: EventSettings, ocr_config: OCRSettings) -> dict[str, str | None]: 

305 ocr_field_defs: list[OCRFieldSettings] = [ 

306 ocr_config.fields[k] for k in event_config.ocr_field_ids if k in ocr_config.fields 

307 ] 

308 results: dict[str, str | None] = {f.label: "Unknown" for f in ocr_field_defs} 

309 log.debug("OCR default values: %s", results) 

310 

311 if image is None: 

312 log.debug("OCR Empty image") 

313 return results 

314 if not ocr_field_defs: 

315 log.debug("OCR No fields to scan") 

316 return results 

317 

318 try: 

319 width, height = image.size 

320 except Exception as e: 

321 log.error("OCR fail loading image:%s", e) 

322 results["IMAGE_ERROR"] = str(e) 

323 return results 

324 

325 """ 

326 The Python Imaging Library uses a Cartesian pixel coordinate system, with (0,0) in the upper left corner. 

327 Note that the coordinates refer to the implied pixel corners; the centre of a pixel addressed as (0, 0) 

328 actually lies at (0.5, 0.5). 

329 

330 Coordinates are usually passed to the library as 2-tuples (x, y). 

331 Rectangles are represented as 4-tuples, (x1, y1, x2, y2), with the upper left corner given first. 

332 """ 

333 for field_settings in ocr_field_defs: 

334 try: 

335 if field_settings.crop: 

336 x1: int = field_settings.crop.x # top-left x 

337 y1: int = height - (field_settings.crop.y + field_settings.crop.h) # top-left y [ 0 == top of image] 

338 x2: int = x1 + field_settings.crop.w # bottom-right x 

339 y2: int = height - field_settings.crop.y # bottom-right y [ 0 == top of image] 

340 log.debug("Cropping %s by %s image using PIL to %s", height, width, (x1, y1, x2, y2)) 

341 # region = im.crop((850, height - 30, 1500, height)) "850,30,650,30" 

342 region: Image.Image = image.crop((x1, y1, x2, y2)) 

343 else: 

344 log.debug("No image crop") 

345 region = image 

346 if field_settings.invert: 

347 region = PIL.ImageOps.invert(region) 

348 txt = pytesseract.image_to_string(region, config=r"") 

349 if txt: 

350 log.debug("Tesseract found text %s", txt) 

351 parsed: list[str] = txt.split(":", 1) 

352 else: 

353 log.debug("Tesseract found nothing") 

354 parsed = [] 

355 

356 if len(parsed) > 1: 

357 candidate: str = parsed[1].strip() 

358 if field_settings.correction and candidate not in field_settings.correction: 

359 for correct_to, correct_patterns in field_settings.correction.items(): 

360 if any(re.match(pat, candidate) for pat in correct_patterns): 360 ↛ 359line 360 didn't jump to line 359 because the condition on line 360 was always true

361 log.debug("Auto-correcting %s from %s to %s", field_settings.label, candidate, correct_to) 

362 candidate = correct_to 

363 if candidate and field_settings.values: 

364 for v in field_settings.values: 

365 if candidate.upper() == v.upper() and candidate != v: 

366 log.debug("OCR case correcting field %s from %s to %s", field_settings.label, candidate, v) 

367 candidate = v 

368 if field_settings.values is None or candidate in field_settings.values: 

369 results[field_settings.label] = candidate 

370 else: 

371 log.warning("Unknown value %s for OCR field %s", candidate, field_settings.label) 

372 results[field_settings.label] = "Unknown" 

373 else: 

374 log.warning("Unparsable field %s: %s", field_settings.label, txt) 

375 

376 except Exception as e: 

377 log.error("OCR fail on image:%s", e, exc_info=1) 

378 results["OCR_ERROR"] = f"field:{field_settings.label}, error:{e}" 

379 

380 return results 

381 

382 

383OCR_SAMPLE_IMAGE = "hik_direction_forward.png" 

384OCR_SAMPLE_EXPECTED = {"vehicle_direction": "Forward"} 

385OCR_VERIFY_HINT = ( 

386 "If you don't need OCR, set `ocr_field_ids: []` on each event to turn it off, " 

387 "or `ocr.verify_on_startup: false` to skip only this check" 

388) 

389 

390 

391def verify_ocr() -> bool: 

392 """OCR a bundled sample image, to check at startup that Tesseract is installed and reads text 

393 

394 Uses the built-in Hikvision direction field rather than the configured fields, so it checks the 

395 OCR engine works independently of camera-specific crop and correction settings. 

396 """ 

397 try: 

398 version = pytesseract.get_tesseract_version() 

399 except Exception as e: 

400 log.error("OCR startup verification failed, Tesseract not available (%s). %s", e, OCR_VERIFY_HINT) 

401 return False 

402 with (files("anpr2mqtt") / "samples" / OCR_SAMPLE_IMAGE).open("rb") as f: 

403 image: Image.Image = Image.open(f) 

404 image.load() 

405 results = scan_ocr_fields( 

406 image, 

407 EventSettings(ocr_field_ids=["sample"]), 

408 OCRSettings(fields={"sample": hik_direction_field()}), 

409 ) 

410 if results == OCR_SAMPLE_EXPECTED: 

411 log.info("Verified OCR using Tesseract %s on sample image, read %s", version, results) 

412 return True 

413 log.error( 

414 "OCR startup verification failed, expected %s from sample image but read %s. %s", 

415 OCR_SAMPLE_EXPECTED, 

416 results, 

417 OCR_VERIFY_HINT, 

418 ) 

419 return False