repo stringclasses 85
values | path stringlengths 8 121 | func_name stringlengths 1 82 | original_string stringlengths 112 65.5k | language stringclasses 1
value | code stringlengths 112 65.5k | code_tokens listlengths 20 4.09k | docstring stringlengths 3 46.3k | docstring_tokens listlengths 1 564 | sha stringclasses 85
values | url stringlengths 93 218 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
explosion/spaCy | examples/pipeline/custom_attr_methods.py | overlap_tokens | def overlap_tokens(doc, other_doc):
"""Get the tokens from the original Doc that are also in the comparison Doc.
"""
overlap = []
other_tokens = [token.text for token in other_doc]
for token in doc:
if token.text in other_tokens:
overlap.append(token)
return overlap | python | def overlap_tokens(doc, other_doc):
"""Get the tokens from the original Doc that are also in the comparison Doc.
"""
overlap = []
other_tokens = [token.text for token in other_doc]
for token in doc:
if token.text in other_tokens:
overlap.append(token)
return overlap | [
"def",
"overlap_tokens",
"(",
"doc",
",",
"other_doc",
")",
":",
"overlap",
"=",
"[",
"]",
"other_tokens",
"=",
"[",
"token",
".",
"text",
"for",
"token",
"in",
"other_doc",
"]",
"for",
"token",
"in",
"doc",
":",
"if",
"token",
".",
"text",
"in",
"ot... | Get the tokens from the original Doc that are also in the comparison Doc. | [
"Get",
"the",
"tokens",
"from",
"the",
"original",
"Doc",
"that",
"are",
"also",
"in",
"the",
"comparison",
"Doc",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/examples/pipeline/custom_attr_methods.py#L61-L69 | train |
explosion/spaCy | spacy/cli/converters/iob2json.py | iob2json | def iob2json(input_data, n_sents=10, *args, **kwargs):
"""
Convert IOB files into JSON format for use with train cli.
"""
docs = []
for group in minibatch(docs, n_sents):
group = list(group)
first = group.pop(0)
to_extend = first["paragraphs"][0]["sentences"]
for sent... | python | def iob2json(input_data, n_sents=10, *args, **kwargs):
"""
Convert IOB files into JSON format for use with train cli.
"""
docs = []
for group in minibatch(docs, n_sents):
group = list(group)
first = group.pop(0)
to_extend = first["paragraphs"][0]["sentences"]
for sent... | [
"def",
"iob2json",
"(",
"input_data",
",",
"n_sents",
"=",
"10",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"docs",
"=",
"[",
"]",
"for",
"group",
"in",
"minibatch",
"(",
"docs",
",",
"n_sents",
")",
":",
"group",
"=",
"list",
"(",
"gro... | Convert IOB files into JSON format for use with train cli. | [
"Convert",
"IOB",
"files",
"into",
"JSON",
"format",
"for",
"use",
"with",
"train",
"cli",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/converters/iob2json.py#L10-L22 | train |
explosion/spaCy | spacy/displacy/__init__.py | render | def render(
docs, style="dep", page=False, minify=False, jupyter=None, options={}, manual=False
):
"""Render displaCy visualisation.
docs (list or Doc): Document(s) to visualise.
style (unicode): Visualisation style, 'dep' or 'ent'.
page (bool): Render markup as full HTML page.
minify (bool): M... | python | def render(
docs, style="dep", page=False, minify=False, jupyter=None, options={}, manual=False
):
"""Render displaCy visualisation.
docs (list or Doc): Document(s) to visualise.
style (unicode): Visualisation style, 'dep' or 'ent'.
page (bool): Render markup as full HTML page.
minify (bool): M... | [
"def",
"render",
"(",
"docs",
",",
"style",
"=",
"\"dep\"",
",",
"page",
"=",
"False",
",",
"minify",
"=",
"False",
",",
"jupyter",
"=",
"None",
",",
"options",
"=",
"{",
"}",
",",
"manual",
"=",
"False",
")",
":",
"factories",
"=",
"{",
"\"dep\"",... | Render displaCy visualisation.
docs (list or Doc): Document(s) to visualise.
style (unicode): Visualisation style, 'dep' or 'ent'.
page (bool): Render markup as full HTML page.
minify (bool): Minify HTML markup.
jupyter (bool): Override Jupyter auto-detection.
options (dict): Visualiser-specifi... | [
"Render",
"displaCy",
"visualisation",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/__init__.py#L21-L61 | train |
explosion/spaCy | spacy/displacy/__init__.py | serve | def serve(
docs,
style="dep",
page=True,
minify=False,
options={},
manual=False,
port=5000,
host="0.0.0.0",
):
"""Serve displaCy visualisation.
docs (list or Doc): Document(s) to visualise.
style (unicode): Visualisation style, 'dep' or 'ent'.
page (bool): Render markup ... | python | def serve(
docs,
style="dep",
page=True,
minify=False,
options={},
manual=False,
port=5000,
host="0.0.0.0",
):
"""Serve displaCy visualisation.
docs (list or Doc): Document(s) to visualise.
style (unicode): Visualisation style, 'dep' or 'ent'.
page (bool): Render markup ... | [
"def",
"serve",
"(",
"docs",
",",
"style",
"=",
"\"dep\"",
",",
"page",
"=",
"True",
",",
"minify",
"=",
"False",
",",
"options",
"=",
"{",
"}",
",",
"manual",
"=",
"False",
",",
"port",
"=",
"5000",
",",
"host",
"=",
"\"0.0.0.0\"",
",",
")",
":"... | Serve displaCy visualisation.
docs (list or Doc): Document(s) to visualise.
style (unicode): Visualisation style, 'dep' or 'ent'.
page (bool): Render markup as full HTML page.
minify (bool): Minify HTML markup.
options (dict): Visualiser-specific options, e.g. colors.
manual (bool): Don't parse... | [
"Serve",
"displaCy",
"visualisation",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/__init__.py#L64-L102 | train |
explosion/spaCy | spacy/displacy/__init__.py | parse_deps | def parse_deps(orig_doc, options={}):
"""Generate dependency parse in {'words': [], 'arcs': []} format.
doc (Doc): Document do parse.
RETURNS (dict): Generated dependency parse keyed by words and arcs.
"""
doc = Doc(orig_doc.vocab).from_bytes(orig_doc.to_bytes())
if not doc.is_parsed:
u... | python | def parse_deps(orig_doc, options={}):
"""Generate dependency parse in {'words': [], 'arcs': []} format.
doc (Doc): Document do parse.
RETURNS (dict): Generated dependency parse keyed by words and arcs.
"""
doc = Doc(orig_doc.vocab).from_bytes(orig_doc.to_bytes())
if not doc.is_parsed:
u... | [
"def",
"parse_deps",
"(",
"orig_doc",
",",
"options",
"=",
"{",
"}",
")",
":",
"doc",
"=",
"Doc",
"(",
"orig_doc",
".",
"vocab",
")",
".",
"from_bytes",
"(",
"orig_doc",
".",
"to_bytes",
"(",
")",
")",
"if",
"not",
"doc",
".",
"is_parsed",
":",
"us... | Generate dependency parse in {'words': [], 'arcs': []} format.
doc (Doc): Document do parse.
RETURNS (dict): Generated dependency parse keyed by words and arcs. | [
"Generate",
"dependency",
"parse",
"in",
"{",
"words",
":",
"[]",
"arcs",
":",
"[]",
"}",
"format",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/__init__.py#L113-L165 | train |
explosion/spaCy | spacy/displacy/__init__.py | parse_ents | def parse_ents(doc, options={}):
"""Generate named entities in [{start: i, end: i, label: 'label'}] format.
doc (Doc): Document do parse.
RETURNS (dict): Generated entities keyed by text (original text) and ents.
"""
ents = [
{"start": ent.start_char, "end": ent.end_char, "label": ent.label... | python | def parse_ents(doc, options={}):
"""Generate named entities in [{start: i, end: i, label: 'label'}] format.
doc (Doc): Document do parse.
RETURNS (dict): Generated entities keyed by text (original text) and ents.
"""
ents = [
{"start": ent.start_char, "end": ent.end_char, "label": ent.label... | [
"def",
"parse_ents",
"(",
"doc",
",",
"options",
"=",
"{",
"}",
")",
":",
"ents",
"=",
"[",
"{",
"\"start\"",
":",
"ent",
".",
"start_char",
",",
"\"end\"",
":",
"ent",
".",
"end_char",
",",
"\"label\"",
":",
"ent",
".",
"label_",
"}",
"for",
"ent"... | Generate named entities in [{start: i, end: i, label: 'label'}] format.
doc (Doc): Document do parse.
RETURNS (dict): Generated entities keyed by text (original text) and ents. | [
"Generate",
"named",
"entities",
"in",
"[",
"{",
"start",
":",
"i",
"end",
":",
"i",
"label",
":",
"label",
"}",
"]",
"format",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/__init__.py#L168-L182 | train |
explosion/spaCy | spacy/displacy/__init__.py | set_render_wrapper | def set_render_wrapper(func):
"""Set an optional wrapper function that is called around the generated
HTML markup on displacy.render. This can be used to allow integration into
other platforms, similar to Jupyter Notebooks that require functions to be
called around the HTML. It can also be used to imple... | python | def set_render_wrapper(func):
"""Set an optional wrapper function that is called around the generated
HTML markup on displacy.render. This can be used to allow integration into
other platforms, similar to Jupyter Notebooks that require functions to be
called around the HTML. It can also be used to imple... | [
"def",
"set_render_wrapper",
"(",
"func",
")",
":",
"global",
"RENDER_WRAPPER",
"if",
"not",
"hasattr",
"(",
"func",
",",
"\"__call__\"",
")",
":",
"raise",
"ValueError",
"(",
"Errors",
".",
"E110",
".",
"format",
"(",
"obj",
"=",
"type",
"(",
"func",
")... | Set an optional wrapper function that is called around the generated
HTML markup on displacy.render. This can be used to allow integration into
other platforms, similar to Jupyter Notebooks that require functions to be
called around the HTML. It can also be used to implement custom callbacks
on render, ... | [
"Set",
"an",
"optional",
"wrapper",
"function",
"that",
"is",
"called",
"around",
"the",
"generated",
"HTML",
"markup",
"on",
"displacy",
".",
"render",
".",
"This",
"can",
"be",
"used",
"to",
"allow",
"integration",
"into",
"other",
"platforms",
"similar",
... | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/__init__.py#L185-L199 | train |
explosion/spaCy | spacy/cli/evaluate.py | evaluate | def evaluate(
model,
data_path,
gpu_id=-1,
gold_preproc=False,
displacy_path=None,
displacy_limit=25,
return_scores=False,
):
"""
Evaluate a model. To render a sample of parses in a HTML file, set an
output directory as the displacy_path argument.
"""
msg = Printer()
... | python | def evaluate(
model,
data_path,
gpu_id=-1,
gold_preproc=False,
displacy_path=None,
displacy_limit=25,
return_scores=False,
):
"""
Evaluate a model. To render a sample of parses in a HTML file, set an
output directory as the displacy_path argument.
"""
msg = Printer()
... | [
"def",
"evaluate",
"(",
"model",
",",
"data_path",
",",
"gpu_id",
"=",
"-",
"1",
",",
"gold_preproc",
"=",
"False",
",",
"displacy_path",
"=",
"None",
",",
"displacy_limit",
"=",
"25",
",",
"return_scores",
"=",
"False",
",",
")",
":",
"msg",
"=",
"Pri... | Evaluate a model. To render a sample of parses in a HTML file, set an
output directory as the displacy_path argument. | [
"Evaluate",
"a",
"model",
".",
"To",
"render",
"a",
"sample",
"of",
"parses",
"in",
"a",
"HTML",
"file",
"set",
"an",
"output",
"directory",
"as",
"the",
"displacy_path",
"argument",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/evaluate.py#L22-L81 | train |
explosion/spaCy | spacy/cli/link.py | link | def link(origin, link_name, force=False, model_path=None):
"""
Create a symlink for models within the spacy/data directory. Accepts
either the name of a pip package, or the local path to the model data
directory. Linking models allows loading them via spacy.load(link_name).
"""
msg = Printer()
... | python | def link(origin, link_name, force=False, model_path=None):
"""
Create a symlink for models within the spacy/data directory. Accepts
either the name of a pip package, or the local path to the model data
directory. Linking models allows loading them via spacy.load(link_name).
"""
msg = Printer()
... | [
"def",
"link",
"(",
"origin",
",",
"link_name",
",",
"force",
"=",
"False",
",",
"model_path",
"=",
"None",
")",
":",
"msg",
"=",
"Printer",
"(",
")",
"if",
"util",
".",
"is_package",
"(",
"origin",
")",
":",
"model_path",
"=",
"util",
".",
"get_pack... | Create a symlink for models within the spacy/data directory. Accepts
either the name of a pip package, or the local path to the model data
directory. Linking models allows loading them via spacy.load(link_name). | [
"Create",
"a",
"symlink",
"for",
"models",
"within",
"the",
"spacy",
"/",
"data",
"directory",
".",
"Accepts",
"either",
"the",
"name",
"of",
"a",
"pip",
"package",
"or",
"the",
"local",
"path",
"to",
"the",
"model",
"data",
"directory",
".",
"Linking",
... | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/link.py#L17-L78 | train |
explosion/spaCy | spacy/cli/validate.py | validate | def validate():
"""
Validate that the currently installed version of spaCy is compatible
with the installed models. Should be run after `pip install -U spacy`.
"""
msg = Printer()
with msg.loading("Loading compatibility table..."):
r = requests.get(about.__compatibility__)
if r.s... | python | def validate():
"""
Validate that the currently installed version of spaCy is compatible
with the installed models. Should be run after `pip install -U spacy`.
"""
msg = Printer()
with msg.loading("Loading compatibility table..."):
r = requests.get(about.__compatibility__)
if r.s... | [
"def",
"validate",
"(",
")",
":",
"msg",
"=",
"Printer",
"(",
")",
"with",
"msg",
".",
"loading",
"(",
"\"Loading compatibility table...\"",
")",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"about",
".",
"__compatibility__",
")",
"if",
"r",
".",
"status_... | Validate that the currently installed version of spaCy is compatible
with the installed models. Should be run after `pip install -U spacy`. | [
"Validate",
"that",
"the",
"currently",
"installed",
"version",
"of",
"spaCy",
"is",
"compatible",
"with",
"the",
"installed",
"models",
".",
"Should",
"be",
"run",
"after",
"pip",
"install",
"-",
"U",
"spacy",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/validate.py#L16-L88 | train |
explosion/spaCy | spacy/cli/profile.py | profile | def profile(model, inputs=None, n_texts=10000):
"""
Profile a spaCy pipeline, to find out which functions take the most time.
Input should be formatted as one JSON object per line with a key "text".
It can either be provided as a JSONL file, or be read from sys.sytdin.
If no input file is specified,... | python | def profile(model, inputs=None, n_texts=10000):
"""
Profile a spaCy pipeline, to find out which functions take the most time.
Input should be formatted as one JSON object per line with a key "text".
It can either be provided as a JSONL file, or be read from sys.sytdin.
If no input file is specified,... | [
"def",
"profile",
"(",
"model",
",",
"inputs",
"=",
"None",
",",
"n_texts",
"=",
"10000",
")",
":",
"msg",
"=",
"Printer",
"(",
")",
"if",
"inputs",
"is",
"not",
"None",
":",
"inputs",
"=",
"_read_inputs",
"(",
"inputs",
",",
"msg",
")",
"if",
"inp... | Profile a spaCy pipeline, to find out which functions take the most time.
Input should be formatted as one JSON object per line with a key "text".
It can either be provided as a JSONL file, or be read from sys.sytdin.
If no input file is specified, the IMDB dataset is loaded via Thinc. | [
"Profile",
"a",
"spaCy",
"pipeline",
"to",
"find",
"out",
"which",
"functions",
"take",
"the",
"most",
"time",
".",
"Input",
"should",
"be",
"formatted",
"as",
"one",
"JSON",
"object",
"per",
"line",
"with",
"a",
"key",
"text",
".",
"It",
"can",
"either"... | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/profile.py#L23-L47 | train |
explosion/spaCy | spacy/lang/ja/__init__.py | resolve_pos | def resolve_pos(token):
"""If necessary, add a field to the POS tag for UD mapping.
Under Universal Dependencies, sometimes the same Unidic POS tag can
be mapped differently depending on the literal token or its context
in the sentence. This function adds information to the POS tag to
resolve ambigu... | python | def resolve_pos(token):
"""If necessary, add a field to the POS tag for UD mapping.
Under Universal Dependencies, sometimes the same Unidic POS tag can
be mapped differently depending on the literal token or its context
in the sentence. This function adds information to the POS tag to
resolve ambigu... | [
"def",
"resolve_pos",
"(",
"token",
")",
":",
"# TODO: This is a first take. The rules here are crude approximations.",
"# For many of these, full dependencies are needed to properly resolve",
"# PoS mappings.",
"if",
"token",
".",
"pos",
"==",
"\"連体詞,*,*,*\":",
"",
"if",
"re",
"... | If necessary, add a field to the POS tag for UD mapping.
Under Universal Dependencies, sometimes the same Unidic POS tag can
be mapped differently depending on the literal token or its context
in the sentence. This function adds information to the POS tag to
resolve ambiguous mappings. | [
"If",
"necessary",
"add",
"a",
"field",
"to",
"the",
"POS",
"tag",
"for",
"UD",
"mapping",
".",
"Under",
"Universal",
"Dependencies",
"sometimes",
"the",
"same",
"Unidic",
"POS",
"tag",
"can",
"be",
"mapped",
"differently",
"depending",
"on",
"the",
"literal... | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/lang/ja/__init__.py#L33-L49 | train |
explosion/spaCy | spacy/lang/ja/__init__.py | detailed_tokens | def detailed_tokens(tokenizer, text):
"""Format Mecab output into a nice data structure, based on Janome."""
node = tokenizer.parseToNode(text)
node = node.next # first node is beginning of sentence and empty, skip it
words = []
while node.posid != 0:
surface = node.surface
base = s... | python | def detailed_tokens(tokenizer, text):
"""Format Mecab output into a nice data structure, based on Janome."""
node = tokenizer.parseToNode(text)
node = node.next # first node is beginning of sentence and empty, skip it
words = []
while node.posid != 0:
surface = node.surface
base = s... | [
"def",
"detailed_tokens",
"(",
"tokenizer",
",",
"text",
")",
":",
"node",
"=",
"tokenizer",
".",
"parseToNode",
"(",
"text",
")",
"node",
"=",
"node",
".",
"next",
"# first node is beginning of sentence and empty, skip it",
"words",
"=",
"[",
"]",
"while",
"nod... | Format Mecab output into a nice data structure, based on Janome. | [
"Format",
"Mecab",
"output",
"into",
"a",
"nice",
"data",
"structure",
"based",
"on",
"Janome",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/lang/ja/__init__.py#L52-L68 | train |
explosion/spaCy | spacy/compat.py | symlink_to | def symlink_to(orig, dest):
"""Create a symlink. Used for model shortcut links.
orig (unicode / Path): The origin path.
dest (unicode / Path): The destination path of the symlink.
"""
if is_windows:
import subprocess
subprocess.check_call(
["mklink", "/d", path2str(orig... | python | def symlink_to(orig, dest):
"""Create a symlink. Used for model shortcut links.
orig (unicode / Path): The origin path.
dest (unicode / Path): The destination path of the symlink.
"""
if is_windows:
import subprocess
subprocess.check_call(
["mklink", "/d", path2str(orig... | [
"def",
"symlink_to",
"(",
"orig",
",",
"dest",
")",
":",
"if",
"is_windows",
":",
"import",
"subprocess",
"subprocess",
".",
"check_call",
"(",
"[",
"\"mklink\"",
",",
"\"/d\"",
",",
"path2str",
"(",
"orig",
")",
",",
"path2str",
"(",
"dest",
")",
"]",
... | Create a symlink. Used for model shortcut links.
orig (unicode / Path): The origin path.
dest (unicode / Path): The destination path of the symlink. | [
"Create",
"a",
"symlink",
".",
"Used",
"for",
"model",
"shortcut",
"links",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/compat.py#L86-L99 | train |
explosion/spaCy | spacy/compat.py | symlink_remove | def symlink_remove(link):
"""Remove a symlink. Used for model shortcut links.
link (unicode / Path): The path to the symlink.
"""
# https://stackoverflow.com/q/26554135/6400719
if os.path.isdir(path2str(link)) and is_windows:
# this should only be on Py2.7 and windows
os.rmdir(path2... | python | def symlink_remove(link):
"""Remove a symlink. Used for model shortcut links.
link (unicode / Path): The path to the symlink.
"""
# https://stackoverflow.com/q/26554135/6400719
if os.path.isdir(path2str(link)) and is_windows:
# this should only be on Py2.7 and windows
os.rmdir(path2... | [
"def",
"symlink_remove",
"(",
"link",
")",
":",
"# https://stackoverflow.com/q/26554135/6400719",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path2str",
"(",
"link",
")",
")",
"and",
"is_windows",
":",
"# this should only be on Py2.7 and windows",
"os",
".",
"rmdir... | Remove a symlink. Used for model shortcut links.
link (unicode / Path): The path to the symlink. | [
"Remove",
"a",
"symlink",
".",
"Used",
"for",
"model",
"shortcut",
"links",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/compat.py#L102-L112 | train |
explosion/spaCy | spacy/compat.py | is_config | def is_config(python2=None, python3=None, windows=None, linux=None, osx=None):
"""Check if a specific configuration of Python version and operating system
matches the user's setup. Mostly used to display targeted error messages.
python2 (bool): spaCy is executed with Python 2.x.
python3 (bool): spaCy i... | python | def is_config(python2=None, python3=None, windows=None, linux=None, osx=None):
"""Check if a specific configuration of Python version and operating system
matches the user's setup. Mostly used to display targeted error messages.
python2 (bool): spaCy is executed with Python 2.x.
python3 (bool): spaCy i... | [
"def",
"is_config",
"(",
"python2",
"=",
"None",
",",
"python3",
"=",
"None",
",",
"windows",
"=",
"None",
",",
"linux",
"=",
"None",
",",
"osx",
"=",
"None",
")",
":",
"return",
"(",
"python2",
"in",
"(",
"None",
",",
"is_python2",
")",
"and",
"py... | Check if a specific configuration of Python version and operating system
matches the user's setup. Mostly used to display targeted error messages.
python2 (bool): spaCy is executed with Python 2.x.
python3 (bool): spaCy is executed with Python 3.x.
windows (bool): spaCy is executed on Windows.
linu... | [
"Check",
"if",
"a",
"specific",
"configuration",
"of",
"Python",
"version",
"and",
"operating",
"system",
"matches",
"the",
"user",
"s",
"setup",
".",
"Mostly",
"used",
"to",
"display",
"targeted",
"error",
"messages",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/compat.py#L115-L134 | train |
explosion/spaCy | spacy/compat.py | import_file | def import_file(name, loc):
"""Import module from a file. Used to load models from a directory.
name (unicode): Name of module to load.
loc (unicode / Path): Path to the file.
RETURNS: The loaded module.
"""
loc = path2str(loc)
if is_python_pre_3_5:
import imp
return imp.lo... | python | def import_file(name, loc):
"""Import module from a file. Used to load models from a directory.
name (unicode): Name of module to load.
loc (unicode / Path): Path to the file.
RETURNS: The loaded module.
"""
loc = path2str(loc)
if is_python_pre_3_5:
import imp
return imp.lo... | [
"def",
"import_file",
"(",
"name",
",",
"loc",
")",
":",
"loc",
"=",
"path2str",
"(",
"loc",
")",
"if",
"is_python_pre_3_5",
":",
"import",
"imp",
"return",
"imp",
".",
"load_source",
"(",
"name",
",",
"loc",
")",
"else",
":",
"import",
"importlib",
".... | Import module from a file. Used to load models from a directory.
name (unicode): Name of module to load.
loc (unicode / Path): Path to the file.
RETURNS: The loaded module. | [
"Import",
"module",
"from",
"a",
"file",
".",
"Used",
"to",
"load",
"models",
"from",
"a",
"directory",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/compat.py#L137-L155 | train |
explosion/spaCy | spacy/compat.py | unescape_unicode | def unescape_unicode(string):
"""Python2.7's re module chokes when compiling patterns that have ranges
between escaped unicode codepoints if the two codepoints are unrecognised
in the unicode database. For instance:
re.compile('[\\uAA77-\\uAA79]').findall("hello")
Ends up matching every charac... | python | def unescape_unicode(string):
"""Python2.7's re module chokes when compiling patterns that have ranges
between escaped unicode codepoints if the two codepoints are unrecognised
in the unicode database. For instance:
re.compile('[\\uAA77-\\uAA79]').findall("hello")
Ends up matching every charac... | [
"def",
"unescape_unicode",
"(",
"string",
")",
":",
"if",
"string",
"is",
"None",
":",
"return",
"string",
"# We only want to unescape the unicode, so we first must protect the other",
"# backslashes.",
"string",
"=",
"string",
".",
"replace",
"(",
"\"\\\\\"",
",",
"\"\... | Python2.7's re module chokes when compiling patterns that have ranges
between escaped unicode codepoints if the two codepoints are unrecognised
in the unicode database. For instance:
re.compile('[\\uAA77-\\uAA79]').findall("hello")
Ends up matching every character (on Python 2). This problem doesn... | [
"Python2",
".",
"7",
"s",
"re",
"module",
"chokes",
"when",
"compiling",
"patterns",
"that",
"have",
"ranges",
"between",
"escaped",
"unicode",
"codepoints",
"if",
"the",
"two",
"codepoints",
"are",
"unrecognised",
"in",
"the",
"unicode",
"database",
".",
"For... | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/compat.py#L158-L178 | train |
explosion/spaCy | spacy/util.py | get_lang_class | def get_lang_class(lang):
"""Import and load a Language class.
lang (unicode): Two-letter language code, e.g. 'en'.
RETURNS (Language): Language class.
"""
global LANGUAGES
# Check if an entry point is exposed for the language code
entry_point = get_entry_point("spacy_languages", lang)
... | python | def get_lang_class(lang):
"""Import and load a Language class.
lang (unicode): Two-letter language code, e.g. 'en'.
RETURNS (Language): Language class.
"""
global LANGUAGES
# Check if an entry point is exposed for the language code
entry_point = get_entry_point("spacy_languages", lang)
... | [
"def",
"get_lang_class",
"(",
"lang",
")",
":",
"global",
"LANGUAGES",
"# Check if an entry point is exposed for the language code",
"entry_point",
"=",
"get_entry_point",
"(",
"\"spacy_languages\"",
",",
"lang",
")",
"if",
"entry_point",
"is",
"not",
"None",
":",
"LANG... | Import and load a Language class.
lang (unicode): Two-letter language code, e.g. 'en'.
RETURNS (Language): Language class. | [
"Import",
"and",
"load",
"a",
"Language",
"class",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L53-L71 | train |
explosion/spaCy | spacy/util.py | load_model | def load_model(name, **overrides):
"""Load a model from a shortcut link, package or data path.
name (unicode): Package name, shortcut link or model path.
**overrides: Specific overrides, like pipeline components to disable.
RETURNS (Language): `Language` class with the loaded model.
"""
data_pa... | python | def load_model(name, **overrides):
"""Load a model from a shortcut link, package or data path.
name (unicode): Package name, shortcut link or model path.
**overrides: Specific overrides, like pipeline components to disable.
RETURNS (Language): `Language` class with the loaded model.
"""
data_pa... | [
"def",
"load_model",
"(",
"name",
",",
"*",
"*",
"overrides",
")",
":",
"data_path",
"=",
"get_data_path",
"(",
")",
"if",
"not",
"data_path",
"or",
"not",
"data_path",
".",
"exists",
"(",
")",
":",
"raise",
"IOError",
"(",
"Errors",
".",
"E049",
".",
... | Load a model from a shortcut link, package or data path.
name (unicode): Package name, shortcut link or model path.
**overrides: Specific overrides, like pipeline components to disable.
RETURNS (Language): `Language` class with the loaded model. | [
"Load",
"a",
"model",
"from",
"a",
"shortcut",
"link",
"package",
"or",
"data",
"path",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L117-L136 | train |
explosion/spaCy | spacy/util.py | load_model_from_link | def load_model_from_link(name, **overrides):
"""Load a model from a shortcut link, or directory in spaCy data path."""
path = get_data_path() / name / "__init__.py"
try:
cls = import_file(name, path)
except AttributeError:
raise IOError(Errors.E051.format(name=name))
return cls.load(... | python | def load_model_from_link(name, **overrides):
"""Load a model from a shortcut link, or directory in spaCy data path."""
path = get_data_path() / name / "__init__.py"
try:
cls = import_file(name, path)
except AttributeError:
raise IOError(Errors.E051.format(name=name))
return cls.load(... | [
"def",
"load_model_from_link",
"(",
"name",
",",
"*",
"*",
"overrides",
")",
":",
"path",
"=",
"get_data_path",
"(",
")",
"/",
"name",
"/",
"\"__init__.py\"",
"try",
":",
"cls",
"=",
"import_file",
"(",
"name",
",",
"path",
")",
"except",
"AttributeError",... | Load a model from a shortcut link, or directory in spaCy data path. | [
"Load",
"a",
"model",
"from",
"a",
"shortcut",
"link",
"or",
"directory",
"in",
"spaCy",
"data",
"path",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L139-L146 | train |
explosion/spaCy | spacy/util.py | load_model_from_package | def load_model_from_package(name, **overrides):
"""Load a model from an installed package."""
cls = importlib.import_module(name)
return cls.load(**overrides) | python | def load_model_from_package(name, **overrides):
"""Load a model from an installed package."""
cls = importlib.import_module(name)
return cls.load(**overrides) | [
"def",
"load_model_from_package",
"(",
"name",
",",
"*",
"*",
"overrides",
")",
":",
"cls",
"=",
"importlib",
".",
"import_module",
"(",
"name",
")",
"return",
"cls",
".",
"load",
"(",
"*",
"*",
"overrides",
")"
] | Load a model from an installed package. | [
"Load",
"a",
"model",
"from",
"an",
"installed",
"package",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L149-L152 | train |
explosion/spaCy | spacy/util.py | load_model_from_path | def load_model_from_path(model_path, meta=False, **overrides):
"""Load a model from a data directory path. Creates Language class with
pipeline from meta.json and then calls from_disk() with path."""
if not meta:
meta = get_model_meta(model_path)
cls = get_lang_class(meta["lang"])
nlp = cls(... | python | def load_model_from_path(model_path, meta=False, **overrides):
"""Load a model from a data directory path. Creates Language class with
pipeline from meta.json and then calls from_disk() with path."""
if not meta:
meta = get_model_meta(model_path)
cls = get_lang_class(meta["lang"])
nlp = cls(... | [
"def",
"load_model_from_path",
"(",
"model_path",
",",
"meta",
"=",
"False",
",",
"*",
"*",
"overrides",
")",
":",
"if",
"not",
"meta",
":",
"meta",
"=",
"get_model_meta",
"(",
"model_path",
")",
"cls",
"=",
"get_lang_class",
"(",
"meta",
"[",
"\"lang\"",
... | Load a model from a data directory path. Creates Language class with
pipeline from meta.json and then calls from_disk() with path. | [
"Load",
"a",
"model",
"from",
"a",
"data",
"directory",
"path",
".",
"Creates",
"Language",
"class",
"with",
"pipeline",
"from",
"meta",
".",
"json",
"and",
"then",
"calls",
"from_disk",
"()",
"with",
"path",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L155-L173 | train |
explosion/spaCy | spacy/util.py | load_model_from_init_py | def load_model_from_init_py(init_file, **overrides):
"""Helper function to use in the `load()` method of a model package's
__init__.py.
init_file (unicode): Path to model's __init__.py, i.e. `__file__`.
**overrides: Specific overrides, like pipeline components to disable.
RETURNS (Language): `Langu... | python | def load_model_from_init_py(init_file, **overrides):
"""Helper function to use in the `load()` method of a model package's
__init__.py.
init_file (unicode): Path to model's __init__.py, i.e. `__file__`.
**overrides: Specific overrides, like pipeline components to disable.
RETURNS (Language): `Langu... | [
"def",
"load_model_from_init_py",
"(",
"init_file",
",",
"*",
"*",
"overrides",
")",
":",
"model_path",
"=",
"Path",
"(",
"init_file",
")",
".",
"parent",
"meta",
"=",
"get_model_meta",
"(",
"model_path",
")",
"data_dir",
"=",
"\"%s_%s-%s\"",
"%",
"(",
"meta... | Helper function to use in the `load()` method of a model package's
__init__.py.
init_file (unicode): Path to model's __init__.py, i.e. `__file__`.
**overrides: Specific overrides, like pipeline components to disable.
RETURNS (Language): `Language` class with loaded model. | [
"Helper",
"function",
"to",
"use",
"in",
"the",
"load",
"()",
"method",
"of",
"a",
"model",
"package",
"s",
"__init__",
".",
"py",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L176-L190 | train |
explosion/spaCy | spacy/util.py | get_model_meta | def get_model_meta(path):
"""Get model meta.json from a directory path and validate its contents.
path (unicode or Path): Path to model directory.
RETURNS (dict): The model's meta data.
"""
model_path = ensure_path(path)
if not model_path.exists():
raise IOError(Errors.E052.format(path=... | python | def get_model_meta(path):
"""Get model meta.json from a directory path and validate its contents.
path (unicode or Path): Path to model directory.
RETURNS (dict): The model's meta data.
"""
model_path = ensure_path(path)
if not model_path.exists():
raise IOError(Errors.E052.format(path=... | [
"def",
"get_model_meta",
"(",
"path",
")",
":",
"model_path",
"=",
"ensure_path",
"(",
"path",
")",
"if",
"not",
"model_path",
".",
"exists",
"(",
")",
":",
"raise",
"IOError",
"(",
"Errors",
".",
"E052",
".",
"format",
"(",
"path",
"=",
"path2str",
"(... | Get model meta.json from a directory path and validate its contents.
path (unicode or Path): Path to model directory.
RETURNS (dict): The model's meta data. | [
"Get",
"model",
"meta",
".",
"json",
"from",
"a",
"directory",
"path",
"and",
"validate",
"its",
"contents",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L193-L209 | train |
explosion/spaCy | spacy/util.py | get_package_path | def get_package_path(name):
"""Get the path to an installed package.
name (unicode): Package name.
RETURNS (Path): Path to installed package.
"""
name = name.lower() # use lowercase version to be safe
# Here we're importing the module just to find it. This is worryingly
# indirect, but it'... | python | def get_package_path(name):
"""Get the path to an installed package.
name (unicode): Package name.
RETURNS (Path): Path to installed package.
"""
name = name.lower() # use lowercase version to be safe
# Here we're importing the module just to find it. This is worryingly
# indirect, but it'... | [
"def",
"get_package_path",
"(",
"name",
")",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"# use lowercase version to be safe",
"# Here we're importing the module just to find it. This is worryingly",
"# indirect, but it's otherwise very difficult to find the package.",
"pkg",
... | Get the path to an installed package.
name (unicode): Package name.
RETURNS (Path): Path to installed package. | [
"Get",
"the",
"path",
"to",
"an",
"installed",
"package",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L226-L236 | train |
explosion/spaCy | spacy/util.py | get_entry_points | def get_entry_points(key):
"""Get registered entry points from other packages for a given key, e.g.
'spacy_factories' and return them as a dictionary, keyed by name.
key (unicode): Entry point name.
RETURNS (dict): Entry points, keyed by name.
"""
result = {}
for entry_point in pkg_resource... | python | def get_entry_points(key):
"""Get registered entry points from other packages for a given key, e.g.
'spacy_factories' and return them as a dictionary, keyed by name.
key (unicode): Entry point name.
RETURNS (dict): Entry points, keyed by name.
"""
result = {}
for entry_point in pkg_resource... | [
"def",
"get_entry_points",
"(",
"key",
")",
":",
"result",
"=",
"{",
"}",
"for",
"entry_point",
"in",
"pkg_resources",
".",
"iter_entry_points",
"(",
"key",
")",
":",
"result",
"[",
"entry_point",
".",
"name",
"]",
"=",
"entry_point",
".",
"load",
"(",
"... | Get registered entry points from other packages for a given key, e.g.
'spacy_factories' and return them as a dictionary, keyed by name.
key (unicode): Entry point name.
RETURNS (dict): Entry points, keyed by name. | [
"Get",
"registered",
"entry",
"points",
"from",
"other",
"packages",
"for",
"a",
"given",
"key",
"e",
".",
"g",
".",
"spacy_factories",
"and",
"return",
"them",
"as",
"a",
"dictionary",
"keyed",
"by",
"name",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L239-L249 | train |
explosion/spaCy | spacy/util.py | get_entry_point | def get_entry_point(key, value):
"""Check if registered entry point is available for a given name and
load it. Otherwise, return None.
key (unicode): Entry point name.
value (unicode): Name of entry point to load.
RETURNS: The loaded entry point or None.
"""
for entry_point in pkg_resources... | python | def get_entry_point(key, value):
"""Check if registered entry point is available for a given name and
load it. Otherwise, return None.
key (unicode): Entry point name.
value (unicode): Name of entry point to load.
RETURNS: The loaded entry point or None.
"""
for entry_point in pkg_resources... | [
"def",
"get_entry_point",
"(",
"key",
",",
"value",
")",
":",
"for",
"entry_point",
"in",
"pkg_resources",
".",
"iter_entry_points",
"(",
"key",
")",
":",
"if",
"entry_point",
".",
"name",
"==",
"value",
":",
"return",
"entry_point",
".",
"load",
"(",
")"
... | Check if registered entry point is available for a given name and
load it. Otherwise, return None.
key (unicode): Entry point name.
value (unicode): Name of entry point to load.
RETURNS: The loaded entry point or None. | [
"Check",
"if",
"registered",
"entry",
"point",
"is",
"available",
"for",
"a",
"given",
"name",
"and",
"load",
"it",
".",
"Otherwise",
"return",
"None",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L252-L262 | train |
explosion/spaCy | spacy/util.py | is_in_jupyter | def is_in_jupyter():
"""Check if user is running spaCy from a Jupyter notebook by detecting the
IPython kernel. Mainly used for the displaCy visualizer.
RETURNS (bool): True if in Jupyter, False if not.
"""
# https://stackoverflow.com/a/39662359/6400719
try:
shell = get_ipython().__class... | python | def is_in_jupyter():
"""Check if user is running spaCy from a Jupyter notebook by detecting the
IPython kernel. Mainly used for the displaCy visualizer.
RETURNS (bool): True if in Jupyter, False if not.
"""
# https://stackoverflow.com/a/39662359/6400719
try:
shell = get_ipython().__class... | [
"def",
"is_in_jupyter",
"(",
")",
":",
"# https://stackoverflow.com/a/39662359/6400719",
"try",
":",
"shell",
"=",
"get_ipython",
"(",
")",
".",
"__class__",
".",
"__name__",
"if",
"shell",
"==",
"\"ZMQInteractiveShell\"",
":",
"return",
"True",
"# Jupyter notebook or... | Check if user is running spaCy from a Jupyter notebook by detecting the
IPython kernel. Mainly used for the displaCy visualizer.
RETURNS (bool): True if in Jupyter, False if not. | [
"Check",
"if",
"user",
"is",
"running",
"spaCy",
"from",
"a",
"Jupyter",
"notebook",
"by",
"detecting",
"the",
"IPython",
"kernel",
".",
"Mainly",
"used",
"for",
"the",
"displaCy",
"visualizer",
".",
"RETURNS",
"(",
"bool",
")",
":",
"True",
"if",
"in",
... | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L265-L277 | train |
explosion/spaCy | spacy/util.py | compile_suffix_regex | def compile_suffix_regex(entries):
"""Compile a sequence of suffix rules into a regex object.
entries (tuple): The suffix rules, e.g. spacy.lang.punctuation.TOKENIZER_SUFFIXES.
RETURNS (regex object): The regex object. to be used for Tokenizer.suffix_search.
"""
expression = "|".join([piece + "$" f... | python | def compile_suffix_regex(entries):
"""Compile a sequence of suffix rules into a regex object.
entries (tuple): The suffix rules, e.g. spacy.lang.punctuation.TOKENIZER_SUFFIXES.
RETURNS (regex object): The regex object. to be used for Tokenizer.suffix_search.
"""
expression = "|".join([piece + "$" f... | [
"def",
"compile_suffix_regex",
"(",
"entries",
")",
":",
"expression",
"=",
"\"|\"",
".",
"join",
"(",
"[",
"piece",
"+",
"\"$\"",
"for",
"piece",
"in",
"entries",
"if",
"piece",
".",
"strip",
"(",
")",
"]",
")",
"return",
"re",
".",
"compile",
"(",
... | Compile a sequence of suffix rules into a regex object.
entries (tuple): The suffix rules, e.g. spacy.lang.punctuation.TOKENIZER_SUFFIXES.
RETURNS (regex object): The regex object. to be used for Tokenizer.suffix_search. | [
"Compile",
"a",
"sequence",
"of",
"suffix",
"rules",
"into",
"a",
"regex",
"object",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L346-L353 | train |
explosion/spaCy | spacy/util.py | compile_infix_regex | def compile_infix_regex(entries):
"""Compile a sequence of infix rules into a regex object.
entries (tuple): The infix rules, e.g. spacy.lang.punctuation.TOKENIZER_INFIXES.
RETURNS (regex object): The regex object. to be used for Tokenizer.infix_finditer.
"""
expression = "|".join([piece for piece ... | python | def compile_infix_regex(entries):
"""Compile a sequence of infix rules into a regex object.
entries (tuple): The infix rules, e.g. spacy.lang.punctuation.TOKENIZER_INFIXES.
RETURNS (regex object): The regex object. to be used for Tokenizer.infix_finditer.
"""
expression = "|".join([piece for piece ... | [
"def",
"compile_infix_regex",
"(",
"entries",
")",
":",
"expression",
"=",
"\"|\"",
".",
"join",
"(",
"[",
"piece",
"for",
"piece",
"in",
"entries",
"if",
"piece",
".",
"strip",
"(",
")",
"]",
")",
"return",
"re",
".",
"compile",
"(",
"expression",
")"... | Compile a sequence of infix rules into a regex object.
entries (tuple): The infix rules, e.g. spacy.lang.punctuation.TOKENIZER_INFIXES.
RETURNS (regex object): The regex object. to be used for Tokenizer.infix_finditer. | [
"Compile",
"a",
"sequence",
"of",
"infix",
"rules",
"into",
"a",
"regex",
"object",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L356-L363 | train |
explosion/spaCy | spacy/util.py | update_exc | def update_exc(base_exceptions, *addition_dicts):
"""Update and validate tokenizer exceptions. Will overwrite exceptions.
base_exceptions (dict): Base exceptions.
*addition_dicts (dict): Exceptions to add to the base dict, in order.
RETURNS (dict): Combined tokenizer exceptions.
"""
exc = dict(... | python | def update_exc(base_exceptions, *addition_dicts):
"""Update and validate tokenizer exceptions. Will overwrite exceptions.
base_exceptions (dict): Base exceptions.
*addition_dicts (dict): Exceptions to add to the base dict, in order.
RETURNS (dict): Combined tokenizer exceptions.
"""
exc = dict(... | [
"def",
"update_exc",
"(",
"base_exceptions",
",",
"*",
"addition_dicts",
")",
":",
"exc",
"=",
"dict",
"(",
"base_exceptions",
")",
"for",
"additions",
"in",
"addition_dicts",
":",
"for",
"orth",
",",
"token_attrs",
"in",
"additions",
".",
"items",
"(",
")",... | Update and validate tokenizer exceptions. Will overwrite exceptions.
base_exceptions (dict): Base exceptions.
*addition_dicts (dict): Exceptions to add to the base dict, in order.
RETURNS (dict): Combined tokenizer exceptions. | [
"Update",
"and",
"validate",
"tokenizer",
"exceptions",
".",
"Will",
"overwrite",
"exceptions",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L386-L403 | train |
explosion/spaCy | spacy/util.py | expand_exc | def expand_exc(excs, search, replace):
"""Find string in tokenizer exceptions, duplicate entry and replace string.
For example, to add additional versions with typographic apostrophes.
excs (dict): Tokenizer exceptions.
search (unicode): String to find and replace.
replace (unicode): Replacement.
... | python | def expand_exc(excs, search, replace):
"""Find string in tokenizer exceptions, duplicate entry and replace string.
For example, to add additional versions with typographic apostrophes.
excs (dict): Tokenizer exceptions.
search (unicode): String to find and replace.
replace (unicode): Replacement.
... | [
"def",
"expand_exc",
"(",
"excs",
",",
"search",
",",
"replace",
")",
":",
"def",
"_fix_token",
"(",
"token",
",",
"search",
",",
"replace",
")",
":",
"fixed",
"=",
"dict",
"(",
"token",
")",
"fixed",
"[",
"ORTH",
"]",
"=",
"fixed",
"[",
"ORTH",
"]... | Find string in tokenizer exceptions, duplicate entry and replace string.
For example, to add additional versions with typographic apostrophes.
excs (dict): Tokenizer exceptions.
search (unicode): String to find and replace.
replace (unicode): Replacement.
RETURNS (dict): Combined tokenizer exceptio... | [
"Find",
"string",
"in",
"tokenizer",
"exceptions",
"duplicate",
"entry",
"and",
"replace",
"string",
".",
"For",
"example",
"to",
"add",
"additional",
"versions",
"with",
"typographic",
"apostrophes",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L406-L427 | train |
explosion/spaCy | spacy/util.py | minibatch | def minibatch(items, size=8):
"""Iterate over batches of items. `size` may be an iterator,
so that batch-size can vary on each step.
"""
if isinstance(size, int):
size_ = itertools.repeat(size)
else:
size_ = size
items = iter(items)
while True:
batch_size = next(size_... | python | def minibatch(items, size=8):
"""Iterate over batches of items. `size` may be an iterator,
so that batch-size can vary on each step.
"""
if isinstance(size, int):
size_ = itertools.repeat(size)
else:
size_ = size
items = iter(items)
while True:
batch_size = next(size_... | [
"def",
"minibatch",
"(",
"items",
",",
"size",
"=",
"8",
")",
":",
"if",
"isinstance",
"(",
"size",
",",
"int",
")",
":",
"size_",
"=",
"itertools",
".",
"repeat",
"(",
"size",
")",
"else",
":",
"size_",
"=",
"size",
"items",
"=",
"iter",
"(",
"i... | Iterate over batches of items. `size` may be an iterator,
so that batch-size can vary on each step. | [
"Iterate",
"over",
"batches",
"of",
"items",
".",
"size",
"may",
"be",
"an",
"iterator",
"so",
"that",
"batch",
"-",
"size",
"can",
"vary",
"on",
"each",
"step",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L446-L460 | train |
explosion/spaCy | spacy/util.py | compounding | def compounding(start, stop, compound):
"""Yield an infinite series of compounding values. Each time the
generator is called, a value is produced by multiplying the previous
value by the compound rate.
EXAMPLE:
>>> sizes = compounding(1., 10., 1.5)
>>> assert next(sizes) == 1.
>>> ass... | python | def compounding(start, stop, compound):
"""Yield an infinite series of compounding values. Each time the
generator is called, a value is produced by multiplying the previous
value by the compound rate.
EXAMPLE:
>>> sizes = compounding(1., 10., 1.5)
>>> assert next(sizes) == 1.
>>> ass... | [
"def",
"compounding",
"(",
"start",
",",
"stop",
",",
"compound",
")",
":",
"def",
"clip",
"(",
"value",
")",
":",
"return",
"max",
"(",
"value",
",",
"stop",
")",
"if",
"(",
"start",
">",
"stop",
")",
"else",
"min",
"(",
"value",
",",
"stop",
")... | Yield an infinite series of compounding values. Each time the
generator is called, a value is produced by multiplying the previous
value by the compound rate.
EXAMPLE:
>>> sizes = compounding(1., 10., 1.5)
>>> assert next(sizes) == 1.
>>> assert next(sizes) == 1 * 1.5
>>> assert nex... | [
"Yield",
"an",
"infinite",
"series",
"of",
"compounding",
"values",
".",
"Each",
"time",
"the",
"generator",
"is",
"called",
"a",
"value",
"is",
"produced",
"by",
"multiplying",
"the",
"previous",
"value",
"by",
"the",
"compound",
"rate",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L463-L481 | train |
explosion/spaCy | spacy/util.py | stepping | def stepping(start, stop, steps):
"""Yield an infinite series of values that step from a start value to a
final value over some number of steps. Each step is (stop-start)/steps.
After the final value is reached, the generator continues yielding that
value.
EXAMPLE:
>>> sizes = stepping(1., 2... | python | def stepping(start, stop, steps):
"""Yield an infinite series of values that step from a start value to a
final value over some number of steps. Each step is (stop-start)/steps.
After the final value is reached, the generator continues yielding that
value.
EXAMPLE:
>>> sizes = stepping(1., 2... | [
"def",
"stepping",
"(",
"start",
",",
"stop",
",",
"steps",
")",
":",
"def",
"clip",
"(",
"value",
")",
":",
"return",
"max",
"(",
"value",
",",
"stop",
")",
"if",
"(",
"start",
">",
"stop",
")",
"else",
"min",
"(",
"value",
",",
"stop",
")",
"... | Yield an infinite series of values that step from a start value to a
final value over some number of steps. Each step is (stop-start)/steps.
After the final value is reached, the generator continues yielding that
value.
EXAMPLE:
>>> sizes = stepping(1., 200., 100)
>>> assert next(sizes) ==... | [
"Yield",
"an",
"infinite",
"series",
"of",
"values",
"that",
"step",
"from",
"a",
"start",
"value",
"to",
"a",
"final",
"value",
"over",
"some",
"number",
"of",
"steps",
".",
"Each",
"step",
"is",
"(",
"stop",
"-",
"start",
")",
"/",
"steps",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L484-L504 | train |
explosion/spaCy | spacy/util.py | decaying | def decaying(start, stop, decay):
"""Yield an infinite series of linearly decaying values."""
curr = float(start)
while True:
yield max(curr, stop)
curr -= (decay) | python | def decaying(start, stop, decay):
"""Yield an infinite series of linearly decaying values."""
curr = float(start)
while True:
yield max(curr, stop)
curr -= (decay) | [
"def",
"decaying",
"(",
"start",
",",
"stop",
",",
"decay",
")",
":",
"curr",
"=",
"float",
"(",
"start",
")",
"while",
"True",
":",
"yield",
"max",
"(",
"curr",
",",
"stop",
")",
"curr",
"-=",
"(",
"decay",
")"
] | Yield an infinite series of linearly decaying values. | [
"Yield",
"an",
"infinite",
"series",
"of",
"linearly",
"decaying",
"values",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L507-L513 | train |
explosion/spaCy | spacy/util.py | minibatch_by_words | def minibatch_by_words(items, size, tuples=True, count_words=len):
"""Create minibatches of a given number of words."""
if isinstance(size, int):
size_ = itertools.repeat(size)
else:
size_ = size
items = iter(items)
while True:
batch_size = next(size_)
batch = []
... | python | def minibatch_by_words(items, size, tuples=True, count_words=len):
"""Create minibatches of a given number of words."""
if isinstance(size, int):
size_ = itertools.repeat(size)
else:
size_ = size
items = iter(items)
while True:
batch_size = next(size_)
batch = []
... | [
"def",
"minibatch_by_words",
"(",
"items",
",",
"size",
",",
"tuples",
"=",
"True",
",",
"count_words",
"=",
"len",
")",
":",
"if",
"isinstance",
"(",
"size",
",",
"int",
")",
":",
"size_",
"=",
"itertools",
".",
"repeat",
"(",
"size",
")",
"else",
"... | Create minibatches of a given number of words. | [
"Create",
"minibatches",
"of",
"a",
"given",
"number",
"of",
"words",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L516-L542 | train |
explosion/spaCy | spacy/util.py | itershuffle | def itershuffle(iterable, bufsize=1000):
"""Shuffle an iterator. This works by holding `bufsize` items back
and yielding them sometime later. Obviously, this is not unbiased –
but should be good enough for batching. Larger bufsize means less bias.
From https://gist.github.com/andres-erbsen/1307752
... | python | def itershuffle(iterable, bufsize=1000):
"""Shuffle an iterator. This works by holding `bufsize` items back
and yielding them sometime later. Obviously, this is not unbiased –
but should be good enough for batching. Larger bufsize means less bias.
From https://gist.github.com/andres-erbsen/1307752
... | [
"def",
"itershuffle",
"(",
"iterable",
",",
"bufsize",
"=",
"1000",
")",
":",
"iterable",
"=",
"iter",
"(",
"iterable",
")",
"buf",
"=",
"[",
"]",
"try",
":",
"while",
"True",
":",
"for",
"i",
"in",
"range",
"(",
"random",
".",
"randint",
"(",
"1",... | Shuffle an iterator. This works by holding `bufsize` items back
and yielding them sometime later. Obviously, this is not unbiased –
but should be good enough for batching. Larger bufsize means less bias.
From https://gist.github.com/andres-erbsen/1307752
iterable (iterable): Iterator to shuffle.
bu... | [
"Shuffle",
"an",
"iterator",
".",
"This",
"works",
"by",
"holding",
"bufsize",
"items",
"back",
"and",
"yielding",
"them",
"sometime",
"later",
".",
"Obviously",
"this",
"is",
"not",
"unbiased",
"–",
"but",
"should",
"be",
"good",
"enough",
"for",
"batching"... | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L545-L571 | train |
explosion/spaCy | spacy/util.py | validate_json | def validate_json(data, validator):
"""Validate data against a given JSON schema (see https://json-schema.org).
data: JSON-serializable data to validate.
validator (jsonschema.DraftXValidator): The validator.
RETURNS (list): A list of error messages, if available.
"""
errors = []
for err in... | python | def validate_json(data, validator):
"""Validate data against a given JSON schema (see https://json-schema.org).
data: JSON-serializable data to validate.
validator (jsonschema.DraftXValidator): The validator.
RETURNS (list): A list of error messages, if available.
"""
errors = []
for err in... | [
"def",
"validate_json",
"(",
"data",
",",
"validator",
")",
":",
"errors",
"=",
"[",
"]",
"for",
"err",
"in",
"sorted",
"(",
"validator",
".",
"iter_errors",
"(",
"data",
")",
",",
"key",
"=",
"lambda",
"e",
":",
"e",
".",
"path",
")",
":",
"if",
... | Validate data against a given JSON schema (see https://json-schema.org).
data: JSON-serializable data to validate.
validator (jsonschema.DraftXValidator): The validator.
RETURNS (list): A list of error messages, if available. | [
"Validate",
"data",
"against",
"a",
"given",
"JSON",
"schema",
"(",
"see",
"https",
":",
"//",
"json",
"-",
"schema",
".",
"org",
")",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L672-L690 | train |
explosion/spaCy | spacy/util.py | get_serialization_exclude | def get_serialization_exclude(serializers, exclude, kwargs):
"""Helper function to validate serialization args and manage transition from
keyword arguments (pre v2.1) to exclude argument.
"""
exclude = list(exclude)
# Split to support file names like meta.json
options = [name.split(".")[0] for n... | python | def get_serialization_exclude(serializers, exclude, kwargs):
"""Helper function to validate serialization args and manage transition from
keyword arguments (pre v2.1) to exclude argument.
"""
exclude = list(exclude)
# Split to support file names like meta.json
options = [name.split(".")[0] for n... | [
"def",
"get_serialization_exclude",
"(",
"serializers",
",",
"exclude",
",",
"kwargs",
")",
":",
"exclude",
"=",
"list",
"(",
"exclude",
")",
"# Split to support file names like meta.json",
"options",
"=",
"[",
"name",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
... | Helper function to validate serialization args and manage transition from
keyword arguments (pre v2.1) to exclude argument. | [
"Helper",
"function",
"to",
"validate",
"serialization",
"args",
"and",
"manage",
"transition",
"from",
"keyword",
"arguments",
"(",
"pre",
"v2",
".",
"1",
")",
"to",
"exclude",
"argument",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L693-L707 | train |
explosion/spaCy | spacy/pipeline/entityruler.py | EntityRuler.labels | def labels(self):
"""All labels present in the match patterns.
RETURNS (set): The string labels.
DOCS: https://spacy.io/api/entityruler#labels
"""
all_labels = set(self.token_patterns.keys())
all_labels.update(self.phrase_patterns.keys())
return tuple(all_labels... | python | def labels(self):
"""All labels present in the match patterns.
RETURNS (set): The string labels.
DOCS: https://spacy.io/api/entityruler#labels
"""
all_labels = set(self.token_patterns.keys())
all_labels.update(self.phrase_patterns.keys())
return tuple(all_labels... | [
"def",
"labels",
"(",
"self",
")",
":",
"all_labels",
"=",
"set",
"(",
"self",
".",
"token_patterns",
".",
"keys",
"(",
")",
")",
"all_labels",
".",
"update",
"(",
"self",
".",
"phrase_patterns",
".",
"keys",
"(",
")",
")",
"return",
"tuple",
"(",
"a... | All labels present in the match patterns.
RETURNS (set): The string labels.
DOCS: https://spacy.io/api/entityruler#labels | [
"All",
"labels",
"present",
"in",
"the",
"match",
"patterns",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/pipeline/entityruler.py#L96-L105 | train |
explosion/spaCy | spacy/pipeline/entityruler.py | EntityRuler.patterns | def patterns(self):
"""Get all patterns that were added to the entity ruler.
RETURNS (list): The original patterns, one dictionary per pattern.
DOCS: https://spacy.io/api/entityruler#patterns
"""
all_patterns = []
for label, patterns in self.token_patterns.items():
... | python | def patterns(self):
"""Get all patterns that were added to the entity ruler.
RETURNS (list): The original patterns, one dictionary per pattern.
DOCS: https://spacy.io/api/entityruler#patterns
"""
all_patterns = []
for label, patterns in self.token_patterns.items():
... | [
"def",
"patterns",
"(",
"self",
")",
":",
"all_patterns",
"=",
"[",
"]",
"for",
"label",
",",
"patterns",
"in",
"self",
".",
"token_patterns",
".",
"items",
"(",
")",
":",
"for",
"pattern",
"in",
"patterns",
":",
"all_patterns",
".",
"append",
"(",
"{"... | Get all patterns that were added to the entity ruler.
RETURNS (list): The original patterns, one dictionary per pattern.
DOCS: https://spacy.io/api/entityruler#patterns | [
"Get",
"all",
"patterns",
"that",
"were",
"added",
"to",
"the",
"entity",
"ruler",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/pipeline/entityruler.py#L108-L122 | train |
explosion/spaCy | spacy/pipeline/entityruler.py | EntityRuler.add_patterns | def add_patterns(self, patterns):
"""Add patterns to the entitiy ruler. A pattern can either be a token
pattern (list of dicts) or a phrase pattern (string). For example:
{'label': 'ORG', 'pattern': 'Apple'}
{'label': 'GPE', 'pattern': [{'lower': 'san'}, {'lower': 'francisco'}]}
... | python | def add_patterns(self, patterns):
"""Add patterns to the entitiy ruler. A pattern can either be a token
pattern (list of dicts) or a phrase pattern (string). For example:
{'label': 'ORG', 'pattern': 'Apple'}
{'label': 'GPE', 'pattern': [{'lower': 'san'}, {'lower': 'francisco'}]}
... | [
"def",
"add_patterns",
"(",
"self",
",",
"patterns",
")",
":",
"for",
"entry",
"in",
"patterns",
":",
"label",
"=",
"entry",
"[",
"\"label\"",
"]",
"pattern",
"=",
"entry",
"[",
"\"pattern\"",
"]",
"if",
"isinstance",
"(",
"pattern",
",",
"basestring_",
... | Add patterns to the entitiy ruler. A pattern can either be a token
pattern (list of dicts) or a phrase pattern (string). For example:
{'label': 'ORG', 'pattern': 'Apple'}
{'label': 'GPE', 'pattern': [{'lower': 'san'}, {'lower': 'francisco'}]}
patterns (list): The patterns to add.
... | [
"Add",
"patterns",
"to",
"the",
"entitiy",
"ruler",
".",
"A",
"pattern",
"can",
"either",
"be",
"a",
"token",
"pattern",
"(",
"list",
"of",
"dicts",
")",
"or",
"a",
"phrase",
"pattern",
"(",
"string",
")",
".",
"For",
"example",
":",
"{",
"label",
":... | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/pipeline/entityruler.py#L124-L146 | train |
explosion/spaCy | spacy/pipeline/entityruler.py | EntityRuler.from_bytes | def from_bytes(self, patterns_bytes, **kwargs):
"""Load the entity ruler from a bytestring.
patterns_bytes (bytes): The bytestring to load.
**kwargs: Other config paramters, mostly for consistency.
RETURNS (EntityRuler): The loaded entity ruler.
DOCS: https://spacy.io/api/entit... | python | def from_bytes(self, patterns_bytes, **kwargs):
"""Load the entity ruler from a bytestring.
patterns_bytes (bytes): The bytestring to load.
**kwargs: Other config paramters, mostly for consistency.
RETURNS (EntityRuler): The loaded entity ruler.
DOCS: https://spacy.io/api/entit... | [
"def",
"from_bytes",
"(",
"self",
",",
"patterns_bytes",
",",
"*",
"*",
"kwargs",
")",
":",
"patterns",
"=",
"srsly",
".",
"msgpack_loads",
"(",
"patterns_bytes",
")",
"self",
".",
"add_patterns",
"(",
"patterns",
")",
"return",
"self"
] | Load the entity ruler from a bytestring.
patterns_bytes (bytes): The bytestring to load.
**kwargs: Other config paramters, mostly for consistency.
RETURNS (EntityRuler): The loaded entity ruler.
DOCS: https://spacy.io/api/entityruler#from_bytes | [
"Load",
"the",
"entity",
"ruler",
"from",
"a",
"bytestring",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/pipeline/entityruler.py#L148-L159 | train |
explosion/spaCy | spacy/pipeline/entityruler.py | EntityRuler.from_disk | def from_disk(self, path, **kwargs):
"""Load the entity ruler from a file. Expects a file containing
newline-delimited JSON (JSONL) with one entry per line.
path (unicode / Path): The JSONL file to load.
**kwargs: Other config paramters, mostly for consistency.
RETURNS (EntityRu... | python | def from_disk(self, path, **kwargs):
"""Load the entity ruler from a file. Expects a file containing
newline-delimited JSON (JSONL) with one entry per line.
path (unicode / Path): The JSONL file to load.
**kwargs: Other config paramters, mostly for consistency.
RETURNS (EntityRu... | [
"def",
"from_disk",
"(",
"self",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"ensure_path",
"(",
"path",
")",
"path",
"=",
"path",
".",
"with_suffix",
"(",
"\".jsonl\"",
")",
"patterns",
"=",
"srsly",
".",
"read_jsonl",
"(",
"path",
... | Load the entity ruler from a file. Expects a file containing
newline-delimited JSON (JSONL) with one entry per line.
path (unicode / Path): The JSONL file to load.
**kwargs: Other config paramters, mostly for consistency.
RETURNS (EntityRuler): The loaded entity ruler.
DOCS: ht... | [
"Load",
"the",
"entity",
"ruler",
"from",
"a",
"file",
".",
"Expects",
"a",
"file",
"containing",
"newline",
"-",
"delimited",
"JSON",
"(",
"JSONL",
")",
"with",
"one",
"entry",
"per",
"line",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/pipeline/entityruler.py#L170-L184 | train |
explosion/spaCy | spacy/pipeline/entityruler.py | EntityRuler.to_disk | def to_disk(self, path, **kwargs):
"""Save the entity ruler patterns to a directory. The patterns will be
saved as newline-delimited JSON (JSONL).
path (unicode / Path): The JSONL file to load.
**kwargs: Other config paramters, mostly for consistency.
RETURNS (EntityRuler): The ... | python | def to_disk(self, path, **kwargs):
"""Save the entity ruler patterns to a directory. The patterns will be
saved as newline-delimited JSON (JSONL).
path (unicode / Path): The JSONL file to load.
**kwargs: Other config paramters, mostly for consistency.
RETURNS (EntityRuler): The ... | [
"def",
"to_disk",
"(",
"self",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"ensure_path",
"(",
"path",
")",
"path",
"=",
"path",
".",
"with_suffix",
"(",
"\".jsonl\"",
")",
"srsly",
".",
"write_jsonl",
"(",
"path",
",",
"self",
".",
... | Save the entity ruler patterns to a directory. The patterns will be
saved as newline-delimited JSON (JSONL).
path (unicode / Path): The JSONL file to load.
**kwargs: Other config paramters, mostly for consistency.
RETURNS (EntityRuler): The loaded entity ruler.
DOCS: https://sp... | [
"Save",
"the",
"entity",
"ruler",
"patterns",
"to",
"a",
"directory",
".",
"The",
"patterns",
"will",
"be",
"saved",
"as",
"newline",
"-",
"delimited",
"JSON",
"(",
"JSONL",
")",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/pipeline/entityruler.py#L186-L198 | train |
explosion/spaCy | bin/ud/ud_train.py | read_data | def read_data(
nlp,
conllu_file,
text_file,
raw_text=True,
oracle_segments=False,
max_doc_length=None,
limit=None,
):
"""Read the CONLLU format into (Doc, GoldParse) tuples. If raw_text=True,
include Doc objects created using nlp.make_doc and then aligned against
the gold-standar... | python | def read_data(
nlp,
conllu_file,
text_file,
raw_text=True,
oracle_segments=False,
max_doc_length=None,
limit=None,
):
"""Read the CONLLU format into (Doc, GoldParse) tuples. If raw_text=True,
include Doc objects created using nlp.make_doc and then aligned against
the gold-standar... | [
"def",
"read_data",
"(",
"nlp",
",",
"conllu_file",
",",
"text_file",
",",
"raw_text",
"=",
"True",
",",
"oracle_segments",
"=",
"False",
",",
"max_doc_length",
"=",
"None",
",",
"limit",
"=",
"None",
",",
")",
":",
"if",
"not",
"raw_text",
"and",
"not",... | Read the CONLLU format into (Doc, GoldParse) tuples. If raw_text=True,
include Doc objects created using nlp.make_doc and then aligned against
the gold-standard sequences. If oracle_segments=True, include Doc objects
created from the gold-standard segments. At least one must be True. | [
"Read",
"the",
"CONLLU",
"format",
"into",
"(",
"Doc",
"GoldParse",
")",
"tuples",
".",
"If",
"raw_text",
"=",
"True",
"include",
"Doc",
"objects",
"created",
"using",
"nlp",
".",
"make_doc",
"and",
"then",
"aligned",
"against",
"the",
"gold",
"-",
"standa... | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/bin/ud/ud_train.py#L52-L110 | train |
explosion/spaCy | bin/ud/ud_train.py | golds_to_gold_tuples | def golds_to_gold_tuples(docs, golds):
"""Get out the annoying 'tuples' format used by begin_training, given the
GoldParse objects."""
tuples = []
for doc, gold in zip(docs, golds):
text = doc.text
ids, words, tags, heads, labels, iob = zip(*gold.orig_annot)
sents = [((ids, words... | python | def golds_to_gold_tuples(docs, golds):
"""Get out the annoying 'tuples' format used by begin_training, given the
GoldParse objects."""
tuples = []
for doc, gold in zip(docs, golds):
text = doc.text
ids, words, tags, heads, labels, iob = zip(*gold.orig_annot)
sents = [((ids, words... | [
"def",
"golds_to_gold_tuples",
"(",
"docs",
",",
"golds",
")",
":",
"tuples",
"=",
"[",
"]",
"for",
"doc",
",",
"gold",
"in",
"zip",
"(",
"docs",
",",
"golds",
")",
":",
"text",
"=",
"doc",
".",
"text",
"ids",
",",
"words",
",",
"tags",
",",
"hea... | Get out the annoying 'tuples' format used by begin_training, given the
GoldParse objects. | [
"Get",
"out",
"the",
"annoying",
"tuples",
"format",
"used",
"by",
"begin_training",
"given",
"the",
"GoldParse",
"objects",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/bin/ud/ud_train.py#L173-L182 | train |
explosion/spaCy | spacy/lang/fa/lex_attrs.py | like_num | def like_num(text):
"""
check if text resembles a number
"""
text = (
text.replace(",", "")
.replace(".", "")
.replace("،", "")
.replace("٫", "")
.replace("/", "")
)
if text.isdigit():
return True
if text in _num_words:
return True
... | python | def like_num(text):
"""
check if text resembles a number
"""
text = (
text.replace(",", "")
.replace(".", "")
.replace("،", "")
.replace("٫", "")
.replace("/", "")
)
if text.isdigit():
return True
if text in _num_words:
return True
... | [
"def",
"like_num",
"(",
"text",
")",
":",
"text",
"=",
"(",
"text",
".",
"replace",
"(",
"\",\"",
",",
"\"\"",
")",
".",
"replace",
"(",
"\".\"",
",",
"\"\"",
")",
".",
"replace",
"(",
"\"،\",",
" ",
"\")",
"",
".",
"replace",
"(",
"\"٫\",",
" ",... | check if text resembles a number | [
"check",
"if",
"text",
"resembles",
"a",
"number"
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/lang/fa/lex_attrs.py#L84-L101 | train |
explosion/spaCy | spacy/tokens/_serialize.py | merge_bytes | def merge_bytes(binder_strings):
"""Concatenate multiple serialized binders into one byte string."""
output = None
for byte_string in binder_strings:
binder = Binder().from_bytes(byte_string)
if output is None:
output = binder
else:
output.merge(binder)
re... | python | def merge_bytes(binder_strings):
"""Concatenate multiple serialized binders into one byte string."""
output = None
for byte_string in binder_strings:
binder = Binder().from_bytes(byte_string)
if output is None:
output = binder
else:
output.merge(binder)
re... | [
"def",
"merge_bytes",
"(",
"binder_strings",
")",
":",
"output",
"=",
"None",
"for",
"byte_string",
"in",
"binder_strings",
":",
"binder",
"=",
"Binder",
"(",
")",
".",
"from_bytes",
"(",
"byte_string",
")",
"if",
"output",
"is",
"None",
":",
"output",
"="... | Concatenate multiple serialized binders into one byte string. | [
"Concatenate",
"multiple",
"serialized",
"binders",
"into",
"one",
"byte",
"string",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/tokens/_serialize.py#L97-L106 | train |
explosion/spaCy | spacy/tokens/_serialize.py | Binder.add | def add(self, doc):
"""Add a doc's annotations to the binder for serialization."""
array = doc.to_array(self.attrs)
if len(array.shape) == 1:
array = array.reshape((array.shape[0], 1))
self.tokens.append(array)
spaces = doc.to_array(SPACY)
assert array.shape[0... | python | def add(self, doc):
"""Add a doc's annotations to the binder for serialization."""
array = doc.to_array(self.attrs)
if len(array.shape) == 1:
array = array.reshape((array.shape[0], 1))
self.tokens.append(array)
spaces = doc.to_array(SPACY)
assert array.shape[0... | [
"def",
"add",
"(",
"self",
",",
"doc",
")",
":",
"array",
"=",
"doc",
".",
"to_array",
"(",
"self",
".",
"attrs",
")",
"if",
"len",
"(",
"array",
".",
"shape",
")",
"==",
"1",
":",
"array",
"=",
"array",
".",
"reshape",
"(",
"(",
"array",
".",
... | Add a doc's annotations to the binder for serialization. | [
"Add",
"a",
"doc",
"s",
"annotations",
"to",
"the",
"binder",
"for",
"serialization",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/tokens/_serialize.py#L35-L45 | train |
explosion/spaCy | spacy/tokens/_serialize.py | Binder.get_docs | def get_docs(self, vocab):
"""Recover Doc objects from the annotations, using the given vocab."""
for string in self.strings:
vocab[string]
orth_col = self.attrs.index(ORTH)
for tokens, spaces in zip(self.tokens, self.spaces):
words = [vocab.strings[orth] for orth... | python | def get_docs(self, vocab):
"""Recover Doc objects from the annotations, using the given vocab."""
for string in self.strings:
vocab[string]
orth_col = self.attrs.index(ORTH)
for tokens, spaces in zip(self.tokens, self.spaces):
words = [vocab.strings[orth] for orth... | [
"def",
"get_docs",
"(",
"self",
",",
"vocab",
")",
":",
"for",
"string",
"in",
"self",
".",
"strings",
":",
"vocab",
"[",
"string",
"]",
"orth_col",
"=",
"self",
".",
"attrs",
".",
"index",
"(",
"ORTH",
")",
"for",
"tokens",
",",
"spaces",
"in",
"z... | Recover Doc objects from the annotations, using the given vocab. | [
"Recover",
"Doc",
"objects",
"from",
"the",
"annotations",
"using",
"the",
"given",
"vocab",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/tokens/_serialize.py#L47-L56 | train |
explosion/spaCy | spacy/tokens/_serialize.py | Binder.merge | def merge(self, other):
"""Extend the annotations of this binder with the annotations from another."""
assert self.attrs == other.attrs
self.tokens.extend(other.tokens)
self.spaces.extend(other.spaces)
self.strings.update(other.strings) | python | def merge(self, other):
"""Extend the annotations of this binder with the annotations from another."""
assert self.attrs == other.attrs
self.tokens.extend(other.tokens)
self.spaces.extend(other.spaces)
self.strings.update(other.strings) | [
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"assert",
"self",
".",
"attrs",
"==",
"other",
".",
"attrs",
"self",
".",
"tokens",
".",
"extend",
"(",
"other",
".",
"tokens",
")",
"self",
".",
"spaces",
".",
"extend",
"(",
"other",
".",
"spac... | Extend the annotations of this binder with the annotations from another. | [
"Extend",
"the",
"annotations",
"of",
"this",
"binder",
"with",
"the",
"annotations",
"from",
"another",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/tokens/_serialize.py#L58-L63 | train |
explosion/spaCy | spacy/tokens/_serialize.py | Binder.to_bytes | def to_bytes(self):
"""Serialize the binder's annotations into a byte string."""
for tokens in self.tokens:
assert len(tokens.shape) == 2, tokens.shape
lengths = [len(tokens) for tokens in self.tokens]
msg = {
"attrs": self.attrs,
"tokens": numpy.vstac... | python | def to_bytes(self):
"""Serialize the binder's annotations into a byte string."""
for tokens in self.tokens:
assert len(tokens.shape) == 2, tokens.shape
lengths = [len(tokens) for tokens in self.tokens]
msg = {
"attrs": self.attrs,
"tokens": numpy.vstac... | [
"def",
"to_bytes",
"(",
"self",
")",
":",
"for",
"tokens",
"in",
"self",
".",
"tokens",
":",
"assert",
"len",
"(",
"tokens",
".",
"shape",
")",
"==",
"2",
",",
"tokens",
".",
"shape",
"lengths",
"=",
"[",
"len",
"(",
"tokens",
")",
"for",
"tokens",... | Serialize the binder's annotations into a byte string. | [
"Serialize",
"the",
"binder",
"s",
"annotations",
"into",
"a",
"byte",
"string",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/tokens/_serialize.py#L65-L77 | train |
explosion/spaCy | spacy/tokens/_serialize.py | Binder.from_bytes | def from_bytes(self, string):
"""Deserialize the binder's annotations from a byte string."""
msg = srsly.msgpack_loads(gzip.decompress(string))
self.attrs = msg["attrs"]
self.strings = set(msg["strings"])
lengths = numpy.fromstring(msg["lengths"], dtype="int32")
flat_spac... | python | def from_bytes(self, string):
"""Deserialize the binder's annotations from a byte string."""
msg = srsly.msgpack_loads(gzip.decompress(string))
self.attrs = msg["attrs"]
self.strings = set(msg["strings"])
lengths = numpy.fromstring(msg["lengths"], dtype="int32")
flat_spac... | [
"def",
"from_bytes",
"(",
"self",
",",
"string",
")",
":",
"msg",
"=",
"srsly",
".",
"msgpack_loads",
"(",
"gzip",
".",
"decompress",
"(",
"string",
")",
")",
"self",
".",
"attrs",
"=",
"msg",
"[",
"\"attrs\"",
"]",
"self",
".",
"strings",
"=",
"set"... | Deserialize the binder's annotations from a byte string. | [
"Deserialize",
"the",
"binder",
"s",
"annotations",
"from",
"a",
"byte",
"string",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/tokens/_serialize.py#L79-L94 | train |
explosion/spaCy | examples/training/train_textcat.py | load_data | def load_data(limit=0, split=0.8):
"""Load data from the IMDB dataset."""
# Partition off part of the train data for evaluation
train_data, _ = thinc.extra.datasets.imdb()
random.shuffle(train_data)
train_data = train_data[-limit:]
texts, labels = zip(*train_data)
cats = [{"POSITIVE": bool(y... | python | def load_data(limit=0, split=0.8):
"""Load data from the IMDB dataset."""
# Partition off part of the train data for evaluation
train_data, _ = thinc.extra.datasets.imdb()
random.shuffle(train_data)
train_data = train_data[-limit:]
texts, labels = zip(*train_data)
cats = [{"POSITIVE": bool(y... | [
"def",
"load_data",
"(",
"limit",
"=",
"0",
",",
"split",
"=",
"0.8",
")",
":",
"# Partition off part of the train data for evaluation",
"train_data",
",",
"_",
"=",
"thinc",
".",
"extra",
".",
"datasets",
".",
"imdb",
"(",
")",
"random",
".",
"shuffle",
"("... | Load data from the IMDB dataset. | [
"Load",
"data",
"from",
"the",
"IMDB",
"dataset",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/examples/training/train_textcat.py#L120-L129 | train |
explosion/spaCy | spacy/cli/package.py | package | def package(input_dir, output_dir, meta_path=None, create_meta=False, force=False):
"""
Generate Python package for model data, including meta and required
installation files. A new directory will be created in the specified
output directory, and model data will be copied over. If --create-meta is
s... | python | def package(input_dir, output_dir, meta_path=None, create_meta=False, force=False):
"""
Generate Python package for model data, including meta and required
installation files. A new directory will be created in the specified
output directory, and model data will be copied over. If --create-meta is
s... | [
"def",
"package",
"(",
"input_dir",
",",
"output_dir",
",",
"meta_path",
"=",
"None",
",",
"create_meta",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"msg",
"=",
"Printer",
"(",
")",
"input_path",
"=",
"util",
".",
"ensure_path",
"(",
"input_dir"... | Generate Python package for model data, including meta and required
installation files. A new directory will be created in the specified
output directory, and model data will be copied over. If --create-meta is
set and a meta.json already exists in the output directory, the existing
values will be used ... | [
"Generate",
"Python",
"package",
"for",
"model",
"data",
"including",
"meta",
"and",
"required",
"installation",
"files",
".",
"A",
"new",
"directory",
"will",
"be",
"created",
"in",
"the",
"specified",
"output",
"directory",
"and",
"model",
"data",
"will",
"b... | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/package.py#L22-L78 | train |
explosion/spaCy | spacy/lang/fr/lemmatizer/lemmatizer.py | FrenchLemmatizer.is_base_form | def is_base_form(self, univ_pos, morphology=None):
"""
Check whether we're dealing with an uninflected paradigm, so we can
avoid lemmatization entirely.
"""
morphology = {} if morphology is None else morphology
others = [key for key in morphology
if key ... | python | def is_base_form(self, univ_pos, morphology=None):
"""
Check whether we're dealing with an uninflected paradigm, so we can
avoid lemmatization entirely.
"""
morphology = {} if morphology is None else morphology
others = [key for key in morphology
if key ... | [
"def",
"is_base_form",
"(",
"self",
",",
"univ_pos",
",",
"morphology",
"=",
"None",
")",
":",
"morphology",
"=",
"{",
"}",
"if",
"morphology",
"is",
"None",
"else",
"morphology",
"others",
"=",
"[",
"key",
"for",
"key",
"in",
"morphology",
"if",
"key",
... | Check whether we're dealing with an uninflected paradigm, so we can
avoid lemmatization entirely. | [
"Check",
"whether",
"we",
"re",
"dealing",
"with",
"an",
"uninflected",
"paradigm",
"so",
"we",
"can",
"avoid",
"lemmatization",
"entirely",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/lang/fr/lemmatizer/lemmatizer.py#L63-L93 | train |
explosion/spaCy | examples/training/train_new_entity_type.py | main | def main(model=None, new_model_name="animal", output_dir=None, n_iter=30):
"""Set up the pipeline and entity recognizer, and train the new entity."""
random.seed(0)
if model is not None:
nlp = spacy.load(model) # load existing spaCy model
print("Loaded model '%s'" % model)
else:
... | python | def main(model=None, new_model_name="animal", output_dir=None, n_iter=30):
"""Set up the pipeline and entity recognizer, and train the new entity."""
random.seed(0)
if model is not None:
nlp = spacy.load(model) # load existing spaCy model
print("Loaded model '%s'" % model)
else:
... | [
"def",
"main",
"(",
"model",
"=",
"None",
",",
"new_model_name",
"=",
"\"animal\"",
",",
"output_dir",
"=",
"None",
",",
"n_iter",
"=",
"30",
")",
":",
"random",
".",
"seed",
"(",
"0",
")",
"if",
"model",
"is",
"not",
"None",
":",
"nlp",
"=",
"spac... | Set up the pipeline and entity recognizer, and train the new entity. | [
"Set",
"up",
"the",
"pipeline",
"and",
"entity",
"recognizer",
"and",
"train",
"the",
"new",
"entity",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/examples/training/train_new_entity_type.py#L71-L134 | train |
explosion/spaCy | spacy/cli/converters/conll_ner2json.py | conll_ner2json | def conll_ner2json(input_data, **kwargs):
"""
Convert files in the CoNLL-2003 NER format into JSON format for use with
train cli.
"""
delimit_docs = "-DOCSTART- -X- O O"
output_docs = []
for doc in input_data.strip().split(delimit_docs):
doc = doc.strip()
if not doc:
... | python | def conll_ner2json(input_data, **kwargs):
"""
Convert files in the CoNLL-2003 NER format into JSON format for use with
train cli.
"""
delimit_docs = "-DOCSTART- -X- O O"
output_docs = []
for doc in input_data.strip().split(delimit_docs):
doc = doc.strip()
if not doc:
... | [
"def",
"conll_ner2json",
"(",
"input_data",
",",
"*",
"*",
"kwargs",
")",
":",
"delimit_docs",
"=",
"\"-DOCSTART- -X- O O\"",
"output_docs",
"=",
"[",
"]",
"for",
"doc",
"in",
"input_data",
".",
"strip",
"(",
")",
".",
"split",
"(",
"delimit_docs",
")",
":... | Convert files in the CoNLL-2003 NER format into JSON format for use with
train cli. | [
"Convert",
"files",
"in",
"the",
"CoNLL",
"-",
"2003",
"NER",
"format",
"into",
"JSON",
"format",
"for",
"use",
"with",
"train",
"cli",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/converters/conll_ner2json.py#L7-L38 | train |
explosion/spaCy | examples/training/train_tagger.py | main | def main(lang="en", output_dir=None, n_iter=25):
"""Create a new model, set up the pipeline and train the tagger. In order to
train the tagger with a custom tag map, we're creating a new Language
instance with a custom vocab.
"""
nlp = spacy.blank(lang)
# add the tagger to the pipeline
# nlp... | python | def main(lang="en", output_dir=None, n_iter=25):
"""Create a new model, set up the pipeline and train the tagger. In order to
train the tagger with a custom tag map, we're creating a new Language
instance with a custom vocab.
"""
nlp = spacy.blank(lang)
# add the tagger to the pipeline
# nlp... | [
"def",
"main",
"(",
"lang",
"=",
"\"en\"",
",",
"output_dir",
"=",
"None",
",",
"n_iter",
"=",
"25",
")",
":",
"nlp",
"=",
"spacy",
".",
"blank",
"(",
"lang",
")",
"# add the tagger to the pipeline",
"# nlp.create_pipe works for built-ins that are registered with sp... | Create a new model, set up the pipeline and train the tagger. In order to
train the tagger with a custom tag map, we're creating a new Language
instance with a custom vocab. | [
"Create",
"a",
"new",
"model",
"set",
"up",
"the",
"pipeline",
"and",
"train",
"the",
"tagger",
".",
"In",
"order",
"to",
"train",
"the",
"tagger",
"with",
"a",
"custom",
"tag",
"map",
"we",
"re",
"creating",
"a",
"new",
"Language",
"instance",
"with",
... | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/examples/training/train_tagger.py#L47-L89 | train |
explosion/spaCy | examples/training/pretrain_textcat.py | load_textcat_data | def load_textcat_data(limit=0):
"""Load data from the IMDB dataset."""
# Partition off part of the train data for evaluation
train_data, eval_data = thinc.extra.datasets.imdb()
random.shuffle(train_data)
train_data = train_data[-limit:]
texts, labels = zip(*train_data)
eval_texts, eval_label... | python | def load_textcat_data(limit=0):
"""Load data from the IMDB dataset."""
# Partition off part of the train data for evaluation
train_data, eval_data = thinc.extra.datasets.imdb()
random.shuffle(train_data)
train_data = train_data[-limit:]
texts, labels = zip(*train_data)
eval_texts, eval_label... | [
"def",
"load_textcat_data",
"(",
"limit",
"=",
"0",
")",
":",
"# Partition off part of the train data for evaluation",
"train_data",
",",
"eval_data",
"=",
"thinc",
".",
"extra",
".",
"datasets",
".",
"imdb",
"(",
")",
"random",
".",
"shuffle",
"(",
"train_data",
... | Load data from the IMDB dataset. | [
"Load",
"data",
"from",
"the",
"IMDB",
"dataset",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/examples/training/pretrain_textcat.py#L41-L51 | train |
explosion/spaCy | spacy/cli/init_model.py | init_model | def init_model(
lang,
output_dir,
freqs_loc=None,
clusters_loc=None,
jsonl_loc=None,
vectors_loc=None,
prune_vectors=-1,
):
"""
Create a new model from raw data, like word frequencies, Brown clusters
and word vectors. If vectors are provided in Word2Vec format, they can
be ei... | python | def init_model(
lang,
output_dir,
freqs_loc=None,
clusters_loc=None,
jsonl_loc=None,
vectors_loc=None,
prune_vectors=-1,
):
"""
Create a new model from raw data, like word frequencies, Brown clusters
and word vectors. If vectors are provided in Word2Vec format, they can
be ei... | [
"def",
"init_model",
"(",
"lang",
",",
"output_dir",
",",
"freqs_loc",
"=",
"None",
",",
"clusters_loc",
"=",
"None",
",",
"jsonl_loc",
"=",
"None",
",",
"vectors_loc",
"=",
"None",
",",
"prune_vectors",
"=",
"-",
"1",
",",
")",
":",
"if",
"jsonl_loc",
... | Create a new model from raw data, like word frequencies, Brown clusters
and word vectors. If vectors are provided in Word2Vec format, they can
be either a .txt or zipped as a .zip or .tar.gz. | [
"Create",
"a",
"new",
"model",
"from",
"raw",
"data",
"like",
"word",
"frequencies",
"Brown",
"clusters",
"and",
"word",
"vectors",
".",
"If",
"vectors",
"are",
"provided",
"in",
"Word2Vec",
"format",
"they",
"can",
"be",
"either",
"a",
".",
"txt",
"or",
... | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/init_model.py#L39-L91 | train |
explosion/spaCy | spacy/cli/init_model.py | open_file | def open_file(loc):
"""Handle .gz, .tar.gz or unzipped files"""
loc = ensure_path(loc)
if tarfile.is_tarfile(str(loc)):
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].endswi... | python | def open_file(loc):
"""Handle .gz, .tar.gz or unzipped files"""
loc = ensure_path(loc)
if tarfile.is_tarfile(str(loc)):
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].endswi... | [
"def",
"open_file",
"(",
"loc",
")",
":",
"loc",
"=",
"ensure_path",
"(",
"loc",
")",
"if",
"tarfile",
".",
"is_tarfile",
"(",
"str",
"(",
"loc",
")",
")",
":",
"return",
"tarfile",
".",
"open",
"(",
"str",
"(",
"loc",
")",
",",
"\"r:gz\"",
")",
... | Handle .gz, .tar.gz or unzipped files | [
"Handle",
".",
"gz",
".",
"tar",
".",
"gz",
"or",
"unzipped",
"files"
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/init_model.py#L94-L107 | train |
explosion/spaCy | examples/training/train_ner.py | main | def main(model=None, output_dir=None, n_iter=100):
"""Load the model, set up the pipeline and train the entity recognizer."""
if model is not None:
nlp = spacy.load(model) # load existing spaCy model
print("Loaded model '%s'" % model)
else:
nlp = spacy.blank("en") # create blank La... | python | def main(model=None, output_dir=None, n_iter=100):
"""Load the model, set up the pipeline and train the entity recognizer."""
if model is not None:
nlp = spacy.load(model) # load existing spaCy model
print("Loaded model '%s'" % model)
else:
nlp = spacy.blank("en") # create blank La... | [
"def",
"main",
"(",
"model",
"=",
"None",
",",
"output_dir",
"=",
"None",
",",
"n_iter",
"=",
"100",
")",
":",
"if",
"model",
"is",
"not",
"None",
":",
"nlp",
"=",
"spacy",
".",
"load",
"(",
"model",
")",
"# load existing spaCy model",
"print",
"(",
... | Load the model, set up the pipeline and train the entity recognizer. | [
"Load",
"the",
"model",
"set",
"up",
"the",
"pipeline",
"and",
"train",
"the",
"entity",
"recognizer",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/examples/training/train_ner.py#L34-L99 | train |
explosion/spaCy | spacy/cli/pretrain.py | pretrain | def pretrain(
texts_loc,
vectors_model,
output_dir,
width=96,
depth=4,
embed_rows=2000,
loss_func="cosine",
use_vectors=False,
dropout=0.2,
n_iter=1000,
batch_size=3000,
max_length=500,
min_length=5,
seed=0,
n_save_every=None,
):
"""
Pre-train the 'tok... | python | def pretrain(
texts_loc,
vectors_model,
output_dir,
width=96,
depth=4,
embed_rows=2000,
loss_func="cosine",
use_vectors=False,
dropout=0.2,
n_iter=1000,
batch_size=3000,
max_length=500,
min_length=5,
seed=0,
n_save_every=None,
):
"""
Pre-train the 'tok... | [
"def",
"pretrain",
"(",
"texts_loc",
",",
"vectors_model",
",",
"output_dir",
",",
"width",
"=",
"96",
",",
"depth",
"=",
"4",
",",
"embed_rows",
"=",
"2000",
",",
"loss_func",
"=",
"\"cosine\"",
",",
"use_vectors",
"=",
"False",
",",
"dropout",
"=",
"0.... | Pre-train the 'token-to-vector' (tok2vec) layer of pipeline components,
using an approximate language-modelling objective. Specifically, we load
pre-trained vectors, and train a component like a CNN, BiLSTM, etc to predict
vectors which match the pre-trained ones. The weights are saved to a directory
af... | [
"Pre",
"-",
"train",
"the",
"token",
"-",
"to",
"-",
"vector",
"(",
"tok2vec",
")",
"layer",
"of",
"pipeline",
"components",
"using",
"an",
"approximate",
"language",
"-",
"modelling",
"objective",
".",
"Specifically",
"we",
"load",
"pre",
"-",
"trained",
... | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/pretrain.py#L40-L161 | train |
explosion/spaCy | spacy/cli/pretrain.py | make_update | def make_update(model, docs, optimizer, drop=0.0, objective="L2"):
"""Perform an update over a single batch of documents.
docs (iterable): A batch of `Doc` objects.
drop (float): The droput rate.
optimizer (callable): An optimizer.
RETURNS loss: A float for the loss.
"""
predictions, backpr... | python | def make_update(model, docs, optimizer, drop=0.0, objective="L2"):
"""Perform an update over a single batch of documents.
docs (iterable): A batch of `Doc` objects.
drop (float): The droput rate.
optimizer (callable): An optimizer.
RETURNS loss: A float for the loss.
"""
predictions, backpr... | [
"def",
"make_update",
"(",
"model",
",",
"docs",
",",
"optimizer",
",",
"drop",
"=",
"0.0",
",",
"objective",
"=",
"\"L2\"",
")",
":",
"predictions",
",",
"backprop",
"=",
"model",
".",
"begin_update",
"(",
"docs",
",",
"drop",
"=",
"drop",
")",
"loss"... | Perform an update over a single batch of documents.
docs (iterable): A batch of `Doc` objects.
drop (float): The droput rate.
optimizer (callable): An optimizer.
RETURNS loss: A float for the loss. | [
"Perform",
"an",
"update",
"over",
"a",
"single",
"batch",
"of",
"documents",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/pretrain.py#L164-L178 | train |
explosion/spaCy | spacy/cli/pretrain.py | get_vectors_loss | def get_vectors_loss(ops, docs, prediction, objective="L2"):
"""Compute a mean-squared error loss between the documents' vectors and
the prediction.
Note that this is ripe for customization! We could compute the vectors
in some other word, e.g. with an LSTM language model, or use some other
type of... | python | def get_vectors_loss(ops, docs, prediction, objective="L2"):
"""Compute a mean-squared error loss between the documents' vectors and
the prediction.
Note that this is ripe for customization! We could compute the vectors
in some other word, e.g. with an LSTM language model, or use some other
type of... | [
"def",
"get_vectors_loss",
"(",
"ops",
",",
"docs",
",",
"prediction",
",",
"objective",
"=",
"\"L2\"",
")",
":",
"# The simplest way to implement this would be to vstack the",
"# token.vector values, but that's a bit inefficient, especially on GPU.",
"# Instead we fetch the index in... | Compute a mean-squared error loss between the documents' vectors and
the prediction.
Note that this is ripe for customization! We could compute the vectors
in some other word, e.g. with an LSTM language model, or use some other
type of objective. | [
"Compute",
"a",
"mean",
"-",
"squared",
"error",
"loss",
"between",
"the",
"documents",
"vectors",
"and",
"the",
"prediction",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/pretrain.py#L199-L218 | train |
explosion/spaCy | spacy/cli/pretrain.py | create_pretraining_model | def create_pretraining_model(nlp, tok2vec):
"""Define a network for the pretraining. We simply add an output layer onto
the tok2vec input model. The tok2vec input model needs to be a model that
takes a batch of Doc objects (as a list), and returns a list of arrays.
Each array in the output needs to have... | python | def create_pretraining_model(nlp, tok2vec):
"""Define a network for the pretraining. We simply add an output layer onto
the tok2vec input model. The tok2vec input model needs to be a model that
takes a batch of Doc objects (as a list), and returns a list of arrays.
Each array in the output needs to have... | [
"def",
"create_pretraining_model",
"(",
"nlp",
",",
"tok2vec",
")",
":",
"output_size",
"=",
"nlp",
".",
"vocab",
".",
"vectors",
".",
"data",
".",
"shape",
"[",
"1",
"]",
"output_layer",
"=",
"chain",
"(",
"LN",
"(",
"Maxout",
"(",
"300",
",",
"pieces... | Define a network for the pretraining. We simply add an output layer onto
the tok2vec input model. The tok2vec input model needs to be a model that
takes a batch of Doc objects (as a list), and returns a list of arrays.
Each array in the output needs to have one row per token in the doc. | [
"Define",
"a",
"network",
"for",
"the",
"pretraining",
".",
"We",
"simply",
"add",
"an",
"output",
"layer",
"onto",
"the",
"tok2vec",
"input",
"model",
".",
"The",
"tok2vec",
"input",
"model",
"needs",
"to",
"be",
"a",
"model",
"that",
"takes",
"a",
"bat... | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/pretrain.py#L236-L256 | train |
explosion/spaCy | spacy/cli/pretrain.py | _smart_round | def _smart_round(figure, width=10, max_decimal=4):
"""Round large numbers as integers, smaller numbers as decimals."""
n_digits = len(str(int(figure)))
n_decimal = width - (n_digits + 1)
if n_decimal <= 1:
return str(int(figure))
else:
n_decimal = min(n_decimal, max_decimal)
... | python | def _smart_round(figure, width=10, max_decimal=4):
"""Round large numbers as integers, smaller numbers as decimals."""
n_digits = len(str(int(figure)))
n_decimal = width - (n_digits + 1)
if n_decimal <= 1:
return str(int(figure))
else:
n_decimal = min(n_decimal, max_decimal)
... | [
"def",
"_smart_round",
"(",
"figure",
",",
"width",
"=",
"10",
",",
"max_decimal",
"=",
"4",
")",
":",
"n_digits",
"=",
"len",
"(",
"str",
"(",
"int",
"(",
"figure",
")",
")",
")",
"n_decimal",
"=",
"width",
"-",
"(",
"n_digits",
"+",
"1",
")",
"... | Round large numbers as integers, smaller numbers as decimals. | [
"Round",
"large",
"numbers",
"as",
"integers",
"smaller",
"numbers",
"as",
"decimals",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/pretrain.py#L295-L304 | train |
explosion/spaCy | spacy/lang/el/syntax_iterators.py | noun_chunks | def noun_chunks(obj):
"""
Detect base noun phrases. Works on both Doc and Span.
"""
# It follows the logic of the noun chunks finder of English language,
# adjusted to some Greek language special characteristics.
# obj tag corrects some DEP tagger mistakes.
# Further improvement of the model... | python | def noun_chunks(obj):
"""
Detect base noun phrases. Works on both Doc and Span.
"""
# It follows the logic of the noun chunks finder of English language,
# adjusted to some Greek language special characteristics.
# obj tag corrects some DEP tagger mistakes.
# Further improvement of the model... | [
"def",
"noun_chunks",
"(",
"obj",
")",
":",
"# It follows the logic of the noun chunks finder of English language,",
"# adjusted to some Greek language special characteristics.",
"# obj tag corrects some DEP tagger mistakes.",
"# Further improvement of the models will eliminate the need for this t... | Detect base noun phrases. Works on both Doc and Span. | [
"Detect",
"base",
"noun",
"phrases",
".",
"Works",
"on",
"both",
"Doc",
"and",
"Span",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/lang/el/syntax_iterators.py#L7-L55 | train |
explosion/spaCy | spacy/tokens/underscore.py | get_ext_args | def get_ext_args(**kwargs):
"""Validate and convert arguments. Reused in Doc, Token and Span."""
default = kwargs.get("default")
getter = kwargs.get("getter")
setter = kwargs.get("setter")
method = kwargs.get("method")
if getter is None and setter is not None:
raise ValueError(Errors.E08... | python | def get_ext_args(**kwargs):
"""Validate and convert arguments. Reused in Doc, Token and Span."""
default = kwargs.get("default")
getter = kwargs.get("getter")
setter = kwargs.get("setter")
method = kwargs.get("method")
if getter is None and setter is not None:
raise ValueError(Errors.E08... | [
"def",
"get_ext_args",
"(",
"*",
"*",
"kwargs",
")",
":",
"default",
"=",
"kwargs",
".",
"get",
"(",
"\"default\"",
")",
"getter",
"=",
"kwargs",
".",
"get",
"(",
"\"getter\"",
")",
"setter",
"=",
"kwargs",
".",
"get",
"(",
"\"setter\"",
")",
"method",... | Validate and convert arguments. Reused in Doc, Token and Span. | [
"Validate",
"and",
"convert",
"arguments",
".",
"Reused",
"in",
"Doc",
"Token",
"and",
"Span",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/tokens/underscore.py#L69-L87 | train |
explosion/spaCy | spacy/tokens/underscore.py | is_writable_attr | def is_writable_attr(ext):
"""Check if an extension attribute is writable.
ext (tuple): The (default, getter, setter, method) tuple available via
{Doc,Span,Token}.get_extension.
RETURNS (bool): Whether the attribute is writable.
"""
default, method, getter, setter = ext
# Extension is w... | python | def is_writable_attr(ext):
"""Check if an extension attribute is writable.
ext (tuple): The (default, getter, setter, method) tuple available via
{Doc,Span,Token}.get_extension.
RETURNS (bool): Whether the attribute is writable.
"""
default, method, getter, setter = ext
# Extension is w... | [
"def",
"is_writable_attr",
"(",
"ext",
")",
":",
"default",
",",
"method",
",",
"getter",
",",
"setter",
"=",
"ext",
"# Extension is writable if it has a setter (getter + setter), if it has a",
"# default value (or, if its default value is none, none of the other values",
"# should... | Check if an extension attribute is writable.
ext (tuple): The (default, getter, setter, method) tuple available via
{Doc,Span,Token}.get_extension.
RETURNS (bool): Whether the attribute is writable. | [
"Check",
"if",
"an",
"extension",
"attribute",
"is",
"writable",
".",
"ext",
"(",
"tuple",
")",
":",
"The",
"(",
"default",
"getter",
"setter",
"method",
")",
"tuple",
"available",
"via",
"{",
"Doc",
"Span",
"Token",
"}",
".",
"get_extension",
".",
"RETU... | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/tokens/underscore.py#L90-L102 | train |
explosion/spaCy | setup.py | is_new_osx | def is_new_osx():
"""Check whether we're on OSX >= 10.10"""
name = distutils.util.get_platform()
if sys.platform != "darwin":
return False
elif name.startswith("macosx-10"):
minor_version = int(name.split("-")[1].split(".")[1])
if minor_version >= 7:
return True
... | python | def is_new_osx():
"""Check whether we're on OSX >= 10.10"""
name = distutils.util.get_platform()
if sys.platform != "darwin":
return False
elif name.startswith("macosx-10"):
minor_version = int(name.split("-")[1].split(".")[1])
if minor_version >= 7:
return True
... | [
"def",
"is_new_osx",
"(",
")",
":",
"name",
"=",
"distutils",
".",
"util",
".",
"get_platform",
"(",
")",
"if",
"sys",
".",
"platform",
"!=",
"\"darwin\"",
":",
"return",
"False",
"elif",
"name",
".",
"startswith",
"(",
"\"macosx-10\"",
")",
":",
"minor_... | Check whether we're on OSX >= 10.10 | [
"Check",
"whether",
"we",
"re",
"on",
"OSX",
">",
"=",
"10",
".",
"10"
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/setup.py#L15-L27 | train |
explosion/spaCy | examples/training/ner_multitask_objective.py | get_position_label | def get_position_label(i, words, tags, heads, labels, ents):
"""Return labels indicating the position of the word in the document.
"""
if len(words) < 20:
return "short-doc"
elif i == 0:
return "first-word"
elif i < 10:
return "early-word"
elif i < 20:
return "mid... | python | def get_position_label(i, words, tags, heads, labels, ents):
"""Return labels indicating the position of the word in the document.
"""
if len(words) < 20:
return "short-doc"
elif i == 0:
return "first-word"
elif i < 10:
return "early-word"
elif i < 20:
return "mid... | [
"def",
"get_position_label",
"(",
"i",
",",
"words",
",",
"tags",
",",
"heads",
",",
"labels",
",",
"ents",
")",
":",
"if",
"len",
"(",
"words",
")",
"<",
"20",
":",
"return",
"\"short-doc\"",
"elif",
"i",
"==",
"0",
":",
"return",
"\"first-word\"",
... | Return labels indicating the position of the word in the document. | [
"Return",
"labels",
"indicating",
"the",
"position",
"of",
"the",
"word",
"in",
"the",
"document",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/examples/training/ner_multitask_objective.py#L36-L50 | train |
explosion/spaCy | spacy/cli/download.py | download | def download(model, direct=False, *pip_args):
"""
Download compatible model from default download path using pip. Model
can be shortcut, model name or, if --direct flag is set, full model name
with version. For direct downloads, the compatibility check will be skipped.
"""
dl_tpl = "{m}-{v}/{m}-... | python | def download(model, direct=False, *pip_args):
"""
Download compatible model from default download path using pip. Model
can be shortcut, model name or, if --direct flag is set, full model name
with version. For direct downloads, the compatibility check will be skipped.
"""
dl_tpl = "{m}-{v}/{m}-... | [
"def",
"download",
"(",
"model",
",",
"direct",
"=",
"False",
",",
"*",
"pip_args",
")",
":",
"dl_tpl",
"=",
"\"{m}-{v}/{m}-{v}.tar.gz#egg={m}=={v}\"",
"if",
"direct",
":",
"components",
"=",
"model",
".",
"split",
"(",
"\"-\"",
")",
"model_name",
"=",
"\"\"... | Download compatible model from default download path using pip. Model
can be shortcut, model name or, if --direct flag is set, full model name
with version. For direct downloads, the compatibility check will be skipped. | [
"Download",
"compatible",
"model",
"from",
"default",
"download",
"path",
"using",
"pip",
".",
"Model",
"can",
"be",
"shortcut",
"model",
"name",
"or",
"if",
"--",
"direct",
"flag",
"is",
"set",
"full",
"model",
"name",
"with",
"version",
".",
"For",
"dire... | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/download.py#L24-L69 | train |
explosion/spaCy | spacy/cli/convert.py | convert | def convert(
input_file,
output_dir="-",
file_type="json",
n_sents=1,
morphology=False,
converter="auto",
lang=None,
):
"""
Convert files into JSON format for use with train command and other
experiment management functions. If no output_dir is specified, the data
is written ... | python | def convert(
input_file,
output_dir="-",
file_type="json",
n_sents=1,
morphology=False,
converter="auto",
lang=None,
):
"""
Convert files into JSON format for use with train command and other
experiment management functions. If no output_dir is specified, the data
is written ... | [
"def",
"convert",
"(",
"input_file",
",",
"output_dir",
"=",
"\"-\"",
",",
"file_type",
"=",
"\"json\"",
",",
"n_sents",
"=",
"1",
",",
"morphology",
"=",
"False",
",",
"converter",
"=",
"\"auto\"",
",",
"lang",
"=",
"None",
",",
")",
":",
"msg",
"=",
... | Convert files into JSON format for use with train command and other
experiment management functions. If no output_dir is specified, the data
is written to stdout, so you can pipe them forward to a JSON file:
$ spacy convert some_file.conllu > some_file.json | [
"Convert",
"files",
"into",
"JSON",
"format",
"for",
"use",
"with",
"train",
"command",
"and",
"other",
"experiment",
"management",
"functions",
".",
"If",
"no",
"output_dir",
"is",
"specified",
"the",
"data",
"is",
"written",
"to",
"stdout",
"so",
"you",
"c... | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/convert.py#L39-L97 | train |
explosion/spaCy | bin/ud/run_eval.py | load_model | def load_model(modelname, add_sentencizer=False):
""" Load a specific spaCy model """
loading_start = time.time()
nlp = spacy.load(modelname)
if add_sentencizer:
nlp.add_pipe(nlp.create_pipe('sentencizer'))
loading_end = time.time()
loading_time = loading_end - loading_start
if add_s... | python | def load_model(modelname, add_sentencizer=False):
""" Load a specific spaCy model """
loading_start = time.time()
nlp = spacy.load(modelname)
if add_sentencizer:
nlp.add_pipe(nlp.create_pipe('sentencizer'))
loading_end = time.time()
loading_time = loading_end - loading_start
if add_s... | [
"def",
"load_model",
"(",
"modelname",
",",
"add_sentencizer",
"=",
"False",
")",
":",
"loading_start",
"=",
"time",
".",
"time",
"(",
")",
"nlp",
"=",
"spacy",
".",
"load",
"(",
"modelname",
")",
"if",
"add_sentencizer",
":",
"nlp",
".",
"add_pipe",
"("... | Load a specific spaCy model | [
"Load",
"a",
"specific",
"spaCy",
"model"
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/bin/ud/run_eval.py#L34-L44 | train |
explosion/spaCy | bin/ud/run_eval.py | load_default_model_sentencizer | def load_default_model_sentencizer(lang):
""" Load a generic spaCy model and add the sentencizer for sentence tokenization"""
loading_start = time.time()
lang_class = get_lang_class(lang)
nlp = lang_class()
nlp.add_pipe(nlp.create_pipe('sentencizer'))
loading_end = time.time()
loading_time =... | python | def load_default_model_sentencizer(lang):
""" Load a generic spaCy model and add the sentencizer for sentence tokenization"""
loading_start = time.time()
lang_class = get_lang_class(lang)
nlp = lang_class()
nlp.add_pipe(nlp.create_pipe('sentencizer'))
loading_end = time.time()
loading_time =... | [
"def",
"load_default_model_sentencizer",
"(",
"lang",
")",
":",
"loading_start",
"=",
"time",
".",
"time",
"(",
")",
"lang_class",
"=",
"get_lang_class",
"(",
"lang",
")",
"nlp",
"=",
"lang_class",
"(",
")",
"nlp",
".",
"add_pipe",
"(",
"nlp",
".",
"create... | Load a generic spaCy model and add the sentencizer for sentence tokenization | [
"Load",
"a",
"generic",
"spaCy",
"model",
"and",
"add",
"the",
"sentencizer",
"for",
"sentence",
"tokenization"
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/bin/ud/run_eval.py#L47-L55 | train |
explosion/spaCy | bin/ud/run_eval.py | get_freq_tuples | def get_freq_tuples(my_list, print_total_threshold):
""" Turn a list of errors into frequency-sorted tuples thresholded by a certain total number """
d = {}
for token in my_list:
d.setdefault(token, 0)
d[token] += 1
return sorted(d.items(), key=operator.itemgetter(1), reverse=True)[:prin... | python | def get_freq_tuples(my_list, print_total_threshold):
""" Turn a list of errors into frequency-sorted tuples thresholded by a certain total number """
d = {}
for token in my_list:
d.setdefault(token, 0)
d[token] += 1
return sorted(d.items(), key=operator.itemgetter(1), reverse=True)[:prin... | [
"def",
"get_freq_tuples",
"(",
"my_list",
",",
"print_total_threshold",
")",
":",
"d",
"=",
"{",
"}",
"for",
"token",
"in",
"my_list",
":",
"d",
".",
"setdefault",
"(",
"token",
",",
"0",
")",
"d",
"[",
"token",
"]",
"+=",
"1",
"return",
"sorted",
"(... | Turn a list of errors into frequency-sorted tuples thresholded by a certain total number | [
"Turn",
"a",
"list",
"of",
"errors",
"into",
"frequency",
"-",
"sorted",
"tuples",
"thresholded",
"by",
"a",
"certain",
"total",
"number"
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/bin/ud/run_eval.py#L62-L68 | train |
explosion/spaCy | bin/ud/run_eval.py | _contains_blinded_text | def _contains_blinded_text(stats_xml):
""" Heuristic to determine whether the treebank has blinded texts or not """
tree = ET.parse(stats_xml)
root = tree.getroot()
total_tokens = int(root.find('size/total/tokens').text)
unique_lemmas = int(root.find('lemmas').get('unique'))
# assume the corpus... | python | def _contains_blinded_text(stats_xml):
""" Heuristic to determine whether the treebank has blinded texts or not """
tree = ET.parse(stats_xml)
root = tree.getroot()
total_tokens = int(root.find('size/total/tokens').text)
unique_lemmas = int(root.find('lemmas').get('unique'))
# assume the corpus... | [
"def",
"_contains_blinded_text",
"(",
"stats_xml",
")",
":",
"tree",
"=",
"ET",
".",
"parse",
"(",
"stats_xml",
")",
"root",
"=",
"tree",
".",
"getroot",
"(",
")",
"total_tokens",
"=",
"int",
"(",
"root",
".",
"find",
"(",
"'size/total/tokens'",
")",
"."... | Heuristic to determine whether the treebank has blinded texts or not | [
"Heuristic",
"to",
"determine",
"whether",
"the",
"treebank",
"has",
"blinded",
"texts",
"or",
"not"
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/bin/ud/run_eval.py#L71-L79 | train |
explosion/spaCy | bin/ud/run_eval.py | fetch_all_treebanks | def fetch_all_treebanks(ud_dir, languages, corpus, best_per_language):
"""" Fetch the txt files for all treebanks for a given set of languages """
all_treebanks = dict()
treebank_size = dict()
for l in languages:
all_treebanks[l] = []
treebank_size[l] = 0
for treebank_dir in ud_dir.... | python | def fetch_all_treebanks(ud_dir, languages, corpus, best_per_language):
"""" Fetch the txt files for all treebanks for a given set of languages """
all_treebanks = dict()
treebank_size = dict()
for l in languages:
all_treebanks[l] = []
treebank_size[l] = 0
for treebank_dir in ud_dir.... | [
"def",
"fetch_all_treebanks",
"(",
"ud_dir",
",",
"languages",
",",
"corpus",
",",
"best_per_language",
")",
":",
"all_treebanks",
"=",
"dict",
"(",
")",
"treebank_size",
"=",
"dict",
"(",
")",
"for",
"l",
"in",
"languages",
":",
"all_treebanks",
"[",
"l",
... | Fetch the txt files for all treebanks for a given set of languages | [
"Fetch",
"the",
"txt",
"files",
"for",
"all",
"treebanks",
"for",
"a",
"given",
"set",
"of",
"languages"
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/bin/ud/run_eval.py#L82-L111 | train |
explosion/spaCy | bin/ud/run_eval.py | run_single_eval | def run_single_eval(nlp, loading_time, print_name, text_path, gold_ud, tmp_output_path, out_file, print_header,
check_parse, print_freq_tasks):
"""" Run an evaluation of a model nlp on a certain specified treebank """
with text_path.open(mode='r', encoding='utf-8') as f:
flat_text = ... | python | def run_single_eval(nlp, loading_time, print_name, text_path, gold_ud, tmp_output_path, out_file, print_header,
check_parse, print_freq_tasks):
"""" Run an evaluation of a model nlp on a certain specified treebank """
with text_path.open(mode='r', encoding='utf-8') as f:
flat_text = ... | [
"def",
"run_single_eval",
"(",
"nlp",
",",
"loading_time",
",",
"print_name",
",",
"text_path",
",",
"gold_ud",
",",
"tmp_output_path",
",",
"out_file",
",",
"print_header",
",",
"check_parse",
",",
"print_freq_tasks",
")",
":",
"with",
"text_path",
".",
"open",... | Run an evaluation of a model nlp on a certain specified treebank | [
"Run",
"an",
"evaluation",
"of",
"a",
"model",
"nlp",
"on",
"a",
"certain",
"specified",
"treebank"
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/bin/ud/run_eval.py#L114-L181 | train |
explosion/spaCy | bin/ud/run_eval.py | run_all_evals | def run_all_evals(models, treebanks, out_file, check_parse, print_freq_tasks):
"""" Run an evaluation for each language with its specified models and treebanks """
print_header = True
for tb_lang, treebank_list in treebanks.items():
print()
print("Language", tb_lang)
for text_path i... | python | def run_all_evals(models, treebanks, out_file, check_parse, print_freq_tasks):
"""" Run an evaluation for each language with its specified models and treebanks """
print_header = True
for tb_lang, treebank_list in treebanks.items():
print()
print("Language", tb_lang)
for text_path i... | [
"def",
"run_all_evals",
"(",
"models",
",",
"treebanks",
",",
"out_file",
",",
"check_parse",
",",
"print_freq_tasks",
")",
":",
"print_header",
"=",
"True",
"for",
"tb_lang",
",",
"treebank_list",
"in",
"treebanks",
".",
"items",
"(",
")",
":",
"print",
"("... | Run an evaluation for each language with its specified models and treebanks | [
"Run",
"an",
"evaluation",
"for",
"each",
"language",
"with",
"its",
"specified",
"models",
"and",
"treebanks"
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/bin/ud/run_eval.py#L184-L212 | train |
explosion/spaCy | bin/ud/run_eval.py | main | def main(out_path, ud_dir, check_parse=False, langs=ALL_LANGUAGES, exclude_trained_models=False, exclude_multi=False,
hide_freq=False, corpus='train', best_per_language=False):
""""
Assemble all treebanks and models to run evaluations with.
When setting check_parse to True, the default models will ... | python | def main(out_path, ud_dir, check_parse=False, langs=ALL_LANGUAGES, exclude_trained_models=False, exclude_multi=False,
hide_freq=False, corpus='train', best_per_language=False):
""""
Assemble all treebanks and models to run evaluations with.
When setting check_parse to True, the default models will ... | [
"def",
"main",
"(",
"out_path",
",",
"ud_dir",
",",
"check_parse",
"=",
"False",
",",
"langs",
"=",
"ALL_LANGUAGES",
",",
"exclude_trained_models",
"=",
"False",
",",
"exclude_multi",
"=",
"False",
",",
"hide_freq",
"=",
"False",
",",
"corpus",
"=",
"'train'... | Assemble all treebanks and models to run evaluations with.
When setting check_parse to True, the default models will not be evaluated as they don't have parsing functionality | [
"Assemble",
"all",
"treebanks",
"and",
"models",
"to",
"run",
"evaluations",
"with",
".",
"When",
"setting",
"check_parse",
"to",
"True",
"the",
"default",
"models",
"will",
"not",
"be",
"evaluated",
"as",
"they",
"don",
"t",
"have",
"parsing",
"functionality"... | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/bin/ud/run_eval.py#L226-L283 | train |
explosion/spaCy | spacy/lang/de/syntax_iterators.py | noun_chunks | def noun_chunks(obj):
"""
Detect base noun phrases from a dependency parse. Works on both Doc and Span.
"""
# this iterator extracts spans headed by NOUNs starting from the left-most
# syntactic dependent until the NOUN itself for close apposition and
# measurement construction, the span is some... | python | def noun_chunks(obj):
"""
Detect base noun phrases from a dependency parse. Works on both Doc and Span.
"""
# this iterator extracts spans headed by NOUNs starting from the left-most
# syntactic dependent until the NOUN itself for close apposition and
# measurement construction, the span is some... | [
"def",
"noun_chunks",
"(",
"obj",
")",
":",
"# this iterator extracts spans headed by NOUNs starting from the left-most",
"# syntactic dependent until the NOUN itself for close apposition and",
"# measurement construction, the span is sometimes extended to the right of",
"# the NOUN. Example: \"ei... | Detect base noun phrases from a dependency parse. Works on both Doc and Span. | [
"Detect",
"base",
"noun",
"phrases",
"from",
"a",
"dependency",
"parse",
".",
"Works",
"on",
"both",
"Doc",
"and",
"Span",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/lang/de/syntax_iterators.py#L7-L46 | train |
explosion/spaCy | spacy/_ml.py | with_cpu | def with_cpu(ops, model):
"""Wrap a model that should run on CPU, transferring inputs and outputs
as necessary."""
model.to_cpu()
def with_cpu_forward(inputs, drop=0.0):
cpu_outputs, backprop = model.begin_update(_to_cpu(inputs), drop=drop)
gpu_outputs = _to_device(ops, cpu_outputs)
... | python | def with_cpu(ops, model):
"""Wrap a model that should run on CPU, transferring inputs and outputs
as necessary."""
model.to_cpu()
def with_cpu_forward(inputs, drop=0.0):
cpu_outputs, backprop = model.begin_update(_to_cpu(inputs), drop=drop)
gpu_outputs = _to_device(ops, cpu_outputs)
... | [
"def",
"with_cpu",
"(",
"ops",
",",
"model",
")",
":",
"model",
".",
"to_cpu",
"(",
")",
"def",
"with_cpu_forward",
"(",
"inputs",
",",
"drop",
"=",
"0.0",
")",
":",
"cpu_outputs",
",",
"backprop",
"=",
"model",
".",
"begin_update",
"(",
"_to_cpu",
"("... | Wrap a model that should run on CPU, transferring inputs and outputs
as necessary. | [
"Wrap",
"a",
"model",
"that",
"should",
"run",
"on",
"CPU",
"transferring",
"inputs",
"and",
"outputs",
"as",
"necessary",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/_ml.py#L84-L99 | train |
explosion/spaCy | spacy/_ml.py | build_simple_cnn_text_classifier | def build_simple_cnn_text_classifier(tok2vec, nr_class, exclusive_classes=False, **cfg):
"""
Build a simple CNN text classifier, given a token-to-vector model as inputs.
If exclusive_classes=True, a softmax non-linearity is applied, so that the
outputs sum to 1. If exclusive_classes=False, a logistic no... | python | def build_simple_cnn_text_classifier(tok2vec, nr_class, exclusive_classes=False, **cfg):
"""
Build a simple CNN text classifier, given a token-to-vector model as inputs.
If exclusive_classes=True, a softmax non-linearity is applied, so that the
outputs sum to 1. If exclusive_classes=False, a logistic no... | [
"def",
"build_simple_cnn_text_classifier",
"(",
"tok2vec",
",",
"nr_class",
",",
"exclusive_classes",
"=",
"False",
",",
"*",
"*",
"cfg",
")",
":",
"with",
"Model",
".",
"define_operators",
"(",
"{",
"\">>\"",
":",
"chain",
"}",
")",
":",
"if",
"exclusive_cl... | Build a simple CNN text classifier, given a token-to-vector model as inputs.
If exclusive_classes=True, a softmax non-linearity is applied, so that the
outputs sum to 1. If exclusive_classes=False, a logistic non-linearity
is applied instead, so that outputs are in the range [0, 1]. | [
"Build",
"a",
"simple",
"CNN",
"text",
"classifier",
"given",
"a",
"token",
"-",
"to",
"-",
"vector",
"model",
"as",
"inputs",
".",
"If",
"exclusive_classes",
"=",
"True",
"a",
"softmax",
"non",
"-",
"linearity",
"is",
"applied",
"so",
"that",
"the",
"ou... | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/_ml.py#L635-L652 | train |
explosion/spaCy | spacy/_ml.py | concatenate_lists | def concatenate_lists(*layers, **kwargs): # pragma: no cover
"""Compose two or more models `f`, `g`, etc, such that their outputs are
concatenated, i.e. `concatenate(f, g)(x)` computes `hstack(f(x), g(x))`
"""
if not layers:
return noop()
drop_factor = kwargs.get("drop_factor", 1.0)
ops... | python | def concatenate_lists(*layers, **kwargs): # pragma: no cover
"""Compose two or more models `f`, `g`, etc, such that their outputs are
concatenated, i.e. `concatenate(f, g)(x)` computes `hstack(f(x), g(x))`
"""
if not layers:
return noop()
drop_factor = kwargs.get("drop_factor", 1.0)
ops... | [
"def",
"concatenate_lists",
"(",
"*",
"layers",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"if",
"not",
"layers",
":",
"return",
"noop",
"(",
")",
"drop_factor",
"=",
"kwargs",
".",
"get",
"(",
"\"drop_factor\"",
",",
"1.0",
")",
"ops",
"="... | Compose two or more models `f`, `g`, etc, such that their outputs are
concatenated, i.e. `concatenate(f, g)(x)` computes `hstack(f(x), g(x))` | [
"Compose",
"two",
"or",
"more",
"models",
"f",
"g",
"etc",
"such",
"that",
"their",
"outputs",
"are",
"concatenated",
"i",
".",
"e",
".",
"concatenate",
"(",
"f",
"g",
")",
"(",
"x",
")",
"computes",
"hstack",
"(",
"f",
"(",
"x",
")",
"g",
"(",
"... | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/_ml.py#L667-L690 | train |
explosion/spaCy | spacy/_ml.py | masked_language_model | def masked_language_model(vocab, model, mask_prob=0.15):
"""Convert a model into a BERT-style masked language model"""
random_words = _RandomWords(vocab)
def mlm_forward(docs, drop=0.0):
mask, docs = _apply_mask(docs, random_words, mask_prob=mask_prob)
mask = model.ops.asarray(mask).reshap... | python | def masked_language_model(vocab, model, mask_prob=0.15):
"""Convert a model into a BERT-style masked language model"""
random_words = _RandomWords(vocab)
def mlm_forward(docs, drop=0.0):
mask, docs = _apply_mask(docs, random_words, mask_prob=mask_prob)
mask = model.ops.asarray(mask).reshap... | [
"def",
"masked_language_model",
"(",
"vocab",
",",
"model",
",",
"mask_prob",
"=",
"0.15",
")",
":",
"random_words",
"=",
"_RandomWords",
"(",
"vocab",
")",
"def",
"mlm_forward",
"(",
"docs",
",",
"drop",
"=",
"0.0",
")",
":",
"mask",
",",
"docs",
"=",
... | Convert a model into a BERT-style masked language model | [
"Convert",
"a",
"model",
"into",
"a",
"BERT",
"-",
"style",
"masked",
"language",
"model"
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/_ml.py#L693-L709 | train |
explosion/spaCy | spacy/pipeline/hooks.py | SimilarityHook.begin_training | def begin_training(self, _=tuple(), pipeline=None, sgd=None, **kwargs):
"""Allocate model, using width from tensorizer in pipeline.
gold_tuples (iterable): Gold-standard training data.
pipeline (list): The pipeline the model is part of.
"""
if self.model is True:
sel... | python | def begin_training(self, _=tuple(), pipeline=None, sgd=None, **kwargs):
"""Allocate model, using width from tensorizer in pipeline.
gold_tuples (iterable): Gold-standard training data.
pipeline (list): The pipeline the model is part of.
"""
if self.model is True:
sel... | [
"def",
"begin_training",
"(",
"self",
",",
"_",
"=",
"tuple",
"(",
")",
",",
"pipeline",
"=",
"None",
",",
"sgd",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"model",
"is",
"True",
":",
"self",
".",
"model",
"=",
"self",
... | Allocate model, using width from tensorizer in pipeline.
gold_tuples (iterable): Gold-standard training data.
pipeline (list): The pipeline the model is part of. | [
"Allocate",
"model",
"using",
"width",
"from",
"tensorizer",
"in",
"pipeline",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/pipeline/hooks.py#L89-L100 | train |
explosion/spaCy | spacy/displacy/render.py | DependencyRenderer.render | def render(self, parsed, page=False, minify=False):
"""Render complete markup.
parsed (list): Dependency parses to render.
page (bool): Render parses wrapped as full HTML page.
minify (bool): Minify HTML markup.
RETURNS (unicode): Rendered SVG or HTML markup.
"""
... | python | def render(self, parsed, page=False, minify=False):
"""Render complete markup.
parsed (list): Dependency parses to render.
page (bool): Render parses wrapped as full HTML page.
minify (bool): Minify HTML markup.
RETURNS (unicode): Rendered SVG or HTML markup.
"""
... | [
"def",
"render",
"(",
"self",
",",
"parsed",
",",
"page",
"=",
"False",
",",
"minify",
"=",
"False",
")",
":",
"# Create a random ID prefix to make sure parses don't receive the",
"# same ID, even if they're identical",
"id_prefix",
"=",
"uuid",
".",
"uuid4",
"(",
")"... | Render complete markup.
parsed (list): Dependency parses to render.
page (bool): Render parses wrapped as full HTML page.
minify (bool): Minify HTML markup.
RETURNS (unicode): Rendered SVG or HTML markup. | [
"Render",
"complete",
"markup",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/render.py#L39-L68 | train |
explosion/spaCy | spacy/displacy/render.py | DependencyRenderer.render_svg | def render_svg(self, render_id, words, arcs):
"""Render SVG.
render_id (int): Unique ID, typically index of document.
words (list): Individual words and their tags.
arcs (list): Individual arcs and their start, end, direction and label.
RETURNS (unicode): Rendered SVG markup.
... | python | def render_svg(self, render_id, words, arcs):
"""Render SVG.
render_id (int): Unique ID, typically index of document.
words (list): Individual words and their tags.
arcs (list): Individual arcs and their start, end, direction and label.
RETURNS (unicode): Rendered SVG markup.
... | [
"def",
"render_svg",
"(",
"self",
",",
"render_id",
",",
"words",
",",
"arcs",
")",
":",
"self",
".",
"levels",
"=",
"self",
".",
"get_levels",
"(",
"arcs",
")",
"self",
".",
"highest_level",
"=",
"len",
"(",
"self",
".",
"levels",
")",
"self",
".",
... | Render SVG.
render_id (int): Unique ID, typically index of document.
words (list): Individual words and their tags.
arcs (list): Individual arcs and their start, end, direction and label.
RETURNS (unicode): Rendered SVG markup. | [
"Render",
"SVG",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/render.py#L70-L100 | train |
explosion/spaCy | spacy/displacy/render.py | DependencyRenderer.render_word | def render_word(self, text, tag, i):
"""Render individual word.
text (unicode): Word text.
tag (unicode): Part-of-speech tag.
i (int): Unique ID, typically word index.
RETURNS (unicode): Rendered SVG markup.
"""
y = self.offset_y + self.word_spacing
x = s... | python | def render_word(self, text, tag, i):
"""Render individual word.
text (unicode): Word text.
tag (unicode): Part-of-speech tag.
i (int): Unique ID, typically word index.
RETURNS (unicode): Rendered SVG markup.
"""
y = self.offset_y + self.word_spacing
x = s... | [
"def",
"render_word",
"(",
"self",
",",
"text",
",",
"tag",
",",
"i",
")",
":",
"y",
"=",
"self",
".",
"offset_y",
"+",
"self",
".",
"word_spacing",
"x",
"=",
"self",
".",
"offset_x",
"+",
"i",
"*",
"self",
".",
"distance",
"if",
"self",
".",
"di... | Render individual word.
text (unicode): Word text.
tag (unicode): Part-of-speech tag.
i (int): Unique ID, typically word index.
RETURNS (unicode): Rendered SVG markup. | [
"Render",
"individual",
"word",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/render.py#L102-L115 | train |
explosion/spaCy | spacy/displacy/render.py | DependencyRenderer.render_arrow | def render_arrow(self, label, start, end, direction, i):
"""Render individual arrow.
label (unicode): Dependency label.
start (int): Index of start word.
end (int): Index of end word.
direction (unicode): Arrow direction, 'left' or 'right'.
i (int): Unique ID, typically ... | python | def render_arrow(self, label, start, end, direction, i):
"""Render individual arrow.
label (unicode): Dependency label.
start (int): Index of start word.
end (int): Index of end word.
direction (unicode): Arrow direction, 'left' or 'right'.
i (int): Unique ID, typically ... | [
"def",
"render_arrow",
"(",
"self",
",",
"label",
",",
"start",
",",
"end",
",",
"direction",
",",
"i",
")",
":",
"level",
"=",
"self",
".",
"levels",
".",
"index",
"(",
"end",
"-",
"start",
")",
"+",
"1",
"x_start",
"=",
"self",
".",
"offset_x",
... | Render individual arrow.
label (unicode): Dependency label.
start (int): Index of start word.
end (int): Index of end word.
direction (unicode): Arrow direction, 'left' or 'right'.
i (int): Unique ID, typically arrow index.
RETURNS (unicode): Rendered SVG markup. | [
"Render",
"individual",
"arrow",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/render.py#L117-L156 | train |
explosion/spaCy | spacy/displacy/render.py | DependencyRenderer.get_arc | def get_arc(self, x_start, y, y_curve, x_end):
"""Render individual arc.
x_start (int): X-coordinate of arrow start point.
y (int): Y-coordinate of arrow start and end point.
y_curve (int): Y-corrdinate of Cubic Bézier y_curve point.
x_end (int): X-coordinate of arrow end point.... | python | def get_arc(self, x_start, y, y_curve, x_end):
"""Render individual arc.
x_start (int): X-coordinate of arrow start point.
y (int): Y-coordinate of arrow start and end point.
y_curve (int): Y-corrdinate of Cubic Bézier y_curve point.
x_end (int): X-coordinate of arrow end point.... | [
"def",
"get_arc",
"(",
"self",
",",
"x_start",
",",
"y",
",",
"y_curve",
",",
"x_end",
")",
":",
"template",
"=",
"\"M{x},{y} C{x},{c} {e},{c} {e},{y}\"",
"if",
"self",
".",
"compact",
":",
"template",
"=",
"\"M{x},{y} {x},{c} {e},{c} {e},{y}\"",
"return",
"templa... | Render individual arc.
x_start (int): X-coordinate of arrow start point.
y (int): Y-coordinate of arrow start and end point.
y_curve (int): Y-corrdinate of Cubic Bézier y_curve point.
x_end (int): X-coordinate of arrow end point.
RETURNS (unicode): Definition of the arc path ('d... | [
"Render",
"individual",
"arc",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/render.py#L158-L170 | train |
explosion/spaCy | spacy/displacy/render.py | DependencyRenderer.get_arrowhead | def get_arrowhead(self, direction, x, y, end):
"""Render individual arrow head.
direction (unicode): Arrow direction, 'left' or 'right'.
x (int): X-coordinate of arrow start point.
y (int): Y-coordinate of arrow start and end point.
end (int): X-coordinate of arrow end point.
... | python | def get_arrowhead(self, direction, x, y, end):
"""Render individual arrow head.
direction (unicode): Arrow direction, 'left' or 'right'.
x (int): X-coordinate of arrow start point.
y (int): Y-coordinate of arrow start and end point.
end (int): X-coordinate of arrow end point.
... | [
"def",
"get_arrowhead",
"(",
"self",
",",
"direction",
",",
"x",
",",
"y",
",",
"end",
")",
":",
"if",
"direction",
"==",
"\"left\"",
":",
"pos1",
",",
"pos2",
",",
"pos3",
"=",
"(",
"x",
",",
"x",
"-",
"self",
".",
"arrow_width",
"+",
"2",
",",
... | Render individual arrow head.
direction (unicode): Arrow direction, 'left' or 'right'.
x (int): X-coordinate of arrow start point.
y (int): Y-coordinate of arrow start and end point.
end (int): X-coordinate of arrow end point.
RETURNS (unicode): Definition of the arrow head path... | [
"Render",
"individual",
"arrow",
"head",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/render.py#L172-L197 | train |
explosion/spaCy | spacy/displacy/render.py | DependencyRenderer.get_levels | def get_levels(self, arcs):
"""Calculate available arc height "levels".
Used to calculate arrow heights dynamically and without wasting space.
args (list): Individual arcs and their start, end, direction and label.
RETURNS (list): Arc levels sorted from lowest to highest.
"""
... | python | def get_levels(self, arcs):
"""Calculate available arc height "levels".
Used to calculate arrow heights dynamically and without wasting space.
args (list): Individual arcs and their start, end, direction and label.
RETURNS (list): Arc levels sorted from lowest to highest.
"""
... | [
"def",
"get_levels",
"(",
"self",
",",
"arcs",
")",
":",
"levels",
"=",
"set",
"(",
"map",
"(",
"lambda",
"arc",
":",
"arc",
"[",
"\"end\"",
"]",
"-",
"arc",
"[",
"\"start\"",
"]",
",",
"arcs",
")",
")",
"return",
"sorted",
"(",
"list",
"(",
"lev... | Calculate available arc height "levels".
Used to calculate arrow heights dynamically and without wasting space.
args (list): Individual arcs and their start, end, direction and label.
RETURNS (list): Arc levels sorted from lowest to highest. | [
"Calculate",
"available",
"arc",
"height",
"levels",
".",
"Used",
"to",
"calculate",
"arrow",
"heights",
"dynamically",
"and",
"without",
"wasting",
"space",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/render.py#L199-L207 | train |
explosion/spaCy | spacy/displacy/render.py | EntityRenderer.render | def render(self, parsed, page=False, minify=False):
"""Render complete markup.
parsed (list): Dependency parses to render.
page (bool): Render parses wrapped as full HTML page.
minify (bool): Minify HTML markup.
RETURNS (unicode): Rendered HTML markup.
"""
render... | python | def render(self, parsed, page=False, minify=False):
"""Render complete markup.
parsed (list): Dependency parses to render.
page (bool): Render parses wrapped as full HTML page.
minify (bool): Minify HTML markup.
RETURNS (unicode): Rendered HTML markup.
"""
render... | [
"def",
"render",
"(",
"self",
",",
"parsed",
",",
"page",
"=",
"False",
",",
"minify",
"=",
"False",
")",
":",
"rendered",
"=",
"[",
"]",
"for",
"i",
",",
"p",
"in",
"enumerate",
"(",
"parsed",
")",
":",
"if",
"i",
"==",
"0",
":",
"settings",
"... | Render complete markup.
parsed (list): Dependency parses to render.
page (bool): Render parses wrapped as full HTML page.
minify (bool): Minify HTML markup.
RETURNS (unicode): Rendered HTML markup. | [
"Render",
"complete",
"markup",
"."
] | 8ee4100f8ffb336886208a1ea827bf4c745e2709 | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/render.py#L247-L269 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.