Coverage for geoparser/modules/module.py: 100%
19 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-20 18:08 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-20 18:08 +0000
1import hashlib
2import json
3from abc import ABC
6class Module(ABC):
7 """
8 Abstract base class for any geoparser module.
10 All modules must implement this interface to be compatible
11 with the geoparser architecture.
13 Modules focus purely on the prediction logic without database interactions.
14 """
16 # Module name should be defined by subclasses
17 NAME: str = None
19 def __init__(self, **kwargs):
20 """
21 Initialize a module.
23 Args:
24 **kwargs: Configuration parameters for this module
25 """
26 if self.NAME is None:
27 raise ValueError("Module must define a NAME class attribute")
29 self.name = self.NAME
30 # Normalize config using JSON round-trip to ensure consistent serialization
31 self.config = json.loads(json.dumps(kwargs, sort_keys=True))
33 def __str__(self) -> str:
34 """
35 Return a string representation of the module.
37 Returns:
38 String with module name and config parameters
39 """
40 config_str = ", ".join(f"{k}={repr(v)}" for k, v in self.config.items())
41 return f"{self.name}({config_str})"
43 def __repr__(self) -> str:
44 """
45 Return a developer representation of the module.
47 Returns:
48 Same as __str__ method
49 """
50 return self.__str__()
52 @property
53 def id(self) -> str:
54 """
55 Generate a deterministic ID for this module based on name and config.
57 This ID is computed by hashing the module's string representation,
58 ensuring that modules with the same name and config get the same ID,
59 while modules with different configs get unique IDs.
61 Returns:
62 String ID uniquely identifying this module configuration
63 """
64 # Hash the string representation to create a short, deterministic ID
65 hash_object = hashlib.sha256(str(self).encode())
66 # Use first 8 characters of hex digest for a reasonably short ID
67 return hash_object.hexdigest()[:8]