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

1import hashlib 

2import json 

3from abc import ABC 

4 

5 

6class Module(ABC): 

7 """ 

8 Abstract base class for any geoparser module. 

9 

10 All modules must implement this interface to be compatible 

11 with the geoparser architecture. 

12 

13 Modules focus purely on the prediction logic without database interactions. 

14 """ 

15 

16 # Module name should be defined by subclasses 

17 NAME: str = None 

18 

19 def __init__(self, **kwargs): 

20 """ 

21 Initialize a module. 

22 

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") 

28 

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)) 

32 

33 def __str__(self) -> str: 

34 """ 

35 Return a string representation of the module. 

36 

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})" 

42 

43 def __repr__(self) -> str: 

44 """ 

45 Return a developer representation of the module. 

46 

47 Returns: 

48 Same as __str__ method 

49 """ 

50 return self.__str__() 

51 

52 @property 

53 def id(self) -> str: 

54 """ 

55 Generate a deterministic ID for this module based on name and config. 

56 

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. 

60 

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]