Skip to content

Latest commit

 

History

History
275 lines (213 loc) · 12.2 KB

README.md

File metadata and controls

275 lines (213 loc) · 12.2 KB

LIMA python bindings

Downloads

Introducing LIMA

LIMA is a multilingual linguistic analyzer developed by the CEA LIST, LASTI laboratory (French acronym for Text and Image Semantic Analysis Laboratory). LIMA is Free Software, available under the MIT license.

LIMA has state of the art performance for more than 60 languages thanks to its recent deep learning (neural network) based modules. But it includes also a very powerful rules based mechanism called ModEx allowing to quickly extract information (entities, relations, events…) in new domains where annotated data does not exist.

For more information, detailed installation instructions and documentation, please refer to the LIMA documentation.

Installation

LIMA python bindings are available under Linux (x86_64), Windows (x64) and macOS (Apple Silicon).

With Python >= 3.9 (>= 3.10 on Windows and macOS) and an upgraded pip, which picks the right one of the wheels of each release:

Wheel Qt Python Systems
manylinux_2_34 6.12 3.10 to 3.15 Linux, glibc >= 2.34 (Ubuntu 22.04+, Debian 12+, RHEL 9+...)
manylinux_2_28 6.9 3.9 to 3.13 Linux, glibc >= 2.28 (older systems, and Python 3.9)
win_amd64 6.12 3.10 and later Windows 10/11 x64
macosx_15_0_arm64 6.12 3.10 and later macOS >= 15 on Apple Silicon
# Upgrading pip is fundamental in order to obtain the correct LIMA version
$ pip install --upgrade pip
$ pip install aymara
$ lima_models -i eng
# Either simply use the lima command to produce an analysis of a file in CoNLLU format:
$ lima <path to the file to analyse>
# Or use the python API:
$ python
>>> import aymara.lima
>>> nlp = aymara.lima.Lima("ud-eng")
>>> doc = nlp('Hello, World!')
>>> print(doc[0].lemma)
hello
>>> print(repr(doc))
1       Hello   hello   INTJ    _       _               0       root    _       Pos=0|Len=5
2       ,       ,       PUNCT   _       _               1       punct   _       Pos=5|Len=1
3       World   World   PROPN   _       Number:Sing     1       vocative        _       Pos=7|Len=5
4       !       !       PUNCT   _       _               1       punct   _       Pos=12|Len=1
>>> doc.save_conllu("hello.conllu")   # with the "# sent_id" and "# text" comments

lima_models -i eng installs the default English model, which aymara.lima.Lima("ud-eng") then uses (lima_models -a lists the languages and models available). Check the language models documentation for more information about using these models.

Running

$ lima <utf-8 text file to analyze>
# OR
$ python
>>> import aymara.lima
>>> l = aymara.lima.Lima("ud-eng")
>>> r = l.analyzeText("The author wrote a novel.", lang="ud-eng")
>>> print(r)
# sent_id = 1
# text = The author wrote a novel.
1       The     the     DET     _       Definite=Def|PronType=Art       2       det     _       Len=3|Pos=1
2       author  author  NOUN    _       Number=Sing     3       nsubj   _       Len=6|Pos=5
3       wrote   write   VERB    _       Mood=Ind|Tense=Past|VerbForm=Fin        0       root    _       Len=5|Pos=12
4       a       a       DET     _       Definite=Ind|PronType=Art       5       det     _       Len=1|Pos=18
5       novel   novel   NOUN    _       Number=Sing     3       obj     _       Len=5|Pos=20|SpaceAfter=No
6       .       .       PUNCT   _       _       3       punct   _       Len=1|Pos=25

>>>

Note that some error messages could be displayed during the Lima object instantiation. If you get a valid result, you can ignore them. Most of them are debug messages that will be removed in a later version.

Create a Lima analyzer once and reuse it: initialization loads the models, and an analyzer with a neural pipeline (deepud) uses about 3 GB of memory. Since aymara 0.8.0, deleting the last analyzer of a language frees its models (up to 0.7.1, this memory was never freed: avoid creating several analyzers in one process with these versions).

For French, use ud-fra (after lima_models -i fra). The deepud pipeline of ud-eng and ud-fra also recognizes named entities (persons, locations, organizations, dates, amounts...), available as doc.ents:

>>> nlp = aymara.lima.Lima("ud-fra")
>>> doc = nlp("Jean Dupont a visité Paris le 12 janvier 2021.")
>>> [(ent.text, ent.label) for ent in doc.ents]

The legacy rule-based languages eng, fre and por and their pipelines (main...) are deprecated and no longer distributed: these names now select ud-eng, ud-fra and ud-por and the deepud pipeline, with a DeprecationWarning.

Matching phrases

Since aymara 0.10.0, aymara.lima.PhraseMatcher follows spaCy's PhraseMatcher API, on LIMA's ModEx rules: the patterns are compiled into rules that the analyzer applies itself (before its named entities rules), so the documents must be analyzed after the patterns are added:

import aymara.lima
nlp = aymara.lima.Lima("ud-eng")
# attr: "ORTH" (default), "LOWER", "LEMMA" or "POS"
matcher = aymara.lima.PhraseMatcher(nlp)
matcher.add("OBAMA", [nlp("Barack Obama")])       # or ["Barack Obama"]
doc = nlp("Barack Obama lifts America one last time in emotional farewell")
print(matcher(doc))                               # [('OBAMA', 0, 2)]

