From 695813d35f4b51cf82adf9539f52a9ff940fedd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A9ophile=20Bastian?= Date: Mon, 16 Sep 2024 22:41:45 +0200 Subject: [PATCH] Fixup word_db unserialization --- pwgen_fr/word_db.py | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/pwgen_fr/word_db.py b/pwgen_fr/word_db.py index e8e7e48..353cbb5 100644 --- a/pwgen_fr/word_db.py +++ b/pwgen_fr/word_db.py @@ -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)