hfst-altlab 0.1.2__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.
@@ -0,0 +1,327 @@
1
+ import hfst
2
+ import gzip
3
+ from pathlib import Path
4
+ from .types import Analysis, FullAnalysis, Wordform, as_fst_input, fst_output_format
5
+ from typing import cast, Optional
6
+ from collections.abc import Callable
7
+
8
+
9
+ class TransducerFile:
10
+ """
11
+ Loads an ``.hfst`` or an ``.hfstol`` transducer file.
12
+ This is intended as a replacement and extension of the
13
+ hfst-optimized-lookup python package, but depending on the
14
+ hfst project to pack the C code directly. This provides the
15
+ added benefit of regaining access to weighted FSTs without extra work.
16
+ Note that lookup will only be fast if the input file has been processed
17
+ into the hfstol format.
18
+
19
+ :param filename: The path of the transducer
20
+ :param search_cutoff: The maximum amount of time (in seconds) that the search will go on for. The intention of a limit is to avoid search getting stuck. Defaults to a minute.
21
+ """
22
+
23
+ def __init__(self, filename: Path | str, search_cutoff: int = 60):
24
+ self.cutoff = search_cutoff
25
+
26
+ if not Path(filename).exists():
27
+ exn = FileNotFoundError(f"Transducer not found: ‘{str(filename)}’")
28
+ raise exn
29
+
30
+ # Now we extract the transducer and store it.
31
+ try:
32
+ # Workaround for FOMABIN formats
33
+ with open(filename, "rb") as f:
34
+ if f.read(3) == b"\x1f\x8b\x08":
35
+ # It is a gzipped file!
36
+ print(
37
+ "\n".join(
38
+ [
39
+ f"The Transducer file {filename} is compressed.",
40
+ "Unfortunately, our library cannot currently handle directly compressed files (e.g. .fomabin).",
41
+ "Please decompress the file first.",
42
+ "If you don't know how, you can use the hfst_altlab.decompress_foma function as follows:\n\n",
43
+ "from hfst_altlab import decompress_foma",
44
+ 'with open(output_name, "wb") as f:',
45
+ f' with decompress_foma("{str(filename)}") as fst:',
46
+ f" f.write(fst.read())\n\n",
47
+ ]
48
+ )
49
+ )
50
+ raise ValueError(filename)
51
+ else:
52
+ stream = hfst.HfstInputStream(str(filename))
53
+ except hfst.exceptions.NotTransducerStreamException as e:
54
+ # Expected message for backwards compatibility.
55
+ e.args = ("wrong or corrupt file?",)
56
+ raise e
57
+
58
+ transducers = stream.read_all()
59
+ if not len(transducers) == 1:
60
+ error = ValueError(self)
61
+ error.add_note("We expected a single transducer to arise in the file.")
62
+ stream.close()
63
+ raise error
64
+
65
+ stream.close()
66
+ self.transducer = transducers[0]
67
+ if self.transducer.is_infinitely_ambiguous():
68
+ print(f"Warning: The transducer at {filename} is infinitely ambiguous.")
69
+ if not (
70
+ self.transducer.get_type()
71
+ in [
72
+ hfst.ImplementationType.HFST_OL_TYPE,
73
+ hfst.ImplementationType.HFST_OLW_TYPE,
74
+ ]
75
+ ):
76
+ print("Transducer not optimized. Optimizing...")
77
+ self.transducer.convert(hfst.ImplementationType.HFST_OLW_TYPE)
78
+ self.transducer.lookup_optimize()
79
+ print("Done.")
80
+
81
+ def bulk_lookup(self, words: list[str]) -> dict[str, set[str]]:
82
+ """
83
+ Like ``lookup()`` but applied to multiple inputs. Useful for generating multiple
84
+ surface forms.
85
+
86
+ .. note:: Backwards-compatible with ``hfst-optimized-lookup``
87
+
88
+ :param words: list of words to lookup
89
+ :return: a dictionary mapping words in the input to a set of its tranductions
90
+ """
91
+ return {word: set(self.lookup(word)) for word in words}
92
+
93
+ def lookup(self, input: str) -> list[str]:
94
+ """
95
+ Lookup the input string, returning a list of tranductions. This is
96
+ most similar to using ``hfst-optimized-lookup`` on the command line.
97
+
98
+ .. note:: Backwards-compatible with ``hfst-optimized-lookup``
99
+
100
+ :param input: The string to lookup.
101
+ :return: list of analyses as concatenated strings, or an empty list if the input
102
+ cannot be analyzed.
103
+ """
104
+ return ["".join(transduction) for transduction in self.lookup_symbols(input)]
105
+
106
+ def lookup_lemma_with_affixes(self, surface_form: str) -> list[Analysis]:
107
+ """
108
+ Like lookup, but separates the results into a tuple of prefixes, a lemma, and a tuple of suffixes. Expected to be used only on analyser FSTs.
109
+
110
+ .. note:: Backwards-compatible with ``hfst-optimized-lookup``
111
+
112
+ :param surface_form: The entry to search for.
113
+ """
114
+ return [
115
+ analysis.analysis
116
+ for analysis in self.weighted_lookup_full_analysis(surface_form)
117
+ ]
118
+
119
+ def lookup_symbols(self, input: str) -> list[list[str]]:
120
+ """
121
+ Transduce the input string. The result is a list of tranductions. Each
122
+ tranduction is a list of symbols returned in the model; that is, the symbols are
123
+ not concatenated into a single string.
124
+
125
+ .. note:: Backwards-compatible with ``hfst-optimized-lookup``
126
+
127
+ :param input: The string to lookup.
128
+ """
129
+ return [
130
+ [x for x in analysis.tokens if x and not hfst.is_diacritic(x)]
131
+ for analysis in self.weighted_lookup_full_analysis(input)
132
+ ]
133
+
134
+ def _weighted_lookup(self, input: str) -> list[tuple[str, tuple[str, ...]]]:
135
+ """
136
+ Internal Function. Transduce the input string. The result is a list of weighted tranductions. Each
137
+ weighted tranduction is a tuple with a number for the weight and a list of symbols returned in the model; that is, the symbols are
138
+ not concatenated into a single string.
139
+
140
+ :param input: The string to lookup.
141
+ :return:
142
+ """
143
+ return cast(
144
+ list[tuple[str, tuple[str, ...]]],
145
+ self.transducer.lookup(str(input), time_cutoff=self.cutoff, output="raw"),
146
+ )
147
+
148
+ def weighted_lookup_full_analysis(
149
+ self, wordform: str | Wordform, generator: Optional["TransducerFile"] = None
150
+ ) -> list[FullAnalysis]:
151
+ """
152
+ Transduce a wordform into a list of analyzed outputs. This method is likely only useful for analyser FSTs.
153
+
154
+ If a generator is provided, it will incorporate a standardized version of the string when available.
155
+ That is, it will pass the output to a secondary FST, and check if all the outputs of that "generator" FST match for an output.
156
+ If so, the output will be marked with the output string in the `standardized` field (See :py:class:`hfst_altlab.FullAnalysis`)
157
+
158
+ :param wordform: The string to lookup.
159
+ :param generator: The FST that will be used to fill the standardized version of the wordform from the produced analysis.
160
+ """
161
+ if generator:
162
+
163
+ def generate(tokens: tuple[str, ...]) -> str | None:
164
+ entry: str | None = None
165
+ for _, output in generator._weighted_lookup(fst_output_format(tokens)):
166
+ candidate = "".join(x for x in output if x and not hfst.is_diacritic(x))
167
+ if entry and entry != candidate:
168
+ return None
169
+ else:
170
+ entry = candidate
171
+ return entry
172
+
173
+ else:
174
+
175
+ def generate(tokens: tuple[str, ...]) -> str | None:
176
+ return None
177
+
178
+ return [
179
+ FullAnalysis(float(weight), tokens, generate(tokens))
180
+ for weight, tokens in self._weighted_lookup(as_fst_input(wordform))
181
+ ]
182
+
183
+ def weighted_lookup_full_wordform(
184
+ self, analysis: str | FullAnalysis
185
+ ) -> list[Wordform]:
186
+ """
187
+ Transduce the input string. The result is a list of weighted wordforms. This method is likely only useful for generator FSTs.
188
+
189
+ :param analysis: The string to lookup.
190
+ :return:
191
+ """
192
+ return [
193
+ Wordform(float(weight), tokens)
194
+ for weight, tokens in self._weighted_lookup(as_fst_input(analysis))
195
+ ]
196
+
197
+ def symbol_count(self) -> int:
198
+ """
199
+ Returns the number of symbols in the sigma (the symbol table or alphabet).
200
+
201
+ .. note:: Backwards-compatible with ``hfst-optimized-lookup``
202
+
203
+ """
204
+ return len(self.transducer.get_alphabet())
205
+
206
+ def invert(self) -> None:
207
+ """
208
+ Invert the transducer. That is, take what previously were outputs as inputs and produce as output what previously were inputs.
209
+
210
+ Although the same process can be done directly on the terminal, the intention of this method is to provide an easy way of obtaining the inverse FST.
211
+
212
+ .. warning:: Because the ``hfst`` python package cannot currently invert HFSTOL FSTs, we first convert the transducer to an SFST formatted equivalent. If for any reason you find out that the inverted FST is providing unexpected results, report a bug.
213
+ """
214
+ # Unfortunately, hfst does not directly invert hfstol FSTs.
215
+ # We take a detour by changing to a different format.
216
+ # We do not use foma here just in case we are not dealing with a system that has foma.
217
+ self.transducer.convert(hfst.ImplementationType.SFST_TYPE)
218
+ self.transducer.invert()
219
+ self.transducer.lookup_optimize()
220
+ return None
221
+
222
+
223
+ class TransducerPair:
224
+ """
225
+ This class provides a useful wrapper to combine an analyser FST and a generator FST for the same language.
226
+ It also provides sorted search when a distance function between two strings is provided.
227
+
228
+ For the cases when only a single FST is available but sorting is desired, use the :py:meth:`hfst_altlab.TransducerPair.duplicate` factory method, which produces a TransducerPair from a single FST.
229
+
230
+ On initialization, this class generates two :py:class:`hfst_altlab.TransducerFile` objects.
231
+
232
+ :param analyser: The path to the analyser FST (input: wordform, output: analyses)
233
+ :param generator: The path to the generator FST (input:analysis, output: wordforms)
234
+ :param search_cutoff: The maximum amount of time allowed for lookup on each transducer.
235
+ :param default_distance: An optional function providing a distance between two strings. (see :py:meth:`hfst_altlab.TransducerPair.analyse`)
236
+ """
237
+
238
+ analyser: TransducerFile
239
+ generator: TransducerFile
240
+ default_distance: None | Callable[[str, str], float]
241
+
242
+ def __init__(
243
+ self,
244
+ analyser: Path | str,
245
+ generator: Path | str,
246
+ search_cutoff: int = 60,
247
+ default_distance: None | Callable[[str, str], float] = None,
248
+ ):
249
+ self.analyser = TransducerFile(analyser, search_cutoff)
250
+ self.generator = TransducerFile(generator, search_cutoff)
251
+ self.default_distance = default_distance
252
+
253
+ def analyse(
254
+ self, input: Wordform | str, distance: None | Callable[[str, str], float] = None
255
+ ) -> list[FullAnalysis]:
256
+ """
257
+ Provide a list of analysis for a particular wordform using the analyser FST of this object.
258
+
259
+ If a `distance` function is provided (or the object has a `default_distance` property),
260
+ the results provided by the FST are sorted using the function to compute a distance between the
261
+ input wordform and the standardized wordform associated with each analysis (the result of applying the generator FST, if unique)
262
+
263
+ :param input: The wordform to analyse.
264
+ :param distance: The sorting function for this particular method call. When it is not `None`, it overrides `default_distance`, but only for this particular call.
265
+ """
266
+ candidate = self.analyser.weighted_lookup_full_analysis(input, self.generator)
267
+ sort_function = distance or self.default_distance
268
+ if sort_function:
269
+ # If there is a distance function, use that for sorting
270
+ source = str(input)
271
+
272
+ def key(other: FullAnalysis) -> float:
273
+ if other.standardized is None:
274
+ return float("+Infinity")
275
+ return sort_function(source, other.standardized)
276
+
277
+ candidate.sort(key=key)
278
+ return candidate
279
+
280
+ def generate(self, analysis: FullAnalysis | Analysis | str) -> list[Wordform]:
281
+ """
282
+ Provide a list of wordforms for a particular analysis using the generator FST of this object.
283
+
284
+ :param analysis: The analysis to generate via the FST.
285
+ """
286
+ input = (
287
+ "".join(analysis.prefixes) + analysis.lemma + "".join(analysis.suffixes)
288
+ if isinstance(analysis, Analysis)
289
+ else analysis
290
+ )
291
+ return self.generator.weighted_lookup_full_wordform(input)
292
+
293
+ @classmethod
294
+ def duplicate(
295
+ cls,
296
+ transducer: Path | str,
297
+ is_analyser: bool = False,
298
+ search_cutoff: int = 60,
299
+ default_distance: None | Callable[[str, str], float] = None,
300
+ ):
301
+ """
302
+ Factory Method. Generates a TransducerPair from a single FST. You can use the is_analyser argument to tell the direction of the input FST. Note that the FST will be generated twice before inverting one.
303
+
304
+ :param transducer: The location of the single FST used to generate a :py:class:`hfst_altlab.TransducerPair` object.
305
+ :param is_analyser: If true, then the generator FST is generated by inverting. If false, then the analyser FST is generated by inverting.
306
+ :param search_cutoff: The maximum amount of time (in seconds) that the search will go on for. The intention of a limit is to avoid search getting stuck.
307
+ :param default_distance: An optional function providing a distance between two strings. (see :py:meth:`hfst_altlab.TransducerPair.analyse`)
308
+ """
309
+ object = cls(
310
+ transducer,
311
+ transducer,
312
+ search_cutoff=search_cutoff,
313
+ default_distance=default_distance,
314
+ )
315
+ if is_analyser:
316
+ object.generator.invert()
317
+ else:
318
+ object.analyser.invert()
319
+ return object
320
+
321
+
322
+ def decompress_foma(filename: Path | str):
323
+ """
324
+ Single wrapper around gzip. This is to increase readability.
325
+ This method is not used, but it is suggested as a way to debug the process of building a Transducer from a FOMA object.
326
+ """
327
+ return gzip.open(filename)
@@ -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)
hfst_altlab/types.py ADDED
@@ -0,0 +1,231 @@
1
+ from typing import NamedTuple, Tuple
2
+ from hfst import is_diacritic
3
+
4
+
5
+ class Analysis(NamedTuple):
6
+ """
7
+ An analysis of a wordform. This class is backwards compatible with the ``hfst-optimized-lookup`` package.
8
+
9
+ This is a *named tuple*, so you can use it both with attributes and indices:
10
+
11
+ >>> analysis = Analysis(('PV/e+',), 'wâpamêw', ('+V', '+TA', '+Cnj', '+3Sg', '+4Sg/PlO'))
12
+
13
+ Using attributes:
14
+
15
+ >>> analysis.lemma
16
+ 'wâpamêw'
17
+ >>> analysis.prefixes
18
+ ('PV/e+',)
19
+ >>> analysis.suffixes
20
+ ('+V', '+TA', '+Cnj', '+3Sg', '+4Sg/PlO')
21
+
22
+ Using with indices:
23
+
24
+ >>> len(analysis)
25
+ 3
26
+ >>> analysis[0]
27
+ ('PV/e+',)
28
+ >>> analysis[1]
29
+ 'wâpamêw'
30
+ >>> analysis[2]
31
+ ('+V', '+TA', '+Cnj', '+3Sg', '+4Sg/PlO')
32
+ >>> prefixes, lemma, suffix = analysis
33
+ >>> lemma
34
+ 'wâpamêw'
35
+ """
36
+
37
+ prefixes: Tuple[str, ...]
38
+ """
39
+ Tags that appear before the lemma.
40
+ """
41
+
42
+ lemma: str
43
+ """
44
+ The base form of the analyzed wordform.
45
+ """
46
+
47
+ suffixes: Tuple[str, ...]
48
+ """
49
+ Tags that appear after the lemma.
50
+ """
51
+
52
+ def __str__(self) -> str:
53
+ return f"{''.join(self.prefixes)}{self.lemma}{''.join(self.suffixes)}"
54
+
55
+
56
+ def _parse_analysis(letters_and_tags: tuple[str, ...]) -> Analysis:
57
+ prefix_tags: list[str] = []
58
+ lemma_chars: list[str] = []
59
+ suffix_tags: list[str] = []
60
+
61
+ tag_destination = prefix_tags
62
+ for symbol in letters_and_tags:
63
+ if not is_diacritic(symbol):
64
+ if len(symbol) == 1:
65
+ lemma_chars.append(symbol)
66
+ tag_destination = suffix_tags
67
+ else:
68
+ assert len(symbol) > 1
69
+ tag_destination.append(symbol)
70
+
71
+ return Analysis(
72
+ tuple(prefix_tags),
73
+ "".join(lemma_chars),
74
+ tuple(suffix_tags),
75
+ )
76
+
77
+
78
+ class FullAnalysis:
79
+ """
80
+ An analysis for a wordform. Objects of this class include an analysis, a tuple of tokens (which provides information about flag diacritics), a weight (for weighted FST support), and a space to hold a standardized version of the wordform.
81
+ """
82
+
83
+ weight: float
84
+ """
85
+ The weight provided by the FST. If the FST is not weighted, it is likely to be ``0.0``.
86
+ """
87
+
88
+ tokens: tuple[str, ...]
89
+ """
90
+ The real output of the FST. Each element of the tuple is a symbol coming out of the FST.
91
+ The tuple includes flag diacritic symbols, which begin and end with an ``@`` character.
92
+ We remove empty flag diacritic transitions (``@_EPSILON_SYMBOL_@``) to make the information usable and comparable with the output of the CLI tools.
93
+ """
94
+
95
+ analysis: Analysis
96
+ """
97
+ A grouping of the prefixes, lemma, and suffixes produced in the output of the FST.
98
+
99
+ The analysis is a split of the non-diacritic symbols in the tokens list. We consider as the lemma the concatenation of all single-character symbols. Prefixes are all multi-character symbols happening before the first single-character symbol, and suffixes are all multi-character symbols happening after that.
100
+
101
+ .. note:: The assumption of single-character symbols will conflict with multi-character emojis (for example, skin toned emojis). Although we are currently keeping this implementation, an alternative future approach would be to define prefixes as all multi-character symbols terminating in ``+``, suffixes as all multi-character symbols beginning with ``+``, and the lemma to be the concatenation of all other symbols.
102
+ """
103
+ standardized: str | None
104
+
105
+ @property
106
+ def prefixes(self) -> tuple[str, ...]:
107
+ """
108
+ For simplicity, prefixes can be accessed directly as if this were an :py:class:`hfst_altlab.Analysis` object.
109
+ """
110
+ return self.analysis.prefixes
111
+
112
+ @property
113
+ def lemma(self) -> str:
114
+ """
115
+ For simplicity, the lemma can be accessed directly as if this were an :py:class:`hfst_altlab.Analysis` object.
116
+ """
117
+ return self.analysis.lemma
118
+
119
+ @property
120
+ def suffixes(self) -> tuple[str, ...]:
121
+ """
122
+ For simplicity, suffixes can be accessed directly as if this were an :py:class:`hfst_altlab.Analysis` object.
123
+ """
124
+ return self.analysis.suffixes
125
+
126
+ def __init__(
127
+ self, weight: float, tokens: tuple[str, ...], standardized: str | None = None
128
+ ):
129
+ """
130
+ This object is not usually created directly by library users, but it is the output of some methods of :py:class:`hfst_altlab.TransducerFile` and :py:class:`hfst_altlab.TransducerPair`.
131
+ The information comes from direct calls to the ``hfst`` library.
132
+ :param weight: The weight of this analysis
133
+ :param tokens: The tuple of tokens coming from the FST. It might contain empty symbols and epsilon diacritic transitions, which the FullAnalysis does not keep.
134
+ :param standardized: A standardized version of the associated wordform (only intrpoduced by :py:class:`hfst_altlab.TransducerPair` objects). It is the result of providing the analysis to some other generator FST.
135
+ """
136
+ self.weight = weight
137
+ self.tokens = tuple(x for x in tokens if x and x != "@_EPSILON_SYMBOL_@")
138
+ self.analysis = _parse_analysis(self.tokens)
139
+ self.standardized = standardized
140
+
141
+ def __str__(self):
142
+ return f"FullAnalysis(weight={self.weight}, prefixes={self.analysis.prefixes}, lemma={self.analysis.lemma}, suffixes={self.analysis.suffixes})"
143
+
144
+ def __repr__(self):
145
+ return f"FullAnalysis(weight={self.weight}, tokens={self.tokens})"
146
+
147
+ def __eq__(self, other):
148
+ """
149
+ Note that equality between wordforms considers both weight and all tokens generated by the FST. That is, there might be two Analysis objects such that ``a != b`` while ``a.lemma == b.lemma``, ``a.prefixes == b.prefixes``, and ``a.suffixes == b.suffixes``, if their flag diacritics are different.
150
+ """
151
+ if isinstance(other, self.__class__):
152
+ return self.weight == other.weight and self.tokens == other.tokens
153
+ else:
154
+ return False
155
+
156
+ def __hash__(self):
157
+ """
158
+ By providing a hashing function, we can place objects of this class into standard Python sets.
159
+ """
160
+ return hash((self.weight,) + self.tokens)
161
+
162
+ def as_fst_input(self) -> str:
163
+ return fst_output_format(self.tokens)
164
+
165
+
166
+ class Wordform:
167
+ """
168
+ A wordform is the output of passing an analysis to a generator FST.
169
+ """
170
+
171
+ weight: float
172
+ """
173
+ For weighted FSTs, the weight of this particular wordform output.
174
+ """
175
+
176
+ tokens: tuple[str, ...]
177
+ """
178
+ The real output of the FST. Each element of the tuple is a symbol coming out of the FST.
179
+ The tuple includes flag diacritic symbols, which begin and end with an ``@`` character.
180
+ We remove empty flag diacritic transitions (``@_EPSILON_SYMBOL_@``) to make the information usable and comparable with the output of the CLI tools.
181
+ """
182
+
183
+ wordform: str
184
+ """
185
+ The wordform associated with the FST output, obtained by concatenating all the non-flag diacritic symbols in the tokens tuple.
186
+ """
187
+
188
+ def __init__(self, weight: float, tokens: tuple[str, ...]):
189
+ self.weight = weight
190
+ self.tokens = tokens
191
+ self.wordform = "".join(
192
+ x for x in tokens if x and not is_diacritic(x) and x != "@_EPSILON_SYMBOL_@"
193
+ )
194
+
195
+ def __str__(self):
196
+ """
197
+ The string representation of this object. Equivalent to ``self.wordform``.
198
+ """
199
+ return self.wordform
200
+
201
+ def __repr__(self):
202
+ return f"Wordform(weight={self.weight}, wordform={self.wordform})"
203
+
204
+ def __eq__(self, other):
205
+ """
206
+ Note that equality between wordforms considers both weight and all tokens generated by the FST. That is, there might be two Wordform objects such that ``a != b`` while ``str(a) == str(b)``, if their flag diacritics are different.
207
+ """
208
+ if isinstance(other, self.__class__):
209
+ return self.weight == other.weight and self.tokens == other.tokens
210
+ else:
211
+ return False
212
+
213
+ def __hash__(self):
214
+ """
215
+ By providing a hashing function, we can place objects of this class into standard Python sets.
216
+ """
217
+ return hash((self.weight,) + self.tokens)
218
+
219
+ def as_fst_input(self):
220
+ return self.wordform
221
+
222
+
223
+ def as_fst_input(data: str | FullAnalysis | Wordform) -> str:
224
+ if isinstance(data, str):
225
+ return data
226
+ else:
227
+ return data.as_fst_input()
228
+
229
+
230
+ def fst_output_format(tokens: tuple[str, ...]) -> str:
231
+ return "".join(x for x in tokens if not is_diacritic(x))
@@ -0,0 +1,37 @@
1
+ Metadata-Version: 2.4
2
+ Name: hfst-altlab
3
+ Version: 0.1.2
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
+ Requires-Dist: hfst
15
+ Dynamic: license-file
16
+
17
+ hfst-altlab
18
+ ===========
19
+
20
+ A wrapper on the [hfst][] python package, currently working as a replacement for [hfst-optimized-lookup][], built originally for [itwêwina][].
21
+
22
+ This module helps to use both analyser and generator FSTs for multiple linguistic uses and language tools.
23
+
24
+ [itwêwina]: https://itwewina.altlab.app
25
+ [hfst-optimized-lookup]: https://github.com/UAlbertaALTLab/hfst-optimized-lookup
26
+ [hfst]: https://pypi.org/project/hfst/
27
+
28
+ Languages currently supported:
29
+ - Python
30
+
31
+ [hfst] is a great toolkit with all sorts of functionality, and is
32
+ indispensable for building FSTs, but for various applications that only
33
+ want to do unweighted hfstol lookups, this package may be easier to use.
34
+
35
+ [hfst]: https://github.com/hfst/hfst
36
+
37
+ [morphodict]: https://github.com/UAlbertaALTLab/morphodict
@@ -0,0 +1,8 @@
1
+ hfst_altlab/__init__.py,sha256=dRYo0ZPmN3SoxWMCZGDNFrjNRHBthMKTxT-9s_gY_24,14571
2
+ hfst_altlab/import_test.py,sha256=Fis-zc_Kw5pMkBFxey9Z9BYpdqRkHJmpam0d1BnsLZs,5472
3
+ hfst_altlab/types.py,sha256=pwyveMoHgUsJc8t7M2GRjuzXL3r94WG3QAF7d9KLiGU,8604
4
+ hfst_altlab-0.1.2.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
5
+ hfst_altlab-0.1.2.dist-info/METADATA,sha256=WxLHUZuBYplTBETieYT_AjEu4EaB8i5CX1qG5p-nDfo,1409
6
+ hfst_altlab-0.1.2.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
7
+ hfst_altlab-0.1.2.dist-info/top_level.txt,sha256=gQi_zoi-ZXaVv7mohs7_OBSvnXW-2v0mBSTCb6wgK7E,12
8
+ hfst_altlab-0.1.2.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.10.2)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -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 @@
1
+ hfst_altlab