Coverage for src/anpr2mqtt/tools.py: 85%

68 statements  

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

1import json 

2import sys 

3from pathlib import Path 

4from typing import TYPE_CHECKING, Any, Literal 

5 

6import structlog 

7from PIL import Image 

8from pydantic import BaseModel, Field 

9from pydantic_settings import ( 

10 BaseSettings, 

11 CliApp, 

12 CliPositionalArg, 

13 CliSubCommand, 

14 SettingsConfigDict, 

15) 

16 

17from anpr2mqtt.api_client import DVLAClient 

18from anpr2mqtt.event_handler import examine_file, scan_ocr_fields 

19from anpr2mqtt.heartbeat import DEFAULT_MAX_AGE, heartbeat_age, heartbeat_path 

20from anpr2mqtt.settings import DVLASettings, EventSettings, OCRFieldSettings, OCRSettings 

21 

22if TYPE_CHECKING: 

23 from anpr2mqtt.const import ImageInfo 

24 

25log = structlog.get_logger() 

26 

27 

28class OCRTool(BaseModel): 

29 event: EventSettings | None = EventSettings() 

30 ocr: OCRFieldSettings | None = None 

31 log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "INFO" 

32 image_file: CliPositionalArg[str] 

33 

34 def cli_cmd(self) -> None: 

35 structlog.configure(wrapper_class=structlog.make_filtering_bound_logger(self.log_level)) 

36 

37 image_path: Path = self.event.watch_path if self.event is not None else Path() 

38 image: Image.Image | None = Image.open(image_path / self.image_file) 

39 if self.ocr is not None: 

40 ocr_settings: OCRSettings = OCRSettings(fields={"hik_direction": self.ocr}) 

41 else: 

42 ocr_settings = OCRSettings() 

43 log.debug("ocr_files: ocr_settings->%s", ocr_settings) 

44 if image and self.event: 

45 print(scan_ocr_fields(image, self.event, ocr_settings)) # ruff: ignore[print] 

46 else: 

47 print("Image can't be loaded") # ruff: ignore[print] 

48 

49 

50class ListTool(BaseModel): 

51 event: EventSettings = EventSettings() 

52 log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "INFO" 

53 

54 def cli_cmd(self) -> None: 

55 structlog.configure(wrapper_class=structlog.make_filtering_bound_logger(self.log_level)) 

56 log.info(f"list_dir: {self.event.event} from {self.event.watch_path.resolve()}") 

57 for p in self.event.watch_path.iterdir(): 

58 results: ImageInfo | None = examine_file(p, self.event.image_name_re) 

59 if results is not None: 

60 print(f"{results.target}: timestamp={results.timestamp},ext={results.ext}") # ruff: ignore[print] 

61 

62 

63class DVLATool(BaseModel): 

64 dvla: DVLASettings = DVLASettings() 

65 test: bool = Field(default=False, description="Use DVLA UAT environment") 

66 log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "INFO" 

67 registration: CliPositionalArg[str] 

68 

69 def cli_cmd(self) -> None: 

70 structlog.configure(wrapper_class=structlog.make_filtering_bound_logger(self.log_level)) 

71 if not self.dvla.api_key: 

72 print("Error: DVLA API key required (--dvla.api_key or DVLA__API_KEY env var)") # ruff: ignore[print] 

73 return 

74 print( # ruff: ignore[print] 

75 "Caching for {} at {}".format(self.dvla.cache_ttl, "in memory" if not self.dvla.cache_dir else self.dvla.cache_dir) 

76 ) 

77 client = DVLAClient( 

78 api_key=self.dvla.api_key, 

79 cache_type=self.dvla.cache_type, 

80 cache_dir=self.dvla.cache_dir, 

81 cache_ttl=self.dvla.cache_ttl, 

82 test=self.test, 

83 ) 

84 result: dict[str, Any] = client.lookup(self.registration.upper()) 

85 print(json.dumps(result, indent=2)) # ruff: ignore[print] 

86 

87 

88class HealthcheckTool(BaseModel): 

89 max_age: int = Field(default=DEFAULT_MAX_AGE, description="Seconds since the last heartbeat before failing") 

90 

91 def cli_cmd(self) -> None: 

92 age: float | None = heartbeat_age() 

93 if age is None: 

94 print(f"UNHEALTHY: no heartbeat at {heartbeat_path()}") # ruff: ignore[print] 

95 sys.exit(1) 

96 if age > self.max_age: 

97 print(f"UNHEALTHY: heartbeat is {age:.0f}s old (limit {self.max_age}s)") # ruff: ignore[print] 

98 sys.exit(1) 

99 print(f"HEALTHY: heartbeat is {age:.0f}s old") # ruff: ignore[print] 

100 

101 

102class Tools(BaseSettings, cli_parse_args=True, cli_exit_on_error=True): 

103 model_config = SettingsConfigDict( 

104 env_nested_delimiter="__", 

105 env_ignore_empty=True, 

106 cli_avoid_json=True, 

107 ) 

108 ocr_file: CliSubCommand[OCRTool] 

109 list_dir: CliSubCommand[ListTool] 

110 dvla_lookup: CliSubCommand[DVLATool] 

111 healthcheck: CliSubCommand[HealthcheckTool] 

112 

113 def cli_cmd(self) -> None: 

114 CliApp.run_subcommand(self) 

115 

116 

117def tools() -> None: 

118 CliApp.run(model_cls=Tools)