engtagger 0.4.6 → 2.0.0.pre

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 61101478ee5332b3ba91df6598db0e4822832be62edaf5ac8613256d8ba8d7d4
4
- data.tar.gz: 903c665fd059b5095f2f240c2522f2a593d92bbf8cb500b142f6af373d48802c
3
+ metadata.gz: af1551df132a2b3d992f8de0bdb2cefa7ddbba8a5a8e06da200dad9ef6f0d909
4
+ data.tar.gz: d434df66126fad9b79fb896e527d0e30ab60f920a7eefd1ea37fc2fab8a64503
5
5
  SHA512:
6
- metadata.gz: 066d0510e7a585c38273a4fb28f33e05f9eb6f64a340b22ca3a6e05e8946866b769dc1966fc729f5351d16a318e6f6d2c41f4929a2bc627ad9d384654ba3a85f
7
- data.tar.gz: d19da0ed3236dcc64963cb64fe5a7833b3c3790433c9b4dee06c87e2abb2cdf30733cdf55a6b9409396096c0f95e383d47a8cd168f7fda954874c544646227d8
6
+ metadata.gz: 58647f6531a2a8271144e4a928af6abb477b4039386f94208f4eb841eaad2e309aafbbd23e758994640e777af0acc9c4b3c1b0b29cb735b6ee2330ee18696098
7
+ data.tar.gz: 1dde796134c2a1f6a6403be9f49d4944ee993abe95d4d470d50c2bcc995a65bf19c32c90b56143529d64991871fd9aa7bc3ad99180edaecf403d99175fb9b00c
data/CHANGELOG.md CHANGED
@@ -1,73 +1,43 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.0.0 (unreleased)
4
+
5
+ A rewrite of the tagging engine. Tagging and tokenization output differ from 0.4.x; pin `gem "engtagger", "~> 0.4"` to keep the old engine.
6
+
7
+ - Replace the HMM tagger with an averaged perceptron and a bundled model trained on UD English-EWT and automatically tagged Wikipedia, Wikinews and Stack Exchange text (see NOTICE).
8
+ - Add a PTB/UD-compatible tokenizer whose tokens are substrings of the input.
9
+ - Add the `tagset: :ptb` option, which makes `tag_pairs` and `get_readable` emit standard Penn Treebank tags.
10
+ - Remove the HMM probability tables derived from the Penn Treebank, `install`, `assign_tag`, `EngTagger.hmm`, `EngTagger.lexicon` and the `DEFAULT_*PATH` constants.
11
+ - Ignore the configuration keys of the HMM engine (`:relax`, `:unknown_word_tag`, lexicon paths) with a warning.
12
+ - Remove the `sin_lru_redux` dependency; the gem has no runtime dependencies.
13
+ - Require Ruby >= 3.0.
14
+ - Ship only `lib/` and the user-facing documents in the gem package.
15
+
3
16
  ## 0.4.6 (2026-11-14)
4
17
 
5
- - Fix `get_noun_phrases`, `get_words` and `add_tags` taking time quadratic in
6
- the input length on long runs of nouns and on long texts. Output is
7
- unchanged. Upgrade if you tag text from untrusted sources.
18
+ - Fix `get_noun_phrases`, `get_words` and `add_tags` taking time quadratic in the input length; output is unchanged. Upgrade if you tag text from untrusted sources.
8
19
 
9
20
  ## 0.4.5 (2026-08-14)
10
21
 
11
- License metadata correction; no code changes. This library is a port (2009) of
12
- Perl Lingua::EN::Tagger, which has been licensed GPL-3.0-only since its
13
- version 0.14 (2008). As a derivative work EngTagger is therefore GPL-3.0-only:
14
- the bundled LICENSE is now the GPLv3 text and the gemspec declares
15
- `GPL-3.0-only`. Earlier releases carried a GPLv2 license text, and 0.4.4
16
- declared `GPL-2.0-or-later`; both were inaccurate.
22
+ - Correct the license to GPL-3.0-only, the license of Lingua::EN::Tagger, which this library is a port of; the LICENSE file is now the GPLv3 text.
17
23
 
18
24
  ## 0.4.4 (2026-08-14)
19
25
 
