Metadata-Version: 2.3
Name: dkpro-cassis
Version: 0.12.0
Summary: UIMA CAS processing library in Python
Keywords: 
Author: The DKPro cassis team
License:                                  Apache License
                                    Version 2.0, January 2004
                                 http://www.apache.org/licenses/
         
            TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
         
            1. Definitions.
         
               "License" shall mean the terms and conditions for use, reproduction,
               and distribution as defined by Sections 1 through 9 of this document.
         
               "Licensor" shall mean the copyright owner or entity authorized by
               the copyright owner that is granting the License.
         
               "Legal Entity" shall mean the union of the acting entity and all
               other entities that control, are controlled by, or are under common
               control with that entity. For the purposes of this definition,
               "control" means (i) the power, direct or indirect, to cause the
               direction or management of such entity, whether by contract or
               otherwise, or (ii) ownership of fifty percent (50%) or more of the
               outstanding shares, or (iii) beneficial ownership of such entity.
         
               "You" (or "Your") shall mean an individual or Legal Entity
               exercising permissions granted by this License.
         
               "Source" form shall mean the preferred form for making modifications,
               including but not limited to software source code, documentation
               source, and configuration files.
         
               "Object" form shall mean any form resulting from mechanical
               transformation or translation of a Source form, including but
               not limited to compiled object code, generated documentation,
               and conversions to other media types.
         
               "Work" shall mean the work of authorship, whether in Source or
               Object form, made available under the License, as indicated by a
               copyright notice that is included in or attached to the work
               (an example is provided in the Appendix below).
         
               "Derivative Works" shall mean any work, whether in Source or Object
               form, that is based on (or derived from) the Work and for which the
               editorial revisions, annotations, elaborations, or other modifications
               represent, as a whole, an original work of authorship. For the purposes
               of this License, Derivative Works shall not include works that remain
               separable from, or merely link (or bind by name) to the interfaces of,
               the Work and Derivative Works thereof.
         
               "Contribution" shall mean any work of authorship, including
               the original version of the Work and any modifications or additions
               to that Work or Derivative Works thereof, that is intentionally
               submitted to Licensor for inclusion in the Work by the copyright owner
               or by an individual or Legal Entity authorized to submit on behalf of
               the copyright owner. For the purposes of this definition, "submitted"
               means any form of electronic, verbal, or written communication sent
               to the Licensor or its representatives, including but not limited to
               communication on electronic mailing lists, source code control systems,
               and issue tracking systems that are managed by, or on behalf of, the
               Licensor for the purpose of discussing and improving the Work, but
               excluding communication that is conspicuously marked or otherwise
               designated in writing by the copyright owner as "Not a Contribution."
         
               "Contributor" shall mean Licensor and any individual or Legal Entity
               on behalf of whom a Contribution has been received by Licensor and
               subsequently incorporated within the Work.
         
            2. Grant of Copyright License. Subject to the terms and conditions of
               this License, each Contributor hereby grants to You a perpetual,
               worldwide, non-exclusive, no-charge, royalty-free, irrevocable
               copyright license to reproduce, prepare Derivative Works of,
               publicly display, publicly perform, sublicense, and distribute the
               Work and such Derivative Works in Source or Object form.
         
            3. Grant of Patent License. Subject to the terms and conditions of
               this License, each Contributor hereby grants to You a perpetual,
               worldwide, non-exclusive, no-charge, royalty-free, irrevocable
               (except as stated in this section) patent license to make, have made,
               use, offer to sell, sell, import, and otherwise transfer the Work,
               where such license applies only to those patent claims licensable
               by such Contributor that are necessarily infringed by their
               Contribution(s) alone or by combination of their Contribution(s)
               with the Work to which such Contribution(s) was submitted. If You
               institute patent litigation against any entity (including a
               cross-claim or counterclaim in a lawsuit) alleging that the Work
               or a Contribution incorporated within the Work constitutes direct
               or contributory patent infringement, then any patent licenses
               granted to You under this License for that Work shall terminate
               as of the date such litigation is filed.
         
            4. Redistribution. You may reproduce and distribute copies of the
               Work or Derivative Works thereof in any medium, with or without
               modifications, and in Source or Object form, provided that You
               meet the following conditions:
         
               (a) You must give any other recipients of the Work or
                   Derivative Works a copy of this License; and
         
               (b) You must cause any modified files to carry prominent notices
                   stating that You changed the files; and
         
               (c) You must retain, in the Source form of any Derivative Works
                   that You distribute, all copyright, patent, trademark, and
                   attribution notices from the Source form of the Work,
                   excluding those notices that do not pertain to any part of
                   the Derivative Works; and
         
               (d) If the Work includes a "NOTICE" text file as part of its
                   distribution, then any Derivative Works that You distribute must
                   include a readable copy of the attribution notices contained
                   within such NOTICE file, excluding those notices that do not
                   pertain to any part of the Derivative Works, in at least one
                   of the following places: within a NOTICE text file distributed
                   as part of the Derivative Works; within the Source form or
                   documentation, if provided along with the Derivative Works; or,
                   within a display generated by the Derivative Works, if and
                   wherever such third-party notices normally appear. The contents
                   of the NOTICE file are for informational purposes only and
                   do not modify the License. You may add Your own attribution
                   notices within Derivative Works that You distribute, alongside
                   or as an addendum to the NOTICE text from the Work, provided
                   that such additional attribution notices cannot be construed
                   as modifying the License.
         
               You may add Your own copyright statement to Your modifications and
               may provide additional or different license terms and conditions
               for use, reproduction, or distribution of Your modifications, or
               for any such Derivative Works as a whole, provided Your use,
               reproduction, and distribution of the Work otherwise complies with
               the conditions stated in this License.
         
            5. Submission of Contributions. Unless You explicitly state otherwise,
               any Contribution intentionally submitted for inclusion in the Work
               by You to the Licensor shall be under the terms and conditions of
               this License, without any additional terms or conditions.
               Notwithstanding the above, nothing herein shall supersede or modify
               the terms of any separate license agreement you may have executed
               with Licensor regarding such Contributions.
         
            6. Trademarks. This License does not grant permission to use the trade
               names, trademarks, service marks, or product names of the Licensor,
               except as required for reasonable and customary use in describing the
               origin of the Work and reproducing the content of the NOTICE file.
         
            7. Disclaimer of Warranty. Unless required by applicable law or
               agreed to in writing, Licensor provides the Work (and each
               Contributor provides its Contributions) on an "AS IS" BASIS,
               WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
               implied, including, without limitation, any warranties or conditions
               of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
               PARTICULAR PURPOSE. You are solely responsible for determining the
               appropriateness of using or redistributing the Work and assume any
               risks associated with Your exercise of permissions under this License.
         
            8. Limitation of Liability. In no event and under no legal theory,
               whether in tort (including negligence), contract, or otherwise,
               unless required by applicable law (such as deliberate and grossly
               negligent acts) or agreed to in writing, shall any Contributor be
               liable to You for damages, including any direct, indirect, special,
               incidental, or consequential damages of any character arising as a
               result of this License or out of the use or inability to use the
               Work (including but not limited to damages for loss of goodwill,
               work stoppage, computer failure or malfunction, or any and all
               other commercial damages or losses), even if such Contributor
               has been advised of the possibility of such damages.
         
            9. Accepting Warranty or Additional Liability. While redistributing
               the Work or Derivative Works thereof, You may choose to offer,
               and charge a fee for, acceptance of support, warranty, indemnity,
               or other liability obligations and/or rights consistent with this
               License. However, in accepting such obligations, You may act only
               on Your own behalf and on Your sole responsibility, not on behalf
               of any other Contributor, and only if You agree to indemnify,
               defend, and hold each Contributor harmless for any liability
               incurred by, or claims asserted against, such Contributor by reason
               of your accepting any such warranty or additional liability.
         
            END OF TERMS AND CONDITIONS
         
            APPENDIX: How to apply the Apache License to your work.
         
               To apply the Apache License to your work, attach the following
               boilerplate notice, with the fields enclosed by brackets "[]"
               replaced with your own identifying information. (Don't include
               the brackets!)  The text should be enclosed in the appropriate
               comment syntax for the file format. We also recommend that a
               file or class name and description of purpose be included on the
               same "printed page" as the copyright notice for easier
               identification within third-party archives.
         
            Copyright [yyyy] [name of copyright owner]
         
            Licensed under the Apache License, Version 2.0 (the "License");
            you may not use this file except in compliance with the License.
            You may obtain a copy of the License at
         
                http://www.apache.org/licenses/LICENSE-2.0
         
            Unless required by applicable law or agreed to in writing, software
            distributed under the License is distributed on an "AS IS" BASIS,
            WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
            See the License for the specific language governing permissions and
            limitations under the License.
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries
Classifier: Topic :: Scientific/Engineering :: Human Machine Interfaces
Classifier: Topic :: Text Processing :: Linguistic
Requires-Dist: lxml~=6.1.0
Requires-Dist: attrs>=21.2,<27
Requires-Dist: sortedcontainers~=2.4
Requires-Dist: toposort~=1.10
Requires-Dist: more-itertools~=10.8.0
Requires-Dist: deprecation~=2.1
Requires-Dist: importlib-resources~=6.5.2
Maintainer: Richard Eckart de Castilho
Requires-Python: >=3.10
Project-URL: Homepage, https://dkpro.github.io
Project-URL: Documentation, https://cassis.readthedocs.io
Project-URL: Repository, https://github.com/dkpro/dkpro-cassis
Description-Content-Type: text/markdown

