/
core.py
183 lines (139 loc) · 5.34 KB
/
core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
"""Cihai core functionality."""
import inspect
import logging
import pathlib
import typing as t
from cihai._internal.config_reader import ConfigReader
from cihai.data.unihan.dataset import Unihan
from unihan_etl.util import merge_dict
from . import exc, extend
from .config import expand_config
from .constants import DEFAULT_CONFIG, UNIHAN_CONFIG, app_dirs
from .db import Database
from .utils import import_string
if t.TYPE_CHECKING:
from typing import TypeGuard
from cihai.types import ConfigDict, UntypedDict
DS = t.TypeVar("DS", bound=type[extend.Dataset])
log = logging.getLogger(__name__)
class CihaiConfigError(exc.CihaiException):
def __init__(self):
return super().__init__("Invalid exception with configuration")
def is_valid_config(config: "UntypedDict") -> "TypeGuard[ConfigDict]":
return True
class Cihai:
"""
Central application object.
By default, this automatically adds the UNIHAN dataset.
Attributes
----------
config : dict
Notes
-----
Inspired by the early pypa/warehouse application object [1]_.
**Configuration templates**
The ``config`` :py:class:`dict` parameter supports a basic template system
for replacing :term:`XDG Base Directory` directory variables, tildes
and environmentas variables. This is done by passing the option dict
through :func:`cihai.config.expand_config` during initialization.
Examples
--------
To use cihai programmatically, invoke and install the UNIHAN [2]_ dataset:
.. literalinclude:: ../examples/basic_usage.py
:language: python
Above: :attr:`~cihai.data.unihan.bootstrap.is_bootstrapped` can check if the system
has the database installed.
References
----------
.. [1] PyPA Warehouse on GitHub. https://github.com/pypa/warehouse.
Accessed sometime in 2013.
.. [2] UNICODE HAN DATABASE (UNIHAN) documentation.
https://www.unicode.org/reports/tr38/. Accessed March 31st, 2018.
"""
#: :py:class:`dict` of default config, can be monkey-patched during tests
default_config: "UntypedDict" = DEFAULT_CONFIG
config: "ConfigDict"
unihan: Unihan
sql: Database
def __init__(
self,
config: t.Optional["UntypedDict"] = None,
unihan: bool = True,
) -> None:
"""
Parameters
----------
config : dict, optional
unihan : boolean, optional
Bootstrap the core UNIHAN dataset (recommended)
"""
_config: "UntypedDict" = config if config is not None else {}
if config is None:
_config = self.default_config
# Merges custom configuration settings on top of defaults
#: Configuration dictionary
_config = merge_dict(self.default_config, _config)
if unihan:
_config = merge_dict(UNIHAN_CONFIG, _config)
#: Expand template variables
expand_config(_config, app_dirs)
if not is_valid_config(config=_config):
raise CihaiConfigError()
self.config = _config
user_data_dir = pathlib.Path(app_dirs.user_data_dir)
if not user_data_dir.exists():
user_data_dir.mkdir(parents=True)
#: :class:`cihai.db.Database` : Database instance
self.sql = Database(self.config)
self.bootstrap()
def bootstrap(self) -> None:
for namespace, class_string in self.config.get("datasets", {}).items():
assert isinstance(class_string, str) or (
inspect.isclass(class_string)
and (
issubclass(class_string, extend.Dataset)
or class_string == extend.Dataset
)
)
assert isinstance(namespace, str)
self.add_dataset(class_string, namespace)
for dataset, plugins in self.config.get("plugins", {}).items():
assert isinstance(dataset, str)
assert isinstance(plugins, dict)
for namespace, class_string in plugins.items():
assert isinstance(namespace, str)
assert isinstance(class_string, str) or (
inspect.isclass(class_string)
and (
issubclass(class_string, extend.DatasetPlugin)
or class_string == extend.DatasetPlugin
)
)
getattr(self, dataset).add_plugin(class_string, namespace)
def add_dataset(self, _cls: t.Union["DS", str], namespace: str) -> None:
if isinstance(_cls, str):
_cls = import_string(_cls)
assert callable(_cls)
setattr(self, namespace, _cls())
dataset = getattr(self, namespace)
if isinstance(dataset, extend.SQLAlchemyMixin):
dataset.sql = self.sql
@classmethod
def from_file(
cls, config_path: pathlib.Path | str, *args: object, **kwargs: object
) -> "Cihai":
"""
Create a Cihai instance from a JSON or YAML config.
Parameters
----------
config_path : str, optional
path to custom config file
Returns
-------
:class:`Cihai` :
application object
"""
if isinstance(config_path, str):
config_path = pathlib.Path(config_path)
config = ConfigReader.from_file(path=config_path)
return cls(config.content)