20
- This is the final planned release of the 0.4 line. Version 2.0 replaces the
21
- HMM engine with an averaged perceptron and does not ship the Penn
22
- Treebank-derived probability tables, so its tagging output differs. Pin
23
- `gem "engtagger", "~> 0.4"` to stay on this line; it will receive critical
24
- fixes only.
25
-
26
- - Fix the test suite silently rewriting the bundled lexicon files
27
- (`lib/engtagger/*.hash`) on every run: a path-join bug in the test setup made
28
- the existence check always fail, so `install` ran before each test. This was
29
- also the enabler of the 0600-permission contamination behind #20. Tests are
30
- ~6x faster as a result.
31
- - `get_sentences` now applies its intended punctuation cleanup. Four of its
32
- five reattachment rules had discarded their results since the original port
33
- (only the leading-backquote rule was ever applied), and their regexes were
34
- corrupted by string escaping (`\W` matched a literal "W"). Sentences returned
35
- by this method now read naturally (`"Lisa Raines, a lawyer,"`,`"$3"`).
36
- Known limitation carried over from the tokenizer: contractions other than
37
- possessives remain space-separated (`"I 'm"`, `"is n't"`).
38
- - Fix the public `WORD` constant, whose regex was corrupted by the same
39
- escaping problem and matched only `<w>`-style tags.
40
- - Tag regexes produced by `EngTagger.get_ext` (NUM, NN, SEN, etc.) now end with
41
- a real `\s*`, so they consume trailing whitespace including newlines instead
42
- of spaces only.
43
- - `assign_tag` no longer raises `NoMethodError` for words absent from the
44
- lexicon; it returns `""` so callers fall back to `"nn"` as designed.
45
- - `EngTagger::VERSION` is now defined at runtime (`engtagger/version` was not
46
- required by the library itself).
47
- - Read and write the Marshal lexicon files in binary mode to avoid corruption
48
- on Windows.
49
- - Remove the stray shebang and executable bit from `lib/engtagger.rb`, and the
50
- obsolete `require "rubygems"`.
51
- - Clarify licensing: the LICENSE file had a stray MIT license appended after
52
- the GPLv2 text. The library is licensed as GPL-2.0-or-later; the MIT tail has
53
- been removed and the gemspec now declares the SPDX identifier.
54
- - Gemspec: use the https homepage URL, add `metadata` URIs, and drop the
55
- obsolete `test_files`.
56
- - Fix a dead test (`text_get_ext` typo) that had never run and would have
57
- failed if enabled.
58
- - Note in the README that 0.4.x carries Penn Treebank-derived probability
59
- tables; 2.x is trained on openly licensed data instead.
26
+ - Fix `get_sentences` so that punctuation is reattached to the neighboring word.
27
+ - Fix the `WORD` constant, which matched only `<w>` tags.
28
+ - Fix the tag regexes of `EngTagger.get_ext` so that they consume trailing whitespace, including newlines.
29
+ - Fix `assign_tag` raising `NoMethodError` for words absent from the lexicon.
30
+ - Fix the lexicon files being read and written in text mode, which corrupted them on Windows.
31
+ - Fix the test suite rewriting the bundled lexicon files on every run.
32
+ - Define `EngTagger::VERSION` when the library is required.
33
+ - Remove a stray MIT license text from the LICENSE file and declare the license in the gemspec.
34
+ - Remove the shebang and executable bit from `lib/engtagger.rb`.
60
35
 
61
36
  ## 0.4.3
62
37
 
