engtagger 2.0.0.pre3 → 2.0.0.pre4

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: b89f4c9aed0238597b71b1f5bd1a32cd99e09448778c4fc486ff281dbbf60d45
4
- data.tar.gz: 1123bad4fa5901d9f67e5c34a2783487af73dfb5c130999b96ca2b9c3f09b0eb
3
+ metadata.gz: 86ed98bd1fbb1c3ddd98ac3acd52bcc1a31e2396afab1afec631ba87e3f76e47
4
+ data.tar.gz: ab32f9642922a5506b94634faeb1ae607481ddcbcd1cf0ddc5ccd5ed656a1a7a
5
5
  SHA512:
6
- metadata.gz: e81868b829d035cd540c27bad7e2a97f4a6e82930f3fa360ea2c05c0685b6de1fc9247cbea8fe89ae2e8573de0169dffaa65c9d5eccfd51bc9f8075a9be1a0f5
7
- data.tar.gz: 478095438721d6b67c34df79871a02a6215480c2b4136c87eb5144045b2f2b8c05400f7e7a91abb673f9d437c9a4a3d74ae4e9ca89fdd05d06c262cc4d8cfa66
6
+ metadata.gz: 84209f716543f6fb62725f4e9905bd15ab939b5548c5ed2026a86ff037234f2e80db98df2c204dad49b39d49cc5d9715a1ed142afe57e4f06af20be126fe5004
7
+ data.tar.gz: c245d3971b7d6deba393e95879fa96f9d0b5612e77cd9f996d03f918ec3251abf668e441351954e32c58c44051d265789c9dda7a3892e6e12348937a6ffcc826
data/CHANGELOG.md CHANGED
@@ -6,7 +6,9 @@ A rewrite of the tagging engine. Tagging and tokenization output differ from 0.4
6
6
 
7
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
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.
9
+ - Tag each sentence of a text on its own, splitting after `.`, `!` and `?`.
10
+ - Add `tag_tokens`, which tags one sentence that is already split into tokens.
11
+ - Add the `tagset: :ptb` option, which makes `tag_pairs`, `tag_tokens` and `get_readable` emit standard Penn Treebank tags.
10
12
  - Remove the HMM probability tables derived from the Penn Treebank, `install`, `EngTagger.hmm`, `EngTagger.lexicon` and the `DEFAULT_*PATH` constants.
11
13
  - Correct the descriptions of several tags; the verbose names from `EngTagger.explain_tag`, `add_tags(text, true)` and `get_readable(text, true)` change accordingly.
12
14
  - Keep `assign_tag(prev_tag, word)`, which now tags one word with the bundled model.
data/README.md CHANGED
@@ -19,6 +19,7 @@ was removed.
19
19
  * Part-of-speech tagging with a corpus-trained averaged perceptron
20
20
  * PTB/Universal Dependencies-compatible word tokenizer (non-destructive:
21
21
  every token is a substring of the input)
22
+ * Each sentence of a text is tagged on its own
22
23
  * Noun and noun-phrase extraction from tagged text
23
24
  * Classic XML-style tagged output, or standard Penn Treebank tags via
24
25
  `tagset: :ptb`
@@ -108,13 +109,26 @@ ptb.get_readable(text)
108
109
  ptb.tag_pairs("Alice chased the cat.")
109
110
 
110
111
  #=> [["Alice", :NNP], ["chased", :VBD], ["the", :DT], ["cat", :NN], [".", :"."]]
112
+
113
+ # Tag one sentence that you have already split into tokens
114
+ tgr.tag_tokens(["Alice", "chased", "the", "cat", "."])
115
+
116
+ #=> [:nnp, :vbd, :det, :nn, :pp]
111
117
  ```
112
118
 
119
+ ## Sentences
120
+
121
+ A text is split into sentences and each sentence is tagged on its own. A
122
+ sentence ends after a period that stands alone or a run of `!` and `?`
123
+ (`!`, `?`, `?!`), together with any closing brackets or quotation marks that
124
+ follow it; abbreviations such as `Dr.`, `...` and line breaks do not end one.
125
+ If you split sentences yourself, pass them one at a time to `tag_tokens`.
126
+
113
127
  ## Options
114
128
 
115
129
  ```ruby
