2015-04-08 06:20:15 +00:00
|
|
|
"""Set up a model directory.
|
|
|
|
|
|
|
|
Requires:
|
|
|
|
|
|
|
|
lang_data --- Rules for the tokenizer
|
|
|
|
* prefix.txt
|
|
|
|
* suffix.txt
|
|
|
|
* infix.txt
|
|
|
|
* morphs.json
|
|
|
|
* specials.json
|
|
|
|
|
|
|
|
corpora --- Data files
|
|
|
|
* WordNet
|
|
|
|
* words.sgt.prob --- Smoothed unigram probabilities
|
|
|
|
* clusters.txt --- Output of hierarchical clustering, e.g. Brown clusters
|
|
|
|
* vectors.tgz --- output of something like word2vec
|
|
|
|
"""
|
2015-07-23 04:35:38 +00:00
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
2015-07-25 20:16:36 +00:00
|
|
|
from ast import literal_eval
|
2015-07-25 20:56:35 +00:00
|
|
|
import math
|
2015-07-26 20:39:22 +00:00
|
|
|
import gzip
|
2015-09-06 15:51:30 +00:00
|
|
|
import json
|
2015-07-25 20:16:36 +00:00
|
|
|
|
2015-04-08 05:46:53 +00:00
|
|
|
import plac
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
|
|
from shutil import copyfile
|
2015-04-12 02:45:31 +00:00
|
|
|
from shutil import copytree
|
2015-07-01 16:48:59 +00:00
|
|
|
from collections import defaultdict
|
2015-09-30 18:20:09 +00:00
|
|
|
import io
|
2015-04-08 05:46:53 +00:00
|
|
|
|
|
|
|
from spacy.vocab import Vocab
|
2015-04-08 06:20:15 +00:00
|
|
|
from spacy.vocab import write_binary_vectors
|
2015-07-25 20:16:36 +00:00
|
|
|
from spacy.strings import hash_string
|
|
|
|
from preshed.counter import PreshCounter
|
2015-04-08 05:46:53 +00:00
|
|
|
|
2015-07-01 16:48:59 +00:00
|
|
|
from spacy.parts_of_speech import NOUN, VERB, ADJ
|
|
|
|
|
2015-08-23 23:05:20 +00:00
|
|
|
import spacy.en
|
|
|
|
import spacy.de
|
2015-08-27 08:26:02 +00:00
|
|
|
import spacy.fi
|
2015-09-06 15:51:30 +00:00
|
|
|
import spacy.it
|
2015-08-23 23:05:20 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
2015-04-08 05:46:53 +00:00
|
|
|
|
|
|
|
def setup_tokenizer(lang_data_dir, tok_dir):
|
|
|
|
if not tok_dir.exists():
|
|
|
|
tok_dir.mkdir()
|
|
|
|
|
|
|
|
for filename in ('infix.txt', 'morphs.json', 'prefix.txt', 'specials.json',
|
|
|
|
'suffix.txt'):
|
|
|
|
src = lang_data_dir / filename
|
|
|
|
dst = tok_dir / filename
|
2015-07-25 23:36:19 +00:00
|
|
|
copyfile(str(src), str(dst))
|
2015-04-08 05:46:53 +00:00
|
|
|
|
|
|
|
|
|
|
|
def _read_clusters(loc):
|
2015-07-21 22:25:14 +00:00
|
|
|
if not loc.exists():
|
2015-07-23 04:35:38 +00:00
|
|
|
print("Warning: Clusters file not found")
|
2015-07-21 22:25:14 +00:00
|
|
|
return {}
|
2015-04-08 05:46:53 +00:00
|
|
|
clusters = {}
|
2015-09-30 18:20:09 +00:00
|
|
|
for line in io.open(str(loc), 'r', encoding='utf8'):
|
2015-04-08 05:46:53 +00:00
|
|
|
try:
|
|
|
|
cluster, word, freq = line.split()
|
|
|
|
except ValueError:
|
|
|
|
continue
|
2015-04-17 02:44:52 +00:00
|
|
|
# If the clusterer has only seen the word a few times, its cluster is
|
|
|
|
# unreliable.
|
|
|
|
if int(freq) >= 3:
|
|
|
|
clusters[word] = cluster
|
2015-04-29 12:23:13 +00:00
|
|
|
else:
|
|
|
|
clusters[word] = '0'
|
2015-05-31 03:50:50 +00:00
|
|
|
# Expand clusters with re-casing
|
2015-07-23 11:13:15 +00:00
|
|
|
for word, cluster in list(clusters.items()):
|
2015-05-31 03:50:50 +00:00
|
|
|
if word.lower() not in clusters:
|
|
|
|
clusters[word.lower()] = cluster
|
|
|
|
if word.title() not in clusters:
|
|
|
|
clusters[word.title()] = cluster
|
2015-05-31 13:21:28 +00:00
|
|
|
if word.upper() not in clusters:
|
2015-05-31 03:50:50 +00:00
|
|
|
clusters[word.upper()] = cluster
|
2015-04-08 05:46:53 +00:00
|
|
|
return clusters
|
|
|
|
|
|
|
|
|
|
|
|
def _read_probs(loc):
|
2015-07-21 22:25:14 +00:00
|
|
|
if not loc.exists():
|
2015-07-26 20:39:22 +00:00
|
|
|
print("Probabilities file not found. Trying freqs.")
|
2015-07-25 21:33:02 +00:00
|
|
|
return {}, 0.0
|
2015-04-08 05:46:53 +00:00
|
|
|
probs = {}
|
2015-09-30 18:20:09 +00:00
|
|
|
for i, line in enumerate(io.open(str(loc), 'r', encoding='utf8')):
|
2015-04-08 05:46:53 +00:00
|
|
|
prob, word = line.split()
|
|
|
|
prob = float(prob)
|
|
|
|
probs[word] = prob
|
2015-07-25 21:33:02 +00:00
|
|
|
return probs, probs['-OOV-']
|
2015-04-08 05:46:53 +00:00
|
|
|
|
|
|
|
|
2015-07-27 19:44:51 +00:00
|
|
|
def _read_freqs(loc, max_length=100, min_doc_freq=5, min_freq=200):
|
2015-07-25 20:54:08 +00:00
|
|
|
if not loc.exists():
|
|
|
|
print("Warning: Frequencies file not found")
|
2015-07-26 12:03:30 +00:00
|
|
|
return {}, 0.0
|
2015-07-25 20:16:36 +00:00
|
|
|
counts = PreshCounter()
|
|
|
|
total = 0
|
2015-07-26 20:39:22 +00:00
|
|
|
if str(loc).endswith('gz'):
|
|
|
|
file_ = gzip.open(str(loc))
|
|
|
|
else:
|
|
|
|
file_ = loc.open()
|
|
|
|
for i, line in enumerate(file_):
|
2015-07-25 20:16:36 +00:00
|
|
|
freq, doc_freq, key = line.split('\t', 2)
|
|
|
|
freq = int(freq)
|
2015-07-25 20:56:35 +00:00
|
|
|
counts.inc(i+1, freq)
|
2015-07-25 20:16:36 +00:00
|
|
|
total += freq
|
|
|
|
counts.smooth()
|
|
|
|
log_total = math.log(total)
|
|
|
|
probs = {}
|
2015-07-25 20:56:35 +00:00
|
|
|
for line in loc.open():
|
2015-07-25 20:16:36 +00:00
|
|
|
freq, doc_freq, key = line.split('\t', 2)
|
2015-07-25 22:22:19 +00:00
|
|
|
doc_freq = int(doc_freq)
|
|
|
|
freq = int(freq)
|
|
|
|
if doc_freq >= min_doc_freq and freq >= min_freq and len(key) < max_length:
|
2015-07-25 20:16:36 +00:00
|
|
|
word = literal_eval(key)
|
|
|
|
smooth_count = counts.smoother(int(freq))
|
|
|
|
log_smooth_count = math.log(smooth_count)
|
|
|
|
probs[word] = math.log(smooth_count) - log_total
|
2015-07-25 21:29:51 +00:00
|
|
|
oov_prob = math.log(counts.smoother(0)) - log_total
|
|
|
|
return probs, oov_prob
|
2015-07-25 20:16:36 +00:00
|
|
|
|
|
|
|
|
2015-07-01 16:48:59 +00:00
|
|
|
def _read_senses(loc):
|
|
|
|
lexicon = defaultdict(lambda: defaultdict(list))
|
2015-07-21 22:25:14 +00:00
|
|
|
if not loc.exists():
|
2015-07-23 04:35:38 +00:00
|
|
|
print("Warning: WordNet senses not found")
|
2015-07-21 22:25:14 +00:00
|
|
|
return lexicon
|
2015-07-01 16:48:59 +00:00
|
|
|
sense_names = dict((s, i) for i, s in enumerate(spacy.senses.STRINGS))
|
|
|
|
pos_ids = {'noun': NOUN, 'verb': VERB, 'adjective': ADJ}
|
|
|
|
for line in codecs.open(str(loc), 'r', 'utf8'):
|
|
|
|
sense_strings = line.split()
|
|
|
|
word = sense_strings.pop(0)
|
|
|
|
for sense in sense_strings:
|
|
|
|
pos, sense = sense[3:].split('.')
|
|
|
|
sense_name = '%s_%s' % (pos[0].upper(), sense.lower())
|
|
|
|
if sense_name != 'N_tops':
|
|
|
|
sense_id = sense_names[sense_name]
|
|
|
|
lexicon[word][pos_ids[pos]].append(sense_id)
|
|
|
|
return lexicon
|
|
|
|
|
|
|
|
|
2015-09-06 15:51:30 +00:00
|
|
|
def setup_vocab(get_lex_attr, tag_map, src_dir, dst_dir):
|
2015-04-08 05:46:53 +00:00
|
|
|
if not dst_dir.exists():
|
|
|
|
dst_dir.mkdir()
|
2015-04-08 06:20:15 +00:00
|
|
|
|
|
|
|
vectors_src = src_dir / 'vectors.tgz'
|
|
|
|
if vectors_src.exists():
|
|
|
|
write_binary_vectors(str(vectors_src), str(dst_dir / 'vec.bin'))
|
2015-07-21 22:25:14 +00:00
|
|
|
else:
|
2015-07-23 04:35:38 +00:00
|
|
|
print("Warning: Word vectors file not found")
|
2015-09-06 15:51:30 +00:00
|
|
|
vocab = Vocab(get_lex_attr=get_lex_attr, tag_map=tag_map)
|
2015-04-08 05:46:53 +00:00
|
|
|
clusters = _read_clusters(src_dir / 'clusters.txt')
|
2015-07-25 21:29:51 +00:00
|
|
|
probs, oov_prob = _read_probs(src_dir / 'words.sgt.prob')
|
2015-07-25 20:16:36 +00:00
|
|
|
if not probs:
|
2015-07-27 19:44:51 +00:00
|
|
|
probs, oov_prob = _read_freqs(src_dir / 'freqs.txt')
|
2015-07-23 07:27:07 +00:00
|
|
|
if not probs:
|
2015-08-23 23:05:20 +00:00
|
|
|
oov_prob = -20
|
2015-07-23 07:27:07 +00:00
|
|
|
else:
|
2015-07-25 21:29:51 +00:00
|
|
|
oov_prob = min(probs.values())
|
2015-07-23 07:27:07 +00:00
|
|
|
for word in clusters:
|
|
|
|
if word not in probs:
|
2015-07-25 21:29:51 +00:00
|
|
|
probs[word] = oov_prob
|
2015-07-23 07:27:07 +00:00
|
|
|
|
2015-04-08 05:46:53 +00:00
|
|
|
lexicon = []
|
2015-07-23 07:45:15 +00:00
|
|
|
for word, prob in reversed(sorted(list(probs.items()), key=lambda item: item[1])):
|
2015-10-06 13:39:50 +00:00
|
|
|
# First encode the strings into the StringStore. This way, we can map
|
|
|
|
# the orth IDs to frequency ranks
|
|
|
|
orth = vocab.strings[word]
|
|
|
|
# Now actually load the vocab
|
|
|
|
for word, prob in reversed(sorted(list(probs.items()), key=lambda item: item[1])):
|
2015-08-23 23:05:20 +00:00
|
|
|
lexeme = vocab[word]
|
|
|
|
lexeme.prob = prob
|
|
|
|
lexeme.is_oov = False
|
2015-07-25 21:29:51 +00:00
|
|
|
# Decode as a little-endian string, so that we can do & 15 to get
|
|
|
|
# the first 4 bits. See _parse_features.pyx
|
2015-08-23 23:05:20 +00:00
|
|
|
if word in clusters:
|
|
|
|
lexeme.cluster = int(clusters[word][::-1], 2)
|
|
|
|
else:
|
|
|
|
lexeme.cluster = 0
|
2015-04-08 05:46:53 +00:00
|
|
|
vocab.dump(str(dst_dir / 'lexemes.bin'))
|
|
|
|
vocab.strings.dump(str(dst_dir / 'strings.txt'))
|
2015-07-25 21:29:51 +00:00
|
|
|
with (dst_dir / 'oov_prob').open('w') as file_:
|
|
|
|
file_.write('%f' % oov_prob)
|
2015-04-08 05:46:53 +00:00
|
|
|
|
|
|
|
|
2015-08-23 23:05:20 +00:00
|
|
|
def main(lang_id, lang_data_dir, corpora_dir, model_dir):
|
|
|
|
languages = {
|
2015-08-26 17:14:05 +00:00
|
|
|
'en': spacy.en.English.default_lex_attrs(),
|
2015-09-06 18:18:58 +00:00
|
|
|
'de': spacy.de.German.default_lex_attrs(),
|
2015-09-06 15:51:30 +00:00
|
|
|
'fi': spacy.fi.Finnish.default_lex_attrs(),
|
|
|
|
'it': spacy.it.Italian.default_lex_attrs(),
|
2015-08-23 23:05:20 +00:00
|
|
|
}
|
|
|
|
|
2015-04-08 05:46:53 +00:00
|
|
|
model_dir = Path(model_dir)
|
2015-08-23 23:05:20 +00:00
|
|
|
lang_data_dir = Path(lang_data_dir) / lang_id
|
|
|
|
corpora_dir = Path(corpora_dir) / lang_id
|
2015-04-08 06:20:15 +00:00
|
|
|
|
|
|
|
assert corpora_dir.exists()
|
|
|
|
assert lang_data_dir.exists()
|
2015-04-08 05:46:53 +00:00
|
|
|
|
|
|
|
if not model_dir.exists():
|
|
|
|
model_dir.mkdir()
|
|
|
|
|
2015-09-06 15:51:30 +00:00
|
|
|
tag_map = json.load((lang_data_dir / 'tag_map.json').open())
|
2015-04-08 05:46:53 +00:00
|
|
|
setup_tokenizer(lang_data_dir, model_dir / 'tokenizer')
|
2015-09-06 15:51:30 +00:00
|
|
|
setup_vocab(languages[lang_id], tag_map, corpora_dir, model_dir / 'vocab')
|
2015-08-06 14:07:23 +00:00
|
|
|
|
|
|
|
if (lang_data_dir / 'gazetteer.json').exists():
|
|
|
|
copyfile(str(lang_data_dir / 'gazetteer.json'),
|
|
|
|
str(model_dir / 'vocab' / 'gazetteer.json'))
|
2015-08-27 08:26:02 +00:00
|
|
|
|
2015-09-12 03:54:02 +00:00
|
|
|
if (lang_data_dir / 'tag_map.json').exists():
|
|
|
|
copyfile(str(lang_data_dir / 'tag_map.json'),
|
|
|
|
str(model_dir / 'vocab' / 'tag_map.json'))
|
|
|
|
|
2015-08-27 08:26:02 +00:00
|
|
|
if (lang_data_dir / 'lemma_rules.json').exists():
|
|
|
|
copyfile(str(lang_data_dir / 'lemma_rules.json'),
|
|
|
|
str(model_dir / 'vocab' / 'lemma_rules.json'))
|
|
|
|
|
2015-08-23 23:05:20 +00:00
|
|
|
if not (model_dir / 'wordnet').exists() and (corpora_dir / 'wordnet').exists():
|
2015-07-23 04:35:38 +00:00
|
|
|
copytree(str(corpora_dir / 'wordnet' / 'dict'), str(model_dir / 'wordnet'))
|
2015-04-08 05:46:53 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
plac.call(main)
|