Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

First iteration of model install mechanism. #55

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/TRUNAJOD/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""TRUNAJOD init module."""
from pathlib import Path
from typing import Union

from .language import Language


def load(name: Union[str, Path]) -> Language:
"""Load a TRUNAJOD model from a local path.

:param name: Model name
:type name: Union[str, Path]
:return: A TRUNAJOD language model.
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Check language config.

:rtype: Language
"""
return _util.load_model(name)
67 changes: 67 additions & 0 deletions src/TRUNAJOD/_util.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
"""Utilities used by model loader."""
from pathlib import Path
from typing import Any
from typing import Dict

import srsly

from .language import Language


METADATA_FILENAME = "meta.json"


def load_model(name: str) -> Language:
"""Load a TRUNAJOD model.

:param name: [description]
:type name: Union[str, Path]
:return: [description]
:rtype: Language
"""
if isinstance(name, str):
if Path(name).exists():
return load_model_from_path(Path(name))


def load_model_from_path(model_path: Path) -> Language:
"""Load a model from path, provided it was installed."""
if not model_path.exists():
raise IOError("Model does not exist!")

meta = get_model_meta(model_path)


def get_model_meta(path: Path) -> Dict[str, Any]:
"""Get metadata from model.

:param path: Path to load meta from
:type path: Path
:return: Metadata dict
:rtype: Dict[str, Any]
"""
return load_meta(path / METADATA_FILENAME)


def load_meta(path: Path) -> Dict[str, Any]:
"""Load and validate metadata file.

:param path: Path of the metadata file
:type path: Path
:raises IOError: If E03, E04 happens (placeholder)
:raises ValueError: If metadata is invalid
:return: Metadata dict
:rtype: Dict[str, Any]
"""
if not path.parent.exists():
raise IOError("Not exists!")

if not path.exists() or not path.is_file():
raise IOError("Cannot load json!")

meta = srsly.read_json(path)
for setting in ("lang", "name", "version"):
if setting not in meta or not meta[setting]:
raise ValueError("Required metadata not found!")

return meta
42 changes: 42 additions & 0 deletions src/TRUNAJOD/language.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"""Define model for languages."""
from typing import Any
from typing import Dict


class Language:
"""Class that hold data for a specific language.

For example, given that Spanish model was installed, this
class holds infinitve map, frequency indices, and any
resource defined in the model.
"""

def __init__(self, *, meta: Dict[str, Any] = {}):
"""Initialize a Language object.

:param meta: model's metadata, defaults to {}
:type meta: Dict[str, Any], optional
"""
self.lang = None
self._meta = dict(meta)

@property
def meta(self) -> Dict[str, Any]:
"""Metadata of the language class.

If a model is loaded, this includes details from the
model's meta.json
"""
self._meta.setdefault("lang", self.lang)
self._meta.setdefault("version", "0.0.0")
self._meta.setdefault("description", "")
self._meta.setdefault("author", "")
self._meta.setdefault("email", "")
self._meta.setdefault("url", "")
self._meta.setdefault("license", "")
return self._meta

@meta.setter
def meta(self, value: Dict[str, Any]) -> None:
"""Metadata setter."""
self._meta = value
27 changes: 27 additions & 0 deletions tests/util_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""Unit tests for Language loading utilities."""
import json
from pathlib import Path

from TRUNAJOD import _util


def test_load_meta(tmpdir):
"""Test load_meta."""
fp = tmpdir.mkdir("test_data").join("meta.json")
fp.write(
json.dumps(
{
"lang": "es",
"name": "trunajod",
"version": "v0.0.0",
"env": "pytest",
}
)
)
path = Path(fp.strpath)
assert _util.load_meta(path) == {
"lang": "es",
"name": "trunajod",
"version": "v0.0.0",
"env": "pytest",
}