spaCy/website
adrianeboyd faaa832518 Generalize handling of tokenizer special cases (#4259)
* Generalize handling of tokenizer special cases

Handle tokenizer special cases more generally by using the Matcher
internally to match special cases after the affix/token_match
tokenization is complete.

Instead of only matching special cases while processing balanced or
nearly balanced prefixes and suffixes, this recognizes special cases in
a wider range of contexts:

* Allows arbitrary numbers of prefixes/affixes around special cases
* Allows special cases separated by infixes

Existing tests/settings that couldn't be preserved as before:

* The emoticon '")' is no longer a supported special case
* The emoticon ':)' in "example:)" is a false positive again

When merged with #4258 (or the relevant cache bugfix), the affix and
token_match properties should be modified to flush and reload all
special cases to use the updated internal tokenization with the Matcher.

* Remove accidentally added test case

* Really remove accidentally added test

* Reload special cases when necessary

Reload special cases when affixes or token_match are modified. Skip
reloading during initialization.

* Update error code number

* Fix offset and whitespace in Matcher special cases

* Fix offset bugs when merging and splitting tokens
* Set final whitespace on final token in inserted special case

* Improve cache flushing in tokenizer

* Separate cache and specials memory (temporarily)
* Flush cache when adding special cases
* Repeated `self._cache = PreshMap()` and `self._specials = PreshMap()`
are necessary due to this bug:
https://github.com/explosion/preshed/issues/21

* Remove reinitialized PreshMaps on cache flush

* Update UD bin scripts

* Update imports for `bin/`
* Add all currently supported languages
* Update subtok merger for new Matcher validation
* Modify blinded check to look at tokens instead of lemmas (for corpora
with tokens but not lemmas like Telugu)

* Use special Matcher only for cases with affixes

* Reinsert specials cache checks during normal tokenization for special
cases as much as possible
  * Additionally include specials cache checks while splitting on infixes
  * Since the special Matcher needs consistent affix-only tokenization
    for the special cases themselves, introduce the argument
    `with_special_cases` in order to do tokenization with or without
    specials cache checks
* After normal tokenization, postprocess with special cases Matcher for
special cases containing affixes

* Replace PhraseMatcher with Aho-Corasick

Replace PhraseMatcher with the Aho-Corasick algorithm over numpy arrays
of the hash values for the relevant attribute. The implementation is
based on FlashText.

The speed should be similar to the previous PhraseMatcher. It is now
possible to easily remove match IDs and matches don't go missing with
large keyword lists / vocabularies.

Fixes #4308.

* Restore support for pickling

* Fix internal keyword add/remove for numpy arrays

* Add test for #4248, clean up test

* Improve efficiency of special cases handling

* Use PhraseMatcher instead of Matcher
* Improve efficiency of merging/splitting special cases in document
  * Process merge/splits in one pass without repeated token shifting
  * Merge in place if no splits

* Update error message number

* Remove UD script modifications

Only used for timing/testing, should be a separate PR

* Remove final traces of UD script modifications

* Update UD bin scripts

* Update imports for `bin/`
* Add all currently supported languages
* Update subtok merger for new Matcher validation
* Modify blinded check to look at tokens instead of lemmas (for corpora
with tokens but not lemmas like Telugu)

* Add missing loop for match ID set in search loop

* Remove cruft in matching loop for partial matches

There was a bit of unnecessary code left over from FlashText in the
matching loop to handle partial token matches, which we don't have with
PhraseMatcher.

* Replace dict trie with MapStruct trie

* Fix how match ID hash is stored/added

* Update fix for match ID vocab

* Switch from map_get_unless_missing to map_get

* Switch from numpy array to Token.get_struct_attr

Access token attributes directly in Doc instead of making a copy of the
relevant values in a numpy array.

Add unsatisfactory warning for hash collision with reserved terminal
hash key. (Ideally it would change the reserved terminal hash and redo
the whole trie, but for now, I'm hoping there won't be collisions.)

* Restructure imports to export find_matches

* Implement full remove()

Remove unnecessary trie paths and free unused maps.

Parallel to Matcher, raise KeyError when attempting to remove a match ID
that has not been added.

* Switch to PhraseMatcher.find_matches

* Switch to local cdef functions for span filtering

* Switch special case reload threshold to variable

Refer to variable instead of hard-coded threshold

* Move more of special case retokenize to cdef nogil

Move as much of the special case retokenization to nogil as possible.

* Rewrap sort as stdsort for OS X

* Rewrap stdsort with specific types

* Switch to qsort

* Fix merge

* Improve cmp functions

* Fix realloc

* Fix realloc again

* Initialize span struct while retokenizing

* Temporarily skip retokenizing

* Revert "Move more of special case retokenize to cdef nogil"

This reverts commit 0b7e52c797.

* Revert "Switch to qsort"

This reverts commit a98d71a942.

* Fix specials check while caching

* Modify URL test with emoticons

The multiple suffix tests result in the emoticon `:>`, which is now
retokenized into one token as a special case after the suffixes are
split off.

* Refactor _apply_special_cases()

* Use cdef ints for span info used in multiple spots

* Modify _filter_special_spans() to prefer earlier

Parallel to #4414, modify _filter_special_spans() so that the earlier
span is preferred for overlapping spans of the same length.

* Replace MatchStruct with Entity

Replace MatchStruct with Entity since the existing Entity struct is
nearly identical.

* Replace Entity with more general SpanC

* Replace MatchStruct with SpanC

* Add error in debug-data if no dev docs are available (see #4575)

* Update azure-pipelines.yml

* Revert "Update azure-pipelines.yml"

This reverts commit ed1060cf59.

* Use latest wasabi

* Reorganise install_requires

* add dframcy to universe.json (#4580)

* Update universe.json [ci skip]

* Fix multiprocessing for as_tuples=True (#4582)

* Fix conllu script (#4579)

* force extensions to avoid clash between example scripts

* fix arg order and default file encoding

* add example config for conllu script

* newline

* move extension definitions to main function

* few more encodings fixes

* Add load_from_docbin example [ci skip]

TODO: upload the file somewhere

* Update README.md

* Add warnings about 3.8 (resolves #4593) [ci skip]

* Fixed typo: Added space between "recognize" and "various" (#4600)

* Fix DocBin.merge() example (#4599)

* Replace function registries with catalogue (#4584)

* Replace functions registries with catalogue

* Update __init__.py

* Fix test

* Revert unrelated flag [ci skip]

* Bugfix/dep matcher issue 4590 (#4601)

* add contributor agreement for prilopes

* add test for issue #4590

* fix on_match params for DependencyMacther (#4590)

* Minor updates to language example sentences (#4608)

* Add punctuation to Spanish example sentences

* Combine multilanguage examples for lang xx

* Add punctuation to nb examples

* Always realloc to a larger size

Avoid potential (unlikely) edge case and cymem error seen in #4604.

* Add error in debug-data if no dev docs are available (see #4575)

* Update debug-data for GoldCorpus / Example

* Ignore None label in misaligned NER data
2019-11-13 21:24:35 +01:00
..
docs Generalize handling of tokenizer special cases (#4259) 2019-11-13 21:24:35 +01:00
meta Generalize handling of tokenizer special cases (#4259) 2019-11-13 21:24:35 +01:00
src Only show label scheme if not empty [ci skip] 2019-10-08 15:52:59 +02:00
.eslintrc Tidy up website and add eslint config [ci skip] 2019-03-12 15:21:58 +01:00
.prettierrc 💫 Update website (#3285) 2019-02-17 19:31:19 +01:00
gatsby-browser.js Merge branch 'spacy.io' into develop [ci skip] 2019-02-26 16:51:22 +01:00
gatsby-config.js 💫 Update website (#3285) 2019-02-17 19:31:19 +01:00
gatsby-node.js Fix met a description in universe projects [ci skip] 2019-03-28 15:26:01 +01:00
package-lock.json Tidy up website and add eslint config [ci skip] 2019-03-12 15:21:58 +01:00
package.json Don't auto-slugify accordion links [ci skip] 2019-03-12 15:30:49 +01:00
README.md Remove u-strings and fix formatting [ci skip] 2019-09-12 16:11:15 +02:00
UNIVERSE.md Update UNIVERSE.md 2019-06-01 16:37:06 +02:00

spacy.io website and docs

Netlify Status

This page contains the documentation and styleguide for the spaCy website. Its rendered version is available at https://spacy.io/styleguide.


The spacy.io website is implemented using Gatsby with Remark and MDX. This allows authoring content in straightforward Markdown without the usual limitations. Standard elements can be overwritten with powerful React components and wherever Markdown syntax isn't enough, JSX components can be used.

Contributing to the site

The docs can always use another example or more detail, and they should always be up to date and not misleading. We always appreciate a pull request. To quickly find the correct file to edit, simply click on the "Suggest edits" button at the bottom of a page.

For more details on editing the site locally, see the installation instructions and markdown reference below.

import { Logos } from 'widgets/styleguide'

If you would like to use the spaCy logo on your site, please get in touch and ask us first. However, if you want to show support and tell others that your project is using spaCy, you can grab one of our spaCy badges.

Colors

import { Colors, Patterns } from 'widgets/styleguide'

Patterns

Typography

import { H1, H2, H3, H4, H5, Label, InlineList, Comment } from 'components/typography'

Markdown

## Headline 2
## Headline 2 {#some_id}
## Headline 2 {#some_id tag="method"}

JSX

<H2>Headline 2</H2>
<H2 id="some_id">Headline 2</H2>
<H2 id="some_id" tag="method">Headline 2</H2>

Headlines are set in HK Grotesk by Hanken Design. All other body text and code uses the best-matching default system font to provide a "native" reading experience.

Level 2 headings are automatically wrapped in <section> elements at compile time, using a custom Markdown transformer. This makes it easier to highlight the section that's currently in the viewpoint in the sidebar menu.

Headline 1

Headline 2

Headline 3

Headline 4

Headline 5
Label

The following optional attributes can be set on the headline to modify it. For example, to add a tag for the documented type or mark features that have been introduced in a specific version or require statistical models to be loaded. Tags are also available as standalone <Tag /> components.

Argument Example Result
tag {tag="method"} method
new {new="2"} 2
model {model="tagger, parser"} tagger, parser
hidden {hidden="true"}

Elements

Markdown

[I am a link](https://spacy.io)

JSX

<Link to="https://spacy.io">I am a link</Link>

Special link styles are used depending on the link URL.

Abbreviations

import { Abbr } from 'components/typography'

JSX

<Abbr title="Explanation">Abbreviation</Abbr>

Some text with an abbreviation. On small screens, I collapse and the explanation text is displayed next to the abbreviation.

Tags

import Tag from 'components/tag'

<Tag>method</Tag>
<Tag variant="new">2.1</Tag>
<Tag variant="model">tagger, parser</Tag>

Tags can be used together with headlines, or next to properties across the documentation, and combined with tooltips to provide additional information. An optional variant argument can be used for special tags. variant="new" makes the tag take a version number to mark new features. Using the component, visibility of this tag can later be toggled once the feature isn't considered new anymore. Setting variant="model" takes a description of model capabilities and can be used to mark features that require a respective model to be installed.

method 2 tagger, parser

Buttons

import Button from 'components/button'

<Button to="#" variant="primary">Primary small</Button>
<Button to="#" variant="secondary">Secondary small</Button>

Link buttons come in two variants, primary and secondary and two sizes, with an optional large size modifier. Since they're mostly used as enhanced links, the buttons are implemented as styled links instead of native button elements.

Primary small Secondary small

Primary large Secondary large

Components

Table

Markdown

| Header 1 | Header 2 |
| --- | --- |
| Column 1 | Column 2 |

JSX

<Table>
    <Tr><Th>Header 1</Th><Th>Header 2</Th></Tr></thead>
    <Tr><Td>Column 1</Td><Td>Column 2</Td></Tr>
</Table>

Tables are used to present data and API documentation. Certain keywords can be used to mark a footer row with a distinct style, for example to visualise the return values of a documented function.

Header 1 Header 2 Header 3 Header 4
Column 1 Column 2 Column 3 Column 4
Column 1 Column 2 Column 3 Column 4
Column 1 Column 2 Column 3 Column 4
Column 1 Column 2 Column 3 Column 4
RETURNS Column 2 Column 3 Column 4

List

Markdown

1. One
2. Two

JSX

<Ol>
    <Li>One</Li>
    <Li>Two</Li>
</Ol>

Lists are available as bulleted and numbered. Markdown lists are transformed automatically.

  • I am a bulleted list
  • I have nice bullets
  • Lorem ipsum dolor
  • consectetur adipiscing elit
  1. I am an ordered list
  2. I have nice numbers
  3. Lorem ipsum dolor
  4. consectetur adipiscing elit

Aside

Markdown

> #### Aside title
> This is aside text.

JSX

<Aside title="Aside title">This is aside text.</Aside>

Asides can be used to display additional notes and content in the right-hand column. Asides can contain text, code and other elements if needed. Visually, asides are moved to the side on the X-axis, and displayed at the same level they were inserted. On small screens, they collapse and are rendered in their original position, in between the text.

To make them easier to use in Markdown, paragraphs formatted as blockquotes will turn into asides by default. Level 4 headlines (with a leading ####) will become aside titles.

Code Block

Markdown

```python
### This is a title
import spacy
```

JSX

<CodeBlock title="This is a title" lang="python">
  import spacy
</CodeBlock>

Code blocks use the Prism syntax highlighter with a custom theme. The language can be set individually on each block, and defaults to raw text with no highlighting. An optional label can be added as the first line with the prefix #### (Python-like) and /// (JavaScript-like). the indented block as plain text and preserve whitespace.

### Using spaCy
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("This is a sentence.")
for token in doc:
    print(token.text, token.pos_)

Code blocks and also specify an optional range of line numbers to highlight by adding {highlight="..."} to the headline. Acceptable ranges are spans like 5-7, but also 5-7,10 or 5-7,10,13-14.

Markdown

```python
### This is a title {highlight="1-2"}
import spacy
nlp = spacy.load("en_core_web_sm")
```
### Using the matcher {highlight="5-7"}
import spacy
from spacy.matcher import Matcher

nlp = spacy.load('en_core_web_sm')
matcher = Matcher(nlp.vocab)
pattern = [{"LOWER": "hello"}, {"IS_PUNCT": True}, {"LOWER": "world"}]
matcher.add("HelloWorld", None, pattern)
doc = nlp("Hello, world! Hello world!")
matches = matcher(doc)

Adding {executable="true"} to the title turns the code into an executable block, powered by Binder and Juniper. If JavaScript is disabled, the interactive widget defaults to a regular code block.

Markdown

```python
### {executable="true"}
import spacy
nlp = spacy.load("en_core_web_sm")
```
### {executable="true"}
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("This is a sentence.")
for token in doc:
    print(token.text, token.pos_)

If a code block only contains a URL to a GitHub file, the raw file contents are embedded automatically and syntax highlighting is applied. The link to the original file is shown at the top of the widget.

Markdown

```python
https://github.com/...
```

JSX

<GitHubCode url="https://github.com/..." lang="python" />
https://github.com/explosion/spaCy/tree/master/examples/pipeline/custom_component_countries_api.py

Infobox

import Infobox from 'components/infobox'

JSX

<Infobox title="Information">Regular infobox</Infobox>
<Infobox title="Important note" variant="warning">This is a warning.</Infobox>
<Infobox title="Be careful!" variant="danger">This is dangerous.</Infobox>

Infoboxes can be used to add notes, updates, warnings or additional information to a page or section. Semantically, they're implemented and interpreted as an aside element. Infoboxes can take an optional title argument, as well as an optional variant (either "warning" or "danger").

If needed, an infobox can contain regular text, inline code, lists and other blocks.

If needed, an infobox can contain regular text, inline code, lists and other blocks.

If needed, an infobox can contain regular text, inline code, lists and other blocks.

Accordion

import Accordion from 'components/accordion'

JSX

<Accordion title="This is an accordion">
  Accordion content goes here.
</Accordion>

Accordions are collapsible sections that are mostly used for lengthy tables, like the tag and label annotation schemes for different languages. They all need to be presented but chances are the user doesn't actually care about all of them, especially not at the same time. So it's fairly reasonable to hide them begin a click. This particular implementation was inspired by the amazing Inclusive Components blog.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque enim ante, pretium a orci eget, varius dignissim augue. Nam eu dictum mauris, id tincidunt nisi. Integer commodo pellentesque tincidunt. Nam at turpis finibus tortor gravida sodales tincidunt sit amet est. Nullam euismod arcu in tortor auctor, sit amet dignissim justo congue.

Setup and installation

Before running the setup, make sure your versions of Node and npm are up to date. Node v10.15 or later is required.

# Clone the repository
git clone https://github.com/explosion/spaCy
cd spaCy/website

# Install Gatsby's command-line tool
npm install --global gatsby-cli

# Install the dependencies
npm install

# Start the development server
npm run dev

If you are planning on making edits to the site, you should also set up the Prettier code formatter. It takes care of formatting Markdown and other files automatically. See here for the available extensions for your code editor. The .prettierrc file in the root defines the settings used in this codebase.

Markdown reference

All page content and page meta lives in the .md files in the /docs directory. The frontmatter block at the top of each file defines the page title and other settings like the sidebar menu.

---
title: Page title
---

## Headline starting a section {#some_id}

This is a regular paragraph with a [link](https://spacy.io) and **bold text**.

> #### This is an aside title
>
> This is aside text.

### Subheadline

| Header 1 | Header 2 |
| -------- | -------- |
| Column 1 | Column 2 |

```python
### Code block title {highlight="2-3"}
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("Hello world")
```

<Infobox title="Important note" variant="warning">

This is content in the infobox.

</Infobox>

In addition to the native markdown elements, you can use the components <Infobox />, <Accordion />, <Abbr /> and <Tag /> via their JSX syntax.

Project structure

### Directory structure
├── docs                 # the actual markdown content
├── meta                 # JSON-formatted site metadata
|   ├── languages.json   # supported languages and statistical models
|   ├── logos.json       # logos and links for landing page
|   ├── sidebars.json    # sidebar navigations for different sections
|   ├── site.json        # general site metadata
|   └── universe.json    # data for the spaCy universe section
├── public               # compiled site
├── src                  # source
|   ├── components       # React components
|   ├── fonts            # webfonts
|   ├── images           # images used in the layout
|   ├── plugins          # custom plugins to transform Markdown
|   ├── styles           # CSS modules and global styles
|   ├── templates        # page layouts
|   |   ├── docs.js      # layout template for documentation pages
|   |   ├── index.js     # global layout template
|   |   ├── models.js    # layout template for model pages
|   |   └── universe.js  # layout templates for universe
|   └── widgets          # non-reusable components with content, e.g. changelog
├── gatsby-browser.js    # browser-specific hooks for Gatsby
├── gatsby-config.js     # Gatsby configuration
├── gatsby-node.js       # Node-specific hooks for Gatsby
└── package.json         # package settings and dependencies