gedcom-x 0.5.2__py3-none-any.whl → 0.5.6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17,17 +17,18 @@ class PlaceDescription(Subject):
17
17
  identifier = "http://gedcomx.org/v1/PlaceDescription"
18
18
  version = 'http://gedcomx.org/conceptual-model/v1'
19
19
 
20
- def __init__(self, id: str =None,
20
+ def __init__(self, id: Optional[str] =None,
21
21
  lang: str = 'en',
22
- sources: Optional[List[SourceReference]] = [],
23
- analysis: Resource = None, notes: Optional[List[Note]] =[],
24
- confidence: ConfidenceLevel = None,
25
- attribution: Attribution = None,
26
- extracted: bool = None,
27
- evidence: List[EvidenceReference] = None,
28
- media: List[SourceReference] = [],
29
- identifiers: List[IdentifierList] = [],
30
- names: List[TextValue] = [],
22
+ sources: Optional[List[SourceReference]] = None,
23
+ analysis: Optional[Resource] = None,
24
+ notes: Optional[List[Note]] =None,
25
+ confidence: Optional[ConfidenceLevel] = None,
26
+ attribution: Optional[Attribution] = None,
27
+ extracted: Optional[bool] = None,
28
+ evidence: Optional[List[EvidenceReference]] = None,
29
+ media: Optional[List[SourceReference]] = None,
30
+ identifiers: Optional[IdentifierList] = None,
31
+ names: Optional[List[TextValue]] = None,
31
32
  type: Optional[str] = None,
32
33
  place: Optional[URI] = None,
33
34
  jurisdiction: Optional["Resource | PlaceDescription"] = None, # PlaceDescription
@@ -35,6 +36,7 @@ class PlaceDescription(Subject):
35
36
  longitude: Optional[float] = None,
36
37
  temporalDescription: Optional[Date] = None,
37
38
  spatialDescription: Optional[Resource] = None,) -> None:
39
+
38
40
  super().__init__(id, lang, sources, analysis, notes, confidence, attribution, extracted, evidence, media, identifiers)
39
41
  self.names = names
40
42
  self.type = type
@@ -47,8 +49,8 @@ class PlaceDescription(Subject):
47
49
 
48
50
  @property
49
51
  def _as_dict_(self):
50
- place_description_dict = super()._as_dict_
51
- place_description_dict.update({
52
+ type_as_dict = super()._as_dict_
53
+ type_as_dict.update({
52
54
  "names": [n for n in self.names] if self.names else None,
53
55
  "type": self.type if self.type else None,
54
56
  "place": self.place._as_dict_ if self.place else None,
@@ -56,6 +58,13 @@ class PlaceDescription(Subject):
56
58
  "latitude": float(self.latitide) if self.latitide else None,
57
59
  "longitude": float(self.longitute) if self.longitute else None,
58
60
  "temporalDescription": self.temporalDescription if self.temporalDescription else None,
59
- "spatialDescription": self.spacialDescription._as_dict_ if self.temporalDescription else None
61
+ "spatialDescription": self.spacialDescription._as_dict_ if self.spacialDescription else None
60
62
  })
61
- return Serialization.serialize_dict(place_description_dict)
63
+ return Serialization.serialize_dict(type_as_dict)
64
+
65
+ @classmethod
66
+ def _from_json_(cls, data: dict):
67
+ """
68
+ Create a PlaceDescription instance from a JSON-dict (already parsed).
69
+ """
70
+ return Serialization.deserialize(data, PlaceDescription)
gedcomx/PlaceReference.py CHANGED
@@ -7,27 +7,24 @@ class PlaceReference:
7
7
  identifier = 'http://gedcomx.org/v1/PlaceReference'
8
8
  version = 'http://gedcomx.org/conceptual-model/v1'
9
9
 
10
- def __init__(self, original: Optional[str], descriptionRef: Optional[Resource]) -> None:
10
+ def __init__(self,
11
+ original: Optional[str] = None,
12
+ description: Optional[Resource] = None) -> None:
11
13
  self.original = original
12
- self.descriptionRef = descriptionRef
14
+ self.description = description
13
15
 
14
16
  @property
15
17
  def _as_dict_(self):
16
- place_reference_dict = {
18
+ type_as_dict = {
17
19
  'original': self.original,
18
- 'descriptionRef': self.descriptionRef._as_dict_ if isinstance(self.descriptionRef,Resource) else Resource(target=self.descriptionRef)._as_dict_
20
+ 'description': self.description._as_dict_ if self.description else None
19
21
  }
20
- return Serialization.serialize_dict(place_reference_dict)
22
+ return Serialization.serialize_dict(type_as_dict)
23
+
24
+ @classmethod
25
+ def _from_json_(cls, data):
26
+
27
+ return Serialization.deserialize(data, PlaceReference)
21
28
 
22
- def ensure_list(val):
23
- if val is None:
24
- return []
25
- return val if isinstance(val, list) else [val]
26
29
 
27
- # PlaceReference
28
- PlaceReference._from_json_ = classmethod(lambda cls, data: PlaceReference(
29
- original=data.get('original'),
30
- descriptionRef=Resource._from_json_(data['description']) if data.get('description') else None
31
- ))
32
30
 
33
-
gedcomx/Relationship.py CHANGED
@@ -35,12 +35,15 @@ class Relationship(Subject):
35
35
  person2 (Person): Second Person in Relationship
36
36
 
37
37
  Raises:
38
- ValueError: If `id` is not a valid UUID.
38
+
39
39
  """
40
40
  identifier = 'http://gedcomx.org/v1/Relationship'
41
41
  version = 'http://gedcomx.org/conceptual-model/v1'
42
42
 
43
- def __init__(self,
43
+ def __init__(self,
44
+ person1: Optional[Person | Resource] = None,
45
+ person2: Optional[Person | Resource] = None,
46
+ facts: Optional[List[Fact]] = None,
44
47
  id: Optional[str] = None,
45
48
  lang: Optional[str] = None,
46
49
  sources: Optional[List[SourceReference]] = None,
@@ -53,74 +56,40 @@ class Relationship(Subject):
53
56
  media: Optional[List[SourceReference]] = None,
54
57
  identifiers: Optional[List[Identifier]] = None,
55
58
  type: Optional[RelationshipType] = None,
56
- person1: Optional[Person | Resource] = None,
57
- person2: Optional[Person | Resource] = None,
58
- facts: Optional[List[Fact]] = None) -> None:
59
+ ) -> None:
59
60
 
60
61
  # Call superclass initializer if required
61
62
  super().__init__(id, lang, sources, analysis, notes, confidence, attribution, extracted, evidence, media, identifiers)
62
63
 
63
- # Initialize optional parameters with default empty lists if None
64
- #self.sources = sources if sources is not None else []
65
- #self.notes = notes if notes is not None else []
66
- #self.evidence = evidence if evidence is not None else []
67
- #self.media = media if media is not None else []
68
- #self.identifiers = identifiers if identifiers is not None else []
69
- #self.facts = facts if facts is not None else []
70
-
71
- # Initialize other attributes
72
64
  self.type = type
73
65
  self.person1 = person1
74
66
  self.person2 = person2
75
- self.facts = facts if facts else None
67
+ self.facts = facts if facts else []
76
68
 
69
+ def add_fact(self,fact: Fact):
70
+ if fact is not None and isinstance(fact,Fact):
71
+ for existing_fact in self.facts:
72
+ if fact == existing_fact:
73
+ return
74
+ self.facts.append(fact)
75
+ else:
76
+ raise TypeError(f"Expected type 'Fact' recieved type {type(fact)}")
77
+
77
78
  @property
78
79
  def _as_dict_(self):
79
- return serialize_to_dict(self, {
80
+ type_as_dict = super()._as_dict_
81
+ type_as_dict.update({
80
82
  "type": self.type.value if isinstance(self.type, RelationshipType) else self.type,
81
- "person1": self.person1.uri,
82
- "person2": self.person2.uri,
83
+ "person1": self.person1._as_dict_ if self.person1 else None,
84
+ "person2": self.person2._as_dict_ if self.person2 else None,
83
85
  "facts": [fact for fact in self.facts] if self.facts else None
84
86
  })
87
+ return Serialization.serialize_dict(type_as_dict)
85
88
 
86
89
  @classmethod
87
90
  def _from_json_(cls, data: dict):
88
91
  """
89
- Create a Relationship instance from a JSON-dict (already parsed).
92
+ Create a Person instance from a JSON-dict (already parsed).
90
93
  """
91
- def ensure_list(value):
92
- if value is None:
93
- return []
94
- if isinstance(value, list):
95
- return value
96
- return [value] # wrap single item in list
97
-
98
- # Basic scalar fields (adjust as needed)
99
- id_ = data.get('id')
100
- type_ = data.get('type')
101
- extracted = data.get('extracted', None)
102
- private = data.get('private', None)
103
-
104
- # Complex singletons (adjust as needed)
105
- person1 = Resource.from_url(data.get('person1')['resource']) if data.get('person1') else None
106
- person2 = Resource.from_url(data.get('person2')['resource']) if data.get('person2') else None
107
- facts = [Fact._from_json_(o) for o in ensure_list(data.get('facts'))]
108
- sources = [SourceReference._from_json_(o) for o in ensure_list(data.get('sources'))]
109
- notes = [Note._from_json_(o) for o in ensure_list(data.get('notes'))]
110
-
111
- # Build the instance
112
- inst = cls(
113
- id = id_,
114
- type = type_,
115
- extracted = extracted,
116
- #private = private, #TODO Has this been added?
117
- person1 = person1,
118
- person2 = person2,
119
- facts = facts,
120
- sources = sources,
121
- notes = notes
122
- )
123
-
124
- return inst
125
-
94
+ return Serialization.deserialize(data, Relationship)
126
95
 
gedcomx/Resource.py CHANGED
@@ -1,5 +1,6 @@
1
1
  from typing import List, Optional
2
2
 
3
+
3
4
  from .URI import URI
4
5
 
5
6
  class Resource:
@@ -16,7 +17,7 @@ class Resource:
16
17
  """
17
18
  def __init__(self,uri: Optional[URI|str] = None, id:Optional[str] = None,top_lvl_object: Optional[object] = None,target= None) -> None:
18
19
 
19
- self.resource = URI.from_url(uri.value)
20
+ self.resource = URI.from_url(uri.value) if isinstance(uri,URI) else URI.from_url(uri) if isinstance(uri,str) else None
20
21
  self.Id = id
21
22
 
22
23
  self.type = None
@@ -31,9 +32,23 @@ class Resource:
31
32
 
32
33
  @property
33
34
  def _as_dict_(self):
34
- return {'resource':self.resource.value,
35
+ from .Serialization import Serialization
36
+ typ_as_dict = {'resource':self.resource.value if self.resource else None,
35
37
  'resourceId':self.Id}
38
+ return Serialization.serialize_dict(typ_as_dict)
39
+
40
+ @classmethod
41
+ def _from_json_(cls,data):
42
+ # TODO This is not used but taken care of in Serialization
43
+ r = Resource(uri=data.get('resource'),id=data.get('resourceId',None))
44
+ #return r
36
45
 
46
+ def __repr__(self) -> str:
47
+ return f"Resource(uri={self.resource}, id={self.Id}, target={self.target})"
48
+
49
+ def __str__(self) -> str:
50
+ return f"{self.resource}{f', id={self.Id}' if self.Id else ''}"
51
+
37
52
  def get_resource_as_dict(value):
38
53
  """
39
54
  If value is truthy:
@@ -58,4 +73,3 @@ def get_resource_as_dict(value):
58
73
  print((f"value: {value} as inproper attributes"))
59
74
  exit()
60
75
 
61
-
gedcomx/Serialization.py CHANGED
@@ -1,42 +1,25 @@
1
1
  from typing import Dict
2
2
 
3
+ from .Logging import get_logger
4
+
5
+ log = get_logger(__name__)
6
+ log.setLevel("DEBUG")
7
+ log.info("Logger initialized.")
8
+
3
9
  from collections.abc import Sized
10
+ from typing import Any, get_origin, get_args, List, Set, Tuple, Dict, Union, ForwardRef, Annotated
11
+ import types
12
+
13
+ import enum
14
+ from .Resource import Resource
15
+ from .Identifier import IdentifierList
16
+ from .URI import URI
4
17
 
18
+ _PRIMITIVES = (str, int, float, bool, type(None))
5
19
 
6
20
  def _has_parent_class(obj) -> bool:
7
21
  return hasattr(obj, '__class__') and hasattr(obj.__class__, '__bases__') and len(obj.__class__.__bases__) > 0
8
22
 
9
- def serialize_to_dict(obj,class_values:Dict,ignore_null=True):
10
- def _serialize(value):
11
- if isinstance(value, (str, int, float, bool, type(None))):
12
- return value
13
- elif isinstance(value, dict):
14
- return {k: _serialize(v) for k, v in value.items()}
15
- elif isinstance(value, (list, tuple, set)):
16
- return [_serialize(v) for v in value]
17
- elif hasattr(value, "_as_dict_"):
18
- return value._as_dict_
19
- else:
20
- return str(value) # fallback for unknown objects
21
-
22
- values_dict = {}
23
- if _has_parent_class(obj):
24
- values_dict.update(super(obj.__class__, obj)._as_dict_)
25
- if class_values:
26
- values_dict.update(class_values)
27
- # Serialize and exclude None values
28
-
29
- empty_fields = []
30
- for key, value in values_dict.items():
31
- if value is not None:
32
- values_dict[key] = _serialize(value)
33
- else:
34
- empty_fields.append(key)
35
-
36
- for key in empty_fields:
37
- del values_dict[key]
38
-
39
- return values_dict
40
23
 
41
24
  class Serialization:
42
25
 
@@ -78,3 +61,341 @@ class Serialization:
78
61
  if v is not None and not (isinstance(v, Sized) and len(v) == 0)
79
62
  }
80
63
  return {}
64
+
65
+ @staticmethod
66
+ def _coerce_value(value: Any, typ: Any) -> Any:
67
+ """Coerce `value` to `typ`:
68
+ - primitives: pass through
69
+ - containers: recurse into elements
70
+ - objects: call typ._from_json_(dict) if available and value is dict
71
+ - already-instantiated objects of typ: pass through
72
+ - otherwise: return value unchanged
73
+ """
74
+ def is_enum_type(T) -> bool:
75
+ """Return True if T (possibly a typing construct) is or contains an Enum type."""
76
+ origin = get_origin(T)
77
+
78
+ # Unwrap Union/Optional/PEP 604 (A | B)
79
+ if origin in (Union, types.UnionType):
80
+ return any(is_enum_type(a) for a in get_args(T))
81
+
82
+ # Unwrap Annotated[T, ...]
83
+ if origin is Annotated:
84
+ return is_enum_type(get_args(T)[0])
85
+
86
+ # Resolve forward refs / strings if you use them
87
+ if isinstance(T, ForwardRef):
88
+ T = globals().get(T.__forward_arg__, T)
89
+ if isinstance(T, str):
90
+ T = globals().get(T, T)
91
+
92
+ # Finally check enum-ness
93
+ try:
94
+ return issubclass(T, enum.Enum)
95
+ except TypeError:
96
+ return False # not a class (e.g., typing.List[int], etc.)
97
+ log.debug(f"Coercing value '{value}' of type '{type(value).__name__}' to '{typ}'")
98
+
99
+ def _resolve(t):
100
+ # resolve ForwardRef('Resource') -> actual object if already in globals()
101
+ if isinstance(t, ForwardRef):
102
+ return globals().get(t.__forward_arg__, t)
103
+ return t
104
+
105
+ if is_enum_type(typ):
106
+ log.debug(f"Enum type detected: {typ}")
107
+ return typ(value) # cast to enum
108
+
109
+ origin = get_origin(typ)
110
+ if origin in (Union, types.UnionType):
111
+ args = tuple(_resolve(a) for a in get_args(typ))
112
+ else:
113
+ args = (_resolve(typ),)
114
+ log.debug(f"Origin: {origin}, args: {args}")
115
+
116
+ if Resource in args and isinstance(value, dict):
117
+ if Resource in args:
118
+ log.info(f"Deserializing Resource from value: {value}")
119
+ return Resource(uri=value.get('resource'), id=value.get('resourceId', None))
120
+
121
+ if isinstance(value, _PRIMITIVES):
122
+ if Resource in args:
123
+ log.info(f"Deserializing Resource from value: {value}")
124
+ return Resource(uri=value)
125
+ if URI in args:
126
+ log.info(f"Deserializing URI from value: {value}")
127
+ return URI.from_url(value)
128
+ return value
129
+
130
+ if IdentifierList in args:
131
+ log.error(f"Deserializing IdentifierList from value: {value}")
132
+ return IdentifierList._from_json_(value)
133
+
134
+ if origin in (list, List):
135
+ elem_args = get_args(typ) # NOT get_args(args)
136
+ elem_t = elem_args[0] if elem_args else Any
137
+ log.debug(f"List: {typ}, elem={elem_t}")
138
+ return [Serialization._coerce_value(v, elem_t) for v in (value or [])]
139
+
140
+ if origin in (set, Set):
141
+ (elem_t,) = args or (Any,)
142
+ return { Serialization._coerce_value(v, elem_t) for v in (value or []) }
143
+
144
+ if origin in (tuple, Tuple):
145
+ if not args:
146
+ return tuple(value)
147
+ if len(args) == 2 and args[1] is Ellipsis: # Tuple[T, ...]
148
+ elem_t = args[0]
149
+ return tuple(Serialization._coerce_value(v, elem_t) for v in (value or []))
150
+ return tuple(Serialization._coerce_value(v, t) for v, t in zip(value, args))
151
+
152
+ if origin in (dict, Dict):
153
+ k_t, v_t = args or (Any, Any)
154
+ return {
155
+ Serialization._coerce_value(k, k_t): Serialization._coerce_value(v, v_t)
156
+ for k, v in (value or {}).items()
157
+ }
158
+
159
+ # If `typ` has _from_json_ and value is a dict, use it
160
+ if hasattr(typ, "_from_json_") and isinstance(value, dict):
161
+ log.info(f"Deserializing {typ} from json method with value: {value}")
162
+ return typ._from_json_(value)
163
+
164
+ # If already the right type, keep it
165
+ try:
166
+ if isinstance(value, typ):
167
+ return value
168
+ except TypeError:
169
+ log.debug(f"Could not coerce value '{value}' to type '{typ}'")
170
+ pass # `typ` may be a typing construct not valid for isinstance
171
+
172
+ # Fallback: leave as-is
173
+ log.debug(f"Returning '{type(value)}' type")
174
+ return value
175
+
176
+ @staticmethod
177
+ def get_class_fields(cls_name) -> Dict:
178
+ from typing import List, Optional
179
+ from gedcomx.Attribution import Attribution
180
+ from gedcomx.Document import Document , DocumentType, TextType
181
+ from gedcomx.Note import Note
182
+ from gedcomx.Resource import Resource
183
+ from gedcomx.SourceReference import SourceReference
184
+ from gedcomx.extensions.rs10.rsLink import _rsLinkList
185
+ from gedcomx.Conclusion import ConfidenceLevel
186
+ from gedcomx.EvidenceReference import EvidenceReference
187
+ from gedcomx.Identifier import IdentifierList
188
+ from gedcomx.Gender import Gender, GenderType
189
+ from gedcomx.Fact import Fact
190
+ from gedcomx.Name import Name
191
+ from gedcomx.URI import URI
192
+ from gedcomx.Qualifier import Qualifier
193
+ from gedcomx.PlaceDescription import PlaceDescription
194
+ from gedcomx.PlaceReference import PlaceReference
195
+ from gedcomx.Person import Person
196
+ from gedcomx.Relationship import Relationship, RelationshipType
197
+ from gedcomx.Identifier import Identifier
198
+ from gedcomx.Date import Date
199
+ from gedcomx.TextValue import TextValue
200
+ from gedcomx.Address import Address
201
+ from gedcomx.OnlineAccount import OnlineAccount
202
+ from gedcomx.Event import Event, EventType, EventRole
203
+ from .SourceDescription import SourceDescription
204
+
205
+ fields = { 'Conclusion' : {
206
+ "id": str,
207
+ "lang": str,
208
+ "sources": List["SourceReference"],
209
+ "analysis": Document | Resource,
210
+ "notes": List[Note],
211
+ "confidence": ConfidenceLevel,
212
+ "attribution": Attribution,
213
+ "uri": "Resource",
214
+ "max_note_count": int,
215
+ "links": _rsLinkList
216
+ },
217
+ 'Subject' : {
218
+ "id": str,
219
+ "lang": str,
220
+ "sources": List["SourceReference"],
221
+ "analysis": Resource,
222
+ "notes": List["Note"],
223
+ "confidence": ConfidenceLevel,
224
+ "attribution": Attribution,
225
+ "extracted": bool,
226
+ "evidence": List[EvidenceReference],
227
+ "media": List[SourceReference],
228
+ "identifiers": IdentifierList,
229
+ "uri": Resource,
230
+ "links": _rsLinkList
231
+ },
232
+ 'Person' : {
233
+ "id": str,
234
+ "lang": str,
235
+ "sources": List[SourceReference],
236
+ "analysis": Resource,
237
+ "notes": List[Note],
238
+ "confidence": ConfidenceLevel,
239
+ "attribution": Attribution,
240
+ "extracted": bool,
241
+ "evidence": List[EvidenceReference],
242
+ "media": List[SourceReference],
243
+ "identifiers": IdentifierList,
244
+ "private": bool,
245
+ "gender": Gender,
246
+ "names": List[Name],
247
+ "facts": List[Fact],
248
+ "living": bool,
249
+ "links": _rsLinkList,
250
+ 'uri': Resource
251
+ },
252
+ 'SourceReference' : {
253
+ "description": SourceDescription | URI | Resource,
254
+ "descriptionId": str,
255
+ "attribution": Attribution,
256
+ "qualifiers": List[Qualifier],
257
+ },
258
+ 'Attribution' : {
259
+ "contributor": Resource | Attribution,
260
+ "modified": str,
261
+ "changeMessage": str,
262
+ "creator": Resource | Attribution,
263
+ "created": str
264
+ },
265
+ 'Gender' : {
266
+ "id": str,
267
+ "lang": str,
268
+ "sources": List[SourceReference],
269
+ "analysis": Resource,
270
+ "notes": List[Note],
271
+ "confidence": ConfidenceLevel,
272
+ "attribution": Attribution,
273
+ "type": GenderType,
274
+ },
275
+ 'PlaceReference' : {
276
+ "original": str,
277
+ "description": PlaceDescription | URI,
278
+ },
279
+ 'Relationship' : {
280
+ "id": str,
281
+ "lang": str,
282
+ "sources": List[SourceReference],
283
+ "analysis": Document | Resource,
284
+ "notes": List[Note],
285
+ "confidence": ConfidenceLevel,
286
+ "attribution": Attribution,
287
+ "extracted": bool,
288
+ "evidence": List[EvidenceReference],
289
+ "media": List[SourceReference],
290
+ "identifiers": IdentifierList,
291
+ "type": RelationshipType,
292
+ "person1": Person | Resource,
293
+ "person2": Person | Resource,
294
+ "facts": List[Fact],
295
+ },
296
+ 'Document' : {
297
+ "id": str,
298
+ "lang": str,
299
+ "sources": List[SourceReference],
300
+ "analysis": Resource,
301
+ "notes": List[Note],
302
+ "confidence": ConfidenceLevel,
303
+ "attribution": Attribution,
304
+ "type": DocumentType,
305
+ "extracted": bool,
306
+ "textType": TextType,
307
+ "text": str,
308
+ },
309
+ 'PlaceDescription' : {
310
+ "id": str,
311
+ "lang": str,
312
+ "sources": List[SourceReference],
313
+ "analysis": Resource,
314
+ "notes": List[Note],
315
+ "confidence": ConfidenceLevel,
316
+ "attribution": Attribution,
317
+ "extracted": bool,
318
+ "evidence": List[EvidenceReference],
319
+ "media": List[SourceReference],
320
+ "identifiers": List[IdentifierList],
321
+ "names": List[TextValue],
322
+ "type": str,
323
+ "place": URI,
324
+ "jurisdiction": Resource | PlaceDescription,
325
+ "latitude": float,
326
+ "longitude": float,
327
+ "temporalDescription": Date,
328
+ "spatialDescription": Resource,
329
+ },
330
+ "Agent" : {
331
+ "id": str,
332
+ "identifiers": IdentifierList,
333
+ "names": List[TextValue],
334
+ "homepage": URI,
335
+ "openid": URI,
336
+ "accounts": List[OnlineAccount],
337
+ "emails": List[URI],
338
+ "phones": List[URI],
339
+ "addresses": List[Address],
340
+ "person": object | Resource, # intended to be Person | Resource
341
+ # "xnotes": List[Note], # commented out in your __init__
342
+ "attribution": object, # for GEDCOM5/7 compatibility
343
+ "uri": URI | Resource,
344
+ },
345
+ 'Event' : {
346
+ "id": str,
347
+ "lang": str,
348
+ "sources": List[SourceReference],
349
+ "analysis": Resource,
350
+ "notes": List[Note],
351
+ "confidence": ConfidenceLevel,
352
+ "attribution": Attribution,
353
+ "extracted": bool,
354
+ "evidence": List[EvidenceReference],
355
+ "media": List[SourceReference],
356
+ "identifiers": List[Identifier],
357
+ "type": EventType,
358
+ "date": Date,
359
+ "place": PlaceReference,
360
+ "roles": List[EventRole],
361
+ }
362
+
363
+ }
364
+
365
+
366
+ return fields[cls_name] if cls_name in fields else {}
367
+
368
+ @staticmethod
369
+ def deserialize(data: dict[str, Any], class_type) -> Any:
370
+ """
371
+ Deserialize `data` according to `fields` (field -> type).
372
+ - Primitives are assigned directly.
373
+ - Objects use `type._from_json_(dict)` when present.
374
+ - Lists/Sets/Tuples/Dicts are recursively processed.
375
+ Returns (result, unknown_keys).
376
+ """
377
+ log.debug(f"Deserializing '{data}' into '{class_type.__name__}'")
378
+ class_fields = Serialization.get_class_fields(str(class_type.__name__))
379
+ if class_fields == {}:
380
+ log.warning(f"No class fields found for '{class_type.__name__}'")
381
+ log.debug(f"class fields: {class_fields}")
382
+ result: dict[str, Any] = {}
383
+ known = set(class_fields.keys())
384
+ log.debug(f"keys found in JSON: {data.keys()}")
385
+ #log.debug(f"known fields: {known}")
386
+ for name, typ in class_fields.items():
387
+ if name in data:
388
+ log.debug(f"Field '{name}' of {class_type.__name__} found in data")
389
+ result[name] = Serialization._coerce_value(data[name], typ)
390
+ #if type(result[name]) != class_fields[name]:# TODO Write better type checking
391
+ # log.error(f"Field '{name}' of {class_type.__name__} was expected to be of type '{class_fields[name]}', but got '{type(result[name])}' with value '{result[name]}'")
392
+ # raise TypeError(f"Field '{name}' expected type '{class_fields[name]}', got '{type(result[name])}'")
393
+ log.debug(f"Field '{name}' of '{class_type.__name__}' resulted in a '{type(result[name]).__name__}' with value '{result[name]}'")
394
+ else:
395
+ log.debug(f"Field '{name}' of '{class_type.__name__}' not found in JSON data")
396
+
397
+ unknown_keys = [k for k in data.keys() if k not in known]
398
+ log.info(f"Creating instance of {class_type.__name__} with fields: {result.keys()}")
399
+ new_cls = class_type(**result)
400
+ log.debug(f"Deserialized {class_type.__name__} with unknown keys: {unknown_keys}")
401
+ return new_cls # type: ignore, unknown_keys