# dkpro-cassis

[![image](https://github.com/dkpro/dkpro-cassis/actions/workflows/run_tests.yml/badge.svg)](https://github.com/dkpro/dkpro-cassis/actions/workflows/run_tests.yml)

[![Documentation Status](https://readthedocs.org/projects/cassis/badge/?version=latest)](https://cassis.readthedocs.io/en/latest/?badge=latest)

[![image](https://codecov.io/gh/dkpro/dkpro-cassis/branch/main/graph/badge.svg)](https://codecov.io/gh/dkpro/dkpro-cassis)

[![PyPI - License](https://img.shields.io/pypi/l/dkpro-cassis.svg)](https://pypi.org/project/dkpro-cassis/)

[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/dkpro-cassis.svg)](https://pypi.org/project/dkpro-cassis/)

[![PyPI](https://img.shields.io/pypi/v/dkpro-cassis.svg)](https://pypi.org/project/dkpro-cassis/)

[![image](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/ambv/black)

DKPro **cassis** (pronunciation: [ka.sis]) provides a pure-Python implementation of the *Common Analysis System* (CAS)
as defined by the [UIMA](https://uima.apache.org) framework. The CAS is a data structure representing an object to
be enriched with annotations (the co-called *Subject of Analysis*, short *SofA*).

This library enables the creation and manipulation of annotated documents (CAS objects) and their associated type systems as well as loading
and saving them in the [CAS XMI XML representation](https://uima.apache.org/d/uimaj-current/ref.html#ugr.ref.xmi)
or the [CAS JSON representation](https://github.com/apache/uima-uimaj-io-jsoncas#readme) in Python programs. This can ease in particular the integration of Python-based Natural Language Processing (e.g.
[spacy](https://spacy.io) or [NLTK](https://www.nltk.org)) and Machine Learning librarys (e.g.
[scikit-learn](https://scikit-learn.org/stable/) or [Keras](https://keras.io)) in UIMA-based text analysis workflows.

An example of cassis in action is the [spacy recommender for INCEpTION](https://github.com/inception-project/external-recommender-spacy),
which wraps the spacy NLP library as a web service which can be used in conjunction with the [INCEpTION](https://inception-project.github.io)
text annotation platform to automatically generate annotation suggestions.

## Features

Currently supported features are:

- Text SofAs
- Deserializing/serializing UIMA CAS from/to XMI
- Deserializing/serializing UIMA CAS from/to JSON
- Deserializing/serializing type systems from/to XML
- Selecting annotations, selecting covered annotations, adding annotations
- Type inheritance
- Multiple SofA support
- Type system can be changed after loading
- Primitive and reference features and arrays of primitives and references

Some features are still under development, e.g.

- Proper type checking
- XML/XMI schema validation

## Installation

To install the package with `pip`, just run

```
pip install dkpro-cassis
```

## Usage

Example CAS XMI and types system files can be found under `tests\test_files`.

### Reading a CAS file

**From XMI:** A CAS can be deserialized from the UIMA CAS XMI (XML 1.0) format either
by reading from a file or string using `load_cas_from_xmi`.

``` python
from cassis import *

with open('typesystem.xml', 'rb') as f:
    typesystem = load_typesystem(f)

with open('cas.xmi', 'rb') as f:
   cas = load_cas_from_xmi(f, typesystem=typesystem)
```

**From JSON:** The UIMA JSON CAS format is also supported and can be loaded using `load_cas_from_json`.
Most UIMA JSON CAS files come with an embedded typesystem, so it is not necessary to specify one.

``` python
from cassis import *

with open('cas.json', 'rb') as f:
   cas = load_cas_from_json(f)
```

### Writing a CAS file

**To XMI:** A CAS can be serialized to XMI either by writing to a file or be
returned as a string using `cas.to_xmi()`.

``` python
from cassis import *

# Returned as a string
xmi = cas.to_xmi()

# Written to file
cas.to_xmi("my_cas.xmi")
```

**To JSON:** A CAS can also be written to JSON using `cas.to_json()`.

``` python
from cassis import *

# Returned as a string
xmi = cas.to_json()

# Written to file
cas.to_json("my_cas.json")
```

### Creating a CAS

A CAS (Common Analysis System) object typically represents a (text) document. When using cassis,
you will likely most often reading existing CAS files, modify them and then
writing them out again. But you can also create CAS objects from scratch,
e.g. if you want to convert some data into a CAS object in order to create a pre-annotated text.
If you do not have a pre-defined typesystem to work with, you will have to define one.

``` python
typesystem = TypeSystem()

cas = Cas(
    sofa_string = "Joe waited for the train . The train was late .",
    document_language = "en",
    typesystem = typesystem)

print(cas.sofa_string)
print(cas.sofa_mime)
print(cas.document_language)
```

### Adding annotations

**Note:** type names used below are examples only. The actual CAS files you will be
dealing with will use other names! You can get a list of the types using
`cas.typesystem.get_types()`.

Given a type system with a type `cassis.Token` that has an `id` and
`pos` feature, annotations can be added in the following:

``` python
from cassis import *

with open('typesystem.xml', 'rb') as f:
    typesystem = load_typesystem(f)

with open('cas.xmi', 'rb') as f:
    cas = load_cas_from_xmi(f, typesystem=typesystem)

Token = typesystem.get_type('cassis.Token')

tokens = [
    Token(begin=0, end=3, id='0', pos='NNP'),
    Token(begin=4, end=10, id='1', pos='VBD'),
    Token(begin=11, end=14, id='2', pos='IN'),
    Token(begin=15, end=18, id='3', pos='DT'),
    Token(begin=19, end=24, id='4', pos='NN'),
    Token(begin=25, end=26, id='5', pos='.'),
]

for token in tokens:
    cas.add(token)
```

### Selecting annotations

``` python
from cassis import *

with open('typesystem.xml', 'rb') as f:
    typesystem = load_typesystem(f)

with open('cas.xmi', 'rb') as f:
    cas = load_cas_from_xmi(f, typesystem=typesystem)

for sentence in cas.select('cassis.Sentence'):
    for token in cas.select_covered('cassis.Token', sentence):
        print(token.get_covered_text())

        # Annotation values can be accessed as properties
        print('Token: begin={0}, end={1}, id={2}, pos={3}'.format(token.begin, token.end, token.id, token.pos)) 
```

### Getting and setting (nested) features

If you want to access a variable but only have its name as a string or have nested feature structures,
e.g. a feature structure with feature `a` that has a
feature `b` that has a feature `c`, some of which can be `None`, then you can use the
following:

``` python
fs.get("var_name") # Or
fs["var_name"]
```

Or in the nested case,

``` python
fs.get("a.b.c")
fs["a.b.c"]
```

If `a` or `b` or `c` are `None`, then this returns instead of
throwing an error.

Another example would be a StringList containing `["Foo", "Bar", "Baz"]`:

``` python
assert lst.get("head") == "foo"
assert lst.get("tail.head") == "bar"
assert lst.get("tail.tail.head") == "baz"
assert lst.get("tail.tail.tail.head") == None
assert lst.get("tail.tail.tail.tail.head") == None
```

The same goes for setting:

``` python
# Functional
lst.set("head", "new_foo")
lst.set("tail.head", "new_bar")
lst.set("tail.tail.head", "new_baz")

assert lst.get("head") == "new_foo"
assert lst.get("tail.head") == "new_bar"
assert lst.get("tail.tail.head") == "new_baz"

# Bracket access
lst["head"] = "newer_foo"
lst["tail.head"] = "newer_bar"
lst["tail.tail.head"] = "newer_baz"

assert lst["head"] == "newer_foo"
assert lst["tail.head"] == "newer_bar"
assert lst["tail.tail.head"] == "newer_baz"
```

### Creating types and adding features

``` python
from cassis import *

typesystem = TypeSystem()

parent_type = typesystem.create_type(name='example.ParentType')
typesystem.create_feature(domainType=parent_type, name='parentFeature', rangeType=TYPE_NAME_STRING)

child_type = typesystem.create_type(name='example.ChildType', supertypeName=parent_type.name)
typesystem.create_feature(domainType=child_type, name='childFeature', rangeType=TYPE_NAME_INTEGER)

annotation = child_type(parentFeature='parent', childFeature='child')
```

When adding new features, these changes are propagated. For example,
adding a feature to a parent type makes it available to a child type.
Therefore, the type system does not need to be frozen for consistency.
The type system can be changed even after loading, it is not frozen
like in UIMAj.

### Sofa support

A Sofa represents some form of an unstructured artifact that is processed in a UIMA pipeline. It contains for instance
the document text. Currently, new Sofas can be created. This is automatically done when creating a new view. Basic
properties of the Sofa can be read and written:

``` python
cas = Cas(
    sofa_string = "Joe waited for the train . The train was late .",
    document_language = "en")

print(cas.sofa_string)
print(cas.sofa_mime)
print(cas.document_language)
```

### Array support

Array feature values are not simply Python arrays, but they are wrapped in a feature structure of
a UIMA array type such as `uima.cas.FSArray`.

``` python
# Setting up an annotation type with an array feature containing
# references to other annotations
typesystem = TypeSystem()
ArrayHolder = typesystem.create_type(name='example.ArrayHolder')
typesystem.create_feature(domainType=ArrayHolder, name='values', rangeType=TYPE_NAME_FS_ARRAY)

cas = Cas(typesystem=typesystem)

# Populating the document an annotation that contains references to another annotation in its array feature
Annotation = cas.typesystem.get_type(TYPE_NAME_ANNOTATION)
FSArray = cas.typesystem.get_type(TYPE_NAME_FS_ARRAY)
ann = Annotation(begin=0, end=1)
cas.add(ann)
holder = ArrayHolder(values=FSArray(elements=[ann, ann, ann]))
cas.add(holder)

# Reading the elements from the array feature
for e in holder.values.elements:
    print(e)
```

### Managing views

A view into a CAS contains a subset of feature structures and annotations. One view corresponds to exactly one Sofa. It
can also be used to query and alter information about the Sofa, e.g. the document text. Annotations added to one view
are not visible in another view. A view Views can be created and changed. A view has the same methods and attributes
as a `Cas` .

``` python
from cassis import *

with open('typesystem.xml', 'rb') as f:
    typesystem = load_typesystem(f)
Token = typesystem.get_type('cassis.Token')

# This creates automatically the view `_InitialView`
cas = Cas()
cas.sofa_string = "I like cheese ."

cas.add_all([
    Token(begin=0, end=1),
    Token(begin=2, end=6),
    Token(begin=7, end=13),
    Token(begin=14, end=15)
])

print([x.get_covered_text() for x in cas.select_all()])

# Create a new view and work on it.
view = cas.create_view('testView')
view.sofa_string = "I like blackcurrant ."

view.add_all([
    Token(begin=0, end=1),
    Token(begin=2, end=6),
    Token(begin=7, end=19),
    Token(begin=20, end=21)
])

print([x.get_covered_text() for x in view.select_all()])
```

### Merging type systems

Sometimes, it is desirable to merge two type systems. With **cassis**, this can be
achieved via the `merge_typesystems` function. The detailed rules of merging can be found
[here](https://uima.apache.org/d/uimaj-current/ref.html#ugr.ref.cas.typemerging).

``` python
from cassis import *

with open('typesystem.xml', 'rb') as f:
    typesystem = load_typesystem(f)

ts = merge_typesystems([typesystem, load_dkpro_core_typesystem()])
```

### Type checking

When adding annotations, no type checking is performed for simplicity reasons.
In order to check types, call the `cas.typecheck()` method. Currently, it only
checks whether elements in `uima.cas.FSArray` are
adhere to the specified `elementType`.

## DKPro Core Integration

A CAS using the DKPro Core Type System can be created via

``` python
from cassis import *

cas = Cas(typesystem=load_dkpro_core_typesystem())

for t in cas.typesystem.get_types():
    print(t)
```

## Miscellaneous

### If feature names clash with Python magic variables

If your type system defines a type called `self` or `type`, then it will be made
available as a member variable `self_` or `type_` on the respective type:

``` python
from cassis import *
from cassis.typesystem import *

typesystem = TypeSystem()

ExampleType = typesystem.create_type(name='example.Type')
typesystem.create_feature(domainType=ExampleType, name='self', rangeType=TYPE_NAME_STRING)
typesystem.create_feature(domainType=ExampleType, name='type', rangeType=TYPE_NAME_STRING)

annotation = ExampleType(self_="Test string1", type_="Test string2")

print(annotation.self_)
print(annotation.type_)
```

### Leniency

If the type for a feature structure is not found in the typesystem, it will raise an exception by default.
If you want to ignore these kind of errors, you can pass `lenient=True` to the `Cas` constructor or
to `load_cas_from_xmi`.

### Large XMI files

If you try to parse large XMI files and get an error message like `XMLSyntaxError: internal error: Huge input lookup`,
then you can disable this security check by passing `trusted=True` to your calls to `load_cas_from_xmi`.

## Citing & Authors

If you find this repository helpful, feel free to cite

``` bibtex
@software{klie2020_cassis,
  author       = {Jan-Christoph Klie and
                  Richard Eckart de Castilho},
  title        = {DKPro Cassis - Reading and Writing UIMA CAS Files in Python},
  publisher    = {Zenodo},
  doi          = {10.5281/zenodo.3994108},
  url          = {https://github.com/dkpro/dkpro-cassis}
}
```

## Development

The project uses [uv](https://docs.astral.sh/uv/) to manage its virtual
environment and dependencies. To set up a development environment with all
dev and doc dependencies installed, run

```bash
uv sync --all-groups
```

Common development tasks are exposed via [taskipy](https://github.com/taskipy/taskipy):

```bash
uv run task test       # run the test suite
uv run task test-cov   # run tests with coverage
uv run task lint       # run ruff linter
uv run task format     # format code with ruff
uv run task fix        # auto-fix lint issues
uv run task typecheck  # run pyright
```

## Release

- Make sure all issues for the milestone are completed, otherwise move them to the next
- Checkout the `main` branch
- Bump the version in `pyproject.toml` to a stable one, e.g. `0.6.0`, commit and push, wait until the build completed. An example commit message would be `No issue. Release 0.6.0`
- Create a tag for that version via e.g. `git tag v0.6.0` and push the tags via `git push --tags`. Pushing a tag triggers the release to pypi
- Bump the version in `pyproject.toml` to the next development version, e.g. `0.7.0.dev0`, commit and push that. An example commit message would be `No issue. Bump version after release`
- Once the build has completed and pypi accepted the new version, go to the Github release and write the changelog based on the issues in the respective milestone
- Create a new milestone for the next version