matcher(doc, as_spans=True) gives the matches as spans labelled with their keys. matcher.remove(key) removes the patterns of a key, and add(key, patterns, on_match=callback) calls callback(matcher, doc, i, matches) for each match.

The differences with spaCy:

  • the matcher is created with the analyzer (nlp), not its vocabulary, and only the documents analyzed after add contain matches (adding the first pattern makes nlp use a new pipeline, with the matcher);
  • the match ids are the keys, not their hashes;
  • the matches do not overlap: the longest one starting first is kept;
  • the matches are entities of the document (in doc.ents, labelled PhraseMatcher<n>_<k>.<KEY>); the named entities rules may include one in a larger entity (e.g. Paris in a Location.CITY), which then hides it in doc.ents, but matcher(doc) still finds it;
  • LOWER matches the original, lowercase, uppercase, capitalized and title forms of the pattern's words; LEMMA matches their lemmas and parts of speech (take the patterns in sentences, so that their words get the POS they have in the texts).

Compiling ModEx rules

Lima.compile_rules compiles ModEx rules, as LIMA's compile-rules tool does. The rules can come from a string or a file. It saves the compiled rules (a .bin file, for the given language) and, optionally, the rules themselves. Lima.add_rules makes an analyzer apply a .bin file (or a text rules file) before its named entities rules. The documents analyzed afterwards contain the rules' entities in doc.ents:

import aymara.lima
nlp = aymara.lima.Lima("ud-eng")
rules = """set encoding=utf8
using groups Software
set defaultAction=>CreateSpecificEntity()
Python:::Software.PROGRAM:
"""
# or rules_file="software.rules"
nlp.compile_rules("software.bin", rules=rules, save_rules="software.rules",
                  entity_types=["Software.PROGRAM"])

# Later, possibly in another process
nlp.add_rules("software.bin", entity_types=["Software.PROGRAM"])
print(nlp("Python analyzes texts.").ents)

entity_types declares the entity types that the LIMA configuration does not know yet. The types of a group are declared all at once. Instead of entity_types, modex takes a ModEx configuration, as a file or as its XML content (like the --modex option of compile-rules). Its entities module gives the types, and the SpecificEntitiesMicros of its resources-<lang> module give the micro-categories (the default is PROPN). It can also be a file of the LIMA configuration, e.g. Product-modex.xml, to compile rules for the Product group. When the rules come from a string, their includes are searched for next to save_rules. The .bin file can also be used as the rules of an AutomatonRecognizer resource in a LIMA configuration. There, its path is relative to a resources directory (e.g. the user_resources_path of Lima).

Python bindings API documentation

The Lima python API documentation is part of the LIMA documentation, along with a user guide for Python.

Configuration and customization

To configure finely LIMA for your needs, follow the same instructions as for the native C++ tools, described in Configuring LIMA.

PySide LIMA python bindings build and deploy instructions

Building the wheel

The CI (.github/workflows/build-qt6.yml) builds the four wheels. The Linux ones on the LIMA images of the same configuration (built by aymara/lima's own build-qt6.yml):

  • manylinux_2_28, Qt 6.9.3, built with Python 3.9 (cp39-abi3), tested on Python 3.9 and 3.13;
  • manylinux_2_34, Qt 6.12.0, built with Python 3.10 (cp310-abi3), tested on Python 3.10 and 3.15.

The Windows and macOS ones against the LIMA packages of aymara/lima's build-win.yml and build-macos.yml (its continuous prerelease), with scripts/build-wheel-windows.ps1 and scripts/build-wheel-macos.sh:

  • win_amd64, Qt 6.12.0, built with Python 3.10 (cp310-abi3), tested on Python 3.10 and 3.13;
  • macosx_15_0_arm64, Qt 6.12.0, built with Python 3.10 (cp310-abi3), tested on Python 3.10 and 3.13.

The wheels of the master branch are published in the continuous prerelease.

To build the manylinux_2_28 wheel locally, with Docker:

./gbuild-manylinux_2_28.sh

Releasing

The version is in aymara/version.py (and the [tool.bumpver] section of pyproject.toml), and is changed with bumpver:

  1. Give the new version its section in CHANGES.md (merged on master): its first section is the release notes.
  2. On an up-to-date master, bumpver update --minor (or --patch, --major; --dry to see the changes first) updates the version, commits, tags it (e.g. 0.8.0; releases up to 0.7.1 were tagged v0.7.1) and pushes.
  3. The tag makes the CI build and test the four wheels and publish them to PyPI and as a GitHub release. The tag must match aymara/version.py.

Developer Notes

To see the wheels accepted on current system:

>>> from packaging.tags import sys_tags
>>> [str(t) for t in sys_tags()]

See:

License notes

Some part of this API are largely inspired by the spaCy one and some text of the documentation are reproduced from the spaCy documentation. spaCy is also released under the MIT license. We thus reproduce its copyright notice below:

The MIT License (MIT)

Copyright (C) 2016-2022 ExplosionAI GmbH, 2016 spaCy GmbH, 2015 Matthew Honnibal

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.