63
- - Fix gem packaging that produced files with owner-only (0600) permissions,
64
- making the gem unreadable after a `sudo gem install` (#20). File permissions
65
- are now normalized before packaging.
66
- - Restore lost debug output in `valid_text` (a remnant of the Perl port left
67
- the message string in void context).
68
- - Clarify that the VBG tag covers both gerunds and present participles, as in
69
- the Penn Treebank tagset (#19).
70
- - Minor RuboCop cleanups.
38
+ - Fix gem files being packaged with owner-only permissions, which made the gem unreadable after `sudo gem install` (#20).
39
+ - Fix the debug message of `valid_text` not being printed.
40
+ - Document that the VBG tag covers both gerunds and present participles (#19).
71
41
 
72
42
  ## 0.4.2 and earlier
73
43
 
data/NOTICE ADDED
@@ -0,0 +1,73 @@
1
+ NOTICE — provenance and licensing of EngTagger 2.x
2
+
3
+ This file records where the pieces of this gem come from and under which
4
+ terms each is distributed. The source code is distributed under
5
+ GPL-3.0-only (see LICENSE). The bundled model file is distributed under
6
+ CC BY-SA 4.0 (section 2).
7
+
8
+ 1. Code lineage
9
+
10
+ EngTagger began (2009) as a Ruby port of the Perl library
11
+ Lingua::EN::Tagger by Aaron Coburn
12
+ (https://metacpan.org/dist/Lingua-EN-Tagger), which is licensed under
13
+ version 3 of the GNU General Public License.
14
+
15
+ Version 2.0 replaces the HMM tagger and probability tables of that
16
+ library with a new averaged-perceptron tagger, tokenizer and trained
17
+ model (lib/engtagger/perceptron.rb, tokenizer.rb, model.rb,
18
+ model_builder.rb), none of which is ported from it. lib/engtagger.rb
19
+ retains routines ported and adapted from Lingua::EN::Tagger for
20
+ extracting nouns, proper nouns and noun phrases, formatting tagged
21
+ output and related text processing, together with its tagset
22
+ conventions. The library keeps the licence of the 0.4 line,
23
+ GPL-3.0-only.
24
+
25
+ Lingua::EN::Tagger:
26
+ Copyright 2003-2010 Aaron Coburn
27
+ EngTagger:
28
+ Copyright (c) 2009-2026 Yoichiro Hasebe
29
+
30
+ The Porter stemmer (lib/engtagger/porter.rb) is the Ruby implementation
31
+ by Ray Pereda of the Porter stemming algorithm (Martin Porter, 1980),
32
+ from https://tartarus.org/martin/PorterStemmer/, where the
33
+ implementations are offered free of charge for any purpose.
34
+
35
+ 2. Bundled model (lib/engtagger/model.etm.gz)
36
+
37
+ The bundled part-of-speech model is a set of learned weights, distributed
38
+ under the Creative Commons Attribution-ShareAlike 4.0 International
39
+ licence (https://creativecommons.org/licenses/by-sa/4.0/). Whether learned
40
+ weights are a derivative of their training data is not legally settled;
41
+ the model takes the ShareAlike terms of the resources below as a
42
+ conservative choice.
43
+
44
+ The model was trained on:
45
+
46
+ - Universal Dependencies English Web Treebank (EWT), release 2.18.
47
+ https://github.com/UniversalDependencies/UD_English-EWT
48
+ Annotations (c) 2013-2021 The Board of Trustees of The Leland Stanford
49
+ Junior University. The annotations and database rights are licensed
50
+ CC BY-SA 4.0. That licence does not cover the underlying texts
51
+ (weblogs, newsgroups, emails, reviews and Yahoo! Answers); see the
52
+ treebank's README for the rights in them.
53
+
54
+ - Sentences from Wikipedia, Wikinews and Stack Exchange, tagged
55
+ automatically with Claude Sonnet 5 (`claude-sonnet-5`, Anthropic) in
56
+ July 2026:
57
+ Wikipedia CC BY-SA 4.0
58
+ Wikinews public domain, CC BY 2.5 or CC BY 4.0, by publication
59
+ date
60
+ Stack Exchange CC BY-SA 2.5, 3.0 or 4.0, per post
61
+ Every article and post is listed with its URL, revision or author, and
62
+ licence at
63
+ https://github.com/yohasebe/engtagger/tree/master/sources
64
+ Neither the original authors nor Anthropic endorse the model.
65
+
66
+ When redistributing the model file, keep this notice.
67
+
68
+ 3. Not included
69
+
70
+ Unlike the 0.4.x line, this version bundles no data derived from the Penn
71
+ Treebank; the classic HMM probability tables were retired with the HMM
72
+ engine. The 0.4.x releases remain available on RubyGems for users who
73
+ need them (gem "engtagger", "~> 0.4").
data/README.md CHANGED
@@ -1,80 +1,136 @@
1
1
  # EngTagger
2
2
 
3
- English Part-of-Speech Tagger Library; a Ruby port of Lingua::EN::Tagger
3
+ English part-of-speech tagger library in pure Ruby
4
4
 
5
5
  ## Description
6
6
 
7
- A Ruby port of Perl Lingua::EN::Tagger, a probability based, corpus-trained
8
- tagger that assigns POS tags to English text based on a lookup dictionary and
9
- a set of probability values. The tagger assigns appropriate tags based on
10
- conditional probabilities--it examines the preceding tag to determine the
11
- appropriate tag for the current word. Unknown words are classified according to
12
- word morphology or can be set to be treated as nouns or other parts of speech.
13
- The tagger also extracts as many nouns and noun phrases as it can, using a set
14
- of regular expressions.
7
+ EngTagger assigns Penn Treebank-style part-of-speech tags to English text and
8
+ extracts nouns and noun phrases from the tagged result. Since version 2.0 the
9
+ tagger is an **averaged perceptron** with a bundled model — no external
10
+ dependencies, no Python, no network: `gem install engtagger` and everything
11
+ runs anywhere Ruby (>= 3.0) runs.
12
+
13
+ The tagging and extraction methods of the 0.4 line are kept, with considerably
14
+ more accurate tags. See [Upgrading from 0.4.x](#upgrading-from-04x) for what
15
+ was removed.
15
16
 
16
17
  ## Features
17
18
 
18
- * Assigns POS tags to English text
19
- * Extract noun phrases from tagged text
20
- * etc.
19
+ * Part-of-speech tagging with a corpus-trained averaged perceptron
20
+ * PTB/Universal Dependencies-compatible word tokenizer (non-destructive:
21
+ every token is a substring of the input)
22
+ * Noun and noun-phrase extraction from tagged text
23
+ * Classic XML-style tagged output, or standard Penn Treebank tags via
24
+ `tagset: :ptb`
25
+ * Pure Ruby, zero runtime dependencies, 2.4 MB bundled model
26
+ * One tagger object can be shared between threads
27
+
28
+ ## Accuracy
29
+
30
+ ![Token accuracy of EngTagger and other POS taggers](https://raw.githubusercontent.com/yohasebe/engtagger/master/docs/accuracy.svg)
31
+
32
+ Token accuracy (%) on the test splits of two Universal Dependencies English
33
+ treebanks — [EWT](https://universaldependencies.org/treebanks/en_ewt/) (web
34
+ media: reviews, emails, forums) and
35
+ [GUM](https://universaldependencies.org/treebanks/en_gum/) (multi-genre) —
36
+ using Penn Treebank tags, gold tokenization and gold sentence boundaries
37
+ (Universal Dependencies release 2.18):
38
+
39
+ | System | Algorithm | EWT test | GUM test |
40
+ |---|---|---|---|
41
+ | EngTagger 0.4 (previous) | HMM (bigram) | 84.9 | 88.4 |
42
+ | NLTK 3 | averaged perceptron, WSJ-trained | 85.1 | 90.4 |
43
+ | **EngTagger 2.0 (this gem)** | **averaged perceptron** | **94.2** | **95.7** |
44
+ | Stanza | neural, EWT-trained | 96.2 | 97.7 |
45
+
46
+ For a fair reading of the numbers:
47
+
48
+ * **EngTagger 2.0** is measured with the model file shipped in this gem. It
49
+ is trained on the EWT training split and on automatically tagged text from
50
+ Wikipedia, Wikinews and Stack Exchange. No GUM annotations were used in
51
+ training, so GUM is a held-out treebank for it.
52
+ * The figures are for text that is already split into sentences and tokens.
53
+ Tagging raw text also depends on the tokenizer.
54
+ * **NLTK 3** uses the same algorithm family as EngTagger 2.0 but its bundled
55
+ model is trained on Wall Street Journal text, so it runs out-of-domain on
56
+ these test sets.
57
+ * **Stanza** is a neural pipeline (Python/PyTorch, large models) trained on
58
+ EWT itself; it serves as the accuracy reference point, at the cost of
59
+ dependencies and compute.
21
60
 
22
61
  ## Synopsis
23
62
 
24
63
  ```ruby
25
64
  require 'engtagger'
26
65
 
27
- # Create a parser object
66
+ # Create a tagger object
28
67
  tgr = EngTagger.new
29
68
 
30
69
  # Sample text
31
- text = "Alice chased the big fat cat."
70
+ text = "Alice chased the big black cat."
32
71
 
33
72
  # Add part-of-speech tags to text
34
73
  tagged = tgr.add_tags(text)
35
74
 
36
- #=> "<nnp>Alice</nnp> <vbd>chased</vbd> <det>the</det> <jj>big</jj> <jj>fat</jj><nn>cat</nn> <pp>.</pp>"
75
+ #=> "<nnp>Alice</nnp> <vbd>chased</vbd> <det>the</det> <jj>big</jj> <jj>black</jj> <nn>cat</nn> <pp>.</pp>"
37
76
 
38
77
  # Get a list of all nouns and noun phrases with occurrence counts
39
78
  word_list = tgr.get_words(text)
40
79
 
41
- #=> {"Alice"=>1, "cat"=>1, "fat cat"=>1, "big fat cat"=>1}
80
+ #=> {"Alice" => 1, "big black cat" => 1, "black cat" => 1, "cat" => 1}
42
81
 
43
82
  # Get a readable version of the tagged text
44
83
  readable = tgr.get_readable(text)
45
84
 
46
- #=> "Alice/NNP chased/VBD the/DET big/JJ fat/JJ cat/NN ./PP"
85
+ #=> "Alice/NNP chased/VBD the/DET big/JJ black/JJ cat/NN ./PP"
47
86
 
48
87
  # Get all nouns from a tagged output
49
88
  nouns = tgr.get_nouns(tagged)
50
89
 
51
- #=> {"cat"=>1, "Alice"=>1}
90
+ #=> {"Alice" => 1, "cat" => 1}
52
91
 
53
92
  # Get all proper nouns
54
93
  proper = tgr.get_proper_nouns(tagged)
55
94
 
56
- #=> {"Alice"=>1}
95
+ #=> {"Alice" => 1}
57
96
 
58
97
  # Get all past tense verbs
59
98
  pt_verbs = tgr.get_past_tense_verbs(tagged)
60
99
 
61
- #=> {"chased"=>1}
100
+ #=> {"chased" => 1}
62
101
 
63
102
  # Get all the adjectives
64
103
  adj = tgr.get_adjectives(tagged)
65
104
 
66
- #=> {"big"=>1, "fat"=>1}
105
+ #=> {"big" => 1, "black" => 1}
67
106
 
68
107
  # Get all noun phrases of any syntactic level
69
- # (same as word_list but take a tagged input)
108
+ # (same as word_list but takes a tagged input)
70
109
  nps = tgr.get_noun_phrases(tagged)
71
110
 
72
- #=> {"Alice"=>1, "cat"=>1, "fat cat"=>1, "big fat cat"=>1}
111
+ #=> {"Alice" => 1, "big black cat" => 1, "black cat" => 1, "cat" => 1}
112
+
113
+ # Standard Penn Treebank tags, if you prefer them over the classic tagset
114
+ ptb = EngTagger.new(tagset: :ptb)
115
+ ptb.get_readable(text)
116
+
117
+ #=> "Alice/NNP chased/VBD the/DT big/JJ black/JJ cat/NN ./."
118
+
119
+ ptb.tag_pairs("Alice chased the cat.")
120
+
121
+ #=> [["Alice", :NNP], ["chased", :VBD], ["the", :DT], ["cat", :NN], [".", :"."]]
73
122
  ```
74
123
 
75
124
  ## Tag Set
76
125
 
77
- The set of POS tags used here is a modified version of the Penn Treebank tagset. Tags with non-letter characters have been redefined to work better in our data structures. Also, the "Determiner" tag (DET) has been changed from 'DT', in order to avoid confusion with the HTML tag, `<DT>`.
126
+ `add_tags`, `tag_pairs` and `get_readable` use the classic EngTagger tagset by
127
+ default: a modified Penn Treebank tagset in which tags with non-letter
128
+ characters are renamed to work in XML-style markup and regular expressions
129
+ (`DET` for `DT`, `PRPS` for `PRP$`, and named punctuation classes such as `PP`
130
+ for `.`). With `EngTagger.new(tagset: :ptb)`, `tag_pairs` and `get_readable`
131
+ emit standard Penn Treebank tags instead; `add_tags` always uses the classic
132
+ tagset, whose tags are valid element names. The text inside the tags is not
133
+ escaped.
78
134
 
79
135
  CC Conjunction, coordinating and, or
80
136
  CD Adjective, cardinal number 3, fifteen
@@ -122,63 +178,61 @@ The set of POS tags used here is a modified version of the Penn Treebank tagset.
122
178
  LRB Punctuation, left bracket (, {, [
123
179
  RRB Punctuation, right bracket ), }, ]
124
180
 
125
- ## Installation
181
+ ## The bundled model
126
182
 
127
- **Recommended Approach (without sudo):**
183
+ The tagger ships with an averaged-perceptron model
184
+ (`lib/engtagger/model.etm.gz`, distributed under CC BY-SA 4.0) trained on:
128
185
 
129
- It is recommended to install the `engtagger` gem within your user environment without root privileges. This ensures proper file permissions and avoids potential issues. You can achieve this by using Ruby version managers like `rbenv` or `rvm` to manage your Ruby versions and gemsets.
186
+ * the [Universal Dependencies English Web Treebank](https://github.com/UniversalDependencies/UD_English-EWT),
187
+ whose annotations are licensed CC BY-SA 4.0;
188
+ * about 32,000 sentences from Wikipedia, Wikinews and Stack Exchange, tagged
189
+ automatically with a large language model. Every article and post is listed
190
+ with its licence in [`sources/`](https://github.com/yohasebe/engtagger/tree/master/sources).
130
191
 
131
- To install without `sudo`, simply run:
192
+ Unlike the 0.4.x line, no Penn Treebank-derived data is included. Provenance
193
+ and attribution details are in the NOTICE file; the packed model format is
194
+ documented in the repository (`docs/model-format.md`).
195
+
196
+ ## Installation
132
197
 
133
198
  ```bash
134
199
  gem install engtagger
135
200
  ```
136
201
 
137
- **Alternative Approach (with sudo):**
138
-
139
- If you must use `sudo` for installation, you'll need to adjust file permissions afterward to ensure accessibility.
202
+ Requires Ruby >= 3.0 and nothing else. Pre-release versions are installed with
203
+ `gem install engtagger --pre`.
140
204
 
141
- 1. Install the gem with `sudo`:
205
+ ## Upgrading from 0.4.x
142
206
 
143
- ```bash
144
- sudo gem install engtagger
145
- ```
207
+ The tagging and extraction methods keep their names and arguments, but the
208
+ tags themselves are produced by a different, considerably more accurate
209
+ engine, so tagged output is not byte-identical to 0.4.x. Tokenization also
210
+ follows PTB/UD conventions more closely (e.g. `don't` splits as `do|n't`).
211
+ Configuration keys of the retired HMM engine
212
+ (`:relax`, `:unknown_word_tag`, lexicon paths) are accepted and ignored with
213
+ a warning; `install`, `assign_tag`, `EngTagger.hmm`, `EngTagger.lexicon` and
214
+ the `DEFAULT_LEXPATH`, `DEFAULT_WORDPATH` and `DEFAULT_TAGPATH` constants were
215
+ removed.
146
216
 
147
- 2. Grant necessary permissions to your user:
217
+ If you need the old engine's exact output, pin the previous line:
148
218
 
149
- ```bash
150
- sudo chown -R $(whoami) /Library/Ruby/Gems/2.6.0/gems/engtagger-0.4.2
219
+ ```ruby
220
+ gem "engtagger", "~> 0.4"
151
221
  ```
152
222
 
153
- **Note:** The path above assumes you are using Ruby version 2.6.0. If you are using a different version, you will need to modify the path accordingly. You can find your Ruby version by running `ruby -v`.
154
-
155
- ## Troubleshooting
156
-
157
- **Permission Issues:**
158
-
159
- If you encounter "cannot load such file" errors after installation, it might be due to incorrect file permissions. Ensure you've followed the instructions for adjusting permissions if you used `sudo` during installation.
160
-
161
223
  ## Author
162
224
 
163
- Yoichiro Hasebe (yohasebe [at] gmail.com)
164
-
165
- ## Contributors
166
-
167
- Many thanks to the collaborators listed in the right column of this GitHub page.
225
+ Yoichiro Hasebe
168
226
 
169
- ## Acknowledgement
170
-
171
- This Ruby library is a direct port of Lingua::EN::Tagger available at CPAN.
172
- The credit for the crucial part of its algorithm/design therefore goes to
173
- Aaron Coburn, the author of the original Perl version.
227
+ EngTagger began in 2009 as a Ruby port of Lingua::EN::Tagger by Aaron Coburn.
228
+ Version 2.0 replaces its HMM tagger and probability tables with a new
229
+ averaged-perceptron tagger, tokenizer and trained model. The extraction of
230
+ nouns and noun phrases and the formatting of tagged output retain routines
231
+ ported and adapted from Lingua::EN::Tagger.
174
232
 
175
233
  ## License
176
234
 
177
235
  This library is distributed under the GNU General Public License version 3
178
- (GPL-3.0-only), following the license of the Perl library it derives from
179
- (Lingua::EN::Tagger has been GPL-3 since its version 0.14, 2008). Please see
180
- the LICENSE file.
181
-
182
- The 0.4 line ships probability tables derived from the Penn Treebank. Version
183
- 2.0 drops them in favour of a model trained on openly licensed corpora; if the
184
- provenance of the bundled data matters for your use, prefer 2.x.
236
+ (GPL-3.0-only), the same license as the 0.4 line.
237
+ See the LICENSE file, and the NOTICE file for the licensing of the bundled
238
+ model and its training data.
Binary file
@@ -0,0 +1,178 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "stringio"
4
+ require "zlib"
5
+
6
+ class EngTagger
7
+ # Packed, read-only container for a trained averaged-perceptron model.
8
+ #
9
+ # The trainer produces string-keyed weights ("i-1 tag+i word nn the" =>
10
+ # {"nn" => 1.25, ...}), one small Hash per feature. This format keeps the
11
+ # feature strings -- a feature absent from the model can then never be
12
+ # mistaken for one that is present -- but replaces the per-feature Hashes
13
+ # with one packed buffer of postings, so a loaded model is a single
14
+ # String => Integer index plus a flat byte string.
15
+ #
16
+ # Weights are quantized to int16 with a fixed scale. Since every weight
17
+ # shares one scale, tag scores can be accumulated as integers and compared
18
+ # directly -- the scale never enters the argmax.
19
+ #
20
+ # ETM2 layout (little-endian; see docs/model-format.md):
21
+ # magic "ETM2" | u16 version | u16 flags | u16 scale | u16 n_classes
22
+ # u32 n_features | u32 n_postings | u32 n_tagdict | u32 keys_bytes
23
+ # classes: n_classes x [u8 len, bytes] (tag_id order)
24
+ # tagdict: n_tagdict x [u8 len, bytes, u8 tag_id] (bytewise ascending)
25
+ # keys: n_features x [bytes, 0x00] (bytewise ascending)
26
+ # counts: n_features x u8 (postings per feature)
27
+ # postings: n_postings x [u8 tag_id, i16 weight]
28
+ class Model
29
+ MAGIC = "ETM2"
30
+ FORMAT_VERSION = 2
31
+ FLAG_QUANTIZED = 0x1
32
+ HEADER_SIZE = 28
33
+ POSTING_SIZE = 3
34
+ KEY_TERMINATOR = "\0"
35
+
36
+ # Upper bound on the inflated size of a gzipped model file.
37
+ MAX_PACKED_BYTES = 256 * 1024 * 1024
38
+
39
+ attr_reader :classes, :tagdict, :weight_scale
40
+
41
+ class Error < StandardError; end
42
+
43
+ # Read a model file, gzipped or not.
44
+ def self.read(path)
45
+ blob = File.binread(path)
46
+ blob = inflate(blob) if blob.start_with?("\x1f\x8b".b)
47
+ new(blob)
48
+ end
49
+
50
+ def self.inflate(blob)
51
+ gz = Zlib::GzipReader.new(StringIO.new(blob))
52
+ packed = gz.read(MAX_PACKED_BYTES + 1).to_s.b
53
+ raise Error, "model file inflates to more than #{MAX_PACKED_BYTES} bytes" if packed.bytesize > MAX_PACKED_BYTES
54
+
55
+ gz.read(1) # reaching the end of the stream is what verifies the gzip checksum
56
+ packed
57
+ rescue Zlib::Error => e
58
+ raise Error, "corrupt gzip container: #{e.message}"
59
+ end
60
+ private_class_method :inflate
61
+
62
+ def initialize(blob)
63
+ parse_header(blob)
64
+ parse_sections(blob)
65
+ end
66
+
67
+ # Number of distinct features carried by this model.
68
+ def size
69
+ @index.size
70
+ end
71
+
72
+ # Yield [tag_id, quantized_weight] for each posting of `feature`, or
73
+ # nothing when the feature is absent. Written as an each-style method so
74
+ # scoring allocates no intermediate array per lookup.
75
+ def each_posting(feature)
76
+ slot = @index[key_of(feature)]
77
+ return unless slot
78
+
79
+ pos = (slot >> 8) * POSTING_SIZE
80
+ (slot & 0xff).times do
81
+ yield @postings.getbyte(pos), unpack_i16(pos + 1)
82
+ pos += POSTING_SIZE
83
+ end
84
+ end
85
+
86
+ # Yield each feature string.
87
+ def each_feature(&block)
88
+ @index.each_key(&block)
89
+ end
90
+
91
+ # Human-readable weight, mainly for inspection and tests.
92
+ def weight(feature, tag)
93
+ tag_id = @classes.index(tag) or return 0.0
94
+ each_posting(feature) { |t, w| return w.fdiv(@weight_scale) if t == tag_id }
95
+ 0.0
96
+ end
97
+
98
+ private
99
+
100
+ # Keys are compared as UTF-8 byte strings, whatever encoding the tagged
101
+ # text arrived in.
102
+ def key_of(feature)
103
+ feature.encoding == Encoding::UTF_8 ? feature : feature.b.force_encoding(Encoding::UTF_8)
104
+ end
105
+
106
+ def unpack_i16(pos)
107
+ v = @postings.getbyte(pos) | (@postings.getbyte(pos + 1) << 8)
108
+ v >= 0x8000 ? v - 0x10000 : v
109
+ end
110
+
111
+ def parse_header(blob)
112
+ raise Error, "not an EngTagger model file" unless blob.byteslice(0, 4) == MAGIC && blob.bytesize >= HEADER_SIZE
113
+
114
+ version, flags, @weight_scale, @n_classes = blob.byteslice(4, 8).unpack("v4")
115
+ raise Error, "unsupported model format version #{version}" unless version == FORMAT_VERSION
116
+ raise Error, "model is not quantized" unless flags.anybits?(FLAG_QUANTIZED)
117
+ raise Error, "model has a zero weight scale" if @weight_scale.zero?
118
+
119
+ @n_features, @n_postings, @n_tagdict, @keys_bytes = blob.byteslice(12, 16).unpack("V4")
120
+ end
121
+
122
+ def parse_sections(blob)
123
+ pos = parse_classes(blob, HEADER_SIZE)
124
+ pos = parse_tagdict(blob, pos)
125
+ expected = pos + @keys_bytes + @n_features + (@n_postings * POSTING_SIZE)
126
+ raise Error, "model file is truncated or has trailing data" unless blob.bytesize == expected
127
+
128
+ build_index(blob, pos)
129
+ end
130
+
131
+ def parse_classes(blob, pos)
132
+ @classes = Array.new(@n_classes) do
133
+ tag, pos = read_string(blob, pos)
134
+ tag
135
+ end
136
+ pos
137
+ end
138
+
139
+ def parse_tagdict(blob, pos)
140
+ @tagdict = {}
141
+ @n_tagdict.times do
142
+ word, pos = read_string(blob, pos)
143
+ @tagdict[word] = @classes.fetch(blob.getbyte(pos) || @n_classes) do
144
+ raise Error, "tag dictionary refers to an unknown tag"
145
+ end
146
+ pos += 1
147
+ end
148
+ pos
149
+ end
150
+
151
+ # => [string, position after it]
152
+ def read_string(blob, pos)
153
+ len = blob.getbyte(pos) or raise Error, "model file is truncated"
154
+ bytes = blob.byteslice(pos + 1, len)
155
+ raise Error, "model file is truncated" unless bytes && bytes.bytesize == len
156
+
157
+ [bytes.force_encoding(Encoding::UTF_8).freeze, pos + 1 + len]
158
+ end
159
+
160
+ # One String => Integer Hash for the whole model: feature => posting
161
+ # offset in the high bits, posting count in the low byte. The postings
162
+ # themselves stay in one packed buffer.
163
+ def build_index(blob, pos)
164
+ keys = blob.byteslice(pos, @keys_bytes).force_encoding(Encoding::UTF_8).split(KEY_TERMINATOR)
165
+ counts = blob.byteslice(pos + @keys_bytes, @n_features).unpack("C*")
166
+ raise Error, "model index does not match its header" unless keys.size == @n_features && counts.sum == @n_postings
167
+
168
+ @postings = blob.byteslice(pos + @keys_bytes + @n_features, @n_postings * POSTING_SIZE)
169
+ @index = {}
170
+ offset = 0
171
+ keys.each_with_index do |key, i|
172
+ @index[key.freeze] = (offset << 8) | counts[i]
173
+ offset += counts[i]
174
+ end
175
+ raise Error, "model index has duplicate features" unless @index.size == @n_features
176
+ end
177
+ end
178
+ end