### Install quantulum3 Source: https://github.com/nielstron/quantulum3/blob/dev/README.md Install the quantulum3 library using pip or uv. For classifier functionality, install with the 'classifier' extra. ```bash pip install quantulum3 ``` ```bash uv add quantulum3 ``` ```bash pip install quantulum3[classifier] ``` ```bash uv add "quantulum3[classifier]" ``` -------------------------------- ### Entities JSON Format Source: https://context7.com/nielstron/quantulum3/llms.txt Example structure for an `entities.json` file, defining entity dimensions and URIs. ```json { "speed": { "dimensions": [{"base": "length", "power": 1}, {"base": "time", "power": -1}], "URI": "Speed" }, "volume": { "dimensions": [{"base": "length", "power": 3}], "URI": "Volume" } } ``` -------------------------------- ### Training Data JSON Format Source: https://context7.com/nielstron/quantulum3/llms.txt Example structure for training data, where each entry contains text and the corresponding unit. ```json [ {"text": "The car weighs 2000 pounds", "unit": "pound-mass"}, {"text": "I paid 50 pounds", "unit": "pound sterling"}, {"text": "The temperature is 25 degrees Celsius", "unit": "degree Celsius"} ] ``` -------------------------------- ### Units JSON Format Source: https://context7.com/nielstron/quantulum3/llms.txt Example structure for a `units.json` file, defining unit surfaces, entities, URIs, dimensions, and symbols. ```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"] } } ``` -------------------------------- ### Entity Disambiguation by Context Source: https://context7.com/nielstron/quantulum3/llms.txt The parser disambiguates physical entities based on context. For example, it identifies 'density' from 'kg/cm³' and 'concentration' from 'kg per liter'. ```python text = 'The average density of the Earth is about 5.5x10-3 kg/cm³' entity = parser.parse(text)[0].unit.entity print(entity.name) # 'density' text = 'The amount of O₂ is 2.98e-4 kg per liter of atmosphere' entity = parser.parse(text)[0].unit.entity print(entity.name) # 'concentration' ``` -------------------------------- ### Manual Loading of Custom Units and Entities Source: https://context7.com/nielstron/quantulum3/llms.txt Demonstrates how to manually load custom units and entities, replacing the default ones, and how to reset to defaults. ```APIDOC ## load.load_custom_units() / load.load_custom_entities() ### Description Manually load custom units and entities, replacing the default ones. ### Method Python Functions ### Endpoint N/A ### Parameters #### load.load_custom_units() - **unit_files** (list of str) - Required - Paths to JSON files containing custom unit definitions. - **use_general_units** (bool) - Optional - Whether to use general units. - **use_language_units** (bool) - Optional - Whether to use language-specific units. - **use_additional_units** (bool) - Optional - Whether to use additional units. #### load.load_custom_entities() - **entity_files** (list of str) - Required - Paths to JSON files containing custom entity definitions. - **use_general_entities** (bool) - Optional - Whether to use general entities. - **use_language_entities** (bool) - Optional - Whether to use language-specific entities. - **use_additional_entities** (bool) - Optional - Whether to use additional entities. ### Request Example ```python from quantulum3 import load, parser # Load custom units (replaces defaults) load.load_custom_units( ["path/to/units.json"], use_general_units=False, use_language_units=False, use_additional_units=True ) # Load custom entities (replaces defaults) load.load_custom_entities( ["path/to/entities.json"], use_general_entities=False, use_language_entities=False, use_additional_entities=True ) # Parse with custom units and entities quants = parser.parse("Text with custom units") # Reset to default units and entities load.reset_quantities() ``` ### Response N/A (These are loading functions, results are internal state changes) ### Error Handling - File not found errors for specified paths. - JSON parsing errors for invalid file formats. ``` -------------------------------- ### Run Build Script Source: https://github.com/nielstron/quantulum3/blob/dev/README.md Execute this command from the package root directory to regenerate `common-words.json` and `clf.joblib` as part of the build process. ```bash uv run scripts/build.py ``` -------------------------------- ### Train Quantulum3 Classifier Source: https://github.com/nielstron/quantulum3/blob/dev/README.md Use this command-line script to train the classifier. Specify the language, path to training data, and output file. ```bash quantulum3-training --lang --data --output ``` ```bash uv run quantulum3-training --lang --data --output ``` -------------------------------- ### Command Line Classifier Training Source: https://context7.com/nielstron/quantulum3/llms.txt Train the classifier from the command line using the `quantulum3-training` script. You can specify language, data sources, and output paths. ```bash # Train with default data quantulum3-training --lang en_US --store # Train with custom data and output path quantulum3-training --data train1.json --data train2.json --output model.joblib # Using uv uv run quantulum3-training --lang en_US --data training.json --output clf.joblib ``` -------------------------------- ### Run Tests Source: https://github.com/nielstron/quantulum3/blob/dev/README.md Execute this command to run the project's tests using pytest. ```bash uv run pytest ``` -------------------------------- ### Load Custom Quantities with Context Manager Source: https://github.com/nielstron/quantulum3/blob/dev/README.md Use a context manager to load custom units and entities from specified JSON files, replacing default ones temporarily. Custom quantities are automatically reloaded after exiting the context. ```python 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") ``` -------------------------------- ### Load Custom Units and Entities Source: https://context7.com/nielstron/quantulum3/llms.txt Manually load custom units and entities, replacing the default ones. Use `reset_quantities()` to revert to defaults. ```python from quantulum3 import load, parser # Load custom units (replaces defaults) load.load_custom_units( ["path/to/units.json"], use_general_units=False, use_language_units=False, use_additional_units=True ) # Load custom entities (replaces defaults) load.load_custom_entities( ["path/to/entities.json"], use_general_entities=False, use_language_entities=False, use_additional_entities=True ) # Parse with custom units and entities quants = parser.parse("Text with custom units") # Reset to default units and entities load.reset_quantities() ``` -------------------------------- ### Context Manager for Custom Units and Entities Source: https://context7.com/nielstron/quantulum3/llms.txt Temporarily load custom units and entities using the `CustomQuantities` context manager. This allows for isolated parsing with specific datasets without affecting the global configuration. Options control which unit sets are included. ```python with load.CustomQuantities( custom_units=["path/to/units.json"], custom_entities=["path/to/entities.json"], use_general_units=False, # Don't include default units use_language_units=False, # Don't include language-specific units use_additional_units=True # Include units added via add_custom_unit() ): quants = parser.parse("Custom parsing with custom units") # Default units and entities are restored after context exits quants = parser.parse("Back to default parsing") ``` -------------------------------- ### Convert Quantities to Spoken Form with parser.inline_parse_and_expand() Source: https://context7.com/nielstron/quantulum3/llms.txt Use parser.inline_parse_and_expand() to parse text and replace quantities with their spoken (human-readable) form. You can specify the language for conversion. ```python from quantulum3 import parser result = parser.inline_parse_and_expand("Gimme 10e9 GW now!") print(result) # 'Gimme ten billion gigawatts now!' result = parser.inline_parse_and_expand("Gimme $1e10 now and also 1 TW and 0.5 J!") print(result) # 'Gimme ten billion dollars now and also one terawatt and zero point five joules!' # Specify language result = parser.inline_parse_and_expand("I need 5 kg", lang="en_US") print(result) # 'I need five kilograms' ``` -------------------------------- ### Load Custom Units and Entities Manually Source: https://github.com/nielstron/quantulum3/blob/dev/README.md Manually load custom units and entities from JSON files. This replaces the default sets. Use reset_quantities() to revert to default units and entities. ```python 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") load.reset_quantities() ``` -------------------------------- ### Import Quantity from Dictionary and JSON Source: https://context7.com/nielstron/quantulum3/llms.txt Restore a Quantity object from a dictionary or JSON string. Ensure that the dictionary was created with include_unit_dict=True and include_entity_dict=True for full fidelity. ```python quant_dict = quant.to_dict(include_unit_dict=True, include_entity_dict=True) restored_quant = Quantity.from_dict(quant_dict) ``` ```python restored_quant = Quantity.from_json(json_str) ``` -------------------------------- ### Import Quantity and Entity from Dictionary/JSON Source: https://github.com/nielstron/quantulum3/blob/dev/README.md Import Quantity and Entity objects from their dictionary or JSON representations. Ensure that nested objects were included during export for successful import. ```python >>> quant_dict = quant[0].to_dict(include_unit_dict=True, include_entity_dict=True) >>> quant = Quantity.from_dict(quant_dict) ``` ```python >>> ent_json = "{'name': 'volume', 'dimensions': [{'base': 'length', 'power': 3}], 'uri': 'Volume'}" >>> ent = Entity.from_json(ent_json) ``` -------------------------------- ### JSON File Formats Source: https://context7.com/nielstron/quantulum3/llms.txt Describes the expected JSON formats for custom units, entities, and training data. ```APIDOC ### units.json Format #### Description Defines custom units with their surfaces, associated entity, URI, dimensions, and symbols. #### Structure ```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"] } } ``` ### entities.json Format #### Description Defines custom entities with their dimensions and URI. #### Structure ```json { "speed": { "dimensions": [{"base": "length", "power": 1}, {"base": "time", "power": -1}], "URI": "Speed" }, "volume": { "dimensions": [{"base": "length", "power": 3}], "URI": "Volume" } } ``` ### Training Data Format #### Description Specifies the format for custom training data used to train the disambiguation classifier. #### Structure ```json [ {"text": "The car weighs 2000 pounds", "unit": "pound-mass"}, {"text": "I paid 50 pounds", "unit": "pound sterling"}, {"text": "The temperature is 25 degrees Celsius", "unit": "degree Celsius"} ] ``` ``` -------------------------------- ### Import Unit from Dictionary Source: https://context7.com/nielstron/quantulum3/llms.txt Reconstruct a Unit object from its dictionary representation. This is useful for loading custom units or restoring units from saved data. ```python restored_unit = Unit.from_dict(unit_dict) ``` -------------------------------- ### parser.inline_parse_and_expand() - Convert to Spoken Form Source: https://context7.com/nielstron/quantulum3/llms.txt Parses text and replaces quantities with their spoken (human-readable) form, making the text more accessible. ```APIDOC ## parser.inline_parse_and_expand() ### Description Parses text and replaces quantities with their spoken (human-readable) form. ### Method `parser.inline_parse_and_expand(text, lang='en_US')` ### Parameters #### Path Parameters None #### Query Parameters - **text** (string) - Required - The input text to parse. - **lang** (string) - Optional - The language for spoken form conversion (default is 'en_US'). ### Request Example ```python from quantulum3 import parser result = parser.inline_parse_and_expand("Gimme 10e9 GW now!") print(result) result = parser.inline_parse_and_expand("Gimme $1e10 now and also 1 TW and 0.5 J!") print(result) result = parser.inline_parse_and_expand("I need 5 kg", lang="en_US") print(result) ``` ### Response #### Success Response (200) - **string** - The input text with quantities converted to their spoken form. #### Response Example ``` 'Gimme ten billion gigawatts now!' 'Gimme ten billion dollars now and also one terawatt and zero point five joules!' 'I need five kilograms' ``` ``` -------------------------------- ### Access Unit and Entity Registries Source: https://context7.com/nielstron/quantulum3/llms.txt Access the loaded units and entities for inspection or manual lookups. Functions like `pluralize` and `number_to_words` are also available. ```python from quantulum3 import load # Get all loaded units units = load.units(lang="en_US") print(units.names["litre"]) print(units.symbols["kg"]) print(units.surfaces["kilogram"]) # Get all loaded entities entities = load.entities(lang="en_US") print(entities.names["volume"]) print(entities.derived) # Pluralize unit names plural = load.pluralize("litre", count=2, lang="en_US") print(plural) # 'litres' # Convert number to words words = load.number_to_words(42, lang="en_US") print(words) # 'forty-two' ``` -------------------------------- ### Add Custom Unit Source: https://context7.com/nielstron/quantulum3/llms.txt Add a custom unit to Quantulum 3's parsing capabilities using `add_custom_unit`. The unit becomes available immediately. Remember to remove it with `remove_custom_unit` if it's only needed temporarily. ```python add_custom_unit( name="schlurp", surfaces=["slp", "schlurp"], entity="dimensionless", symbols=["SLP"] ) quants = parser.parse("This extremely sharp tool is precise up to 0.5 slp") print(quants[0].unit.name) # 'schlurp' print(quants[0].value) # 0.5 remove_custom_unit("schlurp") ``` -------------------------------- ### Utility Functions Source: https://context7.com/nielstron/quantulum3/llms.txt Provides access to loaded unit and entity registries, and functions for number conversion. ```APIDOC ## load.units() / load.entities() - Access Unit and Entity Registries ### Description Access the loaded units and entities for inspection or manual lookups. Also includes functions for pluralization and number-to-words conversion. ### Method Python Functions ### Endpoint N/A ### Parameters #### load.units() - **lang** (str) - Optional - Language code for units (e.g., "en_US"). Defaults to the current language. #### load.entities() - **lang** (str) - Optional - Language code for entities (e.g., "en_US"). Defaults to the current language. #### load.pluralize() - **name** (str) - Required - The unit name to pluralize. - **count** (int) - Optional - The number to determine pluralization. Defaults to 2. - **lang** (str) - Optional - Language code for pluralization rules. #### load.number_to_words() - **number** (int/float) - Required - The number to convert to words. - **lang** (str) - Optional - Language code for number-to-words conversion. ### Request Example ```python from quantulum3 import load # Get all loaded units units = load.units(lang="en_US") print(units.names["litre"]) print(units.symbols["kg"]) print(units.surfaces["kilogram"]) # Get all loaded entities entities = load.entities(lang="en_US") print(entities.names["volume"]) print(entities.derived) # Pluralize unit names plural = load.pluralize("litre", count=2, lang="en_US") print(plural) # Convert number to words words = load.number_to_words(42, lang="en_US") print(words) ``` ### Response - **units** (object) - An object containing unit registries (names, symbols, surfaces). - **entities** (object) - An object containing entity registries (names, derived). - **plural** (str) - The pluralized form of the unit name. - **words** (str) - The word representation of the number. ### Error Handling - Errors for unsupported languages. ``` ```APIDOC ## parser.extract_spellout_values() - Convert Spelled Numbers to Digits ### Description Extract and convert spelled-out numbers in text to their numeric equivalents. ### Method Python Function ### Endpoint N/A ### Parameters - **text** (str) - Required - The input text containing spelled-out numbers. - **lang** (str) - Optional - Language code for number parsing (e.g., "en_US"). Defaults to "en_US". ### Request Example ```python from quantulum3 import parser # Extract spelled-out values values = parser.extract_spellout_values("I want twenty-five liters", lang="en_US") print(values) ``` ### Response - **values** (list of dict) - A list of dictionaries, each containing: - **old_surface** (str) - The original spelled-out number string. - **new_surface** (str) - The converted numeric string. - **old_span** (tuple) - The start and end indices of the original string in the input text. ### Error Handling - Errors for unsupported languages. ``` -------------------------------- ### Add Custom Unit Dynamically Source: https://github.com/nielstron/quantulum3/blob/dev/README.md Dynamically add a new unit to Quantulum3 for parsing. This requires importing the add_custom_unit function and specifying the unit's name, surfaces, and entity. ```python 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") ``` -------------------------------- ### Parse Text with Custom Classifier Source: https://github.com/nielstron/quantulum3/blob/dev/README.md Load a custom trained classifier model into the parser by providing the path to the model file. ```python parser = Parser.parse(, classifier_path="path/to/model.joblib") ``` -------------------------------- ### parser.inline_parse_and_replace() - Standardize Quantities Source: https://context7.com/nielstron/quantulum3/llms.txt Parses text and replaces quantities with their standardized string representation, useful for consistent data formatting. ```APIDOC ## parser.inline_parse_and_replace() ### Description Parses text and replaces quantities with their standardized string representation. ### Method `parser.inline_parse_and_replace(text, lang='en_US')` ### Parameters #### Path Parameters None #### Query Parameters - **text** (string) - Required - The input text to parse. - **lang** (string) - Optional - The language for standardization (default is 'en_US'). ### Request Example ```python from quantulum3 import parser result = parser.inline_parse_and_replace('I want two liters of wine') print(result) result = parser.inline_parse_and_replace('The speed is 100 mph') print(result) ``` ### Response #### Success Response (200) - **string** - The input text with quantities replaced by their standardized string representation. #### Response Example ``` 'I want two litres of wine' 'The speed is one hundred miles per hour' ``` ``` -------------------------------- ### Convert Unit to Spoken Form Source: https://context7.com/nielstron/quantulum3/llms.txt Generate the spoken form of a unit, correctly handling singular and plural forms based on the provided count. Useful for natural language output. ```python print(unit.to_spoken(count=1)) # 'litre' print(unit.to_spoken(count=2)) # 'litres' ``` -------------------------------- ### Convert Quantity to Spoken Version Source: https://github.com/nielstron/quantulum3/blob/dev/README.md Convert a parsed quantity into a human-readable spoken format. This can be done for individual quantities or expanded inline within a text. ```python >>> parser.parse("Gimme 10e9 GW now!")[0].to_spoken() ten billion gigawatts ``` ```python >>> 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! ``` -------------------------------- ### Standardize Quantities with parser.inline_parse_and_replace() Source: https://context7.com/nielstron/quantulum3/llms.txt Use parser.inline_parse_and_replace() to parse text and replace quantities with their standardized string representation. This function can convert numeric values to words. ```python from quantulum3 import parser result = parser.inline_parse_and_replace('I want two liters of wine') print(result) # 'I want two litres of wine' result = parser.inline_parse_and_replace('The speed is 100 mph') print(result) # 'The speed is one hundred miles per hour' ``` -------------------------------- ### Define Unit in units.json Source: https://github.com/nielstron/quantulum3/blob/dev/README.md Define a new unit by specifying its surfaces, associated entity, URI, dimensions, and optional symbols or prefixes. The library handles plurals for surfaces. ```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"] } ``` ```json "year": { "surfaces": [ "year", "annum" ], "entity": "time", "URI": "Year", "dimensions": [], "symbols": [ "a", "y", "yr" ], "prefixes": [ "k", "M", "G", "T", "P", "E" ] } ``` -------------------------------- ### Classifier Training API Source: https://context7.com/nielstron/quantulum3/llms.txt Details on how to train a custom disambiguation classifier using either default or custom training data. ```APIDOC ## classifier.train_classifier() - Train Disambiguation Model ### Description Train a custom disambiguation classifier using your own training data or the default training set. ### Method Python Function ### Endpoint N/A ### Parameters - **lang** (str) - Optional - Language code for training (e.g., "en_US"). Defaults to "en_US". - **store** (bool) - Optional - Whether to save the trained model to the default location. Defaults to False. - **n_jobs** (int) - Optional - Number of CPU cores to use for training. Defaults to 1. - **training_set** (list of dict) - Optional - A list of dictionaries, where each dictionary contains 'text' and 'unit' keys for custom training data. - **output_path** (str) - Optional - Path to save the custom trained model. - **ngram_range** (tuple) - Optional - The range of n-grams to consider (e.g., (1, 2) for unigrams and bigrams). - **parameters** (dict) - Optional - Custom parameters for the SGDClassifier. ### Request Example ```python from quantulum3.classifier import train_classifier # Train with default training data classifier_obj = train_classifier( lang="en_US", store=True, # Save to default location n_jobs=4 # Number of CPU cores to use ) # Train with custom training data training_data = [ {"text": "I bought 5 pounds of apples", "unit": "pound-mass"}, {"text": "I paid 10 pounds for groceries", "unit": "pound sterling"}, {"text": "The temperature is 25 degrees", "unit": "degree Celsius"}, ] classifier_obj = train_classifier( training_set=training_data, store=True, output_path="path/to/custom_model.joblib", n_jobs=4, ngram_range=(1, 2), # Use unigrams and bigrams parameters={ "loss": "log_loss", "penalty": "l2", "alpha": 0.0001, "random_state": 0, } ) # Use custom trained model for parsing from quantulum3 import parser quants = parser.parse("I want 5 pounds", classifier_path="path/to/custom_model.joblib") ``` ### Response - **classifier_obj** (object) - The trained classifier object. ### Error Handling - Errors related to invalid language codes. - Errors during model training due to data format issues. - File I/O errors when saving the model. ``` ```APIDOC ## Command Line Training ### Description Train the classifier from the command line using the `quantulum3-training` script. ### Method Command Line Interface ### Endpoint N/A ### Parameters - **--lang** (str) - Optional - Language code for training (e.g., "en_US"). - **--store** (bool) - Optional - Whether to save the trained model to the default location. - **--data** (str) - Optional - Path to a JSON file containing custom training data. Can be specified multiple times. - **--output** (str) - Optional - Path to save the custom trained model. ### Request Example ```bash # Train with default data quantulum3-training --lang en_US --store # Train with custom data and output path quantulum3-training --data train1.json --data train2.json --output model.joblib # Using uv uv run quantulum3-training --lang en_US --data training.json --output clf.joblib ``` ### Response N/A (Command line execution) ### Error Handling - Errors related to missing or invalid data files. - Errors during model training. ``` -------------------------------- ### Import Entity from Dictionary or JSON Source: https://context7.com/nielstron/quantulum3/llms.txt Reconstruct an Entity object from its dictionary or JSON representation. This is essential for loading custom entities or restoring them from stored data. ```python restored_entity = Entity.from_dict(entity_dict) ``` ```python restored_entity = Entity.from_json(json_str) ``` -------------------------------- ### Unit and Entity information Source: https://github.com/nielstron/quantulum3/blob/dev/README.md Units and their associated entities are reconciled against Wikipedia. Non-standard units may have their entity guessed based on dimensionality. ```python >>> quants[0].unit Unit(name="litre", entity=Entity("volume"), uri=https://en.wikipedia.org/wiki/Litre) ``` ```python >>> quants[0].unit.entity Entity(name="volume", uri=https://en.wikipedia.org/wiki/Volume) ``` ```python >>> parser.parse('Sound travels at 0.34 km/s')[0].unit Unit(name="kilometre per second", entity=Entity("speed"), uri=None) ``` -------------------------------- ### Define Entity in entities.json Source: https://github.com/nielstron/quantulum3/blob/dev/README.md Use this JSON structure to define a new entity, specifying its dimensions and Wikipedia URI. Ensure entity names are unique. ```json "speed": { "dimensions": [{"base": "length", "power": 1}, {"base": "time", "power": -1}], "URI": "https://en.wikipedia.org/wiki/Speed" } ``` -------------------------------- ### Disambiguate Units with Classifier Source: https://github.com/nielstron/quantulum3/blob/dev/README.md Quantulum3 uses a classifier based on Wikipedia pages and GloVe word embeddings to disambiguate units and entities when ambiguity is detected. ```python >>> 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")] ``` ```python >>> 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) ``` ```python >>> 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) ``` -------------------------------- ### Export Quantity to Dictionary and JSON Source: https://context7.com/nielstron/quantulum3/llms.txt Export a Quantity object to a dictionary or JSON string, with options to include unit and entity details. Useful for serialization and data exchange. ```python quant_dict = quant.to_dict(include_unit_dict=True, include_entity_dict=True) print(quant_dict['unit']['symbols']) # ['l', 'L', 'ltr', 'ℓ'] ``` ```python json_str = quant.to_json() ``` ```python json_str = quant.to_json(include_unit_dict=True, include_entity_dict=True) ``` -------------------------------- ### Parse quantities from text Source: https://github.com/nielstron/quantulum3/blob/dev/README.md Use the parser.parse function to extract quantities from a string. The result is a list of Quantity objects. ```python >>> from quantulum3 import parser >>> quants = parser.parse('I want 2 liters of wine') >>> quants [Quantity(2, 'litre')] ``` ```python >>> print parser.inline_parse('I want 2 liters of wine') I want 2 liters {Quantity(2, "litre")} of wine ``` ```python >>> print parser.parse('I want two') [Quantity(2, 'dimensionless')] ``` ```python >>> parser.parse('I want a gallon of beer') [Quantity(1, 'gallon')] ``` ```python >>> parser.parse('The LHC smashes proton beams at 12.8–13.0 TeV') [Quantity(12.8, "teraelectronvolt"), Quantity(13, "teraelectronvolt")] ``` ```python >>> quant = parser.parse('The LHC smashes proton beams at 12.9±0.1 TeV') >>> quant[0].uncertainty 0.1 ``` -------------------------------- ### Quantulum3 NUM_PATTERN Regex Source: https://github.com/nielstron/quantulum3/blob/dev/quantulum3/_lang/README.md Defines the general regex pattern for numbers, ensuring specific formatting groups are included. This pattern is used package-wide and should accommodate various number formats. ```regexp (?{number} # required number [+-]? # optional sign \. விகி+ # required digits (?:[{grouping}] விகி{3}})* # allowed grouping (?{decimals}[{decimal_operators}] விகி+)? # optional decimals ) (?{scale} # optional exponent (?:{multipliers})? # multiplicative operators (?{base}(E|e|+)^?) # required exponent prefix (?{exponent}[+-]? விகி+|[{superscript}]) # required exponent, superscript or normal ) (?{fraction} # optional fraction \ \ விகி/ விகி+|\ ?[{unicode_fract}]|/ விகி+ ) ``` -------------------------------- ### Export Unit to Dictionary and JSON Source: https://context7.com/nielstron/quantulum3/llms.txt Serialize a Unit object into a dictionary or JSON string. The `include_entity_dict` option can be used to embed the associated entity's dictionary representation. ```python unit_dict = unit.to_dict() unit_dict = unit.to_dict(include_entity_dict=True) ``` ```python json_str = unit.to_json(include_entity_dict=True) ``` -------------------------------- ### Export Quantity to Dictionary and JSON Source: https://github.com/nielstron/quantulum3/blob/dev/README.md Export a parsed quantity to a dictionary or JSON string. Use include_unit_dict and include_entity_dict to include nested object details. ```python >>> 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'} ``` ```python >>> quant[0].to_json() '{"value": 2.0, "unit": "litre", "entity": "volume", "surface": "2 liters", "span": [7, 15], "uncertainty": null, "lang": "en_US"}' ``` ```python >>> 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'} ``` -------------------------------- ### Export Entity to Dictionary and JSON Source: https://context7.com/nielstron/quantulum3/llms.txt Serialize an Entity object into a dictionary or JSON string. This allows for saving and loading custom entity definitions or for data inspection. ```python entity_dict = entity.to_dict() # {'name': 'volume', 'dimensions': [{'base': 'length', 'power': 3}], 'uri': 'Volume'} ``` ```python json_str = entity.to_json() ``` -------------------------------- ### Train Disambiguation Classifier Source: https://context7.com/nielstron/quantulum3/llms.txt Train a custom disambiguation classifier using your own training data or the default training set. The `store=True` option saves the model to the default location. ```python from quantulum3.classifier import train_classifier # Train with default training data classifier_obj = train_classifier( lang="en_US", store=True, # Save to default location n_jobs=4 # Number of CPU cores to use ) # Train with custom training data training_data = [ {"text": "I bought 5 pounds of apples", "unit": "pound-mass"}, {"text": "I paid 10 pounds for groceries", "unit": "pound sterling"}, {"text": "The temperature is 25 degrees", "unit": "degree Celsius"}, ] classifier_obj = train_classifier( training_set=training_data, store=True, output_path="path/to/custom_model.joblib", n_jobs=4, ngram_range=(1, 2), # Use unigrams and bigrams parameters={ # Custom SGDClassifier parameters "loss": "log_loss", "penalty": "l2", "alpha": 0.0001, "random_state": 0, } ) # Use custom trained model for parsing from quantulum3 import parser quants = parser.parse("I want 5 pounds", classifier_path="path/to/custom_model.joblib") ``` -------------------------------- ### Access Entity Properties from Parsed Quantity Source: https://context7.com/nielstron/quantulum3/llms.txt Retrieve information about the physical entity (e.g., volume, speed) associated with a unit. This includes the entity's name, URI, and its fundamental dimensions. ```python entity = parser.parse('I want 2 liters')[0].unit.entity print(entity.name) # 'volume' print(entity.uri) # 'https://en.wikipedia.org/wiki/Volume' print(entity.dimensions) # [{'base': 'length', 'power': 3}] ``` -------------------------------- ### Quantity Class Properties and Methods Source: https://context7.com/nielstron/quantulum3/llms.txt The Quantity class represents a parsed quantity with its value, unit, surface text, span, and optional uncertainty. You can access its properties and use methods like to_spoken() and to_dict() for conversion and export. ```python from quantulum3 import parser from quantulum3.classes import Quantity, Unit, Entity # Parse and access quantity properties quant = parser.parse('I want 2 liters of wine')[0] print(quant.value) # 2.0 print(quant.unit) # Unit(name="litre", entity=Entity("volume"), uri=https://en.wikipedia.org/wiki/Litre) print(quant.surface) # '2 liters' print(quant.span) # (7, 15) print(quant.uncertainty) # None print(quant.lang) # 'en_US' # Convert to spoken form print(quant.to_spoken()) # 'two litres' # Export to dictionary quant_dict = quant.to_dict() print(quant_dict) # {'value': 2.0, 'unit': 'litre', 'entity': 'volume', 'surface': '2 liters', 'span': (7, 15), 'uncertainty': None, 'lang': 'en_US'} ``` -------------------------------- ### Embed Quantities in Text with parser.inline_parse() Source: https://context7.com/nielstron/quantulum3/llms.txt Use parser.inline_parse() to parse text and embed extracted quantities inline. This is useful for debugging and visualization purposes. ```python from quantulum3 import parser result = parser.inline_parse('I want 2 liters of wine') print(result) # 'I want 2 liters {Quantity(2, "litre")} of wine' result = parser.inline_parse('The car goes 100 mph and weighs 2000 kg') print(result) # 'The car goes 100 mph {Quantity(100, "mile per hour")} and weighs 2000 kg {Quantity(2000, "kilogram")}' ``` -------------------------------- ### parser.parse() - Extract Quantities from Text Source: https://context7.com/nielstron/quantulum3/llms.txt The primary function for extracting all quantities from unstructured text. It returns a list of `Quantity` objects, each containing parsed values, units, entities, and position information. It supports ranges, uncertainties, spelled-out numbers, dimensionless numbers, derived units, and can use custom classifiers or enable verbose output. ```APIDOC ## parser.parse() ### Description Extracts all quantities from unstructured text and returns them as a list of `Quantity` objects. ### Method `parser.parse(text, classifier_path=None, verbose=False, lang='en_US')` ### Parameters #### Path Parameters None #### Query Parameters - **text** (string) - Required - The input text to parse. - **classifier_path** (string) - Optional - Path to a custom classifier model. - **verbose** (boolean) - Optional - If True, enables verbose debug output. - **lang** (string) - Optional - The language of the input text (default is 'en_US'). ### Request Example ```python from quantulum3 import parser quants = parser.parse('I want 2 liters of wine') print(quants) quant = quants[0] print(quant.value) print(quant.unit.name) print(quant.surface) print(quant.span) print(quant.unit.entity) quants = parser.parse('The LHC smashes proton beams at 12.8–13.0 TeV') print(quants) quant = parser.parse('The LHC smashes proton beams at 12.9±0.1 TeV')[0] print(quant.uncertainty) quants = parser.parse('I want a gallon of beer') print(quants) quants = parser.parse('I want two') print(quants) unit = parser.parse('Sound travels at 0.34 km/s')[0].unit print(unit) quants = parser.parse('I want 2 liters', classifier_path='path/to/model.joblib') quants = parser.parse('I want 2 liters', verbose=True) ``` ### Response #### Success Response (200) - **list of Quantity objects** - Each object contains `value`, `unit`, `surface`, `span`, `uncertainty`, and `lang` attributes. #### Response Example ```json [ { "value": 2.0, "unit": "litre", "surface": "2 liters", "span": [7, 15], "uncertainty": null, "lang": "en_US" } ] ``` ``` -------------------------------- ### Extract Quantities from Text with parser.parse() Source: https://context7.com/nielstron/quantulum3/llms.txt Use parser.parse() to extract all quantities from unstructured text. It returns a list of Quantity objects. This function can also parse ranges, uncertainties, spelled-out numbers, and dimensionless numbers. Optional arguments include classifier_path for custom models and verbose for debug output. ```python from quantulum3 import parser # Basic quantity extraction quants = parser.parse('I want 2 liters of wine') print(quants) # [Quantity(2, "litre")] # Access quantity properties quant = quants[0] print(quant.value) # 2.0 print(quant.unit.name) # 'litre' print(quant.surface) # '2 liters' print(quant.span) # (7, 15) print(quant.unit.entity) # Entity(name="volume", uri=https://en.wikipedia.org/wiki/Volume) # Parse ranges (returns averaged value with uncertainty) quants = parser.parse('The LHC smashes proton beams at 12.8–13.0 TeV') print(quants) # [Quantity(12.8, "teraelectronvolt"), Quantity(13, "teraelectronvolt")] # Parse uncertainties quant = parser.parse('The LHC smashes proton beams at 12.9±0.1 TeV')[0] print(quant.uncertainty) # 0.1 # Parse spelled-out numbers quants = parser.parse('I want a gallon of beer') print(quants) # [Quantity(1, 'gallon')] # Dimensionless numbers quants = parser.parse('I want two') print(quants) # [Quantity(2, 'dimensionless')] # Derived units with inferred entity unit = parser.parse('Sound travels at 0.34 km/s')[0].unit print(unit) # Unit(name="kilometre per second", entity=Entity("speed"), uri=None) # Use custom classifier model quants = parser.parse('I want 2 liters', classifier_path='path/to/model.joblib') # Enable verbose debug output quants = parser.parse('I want 2 liters', verbose=True) ``` -------------------------------- ### Create Modified Quantity Source: https://context7.com/nielstron/quantulum3/llms.txt Create a new Quantity object with updated values or uncertainty. This is useful for adjusting parsed quantities without altering the original. ```python new_quant = quant.with_vals(value=5.0, uncertainty=0.1) print(new_quant.value) # 5.0 print(new_quant.uncertainty) # 0.1 ``` -------------------------------- ### parser.inline_parse() - Embed Quantities in Text Source: https://context7.com/nielstron/quantulum3/llms.txt Parses text and embeds the extracted quantities inline within the text, which is useful for debugging and visualization purposes. ```APIDOC ## parser.inline_parse() ### Description Parses text and embeds the extracted quantities inline. ### Method `parser.inline_parse(text, lang='en_US')` ### Parameters #### Path Parameters None #### Query Parameters - **text** (string) - Required - The input text to parse. - **lang** (string) - Optional - The language of the input text (default is 'en_US'). ### Request Example ```python from quantulum3 import parser result = parser.inline_parse('I want 2 liters of wine') print(result) result = parser.inline_parse('The car goes 100 mph and weighs 2000 kg') print(result) ``` ### Response #### Success Response (200) - **string** - The input text with quantities embedded inline. #### Response Example ``` 'I want 2 liters {Quantity(2, "litre")} of wine' 'The car goes 100 mph {Quantity(100, "mile per hour")} and weighs 2000 kg {Quantity(2000, "kilogram")}' ``` ``` -------------------------------- ### Access Quantity attributes Source: https://github.com/nielstron/quantulum3/blob/dev/README.md The Quantity object stores the original surface text, its span, the parsed value, and unit information. ```python >>> quants[0].surface u'2 liters' ``` ```python >>> quants[0].span (7, 15) ``` ```python >>> quants[0].value 2.0 ``` ```python >>> quants[0].unit.name 'litre' ``` -------------------------------- ### Unit Disambiguation by Context Source: https://context7.com/nielstron/quantulum3/llms.txt The parser automatically disambiguates units like 'pounds' based on the surrounding text. It correctly identifies 'pound sterling' in a financial context and 'pound-mass' in a weight context. ```python quants = parser.parse('I spent 20 pounds on this!') print(quants[0].unit.name) # 'pound sterling' quants = parser.parse('It weighs no more than 20 pounds') print(quants[0].unit.name) # 'pound-mass' ```