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 +4 -4
- data/CHANGELOG.md +27 -57
- data/NOTICE +73 -0
- data/README.md +117 -63
- data/lib/engtagger/model.etm.gz +0 -0
- data/lib/engtagger/model.rb +178 -0
- data/lib/engtagger/model_builder.rb +183 -0
- data/lib/engtagger/perceptron.rb +163 -0
- data/lib/engtagger/porter.rb +8 -9
- data/lib/engtagger/tokenizer.rb +279 -0
- data/lib/engtagger/version.rb +1 -1
- data/lib/engtagger.rb +69 -389
- metadata +17 -40
- data/.gitattributes +0 -4
- data/.gitignore +0 -21
- data/.rubocop.yml +0 -72
- data/.solargraph.yml +0 -22
- data/.yardopts +0 -5
- data/Gemfile +0 -10
- data/Rakefile +0 -25
- data/engtagger.gemspec +0 -35
- data/lib/engtagger/pos_tags.hash +0 -0
- data/lib/engtagger/pos_words.hash +0 -0
- data/lib/engtagger/tags.yml +0 -45
- data/lib/engtagger/unknown.yml +0 -12
- data/lib/engtagger/words.yml +0 -43818
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "digest"
|
|
4
|
+
require "zlib"
|
|
5
|
+
require_relative "model"
|
|
6
|
+
|
|
7
|
+
class EngTagger
|
|
8
|
+
class Model
|
|
9
|
+
# Converts a trainer's string-keyed weights into the packed ETM2 format.
|
|
10
|
+
# Build-time only: the gem's runtime never loads this file.
|
|
11
|
+
#
|
|
12
|
+
# EngTagger::Model::Builder.new(
|
|
13
|
+
# weights: weights, tagdict: tagdict, classes: classes
|
|
14
|
+
# ).write("model.etm.gz")
|
|
15
|
+
class Builder
|
|
16
|
+
# int16 at this scale covers weights up to +-64 in steps of 1/512; a
|
|
17
|
+
# weight outside that range raises instead of being clipped.
|
|
18
|
+
DEFAULT_SCALE = 512
|
|
19
|
+
MAX_Q = 32_767
|
|
20
|
+
|
|
21
|
+
# Words that are an address: anything around an "@" (mail addresses,
|
|
22
|
+
# handles) and URIs.
|
|
23
|
+
ADDRESS = /@.|.@|\A[a-z][a-z0-9+.-]*:\S|\Awww\./i
|
|
24
|
+
|
|
25
|
+
# Features whose last field is a word of the tagged text.
|
|
26
|
+
WORD_FEATURE = /\A(?:i|i[+-]\d|i-1 tag\+i) word (?:\S+ )?(\S+)\z/
|
|
27
|
+
|
|
28
|
+
attr_reader :stats
|
|
29
|
+
|
|
30
|
+
# prune: drop postings whose absolute weight is below this threshold
|
|
31
|
+
# (0.0 keeps every posting). Features left with no postings are dropped
|
|
32
|
+
# entirely.
|
|
33
|
+
# omit_words: leave out the tag dictionary entries and word features
|
|
34
|
+
# whose word matches this pattern (ADDRESS for a published model), so
|
|
35
|
+
# the file does not carry those words from the training text. The tagger
|
|
36
|
+
# then relies on the shape, prefix and suffix of such tokens.
|
|
37
|
+
def initialize(weights:, tagdict:, classes:, scale: DEFAULT_SCALE, prune: 0.0, omit_words: nil)
|
|
38
|
+
@omit_words = omit_words
|
|
39
|
+
@weights = omit_words ? weights.reject { |feature, _| omitted?(feature[WORD_FEATURE, 1]) } : weights
|
|
40
|
+
@tagdict = omit_words ? tagdict.reject { |word, _| omitted?(word) } : tagdict
|
|
41
|
+
@omitted = { features: weights.size - @weights.size, words: tagdict.size - @tagdict.size }
|
|
42
|
+
@classes = classes.sort
|
|
43
|
+
@scale = scale
|
|
44
|
+
@prune = prune
|
|
45
|
+
@tag_ids = @classes.each_with_index.to_h
|
|
46
|
+
@stats = { omitted_features: @omitted[:features], omitted_words: @omitted[:words] }
|
|
47
|
+
validate_sections!
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
def write(path)
|
|
51
|
+
blob = pack
|
|
52
|
+
path.end_with?(".gz") ? write_gzipped(path, blob) : File.binwrite(path, blob)
|
|
53
|
+
@stats[:packed_bytes] = blob.bytesize
|
|
54
|
+
@stats[:file_bytes] = File.size(path)
|
|
55
|
+
@stats[:packed_sha256] = Digest::SHA256.hexdigest(blob)
|
|
56
|
+
@stats[:file_sha256] = Digest::SHA256.file(path).hexdigest
|
|
57
|
+
@stats
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
# gzip stores an mtime in its header, so the default writer produces a
|
|
61
|
+
# different file -- and a different SHA-256 -- every run. To keep the
|
|
62
|
+
# file reproducible, mtime is pinned to 0, no orig_name is written and
|
|
63
|
+
# the compression level is fixed.
|
|
64
|
+
def write_gzipped(path, blob)
|
|
65
|
+
File.open(path, "wb") do |file|
|
|
66
|
+
gz = Zlib::GzipWriter.new(file, Zlib::BEST_COMPRESSION)
|
|
67
|
+
gz.mtime = 0
|
|
68
|
+
gz.write(blob)
|
|
69
|
+
gz.close
|
|
70
|
+
end
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
def pack
|
|
74
|
+
entries = build_entries
|
|
75
|
+
keys = keys_section(entries)
|
|
76
|
+
header(entries, keys.bytesize) + classes_section + tagdict_section + keys +
|
|
77
|
+
counts_section(entries) + postings_section(entries)
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
private
|
|
81
|
+
|
|
82
|
+
def omitted?(word)
|
|
83
|
+
word && @omit_words.match?(word)
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
# Every length in the format is a u8 and every tag id fits in a byte.
|
|
87
|
+
# Overflowing either would wrap silently and produce a file that reads
|
|
88
|
+
# back as garbage, so the limits are checked up front rather than
|
|
89
|
+
# trusted.
|
|
90
|
+
def validate_sections!
|
|
91
|
+
count = @classes.size
|
|
92
|
+
raise Model::Error, "model has #{count} classes; tag ids are u8 (max 256)" if count > 256
|
|
93
|
+
|
|
94
|
+
too_long = @classes.find { |tag| tag.b.bytesize > 255 }
|
|
95
|
+
raise Model::Error, "tag name longer than 255 bytes: #{too_long.inspect}" if too_long
|
|
96
|
+
|
|
97
|
+
too_long = @tagdict.keys.find { |word| word.b.bytesize > 255 }
|
|
98
|
+
raise Model::Error, "tagdict word longer than 255 bytes: #{too_long.inspect}" if too_long
|
|
99
|
+
|
|
100
|
+
unknown = @tagdict.values.find { |tag| !@tag_ids.key?(tag) }
|
|
101
|
+
raise Model::Error, "tagdict uses tag outside classes: #{unknown.inspect}" if unknown
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
# [[feature bytes, [[tag_id, quantized], ...]], ...] sorted bytewise by feature.
|
|
105
|
+
def build_entries
|
|
106
|
+
dropped_postings = 0
|
|
107
|
+
entries = []
|
|
108
|
+
@weights.each do |feature, tag_weights|
|
|
109
|
+
postings = []
|
|
110
|
+
tag_weights.each do |tag, weight|
|
|
111
|
+
if weight.abs < @prune
|
|
112
|
+
dropped_postings += 1
|
|
113
|
+
next
|
|
114
|
+
end
|
|
115
|
+
postings << [@tag_ids.fetch(tag), quantize(weight)]
|
|
116
|
+
end
|
|
117
|
+
next if postings.empty?
|
|
118
|
+
raise Model::Error, "feature has more than 255 postings: #{feature}" if postings.size > 255
|
|
119
|
+
|
|
120
|
+
entries << [feature_key(feature), postings.sort_by!(&:first)]
|
|
121
|
+
end
|
|
122
|
+
entries.sort_by!(&:first)
|
|
123
|
+
entries.each_cons(2) do |(a, _), (b, _)|
|
|
124
|
+
raise Model::Error, "duplicate feature: #{a.inspect}" if a == b
|
|
125
|
+
end
|
|
126
|
+
|
|
127
|
+
@stats.update(features: entries.size, dropped_features: @weights.size - entries.size,
|
|
128
|
+
postings: entries.sum { |_, p| p.size }, dropped_postings: dropped_postings)
|
|
129
|
+
entries
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
# Keys are stored NUL-terminated, so a feature can neither be empty nor
|
|
133
|
+
# contain a NUL byte.
|
|
134
|
+
def feature_key(feature)
|
|
135
|
+
key = feature.b
|
|
136
|
+
return key unless key.empty? || key.include?(KEY_TERMINATOR)
|
|
137
|
+
|
|
138
|
+
raise Model::Error, "feature is empty or contains a NUL byte: #{feature.inspect}"
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
def quantize(weight)
|
|
142
|
+
q = (weight * @scale).round
|
|
143
|
+
raise Model::Error, "weight #{weight} overflows int16 at scale #{@scale}" if q.abs > MAX_Q
|
|
144
|
+
|
|
145
|
+
q
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
def header(entries, keys_bytes)
|
|
149
|
+
[MAGIC].pack("a4") +
|
|
150
|
+
[FORMAT_VERSION, FLAG_QUANTIZED, @scale, @classes.size].pack("v4") +
|
|
151
|
+
[entries.size, entries.sum { |_, p| p.size }, @tagdict.size, keys_bytes].pack("V4")
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
def classes_section
|
|
155
|
+
@classes.map { |tag| [tag.bytesize].pack("C") + tag.b }.join
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
def tagdict_section
|
|
159
|
+
@tagdict.map { |word, tag| [word.b, tag] }.sort_by(&:first).map do |bytes, tag|
|
|
160
|
+
[bytes.bytesize].pack("C") + bytes + [@tag_ids.fetch(tag)].pack("C")
|
|
161
|
+
end.join
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
def keys_section(entries)
|
|
165
|
+
entries.map { |key, _| key + KEY_TERMINATOR }.join
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
def counts_section(entries)
|
|
169
|
+
entries.map { |_, p| p.size }.pack("C*")
|
|
170
|
+
end
|
|
171
|
+
|
|
172
|
+
# entries is an Array of [key, postings] pairs, not a Hash --
|
|
173
|
+
# rubocop's each_value suggestion does not apply here.
|
|
174
|
+
def postings_section(entries)
|
|
175
|
+
buf = +"".b
|
|
176
|
+
entries.each do |_key, postings| # rubocop:disable Style/HashEachMethods
|
|
177
|
+
postings.each { |tag_id, q| buf << [tag_id, q].pack("Cs<") }
|
|
178
|
+
end
|
|
179
|
+
buf
|
|
180
|
+
end
|
|
181
|
+
end
|
|
182
|
+
end
|
|
183
|
+
end
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "model"
|
|
4
|
+
require_relative "tokenizer"
|
|
5
|
+
|
|
6
|
+
class EngTagger
|
|
7
|
+
# Averaged-perceptron part-of-speech tagger (Honnibal-style): greedy
|
|
8
|
+
# left-to-right decoding over local features, with a tag dictionary short-
|
|
9
|
+
# circuiting frequent unambiguous words.
|
|
10
|
+
#
|
|
11
|
+
# Only inference is here; training lives outside the gem. The feature
|
|
12
|
+
# strings built below are the keys of the model's weights, so they must stay
|
|
13
|
+
# byte-identical to the ones the model was trained with.
|
|
14
|
+
#
|
|
15
|
+
# Tags are standard Penn Treebank (as used by Universal Dependencies XPOS),
|
|
16
|
+
# not the modified tagset of the classic EngTagger engine. See
|
|
17
|
+
# `EngTagger::Perceptron::LEGACY_TAGS` for the mapping between them.
|
|
18
|
+
class Perceptron
|
|
19
|
+
START = ["-START-", "-START2-"].freeze
|
|
20
|
+
ENDING = ["-END-", "-END2-"].freeze
|
|
21
|
+
|
|
22
|
+
DEFAULT_MODEL = File.join(File.dirname(__FILE__), "model.etm.gz")
|
|
23
|
+
|
|
24
|
+
# PTB/UD tag -> classic EngTagger tag. The classic tagset renames a few
|
|
25
|
+
# categories for XML-tag safety (DET for DT, PRPS for PRP$) and splits
|
|
26
|
+
# punctuation into named classes.
|
|
27
|
+
LEGACY_TAGS = {
|
|
28
|
+
"DT" => "det", "PRP$" => "prps", "WP$" => "wps", "PRP" => "prp",
|
|
29
|
+
"." => "pp", "," => "ppc", ":" => "pps", "``" => "ppl", "''" => "ppr",
|
|
30
|
+
"$" => "ppd", "#" => "ppd", "-LRB-" => "lrb", "-RRB-" => "rrb",
|
|
31
|
+
# UD additions with no classic equivalent
|
|
32
|
+
"HYPH" => "ppc", "NFP" => "sym", "AFX" => "jj", "ADD" => "nn",
|
|
33
|
+
"GW" => "nn", "XX" => "sym"
|
|
34
|
+
}.freeze
|
|
35
|
+
|
|
36
|
+
attr_reader :model
|
|
37
|
+
|
|
38
|
+
# model: path to a packed .etm/.etm.gz file, or an EngTagger::Model.
|
|
39
|
+
def initialize(model: DEFAULT_MODEL)
|
|
40
|
+
@model = model.is_a?(Model) ? model : Model.read(model)
|
|
41
|
+
@classes = @model.classes
|
|
42
|
+
@tagdict = @model.tagdict
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
# Tag a string. Returns [[token, tag], ...] with PTB tags. Text in another
|
|
46
|
+
# encoding is converted to UTF-8 first.
|
|
47
|
+
def tag(text)
|
|
48
|
+
tokens = Tokenizer.tokenize(text.encode(Encoding::UTF_8))
|
|
49
|
+
tokens.zip(tag_tokens(tokens))
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
# Tag an already-tokenized sentence or text. Returns an array of tags.
|
|
53
|
+
def tag_tokens(tokens)
|
|
54
|
+
context = build_context(tokens)
|
|
55
|
+
prev = "-START-"
|
|
56
|
+
prev2 = "-START2-"
|
|
57
|
+
scores = Array.new(@classes.size, 0)
|
|
58
|
+
tokens.each_index.map do |k|
|
|
59
|
+
word = tokens[k]
|
|
60
|
+
t = @tagdict[normalize(word)] || predict(features(k, word, context, prev, prev2), scores)
|
|
61
|
+
prev2 = prev
|
|
62
|
+
prev = t
|
|
63
|
+
t
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
# XML-style output, matching the classic engine's shape:
|
|
68
|
+
# "<nnp>Alice</nnp> <vbd>chased</vbd> ..."
|
|
69
|
+
#
|
|
70
|
+
# legacy: emit classic EngTagger tags instead of PTB ones.
|
|
71
|
+
def add_tags(text, legacy: false)
|
|
72
|
+
tag(text).map do |word, t|
|
|
73
|
+
t = legacy_tag(t) if legacy
|
|
74
|
+
"<#{t}>#{word}</#{t}>"
|
|
75
|
+
end.join(" ")
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
# "Alice/NNP chased/VBD the/DET ..."
|
|
79
|
+
def get_readable(text)
|
|
80
|
+
tag(text).map { |word, t| "#{word}/#{t}" }.join(" ")
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
# Classic-tagset equivalent of a PTB tag (downcased, as the classic engine
|
|
84
|
+
# emits). Unmapped tags simply downcase: NN -> nn, VBD -> vbd.
|
|
85
|
+
def legacy_tag(ptb_tag)
|
|
86
|
+
LEGACY_TAGS[ptb_tag] || ptb_tag.downcase
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
private
|
|
90
|
+
|
|
91
|
+
def normalize(word)
|
|
92
|
+
if word.include?("-") && word[0] != "-"
|
|
93
|
+
"!HYPHEN"
|
|
94
|
+
elsif word =~ /\A\d{4}\z/
|
|
95
|
+
"!YEAR"
|
|
96
|
+
elsif word =~ /\A\d/
|
|
97
|
+
"!DIGITS"
|
|
98
|
+
else
|
|
99
|
+
word.downcase
|
|
100
|
+
end
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
def build_context(tokens)
|
|
104
|
+
START + tokens.map { |w| normalize(w) } + ENDING
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
# Collapsed word-shape pattern: "McDonald's" -> "XxXx'x", "3.5" -> "d.d"
|
|
108
|
+
def shape(word)
|
|
109
|
+
word.gsub(/[A-Z]+/, "X").gsub(/[a-z]+/, "x").gsub(/\d+/, "d")[0, 8]
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
def features(idx, word, context, prev, prev2)
|
|
113
|
+
i = idx + 2 # offset for START padding
|
|
114
|
+
w = word.downcase
|
|
115
|
+
suf = w[-3..] || w
|
|
116
|
+
f = ["bias", "i word #{context[i]}",
|
|
117
|
+
"i suffix #{suf}",
|
|
118
|
+
"i suffix4 #{w[-4..] || w}",
|
|
119
|
+
"i pref1 #{w[0]}",
|
|
120
|
+
"i pref2 #{w[0, 2]}",
|
|
121
|
+
"i pref3 #{w[0, 3]}",
|
|
122
|
+
"i shape #{shape(word)}"]
|
|
123
|
+
f << "i first" if idx.zero?
|
|
124
|
+
f << "i shape upper" if word =~ /\A[A-Z]/
|
|
125
|
+
f << "i shape allcaps" if word =~ /\A[A-Z]+\z/ && word.size > 1
|
|
126
|
+
f.concat [
|
|
127
|
+
"i-1 word #{context[i - 1]}",
|
|
128
|
+
"i-1 suffix #{context[i - 1][-3..] || context[i - 1]}",
|
|
129
|
+
"i-2 word #{context[i - 2]}",
|
|
130
|
+
"i+1 word #{context[i + 1]}",
|
|
131
|
+
"i+1 suffix #{context[i + 1][-3..] || context[i + 1]}",
|
|
132
|
+
"i+2 word #{context[i + 2]}",
|
|
133
|
+
"i-1 tag #{prev}",
|
|
134
|
+
"i-2 tag #{prev2}",
|
|
135
|
+
"i tag+i-2 tag #{prev} #{prev2}",
|
|
136
|
+
"i-1 tag+i word #{prev} #{context[i]}",
|
|
137
|
+
"i-1 tag+i suffix #{prev} #{suf}"
|
|
138
|
+
]
|
|
139
|
+
f
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
# Scores accumulate as integers: every weight shares one quantization
|
|
143
|
+
# scale, so the scale cancels out of the comparison. Ties fall to the
|
|
144
|
+
# lexicographically last tag, matching the trainer's `max_by { [score, t] }`.
|
|
145
|
+
# `scores` is a scratch array owned by the caller, so one tagger can serve
|
|
146
|
+
# several threads.
|
|
147
|
+
def predict(feats, scores)
|
|
148
|
+
scores.fill(0)
|
|
149
|
+
feats.each do |feature|
|
|
150
|
+
@model.each_posting(feature) { |tag_id, weight| scores[tag_id] += weight }
|
|
151
|
+
end
|
|
152
|
+
best = 0
|
|
153
|
+
best_score = scores[0]
|
|
154
|
+
1.upto(scores.size - 1) do |i|
|
|
155
|
+
next if scores[i] < best_score
|
|
156
|
+
|
|
157
|
+
best = i
|
|
158
|
+
best_score = scores[i]
|
|
159
|
+
end
|
|
160
|
+
@classes[best]
|
|
161
|
+
end
|
|
162
|
+
end
|
|
163
|
+
end
|
data/lib/engtagger/porter.rb
CHANGED
|
@@ -37,7 +37,7 @@ module Stemmable
|
|
|
37
37
|
aliti |
|
|
38
38
|
iviti |
|
|
39
39
|
biliti |
|
|
40
|
-
logi)$/x
|
|
40
|
+
logi)$/x
|
|
41
41
|
|
|
42
42
|
SUFFIX_2_REGEXP = /(
|
|
43
43
|
al |
|
|
@@ -57,17 +57,17 @@ module Stemmable
|
|
|
57
57
|
iti |
|
|
58
58
|
ous |
|
|
59
59
|
ive |
|
|
60
|
-
ize)$/x
|
|
60
|
+
ize)$/x
|
|
61
61
|
|
|
62
62
|
C = "[^aeiou]" # consonant
|
|
63
63
|
V = "[aeiouy]" # vowel
|
|
64
|
-
CC = "#{C}(?>[^aeiouy]*)" # consonant sequence
|
|
65
|
-
VV = "#{V}(?>[aeiou]*)" # vowel sequence
|
|
64
|
+
CC = "#{C}(?>[^aeiouy]*)".freeze # consonant sequence
|
|
65
|
+
VV = "#{V}(?>[aeiou]*)".freeze # vowel sequence
|
|
66
66
|
|
|
67
|
-
MGR0 = /^(#{CC})?#{VV}#{CC}/o
|
|
68
|
-
MEQ1 = /^(#{CC})?#{VV}#{CC}(#{VV})?$/o
|
|
69
|
-
MGR1 = /^(#{CC})?#{VV}#{CC}#{VV}#{CC}/o
|
|
70
|
-
VOWEL_IN_STEM = /^(#{CC})?#{V}/o
|
|
67
|
+
MGR0 = /^(#{CC})?#{VV}#{CC}/o # [cc]vvcc... is m>0
|
|
68
|
+
MEQ1 = /^(#{CC})?#{VV}#{CC}(#{VV})?$/o # [cc]vvcc[vv] is m=1
|
|
69
|
+
MGR1 = /^(#{CC})?#{VV}#{CC}#{VV}#{CC}/o # [cc]vvccvvcc... is m>1
|
|
70
|
+
VOWEL_IN_STEM = /^(#{CC})?#{V}/o # vowel in stem
|
|
71
71
|
|
|
72
72
|
# Porter stemmer in Ruby.
|
|
73
73
|
#
|
|
@@ -125,7 +125,6 @@ module Stemmable
|
|
|
125
125
|
if w =~ SUFFIX_1_REGEXP
|
|
126
126
|
stem = $`
|
|
127
127
|
suffix = $1
|
|
128
|
-
# print "stem= " + stem + "\n" + "suffix=" + suffix + "\n"
|
|
129
128
|
w = stem + STEP_2_LIST[suffix] if stem =~ MGR0
|
|
130
129
|
end
|
|
131
130
|
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "strscan"
|
|
4
|
+
require "set"
|
|
5
|
+
|
|
6
|
+
class EngTagger
|
|
7
|
+
# PTB/UD-compatible English word tokenizer.
|
|
8
|
+
#
|
|
9
|
+
# Non-destructive by construction: every token is a
|
|
10
|
+
# contiguous substring of the input, so callers can recover character
|
|
11
|
+
# offsets and detokenize exactly.
|
|
12
|
+
#
|
|
13
|
+
# Conventions follow PTB as adapted by UD: contractions split (do|n't,
|
|
14
|
+
# I|'m), possessive 's split, hyphenated compounds split around HYPH except
|
|
15
|
+
# bound prefixes, URLs/emails/filenames kept whole, multi-dot abbreviations
|
|
16
|
+
# kept with their periods.
|
|
17
|
+
module Tokenizer
|
|
18
|
+
URL = %r{(?:https?://|www\.)[^\s<>"“”]+}
|
|
19
|
+
EMAIL = /[A-Za-z0-9][\w.+-]*@[\w-]+(?:\.[\w-]+)*/
|
|
20
|
+
|
|
21
|
+
# filenames: report.doc, 20.doc, .doc
|
|
22
|
+
FILENAME = /[\w-]*\.(?:docx?|pdf|txt|xlsx?|jpe?g|png|gif|html?|php|zip|exe|mp3|wav|pptx?|csv)(?![\p{L}\d])/i
|
|
23
|
+
|
|
24
|
+
# U.S., e.g., i.e., a.m., D.C., Ph.D., U.S (final dot swallowed by EOS)
|
|
25
|
+
ACRONYM = /(?:[A-Za-z]{1,2}\.){2,}(?![A-Za-z])/
|
|
26
|
+
ACRONYM_TAIL = /(?:[A-Za-z]\.)+[A-Za-z](?![\p{L}\d.])/
|
|
27
|
+
|
|
28
|
+
# bare web domains: amazon.com, galleryfurniture.com
|
|
29
|
+
DOMAIN = /[\w-]+(?:\.[\w-]+)*\.(?:com|net|org|edu|gov|info|biz|io)(?![\p{L}\d])/i
|
|
30
|
+
|
|
31
|
+
ABBREVS = %w[
|
|
32
|
+
mr mrs ms dr prof st jr sr rev gen rep sen gov capt sgt col lt maj
|
|
33
|
+
vs etc inc ltd co corp dept univ assn bros vol pp approx est
|
|
34
|
+
jan feb mar apr jun jul aug sep sept oct nov dec
|
|
35
|
+
mon tue tues wed thu thur thurs fri sat sun
|
|
36
|
+
ave blvd rd mt ft fig ref cf al seq
|
|
37
|
+
].to_set.freeze
|
|
38
|
+
ABBREV = /[A-Za-z]{1,6}\.(?![A-Za-z])/
|
|
39
|
+
|
|
40
|
+
# Name initials kept with period: "George W. Bush" ("I" excluded: pronoun)
|
|
41
|
+
INITIAL = /(?!I\.)[A-Z]\.(?![\p{L}\d])/
|
|
42
|
+
|
|
43
|
+
# 1,000.50 | 12/25/2010 | 5:30 | 646-8420 | .38 | 20th | 1970s | 32A
|
|
44
|
+
# (ordinal/decade/single-capital suffixes attach; "5pm" splits)
|
|
45
|
+
NUMBER = %r{\d+(?:[.,:/-]\d+)*(?:(?:st|nd|rd|th|s)(?![\p{L}\d])|[A-Z](?![\p{L}\d]))?|\.\d+}
|
|
46
|
+
|
|
47
|
+
# AT&T, PG&E, P&L, s/he
|
|
48
|
+
AMP_WORD = %r{\p{L}+(?:&\p{L}+)+|[sS]/he(?![\p{L}\d])}
|
|
49
|
+
|
|
50
|
+
# Truncated / stuttered word: "w- well, I..."
|
|
51
|
+
STUTTER = /\p{L}{1,2}-(?=\s|\z)/
|
|
52
|
+
|
|
53
|
+
# Word-ish chunk incl. internal hyphens/apostrophes; split decisions
|
|
54
|
+
# happen in post-processing.
|
|
55
|
+
WORDLIKE = /[\p{L}\p{M}\d]+(?:[-'’][\p{L}\p{M}\d]+)*['’]?/
|
|
56
|
+
|
|
57
|
+
# Clitic left bare by preceding split/number: the 90 's | `s | 'M
|
|
58
|
+
APOS_CLITIC = /['’`](?:ll|re|ve|em|til|cause|[smd])(?![\p{L}\d])/i
|
|
59
|
+
|
|
60
|
+
MULTI_PUNCT = %r{[.!?…]{2,}|--+|``|''|[‘’]{2}|<<|>>|<3|[:=;]-?[()DPp/]|\(:|;-?\)}
|
|
61
|
+
|
|
62
|
+
# Decorative symbol runs and ASCII emoticons: ==== ____ *** ^_^
|
|
63
|
+
SYM_RUN = /[=_*~^#+]{2,}/
|
|
64
|
+
|
|
65
|
+
# Bound prefixes: keep "pre-owned" etc. as one token (EWT convention).
|
|
66
|
+
HYPHEN_PREFIXES = %w[
|
|
67
|
+
e a non mid pre re anti post co pro multi over ex semi sub neo
|
|
68
|
+
ultra inter intra counter pseudo psycho quasi meta micro macro mini
|
|
69
|
+
uni bi tri cross
|
|
70
|
+
].to_set.freeze
|
|
71
|
+
|
|
72
|
+
# Lexical multiword tokens (surface -> parts, all substrings in order).
|
|
73
|
+
SPECIAL_SPLITS = {
|
|
74
|
+
"cannot" => %w[can not],
|
|
75
|
+
"gonna" => %w[gon na],
|
|
76
|
+
"wanna" => %w[wan na],
|
|
77
|
+
"gotta" => %w[got ta],
|
|
78
|
+
"lemme" => %w[lem me],
|
|
79
|
+
"gimme" => %w[gim me],
|
|
80
|
+
"outta" => %w[out ta],
|
|
81
|
+
"dunno" => %w[du nno],
|
|
82
|
+
"i'ma" => ["i", "'m", "a"],
|
|
83
|
+
"i’ma" => ["i", "’m", "a"],
|
|
84
|
+
# apostrophe-less contractions (typos; UD splits them)
|
|
85
|
+
"dont" => %w[do nt], "wont" => %w[wo nt], "cant" => %w[ca nt],
|
|
86
|
+
"aint" => %w[ai nt], "arent" => %w[are nt], "isnt" => %w[is nt],
|
|
87
|
+
"didnt" => %w[did nt], "doesnt" => %w[does nt], "wasnt" => %w[was nt],
|
|
88
|
+
"couldnt" => %w[could nt], "wouldnt" => %w[would nt],
|
|
89
|
+
"shouldnt" => %w[should nt], "havent" => %w[have nt],
|
|
90
|
+
"hasnt" => %w[has nt],
|
|
91
|
+
"im" => %w[i m], "ive" => %w[i ve], "youre" => %w[you re],
|
|
92
|
+
"youll" => %w[you ll], "thats" => %w[that s], "theres" => %w[there s],
|
|
93
|
+
"hes" => %w[he s], "shes" => %w[she s]
|
|
94
|
+
}.freeze
|
|
95
|
+
|
|
96
|
+
CLITICS = /\A(?:ll|re|ve|d|m|s)\z/i
|
|
97
|
+
|
|
98
|
+
# A candidate that fails after reading a long stretch would read it again
|
|
99
|
+
# from every later start. Each pattern below is paired with the stretch it
|
|
100
|
+
# reads: once it fails at a position, it fails at every position inside
|
|
101
|
+
# that stretch, so it is not tried there again.
|
|
102
|
+
STRETCHES = {
|
|
103
|
+
EMAIL => /[A-Za-z0-9][\w.+-]*/,
|
|
104
|
+
FILENAME => /[\w-]*\.?/,
|
|
105
|
+
DOMAIN => /[\w-]+(?:\.[\w-]+)*/,
|
|
106
|
+
ACRONYM => /(?:[A-Za-z]{1,2}\.)+/,
|
|
107
|
+
ACRONYM_TAIL => /(?:[A-Za-z]\.)+/
|
|
108
|
+
}.freeze
|
|
109
|
+
|
|
110
|
+
module_function
|
|
111
|
+
|
|
112
|
+
# => array of token strings
|
|
113
|
+
def tokenize(text)
|
|
114
|
+
tokenize_spans(text).map { |t, _s, _e| t }
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
# => array of [token, start_offset, end_offset(exclusive)]
|
|
118
|
+
def tokenize_spans(text)
|
|
119
|
+
scanner = StringScanner.new(text)
|
|
120
|
+
out = []
|
|
121
|
+
byte_pos = start = 0
|
|
122
|
+
failed_until = Hash.new(0)
|
|
123
|
+
until scanner.eos?
|
|
124
|
+
next if scanner.skip(/\s+/)
|
|
125
|
+
|
|
126
|
+
# StringScanner#charpos rescans from the beginning of the string on
|
|
127
|
+
# every call, so the character offset is advanced token by token.
|
|
128
|
+
byte_start = scanner.pos
|
|
129
|
+
start += text.byteslice(byte_pos, byte_start - byte_pos).length
|
|
130
|
+
byte_pos = byte_start
|
|
131
|
+
if (tok = scanner.scan(URL) || scan_once(scanner, EMAIL, failed_until))
|
|
132
|
+
# strip trailing sentence punctuation accidentally captured
|
|
133
|
+
tok = strip_trailing_punct(tok)
|
|
134
|
+
scanner.pos = byte_start + tok.bytesize
|
|
135
|
+
out << [tok, start, start + tok.length]
|
|
136
|
+
elsif (tok = scan_name(scanner, failed_until))
|
|
137
|
+
out << [tok, start, start + tok.length]
|
|
138
|
+
elsif (tok = scanner.scan(NUMBER))
|
|
139
|
+
split_number(tok).each do |sub, off|
|
|
140
|
+
out << [sub, start + off, start + off + sub.length]
|
|
141
|
+
end
|
|
142
|
+
elsif (tok = scanner.scan(AMP_WORD) || scanner.scan(STUTTER))
|
|
143
|
+
out << [tok, start, start + tok.length]
|
|
144
|
+
elsif (tok = scanner.scan(WORDLIKE))
|
|
145
|
+
split_wordlike(tok).each do |sub, off|
|
|
146
|
+
out << [sub, start + off, start + off + sub.length]
|
|
147
|
+
end
|
|
148
|
+
elsif (tok = scanner.scan(APOS_CLITIC) || scanner.scan(MULTI_PUNCT) ||
|
|
149
|
+
scanner.scan(SYM_RUN) || scanner.getch)
|
|
150
|
+
out << [tok, start, start + tok.length]
|
|
151
|
+
end
|
|
152
|
+
end
|
|
153
|
+
out
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
# File names, domains, acronyms, initials and abbreviations: tokens that
|
|
157
|
+
# keep their periods.
|
|
158
|
+
def scan_name(scanner, failed_until)
|
|
159
|
+
scan_once(scanner, FILENAME, failed_until) || scan_once(scanner, DOMAIN, failed_until) ||
|
|
160
|
+
scan_once(scanner, ACRONYM, failed_until) || scan_once(scanner, ACRONYM_TAIL, failed_until) ||
|
|
161
|
+
scanner.scan(INITIAL) || check_abbrev(scanner)
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
# Scan `pattern` unless it is known to fail here (see STRETCHES).
|
|
165
|
+
def scan_once(scanner, pattern, failed_until)
|
|
166
|
+
return nil if scanner.pos < failed_until[pattern]
|
|
167
|
+
|
|
168
|
+
tok = scanner.scan(pattern) and return tok
|
|
169
|
+
stretch = scanner.match?(STRETCHES.fetch(pattern))
|
|
170
|
+
failed_until[pattern] = scanner.pos + stretch if stretch
|
|
171
|
+
nil
|
|
172
|
+
end
|
|
173
|
+
|
|
174
|
+
# Drop trailing sentence punctuation, keeping at least one character.
|
|
175
|
+
def strip_trailing_punct(tok)
|
|
176
|
+
kept = tok.reverse.sub(/\A[.,;:!?)]+/, "").reverse
|
|
177
|
+
kept.empty? ? tok[0] : kept
|
|
178
|
+
end
|
|
179
|
+
|
|
180
|
+
def check_abbrev(scanner)
|
|
181
|
+
tok = scanner.check(ABBREV) or return nil
|
|
182
|
+
return nil unless ABBREVS.include?(tok[0..-2].downcase)
|
|
183
|
+
|
|
184
|
+
scanner.pos += tok.bytesize
|
|
185
|
+
tok
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
# Split a word-like chunk into subtokens; returns [[substr, offset], ...]
|
|
189
|
+
def split_wordlike(tok)
|
|
190
|
+
if (parts = SPECIAL_SPLITS[tok.downcase]) && tok != "IM"
|
|
191
|
+
return special_offsets(tok, parts)
|
|
192
|
+
end
|
|
193
|
+
|
|
194
|
+
return split_hyphenated(tok) if tok.include?("-")
|
|
195
|
+
|
|
196
|
+
split_clitics(tok)
|
|
197
|
+
end
|
|
198
|
+
|
|
199
|
+
def special_offsets(tok, parts)
|
|
200
|
+
out = []
|
|
201
|
+
off = 0
|
|
202
|
+
parts.each do |p|
|
|
203
|
+
out << [tok[off, p.length], off]
|
|
204
|
+
off += p.length
|
|
205
|
+
end
|
|
206
|
+
out
|
|
207
|
+
end
|
|
208
|
+
|
|
209
|
+
# Hyphenated numbers: keep phone-like (646-8420, x3-9890), split short
|
|
210
|
+
# ranges (3-4) as UD does.
|
|
211
|
+
def split_number(tok)
|
|
212
|
+
has_hyphen = tok.include?("-")
|
|
213
|
+
return [[tok, 0]] unless has_hyphen && (tok.length < 6 || tok.include?(":"))
|
|
214
|
+
|
|
215
|
+
out = []
|
|
216
|
+
off = 0
|
|
217
|
+
tok.split(/(-)/).each do |p|
|
|
218
|
+
out << [p, off] unless p.empty?
|
|
219
|
+
off += p.length
|
|
220
|
+
end
|
|
221
|
+
out
|
|
222
|
+
end
|
|
223
|
+
|
|
224
|
+
def split_hyphenated(tok)
|
|
225
|
+
pieces = tok.split(/(-)/) # keeps hyphens as separate elements
|
|
226
|
+
words = pieces.reject { |p| p == "-" }
|
|
227
|
+
|
|
228
|
+
keep = (words.all? { |w| w =~ /\d/ } && tok.length >= 6) || # 646-8420
|
|
229
|
+
(words.size == 2 && words[1] =~ /\A[a-z]\z/) || # Naqsh-e
|
|
230
|
+
(words.size == 2 && HYPHEN_PREFIXES.include?(words[0].downcase))
|
|
231
|
+
|
|
232
|
+
if keep
|
|
233
|
+
split_clitics_tail_only(tok)
|
|
234
|
+
else
|
|
235
|
+
out = []
|
|
236
|
+
off = 0
|
|
237
|
+
pieces.each do |p|
|
|
238
|
+
if p == "-"
|
|
239
|
+
out << [p, off]
|
|
240
|
+
off += 1
|
|
241
|
+
else
|
|
242
|
+
split_clitics(p).each { |sub, o| out << [sub, off + o] }
|
|
243
|
+
off += p.length
|
|
244
|
+
end
|
|
245
|
+
end
|
|
246
|
+
out
|
|
247
|
+
end
|
|
248
|
+
end
|
|
249
|
+
|
|
250
|
+
# For tokens we decided to keep whole except a possible clitic tail
|
|
251
|
+
def split_clitics_tail_only(tok)
|
|
252
|
+
split_clitics(tok, split_internal: false)
|
|
253
|
+
end
|
|
254
|
+
|
|
255
|
+
def split_clitics(tok, split_internal: true)
|
|
256
|
+
_ = split_internal
|
|
257
|
+
# n't (don't -> do n't; can't -> ca n't; ain't -> ai n't)
|
|
258
|
+
if tok =~ /\A(.+)(n['’]t)\z/i && Regexp.last_match(1).length >= 1
|
|
259
|
+
base = Regexp.last_match(1)
|
|
260
|
+
return [[base, 0], [Regexp.last_match(2), base.length]]
|
|
261
|
+
end
|
|
262
|
+
|
|
263
|
+
# 'll 're 've 'd 'm 's (keeps o'clock, O'Brien intact)
|
|
264
|
+
if tok =~ /\A(.+)(['’])([A-Za-z]{1,2})\z/ && CLITICS.match?(Regexp.last_match(3))
|
|
265
|
+
base = Regexp.last_match(1)
|
|
266
|
+
clitic = Regexp.last_match(2) + Regexp.last_match(3)
|
|
267
|
+
return [[base, 0], [clitic, base.length]]
|
|
268
|
+
end
|
|
269
|
+
|
|
270
|
+
# trailing bare apostrophe: plural possessive (boys') or quote
|
|
271
|
+
if tok =~ /\A(.*[\p{L}\d])(['’])\z/
|
|
272
|
+
base = Regexp.last_match(1)
|
|
273
|
+
return [[base, 0], [Regexp.last_match(2), base.length]]
|
|
274
|
+
end
|
|
275
|
+
|
|
276
|
+
[[tok, 0]]
|
|
277
|
+
end
|
|
278
|
+
end
|
|
279
|
+
end
|
data/lib/engtagger/version.rb
CHANGED