​python_modules /
module-05 / ex1 / data_stream.py
106 commits
19-05-2026
215 lines 5.9 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    def get_name(self) -> str:
 25        return self._name
 26
 27    def get_total(self) -> int:
 28        return self._counter
 29
 30    def get_remaining(self) -> int:
 31        return len(self._storage)
 32
 33
 34class NumericProcessor(DataProcessor):
 35    def __init__(self) -> None:
 36        super().__init__("Numeric Processor")
 37
 38    def validate(self, data: Any) -> bool:
 39        def is_valid_number(d: Any) -> bool:
 40            return (
 41                isinstance(d, (int, float))
 42                and not isinstance(d, bool)
 43            )
 44        if is_valid_number(data):
 45            return True
 46        if isinstance(data, list) and data:
 47            return all(is_valid_number(d) for d in data)
 48        return False
 49
 50    def ingest(self, data: int | float | list[int | float]) -> None:
 51        if not self.validate(data):
 52            raise Exception("Improper numeric data")
 53        items = data if isinstance(data, list) else [data]
 54        for item in items:
 55            self._storage.append((self._counter, str(item)))
 56            self._counter += 1
 57
 58
 59class TextProcessor(DataProcessor):
 60    def __init__(self) -> None:
 61        super().__init__("Text Processor")
 62
 63    def validate(self, data: Any) -> bool:
 64        if isinstance(data, str):
 65            return True
 66        if isinstance(data, list) and data:
 67            return all(isinstance(d, str) for d in data)
 68        return False
 69
 70    def ingest(self, data: str | list[str]) -> None:
 71        if not self.validate(data):
 72            raise Exception("Improper text data")
 73        items = data if isinstance(data, list) else [data]
 74        for item in items:
 75            self._storage.append((self._counter, item))
 76            self._counter += 1
 77
 78
 79class LogProcessor(DataProcessor):
 80    def __init__(self) -> None:
 81        super().__init__("Log Processor")
 82
 83    def validate(self, data: Any) -> bool:
 84        def is_valid_log(d: Any) -> bool:
 85            return (
 86                isinstance(d, dict)
 87                and "log_level" in d
 88                and "log_message" in d
 89                and all(
 90                    isinstance(k, str) and isinstance(v, str)
 91                    for k, v in d.items()
 92                )
 93            )
 94        if is_valid_log(data):
 95            return True
 96        if isinstance(data, list) and data:
 97            return all(is_valid_log(d) for d in data)
 98        return False
 99
100    def ingest(self, data: dict[str, str] | list[dict[str, str]]) -> None:
101        if not self.validate(data):
102            raise Exception("Improper log data")
103        items = data if isinstance(data, list) else [data]
104        for item in items:
105            s = f"{item['log_level']}: {item['log_message']}"
106            self._storage.append((self._counter, s))
107            self._counter += 1
108
109
110class DataStream:
111    def __init__(self) -> None:
112        self._processors: list[DataProcessor] = []
113
114    def register_processor(self, proc: DataProcessor) -> None:
115        self._processors.append(proc)
116
117    def process_stream(self, stream: list[Any]) -> None:
118        for element in stream:
119            handled = False
120            for proc in self._processors:
121                if proc.validate(element):
122                    proc.ingest(element)
123                    handled = True
124                    break
125            if not handled:
126                print(
127                    f"DataStream error - Can't process element "
128                    f"in stream: {element}"
129                )
130
131    def print_processors_stats(self) -> None:
132        print("=== DataStream statistics ===")
133        if not self._processors:
134            print("No processors found, no data")
135            return
136        for proc in self._processors:
137            print(
138                f"{proc.get_name()}: "
139                f"total {proc.get_total()} items processed, "
140                f"remaining {proc.get_remaining()} on processor"
141            )
142
143
144def main() -> None:
145    print("=== Code Nexus - Data Stream ===\n")
146
147    stream = DataStream()
148
149    numeric = NumericProcessor()
150    text = TextProcessor()
151    log = LogProcessor()
152
153    print("Initialize Data Stream...")
154
155    stream.print_processors_stats()
156
157    print()
158
159    print("Registering Numeric Processor")
160    stream.register_processor(numeric)
161
162    batch = [
163        "Hello World",
164        [3.14, -1, 2.71],
165        [
166            {
167                "log_level": "WARNING",
168                "log_message": "Telnet acess! "
169                               "Use ssh instead"
170            },
171            {
172                "log_level": "INFO",
173                "log_message": "User wil is connected"
174            }
175        ],
176        42,
177        ["Hi", "five"]
178    ]
179
180    print(f"Send first batch of data on stream: {batch}")
181    stream.process_stream(batch)
182    stream.print_processors_stats()
183
184    print()
185
186    print("Registering other data processors")
187
188    stream.register_processor(text)
189    stream.register_processor(log)
190
191    print("Send the same batch again")
192    stream.process_stream(batch)
193    stream.print_processors_stats()
194
195    print()
196
197    print(
198        "Consume some elements from the data processors:"
199        "Numeric 3, Text 2, Log 1"
200    )
201
202    for _ in range(3):
203        numeric.output()
204
205    for _ in range(2):
206        text.output()
207
208    for _ in range(1):
209        log.output()
210
211    stream.print_processors_stats()
212
213
214if __name__ == "__main__":
215    main()