pangloss-models 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pangloss_models/__init__.py +294 -0
- pangloss_models/autocomplete.py +128 -0
- pangloss_models/bulk_upload.py +147 -0
- pangloss_models/citations.py +393 -0
- pangloss_models/companions.py +236 -0
- pangloss_models/computed.py +117 -0
- pangloss_models/context.py +99 -0
- pangloss_models/creators.py +136 -0
- pangloss_models/diagnostics.py +830 -0
- pangloss_models/editor_schema.py +292 -0
- pangloss_models/exceptions.py +280 -0
- pangloss_models/export.py +586 -0
- pangloss_models/field_definitions.py +362 -0
- pangloss_models/hooks.py +863 -0
- pangloss_models/indexes.py +161 -0
- pangloss_models/initialise_models/__init__.py +0 -0
- pangloss_models/initialise_models/builder.py +645 -0
- pangloss_models/initialise_models/check_attributions.py +122 -0
- pangloss_models/initialise_models/check_bindings.py +71 -0
- pangloss_models/initialise_models/check_companions.py +316 -0
- pangloss_models/initialise_models/check_degree_fields.py +168 -0
- pangloss_models/initialise_models/check_grounds.py +102 -0
- pangloss_models/initialise_models/check_label_templates.py +245 -0
- pangloss_models/initialise_models/check_relation_targets.py +74 -0
- pangloss_models/initialise_models/check_reverse_names.py +43 -0
- pangloss_models/initialise_models/check_semantic_spaces.py +215 -0
- pangloss_models/initialise_models/common.py +338 -0
- pangloss_models/initialise_models/initialise_create_db_model.py +22 -0
- pangloss_models/initialise_models/initialise_create_model.py +20 -0
- pangloss_models/initialise_models/initialise_edit_view_model.py +44 -0
- pangloss_models/initialise_models/initialise_field_definitions.py +1721 -0
- pangloss_models/initialise_models/initialise_head_view_model.py +166 -0
- pangloss_models/initialise_models/initialise_incoming_relation_definitions.py +125 -0
- pangloss_models/initialise_models/initialise_reference_models.py +151 -0
- pangloss_models/initialise_models/initialise_update_db_model.py +22 -0
- pangloss_models/initialise_models/initialise_update_model.py +20 -0
- pangloss_models/initialise_models/initialise_view_model.py +32 -0
- pangloss_models/initialise_models/kinds.py +377 -0
- pangloss_models/initialise_models/tagged_union.py +174 -0
- pangloss_models/label_templates.py +770 -0
- pangloss_models/literals.py +533 -0
- pangloss_models/markers.py +126 -0
- pangloss_models/merging.py +490 -0
- pangloss_models/meta_kit/__init__.py +10 -0
- pangloss_models/meta_kit/exceptions.py +2 -0
- pangloss_models/meta_kit/meta.py +350 -0
- pangloss_models/meta_slots.py +110 -0
- pangloss_models/migrations/__init__.py +131 -0
- pangloss_models/migrations/affected.py +225 -0
- pangloss_models/migrations/changes.py +1021 -0
- pangloss_models/migrations/check.py +154 -0
- pangloss_models/migrations/conversion.py +96 -0
- pangloss_models/migrations/diff.py +948 -0
- pangloss_models/migrations/files.py +596 -0
- pangloss_models/migrations/fulfils.py +74 -0
- pangloss_models/migrations/history.py +134 -0
- pangloss_models/migrations/patterns.py +657 -0
- pangloss_models/migrations/planner.py +434 -0
- pangloss_models/migrations/questions.py +274 -0
- pangloss_models/migrations/reports.py +52 -0
- pangloss_models/migrations/reverse.py +469 -0
- pangloss_models/migrations/snapshot.py +187 -0
- pangloss_models/migrations/startup.py +55 -0
- pangloss_models/migrations/state.py +364 -0
- pangloss_models/model_bases/__init__.py +0 -0
- pangloss_models/model_bases/annotated_value.py +34 -0
- pangloss_models/model_bases/base_models.py +502 -0
- pangloss_models/model_bases/base_types.py +6 -0
- pangloss_models/model_bases/binding.py +129 -0
- pangloss_models/model_bases/configs.py +21 -0
- pangloss_models/model_bases/conjunction.py +69 -0
- pangloss_models/model_bases/document.py +261 -0
- pangloss_models/model_bases/edge_model.py +40 -0
- pangloss_models/model_bases/embedded.py +75 -0
- pangloss_models/model_bases/entity.py +221 -0
- pangloss_models/model_bases/from_database.py +25 -0
- pangloss_models/model_bases/fulfilment.py +118 -0
- pangloss_models/model_bases/ground.py +61 -0
- pangloss_models/model_bases/helpers.py +38 -0
- pangloss_models/model_bases/instance_context.py +65 -0
- pangloss_models/model_bases/labels.py +96 -0
- pangloss_models/model_bases/model_tools.py +89 -0
- pangloss_models/model_bases/reified_relation.py +159 -0
- pangloss_models/model_bases/relation.py +7 -0
- pangloss_models/model_bases/semantic_space.py +127 -0
- pangloss_models/model_bases/trait.py +64 -0
- pangloss_models/model_registry.py +704 -0
- pangloss_models/protection.py +67 -0
- pangloss_models/py.typed +0 -0
- pangloss_models/rewriting.py +130 -0
- pangloss_models/search.py +1956 -0
- pangloss_models/search_where.py +776 -0
- pangloss_models/server_only.py +26 -0
- pangloss_models/spaces.py +422 -0
- pangloss_models/text.py +19 -0
- pangloss_models/together.py +29 -0
- pangloss_models/typestubs.py +855 -0
- pangloss_models/usage.py +55 -0
- pangloss_models/utils.py +582 -0
- pangloss_models/validators.py +17 -0
- pangloss_models/write_checks.py +210 -0
- pangloss_models-0.1.0.dist-info/METADATA +21 -0
- pangloss_models-0.1.0.dist-info/RECORD +105 -0
- pangloss_models-0.1.0.dist-info/WHEEL +4 -0
- pangloss_models-0.1.0.dist-info/licenses/LICENCE.txt +21 -0
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
"""Pangloss models: declare research data as Python classes, and generate their create, update and view models.
|
|
2
|
+
|
|
3
|
+
What a project or an add-on uses is imported from here (`from pangloss_models import Document, initialise`), not from
|
|
4
|
+
the module it is kept in; the imports are lazy, so nothing is loaded until it is used. See implementation_docs/imports.md.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
lazy from pangloss_models.creators import Creator, ToolchainRun
|
|
8
|
+
lazy from pangloss_models.context import PathEntry
|
|
9
|
+
lazy from pangloss_models.model_bases.annotated_value import AnnotatedValue
|
|
10
|
+
lazy from pangloss_models.model_bases.configs import RelationConfig
|
|
11
|
+
lazy from pangloss_models.model_bases.conjunction import Conjunction
|
|
12
|
+
lazy from pangloss_models.model_bases.document import Document
|
|
13
|
+
lazy from pangloss_models.model_bases.edge_model import EdgeModel
|
|
14
|
+
lazy from pangloss_models.model_bases.embedded import Embedded
|
|
15
|
+
lazy from pangloss_models.model_bases.entity import Entity
|
|
16
|
+
lazy from pangloss_models.model_bases.helpers import (
|
|
17
|
+
DBField,
|
|
18
|
+
Description,
|
|
19
|
+
Fulfils,
|
|
20
|
+
ViaEdge,
|
|
21
|
+
)
|
|
22
|
+
lazy from pangloss_models.model_bases.ground import Ground
|
|
23
|
+
lazy from pangloss_models.model_bases.reified_relation import (
|
|
24
|
+
ReifiedRelation,
|
|
25
|
+
ReifiedRelationDocument,
|
|
26
|
+
)
|
|
27
|
+
lazy from pangloss_models.model_bases.semantic_space import (
|
|
28
|
+
DEGREE_STEPS,
|
|
29
|
+
DegreeStep,
|
|
30
|
+
Modal,
|
|
31
|
+
SemanticSpace,
|
|
32
|
+
)
|
|
33
|
+
lazy from pangloss_models.model_bases.trait import (
|
|
34
|
+
NonHeritableTrait,
|
|
35
|
+
SemanticNonHeritableTrait,
|
|
36
|
+
SemanticTrait,
|
|
37
|
+
Trait,
|
|
38
|
+
)
|
|
39
|
+
lazy from pangloss_models.field_definitions import (
|
|
40
|
+
FieldBinding,
|
|
41
|
+
FieldSubclassing,
|
|
42
|
+
)
|
|
43
|
+
lazy from pangloss_models.validators import SumsTo
|
|
44
|
+
lazy from pangloss_models.together import create_heads
|
|
45
|
+
lazy from pangloss_models.rewriting import prepare_rewrite, rewrite
|
|
46
|
+
lazy from pangloss_models.companions import (
|
|
47
|
+
Companion,
|
|
48
|
+
CompanionPart,
|
|
49
|
+
CopyFromOuter,
|
|
50
|
+
Standalone,
|
|
51
|
+
Within,
|
|
52
|
+
)
|
|
53
|
+
lazy from pangloss_models.citations import Cites
|
|
54
|
+
lazy from pangloss_models.markers import (
|
|
55
|
+
Attribution,
|
|
56
|
+
Computed,
|
|
57
|
+
Degree,
|
|
58
|
+
FieldMarker,
|
|
59
|
+
KeepOnMerge,
|
|
60
|
+
)
|
|
61
|
+
lazy from pangloss_models.computed import ComputedTarget, ComputedWrite
|
|
62
|
+
lazy from pangloss_models.literals import (
|
|
63
|
+
LiteralCodec,
|
|
64
|
+
ValueNotMigrated,
|
|
65
|
+
register_codec,
|
|
66
|
+
)
|
|
67
|
+
lazy from pangloss_models.search import (
|
|
68
|
+
AnyOf,
|
|
69
|
+
Match,
|
|
70
|
+
Not,
|
|
71
|
+
OrderBy,
|
|
72
|
+
Var,
|
|
73
|
+
ViaItem,
|
|
74
|
+
)
|
|
75
|
+
lazy from pangloss_models.search_where import (
|
|
76
|
+
AnyRel,
|
|
77
|
+
Choice,
|
|
78
|
+
Compare,
|
|
79
|
+
IncomingFrom,
|
|
80
|
+
Items,
|
|
81
|
+
Rel,
|
|
82
|
+
Text,
|
|
83
|
+
Through,
|
|
84
|
+
Where,
|
|
85
|
+
)
|
|
86
|
+
lazy from pangloss_models.hooks import WriteEvent
|
|
87
|
+
lazy from pangloss_models.merging import MergeRules
|
|
88
|
+
lazy from pangloss_models.meta_slots import register_meta_slot
|
|
89
|
+
lazy from pangloss_models.protection import (
|
|
90
|
+
Protection,
|
|
91
|
+
protection_of,
|
|
92
|
+
)
|
|
93
|
+
lazy from pangloss_models.usage import (
|
|
94
|
+
Usage,
|
|
95
|
+
included_only_when_referenced,
|
|
96
|
+
)
|
|
97
|
+
lazy from pangloss_models.export import export_models
|
|
98
|
+
lazy from pangloss_models.label_templates import (
|
|
99
|
+
Formatter,
|
|
100
|
+
LabelTemplate,
|
|
101
|
+
register_label_formatter,
|
|
102
|
+
)
|
|
103
|
+
lazy from pangloss_models.text import fold
|
|
104
|
+
lazy from pangloss_models.exceptions import (
|
|
105
|
+
PanglossAwaitingInitialisation,
|
|
106
|
+
PanglossBulkLoadError,
|
|
107
|
+
PanglossBulkRecordError,
|
|
108
|
+
PanglossClassChangeError,
|
|
109
|
+
PanglossConflictError,
|
|
110
|
+
PanglossEntityInUseError,
|
|
111
|
+
PanglossImportError,
|
|
112
|
+
PanglossInitialisationError,
|
|
113
|
+
PanglossInstructionError,
|
|
114
|
+
PanglossInternalError,
|
|
115
|
+
PanglossMergeBusyError,
|
|
116
|
+
PanglossCitedError,
|
|
117
|
+
PanglossMergedError,
|
|
118
|
+
PanglossMergeError,
|
|
119
|
+
PanglossMergeNotAllowedError,
|
|
120
|
+
PanglossMergeTooLargeError,
|
|
121
|
+
PanglossMetaError,
|
|
122
|
+
PanglossMigrationAnswerNeeded,
|
|
123
|
+
PanglossMigrationError,
|
|
124
|
+
PanglossMigrationIrreversible,
|
|
125
|
+
PanglossMigrationNotSupported,
|
|
126
|
+
PanglossModelError,
|
|
127
|
+
PanglossModelWarning,
|
|
128
|
+
PanglossNotCreatableError,
|
|
129
|
+
PanglossNotDeletableError,
|
|
130
|
+
PanglossNotDeletedError,
|
|
131
|
+
PanglossNotFoundError,
|
|
132
|
+
PanglossReadOnlyError,
|
|
133
|
+
PanglossReferenceError,
|
|
134
|
+
PanglossRuntimeError,
|
|
135
|
+
PanglossSearchError,
|
|
136
|
+
PanglossSearchTimeoutError,
|
|
137
|
+
PanglossServerOnly,
|
|
138
|
+
PanglossUnknownTypeError,
|
|
139
|
+
PanglossUserDisabledError,
|
|
140
|
+
PanglossUserNotFoundError,
|
|
141
|
+
PanglossVersionConflictError,
|
|
142
|
+
PanglossWriteError,
|
|
143
|
+
PanglossWriteRefused,
|
|
144
|
+
)
|
|
145
|
+
lazy from pangloss_models.initialise_models.builder import classes_stood_for
|
|
146
|
+
lazy from pangloss_models.write_checks import (
|
|
147
|
+
before_create,
|
|
148
|
+
before_update,
|
|
149
|
+
create_validator,
|
|
150
|
+
nodes_of,
|
|
151
|
+
read_validator,
|
|
152
|
+
update_validator,
|
|
153
|
+
whole_write,
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
from pangloss_models import hooks
|
|
157
|
+
lazy from pangloss_models import spaces
|
|
158
|
+
from pangloss_models import protection # (registers the `_protect_meta` slot)
|
|
159
|
+
from pangloss_models import usage # (registers the `_usage_meta` slot)
|
|
160
|
+
from pangloss_models.model_registry import ModelRegistry
|
|
161
|
+
from pangloss_models.server_only import server_only
|
|
162
|
+
|
|
163
|
+
initialise = ModelRegistry.finalise
|
|
164
|
+
|
|
165
|
+
__all__ = [
|
|
166
|
+
"Companion",
|
|
167
|
+
"CompanionPart",
|
|
168
|
+
"CopyFromOuter",
|
|
169
|
+
"Standalone",
|
|
170
|
+
"Within",
|
|
171
|
+
"create_heads",
|
|
172
|
+
"prepare_rewrite",
|
|
173
|
+
"rewrite",
|
|
174
|
+
"Creator",
|
|
175
|
+
"Modal",
|
|
176
|
+
"Ground",
|
|
177
|
+
"DegreeStep",
|
|
178
|
+
"DEGREE_STEPS",
|
|
179
|
+
"PathEntry",
|
|
180
|
+
"ToolchainRun",
|
|
181
|
+
"AnnotatedValue",
|
|
182
|
+
"AnyOf",
|
|
183
|
+
"AnyRel",
|
|
184
|
+
"Choice",
|
|
185
|
+
"Compare",
|
|
186
|
+
"Conjunction",
|
|
187
|
+
"DBField",
|
|
188
|
+
"Description",
|
|
189
|
+
"Document",
|
|
190
|
+
"EdgeModel",
|
|
191
|
+
"Embedded",
|
|
192
|
+
"Entity",
|
|
193
|
+
"export_models",
|
|
194
|
+
"FieldBinding",
|
|
195
|
+
"Attribution",
|
|
196
|
+
"Degree",
|
|
197
|
+
"Computed",
|
|
198
|
+
"ComputedTarget",
|
|
199
|
+
"ComputedWrite",
|
|
200
|
+
"FieldMarker",
|
|
201
|
+
"FieldSubclassing",
|
|
202
|
+
"fold",
|
|
203
|
+
"Formatter",
|
|
204
|
+
"Fulfils",
|
|
205
|
+
"hooks",
|
|
206
|
+
"IncomingFrom",
|
|
207
|
+
"initialise",
|
|
208
|
+
"Cites",
|
|
209
|
+
"KeepOnMerge",
|
|
210
|
+
"MergeRules",
|
|
211
|
+
"Items",
|
|
212
|
+
"LabelTemplate",
|
|
213
|
+
"LiteralCodec",
|
|
214
|
+
"ValueNotMigrated",
|
|
215
|
+
"Match",
|
|
216
|
+
"ModelRegistry",
|
|
217
|
+
"NonHeritableTrait",
|
|
218
|
+
"Not",
|
|
219
|
+
"OrderBy",
|
|
220
|
+
"PanglossAwaitingInitialisation",
|
|
221
|
+
"PanglossBulkLoadError",
|
|
222
|
+
"PanglossBulkRecordError",
|
|
223
|
+
"PanglossClassChangeError",
|
|
224
|
+
"PanglossConflictError",
|
|
225
|
+
"PanglossEntityInUseError",
|
|
226
|
+
"PanglossImportError",
|
|
227
|
+
"PanglossInitialisationError",
|
|
228
|
+
"PanglossInstructionError",
|
|
229
|
+
"PanglossInternalError",
|
|
230
|
+
"PanglossMergeBusyError",
|
|
231
|
+
"PanglossCitedError",
|
|
232
|
+
"PanglossMergedError",
|
|
233
|
+
"PanglossMergeError",
|
|
234
|
+
"PanglossMergeNotAllowedError",
|
|
235
|
+
"PanglossMergeTooLargeError",
|
|
236
|
+
"PanglossMetaError",
|
|
237
|
+
"PanglossMigrationAnswerNeeded",
|
|
238
|
+
"PanglossMigrationError",
|
|
239
|
+
"PanglossMigrationIrreversible",
|
|
240
|
+
"PanglossMigrationNotSupported",
|
|
241
|
+
"PanglossModelError",
|
|
242
|
+
"PanglossModelWarning",
|
|
243
|
+
"PanglossNotCreatableError",
|
|
244
|
+
"PanglossNotDeletableError",
|
|
245
|
+
"PanglossNotDeletedError",
|
|
246
|
+
"PanglossNotFoundError",
|
|
247
|
+
"PanglossReadOnlyError",
|
|
248
|
+
"PanglossReferenceError",
|
|
249
|
+
"PanglossRuntimeError",
|
|
250
|
+
"PanglossSearchError",
|
|
251
|
+
"PanglossSearchTimeoutError",
|
|
252
|
+
"PanglossServerOnly",
|
|
253
|
+
"PanglossUnknownTypeError",
|
|
254
|
+
"PanglossUserDisabledError",
|
|
255
|
+
"PanglossUserNotFoundError",
|
|
256
|
+
"PanglossVersionConflictError",
|
|
257
|
+
"PanglossWriteError",
|
|
258
|
+
"PanglossWriteRefused",
|
|
259
|
+
"before_create",
|
|
260
|
+
"before_update",
|
|
261
|
+
"nodes_of",
|
|
262
|
+
"whole_write",
|
|
263
|
+
"classes_stood_for",
|
|
264
|
+
"create_validator",
|
|
265
|
+
"read_validator",
|
|
266
|
+
"update_validator",
|
|
267
|
+
"Protection",
|
|
268
|
+
"Usage",
|
|
269
|
+
"included_only_when_referenced",
|
|
270
|
+
"protection",
|
|
271
|
+
"usage",
|
|
272
|
+
"protection_of",
|
|
273
|
+
"register_meta_slot",
|
|
274
|
+
"ReifiedRelation",
|
|
275
|
+
"register_codec",
|
|
276
|
+
"register_label_formatter",
|
|
277
|
+
"ReifiedRelationDocument",
|
|
278
|
+
"Rel",
|
|
279
|
+
"RelationConfig",
|
|
280
|
+
"SemanticNonHeritableTrait",
|
|
281
|
+
"SemanticSpace",
|
|
282
|
+
"spaces",
|
|
283
|
+
"SemanticTrait",
|
|
284
|
+
"server_only",
|
|
285
|
+
"SumsTo",
|
|
286
|
+
"Text",
|
|
287
|
+
"Through",
|
|
288
|
+
"Trait",
|
|
289
|
+
"Var",
|
|
290
|
+
"ViaEdge",
|
|
291
|
+
"ViaItem",
|
|
292
|
+
"Where",
|
|
293
|
+
"WriteEvent",
|
|
294
|
+
]
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Finding existing entities by their label, over any set of entity types (see implementation_docs/autocomplete.md).
|
|
2
|
+
|
|
3
|
+
The types asked for are named (`resolve_entity_types`), and reduced to as few as will find the same
|
|
4
|
+
entities (`smallest_types`): a node has the name of each of its parents and traits as a label, so a
|
|
5
|
+
class that is a subclass of another one asked for finds nothing more.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import re
|
|
9
|
+
from collections.abc import Sequence
|
|
10
|
+
from typing import Any
|
|
11
|
+
from uuid import UUID
|
|
12
|
+
|
|
13
|
+
from pydantic import AnyHttpUrl
|
|
14
|
+
|
|
15
|
+
from pangloss_models.exceptions import PanglossUnknownTypeError
|
|
16
|
+
from pangloss_models.model_bases.base_models import _BaseObject
|
|
17
|
+
from pangloss_models.model_bases.document import Document
|
|
18
|
+
from pangloss_models.model_bases.entity import Entity
|
|
19
|
+
from pangloss_models.model_bases.labels import labels_for_model
|
|
20
|
+
from pangloss_models.text import fold
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class AutocompleteItem(_BaseObject):
|
|
24
|
+
id: UUID | AnyHttpUrl
|
|
25
|
+
type: str
|
|
26
|
+
label: str
|
|
27
|
+
# If it was found by the label of an entity that was merged into it (`Entity.merge`), and not by its own: that label
|
|
28
|
+
merged_label: str | None = None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class AutocompleteResults(_BaseObject):
|
|
32
|
+
"""One page of what was found, with the paging fields of a list"""
|
|
33
|
+
|
|
34
|
+
results: list[AutocompleteItem]
|
|
35
|
+
count: int
|
|
36
|
+
page: int
|
|
37
|
+
page_size: int
|
|
38
|
+
next_page: int | None
|
|
39
|
+
previous_page: int | None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def resolve_entity_types(names: list[str]) -> list[type]:
|
|
43
|
+
"""The classes named, each once, in the order given. A name that is not an entity (or a trait
|
|
44
|
+
that only entities have) raises `PanglossUnknownTypeError`."""
|
|
45
|
+
from pangloss_models.model_registry import ModelRegistry
|
|
46
|
+
from pangloss_models.utils import get_concrete_types, model_is_trait
|
|
47
|
+
|
|
48
|
+
models = ModelRegistry.all_models()
|
|
49
|
+
found: list[type] = []
|
|
50
|
+
for name in names:
|
|
51
|
+
if name == "Entity": # (any entity)
|
|
52
|
+
found.append(Entity)
|
|
53
|
+
continue
|
|
54
|
+
model = models.get(name)
|
|
55
|
+
if model is None:
|
|
56
|
+
raise PanglossUnknownTypeError(f"There is no model called '{name}'")
|
|
57
|
+
if model_is_trait(model): # type: ignore[arg-type]
|
|
58
|
+
implementing = get_concrete_types(model, include_abstract=True) # type: ignore[type-var]
|
|
59
|
+
ok = bool(implementing) and all(issubclass(t, Entity) for t in implementing)
|
|
60
|
+
else:
|
|
61
|
+
ok = isinstance(model, type) and issubclass(model, Entity)
|
|
62
|
+
if not ok:
|
|
63
|
+
raise PanglossUnknownTypeError(
|
|
64
|
+
f"'{name}' is not an entity type: only entities can be found by their label"
|
|
65
|
+
)
|
|
66
|
+
if model not in found:
|
|
67
|
+
found.append(model)
|
|
68
|
+
return found
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def smallest_types(types: Sequence[type]) -> list[type]:
|
|
72
|
+
"""The types that find everything the given ones do: those that are not a subclass (or an
|
|
73
|
+
application of the trait) of another one in the list"""
|
|
74
|
+
result = []
|
|
75
|
+
for model in types:
|
|
76
|
+
# (a trait has no kind, and its labels are its own and those of the traits it extends)
|
|
77
|
+
labels = labels_for_model(model, getattr(model, "__metatype__", "")) # type: ignore
|
|
78
|
+
if any(other is not model and other.__name__ in labels for other in types):
|
|
79
|
+
continue
|
|
80
|
+
result.append(model)
|
|
81
|
+
return result
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def search_words(text: str) -> list[str]:
|
|
85
|
+
"""What was typed as the words of the text index: lower case, accents folded (`pangloss_models.text.fold`), cut at
|
|
86
|
+
anything that is not a letter or digit. (That is how the index cuts a label, so no punctuation, and no
|
|
87
|
+
regular-expression character, is left to be matched.)"""
|
|
88
|
+
return re.findall(r"\w+", fold(text))
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def labels_to_match(types: Sequence[type]) -> list[str]:
|
|
92
|
+
"""The node labels, any of which finds the entities of these types"""
|
|
93
|
+
return [model.__name__ for model in smallest_types(types)]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def excluded_from_global_search() -> list[str]:
|
|
97
|
+
"""The names of the classes that "search everything" does not find (`global_search=False`)"""
|
|
98
|
+
from pangloss_models.model_registry import ModelRegistry
|
|
99
|
+
|
|
100
|
+
return sorted(
|
|
101
|
+
name
|
|
102
|
+
for name, model in ModelRegistry.all_models().items()
|
|
103
|
+
if isinstance(model, type)
|
|
104
|
+
and issubclass(model, (Document, Entity))
|
|
105
|
+
and not model._meta.global_search # type: ignore[attr-defined]
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def search_everything(
|
|
110
|
+
search_terms: str,
|
|
111
|
+
types: Sequence[type] | None = None,
|
|
112
|
+
page_number: int | None = None,
|
|
113
|
+
page_size: int | None = None,
|
|
114
|
+
documents_only: bool = False,
|
|
115
|
+
) -> Any:
|
|
116
|
+
"""The head documents and entities whose label has every word (of `types` and their subclasses, if given), the most
|
|
117
|
+
connected first (with no words, all of `types`; without those too, nothing); what is awaited on a backend that is async. See implementation_docs/homepage-and-pages.md.
|
|
118
|
+
`documents_only`: no entities (what a citation is chosen from)"""
|
|
119
|
+
from pangloss_core import storage_of
|
|
120
|
+
|
|
121
|
+
return storage_of().operations.search_everything(
|
|
122
|
+
search_terms,
|
|
123
|
+
labels_to_match(types) if types else None,
|
|
124
|
+
excluded_from_global_search(),
|
|
125
|
+
page_number,
|
|
126
|
+
page_size,
|
|
127
|
+
documents_only=documents_only,
|
|
128
|
+
)
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""Writing the records of a file with the models: what `pangloss memgraph bulk-load` does.
|
|
2
|
+
|
|
3
|
+
The file is JSON Lines: a record a line, each a JSON object with the `type` of the model it is a
|
|
4
|
+
`Create` of, and the fields of that:
|
|
5
|
+
|
|
6
|
+
```
|
|
7
|
+
{"type": "Person", "id": "https://example.org/person/1", "create_new": true, "label": "Ann", ...}
|
|
8
|
+
{"type": "Factoid", "label": "...", "source": {"type": "AtPage", "page": "1", "target": [{"type": "Source", "id": "..."}]}}
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
A record is written as `Model.Create(**fields).save()` is, so what it refers to must be written
|
|
12
|
+
**before** it: entities have to be given their ids (`create_with_id`, as a URL or a UUID), so that
|
|
13
|
+
the records that refer to them can say which they mean. The records are written in the order of the
|
|
14
|
+
file; those that follow each other with the same `type` are written by several writers at once
|
|
15
|
+
(`concurrency`), and the next type starts when they have all finished. So a file of entities, then
|
|
16
|
+
factoids, can be written four or more at a time; but a type whose records refer to each other
|
|
17
|
+
(a `Person` with a `Person` in a relation) has to be written by one writer, in order
|
|
18
|
+
(`concurrency=1`).
|
|
19
|
+
|
|
20
|
+
`validate` reads a whole file first and writes nothing, so a record that is not valid is found
|
|
21
|
+
before the database is touched. (It cannot know that something referred to exists.)
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
import asyncio
|
|
25
|
+
import itertools
|
|
26
|
+
import json
|
|
27
|
+
from collections.abc import Callable, Iterable, Iterator
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
from typing import Any
|
|
30
|
+
|
|
31
|
+
from pydantic import ValidationError
|
|
32
|
+
|
|
33
|
+
from pangloss_models.exceptions import (
|
|
34
|
+
PanglossBulkRecordError,
|
|
35
|
+
PanglossNotCreatableError,
|
|
36
|
+
)
|
|
37
|
+
from pangloss_models.model_bases.document import refuse_unless_created_directly
|
|
38
|
+
from pangloss_models.model_registry import ModelRegistry
|
|
39
|
+
|
|
40
|
+
Record = tuple[int, dict[str, Any]]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def read_records(path: Path | str) -> Iterator[Record]:
|
|
44
|
+
"""The records of a JSON Lines file, with their line numbers (blank lines are skipped)"""
|
|
45
|
+
with open(path, encoding="utf-8") as file:
|
|
46
|
+
for number, line in enumerate(file, start=1):
|
|
47
|
+
if not line.strip():
|
|
48
|
+
continue
|
|
49
|
+
try:
|
|
50
|
+
record = json.loads(line)
|
|
51
|
+
except json.JSONDecodeError as error:
|
|
52
|
+
raise PanglossBulkRecordError(number, f"not JSON: {error}") from error
|
|
53
|
+
if not isinstance(record, dict):
|
|
54
|
+
raise PanglossBulkRecordError(number, "a record must be a JSON object")
|
|
55
|
+
yield number, record
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def creator(number: int, record: dict[str, Any]) -> tuple[str, Any]:
|
|
59
|
+
"""The `Create` object of a record, and its type. Raises `PanglossBulkRecordError`"""
|
|
60
|
+
fields = dict(record)
|
|
61
|
+
type_name = fields.pop("type", None)
|
|
62
|
+
if not isinstance(type_name, str):
|
|
63
|
+
raise PanglossBulkRecordError(number, 'a record needs a "type"')
|
|
64
|
+
model = ModelRegistry.all_models().get(type_name)
|
|
65
|
+
create = getattr(model, "Create", None)
|
|
66
|
+
if model is None or create is None:
|
|
67
|
+
raise PanglossBulkRecordError(
|
|
68
|
+
number, f"{type_name!r} is not a model that can be written"
|
|
69
|
+
)
|
|
70
|
+
try:
|
|
71
|
+
refuse_unless_created_directly(model)
|
|
72
|
+
except PanglossNotCreatableError as error:
|
|
73
|
+
raise PanglossBulkRecordError(number, str(error)) from error
|
|
74
|
+
try:
|
|
75
|
+
return type_name, create(**fields)
|
|
76
|
+
except ValidationError as error:
|
|
77
|
+
problems = "; ".join(
|
|
78
|
+
f"{'.'.join(str(part) for part in e['loc'])}: {e['msg']}"
|
|
79
|
+
for e in error.errors()
|
|
80
|
+
)
|
|
81
|
+
raise PanglossBulkRecordError(number, f"{type_name}: {problems}") from error
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def validate(records: Iterable[Record]) -> dict[str, int]:
|
|
85
|
+
"""Check every record as `Create` does, writing nothing; how many there are of each type"""
|
|
86
|
+
counts: dict[str, int] = {}
|
|
87
|
+
for number, record in records:
|
|
88
|
+
type_name, _ = creator(number, record)
|
|
89
|
+
counts[type_name] = counts.get(type_name, 0) + 1
|
|
90
|
+
return counts
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
async def write_group(
|
|
94
|
+
pending: Iterator[Record], concurrency: int, written: Callable[[], None]
|
|
95
|
+
) -> None:
|
|
96
|
+
"""Write records with `concurrency` writers that share the one iterator; `written()` is called
|
|
97
|
+
after each. The first failure stops the others"""
|
|
98
|
+
|
|
99
|
+
async def writer() -> None:
|
|
100
|
+
for number, record in pending:
|
|
101
|
+
_, create = creator(number, record)
|
|
102
|
+
try:
|
|
103
|
+
await create.save()
|
|
104
|
+
except Exception as error:
|
|
105
|
+
raise PanglossBulkRecordError(
|
|
106
|
+
number, f"{type(error).__name__}: {error}"
|
|
107
|
+
) from error
|
|
108
|
+
written()
|
|
109
|
+
|
|
110
|
+
try:
|
|
111
|
+
async with asyncio.TaskGroup() as writers:
|
|
112
|
+
for _ in range(max(1, concurrency)):
|
|
113
|
+
writers.create_task(writer())
|
|
114
|
+
except ExceptionGroup as failures:
|
|
115
|
+
# (the first record, by line, of those that failed together; anything else as it is)
|
|
116
|
+
records_failed = [
|
|
117
|
+
e for e in failures.exceptions if isinstance(e, PanglossBulkRecordError)
|
|
118
|
+
]
|
|
119
|
+
if not records_failed:
|
|
120
|
+
raise
|
|
121
|
+
raise min(records_failed, key=lambda e: e.line) from None
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
async def upload(
|
|
125
|
+
records: Iterable[Record],
|
|
126
|
+
concurrency: int = 4,
|
|
127
|
+
progress: Callable[[int], None] | None = None,
|
|
128
|
+
) -> dict[str, int]:
|
|
129
|
+
"""Write the records, in order (see the module for what that means); how many of each type
|
|
130
|
+
were written. The first record that cannot be written stops the rest, with
|
|
131
|
+
`PanglossBulkRecordError`: what was written before it stays written."""
|
|
132
|
+
written: dict[str, int] = {}
|
|
133
|
+
done = 0
|
|
134
|
+
|
|
135
|
+
for type_name, group in itertools.groupby(
|
|
136
|
+
records, key=lambda record: str(record[1].get("type"))
|
|
137
|
+
):
|
|
138
|
+
|
|
139
|
+
def count(type_name: str = type_name) -> None:
|
|
140
|
+
nonlocal done
|
|
141
|
+
written[type_name] = written.get(type_name, 0) + 1
|
|
142
|
+
done += 1
|
|
143
|
+
if progress:
|
|
144
|
+
progress(done)
|
|
145
|
+
|
|
146
|
+
await write_group(group, concurrency, count)
|
|
147
|
+
return written
|