numtag 0.0.1a2__tar.gz

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.
numtag-0.0.1a2/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2025 TigreGotico
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,37 @@
1
+ Metadata-Version: 2.4
2
+ Name: numtag
3
+ Version: 0.0.1a2
4
+ Summary: Find every number in a text: exact values as digit strings, kinds and character spans.
5
+ Author: TigreGotico
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/TigreGotico/numtag
8
+ Project-URL: Repository, https://github.com/TigreGotico/numtag
9
+ Project-URL: Issues, https://github.com/TigreGotico/numtag/issues
10
+ Keywords: numbers,numerals,nlp,tagger,parser
11
+ Classifier: Development Status :: 2 - Pre-Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Text Processing :: Linguistic
16
+ Requires-Python: >=3.11
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Provides-Extra: test
20
+ Requires-Dist: pytest; extra == "test"
21
+ Dynamic: license-file
22
+
23
+ # numtag
24
+
25
+ numtag finds every number in a text. For each number it gives the exact words, their character offsets, the value and the kind.
26
+
27
+ ```python
28
+ from numtag import tag_numbers
29
+
30
+ tag_numbers("comprou duas dúzias de ovos e um milhão de euros", "pt-PT")
31
+ # [NumberMention(char_span=(8, 19), text='duas dúzias', value='24', kind=Kind.CARDINAL, ...),
32
+ # NumberMention(char_span=(30, 39), text='um milhão', value='1000000', kind=Kind.CARDINAL, ...)]
33
+ ```
34
+
35
+ A value is a digit string with no limit on its length: "24", "-2.5" or "1/3". numtag never converts a value to `int` or `float`, so no rounding changes a digit. Convert it with `int()`, `decimal.Decimal()` or `fractions.Fraction()` when you need a number.
36
+
37
+ The language rules are data files in `numtag/lexicon/`, one per language, with the source of each rule in the file.
@@ -0,0 +1,15 @@
1
+ # numtag
2
+
3
+ numtag finds every number in a text. For each number it gives the exact words, their character offsets, the value and the kind.
4
+
5
+ ```python
6
+ from numtag import tag_numbers
7
+
8
+ tag_numbers("comprou duas dúzias de ovos e um milhão de euros", "pt-PT")
9
+ # [NumberMention(char_span=(8, 19), text='duas dúzias', value='24', kind=Kind.CARDINAL, ...),
10
+ # NumberMention(char_span=(30, 39), text='um milhão', value='1000000', kind=Kind.CARDINAL, ...)]
11
+ ```
12
+
13
+ A value is a digit string with no limit on its length: "24", "-2.5" or "1/3". numtag never converts a value to `int` or `float`, so no rounding changes a digit. Convert it with `int()`, `decimal.Decimal()` or `fractions.Fraction()` when you need a number.
14
+
15
+ The language rules are data files in `numtag/lexicon/`, one per language, with the source of each rule in the file.
@@ -0,0 +1,4 @@
1
+ """numtag: find every number in a text, with exact values and character spans."""
2
+ from numtag.mention import Form, Kind, NumberMention, is_canonical_value
3
+
4
+ __all__ = ["Form", "Kind", "NumberMention", "is_canonical_value"]
@@ -0,0 +1,68 @@
1
+ """The result type of the tagger: one number found in a text."""
2
+ import re
3
+ from dataclasses import dataclass, field
4
+ from enum import Enum
5
+ from typing import Optional, Tuple
6
+
7
+
8
+ class Kind(str, Enum):
9
+ """What the number counts or names."""
10
+ CARDINAL = "cardinal" # "duas dúzias", "21"
11
+ ORDINAL = "ordinal" # "vigésimo primeiro", "21st"
12
+ FRACTION = "fraction" # "um terço", "três quartos"
13
+ DECIMAL = "decimal" # "dois vírgula cinco", "2,5"
14
+
15
+
16
+ class Form(str, Enum):
17
+ """How the number is written."""
18
+ WORDS = "words" # "dois milhões"
19
+ DIGITS = "digits" # "2000000"
20
+ MIXED = "mixed" # "2 milhões"
21
+
22
+
23
+ _WHOLE = r"-?(?:0|[1-9][0-9]*)"
24
+ _CANONICAL = re.compile(
25
+ rf"{_WHOLE}" # whole number
26
+ rf"|-?(?:0|[1-9][0-9]*)\.[0-9]*[1-9]" # decimal, no trailing zero
27
+ rf"|-?[1-9][0-9]*/[1-9][0-9]*") # fraction
28
+ _NEGATIVE_ZERO = re.compile(r"-0(?:\.0*)?$")
29
+
30
+
31
+ def is_canonical_value(value: str) -> bool:
32
+ """True when ``value`` is in one of the three canonical forms.
33
+
34
+ A whole number has no leading zero and is never "-0"; a decimal has no
35
+ trailing zero in its fraction part; a fraction has no zero part. Lowest
36
+ terms and the rule that a fraction with a finite decimal form is written
37
+ as a decimal need arithmetic, so the tagger's own value code keeps them.
38
+ """
39
+ return bool(_CANONICAL.fullmatch(value)) and not _NEGATIVE_ZERO.match(value)
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class NumberMention:
44
+ """One number inside a longer text.
45
+
46
+ ``char_span`` is the half-open ``(start, end)`` character extent in the
47
+ original text, so ``text[start:end] == mention.text``. ``value`` is a
48
+ canonical digit string ("1002", "-2.5", "1/3"); ``int()``,
49
+ ``decimal.Decimal()`` and ``fractions.Fraction()`` read it. ``gender``
50
+ is set when the words show it ("duas" is feminine). ``confidence`` is a
51
+ deterministic score in ``(0, 1]`` that the words are a number at all
52
+ (low for an article such as "uma casa"); it is not a probability and it
53
+ is left out of equality.
54
+ """
55
+ char_span: Tuple[int, int]
56
+ text: str
57
+ value: str
58
+ kind: Kind
59
+ form: Form
60
+ gender: Optional[str] = None
61
+ confidence: float = field(default=1.0, compare=False)
62
+
63
+ def __post_init__(self):
64
+ start, end = self.char_span
65
+ if not 0 <= start < end or end - start != len(self.text):
66
+ raise ValueError(f"char_span {self.char_span} does not fit text {self.text!r}")
67
+ if not is_canonical_value(self.value):
68
+ raise ValueError(f"value {self.value!r} is not a canonical digit string")
File without changes
@@ -0,0 +1,10 @@
1
+ # START_VERSION_BLOCK
2
+ VERSION_MAJOR = 0
3
+ VERSION_MINOR = 0
4
+ VERSION_BUILD = 1
5
+ VERSION_ALPHA = 2
6
+ # END_VERSION_BLOCK
7
+
8
+ VERSION_STR = f"{VERSION_MAJOR}.{VERSION_MINOR}.{VERSION_BUILD}"
9
+ if VERSION_ALPHA:
10
+ VERSION_STR += f"a{VERSION_ALPHA}"
@@ -0,0 +1,37 @@
1
+ Metadata-Version: 2.4
2
+ Name: numtag
3
+ Version: 0.0.1a2
4
+ Summary: Find every number in a text: exact values as digit strings, kinds and character spans.
5
+ Author: TigreGotico
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/TigreGotico/numtag
8
+ Project-URL: Repository, https://github.com/TigreGotico/numtag
9
+ Project-URL: Issues, https://github.com/TigreGotico/numtag/issues
10
+ Keywords: numbers,numerals,nlp,tagger,parser
11
+ Classifier: Development Status :: 2 - Pre-Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Text Processing :: Linguistic
16
+ Requires-Python: >=3.11
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Provides-Extra: test
20
+ Requires-Dist: pytest; extra == "test"
21
+ Dynamic: license-file
22
+
23
+ # numtag
24
+
25
+ numtag finds every number in a text. For each number it gives the exact words, their character offsets, the value and the kind.
26
+
27
+ ```python
28
+ from numtag import tag_numbers
29
+
30
+ tag_numbers("comprou duas dúzias de ovos e um milhão de euros", "pt-PT")
31
+ # [NumberMention(char_span=(8, 19), text='duas dúzias', value='24', kind=Kind.CARDINAL, ...),
32
+ # NumberMention(char_span=(30, 39), text='um milhão', value='1000000', kind=Kind.CARDINAL, ...)]
33
+ ```
34
+
35
+ A value is a digit string with no limit on its length: "24", "-2.5" or "1/3". numtag never converts a value to `int` or `float`, so no rounding changes a digit. Convert it with `int()`, `decimal.Decimal()` or `fractions.Fraction()` when you need a number.
36
+
37
+ The language rules are data files in `numtag/lexicon/`, one per language, with the source of each rule in the file.
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ numtag/__init__.py
5
+ numtag/mention.py
6
+ numtag/py.typed
7
+ numtag/version.py
8
+ numtag.egg-info/PKG-INFO
9
+ numtag.egg-info/SOURCES.txt
10
+ numtag.egg-info/dependency_links.txt
11
+ numtag.egg-info/requires.txt
12
+ numtag.egg-info/top_level.txt
13
+ tests/test_gold_format.py
14
+ tests/test_mention.py
@@ -0,0 +1,3 @@
1
+
2
+ [test]
3
+ pytest
@@ -0,0 +1 @@
1
+ numtag
@@ -0,0 +1,38 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "numtag"
7
+ dynamic = ["version"]
8
+ description = "Find every number in a text: exact values as digit strings, kinds and character spans."
9
+ readme = "README.md"
10
+ license = { text = "Apache-2.0" }
11
+ requires-python = ">=3.11"
12
+ authors = [{ name = "TigreGotico" }]
13
+ keywords = ["numbers", "numerals", "nlp", "tagger", "parser"]
14
+ classifiers = [
15
+ "Development Status :: 2 - Pre-Alpha",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: Apache Software License",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Text Processing :: Linguistic",
20
+ ]
21
+ dependencies = []
22
+
23
+ [project.urls]
24
+ Homepage = "https://github.com/TigreGotico/numtag"
25
+ Repository = "https://github.com/TigreGotico/numtag"
26
+ Issues = "https://github.com/TigreGotico/numtag/issues"
27
+
28
+ [project.optional-dependencies]
29
+ test = ["pytest"]
30
+
31
+ [tool.setuptools.packages.find]
32
+ include = ["numtag*"]
33
+
34
+ [tool.setuptools.dynamic]
35
+ version = { attr = "numtag.version.VERSION_STR" }
36
+
37
+ [tool.setuptools.package-data]
38
+ numtag = ["py.typed", "lexicon/*.toml"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,186 @@
1
+ import contextlib
2
+ import importlib.util
3
+ import io
4
+ import json
5
+ import tempfile
6
+ import unittest
7
+ from pathlib import Path
8
+
9
+ GOLD_DIR = Path(__file__).parent / "gold"
10
+ _spec = importlib.util.spec_from_file_location("check_gold", GOLD_DIR / "check_gold.py")
11
+ check_gold = importlib.util.module_from_spec(_spec)
12
+ _spec.loader.exec_module(check_gold)
13
+
14
+ LANGUAGES = ("pt-PT", "pt-BR", "en")
15
+ MIN_ROWS = 400
16
+
17
+
18
+ def _row(text, *mentions, source="arithmetic"):
19
+ return {"text": text, "mentions": list(mentions), "source": source}
20
+
21
+
22
+ def _m(start, end, value, kind="cardinal", **extra):
23
+ return {"start": start, "end": end, "value": value, "kind": kind, **extra}
24
+
25
+
26
+ class TestGoldFiles(unittest.TestCase):
27
+ def test_every_language_file_passes(self):
28
+ for lang in LANGUAGES:
29
+ with self.subTest(lang=lang):
30
+ n_in, errors = check_gold.check_file(GOLD_DIR / f"{lang}.jsonl")
31
+ self.assertEqual(errors, [])
32
+ self.assertGreaterEqual(n_in, MIN_ROWS)
33
+
34
+ def test_no_text_is_repeated_in_a_file(self):
35
+ for lang in LANGUAGES:
36
+ with self.subTest(lang=lang):
37
+ lines = (GOLD_DIR / f"{lang}.jsonl").read_text(encoding="utf-8").splitlines()
38
+ texts = [json.loads(line)["text"] for line in lines]
39
+ self.assertEqual(len(texts), len(set(texts)))
40
+
41
+
42
+ class TestCheckerRefusesBadRows(unittest.TestCase):
43
+ """The checker must fail on each kind of broken row, or a green run proves nothing."""
44
+
45
+ def assertRefused(self, row):
46
+ with self.assertRaises(AssertionError):
47
+ check_gold.check_row(row)
48
+
49
+ def test_a_good_row_passes(self):
50
+ check_gold.check_row(_row("comprou duas dúzias de ovos", _m(8, 19, "24")))
51
+ check_gold.check_row(_row("Estão -5 graus.", _m(6, 8, "-5")))
52
+ check_gold.check_row(_row("Comprei uma casa.", _m(8, 11, "1", low_confidence=True)))
53
+ check_gold.check_row(_row("Comeu um terço.", _m(6, 14, "1/3", "fraction")))
54
+ check_gold.check_row(_row("Nada aqui."))
55
+
56
+ def test_span_with_trailing_punctuation(self):
57
+ self.assertRefused(_row("Saímos às 7, depois.", _m(10, 12, "7")))
58
+
59
+ def test_span_with_leading_space(self):
60
+ self.assertRefused(_row("Saímos às 7, depois.", _m(9, 11, "7")))
61
+
62
+ def test_span_with_currency_sign(self):
63
+ self.assertRefused(_row("Custa €10.", _m(6, 9, "10")))
64
+
65
+ def test_span_outside_the_text(self):
66
+ self.assertRefused(_row("dez", _m(0, 4, "10")))
67
+
68
+ def test_empty_span(self):
69
+ self.assertRefused(_row("dez", _m(1, 1, "10")))
70
+
71
+ def test_overlapping_mentions(self):
72
+ self.assertRefused(_row("vinte e um", _m(0, 5, "20"), _m(3, 10, "21")))
73
+
74
+ def test_mentions_out_of_order(self):
75
+ self.assertRefused(_row("dois e três", _m(7, 11, "3"), _m(0, 4, "2")))
76
+
77
+ def test_non_canonical_values(self):
78
+ for value in ("2.50", "007", "-0", "1,5"):
79
+ with self.subTest(value=value):
80
+ self.assertRefused(_row("dois vírgula cinco", _m(0, 18, value, "decimal")))
81
+
82
+ def test_fraction_not_in_lowest_terms(self):
83
+ self.assertRefused(_row("dois quartos", _m(0, 12, "2/4", "fraction")))
84
+
85
+ def test_fraction_with_finite_decimal(self):
86
+ self.assertRefused(_row("um meio", _m(0, 7, "1/2", "fraction")))
87
+
88
+ def test_kind_that_contradicts_the_value(self):
89
+ self.assertRefused(_row("dois e meio", _m(0, 11, "2.5", "cardinal")))
90
+ self.assertRefused(_row("um milhão e meio", _m(0, 16, "1500000", "fraction")))
91
+
92
+ def test_unknown_kind(self):
93
+ self.assertRefused(_row("dez", _m(0, 3, "10", "number")))
94
+
95
+ def test_empty_source(self):
96
+ self.assertRefused(_row("dez", _m(0, 3, "10"), source=" "))
97
+
98
+ def test_low_confidence_false(self):
99
+ self.assertRefused(_row("uma casa", _m(0, 3, "1", low_confidence=False)))
100
+
101
+ def test_unknown_key(self):
102
+ self.assertRefused(_row("dez", _m(0, 3, "10", gender="masculine")))
103
+
104
+ def test_span_that_cuts_a_word(self):
105
+ self.assertRefused(_row("comprou duas dúzias", _m(8, 18, "24")))
106
+
107
+ def test_span_that_starts_inside_a_word(self):
108
+ self.assertRefused(_row("Custa 125 euros.", _m(7, 9, "25")))
109
+
110
+ def test_span_that_stops_before_a_digit_mark(self):
111
+ self.assertRefused(_row("Pesava 3,5 quilos.", _m(7, 8, "3")))
112
+ self.assertRefused(_row("It cost 1,000 dollars.", _m(8, 9, "1")))
113
+ self.assertRefused(_row("It is 3.5 m.", _m(6, 7, "3")))
114
+
115
+ def test_span_that_starts_after_a_digit_mark(self):
116
+ self.assertRefused(_row("Pesava 3,5 quilos.", _m(9, 10, "5")))
117
+ self.assertRefused(_row("Custa 1.000 euros.", _m(8, 11, "0")))
118
+ self.assertRefused(_row("It is 3.5 m.", _m(8, 9, "5")))
119
+
120
+ def test_a_mark_after_a_letter_is_no_digit_mark(self):
121
+ check_gold.check_row(_row("Sala n.5", _m(7, 8, "5")))
122
+ check_gold.check_row(_row("Ver p.12", _m(6, 8, "12")))
123
+
124
+ def test_a_list_after_the_digits_is_no_digit_mark(self):
125
+ check_gold.check_row(_row("1, 2 e 3", _m(0, 1, "1"), _m(3, 4, "2"), _m(7, 8, "3")))
126
+
127
+ def test_a_file_with_no_known_decimal_marks_fails(self):
128
+ with tempfile.TemporaryDirectory() as tmp:
129
+ path = Path(tmp) / "xx.jsonl"
130
+ path.write_text('{"text": "dez", "mentions": [], "source": "arithmetic"}\n', encoding="utf-8")
131
+ n_in, errors = check_gold.check_file(path)
132
+ self.assertEqual(len(errors), 1)
133
+ self.assertIn("no decimal marks", errors[0])
134
+
135
+ def test_the_run_counts_good_rows_as_out(self):
136
+ with tempfile.TemporaryDirectory() as tmp:
137
+ path = Path(tmp) / "pt-PT.jsonl"
138
+ path.write_text('{"text": "dez", "mentions": [], "source": "arithmetic"}\n', encoding="utf-8")
139
+ out = io.StringIO()
140
+ with contextlib.redirect_stdout(out):
141
+ status = check_gold.main([str(path)])
142
+ self.assertEqual(status, 0)
143
+ self.assertIn("pt-PT.jsonl: 1 in, 1 out", out.getvalue())
144
+
145
+ def test_a_file_with_no_known_decimal_marks_reports_no_row_checked(self):
146
+ with tempfile.TemporaryDirectory() as tmp:
147
+ path = Path(tmp) / "xx.jsonl"
148
+ path.write_text('{"text": "dez", "mentions": [], "source": "arithmetic"}\n' * 2, encoding="utf-8")
149
+ out = io.StringIO()
150
+ with contextlib.redirect_stdout(out):
151
+ status = check_gold.main([str(path)])
152
+ self.assertEqual(status, 1)
153
+ self.assertIn("xx.jsonl: 2 in, 0 out", out.getvalue())
154
+
155
+ def test_a_unit_may_touch_the_digits(self):
156
+ check_gold.check_row(_row("Pesava 3,5kg.", _m(7, 10, "3.5", "decimal")), "pt-PT")
157
+
158
+ def test_decimal_kind_without_a_decimal_mark(self):
159
+ with self.assertRaises(AssertionError):
160
+ check_gold.check_row(_row("três quartos", _m(0, 12, "0.75", "decimal")), "pt-PT")
161
+
162
+ def test_fraction_kind_with_a_decimal_mark(self):
163
+ with self.assertRaises(AssertionError):
164
+ check_gold.check_row(_row("dois vírgula cinco", _m(0, 18, "2.5", "fraction")), "pt-PT")
165
+
166
+ def test_a_repeated_text_is_reported_by_the_file_check(self):
167
+ with tempfile.TemporaryDirectory() as tmp:
168
+ path = Path(tmp) / "pt-PT.jsonl"
169
+ line = '{"text": "dez", "mentions": [{"start": 0, "end": 3, "value": "10", "kind": "cardinal"}], "source": "arithmetic"}\n'
170
+ path.write_text(line * 2, encoding="utf-8")
171
+ n_in, errors = check_gold.check_file(path)
172
+ self.assertEqual((n_in, len(errors)), (2, 1))
173
+ self.assertIn("repeats line 1", errors[0])
174
+
175
+ def test_invalid_json_line_is_reported(self):
176
+ with tempfile.TemporaryDirectory() as tmp:
177
+ path = Path(tmp) / "pt-PT.jsonl"
178
+ path.write_text('{"text": "dez", "mentions": [], "source": "arithmetic"}\n{not json\n', encoding="utf-8")
179
+ n_in, errors = check_gold.check_file(path)
180
+ self.assertEqual(n_in, 2)
181
+ self.assertEqual(len(errors), 1)
182
+ self.assertIn("pt-PT.jsonl:2", errors[0])
183
+
184
+
185
+ if __name__ == "__main__":
186
+ unittest.main()
@@ -0,0 +1,50 @@
1
+ import unittest
2
+ from decimal import Decimal
3
+ from fractions import Fraction
4
+
5
+ from numtag import Form, Kind, NumberMention, is_canonical_value
6
+
7
+
8
+ class TestCanonicalValue(unittest.TestCase):
9
+ def test_canonical_forms_are_accepted(self):
10
+ for value in ("0", "7", "24", "-21", "1" + "0" * 600,
11
+ "2.5", "-0.25", "0.5", "1/3", "-2/3"):
12
+ with self.subTest(value=value):
13
+ self.assertTrue(is_canonical_value(value))
14
+
15
+ def test_other_forms_are_refused(self):
16
+ for value in ("", "007", "-0", "-0.0", "2.50", "2.", ".5", "+3",
17
+ "0/3", "3/0", "1e6", "1 000", "1,5", "um"):
18
+ with self.subTest(value=value):
19
+ self.assertFalse(is_canonical_value(value))
20
+
21
+ def test_standard_types_read_every_form(self):
22
+ self.assertEqual(int("1" + "0" * 600), 10 ** 600)
23
+ self.assertEqual(Decimal("-0.25"), Decimal(-1) / 4)
24
+ self.assertEqual(Fraction("1/3"), Fraction(1, 3))
25
+ self.assertEqual(Fraction("2.5"), Fraction(5, 2))
26
+
27
+
28
+ class TestNumberMention(unittest.TestCase):
29
+ def test_a_mention_holds_its_slice(self):
30
+ text = "comprou duas dúzias de ovos"
31
+ mention = NumberMention((8, 19), text[8:19], "24", Kind.CARDINAL,
32
+ Form.WORDS, gender="feminine")
33
+ self.assertEqual(text[slice(*mention.char_span)], mention.text)
34
+
35
+ def test_a_span_that_does_not_fit_the_text_is_refused(self):
36
+ with self.assertRaises(ValueError):
37
+ NumberMention((0, 3), "duas", "2", Kind.CARDINAL, Form.WORDS)
38
+
39
+ def test_a_value_that_is_not_canonical_is_refused(self):
40
+ with self.assertRaises(ValueError):
41
+ NumberMention((0, 3), "2,5", "2,5", Kind.DECIMAL, Form.DIGITS)
42
+
43
+ def test_confidence_is_not_part_of_equality(self):
44
+ a = NumberMention((0, 3), "uma", "1", Kind.CARDINAL, Form.WORDS, confidence=0.3)
45
+ b = NumberMention((0, 3), "uma", "1", Kind.CARDINAL, Form.WORDS)
46
+ self.assertEqual(a, b)
47
+
48
+
49
+ if __name__ == "__main__":
50
+ unittest.main()