​python_modules /
module-05 / ex0 / data_processor.py
106 commits
19-05-2026
174 lines 5.1 kB
  1from abc import ABC, abstractmethod
  2from typing import Any
  3
  4
  5class DataProcessor(ABC):
  6    def __init__(self, name: str) -> None:
  7        self._name = name
  8        self._storage: list[tuple[int, str]] = []
  9        self._counter: int = 0
 10
 11    @abstractmethod
 12    def validate(self, data: Any) -> bool:
 13        ...
 14
 15    @abstractmethod
 16    def ingest(self, data: Any) -> None:
 17        ...
 18
 19    def output(self) -> tuple[int, str]:
 20        if not self._storage:
 21            raise Exception("No data available")
 22        return self._storage.pop(0)
 23
 24
 25class NumericProcessor(DataProcessor):
 26    def __init__(self) -> None:
 27        super().__init__("Numeric Processor")
 28
 29    def validate(self, data: Any) -> bool:
 30        def is_valid_number(d: Any) -> bool:
 31            return (
 32                isinstance(d, (int, float))
 33                and not isinstance(d, bool)
 34            )
 35        if is_valid_number(data):
 36            return True
 37        if isinstance(data, list) and data:
 38            return all(is_valid_number(d) for d in data)
 39        return False
 40
 41    def ingest(self, data: int | float | list[int | float]) -> None:
 42        if not self.validate(data):
 43            raise Exception("Improper numeric data")
 44        items = data if isinstance(data, list) else [data]
 45        for item in items:
 46            self._storage.append((self._counter, str(item)))
 47            self._counter += 1
 48
 49
 50class TextProcessor(DataProcessor):
 51    def __init__(self) -> None:
 52        super().__init__("Text Processor")
 53
 54    def validate(self, data: Any) -> bool:
 55        if isinstance(data, str):
 56            return True
 57        if isinstance(data, list) and data:
 58            return all(isinstance(d, str) for d in data)
 59        return False
 60
 61    def ingest(self, data: str | list[str]) -> None:
 62        if not self.validate(data):
 63            raise Exception("Improper text data")
 64        items = data if isinstance(data, list) else [data]
 65        for item in items:
 66            self._storage.append((self._counter, item))
 67            self._counter += 1
 68
 69
 70class LogProcessor(DataProcessor):
 71    def __init__(self) -> None:
 72        super().__init__("Log Processor")
 73
 74    def validate(self, data: Any) -> bool:
 75        def is_valid_log(d: Any) -> bool:
 76            return (
 77                isinstance(d, dict)
 78                and "log_level" in d
 79                and "log_message" in d
 80                and all(
 81                    isinstance(k, str) and isinstance(v, str)
 82                    for k, v in d.items()
 83                )
 84            )
 85        if is_valid_log(data):
 86            return True
 87        if isinstance(data, list) and data:
 88            return all(is_valid_log(d) for d in data)
 89        return False
 90
 91    def ingest(self, data: dict[str, str] | list[dict[str, str]]) -> None:
 92        if not self.validate(data):
 93            raise Exception("Improper log data")
 94        items = data if isinstance(data, list) else [data]
 95        for item in items:
 96            s = f"{item['log_level']}: {item['log_message']}"
 97            self._storage.append((self._counter, s))
 98            self._counter += 1
 99
100
101def main() -> None:
102    print("=== Code Nexus - Data Processor ===\n")
103
104    # numeric processor
105    print("Testing Numeric Processor...")
106    numeric = NumericProcessor()
107    print(
108        f" Trying to validate input '42': "
109        f"{numeric.validate(42)}"
110    )
111    print(
112        f" Trying to validate input 'Hello': "
113        f"{numeric.validate('Hello')}"
114    )
115    print(
116        " Test invalid ingestion of string 'foo' "
117        "without prior validation:"
118    )
119    try:
120        numeric.ingest("foo")
121    except Exception as e:
122        print(" Got exception: ", e)
123    numeric_data: list[int | float] = [1, 2, 3, 4, 5]
124    print(f" Processing data: {numeric_data}")
125    numeric.ingest(numeric_data)
126    print(" Extracting 3 values...")
127    for _ in range(3):
128        rank, value = numeric.output()
129        print(f" Numeric value {rank}: {value}")
130
131    # text processor
132    print("\nTesting Text Processor")
133    text = TextProcessor()
134    print(
135        f" Trying to validate input '42': "
136        f"{text.validate(42)}"
137    )
138    text_data = ["Hello", "Nexus", "World"]
139    print(
140        f" Processing data: "
141        f"{text_data}"
142    )
143    text.ingest(text_data)
144    print(" Extracint 1 value...")
145    rank, value = text.output()
146    print(f" Text value {rank}: {value}")
147
148    # log processor
149    print("\nTesting Log Processor...")
150    log = LogProcessor()
151    print(
152        f" Trying to validate input 'Hello': "
153        f"{log.validate('Hello')}"
154    )
155    log_data = [
156        {
157            "log_level": "NOTICE",
158            "log_message": "Connection to server"
159        },
160        {
161            "log_level": "ERROR",
162            "log_message": "Unauthorized access!!"
163        }
164    ]
165    print(f" Processing data: {log_data}")
166    log.ingest(log_data)
167    print(" Extracting 2 values...")
168    for _ in range(2):
169        rank, value = log.output()
170        print(f" Log entry {rank}: {value}")
171
172
173if __name__ == "__main__":
174    main()