hfst-altlab 0.0.1.dev0__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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,36 @@
1
+ Metadata-Version: 2.4
2
+ Name: hfst-altlab
3
+ Version: 0.0.1.dev0
4
+ Summary: A python wrapper for accessing Helsinki Finite State Transducers used at ALTLab
5
+ Author-email: Felipe Bañados Schwerter <banadoss@ualberta.ca>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/UAlbertaALTLab/hfst-altlab
8
+ Project-URL: Issues, https://github.com/UAlbertaALTLab/hfst-altlab/issues
9
+ Classifier: Topic :: Text Processing :: Linguistic
10
+ Classifier: Topic :: Software Development :: Build Tools
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Dynamic: license-file
15
+
16
+ hfst-altlab
17
+ ===========
18
+
19
+ A wrapper on the [hfst][] python package, currently working as a replacement for [hfst-optimized-lookup][], built for [itwêwina][].
20
+
21
+ [itwêwina]: https://itwewina.altlab.app
22
+ [hfst-optimized-lookup]: https://github.com/UAlbertaALTLab/hfst-optimized-lookup
23
+ [hfst]: https://pypi.org/project/hfst/
24
+
25
+ Languages currently supported:
26
+ - [python](python)
27
+
28
+ [hfst] is a great toolkit with all sorts of functionality, and is
29
+ indispensable for building FSTs, but for various applications that only
30
+ want to do unweighted hfstol lookups, this package may be easier to use.
31
+
32
+ [hfst]: https://github.com/hfst/hfst
33
+
34
+ Although eventually we want to restore maintenance of the [hfst-optimized-lookup][] package, as it follows a more lightweight approach, we are in the process of contacting the maintainers of the pypi package to take over. In the meantime, we want to use this project as an upstream-synced implementation and as a way to explore more advanced behaviours that can be useful for many language projects (especially for [morphodict][]). In particular, we wanted to extend the API to account for weighted FSTs and we intend to explore making flag diacritics available in the not-so-distant future.
35
+
36
+ [morphodict]: https://github.com/UAlbertaALTLab/morphodict
@@ -0,0 +1,21 @@
1
+ hfst-altlab
2
+ ===========
3
+
4
+ A wrapper on the [hfst][] python package, currently working as a replacement for [hfst-optimized-lookup][], built for [itwêwina][].
5
+
6
+ [itwêwina]: https://itwewina.altlab.app
7
+ [hfst-optimized-lookup]: https://github.com/UAlbertaALTLab/hfst-optimized-lookup
8
+ [hfst]: https://pypi.org/project/hfst/
9
+
10
+ Languages currently supported:
11
+ - [python](python)
12
+
13
+ [hfst] is a great toolkit with all sorts of functionality, and is
14
+ indispensable for building FSTs, but for various applications that only
15
+ want to do unweighted hfstol lookups, this package may be easier to use.
16
+
17
+ [hfst]: https://github.com/hfst/hfst
18
+
19
+ Although eventually we want to restore maintenance of the [hfst-optimized-lookup][] package, as it follows a more lightweight approach, we are in the process of contacting the maintainers of the pypi package to take over. In the meantime, we want to use this project as an upstream-synced implementation and as a way to explore more advanced behaviours that can be useful for many language projects (especially for [morphodict][]). In particular, we wanted to extend the API to account for weighted FSTs and we intend to explore making flag diacritics available in the not-so-distant future.
20
+
21
+ [morphodict]: https://github.com/UAlbertaALTLab/morphodict
@@ -0,0 +1,23 @@
1
+ [build-system]
2
+ requires = ["setuptools"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "hfst-altlab"
7
+ version = "0.0.1.dev0"
8
+ authors = [
9
+ { name="Felipe Bañados Schwerter", email="banadoss@ualberta.ca" },
10
+ ]
11
+ description = "A python wrapper for accessing Helsinki Finite State Transducers used at ALTLab"
12
+ readme = "README.md"
13
+ requires-python = ">=3.9"
14
+ classifiers = [
15
+ "Topic :: Text Processing :: Linguistic",
16
+ "Topic :: Software Development :: Build Tools"
17
+ ]
18
+ license = "Apache-2.0"
19
+ license-files = ["LICENSE"]
20
+
21
+ [project.urls]
22
+ Homepage = "https://github.com/UAlbertaALTLab/hfst-altlab"
23
+ Issues = "https://github.com/UAlbertaALTLab/hfst-altlab/issues"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,191 @@
1
+ import hfst
2
+ from pathlib import Path
3
+ from errno import ENOENT
4
+ from os import strerror
5
+ from .types import Analysis
6
+
7
+
8
+ class TransducerFile:
9
+ """
10
+ Loads an ``.hfst`` or an ``.hfstol`` transducer file.
11
+ This is intended as a replacement and extension of the
12
+ hfst-optimized-lookup python package, but depending on the
13
+ hfst project to pack the C code directly. This provides the
14
+ added benefit of regaining access to weighted FSTs without extra work.
15
+ Note that lookup will only be fast if the input file has been processed
16
+ into the hfstol format.
17
+ """
18
+
19
+ def __init__(self, filename: Path | str, search_cutoff: int = 60):
20
+ self.cutoff = search_cutoff
21
+
22
+ if not Path(filename).exists():
23
+ exn = FileNotFoundError(f"Transducer not found: ‘{str(filename)}’")
24
+ raise exn
25
+
26
+ # Now we extract the transducer and store it.
27
+ try:
28
+ stream = hfst.HfstInputStream(str(filename))
29
+ except hfst.exceptions.NotTransducerStreamException as e:
30
+ # Expected message for backwards compatibility.
31
+ e.args = ("wrong or corrupt file?",)
32
+ raise e
33
+
34
+ transducers = stream.read_all()
35
+ if not len(transducers) == 1:
36
+ error = ValueError(self)
37
+ error.add_note("We expected a single transducer to arise in the file.")
38
+ stream.close()
39
+ raise error
40
+
41
+ stream.close()
42
+ self.transducer = transducers[0]
43
+ if self.transducer.is_infinitely_ambiguous():
44
+ raise RuntimeWarning("The transducer is infinitely ambiguous.")
45
+ if not (
46
+ self.transducer.get_type()
47
+ in [
48
+ hfst.ImplementationType.HFST_OL_TYPE,
49
+ hfst.ImplementationType.HFST_OLW_TYPE,
50
+ ]
51
+ ):
52
+ print("Transducer not optimized. Optimizing...")
53
+ self.transducer.lookup_optimize()
54
+ print("Done.")
55
+
56
+ def bulk_lookup(self, words: list[str]) -> dict[str, set[str]]:
57
+ """
58
+ Like ``lookup()`` but applied to multiple inputs. Useful for generating multiple
59
+ surface forms.
60
+
61
+ :param words: list of words to lookup
62
+ :type words: list[str]
63
+ :return: a dictionary mapping words in the input to a set of its tranductions
64
+ :rtype: dict[str, set[str]]
65
+ """
66
+ return {word: set(self.lookup(word)) for word in words}
67
+
68
+ def lookup(self, input: str) -> list[str]:
69
+ """
70
+ Lookup the input string, returning a list of tranductions. This is
71
+ most similar to using ``hfst-optimized-lookup`` on the command line.
72
+
73
+ :param str string: The string to lookup.
74
+ :return: list of analyses as concatenated strings, or an empty list if the input
75
+ cannot be analyzed.
76
+ :rtype: list[str]
77
+ """
78
+ return ["".join(transduction) for transduction in self.lookup_symbols(input)]
79
+
80
+ def weighted_lookup_lemma_with_affixes(
81
+ self, surface_form: str
82
+ ) -> list[tuple[float, Analysis]]:
83
+ """
84
+ Analyze the input string, returning a list
85
+ of tuples containing a ``float`` and a :py:class:`types.Analysis` object.
86
+
87
+ .. note::
88
+ this method assumes an analyzer in which all multicharacter symbols
89
+ represent affixes, and all lexical symbols are contiguous.
90
+
91
+
92
+ :param str string: The string to lookup.
93
+ :return: list of analyses as :py:class:`types.Analysis`
94
+ objects, or an empty list if there are no analyses.
95
+ :rtype: list of :py:class:`types.Analysis`
96
+ """
97
+ raw_weighted_analyses = self.weighted_lookup_symbols(surface_form)
98
+ return [
99
+ (weight, _parse_analysis(analysis))
100
+ for weight, analysis in raw_weighted_analyses
101
+ ]
102
+
103
+ def lookup_lemma_with_affixes(self, surface_form: str) -> list[Analysis]:
104
+ return [
105
+ analysis
106
+ for weight, analysis in self.weighted_lookup_lemma_with_affixes(
107
+ surface_form
108
+ )
109
+ ]
110
+
111
+ def lookup_symbols(self, input: str) -> list[list[str]]:
112
+ """
113
+ Transduce the input string. The result is a list of tranductions. Each
114
+ tranduction is a list of symbols returned in the model; that is, the symbols are
115
+ not concatenated into a single string.
116
+
117
+ :param str input: The string to lookup.
118
+ :return:
119
+ :rtype: list[list[str]]
120
+ """
121
+ return [
122
+ transduction for weight, transduction in self.weighted_lookup_symbols(input)
123
+ ]
124
+
125
+ def weighted_lookup_symbols(self, input: str) -> list[tuple[float, list[str]]]:
126
+ """
127
+ Transduce the input string. The result is a list of weighted tranductions. Each
128
+ weighted tranduction is a tuple with a float for the weight and a list of symbols returned in the model; that is, the symbols are
129
+ not concatenated into a single string.
130
+
131
+ :param str input: The string to lookup.
132
+ :return:
133
+ :rtype: list[tuple[float,list[str]]]
134
+ """
135
+ return [
136
+ (
137
+ float(weight),
138
+ [
139
+ symbol
140
+ for symbol in symbols
141
+ if not hfst.is_diacritic(symbol) and symbol
142
+ ],
143
+ )
144
+ for weight, symbols in self.weighted_lookup_symbols_with_flags(input)
145
+ ]
146
+
147
+ def weighted_lookup_symbols_with_flags(
148
+ self, input: str
149
+ ) -> list[tuple[float, list[str]]]:
150
+ """
151
+ Transduce the input string, preserving the weight information coming from HFST and separating each symbol
152
+
153
+ :param str input: The string to lookup.
154
+ :return: A list of tuples, each containing the weight(float), and a list of strings, each a language symbol
155
+ :rtype: list[tuple[float,list[str]]]
156
+ """
157
+ return list(
158
+ self.transducer.lookup(input, time_cutoff=self.cutoff, output="raw")
159
+ )
160
+
161
+ def symbol_count(self) -> int:
162
+ """
163
+ symbol_count() -> int
164
+
165
+ Returns the number of symbols in the sigma (the symbol table or alphabet).
166
+
167
+ :rtype: int
168
+ """
169
+ return len(self.transducer.get_alphabet())
170
+
171
+
172
+ def _parse_analysis(letters_and_tags: list[str]) -> Analysis:
173
+ prefix_tags: list[str] = []
174
+ lemma_chars: list[str] = []
175
+ suffix_tags: list[str] = []
176
+
177
+ tag_destination = prefix_tags
178
+ for symbol in letters_and_tags:
179
+ if not hfst.is_diacritic(symbol):
180
+ if len(symbol) == 1:
181
+ lemma_chars.append(symbol)
182
+ tag_destination = suffix_tags
183
+ else:
184
+ assert len(symbol) > 1
185
+ tag_destination.append(symbol)
186
+
187
+ return Analysis(
188
+ tuple(prefix_tags),
189
+ "".join(lemma_chars),
190
+ tuple(suffix_tags),
191
+ )
@@ -0,0 +1,36 @@
1
+ Metadata-Version: 2.4
2
+ Name: hfst-altlab
3
+ Version: 0.0.1.dev0
4
+ Summary: A python wrapper for accessing Helsinki Finite State Transducers used at ALTLab
5
+ Author-email: Felipe Bañados Schwerter <banadoss@ualberta.ca>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/UAlbertaALTLab/hfst-altlab
8
+ Project-URL: Issues, https://github.com/UAlbertaALTLab/hfst-altlab/issues
9
+ Classifier: Topic :: Text Processing :: Linguistic
10
+ Classifier: Topic :: Software Development :: Build Tools
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Dynamic: license-file
15
+
16
+ hfst-altlab
17
+ ===========
18
+
19
+ A wrapper on the [hfst][] python package, currently working as a replacement for [hfst-optimized-lookup][], built for [itwêwina][].
20
+
21
+ [itwêwina]: https://itwewina.altlab.app
22
+ [hfst-optimized-lookup]: https://github.com/UAlbertaALTLab/hfst-optimized-lookup
23
+ [hfst]: https://pypi.org/project/hfst/
24
+
25
+ Languages currently supported:
26
+ - [python](python)
27
+
28
+ [hfst] is a great toolkit with all sorts of functionality, and is
29
+ indispensable for building FSTs, but for various applications that only
30
+ want to do unweighted hfstol lookups, this package may be easier to use.
31
+
32
+ [hfst]: https://github.com/hfst/hfst
33
+
34
+ Although eventually we want to restore maintenance of the [hfst-optimized-lookup][] package, as it follows a more lightweight approach, we are in the process of contacting the maintainers of the pypi package to take over. In the meantime, we want to use this project as an upstream-synced implementation and as a way to explore more advanced behaviours that can be useful for many language projects (especially for [morphodict][]). In particular, we wanted to extend the API to account for weighted FSTs and we intend to explore making flag diacritics available in the not-so-distant future.
35
+
36
+ [morphodict]: https://github.com/UAlbertaALTLab/morphodict
@@ -0,0 +1,10 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/__init__.py
5
+ src/import_test.py
6
+ src/types.py
7
+ src/hfst_altlab.egg-info/PKG-INFO
8
+ src/hfst_altlab.egg-info/SOURCES.txt
9
+ src/hfst_altlab.egg-info/dependency_links.txt
10
+ src/hfst_altlab.egg-info/top_level.txt
@@ -0,0 +1,3 @@
1
+ __init__
2
+ import_test
3
+ types
@@ -0,0 +1,192 @@
1
+ """
2
+ This file has been imported from https://github.com/UAlbertaALTLab/hfst-optimized-lookup/,
3
+ to act as a compatibility check layer. Further tests should be incorporated somewhere else.
4
+ """
5
+
6
+ from pathlib import Path
7
+ import pytest
8
+
9
+ from . import TransducerFile, Analysis
10
+
11
+
12
+ @pytest.fixture(scope="session")
13
+ def project_root_path(request):
14
+ return request.config.rootpath
15
+
16
+
17
+ TEST_FST = "crk-relaxed-analyzer-for-dictionary.hfstol"
18
+
19
+
20
+ # scope="session" reuses the FST for all tests that use this fixture
21
+ @pytest.fixture(scope="session")
22
+ def fst(project_root_path) -> TransducerFile:
23
+ return TransducerFile(project_root_path / TEST_FST)
24
+
25
+
26
+ def test_symbol_count(fst: TransducerFile) -> None:
27
+ # If this returned a non-number, we’d get a TypeError here.
28
+ assert fst.symbol_count() > 0
29
+
30
+
31
+ def test_subsequent_lookups(fst: TransducerFile) -> None:
32
+ assert fst.lookup("itwêwina") == ["itwêwin+N+I+Pl"]
33
+ assert fst.lookup("nikî-nipân") == ["PV/ki+nipâw+V+AI+Ind+1Sg"]
34
+
35
+
36
+ def test_valid_lookup_with_invalid_symbol(fst: TransducerFile) -> None:
37
+ assert fst.lookup("avocado") == []
38
+ assert fst.lookup("navajo") == []
39
+
40
+
41
+ def test_multiple_analyses(fst: TransducerFile) -> None:
42
+ assert fst.lookup("môswa") == ["môswa+N+A+Sg", "môswa+N+A+Obv"]
43
+
44
+
45
+ EXPECTED_BULK_LOOKUP_RESULT_1 = {
46
+ "itwêwina": set(["itwêwin+N+I+Pl"]),
47
+ "nikî-nipân": set(["PV/ki+nipâw+V+AI+Ind+1Sg"]),
48
+ "môswa": set(["môswa+N+A+Sg", "môswa+N+A+Obv"]),
49
+ }
50
+
51
+
52
+ def test_bulk_lookup(fst: TransducerFile) -> None:
53
+ assert (
54
+ fst.bulk_lookup(list(EXPECTED_BULK_LOOKUP_RESULT_1.keys()))
55
+ == EXPECTED_BULK_LOOKUP_RESULT_1
56
+ )
57
+
58
+
59
+ def test_bulk_lookup_with_iterator(fst: TransducerFile) -> None:
60
+ assert (
61
+ fst.bulk_lookup([w for w in EXPECTED_BULK_LOOKUP_RESULT_1.keys()])
62
+ == EXPECTED_BULK_LOOKUP_RESULT_1
63
+ )
64
+
65
+
66
+ def test_create_from_path_obj(project_root_path) -> None:
67
+ fst = TransducerFile(Path(project_root_path / TEST_FST))
68
+ assert fst.lookup("itwêwina") == ["itwêwin+N+I+Pl"]
69
+
70
+
71
+ @pytest.mark.skip("not yet implemented")
72
+ def test_limit(fst: TransducerFile) -> None:
73
+ assert fst.lookup("môswa", limit=1) == ["môswa+N+A+Sg"] # type: ignore
74
+
75
+
76
+ @pytest.mark.parametrize(
77
+ ("surface", "deep"),
78
+ [
79
+ [
80
+ "môswa",
81
+ [
82
+ ["m", "ô", "s", "w", "a", "+N", "+A", "+Sg"],
83
+ ["m", "ô", "s", "w", "a", "+N", "+A", "+Obv"],
84
+ ],
85
+ ],
86
+ [
87
+ "nikî-nipân",
88
+ [["PV/ki+", "n", "i", "p", "â", "w", "+V", "+AI", "+Ind", "+1Sg"]],
89
+ ],
90
+ ],
91
+ )
92
+ def test_symbol_lookup1(
93
+ fst: TransducerFile, surface: str, deep: list[list[str]]
94
+ ) -> None:
95
+ assert fst.lookup_symbols(surface) == deep
96
+
97
+
98
+ @pytest.mark.parametrize(
99
+ ("surface", "example"),
100
+ [
101
+ # VTA with a prefix:
102
+ (
103
+ "ê-mowât",
104
+ Analysis(("PV/e+",), "mowêw", ("+V", "+TA", "+Cnj", "+3Sg", "+4Sg/PlO")),
105
+ ),
106
+ # VAI with prefixes:
107
+ (
108
+ "ê-kî-nitawi-kâh-kîmôci-kotiskâwêyâhk",
109
+ Analysis(
110
+ prefixes=("PV/e+", "PV/ki+", "PV/nitawi+", "RdplS+", "PV/kimoci+"),
111
+ lemma="kotiskâwêw",
112
+ suffixes=("+V", "+AI", "+Cnj", "+12Pl"),
113
+ ),
114
+ ),
115
+ # Ipc:
116
+ (
117
+ # NOTE: assuming relaxed analyzer for dictionary which:
118
+ # - understands "tansi" is a spelling of "tânisi"
119
+ # - does NOT output an +Err/Orth tag!
120
+ "tansi",
121
+ Analysis((), "tânisi", ("+Ipc",)),
122
+ ),
123
+ # NA, with possession
124
+ (
125
+ "nitêm",
126
+ Analysis((), "atim", ("+N", "+A", "+Px1Sg", "+Sg")),
127
+ ),
128
+ # NID
129
+ (
130
+ "otâsa",
131
+ Analysis(
132
+ (),
133
+ "mitâs",
134
+ (
135
+ "+N",
136
+ "+I",
137
+ "+D",
138
+ "+Px3Sg",
139
+ "+Pl",
140
+ ),
141
+ ),
142
+ ),
143
+ # VAI, no prefixes, unspecified actor:
144
+ (
145
+ "nîminâniwan",
146
+ Analysis((), "nîmiw", ("+V", "+AI", "+Ind", "+X")),
147
+ ),
148
+ # VII, tense prefix
149
+ (
150
+ "kî-kinêpikoskâw",
151
+ Analysis(
152
+ prefixes=("PV/ki+",),
153
+ lemma="kinêpikoskâw",
154
+ suffixes=(
155
+ "+V",
156
+ "+II",
157
+ "+Ind",
158
+ "+3Sg",
159
+ ),
160
+ ),
161
+ ),
162
+ ],
163
+ )
164
+ def test_lookup_lemma_with_affixes(
165
+ fst: TransducerFile, surface: str, example: Analysis
166
+ ) -> None:
167
+ analyses = fst.lookup_lemma_with_affixes(surface)
168
+ assert example in analyses
169
+
170
+
171
+ def test_raises_exception_on_missing_file() -> None:
172
+ with pytest.raises(Exception) as exception_info:
173
+ TransducerFile("/does-not-exist.hfstol")
174
+
175
+ exception_messages = " ".join([str(s) for s in exception_info.value.args])
176
+ assert "Transducer not found" in exception_messages
177
+ assert "‘/does-not-exist.hfstol’" in exception_messages
178
+
179
+
180
+ def test_raises_exception_on_invalid_file() -> None:
181
+ with pytest.raises(Exception) as exception_info:
182
+ # The python test file is not a valid transducer.
183
+ TransducerFile(__file__)
184
+
185
+ exception_messages = " ".join(exception_info.value.args)
186
+ assert "wrong or corrupt file?" in exception_messages
187
+
188
+
189
+ if __name__ == "__main__":
190
+ import sys
191
+
192
+ pytest.main(sys.argv)
@@ -0,0 +1,152 @@
1
+ from typing import NamedTuple, Tuple
2
+
3
+
4
+ class Analysis(NamedTuple):
5
+ """
6
+ An analysis of a wordform.
7
+
8
+ This is a *named tuple*, so you can use it both with attributes and indices:
9
+
10
+ >>> analysis = Analysis(('PV/e+',), 'wâpamêw', ('+V', '+TA', '+Cnj', '+3Sg', '+4Sg/PlO'))
11
+
12
+ Using attributes:
13
+
14
+ >>> analysis.lemma
15
+ 'wâpamêw'
16
+ >>> analysis.prefixes
17
+ ('PV/e+',)
18
+ >>> analysis.suffixes
19
+ ('+V', '+TA', '+Cnj', '+3Sg', '+4Sg/PlO')
20
+
21
+ Using with indices:
22
+
23
+ >>> len(analysis)
24
+ 3
25
+ >>> analysis[0]
26
+ ('PV/e+',)
27
+ >>> analysis[1]
28
+ 'wâpamêw'
29
+ >>> analysis[2]
30
+ ('+V', '+TA', '+Cnj', '+3Sg', '+4Sg/PlO')
31
+ >>> prefixes, lemma, suffix = analysis
32
+ >>> lemma
33
+ 'wâpamêw'
34
+ """
35
+
36
+ prefixes: Tuple[str, ...]
37
+ """
38
+ Tags that appear before the lemma.
39
+ """
40
+
41
+ lemma: str
42
+ """
43
+ The base form of the analyzed wordform.
44
+ """
45
+
46
+ suffixes: Tuple[str, ...]
47
+ """
48
+ Tags that appear after the lemma.
49
+ """
50
+
51
+
52
+ class RichAnalysis:
53
+ """The one true FST analysis class.
54
+
55
+ Put all your methods for dealing with things like `PV/e+nipâw+V+AI+Cnj+3Pl`
56
+ here.
57
+ """
58
+
59
+ def __init__(self, analysis):
60
+ if isinstance(analysis, Analysis):
61
+ self._tuple = analysis
62
+ elif (isinstance(analysis, list) or isinstance(analysis, tuple)) and (
63
+ len(analysis) == 6 or len(analysis == 3)
64
+ ):
65
+ if len(analysis == 3):
66
+ prefix_tags, lemma, suffix_tags = analysis
67
+ self._tuple = Analysis(
68
+ prefixes=tuple(prefix_tags),
69
+ lemma=lemma,
70
+ suffixes=tuple(suffix_tags),
71
+ prefix_flags=[],
72
+ lemma_flags=[],
73
+ suffix_flags=[],
74
+ )
75
+ else:
76
+ (
77
+ prefix_tags,
78
+ lemma,
79
+ suffix_tags,
80
+ prefix_flags,
81
+ lemma_flags,
82
+ suffix_flags,
83
+ ) = analysis
84
+ self._tuple = Analysis(
85
+ prefixes=tuple(prefix_tags),
86
+ lemma=lemma,
87
+ suffixes=tuple(suffix_tags),
88
+ prefix_flags=prefix_flags,
89
+ lemma_flags=lemma_flags,
90
+ suffix_flags=suffix_flags,
91
+ )
92
+ else:
93
+ raise Exception(f"Unsupported argument: {analysis=!r}")
94
+
95
+ @property
96
+ def tuple(self):
97
+ return self._tuple
98
+
99
+ @property
100
+ def lemma(self):
101
+ return self._tuple.lemma
102
+
103
+ @property
104
+ def prefix_tags(self):
105
+ return self._tuple.prefixes
106
+
107
+ @property
108
+ def suffix_tags(self):
109
+ return self._tuple.suffixes
110
+
111
+ def generate(self):
112
+ return strict_generator().lookup(self.smushed())
113
+
114
+ def generate_with_morphemes(self, inflection):
115
+ try:
116
+ results = strict_generator_with_morpheme_boundaries().lookup(self.smushed())
117
+ if len(results) != 1:
118
+ for result in results:
119
+ if "".join(re.split(r"[<>]", result)) == inflection:
120
+ return re.split(r"[<>]", result)
121
+ return None
122
+ return re.split(r"[<>]", results[0])
123
+ except RuntimeError as e:
124
+ print("Could not generate morphemes:", e)
125
+ return []
126
+
127
+ def smushed(self):
128
+ return "".join(self.prefix_tags) + self.lemma + "".join(self.suffix_tags)
129
+
130
+ def tag_set(self):
131
+ return set(self.suffix_tags + self.prefix_tags)
132
+
133
+ def tag_intersection_count(self, other):
134
+ """How many tags does this analysis have in common with another?"""
135
+ if not isinstance(other, RichAnalysis):
136
+ raise Exception(f"Unsupported argument: {other=!r}")
137
+ return len(self.tag_set().intersection(other.tag_set()))
138
+
139
+ def __iter__(self):
140
+ """Allows doing `head, _, tail = rich_analysis`"""
141
+ return iter(self._tuple)
142
+
143
+ def __hash__(self):
144
+ return hash(self._tuple)
145
+
146
+ def __eq__(self, other):
147
+ if not isinstance(other, RichAnalysis):
148
+ return NotImplemented
149
+ return self._tuple == other.tuple
150
+
151
+ def __repr__(self):
152
+ return f"RichAnalysis({[self.prefix_tags, self.lemma, self.suffix_tags]!r})"