116
130
  EngTagger.new(
117
- tagset: :ptb, # standard tags from tag_pairs and get_readable (default: classic tagset)
131
+ tagset: :ptb, # standard tags from tag_pairs, tag_tokens and get_readable (default: classic tagset)
118
132
  stem: true, # stem the words returned by the extraction methods (default: false)
119
133
  longest_noun_phrase: 3, # longest noun phrase to extract, in words (default: 5)
120
134
  weight_noun_phrases: true # multiply the count of a noun phrase by its length in words (default: false)
@@ -123,12 +137,12 @@ EngTagger.new(
123
137
 
124
138
  ## Tag Set
125
139
 
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
140
+ `add_tags`, `tag_pairs`, `tag_tokens` and `get_readable` use the classic
141
+ EngTagger tagset by default: a modified Penn Treebank tagset in which tags with non-letter
128
142
  characters are renamed to work in XML-style markup and regular expressions
129
143
  (`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
144
+ for `.`). With `EngTagger.new(tagset: :ptb)`, `tag_pairs`, `tag_tokens` and
145
+ `get_readable` emit standard Penn Treebank tags instead; `add_tags` always uses the classic
132
146
  tagset. The text inside the tags is not escaped.
133
147
 
134
148
  With `tagset: :ptb`, the extended Penn Treebank tags used by Universal
@@ -11,7 +11,7 @@ class EngTagger
11
11
  # feature strings -- a feature absent from the model can then never be
12
12
  # mistaken for one that is present -- but replaces the per-feature Hashes
13
13
  # with one packed buffer of postings, so a loaded model is a single
14
- # String => Integer index plus a flat byte string.
14
+ # String => Integer index, a flat byte string and an array of weights.
15
15
  #
16
16
  # Weights are quantized to int16 with a fixed scale. Since every weight
17
17
  # shares one scale, tag scores can be accumulated as integers and compared
@@ -70,16 +70,35 @@ class EngTagger
70
70
  end
71
71
 
72
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.
73
+ # nothing when the feature is absent.
75
74
  def each_posting(feature)
76
75
  slot = @index[key_of(feature)]
77
76
  return unless slot
78
77
 
79
- pos = (slot >> 8) * POSTING_SIZE
78
+ pos = slot >> 8
80
79
  (slot & 0xff).times do
81
- yield @postings.getbyte(pos), unpack_i16(pos + 1)
82
- pos += POSTING_SIZE
80
+ yield @postings.getbyte(pos * POSTING_SIZE), @weights[pos]
81
+ pos += 1
82
+ end
83
+ end
84
+
85
+ # Add the quantized weights of `feature` to `scores`, an array indexed by
86
+ # tag_id. Does nothing when the feature is absent. Scoring spends nearly
87
+ # all of its time here, so the loop is written out instead of going
88
+ # through each_posting.
89
+ def add_scores(feature, scores)
90
+ slot = @index[key_of(feature)]
91
+ return unless slot
92
+
93
+ pos = slot >> 8
94
+ stop = pos + (slot & 0xff)
95
+ byte = pos * POSTING_SIZE
96
+ postings = @postings
97
+ weights = @weights
98
+ while pos < stop
99
+ scores[postings.getbyte(byte)] += weights[pos]
100
+ pos += 1
101
+ byte += POSTING_SIZE
83
102
  end
84
103
  end
85
104
 
@@ -103,11 +122,6 @@ class EngTagger
103
122
  feature.encoding == Encoding::UTF_8 ? feature : feature.b.force_encoding(Encoding::UTF_8)
104
123
  end
105
124
 
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
125
  def parse_header(blob)
112
126
  raise Error, "not an EngTagger model file" unless blob.byteslice(0, 4) == MAGIC && blob.bytesize >= HEADER_SIZE
113
127
 
@@ -158,8 +172,8 @@ class EngTagger
158
172
  end
159
173
 
160
174
  # 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.
175
+ # offset in the high bits, posting count in the low byte. Tag ids are read
176
+ # from the packed buffer; the weights are unpacked once into an array.
163
177
  def build_index(blob, pos)
164
178
  keys = blob.byteslice(pos, @keys_bytes).force_encoding(Encoding::UTF_8).split(KEY_TERMINATOR)
165
179
  counts = blob.byteslice(pos + @keys_bytes, @n_features).unpack("C*")
@@ -173,6 +187,8 @@ class EngTagger
173
187
  offset += counts[i]
174
188
  end
175
189
  raise Error, "model index has duplicate features" unless @index.size == @n_features
190
+
191
+ @weights = @postings.unpack("xs<" * @n_postings)
176
192
  end
177
193
  end
178
194
  end
@@ -40,6 +40,10 @@ class EngTagger
40
40
  # Classic EngTagger tag -> PTB tag, for the renamed categories.
41
41
  PTB_TAGS = RENAMED_TAGS.each_with_object({}) { |(ptb, classic), h| h[classic] ||= ptb }.freeze
42
42
 
43
+ # A token that ends a sentence, and the closing marks that stay with it.
44
+ SENTENCE_END = /\A(?:\.|[!?]+)\z/
45
+ CLOSING_MARKS = [")", "]", "}", "”", "’", "''", '"'].freeze
46
+
43
47
  # Features that read the words and tags around a token.
44
48
  LEFT_CONTEXT = /\A(?:i first\z|i-1 (?:word|suffix) |i-2 |i tag\+i-2 )/
45
49
  RIGHT_CONTEXT = /\Ai\+/
@@ -53,14 +57,15 @@ class EngTagger
53
57
  @tagdict = @model.tagdict
54
58
  end
55
59
 
56
- # Tag a string. Returns [[token, tag], ...] with PTB tags. Text in another
60
+ # Tag a string. Returns [[token, tag], ...] with PTB tags. The text is
61
+ # split into sentences, which are tagged one by one. Text in another
57
62
  # encoding is converted to UTF-8 first.
58
63
  def tag(text)
59
64
  tokens = Tokenizer.tokenize(text.encode(Encoding::UTF_8))
60
- tokens.zip(tag_tokens(tokens))
65
+ tokens.zip(sentences(tokens).flat_map { |sentence| tag_tokens(sentence) })
61
66
  end
62
67
 
63
- # Tag an already-tokenized sentence or text. Returns an array of tags.
68
+ # Tag one already-tokenized sentence. Returns an array of tags.
64
69
  def tag_tokens(tokens)
65
70
  context = build_context(tokens)
66
71
  prev = "-START-"
@@ -68,7 +73,7 @@ class EngTagger
68
73
  scores = Array.new(@classes.size, 0)
69
74
  tokens.each_index.map do |k|
70
75
  word = tokens[k]
71
- t = @tagdict[normalize(word)] || predict(features(k, word, context, prev, prev2), scores)
76
+ t = @tagdict[context[k + 2]] || predict(features(k, word, context, prev, prev2), scores)
72
77
  prev2 = prev
73
78
  prev = t
74
79
  t
@@ -114,6 +119,22 @@ class EngTagger
114
119
 
115
120
  private
116
121
 
122
+ # Split tokens into sentences after `.`, `!` and `?`. Closing brackets and
123
+ # quotation marks that follow stay with the sentence they close.
124
+ def sentences(tokens)
125
+ result = []
126
+ start = 0
127
+ tokens.each_index do |i|
128
+ next if i < start || !tokens[i].match?(SENTENCE_END)
129
+
130
+ i += 1 while CLOSING_MARKS.include?(tokens[i + 1])
131
+ result << tokens[start..i]
132
+ start = i + 1
133
+ end
134
+ result << tokens[start..] if start < tokens.size
135
+ result
136
+ end
137
+
117
138
  def normalize(word)
118
139
  if word.include?("-") && word[0] != "-"
119
140
  "!HYPHEN"
@@ -172,9 +193,7 @@ class EngTagger
172
193
  # several threads.
173
194
  def predict(feats, scores)
174
195
  scores.fill(0)
175
- feats.each do |feature|
176
- @model.each_posting(feature) { |tag_id, weight| scores[tag_id] += weight }
177
- end
196
+ feats.each { |feature| @model.add_scores(feature, scores) }
178
197
  best = 0
179
198
  best_score = scores[0]
180
199
  1.upto(scores.size - 1) do |i|
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  class EngTagger
4
- VERSION = "2.0.0.pre3"
4
+ VERSION = "2.0.0.pre4"
5
5
  end
data/lib/engtagger.rb CHANGED
@@ -10,7 +10,7 @@ require_relative "engtagger/perceptron"
10
10
  # training data). `add_tags` produces XML-style output in the classic tagset,
11
11
  # and the extraction methods (`get_nouns`, `get_noun_phrases`, ...) read that
12
12
  # output. Pass `tagset: :ptb` to get standard Penn Treebank tags from
13
- # `tag_pairs` and `get_readable`.
13
+ # `tag_pairs`, `tag_tokens` and `get_readable`.
14
14
  class EngTagger
15
15
  #################
16
16
  # Class methods #
@@ -137,7 +137,7 @@ class EngTagger
137
137
  # affects only the get_words() and get_nouns() methods.
138
138
  # * :tagset
139
139
  # => (Symbol) :legacy (default) emits the classic XML-safe lowercase tags;
140
- # :ptb makes tag_pairs and get_readable emit standard Penn Treebank
140
+ # :ptb makes tag_pairs, tag_tokens and get_readable emit standard Penn Treebank
141
141
  # tags (DT, PRP$, ".", ...). add_tags always uses the classic tagset,
142
142
  # which is what keeps its output usable as XML and regex-friendly.
143
143
  # * :model
@@ -166,10 +166,14 @@ class EngTagger
166
166
  @@mnp = get_max_noun_regex
167
167
  end
168
168
 
169
- # One loaded model shared across instances.
169
+ @@perceptrons = {}
170
+ PERCEPTRON_LOCK = Mutex.new
171
+
172
+ # One loaded model shared across instances and threads.
170
173
  def self.perceptron_for(model_path)
171
- @@perceptrons ||= {}
172
- @@perceptrons[model_path] ||= Perceptron.new(model: model_path)
174
+ PERCEPTRON_LOCK.synchronize do
175
+ @@perceptrons[model_path] ||= Perceptron.new(model: model_path)
176
+ end
173
177
  end
174
178
 
175
179
  ##################
@@ -184,10 +188,17 @@ class EngTagger
184
188
  def tag_pairs(text)
185
189
  return [] unless valid_text(text)
186
190
 
187
- @tagger.tag(text).map do |word, tag|
188
- tag = @tagger.legacy_tag(tag) unless @conf[:tagset] == :ptb
189
- [word, tag.to_sym]
190
- end
191
+ @tagger.tag(text).map { |word, tag| [word, tag_symbol(tag)] }
192
+ end
193
+
194
+ # Tag one sentence that is already split into tokens.
195
+ #
196
+ # @param tokens [Array<String>] the tokens of one sentence
197
+ # @return [Array<Symbol>] one tag per token
198
+ #
199
+ def tag_tokens(tokens)
200
+ tokens = tokens.map { |token| token.encode(Encoding::UTF_8) }
201
+ @tagger.tag_tokens(tokens).map { |tag| tag_symbol(tag) }
191
202
  end
192
203
 
193
204
  # Examine the string provided and return it fully tagged in XML style.
@@ -560,6 +571,11 @@ class EngTagger
560
571
 
561
572
  private
562
573
 
574
+ # The tag as the configured tagset spells it.
575
+ def tag_symbol(ptb_tag)
576
+ (@conf[:tagset] == :ptb ? ptb_tag : @tagger.legacy_tag(ptb_tag)).to_sym
577
+ end
578
+
563
579
  def warn_retired_keys(params)
564
580
  return unless params
565
581
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: engtagger
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.0.0.pre3
4
+ version: 2.0.0.pre4
5
5
  platform: ruby
6
6
  authors:
7
7
  - Yoichiro Hasebe
@@ -57,7 +57,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
57
57
  - !ruby/object:Gem::Version
58
58
  version: '0'
59
59
  requirements: []
60
- rubygems_version: 4.0.24
60
+ rubygems_version: 3.6.9
61
61
  specification_version: 4
62
62
  summary: A corpus-trained English POS tagger in pure Ruby
63
63
  test_files: []