quantulum3
Python library for information extraction of quantities, measurements and their units from unstructured text. It is able to disambiguate between similar looking units (e.g. "minutes" of time or of arc) from the context of each quantity, with a small fine-tuned language model.
This is the Python 3 compatible fork of recastrodiaz' fork of grhawks' fork of the original by Marco Lagi. The compatibility with the newest version of sklearn is based on the fork of sohrabtowfighi.
User Guide
Installation
quantulum3 requires Python 3.11 or newer.
pip install quantulum3
Or with uv:
uv add quantulum3
When units need to be disambiguated, a compact neural classifier (quantulum3[potion] / quantulum3[classifier]) can be used
(see Disambiguation).
Usage
>>> from quantulum3 import parser
>>> quants = parser.parse('I want 2 liters of wine')
>>> quants
[Quantity(2, 'litre')]
The Quantity class stores the surface of the original text it was extracted from, as well as the (start, end) positions of the match:
>>> quants[0].surface
u'2 liters'
>>> quants[0].span
(7, 15)
The value attribute provides the parsed numeric value and the unit.name attribute provides the name of the parsed unit:
>>> quants[0].value
2.0
>>> quants[0].unit.name
'litre'
An inline parser that embeds the parsed quantities in the text is also available (especially useful for debugging):
>>> print parser.inline_parse('I want 2 liters of wine')
I want 2 liters {Quantity(2, "litre")} of wine
As the parser is also able to parse dimensionless numbers, this library can also be used for simple number extraction.
>>> print parser.parse('I want two')
[Quantity(2, 'dimensionless')]
Units and entities
All units (e.g. litre) and the entities they are associated to (e.g. volume) are reconciled against WikiPedia:
>>> quants[0].unit
Unit(name="litre", entity=Entity("volume"), uri=https://en.wikipedia.org/wiki/Litre)
>>> quants[0].unit.entity
Entity(name="volume", uri=https://en.wikipedia.org/wiki/Volume)
This library includes more than 290 units and 75 entities. It also parses spelled-out numbers, ranges and uncertainties:
>>> parser.parse('I want a gallon of beer')
[Quantity(1, 'gallon')]
>>> parser.parse('The LHC smashes proton beams at 12.8–13.0 TeV')
[Quantity(12.8, "teraelectronvolt"), Quantity(13, "teraelectronvolt")]
>>> quant = parser.parse('The LHC smashes proton beams at 12.9±0.1 TeV')
>>> quant[0].uncertainty
0.1
Non-standard units usually don't have a WikiPedia page. The parser will still try to guess their underlying entity based on their dimensionality:
>>> parser.parse('Sound travels at 0.34 km/s')[0].unit
Unit(name="kilometre per second", entity=Entity("speed"), uri=None)
Export/Import
Entities, Units and Quantities can be exported to dictionaries and JSON strings:
>>> quant = parser.parse('I want 2 liters of wine')
>>> quant[0].to_dict()
{'value': 2.0, 'unit': 'litre', "entity": "volume", 'surface': '2 liters', 'span': (7, 15), 'uncertainty': None, 'lang': 'en_US'}
>>> quant[0].to_json()
'{"value": 2.0, "unit": "litre", "entity": "volume", "surface": "2 liters", "span": [7, 15], "uncertainty": null, "lang": "en_US"}'
By default, only the unit/entity name is included in the exported dictionary, but these can be included:
>>> quant = parser.parse('I want 2 liters of wine')
>>> quant[0].to_dict(include_unit_dict=True, include_entity_dict=True) # same args apply to .to_json()
{'value': 2.0, 'unit': {'name': 'litre', 'surfaces': ['cubic decimetre', 'cubic decimeter', 'litre', 'liter'], 'entity': {'name': 'volume', 'dimensions': [{'base': 'length', 'power': 3}], 'uri': 'Volume'}, 'uri': 'Litre', 'symbols': ['l', 'L', 'ltr', 'ℓ'], 'dimensions': [{'base': 'decimetre', 'power': 3}], 'original_dimensions': [{'base': 'litre', 'power': 1, 'surface': 'liters'}], 'currency_code': None, 'lang': 'en_US'}, 'entity': 'volume', 'surface': '2 liters', 'span': (7, 15), 'uncertainty': None, 'lang': 'en_US'}
Similar export syntax applies to exporting Unit and Entity objects.
You can import Entity, Unit and Quantity objects from dictionaries and JSON. This requires that the object was exported with include_unit_dict=True and include_entity_dict=True (as appropriate):
>>> quant_dict = quant[0].to_dict(include_unit_dict=True, include_entity_dict=True)
>>> quant = Quantity.from_dict(quant_dict)
>>> ent_json = "{'name': 'volume', 'dimensions': [{'base': 'length', 'power': 3}], 'uri': 'Volume'}"
>>> ent = Entity.from_json(ent_json)
Disambiguation
If the parser detects an ambiguity, a classifier tries to guess the right one:
>>> parser.parse('I spent 20 pounds on this!')
[Quantity(20, "pound sterling")]
>>> parser.parse('It weighs no more than 20 pounds')
[Quantity(20, "pound-mass")]
or:
>>> text = 'The average density of the Earth is about 5.5x10-3 kg/cm³'
>>> parser.parse(text)[0].unit.entity
Entity(name="density", uri=https://en.wikipedia.org/wiki/Density)
>>> text = 'The amount of O₂ is 2.98e-4 kg per liter of atmosphere'
>>> parser.parse(text)[0].unit.entity
Entity(name="concentration", uri=https://en.wikipedia.org/wiki/Concentration)
A compact attention model on top of potion-base-8M token vectors (int8 ONNX)
is available for this. It inspects the context around the quantity itself
(its position and casing in the text), and is trained on synthetically created
realistic sentences and cleaned Wikipedia paragraphs:
| backend | install | model | speed | accuracy |
|---|---|---|---|---|
| potion attention, int8 ONNX | pip install quantulum3[potion] |
11 MB | ~1.1 ms | 90.3% |
With the model files present (built by scripts/build.py), quantulum3 uses
potion automatically when onnxruntime and tokenizers are installed, and
otherwise falls back to the word-overlap heuristic. To choose explicitly:
>>> from quantulum3 import model_disambiguation
>>> model_disambiguation.set_backend("potion") # "auto" (default), None (heuristic)
Spoken version
Quantulum classes include methods to convert them to a speakable unit.
>>> parser.parse("Gimme 10e9 GW now!")[0].to_spoken()
ten billion gigawatts
>>> parser.inline_parse_and_expand("Gimme $1e10 now and also 1 TW and 0.5 J!")
Gimme ten billion dollars now and also one terawatt and zero point five joules!
Manipulation
While quantities cannot be manipulated within this library, there are many great options out there:
Extension
Training the disambiguation model
The potion model is trained on usage sentences (quantulum3/_lang/<language>/train/usage.json:
objects with text, unit, surface and quantity, the exact substring holding the
number and unit) and on the cleaned Wikipedia paragraphs in train/wiki.json.
Install the training dependencies (pip install quantulum3[train]) and use
quantulum3-training, quantulum3/scripts/train.py, or model_disambiguation.train_potion:
quantulum3-training --lang <language> --data <path/to/usage.json> --output <path/to/model_dir>
With uv, you can run the installed entry point without activating an environment:
uv run --extra train quantulum3-training --lang <language> --data <path/to/usage.json> --output <path/to/model_dir>
--data (repeatable) replaces usage.json. To use your custom model, pass its
directory to the parser:
parser.parse(<text>, classifier_path="path/to/model_dir")
To pretrain a backbone from scratch on web text (FineWeb-Edu + Wikipedia), fine-tune, and evaluate on the held-out test sets in data/test/:
uv run --extra train --with pyarrow python scripts/pretrain_potion.py prep --out work/web
uv run --extra train --with pyarrow python scripts/pretrain_potion.py pretrain --out work/web --name web2-wide --steps 100000 --train-emb 1.0
uv run --extra train python scripts/train_potion.py --init work/web/web2-wide.pt
uv run --extra potion python scripts/eval_potion.py
and automatically included for training.
The file provided should be in .magnitude format as other formats are first
converted to a .magnitude file on-the-run. Check out
pre-formatted Magnitude formatted word-embeddings
and Magnitude for more information.
Additional units
It is possible to add additional entities and units to be parsed by quantulum. These will be added to the default units and entities. See below code for an example invocation:
>>> from quantulum3.load import add_custom_unit, remove_custom_unit
>>> add_custom_unit(name="schlurp", surfaces=["slp"], entity="dimensionless")
>>> parser.parse("This extremely sharp tool is precise up to 0.5 slp")
[Quantity(0.5, "Unit(name="schlurp", entity=Entity("dimensionless"), uri=None)")]
The keyword arguments to the function add_custom_unit are directly translated
to the properties of the unit to be created.
Custom Units and Entities
It is possible to load a completely custom set of units and entities. This can be done by passing a list of file paths to the load_custom_units and load_custom_entities functions. Loading custom untis and entities will replace the default units and entities that are normally loaded.
The recomended way to load quantities is via a context manager:
>>> from quantulum3 import load, parser
>>> with load.CustomQuantities(["path/to/units.json"], ["path/to/entities.json"]):
>>> parser.parse("This extremely sharp tool is precise up to 0.5 slp")
[Quantity(0.5, "Unit(name="schlurp", entity=Entity("dimensionless"), uri=None)")]
>>> # default units and entities are loaded again
But it is also possible to load custom units and entities manually:
>>> from quantulum3 import load, parser
>>> load.load_custom_units(["path/to/units.json"])
>>> load.load_custom_entities(["path/to/entities.json"])
>>> parser.parse("This extremely sharp tool is precise up to 0.5 slp")
[Quantity(0.5, "Unit(name="schlurp", entity=Entity("dimensionless"), uri=None)")]
>>> # remove custom units and entities and load default units and entities
>>> load.reset_quantities()
See the Developer Guide below for more information about the format of units and entities files.
Developer Guide
Adding Units and Entities
See units.json for the complete list of units and entities.json for the complete list of entities. The criteria for adding units have been:
- the unit has (or is redirected to) a WikiPedia page
- the unit is in common use (e.g. not the premetric Swedish units of measurement).
It's easy to extend these two files to the units/entities of interest. Here is an example of an entry in entities.json:
"speed": {
"dimensions": [{"base": "length", "power": 1}, {"base": "time", "power": -1}],
"URI": "https://en.wikipedia.org/wiki/Speed"
}
- The name of an entity is its key. Names are required to be unique.
- URI is the name of the wikipedia page of the entity. (i.e.
https://en.wikipedia.org/wiki/Speed=>Speed) - dimensions is the dimensionality, a list of dictionaries each having a base (the name of another entity) and a power (an integer, can be negative).
Here is an example of an entry in units.json:
"metre per second": {
"surfaces": ["metre per second", "meter per second"],
"entity": "speed",
"URI": "Metre_per_second",
"dimensions": [{"base": "metre", "power": 1}, {"base": "second", "power": -1}],
"symbols": ["mps"]
},
"year": {
"surfaces": [ "year", "annum" ],
"entity": "time",
"URI": "Year",
"dimensions": [],
"symbols": [ "a", "y", "yr" ],
"prefixes": [ "k", "M", "G", "T", "P", "E" ]
}
- The name of a unit is its key. Names are required to be unique.
- URI follows the same scheme as in the entities.json
- surfaces is a list of strings that refer to that unit. The library takes care of plurals, no need to specify them.
- entity is the name of an entity in entities.json
- dimensions follows the same schema as in entities.json, but the base is the name of another unit, not of another entity.
- symbols is a list of possible symbols and abbreviations for that unit.
- prefixes is an optional list. It can contain Metric and Binary prefixes and automatically generates according units. If you want to add specifics (like different surfaces) you need to create an entry for that prefixes version on its own.
All fields are case sensitive.
Contributing
dev build:
If you'd like to contribute follow these steps:
- Clone a fork of this project into your workspace
- Run
uv sync --extra potion --extra train - Commit the generated
uv.lockchanges when dependencies change - Make your changes
- Run
scripts/format.shanduv run scripts/build.pyfrom the package root directory. The build step regeneratescommon-words.jsonand the potion model. - Test your changes with
uv run pytest - Create a Pull Request when you have committed and pushed your changes
Language support
There is a branch for language support, namely language_support.
From inspecting the README file in the _lang subdirectory and
the functions and values given in the new _lang.en_US submodule,
one should be able to create own language submodules.
The new language modules should automatically be invoked and be available,
both through the lang= keyword argument in the parser functions as well
as in the automatic unittests.
No changes outside the own language submodule folder (i.e. _lang.de_DE) should
be necessary. If there are problems implementing a new language, don't hesitate to open an issue.
Metadata
Release files for quantulum3 0.11.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| quantulum3-0.11.0.tar.gz | 10.1 MB | With provenance | Details for quantulum3-0.11.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| quantulum3-0.11.0-py3-none-any.whl | Python 3 | none | any | Details for quantulum3-0.11.0-py3-none-any.whl |
Total release size: 20.2 MB
Release files / quantulum3-0.11.0.tar.gz
| Download URL | quantulum3-0.11.0.tar.gz |
|---|---|
| Size | 10.1 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
2924d3b2e67cb966022b6d4e3d12b51b42d53f6f224fd69dabbdbbe4cee62116
|
|
BLAKE2b-256 checksum How to use checksums |
0044fa657ae4046e2bf5fe6feb7d8a78f81bfa14a5349999483ad2b3e60abc76
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.
Transparency logRelease files / quantulum3-0.11.0-py3-none-any.whl
| Download URL | quantulum3-0.11.0-py3-none-any.whl |
|---|---|
| Size | 10.1 MB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
76434f549ff0ad76ac17058b7dd7ca96ad3857a49d313392568f8d5288d72ee0
|
|
BLAKE2b-256 checksum How to use checksums |
8ad67278056391cd5b4d45677c29edf78d0dc3daed9ae2dc94907e240bf17d14
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.
Transparency logSecurity for quantulum3 0.11.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for quantulum3-0.11.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.