Fixup word_db unserialization

This commit is contained in:
Théophile Bastian 2024-09-16 22:41:45 +02:00
parent a9c3c90405
commit 695813d35f

View file

@ -1,8 +1,10 @@
""" A pre-processed database of words, independant of their source """
import gzip
import json
import typing as t
from enum import Enum
import json
from pathlib import Path
class Genre(Enum):
@ -41,8 +43,8 @@ class Nom(t.NamedTuple):
return {"genre": self.genre.name, "sing": self.sing, "plur": self.plur}
@classmethod
def unserialized(cls, **kwargs):
genre = Genre(kwargs.pop("genre"))
def unserialized(cls, kwargs):
genre = Genre[kwargs.pop("genre")]
return cls(**kwargs, genre=genre)
@ -64,7 +66,7 @@ class Adjectif(t.NamedTuple):
return self._asdict()
@classmethod
def unserialized(cls, **kwargs):
def unserialized(cls, kwargs):
return cls(**kwargs)
@ -88,7 +90,7 @@ class Verbe(t.NamedTuple):
return self._asdict()
@classmethod
def unserialized(cls, **kwargs):
def unserialized(cls, kwargs):
return cls(**kwargs)
@ -109,13 +111,15 @@ class Adverbe(t.NamedTuple):
return self._asdict()
@classmethod
def unserialized(cls, **kwargs):
def unserialized(cls, kwargs):
return cls(**kwargs)
class WordDb:
"""Base de donnée de mots, sérialisable"""
SERIALIZED_GZ_LOCATION = Path(__file__).parent.parent / "morphalou_full.json.gz"
_serialize_data: dict[str, t.Type[t.NamedTuple]] = {
"noms": Nom,
"adjectifs": Adjectif,
@ -171,3 +175,9 @@ class WordDb:
def load(cls, fd) -> "WordDb":
"""Unserialize from this stream"""
return cls.unserialize(json.load(fd))
@classmethod
def autoload(cls) -> "WordDb":
"""Unserialize from default source"""
with gzip.open(cls.SERIALIZED_GZ_LOCATION) as h:
return cls.load(h)