|
| 1 | +import collections |
| 2 | +from typing import Type, AsyncIterator, List |
| 3 | + |
| 4 | +from dffml.base import config, BaseConfig |
| 5 | +from dffml.db.base import BaseDatabase, Condition |
| 6 | +from dffml.record import Record |
| 7 | +from dffml.source.source import BaseSource, BaseSourceContext |
| 8 | +from dffml.util.entrypoint import entrypoint |
| 9 | + |
| 10 | + |
| 11 | +@config |
| 12 | +class DbSourceConfig(BaseConfig): |
| 13 | + db: BaseDatabase |
| 14 | + table_name: str |
| 15 | + model_columns: List[str] |
| 16 | + |
| 17 | + |
| 18 | +class DbSourceContext(BaseSourceContext): |
| 19 | + async def update(self, record: Record): |
| 20 | + model_columns = self.parent.config.model_columns |
| 21 | + key_value_pairs = collections.OrderedDict() |
| 22 | + for key in model_columns: |
| 23 | + if key.startswith("feature_"): |
| 24 | + modified_key = key.replace("feature_", "") |
| 25 | + key_value_pairs[key] = record.data.features[modified_key] |
| 26 | + elif "_value" in key: |
| 27 | + target = key.replace("_value", "") |
| 28 | + if record.data.prediction: |
| 29 | + key_value_pairs[key] = record.data.prediction[target][ |
| 30 | + "value" |
| 31 | + ] |
| 32 | + else: |
| 33 | + key_value_pairs[key] = "undetermined" |
| 34 | + elif "_confidence" in key: |
| 35 | + target = key.replace("_confidence", "") |
| 36 | + if record.data.prediction: |
| 37 | + key_value_pairs[key] = record.data.prediction[target][ |
| 38 | + "confidence" |
| 39 | + ] |
| 40 | + else: |
| 41 | + key_value_pairs[key] = 1 |
| 42 | + else: |
| 43 | + key_value_pairs[key] = record.data.__dict__[key] |
| 44 | + async with self.parent.db() as db_ctx: |
| 45 | + await db_ctx.insert_or_update( |
| 46 | + self.parent.config.table_name, key_value_pairs |
| 47 | + ) |
| 48 | + self.logger.debug("update: %s", await self.record(record.key)) |
| 49 | + |
| 50 | + async def records(self) -> AsyncIterator[Record]: |
| 51 | + async with self.parent.db() as db_ctx: |
| 52 | + async for result in db_ctx.lookup(self.parent.config.table_name): |
| 53 | + yield self.convert_to_record(result) |
| 54 | + |
| 55 | + def convert_to_record(self, result): |
| 56 | + modified_record = { |
| 57 | + "key": "", |
| 58 | + "data": {"features": {}, "prediction": {}}, |
| 59 | + } |
| 60 | + for key, value in result.items(): |
| 61 | + if key.startswith("feature_"): |
| 62 | + modified_record["data"]["features"][ |
| 63 | + key.replace("feature_", "") |
| 64 | + ] = value |
| 65 | + elif ("_value" in key) or ("_confidence" in key): |
| 66 | + target = key.replace("_value", "").replace("_confidence", "") |
| 67 | + modified_record["data"]["prediction"][target] = { |
| 68 | + "value": result[target + "_value"], |
| 69 | + "confidence": result[target + "_confidence"], |
| 70 | + } |
| 71 | + else: |
| 72 | + modified_record[key] = value |
| 73 | + return Record(modified_record["key"], data=modified_record["data"]) |
| 74 | + |
| 75 | + async def record(self, key: str): |
| 76 | + record = Record(key) |
| 77 | + async with self.parent.db() as db_ctx: |
| 78 | + try: |
| 79 | + row = await db_ctx.lookup( |
| 80 | + self.parent.config.table_name, |
| 81 | + cols=None, # None turns into *. We want all rows |
| 82 | + conditions=[[Condition("key", "=", key)]], |
| 83 | + ).__anext__() |
| 84 | + except StopAsyncIteration: |
| 85 | + # This would happen if there is no matching row, so the async generator reached the end |
| 86 | + return record |
| 87 | + |
| 88 | + if row is not None: |
| 89 | + features = {} |
| 90 | + predictions = {} |
| 91 | + for key, value in row.items(): |
| 92 | + if key.startswith("feature_"): |
| 93 | + features[key.replace("feature_", "")] = value |
| 94 | + elif "_value" in key: |
| 95 | + target = key.replace("_value", "") |
| 96 | + predictions[target] = { |
| 97 | + "value": row[target + "_value"], |
| 98 | + "confidence": row[target + "_confidence"], |
| 99 | + } |
| 100 | + record.merge( |
| 101 | + Record( |
| 102 | + row["key"], |
| 103 | + data={"features": features, "prediction": predictions}, |
| 104 | + ) |
| 105 | + ) |
| 106 | + return record |
| 107 | + |
| 108 | + |
| 109 | +@entrypoint("db") |
| 110 | +class DbSource(BaseSource): |
| 111 | + CONFIG = DbSourceConfig |
| 112 | + CONTEXT = DbSourceContext |
| 113 | + |
| 114 | + def __init__(self, cfg: Type[BaseConfig]) -> None: |
| 115 | + super().__init__(cfg) |
| 116 | + |
| 117 | + async def __aenter__(self) -> "DbSource": |
| 118 | + self.db = await self.config.db.__aenter__() |
| 119 | + return self |
| 120 | + |
| 121 | + async def __aexit__(self, exc_type, exc_value, traceback): |
| 122 | + await self.db.__aexit__(exc_type, exc_value, traceback) |
0 commit comments