2020-06-21 22:35:01 +03:00
from typing import Optional , List , Dict , Any , Union , IO
2017-11-27 01:21:47 +03:00
import math
2019-12-16 15:12:19 +03:00
from tqdm import tqdm
2017-11-27 01:21:47 +03:00
import numpy
from ast import literal_eval
from pathlib import Path
from preshed . counter import PreshCounter
2018-03-21 16:33:23 +03:00
import tarfile
import gzip
2018-03-28 00:01:18 +03:00
import zipfile
💫 Replace ujson, msgpack and dill/pickle/cloudpickle with srsly (#3003)
Remove hacks and wrappers, keep code in sync across our libraries and move spaCy a few steps closer to only depending on packages with binary wheels 🎉
See here: https://github.com/explosion/srsly
Serialization is hard, especially across Python versions and multiple platforms. After dealing with many subtle bugs over the years (encodings, locales, large files) our libraries like spaCy and Prodigy have steadily grown a number of utility functions to wrap the multiple serialization formats we need to support (especially json, msgpack and pickle). These wrapping functions ended up duplicated across our codebases, so we wanted to put them in one place.
At the same time, we noticed that having a lot of small dependencies was making maintainence harder, and making installation slower. To solve this, we've made srsly standalone, by including the component packages directly within it. This way we can provide all the serialization utilities we need in a single binary wheel.
srsly currently includes forks of the following packages:
ujson
msgpack
msgpack-numpy
cloudpickle
* WIP: replace json/ujson with srsly
* Replace ujson in examples
Use regular json instead of srsly to make code easier to read and follow
* Update requirements
* Fix imports
* Fix typos
* Replace msgpack with srsly
* Fix warning
2018-12-03 03:28:22 +03:00
import srsly
2020-04-28 15:00:11 +03:00
import warnings
2020-08-02 16:18:30 +03:00
from wasabi import msg , Printer
import typer
2017-11-27 01:21:47 +03:00
2020-08-02 16:18:30 +03:00
from . _util import app , init_cli , Arg , Opt
2017-12-07 12:03:07 +03:00
from . . vectors import Vectors
2020-04-28 14:37:37 +03:00
from . . errors import Errors , Warnings
2020-06-21 22:35:01 +03:00
from . . language import Language
2020-05-20 19:49:11 +03:00
from . . util import ensure_path , get_lang_class , load_model , OOV_RANK
2017-11-27 01:21:47 +03:00
2018-04-10 20:08:06 +03:00
try :
import ftfy
except ImportError :
ftfy = None
2017-11-27 01:21:47 +03:00
2019-08-01 18:26:09 +03:00
DEFAULT_OOV_PROB = - 20
2018-11-30 22:16:14 +03:00
2020-09-04 13:58:50 +03:00
@init_cli.command ( " vocab " )
2020-08-02 16:18:30 +03:00
@app.command (
" init-model " ,
context_settings = { " allow_extra_args " : True , " ignore_unknown_options " : True } ,
hidden = True , # hide this from main CLI help but still allow it to work with warning
)
2020-06-21 22:35:01 +03:00
def init_model_cli (
2020-01-01 15:15:46 +03:00
# fmt: off
2020-08-02 16:18:30 +03:00
ctx : typer . Context , # This is only used to read additional arguments
2020-09-03 14:13:03 +03:00
lang : str = Arg ( . . . , help = " Pipeline language " ) ,
output_dir : Path = Arg ( . . . , help = " Pipeline output directory " ) ,
2020-06-21 22:35:01 +03:00
freqs_loc : Optional [ Path ] = Arg ( None , help = " Location of words frequencies file " , exists = True ) ,
clusters_loc : Optional [ Path ] = Opt ( None , " --clusters-loc " , " -c " , help = " Optional location of brown clusters data " , exists = True ) ,
jsonl_loc : Optional [ Path ] = Opt ( None , " --jsonl-loc " , " -j " , help = " Location of JSONL-formatted attributes file " , exists = True ) ,
vectors_loc : Optional [ Path ] = Opt ( None , " --vectors-loc " , " -v " , help = " Optional vectors file in Word2Vec format " , exists = True ) ,
2020-07-01 22:00:47 +03:00
prune_vectors : int = Opt ( - 1 , " --prune-vectors " , " -V " , help = " Optional number of vectors to prune to " ) ,
2020-06-21 14:44:00 +03:00
truncate_vectors : int = Opt ( 0 , " --truncate-vectors " , " -t " , help = " Optional number of vectors to truncate to when reading in vectors file " ) ,
vectors_name : Optional [ str ] = Opt ( None , " --vectors-name " , " -vn " , help = " Optional name for the word vectors, e.g. en_core_web_lg.vectors " ) ,
2020-09-03 18:12:24 +03:00
model_name : Optional [ str ] = Opt ( None , " --meta-name " , " -mn " , help = " Optional name of the package for the pipeline meta " ) ,
base_model : Optional [ str ] = Opt ( None , " --base " , " -b " , help = " Name of or path to base pipeline to start with (mostly relevant for pipelines with custom tokenizers) " )
2020-01-01 15:15:46 +03:00
# fmt: on
2018-11-30 22:16:14 +03:00
) :
2017-12-07 12:23:09 +03:00
"""
2020-09-03 14:13:03 +03:00
Create a new blank pipeline directory with vocab and vectors from raw data .
If vectors are provided in Word2Vec format , they can be either a . txt or
zipped as a . zip or . tar . gz .
2020-09-04 13:58:50 +03:00
DOCS : https : / / nightly . spacy . io / api / cli #init-vocab
2017-12-07 12:23:09 +03:00
"""
2020-08-02 16:18:30 +03:00
if ctx . command . name == " init-model " :
msg . warn (
2020-09-03 14:13:03 +03:00
" The init-model command is now called ' init vocab ' . You can run "
" ' python -m spacy init --help ' for an overview of the other "
" available initialization commands. "
2020-08-02 16:18:30 +03:00
)
2020-06-21 22:35:01 +03:00
init_model (
lang ,
output_dir ,
freqs_loc = freqs_loc ,
clusters_loc = clusters_loc ,
jsonl_loc = jsonl_loc ,
2020-07-01 22:00:47 +03:00
vectors_loc = vectors_loc ,
2020-06-21 22:35:01 +03:00
prune_vectors = prune_vectors ,
truncate_vectors = truncate_vectors ,
vectors_name = vectors_name ,
model_name = model_name ,
base_model = base_model ,
silent = False ,
)
def init_model (
lang : str ,
output_dir : Path ,
freqs_loc : Optional [ Path ] = None ,
clusters_loc : Optional [ Path ] = None ,
jsonl_loc : Optional [ Path ] = None ,
vectors_loc : Optional [ Path ] = None ,
prune_vectors : int = - 1 ,
truncate_vectors : int = 0 ,
vectors_name : Optional [ str ] = None ,
model_name : Optional [ str ] = None ,
base_model : Optional [ str ] = None ,
silent : bool = True ,
) - > Language :
msg = Printer ( no_print = silent , pretty = not silent )
2018-07-03 13:22:56 +03:00
if jsonl_loc is not None :
if freqs_loc is not None or clusters_loc is not None :
2018-11-30 22:16:14 +03:00
settings = [ " -j " ]
2018-07-03 13:22:56 +03:00
if freqs_loc :
2018-11-30 22:16:14 +03:00
settings . append ( " -f " )
2018-07-03 13:22:56 +03:00
if clusters_loc :
2018-11-30 22:16:14 +03:00
settings . append ( " -c " )
2018-12-08 13:49:43 +03:00
msg . warn (
" Incompatible arguments " ,
" The -f and -c arguments are deprecated, and not compatible "
" with the -j argument, which should specify the same "
" information. Either merge the frequencies and clusters data "
" into the JSONL-formatted file (recommended), or use only the "
" -f and -c files, without the other lexical attributes. " ,
)
2018-07-03 13:22:56 +03:00
jsonl_loc = ensure_path ( jsonl_loc )
💫 Replace ujson, msgpack and dill/pickle/cloudpickle with srsly (#3003)
Remove hacks and wrappers, keep code in sync across our libraries and move spaCy a few steps closer to only depending on packages with binary wheels 🎉
See here: https://github.com/explosion/srsly
Serialization is hard, especially across Python versions and multiple platforms. After dealing with many subtle bugs over the years (encodings, locales, large files) our libraries like spaCy and Prodigy have steadily grown a number of utility functions to wrap the multiple serialization formats we need to support (especially json, msgpack and pickle). These wrapping functions ended up duplicated across our codebases, so we wanted to put them in one place.
At the same time, we noticed that having a lot of small dependencies was making maintainence harder, and making installation slower. To solve this, we've made srsly standalone, by including the component packages directly within it. This way we can provide all the serialization utilities we need in a single binary wheel.
srsly currently includes forks of the following packages:
ujson
msgpack
msgpack-numpy
cloudpickle
* WIP: replace json/ujson with srsly
* Replace ujson in examples
Use regular json instead of srsly to make code easier to read and follow
* Update requirements
* Fix imports
* Fix typos
* Replace msgpack with srsly
* Fix warning
2018-12-03 03:28:22 +03:00
lex_attrs = srsly . read_jsonl ( jsonl_loc )
2018-07-03 13:22:56 +03:00
else :
clusters_loc = ensure_path ( clusters_loc )
freqs_loc = ensure_path ( freqs_loc )
if freqs_loc is not None and not freqs_loc . exists ( ) :
2018-12-08 13:49:43 +03:00
msg . fail ( " Can ' t find words frequencies file " , freqs_loc , exits = 1 )
2020-06-21 22:35:01 +03:00
lex_attrs = read_attrs_from_deprecated ( msg , freqs_loc , clusters_loc )
2018-07-04 03:29:48 +03:00
2020-09-03 14:13:03 +03:00
with msg . loading ( " Creating blank pipeline... " ) :
2020-05-20 19:49:11 +03:00
nlp = create_model ( lang , lex_attrs , name = model_name , base_model = base_model )
2020-05-20 16:51:44 +03:00
2020-09-03 14:13:03 +03:00
msg . good ( " Successfully created blank pipeline " )
2018-07-04 03:29:48 +03:00
if vectors_loc is not None :
2020-06-21 22:35:01 +03:00
add_vectors (
msg , nlp , vectors_loc , truncate_vectors , prune_vectors , vectors_name
)
2018-07-04 03:29:48 +03:00
vec_added = len ( nlp . vocab . vectors )
lex_added = len ( nlp . vocab )
2018-12-08 13:49:43 +03:00
msg . good (
2019-12-22 03:53:56 +03:00
" Sucessfully compiled vocab " , f " { lex_added } entries, { vec_added } vectors " ,
2018-12-08 13:49:43 +03:00
)
2017-11-27 01:21:47 +03:00
if not output_dir . exists ( ) :
output_dir . mkdir ( )
nlp . to_disk ( output_dir )
return nlp
2018-11-30 22:16:14 +03:00
2020-06-21 22:35:01 +03:00
def open_file ( loc : Union [ str , Path ] ) - > IO :
2018-11-30 22:16:14 +03:00
""" Handle .gz, .tar.gz or unzipped files """
2018-03-21 16:33:23 +03:00
loc = ensure_path ( loc )
if tarfile . is_tarfile ( str ( loc ) ) :
2018-11-30 22:16:14 +03:00
return tarfile . open ( str ( loc ) , " r:gz " )
elif loc . parts [ - 1 ] . endswith ( " gz " ) :
return ( line . decode ( " utf8 " ) for line in gzip . open ( str ( loc ) , " r " ) )
elif loc . parts [ - 1 ] . endswith ( " zip " ) :
2018-03-28 00:01:18 +03:00
zip_file = zipfile . ZipFile ( str ( loc ) )
names = zip_file . namelist ( )
file_ = zip_file . open ( names [ 0 ] )
2018-11-30 22:16:14 +03:00
return ( line . decode ( " utf8 " ) for line in file_ )
2018-03-21 16:33:23 +03:00
else :
2018-11-30 22:16:14 +03:00
return loc . open ( " r " , encoding = " utf8 " )
2018-03-21 16:33:23 +03:00
2020-06-21 22:35:01 +03:00
def read_attrs_from_deprecated (
msg : Printer , freqs_loc : Optional [ Path ] , clusters_loc : Optional [ Path ]
) - > List [ Dict [ str , Any ] ] :
2019-08-01 18:26:09 +03:00
if freqs_loc is not None :
with msg . loading ( " Counting frequencies... " ) :
probs , _ = read_freqs ( freqs_loc )
msg . good ( " Counted frequencies " )
else :
2019-08-18 16:09:16 +03:00
probs , _ = ( { } , DEFAULT_OOV_PROB ) # noqa: F841
2019-08-01 18:26:09 +03:00
if clusters_loc :
with msg . loading ( " Reading clusters... " ) :
clusters = read_clusters ( clusters_loc )
msg . good ( " Read clusters " )
else :
clusters = { }
2018-08-14 14:19:15 +03:00
lex_attrs = [ ]
2018-07-03 13:22:56 +03:00
sorted_probs = sorted ( probs . items ( ) , key = lambda item : item [ 1 ] , reverse = True )
2019-08-01 18:26:09 +03:00
if len ( sorted_probs ) :
for i , ( word , prob ) in tqdm ( enumerate ( sorted_probs ) ) :
attrs = { " orth " : word , " id " : i , " prob " : prob }
# Decode as a little-endian string, so that we can do & 15 to get
# the first 4 bits. See _parse_features.pyx
if word in clusters :
attrs [ " cluster " ] = int ( clusters [ word ] [ : : - 1 ] , 2 )
else :
attrs [ " cluster " ] = 0
lex_attrs . append ( attrs )
2018-07-03 13:22:56 +03:00
return lex_attrs
2020-06-21 22:35:01 +03:00
def create_model (
lang : str ,
lex_attrs : List [ Dict [ str , Any ] ] ,
name : Optional [ str ] = None ,
base_model : Optional [ Union [ str , Path ] ] = None ,
) - > Language :
2020-05-20 19:49:11 +03:00
if base_model :
nlp = load_model ( base_model )
# keep the tokenizer but remove any existing pipeline components due to
# potentially conflicting vectors
for pipe in nlp . pipe_names :
nlp . remove_pipe ( pipe )
else :
lang_class = get_lang_class ( lang )
nlp = lang_class ( )
2017-11-27 01:21:47 +03:00
for lexeme in nlp . vocab :
2020-04-15 14:49:47 +03:00
lexeme . rank = OOV_RANK
2018-07-03 13:22:56 +03:00
for attrs in lex_attrs :
2018-11-30 22:16:14 +03:00
if " settings " in attrs :
2018-07-04 03:29:48 +03:00
continue
2018-11-30 22:16:14 +03:00
lexeme = nlp . vocab [ attrs [ " orth " ] ]
2018-07-04 03:29:48 +03:00
lexeme . set_attrs ( * * attrs )
2019-08-01 18:26:09 +03:00
if len ( nlp . vocab ) :
oov_prob = min ( lex . prob for lex in nlp . vocab ) - 1
else :
oov_prob = DEFAULT_OOV_PROB
nlp . vocab . cfg . update ( { " oov_prob " : oov_prob } )
2019-09-26 04:01:32 +03:00
if name :
nlp . meta [ " name " ] = name
2017-11-27 01:21:47 +03:00
return nlp
2018-11-30 22:16:14 +03:00
2020-06-21 22:35:01 +03:00
def add_vectors (
msg : Printer ,
nlp : Language ,
vectors_loc : Optional [ Path ] ,
truncate_vectors : int ,
prune_vectors : int ,
name : Optional [ str ] = None ,
) - > None :
2018-07-04 03:29:48 +03:00
vectors_loc = ensure_path ( vectors_loc )
2018-11-30 22:16:14 +03:00
if vectors_loc and vectors_loc . parts [ - 1 ] . endswith ( " .npz " ) :
nlp . vocab . vectors = Vectors ( data = numpy . load ( vectors_loc . open ( " rb " ) ) )
2018-07-04 03:29:48 +03:00
for lex in nlp . vocab :
2020-05-13 23:08:28 +03:00
if lex . rank and lex . rank != OOV_RANK :
2018-07-04 03:29:48 +03:00
nlp . vocab . vectors . add ( lex . orth , row = lex . rank )
else :
2018-11-30 22:16:14 +03:00
if vectors_loc :
2019-12-22 03:53:56 +03:00
with msg . loading ( f " Reading vectors from { vectors_loc } " ) :
2020-07-04 17:25:34 +03:00
vectors_data , vector_keys = read_vectors (
msg , vectors_loc , truncate_vectors
)
2019-12-22 03:53:56 +03:00
msg . good ( f " Loaded vectors from { vectors_loc } " )
2018-11-30 22:16:14 +03:00
else :
vectors_data , vector_keys = ( None , None )
2018-07-04 03:29:48 +03:00
if vector_keys is not None :
for word in vector_keys :
if word not in nlp . vocab :
2020-05-19 16:59:14 +03:00
nlp . vocab [ word ]
2018-07-04 03:29:48 +03:00
if vectors_data is not None :
nlp . vocab . vectors = Vectors ( data = vectors_data , keys = vector_keys )
2019-09-25 14:11:00 +03:00
if name is None :
2020-09-03 14:13:03 +03:00
# TODO: Is this correct? Does this matter?
nlp . vocab . vectors . name = f " { nlp . meta [ ' lang ' ] } _ { nlp . meta [ ' name ' ] } .vectors "
2019-09-25 14:11:00 +03:00
else :
nlp . vocab . vectors . name = name
2018-11-30 22:16:14 +03:00
nlp . meta [ " vectors " ] [ " name " ] = nlp . vocab . vectors . name
2018-07-04 03:29:48 +03:00
if prune_vectors > = 1 :
nlp . vocab . prune_vectors ( prune_vectors )
2017-11-27 01:21:47 +03:00
2018-11-30 22:16:14 +03:00
2020-07-01 22:00:47 +03:00
def read_vectors ( msg : Printer , vectors_loc : Path , truncate_vectors : int ) :
2018-03-21 16:33:23 +03:00
f = open_file ( vectors_loc )
shape = tuple ( int ( size ) for size in next ( f ) . split ( ) )
2020-04-29 13:56:46 +03:00
if truncate_vectors > = 1 :
shape = ( truncate_vectors , shape [ 1 ] )
2018-11-30 22:16:14 +03:00
vectors_data = numpy . zeros ( shape = shape , dtype = " f " )
2018-03-21 16:33:23 +03:00
vectors_keys = [ ]
for i , line in enumerate ( tqdm ( f ) ) :
2018-03-28 00:01:18 +03:00
line = line . rstrip ( )
2019-05-07 00:00:38 +03:00
pieces = line . rsplit ( " " , vectors_data . shape [ 1 ] )
2018-03-21 16:33:23 +03:00
word = pieces . pop ( 0 )
2018-03-28 00:01:18 +03:00
if len ( pieces ) != vectors_data . shape [ 1 ] :
2018-11-30 22:16:14 +03:00
msg . fail ( Errors . E094 . format ( line_num = i , loc = vectors_loc ) , exits = 1 )
vectors_data [ i ] = numpy . asarray ( pieces , dtype = " f " )
2018-03-21 16:33:23 +03:00
vectors_keys . append ( word )
2020-04-29 13:56:46 +03:00
if i == truncate_vectors - 1 :
break
2017-11-27 01:21:47 +03:00
return vectors_data , vectors_keys
2020-06-21 22:35:01 +03:00
def read_freqs (
freqs_loc : Path , max_length : int = 100 , min_doc_freq : int = 5 , min_freq : int = 50
) :
2017-11-27 01:21:47 +03:00
counts = PreshCounter ( )
total = 0
with freqs_loc . open ( ) as f :
for i , line in enumerate ( f ) :
2018-11-30 22:16:14 +03:00
freq , doc_freq , key = line . rstrip ( ) . split ( " \t " , 2 )
2017-11-27 01:21:47 +03:00
freq = int ( freq )
counts . inc ( i + 1 , freq )
total + = freq
counts . smooth ( )
log_total = math . log ( total )
probs = { }
with freqs_loc . open ( ) as f :
for line in tqdm ( f ) :
2018-11-30 22:16:14 +03:00
freq , doc_freq , key = line . rstrip ( ) . split ( " \t " , 2 )
2017-11-27 01:21:47 +03:00
doc_freq = int ( doc_freq )
freq = int ( freq )
if doc_freq > = min_doc_freq and freq > = min_freq and len ( key ) < max_length :
2019-01-15 01:48:30 +03:00
try :
word = literal_eval ( key )
except SyntaxError :
# Take odd strings literally.
2019-12-25 19:59:52 +03:00
word = literal_eval ( f " ' { key } ' " )
2017-11-27 01:21:47 +03:00
smooth_count = counts . smoother ( int ( freq ) )
probs [ word ] = math . log ( smooth_count ) - log_total
oov_prob = math . log ( counts . smoother ( 0 ) ) - log_total
return probs , oov_prob
2020-06-21 22:35:01 +03:00
def read_clusters ( clusters_loc : Path ) - > dict :
2017-11-27 01:21:47 +03:00
clusters = { }
2018-04-10 20:08:06 +03:00
if ftfy is None :
2020-04-28 14:37:37 +03:00
warnings . warn ( Warnings . W004 )
2017-11-27 01:21:47 +03:00
with clusters_loc . open ( ) as f :
for line in tqdm ( f ) :
try :
cluster , word , freq = line . split ( )
2018-04-10 20:08:06 +03:00
if ftfy is not None :
word = ftfy . fix_text ( word )
2017-11-27 01:21:47 +03:00
except ValueError :
continue
# If the clusterer has only seen the word a few times, its
# cluster is unreliable.
if int ( freq ) > = 3 :
clusters [ word ] = cluster
else :
2018-11-30 22:16:14 +03:00
clusters [ word ] = " 0 "
2017-11-27 01:21:47 +03:00
# Expand clusters with re-casing
for word , cluster in list ( clusters . items ( ) ) :
if word . lower ( ) not in clusters :
clusters [ word . lower ( ) ] = cluster
if word . title ( ) not in clusters :
clusters [ word . title ( ) ] = cluster
if word . upper ( ) not in clusters :
clusters [ word . upper ( ) ] = cluster
return clusters