anyconv-quantity-basic 1.0.1__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.
- anyconv_quantity_basic/__init__.py +4 -0
- anyconv_quantity_basic/anyconv.module.yaml +110 -0
- anyconv_quantity_basic/module.py +224 -0
- anyconv_quantity_basic/parsing.py +197 -0
- anyconv_quantity_basic-1.0.1.dist-info/METADATA +83 -0
- anyconv_quantity_basic-1.0.1.dist-info/RECORD +10 -0
- anyconv_quantity_basic-1.0.1.dist-info/WHEEL +5 -0
- anyconv_quantity_basic-1.0.1.dist-info/entry_points.txt +2 -0
- anyconv_quantity_basic-1.0.1.dist-info/licenses/LICENSE +21 -0
- anyconv_quantity_basic-1.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
# AnyConv — эталонный модуль anyconv-quantity-basic.
|
|
2
|
+
# Демонстрация: semantic-оси, params_required, params_out, constraints, enum_from.
|
|
3
|
+
spec: "^1.0"
|
|
4
|
+
api: ">=1.0,<2.0"
|
|
5
|
+
id: com.gitlab.raceozr.quantity-basic
|
|
6
|
+
version: 1.0.1
|
|
7
|
+
title:
|
|
8
|
+
en: "Basic quantities"
|
|
9
|
+
ru: "Базовые величины"
|
|
10
|
+
description:
|
|
11
|
+
en: "Mass, length and volume conversion. Deterministic, no network."
|
|
12
|
+
ru: "Преобразование массы, длины и объёма. Детерминированное, без сети."
|
|
13
|
+
license: MIT
|
|
14
|
+
homepage: "https://gitlab.com/raceozr/anyconv-modules"
|
|
15
|
+
keywords: [units, mass, length, volume, reference]
|
|
16
|
+
stability: stable
|
|
17
|
+
entrypoint:
|
|
18
|
+
kind: python
|
|
19
|
+
target: "anyconv_quantity_basic.module:QuantityModule"
|
|
20
|
+
requires:
|
|
21
|
+
python: ">=3.10"
|
|
22
|
+
packages: ["anyconv-core>=1.0,<2.0"]
|
|
23
|
+
|
|
24
|
+
capabilities:
|
|
25
|
+
- id: quantity-convert
|
|
26
|
+
op: convert
|
|
27
|
+
since: 1.0.0
|
|
28
|
+
routing: auto
|
|
29
|
+
fidelity: lossless
|
|
30
|
+
determinism: deterministic
|
|
31
|
+
cache: {reuse: true}
|
|
32
|
+
cost: {weight: 1}
|
|
33
|
+
limits: {timeout_s: 5}
|
|
34
|
+
inputs:
|
|
35
|
+
- name: source
|
|
36
|
+
cardinality: one
|
|
37
|
+
accept:
|
|
38
|
+
semantic: ["quantity:*"]
|
|
39
|
+
params_required: [unit]
|
|
40
|
+
outputs:
|
|
41
|
+
- name: result
|
|
42
|
+
cardinality: one
|
|
43
|
+
kind: data
|
|
44
|
+
produce:
|
|
45
|
+
semantic: ["quantity:*"]
|
|
46
|
+
params_out: {unit: "$settings.target_unit"}
|
|
47
|
+
constraints:
|
|
48
|
+
- "in.dimension == out.dimension"
|
|
49
|
+
settings:
|
|
50
|
+
type: object
|
|
51
|
+
additionalProperties: false
|
|
52
|
+
required: [target_unit]
|
|
53
|
+
properties:
|
|
54
|
+
target_unit:
|
|
55
|
+
type: string
|
|
56
|
+
enum_from:
|
|
57
|
+
registry: units
|
|
58
|
+
filter: {dimension: "$in.dimension"}
|
|
59
|
+
precision: {type: integer, minimum: 0, maximum: 15, default: 6}
|
|
60
|
+
rounding: {enum: [half-up, half-even, down, up], default: half-up}
|
|
61
|
+
|
|
62
|
+
- id: quantity-parse
|
|
63
|
+
op: convert
|
|
64
|
+
since: 1.0.0
|
|
65
|
+
routing: auto
|
|
66
|
+
fidelity: semantic-loss
|
|
67
|
+
determinism: deterministic
|
|
68
|
+
cost: {weight: 20}
|
|
69
|
+
limits: {timeout_s: 5, max_input_bytes: 1024}
|
|
70
|
+
inputs:
|
|
71
|
+
- name: text
|
|
72
|
+
accept: {formats: [text:plain]}
|
|
73
|
+
outputs:
|
|
74
|
+
- name: value
|
|
75
|
+
kind: data
|
|
76
|
+
produce: {semantic: ["quantity:*"]}
|
|
77
|
+
settings:
|
|
78
|
+
type: object
|
|
79
|
+
additionalProperties: false
|
|
80
|
+
properties:
|
|
81
|
+
hint_dimension: {enum: ["quantity:mass", "quantity:length", "quantity:volume"]}
|
|
82
|
+
decimal_separator: {enum: [auto, ".", ","], default: auto}
|
|
83
|
+
strict: {type: boolean, default: false}
|
|
84
|
+
|
|
85
|
+
- id: quantity-format
|
|
86
|
+
op: convert
|
|
87
|
+
since: 1.0.0
|
|
88
|
+
routing: auto
|
|
89
|
+
fidelity: lossless
|
|
90
|
+
determinism: deterministic
|
|
91
|
+
cost: {weight: 1}
|
|
92
|
+
limits: {timeout_s: 5}
|
|
93
|
+
inputs:
|
|
94
|
+
- name: value
|
|
95
|
+
accept:
|
|
96
|
+
semantic: ["quantity:*"]
|
|
97
|
+
params_required: [unit]
|
|
98
|
+
outputs:
|
|
99
|
+
- name: text
|
|
100
|
+
kind: data
|
|
101
|
+
produce: {formats: [text:plain]}
|
|
102
|
+
settings:
|
|
103
|
+
type: object
|
|
104
|
+
additionalProperties: false
|
|
105
|
+
properties:
|
|
106
|
+
style: {enum: [symbol, id, alias], default: symbol}
|
|
107
|
+
locale: {enum: [en, ru], default: en}
|
|
108
|
+
precision: {type: integer, minimum: 0, maximum: 15, default: 6}
|
|
109
|
+
rounding: {enum: [half-up, half-even, down, up], default: half-up}
|
|
110
|
+
space: {type: boolean, default: true}
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""Эталонный модуль величин. Детерминированный, без сети и float."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from decimal import InvalidOperation, localcontext
|
|
5
|
+
from importlib.resources import files
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import yaml
|
|
9
|
+
from anyconv.sdk import Availability, CheckContext, Context, OpResult, Request
|
|
10
|
+
from anyconv.sdk.errors import (
|
|
11
|
+
ConstraintViolation,
|
|
12
|
+
CorruptInput,
|
|
13
|
+
OpNotImplemented,
|
|
14
|
+
SettingsInvalid,
|
|
15
|
+
)
|
|
16
|
+
from anyconv.sdk.registries import units
|
|
17
|
+
|
|
18
|
+
from .parsing import (
|
|
19
|
+
dimension_view,
|
|
20
|
+
format_quantity,
|
|
21
|
+
parse_quantity,
|
|
22
|
+
quantize,
|
|
23
|
+
to_decimal,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class QuantityModule:
|
|
28
|
+
@staticmethod
|
|
29
|
+
def manifest() -> dict[str, Any]:
|
|
30
|
+
return yaml.safe_load(
|
|
31
|
+
files("anyconv_quantity_basic")
|
|
32
|
+
.joinpath("anyconv.module.yaml")
|
|
33
|
+
.read_text("utf-8")
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
def check(self, ctx: CheckContext) -> Availability:
|
|
37
|
+
return Availability(status="ready")
|
|
38
|
+
|
|
39
|
+
def convert(self, req: Request, ctx: Context) -> OpResult:
|
|
40
|
+
if req.capability_id == "quantity-convert":
|
|
41
|
+
return self._convert_value(req, ctx)
|
|
42
|
+
if req.capability_id == "quantity-parse":
|
|
43
|
+
return self._parse_text(req, ctx)
|
|
44
|
+
if req.capability_id == "quantity-format":
|
|
45
|
+
return self._format_value(req, ctx)
|
|
46
|
+
raise OpNotImplemented(
|
|
47
|
+
f"неизвестная возможность {req.capability_id!r}",
|
|
48
|
+
details={"capability": req.capability_id},
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
# ------------------------------------------------------------------ #
|
|
52
|
+
# quantity-convert
|
|
53
|
+
# ------------------------------------------------------------------ #
|
|
54
|
+
|
|
55
|
+
def _convert_value(self, req: Request, ctx: Context) -> OpResult:
|
|
56
|
+
source = req.inputs["source"][0]
|
|
57
|
+
typeref = source.typeref
|
|
58
|
+
if typeref is None:
|
|
59
|
+
raise CorruptInput("вход без TypeRef")
|
|
60
|
+
value = to_decimal(source.value)
|
|
61
|
+
registry = dimension_view(typeref.semantic)
|
|
62
|
+
source_unit = typeref.params.get("unit")
|
|
63
|
+
if not isinstance(source_unit, str):
|
|
64
|
+
raise CorruptInput(
|
|
65
|
+
"во входном значении отсутствует параметр unit",
|
|
66
|
+
details={"typeref": str(typeref)},
|
|
67
|
+
)
|
|
68
|
+
if source_unit not in registry:
|
|
69
|
+
raise CorruptInput(
|
|
70
|
+
f"неизвестная исходная единица {source_unit!r}",
|
|
71
|
+
details={"unit": source_unit, "dimension": registry.dimension},
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
target_unit = ctx.settings["target_unit"]
|
|
75
|
+
if not isinstance(target_unit, str):
|
|
76
|
+
raise SettingsInvalid(
|
|
77
|
+
"target_unit должен быть строкой",
|
|
78
|
+
details={"target_unit": str(target_unit)},
|
|
79
|
+
)
|
|
80
|
+
target_dimension = units.dimension_of(target_unit)
|
|
81
|
+
if target_dimension is None:
|
|
82
|
+
raise SettingsInvalid(
|
|
83
|
+
f"неизвестная целевая единица {target_unit!r}",
|
|
84
|
+
details={"target_unit": target_unit},
|
|
85
|
+
)
|
|
86
|
+
if target_dimension != registry.dimension:
|
|
87
|
+
raise ConstraintViolation(
|
|
88
|
+
"исходная и целевая единицы принадлежат разным размерностям",
|
|
89
|
+
details={
|
|
90
|
+
"from": source_unit,
|
|
91
|
+
"to": target_unit,
|
|
92
|
+
"in_dimension": registry.dimension,
|
|
93
|
+
"out_dimension": target_dimension,
|
|
94
|
+
},
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
try:
|
|
98
|
+
with localcontext() as decimal_context:
|
|
99
|
+
decimal_context.prec = 34
|
|
100
|
+
result = (value * registry.factor(source_unit)) / registry.factor(
|
|
101
|
+
target_unit
|
|
102
|
+
)
|
|
103
|
+
except (InvalidOperation, ZeroDivisionError) as exc:
|
|
104
|
+
raise CorruptInput(
|
|
105
|
+
"арифметическая ошибка при конвертации",
|
|
106
|
+
details={
|
|
107
|
+
"value": str(value),
|
|
108
|
+
"from": source_unit,
|
|
109
|
+
"to": target_unit,
|
|
110
|
+
},
|
|
111
|
+
) from exc
|
|
112
|
+
|
|
113
|
+
precision = int(ctx.settings.get("precision", 6))
|
|
114
|
+
rounding = str(ctx.settings.get("rounding", "half-up"))
|
|
115
|
+
result = quantize(result, precision, rounding)
|
|
116
|
+
output = ctx.out_value(
|
|
117
|
+
"result",
|
|
118
|
+
result,
|
|
119
|
+
semantic=registry.dimension,
|
|
120
|
+
params={"unit": target_unit},
|
|
121
|
+
)
|
|
122
|
+
ctx.emit_provenance(
|
|
123
|
+
{
|
|
124
|
+
"registry_version": registry.version,
|
|
125
|
+
"from": source_unit,
|
|
126
|
+
"to": target_unit,
|
|
127
|
+
"dimension": registry.dimension,
|
|
128
|
+
}
|
|
129
|
+
)
|
|
130
|
+
return OpResult(
|
|
131
|
+
outputs={"result": output},
|
|
132
|
+
provenance={
|
|
133
|
+
"registry_version": registry.version,
|
|
134
|
+
"from": source_unit,
|
|
135
|
+
"to": target_unit,
|
|
136
|
+
},
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
# ------------------------------------------------------------------ #
|
|
140
|
+
# quantity-parse
|
|
141
|
+
# ------------------------------------------------------------------ #
|
|
142
|
+
|
|
143
|
+
def _parse_text(self, req: Request, ctx: Context) -> OpResult:
|
|
144
|
+
source = req.inputs["text"][0]
|
|
145
|
+
if source.kind == "text":
|
|
146
|
+
text = str(source.value if source.value is not None else "")
|
|
147
|
+
elif source.kind == "blob":
|
|
148
|
+
encoding = "utf-8"
|
|
149
|
+
if source.typeref is not None:
|
|
150
|
+
encoding = str(source.typeref.params.get("encoding", "utf-8"))
|
|
151
|
+
text = ctx.read_input("text").decode(encoding)
|
|
152
|
+
else:
|
|
153
|
+
text = str(source.value)
|
|
154
|
+
|
|
155
|
+
try:
|
|
156
|
+
value, unit = parse_quantity(
|
|
157
|
+
text,
|
|
158
|
+
decimal_separator=str(ctx.settings.get("decimal_separator", "auto")),
|
|
159
|
+
hint_dimension=ctx.settings.get("hint_dimension"),
|
|
160
|
+
strict=bool(ctx.settings.get("strict", False)),
|
|
161
|
+
)
|
|
162
|
+
except CorruptInput as exc:
|
|
163
|
+
exc.details.setdefault("text", text[:200])
|
|
164
|
+
raise
|
|
165
|
+
|
|
166
|
+
output = ctx.out_value(
|
|
167
|
+
"value",
|
|
168
|
+
value,
|
|
169
|
+
semantic=unit.dimension,
|
|
170
|
+
params={"unit": unit.id},
|
|
171
|
+
)
|
|
172
|
+
provenance = {
|
|
173
|
+
"registry_version": units.version,
|
|
174
|
+
"unit": unit.id,
|
|
175
|
+
"dimension": unit.dimension,
|
|
176
|
+
}
|
|
177
|
+
ctx.emit_provenance(provenance)
|
|
178
|
+
return OpResult(outputs={"value": output}, provenance=provenance)
|
|
179
|
+
|
|
180
|
+
# ------------------------------------------------------------------ #
|
|
181
|
+
# quantity-format
|
|
182
|
+
# ------------------------------------------------------------------ #
|
|
183
|
+
|
|
184
|
+
def _format_value(self, req: Request, ctx: Context) -> OpResult:
|
|
185
|
+
source = req.inputs["value"][0]
|
|
186
|
+
typeref = source.typeref
|
|
187
|
+
if typeref is None:
|
|
188
|
+
raise CorruptInput("вход без TypeRef")
|
|
189
|
+
value = to_decimal(source.value)
|
|
190
|
+
registry = dimension_view(typeref.semantic)
|
|
191
|
+
unit_id = typeref.params.get("unit")
|
|
192
|
+
if not isinstance(unit_id, str):
|
|
193
|
+
raise CorruptInput(
|
|
194
|
+
"во входном значении отсутствует параметр unit",
|
|
195
|
+
details={"typeref": str(typeref)},
|
|
196
|
+
)
|
|
197
|
+
if unit_id not in registry:
|
|
198
|
+
raise CorruptInput(
|
|
199
|
+
f"неизвестная единица {unit_id!r}",
|
|
200
|
+
details={"unit": unit_id, "dimension": registry.dimension},
|
|
201
|
+
)
|
|
202
|
+
unit = registry.unit(unit_id)
|
|
203
|
+
text = format_quantity(
|
|
204
|
+
value,
|
|
205
|
+
unit,
|
|
206
|
+
style=str(ctx.settings.get("style", "symbol")),
|
|
207
|
+
locale=str(ctx.settings.get("locale", "en")),
|
|
208
|
+
precision=int(ctx.settings.get("precision", 6)),
|
|
209
|
+
rounding=str(ctx.settings.get("rounding", "half-up")),
|
|
210
|
+
space=bool(ctx.settings.get("space", True)),
|
|
211
|
+
)
|
|
212
|
+
output = ctx.out_text("text", text)
|
|
213
|
+
provenance = {
|
|
214
|
+
"registry_version": registry.version,
|
|
215
|
+
"unit": unit.id,
|
|
216
|
+
"dimension": registry.dimension,
|
|
217
|
+
"style": ctx.settings.get("style", "symbol"),
|
|
218
|
+
"locale": ctx.settings.get("locale", "en"),
|
|
219
|
+
}
|
|
220
|
+
ctx.emit_provenance(provenance)
|
|
221
|
+
return OpResult(outputs={"text": output}, provenance=provenance)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
__all__ = ["QuantityModule"]
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""Разбор и форматирование величин. Только decimal, без float (SPEC §5)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
from decimal import (
|
|
6
|
+
ROUND_DOWN,
|
|
7
|
+
ROUND_HALF_EVEN,
|
|
8
|
+
ROUND_HALF_UP,
|
|
9
|
+
ROUND_UP,
|
|
10
|
+
Decimal,
|
|
11
|
+
InvalidOperation,
|
|
12
|
+
localcontext,
|
|
13
|
+
)
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from anyconv.sdk.errors import CorruptInput
|
|
17
|
+
from anyconv.sdk.registries import Unit, units
|
|
18
|
+
|
|
19
|
+
ROUNDING = {
|
|
20
|
+
"half-up": ROUND_HALF_UP,
|
|
21
|
+
"half-even": ROUND_HALF_EVEN,
|
|
22
|
+
"down": ROUND_DOWN,
|
|
23
|
+
"up": ROUND_UP,
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
NUMBER = re.compile(r"^\s*([+-]?(?:\d+(?:[.,]\d*)?|[.,]\d+))\s*(.+?)\s*$")
|
|
27
|
+
STRICT_NUMBER = re.compile(r"^([+-]?(?:\d+(?:[.,]\d*)?|[.,]\d+)) (.+)$")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def to_decimal(value: Any) -> Decimal:
|
|
31
|
+
if isinstance(value, Decimal):
|
|
32
|
+
result = value
|
|
33
|
+
elif isinstance(value, bool):
|
|
34
|
+
raise CorruptInput("логическое значение не является величиной")
|
|
35
|
+
else:
|
|
36
|
+
try:
|
|
37
|
+
result = Decimal(str(value))
|
|
38
|
+
except (InvalidOperation, ValueError) as exc:
|
|
39
|
+
raise CorruptInput(
|
|
40
|
+
f"не удалось разобрать число: {value!r}",
|
|
41
|
+
details={"value": str(value)},
|
|
42
|
+
) from exc
|
|
43
|
+
if not result.is_finite():
|
|
44
|
+
raise CorruptInput(
|
|
45
|
+
"NaN и Infinity недопустимы",
|
|
46
|
+
details={"value": str(value)},
|
|
47
|
+
)
|
|
48
|
+
return result
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def quantize(value: Decimal, precision: int, rounding: str) -> Decimal:
|
|
52
|
+
if precision < 0 or precision > 15:
|
|
53
|
+
raise CorruptInput(
|
|
54
|
+
f"precision вне диапазона 0..15: {precision}",
|
|
55
|
+
details={"precision": precision},
|
|
56
|
+
)
|
|
57
|
+
quantum = Decimal(1).scaleb(-precision)
|
|
58
|
+
try:
|
|
59
|
+
with localcontext() as ctx:
|
|
60
|
+
ctx.prec = 34
|
|
61
|
+
return value.quantize(quantum, rounding=ROUNDING[rounding])
|
|
62
|
+
except InvalidOperation as exc:
|
|
63
|
+
raise CorruptInput(
|
|
64
|
+
"величина слишком велика для заданной точности",
|
|
65
|
+
details={"value": str(value), "precision": precision},
|
|
66
|
+
) from exc
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _normalize_number(raw: str, separator: str) -> str:
|
|
70
|
+
if separator == "auto":
|
|
71
|
+
if "," in raw and "." in raw:
|
|
72
|
+
raise CorruptInput(
|
|
73
|
+
"неоднозначный десятичный разделитель",
|
|
74
|
+
details={"number": raw},
|
|
75
|
+
)
|
|
76
|
+
return raw.replace(",", ".")
|
|
77
|
+
if separator == ",":
|
|
78
|
+
if "." in raw:
|
|
79
|
+
raise CorruptInput(
|
|
80
|
+
"ожидалась запятая как десятичный разделитель",
|
|
81
|
+
details={"number": raw},
|
|
82
|
+
)
|
|
83
|
+
return raw.replace(",", ".")
|
|
84
|
+
if separator == ".":
|
|
85
|
+
if "," in raw:
|
|
86
|
+
raise CorruptInput(
|
|
87
|
+
"ожидалась точка как десятичный разделитель",
|
|
88
|
+
details={"number": raw},
|
|
89
|
+
)
|
|
90
|
+
return raw
|
|
91
|
+
raise CorruptInput(
|
|
92
|
+
f"неизвестный decimal_separator: {separator!r}",
|
|
93
|
+
details={"decimal_separator": separator},
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _resolve_unit(name: str, hint_dimension: str | None) -> Unit:
|
|
98
|
+
candidates = units.resolve(name)
|
|
99
|
+
if hint_dimension is not None:
|
|
100
|
+
filtered = [unit for unit in candidates if unit.dimension == hint_dimension]
|
|
101
|
+
if candidates and not filtered:
|
|
102
|
+
raise CorruptInput(
|
|
103
|
+
f"единица {name!r} относится к другой размерности",
|
|
104
|
+
details={
|
|
105
|
+
"unit": name,
|
|
106
|
+
"candidates": sorted(unit.id for unit in candidates),
|
|
107
|
+
"hint_dimension": hint_dimension,
|
|
108
|
+
},
|
|
109
|
+
)
|
|
110
|
+
candidates = filtered
|
|
111
|
+
if not candidates:
|
|
112
|
+
raise CorruptInput(
|
|
113
|
+
f"неизвестная единица {name!r}",
|
|
114
|
+
details={"unit": name},
|
|
115
|
+
)
|
|
116
|
+
if len(candidates) > 1:
|
|
117
|
+
raise CorruptInput(
|
|
118
|
+
f"неоднозначная единица {name!r}",
|
|
119
|
+
details={
|
|
120
|
+
"unit": name,
|
|
121
|
+
"candidates": sorted(unit.id for unit in candidates),
|
|
122
|
+
},
|
|
123
|
+
)
|
|
124
|
+
return candidates[0]
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def parse_quantity(
|
|
128
|
+
text: str,
|
|
129
|
+
*,
|
|
130
|
+
decimal_separator: str = "auto",
|
|
131
|
+
hint_dimension: str | None = None,
|
|
132
|
+
strict: bool = False,
|
|
133
|
+
) -> tuple[Decimal, Unit]:
|
|
134
|
+
if not isinstance(text, str):
|
|
135
|
+
raise CorruptInput("ожидалась строка", details={"type": type(text).__name__})
|
|
136
|
+
match = (STRICT_NUMBER if strict else NUMBER).match(text)
|
|
137
|
+
if match is None:
|
|
138
|
+
raise CorruptInput(
|
|
139
|
+
"не удалось разобрать величину",
|
|
140
|
+
details={"text": text[:200]},
|
|
141
|
+
)
|
|
142
|
+
raw_number, raw_unit = match.group(1), match.group(2).strip()
|
|
143
|
+
if not raw_unit:
|
|
144
|
+
raise CorruptInput(
|
|
145
|
+
"не указана единица измерения",
|
|
146
|
+
details={"text": text[:200]},
|
|
147
|
+
)
|
|
148
|
+
number = _normalize_number(raw_number, decimal_separator)
|
|
149
|
+
try:
|
|
150
|
+
value = Decimal(number)
|
|
151
|
+
except InvalidOperation as exc:
|
|
152
|
+
raise CorruptInput(
|
|
153
|
+
f"не удалось разобрать число: {raw_number!r}",
|
|
154
|
+
details={"number": raw_number},
|
|
155
|
+
) from exc
|
|
156
|
+
if not value.is_finite():
|
|
157
|
+
raise CorruptInput("NaN и Infinity недопустимы", details={"text": text[:200]})
|
|
158
|
+
unit = _resolve_unit(raw_unit, hint_dimension)
|
|
159
|
+
return value, unit
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def display_unit(unit: Unit, style: str, locale: str) -> str:
|
|
163
|
+
if style == "id":
|
|
164
|
+
return unit.id
|
|
165
|
+
if style == "alias":
|
|
166
|
+
return unit.aliases[0] if unit.aliases else unit.id
|
|
167
|
+
if locale == "ru":
|
|
168
|
+
return unit.symbol
|
|
169
|
+
return unit.symbol if unit.symbol.isascii() else unit.id
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def format_quantity(
|
|
173
|
+
value: Decimal,
|
|
174
|
+
unit: Unit,
|
|
175
|
+
*,
|
|
176
|
+
style: str = "symbol",
|
|
177
|
+
locale: str = "en",
|
|
178
|
+
precision: int = 6,
|
|
179
|
+
rounding: str = "half-up",
|
|
180
|
+
space: bool = True,
|
|
181
|
+
) -> str:
|
|
182
|
+
quantized = quantize(value, precision, rounding)
|
|
183
|
+
number = format(quantized, "f")
|
|
184
|
+
symbol = display_unit(unit, style, locale)
|
|
185
|
+
return f"{number} {symbol}" if space else f"{number}{symbol}"
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def dimension_view(semantic: str | None) -> Any:
|
|
189
|
+
if not semantic:
|
|
190
|
+
raise CorruptInput("у величины отсутствует semantic")
|
|
191
|
+
try:
|
|
192
|
+
return units(semantic)
|
|
193
|
+
except KeyError as exc:
|
|
194
|
+
raise CorruptInput(
|
|
195
|
+
f"неизвестная размерность {semantic!r}",
|
|
196
|
+
details={"semantic": semantic},
|
|
197
|
+
) from exc
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: anyconv-quantity-basic
|
|
3
|
+
Version: 1.0.1
|
|
4
|
+
Summary: Эталонный модуль AnyConv: масса, длина, объём
|
|
5
|
+
Author: AnyConv
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: anyconv,units,mass,length,volume,reference
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Requires-Dist: anyconv-core<2.0,>=1.0
|
|
12
|
+
Provides-Extra: dev
|
|
13
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
14
|
+
Requires-Dist: hypothesis>=6; extra == "dev"
|
|
15
|
+
Requires-Dist: ruff>=0.5; extra == "dev"
|
|
16
|
+
Requires-Dist: click>=8.1; extra == "dev"
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# anyconv-quantity-basic
|
|
20
|
+
|
|
21
|
+
**Эталонный пример модуля AnyConv.** Масса, длина и объём: детерминированно,
|
|
22
|
+
без сети, без `float`, коэффициенты — из реестров ядра.
|
|
23
|
+
|
|
24
|
+
Нормативно: [SPEC.md](https://gitlab.com/raceozr/anyconv-core/-/blob/main/SPEC.md) ·
|
|
25
|
+
[side-modules-dev-instruction.md](https://gitlab.com/raceozr/anyconv-core/-/blob/main/docs/side-modules-dev-instruction.md)
|
|
26
|
+
|
|
27
|
+
## Установка
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install "anyconv-core[all] @ git+https://gitlab.com/raceozr/anyconv-core.git@v1.0.0"
|
|
31
|
+
pip install "git+https://gitlab.com/raceozr/anyconv-modules.git@v1.0.1#subdirectory=modules/quantity-basic"
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## CLI
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
anyconv convert --from "quantity:mass?unit=kg" --to "quantity:mass?unit=lb" \
|
|
38
|
+
--value 10 --set target_unit=lb
|
|
39
|
+
# → 22.046226
|
|
40
|
+
|
|
41
|
+
anyconv convert --from "text:plain" --to "text:plain" \
|
|
42
|
+
--value "10 кг" --set target_unit=lb
|
|
43
|
+
# план: quantity-parse → quantity-convert → quantity-format
|
|
44
|
+
# → 22.046226 lb
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Python
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from anyconv import Engine
|
|
51
|
+
|
|
52
|
+
engine = Engine(modules="auto")
|
|
53
|
+
result = engine.convert(
|
|
54
|
+
10,
|
|
55
|
+
source="quantity:mass?unit=kg",
|
|
56
|
+
to="quantity:mass?unit=lb",
|
|
57
|
+
settings={"target_unit": "lb", "precision": 6},
|
|
58
|
+
)
|
|
59
|
+
print(result.outputs[0].data) # Decimal('22.046226')
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Возможности
|
|
63
|
+
|
|
64
|
+
| id | Направление | fidelity |
|
|
65
|
+
|---|---|---|
|
|
66
|
+
| `quantity-convert` | значение → значение | lossless |
|
|
67
|
+
| `quantity-parse` | `text:plain` → значение | semantic-loss |
|
|
68
|
+
| `quantity-format` | значение → `text:plain` | lossless |
|
|
69
|
+
|
|
70
|
+
Настройки: `target_unit`, `precision` (0–15), `rounding` (`half-up`,
|
|
71
|
+
`half-even`, `down`, `up`), `decimal_separator`, `hint_dimension`, `strict`,
|
|
72
|
+
`style`, `locale`, `space`.
|
|
73
|
+
|
|
74
|
+
## Тесты
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
# ?????????? ?? checkout anyconv-modules
|
|
78
|
+
cd modules/quantity-basic
|
|
79
|
+
pip install -e ".[dev]"
|
|
80
|
+
pytest
|
|
81
|
+
anyconv module validate .
|
|
82
|
+
anyconv module test .
|
|
83
|
+
```
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
anyconv_quantity_basic/__init__.py,sha256=waufRHWW0heKG3DIVE_BKyRSaQSNSUKe1s_LDc7EvY4,139
|
|
2
|
+
anyconv_quantity_basic/anyconv.module.yaml,sha256=ZZpaQ9OkeAlkmaOxqo41GJoYE0OJbwaMbBCgQHuxrY4,3268
|
|
3
|
+
anyconv_quantity_basic/module.py,sha256=Xbu6QLWZsGwSXm1OP5bQ40eDxyar4rn9n728m_LUXVw,8449
|
|
4
|
+
anyconv_quantity_basic/parsing.py,sha256=i5yhGQyZvHmH7vXYLVAw2FNdE519eLyzDT2xB804nms,6645
|
|
5
|
+
anyconv_quantity_basic-1.0.1.dist-info/licenses/LICENSE,sha256=Wahb1xasoYXZBxdcuh2ETI6eaWi4JazPi9yhb0eFBxU,1077
|
|
6
|
+
anyconv_quantity_basic-1.0.1.dist-info/METADATA,sha256=5Pn5Exvmgn5qJMkQ2jrATJInMHD0vdlt142ahN2CuTA,2575
|
|
7
|
+
anyconv_quantity_basic-1.0.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
8
|
+
anyconv_quantity_basic-1.0.1.dist-info/entry_points.txt,sha256=XlUAq_VE5Qgp_WOzR2JeGfyVMiCD8SCAEIKyj0m7xdU,80
|
|
9
|
+
anyconv_quantity_basic-1.0.1.dist-info/top_level.txt,sha256=X4mzL4v0Ts7mBUIRC4uKm3b6xpS7Ph1tjuCJG89m1x4,23
|
|
10
|
+
anyconv_quantity_basic-1.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 AnyConv contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
anyconv_quantity_basic
|