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