jspaulsen commited on
Commit
ef5b92c
·
verified ·
1 Parent(s): 8a1569c

Create metadata.py

Browse files
Files changed (1) hide show
  1. metadata.py +127 -0
metadata.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import csv
3
+ from pathlib import Path
4
+ import threading
5
+ from typing import Any, Protocol, runtime_checkable
6
+
7
+
8
+ @runtime_checkable
9
+ class Hashable(Protocol):
10
+ def to_dict(self) -> dict: ...
11
+ def column_names(self) -> list[str]: ...
12
+ def get(self, key: str) -> str | None: ...
13
+ def __getitem__(self, key: str) -> str: ...
14
+ def __setitem__(self, key: str, value: Any) -> None: ...
15
+ def __contains__(self, key: str) -> bool: ...
16
+
17
+ @classmethod
18
+ def from_dict(cls, data: dict) -> Hashable: ...
19
+
20
+
21
+ class MetadataItem(Hashable):
22
+ def __init__(self, **kwargs) -> None:
23
+ self.data = kwargs
24
+
25
+ def get(self, key: str) -> str | None:
26
+ return self.data.get(key, None)
27
+
28
+ def to_dict(self) -> dict:
29
+ return self.data
30
+
31
+ def column_names(self) -> list[str]:
32
+ return list(self.data.keys())
33
+
34
+ @classmethod
35
+ def from_dict(cls, data: dict) -> MetadataItem:
36
+ return cls(**data)
37
+
38
+ def __getitem__(self, key: str) -> str:
39
+ return self.data[key]
40
+
41
+ def __setitem__(self, key: str, value: str | float) -> None:
42
+ self.data[key] = value
43
+
44
+ def __contains__(self, key: str) -> bool:
45
+ return key in self.data
46
+
47
+
48
+ class LockedMetadata:
49
+ def __init__(
50
+ self,
51
+ key_field: str,
52
+ existing: list[Hashable] | None = None,
53
+ ) -> None:
54
+ self.key_field = key_field
55
+ self.lock = threading.Lock()
56
+ existing = existing or []
57
+ self.metadata: dict[str, Hashable] = {}
58
+
59
+ for item in existing:
60
+ if not isinstance(item, Hashable):
61
+ raise TypeError(f"Item must be of type {Hashable.__name__}, got {type(item).__name__}.")
62
+
63
+ key = item.get(self.key_field)
64
+
65
+ if key is None:
66
+ raise ValueError(f"Item must have a '{self.key_field}' field.")
67
+
68
+ self.metadata[key] = item
69
+
70
+ def add(self, item: Hashable) -> Hashable | None:
71
+ replaced: Hashable | None = None
72
+
73
+ with self.lock:
74
+ key = item.get(self.key_field)
75
+
76
+ if key is None:
77
+ raise ValueError(f"Item must have a '{self.key_field}' field.")
78
+
79
+ if key in self.metadata:
80
+ replaced = self.metadata[key]
81
+
82
+ self.metadata[key] = item
83
+
84
+ return replaced
85
+
86
+ def get(self, key: str) -> Hashable | None:
87
+ with self.lock:
88
+ return self.metadata.get(key, None)
89
+
90
+ def __contains__(self, item: str) -> bool:
91
+ with self.lock:
92
+ return item in self.metadata
93
+
94
+ def __iter__(self):
95
+ with self.lock:
96
+ return iter(self.metadata.values())
97
+
98
+ def save(self, file: Path) -> None:
99
+ with self.lock:
100
+ items = list(self.metadata.values())
101
+
102
+ if not items:
103
+ return
104
+
105
+ item = items[0]
106
+
107
+ with open(file, 'w', newline='', encoding='utf-8') as f:
108
+ writer = csv.DictWriter(f, fieldnames=item.column_names())
109
+ writer.writeheader()
110
+ writer.writerows([item.to_dict() for item in items])
111
+
112
+ @classmethod
113
+ def load(
114
+ cls,
115
+ file: Path,
116
+ key_field: str,
117
+ item_type: type[Hashable] = MetadataItem,
118
+ ) -> LockedMetadata:
119
+ items = []
120
+
121
+ with open(file, 'r', newline='', encoding='utf-8') as f:
122
+ reader = csv.DictReader(f)
123
+
124
+ for row in reader:
125
+ items.append(item_type.from_dict(row))
126
+
127
+ return cls(existing=items, key_field=key_field)