Python library for information extraction of quantities, measurements
and their units from unstructured text. It is able to disambiguate between similar
looking units based on their k-nearest neighbours in their GloVe vector representation
and their Wikipedia page.
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):
If the parser detects an ambiguity, a classifier based on the WikiPedia
pages of the ambiguous units or entities 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)
In addition to that, the classifier is trained on the most similar words to
all of the units surfaces, according to their distance in GloVe
vector representation.
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:
If you want to train the classifier yourself, you will need the dependencies for the classifier (see installation).
Use quantulum3-training on the command line, the script quantulum3/scripts/train.py or the method train_classifier in quantulum3.classifier to train the classifier.
Example training files can be found in quantulum3/_lang/<language>/train.
If you want to create a new or different similars.json, install pymagnitude.
For the extraction of nearest neighbours from a vector word representation file,
use scripts/extract_vere.py. It automatically extracts the k nearest neighbours
in vector space of the vector representation for each of the possible surfaces
of the ambiguous units. The resulting neighbours are stored in quantulum3/similars.json
and automatically included for training.
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 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 classifier
Commit the generated uv.lock changes when dependencies change
Make your changes
Run scripts/format.sh and uv run scripts/build.py from the package root directory. The build step regenerates common-words.json and clf.joblib.
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.