API Reference

This package provides functionality for a universal time tracking system, able to measure time from the big bang, until the heat death of the universe, using meaningful decimal units based on seconds. It can be used to measure the time between any random events by getting the date from Gemini AI, convert between various time systems, and more….

Author: [Daniel Neagaru]

Core modules

utms.config

This module defines the Config class, which manages the configuration of time units and datetime anchors.

The Config class is responsible for populating predefined time units and datetime anchors. It uses the UnitManager class to manage time units such as Planck Time, Picoseconds, and Milliseconds, and the AnchorManager class to manage datetime anchors like Unix Time, CE Time, and Big Bang Time.

Constants from the constants module are used to define the values for the time units and anchors.

Modules: - utms.constants: Contains predefined constants for time and datetime values. - utms.anchors: Contains the AnchorManager class for managing datetime anchors. - utms.units: Contains the UnitManager class for managing time units.

Usage: - Instantiate the Config class to initialize the units and anchors with predefined values.

utms.config.get_ntp_date()[source]

Retrieves the current date in datetime format using an NTP (Network Time Protocol) server.

This function queries an NTP server (default is “pool.ntp.org”) to get the accurate current time. The NTP timestamp is converted to a UTC datetime object and formatted as a date string. If the NTP request fails (due to network issues or other errors), the function falls back to the system time.

Returns:

The current date in ‘YYYY-MM-DD’ format, either from the NTP server or the system clock as a fallback.

Return type:

str

Exceptions:
  • If the NTP request fails, the system time is used instead.

class utms.config.Config[source]

Configuration class that manages units and anchors for time and datetime references.

This class is responsible for populating time units and datetime anchors based on predefined constants. It uses the AnchorManager and UnitManager classes to add relevant time units and datetime anchors.

init_resources()[source]

Copy resources to the user config directory if they do not already exist.

Return type:

None

load()[source]

Load the configuration from the JSON file.

Returns:

Configuration data.

Return type:

dict

save()[source]

Save the configuration data to the JSON file.

Parameters:

config (dict) – Configuration data to be saved.

Return type:

None

load_anchors()[source]

Loads anchors from the ‘anchors.json’ file and populates the anchors dynamically.

This method reads the anchors.json file, parses its content, and uses the AnchorManager to add each anchor to the configuration.

Return type:

None

save_anchors()[source]

Saves the current anchors to the ‘anchors.json’ file.

This method serializes the anchors stored in the self.anchors set and writes them to the anchors.json file.

Return type:

None

load_units()[source]

Loads time units from the ‘units.json’ file and populates the units dynamically.

This method reads the units.json file, parses its content, and uses the UnitManager to add each unit to the configuration.

Return type:

None

save_units()[source]

Saves the current time units to the ‘units.json’ file.

This method serializes the time units stored in the self.units instance and writes them to the units.json file.

Return type:

None

get_value(key, pretty=False)[source]

Get the value from the configuration by key.

Parameters:
  • key (str) – The dot-separated key (e.g., ‘gemini.available_models[1]’).

  • pretty (bool) – If True, return the value formatted as pretty JSON.

Return type:

Union[Any, str]

Returns:

The value at the specified key.

has_value(key)[source]

Checks whether a nested key exists in the configuration and its value is not None.

Parameters:

key (str) – The dot-separated key path (e.g., ‘gemini.api_key’).

Return type:

bool

Returns:

True if the key exists and its value is not None, False otherwise.

set_value(key, value)[source]

Set a value in the configuration by key.

Parameters:
  • key (str) – The dot-separated key (e.g., ‘gemini.available_models[1]’).

  • value (Any) – The value to set.

Return type:

None

print(filter_key=None)[source]

Print the configuration in a formatted JSON style.

Optionally filters the output to display the value of a specific key path.

Parameters:

filter_key (str, optional) – A dot-separated key path to filter the config output (e.g., ‘gemini.api_key’). If provided, only the value of the specified key will be printed. If the key points to a nested dictionary or list, its content is displayed in a formatted manner.

Return type:

None

Raises:

KeyError – If the provided key path is invalid or does not exist in the configuration.

select_from_choices(key)[source]

Allow interactive selection for configuration parameters with a ‘_choices’ field.

If the specified configuration key has an associated ‘_choices’ field, this method displays the available options and prompts the user to select one. The selected value is then set as the new value for the key. If no ‘_choices’ field is found, the current value of the key is returned.

Parameters:

key (str) – The dot-separated key to check (e.g., ‘gemini.model’).

Returns:

The selected value from the available choices, or the current value if no choices are available. Returns None if the user does not make a choice.

Return type:

Any

Raises:

ValueError – If the ‘_choices’ field is not a list.

select_from_list(source_key, target_key, index)[source]

Assign an element from a JSON array to a target key in the configuration.

This method retrieves an element from a list at the specified source key and assigns it to the target key in the configuration. The element is identified by its index in the list.

Parameters:
  • source_key (str) – The dot-separated key path of the source list (e.g., ‘gemini.available_models’).

  • target_key (str) – The dot-separated key path of the destination (e.g., ‘gemini.model’).

  • index (int) – The index of the element to select from the list.

Raises:
  • KeyError – If the source or target key paths are invalid.

  • ValueError – If the source key does not refer to a list or the index is out of range.

Return type:

None

select_from_list_interactive(source_key, target_key)[source]

Prompt the user to select an element from a JSON array interactively.

This method retrieves a list from the specified source key, displays the available elements to the user, and prompts them to select one by index. The selected element is then assigned to the target key in the configuration.

Parameters:
  • source_key (str) – The dot-separated key path of the source list (e.g., ‘gemini.available_models’).

  • target_key (str) – The dot-separated key path of the destination (e.g., ‘gemini.model’).

Raises:
  • KeyError – If the source or target key paths are invalid.

  • ValueError – If the source key does not refer to a list.

Return type:

None

populate_dynamic_anchors()[source]

Populates the AnchorManager instance with predefined datetime anchors.

This method adds various datetime anchors such as Unix Time, CE Time, and Big Bang Time, using the add_datetime_anchor and add_decimal_anchor methods of the AnchorManager instance. Each anchor is added with its name, symbol, and corresponding datetime value.

Return type:

None

utms.ai

This module integrates the Gemini model from the Google Generative AI API to generate precise date and time strings in ISO 8601 format based on input descriptions of events or concepts.

The module is specifically designed to handle a wide range of date inputs, including: - Common Era (CE) events, formatted in full ISO 8601 format. - Before Common Era (BCE) events, using a leading minus (-) and ISO-like formatting. - Events far in the future (beyond 9999 CE) or distant past (beyond -9999 BCE) using scientific

notation or relative years.

  • Relative dates (e.g., “yesterday”, “5 days ago”) by calculating the corresponding date in ISO 8601 format.

  • Unknown or uncertain dates, where the model defaults to UNKNOWN if no valid date can be determined.

Key Features: 1. Precise Formatting:

  • ISO 8601 compliance for all generated dates, including timezone offsets.

  • Default values for unknown time components (e.g., 00:00:00 for time, 01 for unknown days).

  • Special handling for extreme ranges, such as prehistoric or far-future events.

  1. Configurable Generation: - The model is pre-configured with parameters for controlling output length, randomness, and

    sampling strategies: - max_output_tokens=30: Limits the response length. - temperature=0.7: Balances randomness and determinism in output. - top_p=0.9: Enables nucleus sampling for high-probability outputs. - top_k=50: Limits the model’s output options to the top 50 tokens.

  2. Error Handling: - Robust error handling for API connectivity issues, invalid responses, and unexpected model

    outputs.

    • Provides clear fallback messages in case of failures.

Functions: - ai_generate_date(input_text: str) -> str:

Takes a natural language description of an event or date concept and returns a formatted ISO 8601 date string, adhering to predefined formatting rules.

Dependencies: - google.generativeai: For interacting with the Gemini model. - requests: For handling API connectivity.

Usage Example: ```python >>> ai_generate_date(“When did the Apollo 11 moon landing occur?”) “1969-07-20T00:00:00+00:00”

>>> ai_generate_date("5 days before the fall of the Berlin Wall")
"1989-11-04T00:00:00+00:00"
class utms.ai.AI(config)[source]

A class for interfacing with the Gemini Generative AI model.

This class manages the configuration, initialization, and interaction with the Gemini AI API. It includes functionality for generating date-related outputs in ISO format.

config

The configuration for generation, including parameters such as maximum output tokens, temperature, top-p, and top-k.

Type:

genai.GenerationConfig

model

The initialized generative AI model.

Type:

genai.GenerativeModel

generate_date(input_text

str) -> str: Generates a date based on the provided input text using the Gemini AI model.

generate_date(input_text)[source]

Generate a date string in ISO 8601 format from an input text using the Gemini model.

This function generates a precise date in ISO 8601 format based on the input text using the Gemini model. The model is configured to handle dates in various ranges, including Common Era (CE), Before Common Era (BCE), events beyond 9999 CE, relative dates (e.g., “yesterday”, “5 days ago”), and uncertain or unknown dates.

The generated date adheres to strict formatting rules, such as including the correct timezone offset (+00:00 for UTC) and handling missing or uncertain date components by substituting default values like 01 for missing days and months, or 00:00:00 for missing time.

If the model’s response is valid and provides a correctly formatted ISO 8601 date, the function returns it. If the response is invalid, an appropriate fallback message is returned. In case of errors during the model call, the error message is returned.

Parameters:
  • input_text (str) – The input text describing the event or

  • generated. (concept for which a date should be)

Returns:

The generated date in ISO 8601 format, or a fallback

message if the model’s response is invalid or an error occurs.

Return type:

str

Example

>>> ai_generate_date("What is the date of the Apollo 11 moon landing?")
"1969-07-20T00:00:00+00:00"
>>> ai_generate_date("Tell me a random date")
"No valid response received from the API."
Model Configuration:

The model is configured with the following settings:

  • max_output_tokens=30: Limits the length of the model’s response.

  • temperature=0.7: Controls the randomness of the generated content.

  • top_p=0.9: Implements nucleus sampling to select from the top 90% of possible outputs.

  • top_k=50: Limits the possible outputs to the top 50 tokens.

Date Formatting Rules:

The model is instructed to strictly adhere to the following date formatting rules:

  • For Common Era (CE) events: Output the date in full ISO

    8601 format (YYYY-MM-DDTHH:MM:SS+ZZ:ZZ).

  • For Before Common Era (BCE) events: Output the date with

    a leading minus (-YYYY-MM-DD).

  • For events after 9999 CE: Use a + prefix and ISO 8601 format.

  • For relative dates: Calculate the exact ISO 8601 date.

  • For unknown dates: Return UNKNOWN, but avoid unless absolutely necessary.

  • For date ranges: Default to the beginning of the range.

The model is also instructed to avoid providing explanations or context; it should return only the date.

resolve_date(input_text)[source]

Resolves a date from a given string input. The function first attempts to parse the date using dateparser, and if unsuccessful, it uses an AI-based approach to generate a potential date.

The function supports:

  • Parsing valid dates from input text (via dateparser).

  • Handling historical dates expressed as negative years (e.g., ‘-44’ for 44 BCE).

  • Interpreting future events expressed with a ‘+’ sign (e.g., ‘+10’ for 10 years from now).

  • Processing ISO 8601 formatted dates returned by the AI.

Parameters:

input_text (str) – The input string representing the date to resolve. The input can be in formats compatible with dateparser or in special formats (e.g., BCE or future years).

Returns:

  • datetime object if a valid date is resolved.

  • Decimal representing seconds for future events or years before the common era.

  • None if the date cannot be resolved.

Return type:

Union[datetime, Decimal, None]

Raises:

ValueError – If both dateparser and the AI approach fail to resolve a date.

Example

>>> resolve_date("2024-12-11")
datetime.datetime(2024, 12, 11, 0, 0, tzinfo=datetime.timezone.utc)
>>> resolve_date("-44")  # 44 BCE
Decimal('-69422400000')
>>> resolve_date("+10")  # 10 years from now
Decimal('315569520')

Notes

  • The function first attempts to parse the date using the resolve_date_dateparser function. If that fails, it invokes the AI-based date generator.

  • The AI response is expected to be one of:
    • A valid ISO 8601 date string.

    • A negative number representing historical years (BCE).

    • A positive number indicating future years (converted to seconds).

  • Historical dates are converted into seconds using a year-based approximation or ISO 8601 representation when available.

  • Future dates are expressed in seconds from the current time.

utms.anchors

Module: Anchor Management for Time Anchors

This module provides utilities for creating and managing time anchors. Time anchors are representations of specific points in time or numerical values associated with a precision, which can be accessed and organized efficiently.

The module includes two main classes:

  1. Anchor: - Represents a single time anchor with a name, value, and precision. - Designed for simplicity, allowing direct access to attributes such as name,

    value, and precision.

  2. AnchorManager: - Manages multiple time anchors, enabling functionalities such as adding anchors,

    iterating over them, and accessing anchors by index or label.

    • Supports anchors defined by both datetime and Decimal values, with customizable precision.

Features: - Add datetime or decimal-based anchors with specific labels and precision. - Retrieve anchors by label or numerical index. - Iterate over all anchors managed by the class. - Handle edge cases for ancient dates (adjusting for negative timestamps). - Ensure type safety and robust exception handling for invalid access.

Dependencies: - datetime and timezone: For working with time-based anchors. - decimal.Decimal: To ensure precise numerical representation for anchor values. - utms.constants: Provides constants used for calculations, such as SECONDS_IN_YEAR.

Example Usage:

```python from datetime import datetime, timezone from decimal import Decimal from utms.anchor_manager import AnchorManager

# Initialize an AnchorManager manager = AnchorManager()

# Add a datetime anchor manager.add_datetime_anchor(

name=”Epoch Start”, label=”epoch”, value=datetime(1970, 1, 1, tzinfo=timezone.utc)

)

# Add a decimal anchor manager.add_decimal_anchor(

name=”Custom Anchor”, label=”custom”, value=Decimal(“12345.6789”), precision=Decimal(“0.001”)

)

# Access anchors by label epoch_anchor = manager[“epoch”]

# Iterate through all anchors for anchor in manager:

print(anchor.name, anchor.value, anchor.precision)

# Get the number of anchors print(len(manager))

class utms.anchors.AnchorConfig(label: str, name: str, value: Decimal | datetime, breakdowns: List[List[str]] | None = None, groups: List[str] | None = None, precision: Decimal | None = None)[source]

Configuration for defining a time anchor.

This class encapsulates the essential attributes needed to configure a time anchor, including its full name, value, precision, and breakdown structure.

name

The full descriptive name of the anchor.

Type:

str

value

The numeric value associated with the anchor.

Type:

Decimal

precision

The precision to use for calculations involving the anchor.

Type:

Decimal

breakdowns

A nested list defining the breakdown structure for the anchor, where each sublist represents a level of detail (e.g., [“hours”, “minutes”, “seconds”]).

Type:

List[List[str]]

label: str

Alias for field number 0

name: str

Alias for field number 1

value: Union[Decimal, datetime]

Alias for field number 2

breakdowns: Optional[List[List[str]]]

Alias for field number 3

groups: Optional[List[str]]

Alias for field number 4

precision: Optional[Decimal]

Alias for field number 5

class utms.anchors.Anchor(anchor_config)[source]

Represents a single time anchor with a full name, value, precision, and associated breakdown formats.

This class provides functionality to break down a total duration in seconds into a human-readable format using a configurable set of units. It allows the conversion of a given duration into various time units (e.g., hours, minutes, seconds) while considering the precision for breakdown.

name

The full name of the anchor (e.g., “Total Time”).

Type:

str

value

The value associated with the anchor (e.g., total time value in seconds).

Type:

Decimal

precision

The precision threshold for unit breakdown (e.g., the smallest unit for

Type:

Decimal

display).
breakdowns

A list of breakdown formats, each containing a list of unit abbreviations (e.g., [[“h”, “m”, “s”]]).

Type:

List[List[str]]

breakdown(total_seconds

Decimal, units: UnitManager) -> str: Breaks down a given total duration (in seconds) into the configured units and returns a formatted string representing the breakdown.

_apply_color(value

str, color: str = Fore.BLUE) -> str: Applies the specified color style to the given value.

_format_breakdown_entry(count

Union[int, Decimal], unit: str) -> str: Formats a single breakdown entry, ensuring proper string formatting and color styling.

_calculate_breakdown(total_seconds

Decimal, breakdown_units: List[str], units: UnitManager)

-> List[str]

Calculates the breakdown for a given set of units based on the total duration and precision.

print()[source]

Print details of a single anchor by label.

Return type:

None

breakdown(total_seconds, units)[source]

Breaks down a duration in seconds into multiple unit formats.

Parameters:
  • total_seconds (Decimal) – Total duration in seconds.

  • units (UnitManager) – UnitManager instance for unit details.

Returns:

A formatted string representing the breakdown.

Return type:

str

class utms.anchors.AnchorManager(units)[source]

A class to manage time anchors, allowing adding new anchors, sorting by value, and accessing them by abbreviation.

add_anchor(anchor_config)[source]

Adds a new anchor using the given configuration object.

Parameters:

anchor_config (AnchorConfig) – AnchorConfig object containing the configuration for the new anchor.

Return type:

None

delete_anchor(label)[source]

Deletes an anchor by its label.

Parameters:

label (str) – The label of the anchor to delete.

Raises:

KeyError – If the label does not exist in the manager.

Return type:

None

__iter__()[source]

Returns an iterator over the anchors.

Return type:

Iterator[Anchor]

Returns:

An iterator of Anchor objects.

__getitem__(index)[source]

Makes the class subscriptable by allowing access via index or label.

Parameters:

index (Union[int, str]) – The index or label of the item to retrieve.

Return type:

Anchor

Returns:

An Anchor object.

Raises:
  • KeyError – If the label is not found.

  • IndexError – If the index is out of range.

__len__()[source]

Returns the number of anchors in the manager.

Return type:

int

Returns:

The number of anchors.

get(label)[source]

Retrieves the anchor with the specified label.

Parameters:

label (str) – The label of the anchor to retrieve.

Returns:

The anchor with the given label, or None if no such anchor exists.

Return type:

Optional[Anchor]

get_label(anchor)[source]

Returns the label associated with a given anchor.

Parameters:

anchor (Anchor) – The Anchor instance.

Return type:

str

Returns:

The label corresponding to the anchor.

Raises:

ValueError – If the anchor is not found in the manager.

get_anchors_by_group(group_name)[source]

Retrieves a list of anchors that belong to the specified group.

Parameters:

group_name (str) – The name of the group to filter anchors.

Returns:

A list of anchors belonging to the specified group.

Return type:

List[Anchor]

get_anchors_from_str(input_text)[source]

Parses a comma-separated string and returns a sorted list of Anchor objects.

This method splits the input string by commas, retrieves Anchor objects associated with each item, and adds them to a list. It also includes additional anchors based on groups associated with each item. The resulting list is sorted by the value attribute of the Anchor objects.

Parameters:

input_text (str) – A comma-separated string of items, each representing an anchor or group identifier.

Returns:

A sorted list of Anchor objects.

Return type:

List[Anchor]

Raises:

ValueError – If any of the items in the input string cannot be resolved to an Anchor object.

Notes

  • The method first retrieves anchors using the get() method, and then appends anchors retrieved by group using get_anchors_by_group().

  • The sorting is done based on the value attribute of the Anchor objects.

print(label=None)[source]

Prints details of all anchors inside the AnchorManager.

Return type:

None

utms.units

Unit Management Module

This module provides a class, UnitManager, for managing time units. It allows users to add, retrieve, and sort time units by their values (in seconds), as well as print the units and generate conversion tables for easy comparison.

Classes:
  • UnitManager: Handles the addition, management, and retrieval of time units.

Dependencies:
  • decimal.Decimal: For precise arithmetic with time unit values.

  • utms.utils.format_value: A utility function for formatting values.

Features:
  1. Add new time units with a full name, abbreviation, and value (in seconds).

  2. Retrieve time unit values or details by their abbreviation.

  3. Retrieve all stored time units in a sorted dictionary.

  4. Print time units and their details.

  5. Generate and print a conversion table centered around a specific time unit.

Usage:

```python from decimal import Decimal from time_unit_manager import UnitManager

# Initialize the manager manager = UnitManager()

# Add time units manager.add_unit(“Second”, “s”, Decimal(“1”)) manager.add_unit(“Minute”, “m”, Decimal(“60”)) manager.add_unit(“Hour”, “h”, Decimal(“3600”))

# Print all units manager.print_units()

# Print a conversion table centered around seconds manager.print_conversion_table(“s”, num_columns=2, num_rows=5)

utms.units.format_value(value, threshold=Decimal('1E+7'), small_threshold=Decimal('0.001'))[source]

Format a numeric value based on specified thresholds, using conditional formatting.

The function formats the value based on its magnitude, and applies different styles depending on whether the value is above or below specific thresholds.

Parameters:
  • value (Decimal) – The numeric value to format.

  • threshold (Decimal, optional) – The threshold above which

  • 1e7. (scientific notation is used. Defaults to)

  • small_threshold (Decimal, optional) – The threshold below which

  • to (scientific notation with 3 decimal places is used. Defaults)

  • 0.001.

Returns:

The formatted string representation of the value with appropriate styles applied.

Return type:

str

Formatting Rules:
  • Values smaller than small_threshold are formatted in scientific notation with 3 decimal places in red.

  • Values larger than small_threshold but smaller than threshold:
    • Integer values are formatted with no decimal places in green.

    • Values greater than 1 are formatted with 5 decimal places in green.

    • Values close to zero are formatted with 3 or 5 decimal places in red depending on precision.

  • Values greater than or equal to threshold are formatted in scientific notation with 3 decimal places in green.

  • All formatting is left-aligned in a 33-character wide field.

Example

>>> format_value(123456.789)
'123456.78900'  # Example output with a large value
>>> format_value(0.000000123)
'1.230e-07'  # Example output for a small value
class utms.units.Unit(name, abbreviation, value)[source]

Represents a time unit with a full name, abbreviation, and value in seconds. Provides methods for comparisons, conversions, and formatting.

name

The full name of the time unit.

Type:

str

abbreviation

The abbreviation of the time unit.

Type:

str

value

The value of the time unit in seconds.

Type:

Decimal

__repr__()[source]

Provides a string representation of the Unit instance.

Returns:

A string representation of the unit.

Return type:

str

__eq__(other)[source]

Compares two Unit instances for equality based on value.

Parameters:

other (object) – The other object to compare to.

Returns:

True if both units are equal, False otherwise.

Return type:

bool

__lt__(other)[source]

Compares two Unit instances for less-than based on value.

Parameters:

other (object) – The other object to compare to.

Returns:

True if this unit is less than the other unit, False otherwise.

Return type:

bool

convert_to(other, value)[source]

Converts a value from this unit to another unit.

Parameters:
  • other (Unit) – The unit to convert to.

  • value (Decimal) – The value to convert.

Returns:

The converted value in the new unit.

Return type:

Decimal

__str__()[source]

Provides a human-readable string for the unit.

Returns:

A string representation of the unit.

Return type:

str

class utms.units.UnitManager[source]

A class to manage time units, allowing adding new units, sorting by value, and accessing them by abbreviation.

add_unit(name, abbreviation, value)[source]

Adds a new time unit to the manager and ensures the units are sorted by value.

Parameters:
  • name (str) – The full name of the time unit.

  • abbreviation (str) – The abbreviation of the time unit.

  • value (Decimal) – The value of the unit in seconds.

Return type:

None

get_value(abbreviation)[source]

Get a unit value by its abbreviation.

Parameters:

abbreviation (str) – The abbreviation of the time unit.

Returns:

A Decimal value of the unit

Return type:

value

get_unit(abbreviation)[source]

Get a time unit by its abbreviation.

Parameters:

abbreviation (str) – The abbreviation of the time unit.

Returns:

A dictionary containing ‘name’ and ‘value’ of the time unit.

Return type:

dict

get_all_units()[source]

Get all the time units stored in the manager.

Returns:

A dictionary with abbreviations as keys and unit information as values.

Return type:

dict

__iter__()[source]

Returns an iterator over the abbreviations of all time units.

Return type:

Iterator[str]

Returns:

An iterator of unit abbreviations.

__getitem__(index)[source]

Makes the class subscriptable by allowing access via abbreviation or index.

Parameters:

index (int or str) – The abbreviation or index of the unit.

Returns:

A dictionary containing ‘name’ and ‘value’ of the time unit.

Return type:

dict

Raises:
  • KeyError – If the abbreviation does not exist.

  • IndexError – If the index is out of range.

__len__()[source]

Returns the number of time units in the manager.

Return type:

int

Returns:

The number of units.

print(args)[source]

Prints all time units sorted by their value in seconds.

Return type:

None

print_conversion_table(center_unit, num_columns=5, num_rows=100)[source]

Prints a table of time unit conversions centered around a specific unit.

Parameters:
  • center_unit (str) – The abbreviation of the unit around which the table will be centered.

  • num_units (int) – The number of units to display on either side of the center unit. Defaults to 5.

Return type:

None

Example

manager.print_conversion_table(“s”, 3) This will print a table centered around “s”, showing 3 units to the left and right.

convert_units(args)[source]

Convert a given value from one unit to all other units and print the results.

Parameters:
  • value (Decimal) – The value to be converted.

  • input_unit (str) – The abbreviation of the unit of the input value.

Raises:

ValueError – If the input unit is not found in the manager.

Return type:

None

utms.clock

This module provides functionality for creating and updating both analog and decimal clocks using the Tkinter GUI framework. It supports the display of time in traditional 24-hour format as well as in decimal time (divided into decidays, centidays, and seconds).

The clocks are drawn on a canvas with customizable styles for various components such as hands, ticks, and backgrounds. The module uses a global styles dictionary to control colors, fonts, and other visual aspects, ensuring a consistent look across the clocks.

Main Features:

  • Analog clock with 24-hour format and decimal clock using the Swatch Internet Time system.

  • Customizable clock hands (hour, minute, second, deciday, centiday) with different lengths and colors.

  • Digital time display below the clock with configurable font and color.

  • Inner circular scale displaying ticks and numbers for both analog and decimal clocks.

  • Real-time updates with smooth transitions using the update_clock function.

  • Modular approach with helper functions to handle specific parts of the clock, such as drawing hands, updating kiloseconds/decidays, and drawing the clock face.

Functions:

  • update_clock: Updates clock hands and digital time, switching between analog and decimal time.

  • draw_hand: Draws a clock hand as a trapezoid with a triangular tip.

  • draw_inner_scale: Draws an inner circular scale with ticks for time tracking.

  • draw_clock_face: Draws the clock face, including tick marks and numbers.

  • update_kiloseconds: Displays kiloseconds below the clock in the analog time format.

  • update_decidays: Displays decidays below the clock in decimal time format.

  • run_clock: Main function to initialize the Tkinter window and start both analog and decimal clocks.

The module allows users to run a clock that displays time in either the traditional 24-hour format or in a decimal-based time system, providing a visually appealing and functional experience.

Dependencies:

  • math: For trigonometric calculations used in drawing hands and clock ticks.

  • os: Used for system-level operations (though not explicitly used in this module).

  • time: For time-related functions and to retrieve the current system time.

  • tkinter: For creating and updating the graphical user interface.

  • datetime: For working with date and time, especially in retrieving the current time.

class utms.clock.CanvasConfig(canvas: Canvas, width: int, height: int, center: Tuple[int, int])[source]

Configuration for the canvas used to draw the clock.

canvas

The tkinter canvas object where the clock is drawn.

Type:

tk.Canvas

width

The width of the canvas in pixels.

Type:

int

height

The height of the canvas in pixels.

Type:

int

center

The coordinates of the canvas center as (x, y).

Type:

Tuple[int, int]

canvas: Canvas

Alias for field number 0

width: int

Alias for field number 1

height: int

Alias for field number 2

center: Tuple[int, int]

Alias for field number 3

class utms.clock.HandConfig(length: float, angle: float, base_width: int, color: str, tag: str)[source]

Configuration for a clock hand.

length

The length of the clock hand in pixels.

Type:

float

angle

The angle of the clock hand in radians, relative to 12 o’clock.

Type:

float

base_width

The base width of the clock hand in pixels.

Type:

int

color

The color of the clock hand as a hexadecimal or color name.

Type:

str

tag

The tag used for grouping the clock hand in the canvas.

Type:

str

length: float

Alias for field number 0

angle: float

Alias for field number 1

base_width: int

Alias for field number 2

color: str

Alias for field number 3

tag: str

Alias for field number 4

class utms.clock.Styles[source]

Configuration for the visual styles of the clock.

background_color

The background color of the clock as a hexadecimal or color name.

Type:

str

inner_color

The inner color of the clock face as a hexadecimal or color name.

Type:

str

frame_color

The color of the clock frame as a hexadecimal or color name.

Type:

str

center_circle_color

The color of the clock’s center circle.

Type:

str

hand_colors

A mapping of hand names (‘hour’, ‘minute’, etc.) to their

Type:

Dict[str, str]

colors.
hand_widths

A mapping of hand names to their widths in pixels.

Type:

Dict[str, int]

tick_color

The color of the clock’s tick marks.

Type:

str

outline_color

The color of the clock’s outline.

Type:

str

digit_color

The color of the clock’s digits.

Type:

str

font

The font and size used for the clock’s digits.

Type:

Tuple[str, int]

digital_time_color

The color of the digital time display.

Type:

str

digital_font

The font and size used for the digital time display.

Type:

Tuple[str, int]

scale_tick_color

The color of the scale tick marks.

Type:

str

scale_digit_color

The color of the scale digits.

Type:

str

kilosecond_color

The color of the kilosecond hand.

Type:

str

deciday_color

The color of the deciday hand.

Type:

str

background_color: str
inner_color: str
frame_color: str
center_circle_color: str
hand_colors: Dict[str, str]
hand_widths: Dict[str, int]
tick_color: str
outline_color: str
digit_color: str
font: Tuple[str, int]
digital_time_color: str
digital_font: Tuple[str, int]
scale_tick_color: str
scale_digit_color: str
kilosecond_color: str
deciday_color: str
utms.clock.calculate_angles(seconds_since_midnight, is_decimal)[source]

Calculates the angles of the clock hands based on whether it’s decimal time or not.

Return type:

Tuple[float, float, float, Optional[float], Optional[float]]

utms.clock.prepare_hands_and_angles(hands, angles, is_decimal)[source]

Prepare the hands to draw based on the mode (decimal vs.

analog). Returns a list of hands and associated angles to draw.

Return type:

List[Tuple[str, float, float]]

utms.clock.draw_clock_hands(canvas_config, hands_and_angles, tag_prefix)[source]

Draw the clock hands based on the calculated hands and angles.

Return type:

None

utms.clock.update_digital_time(canvas_config, hands, tag_prefix, is_decimal, seconds_since_midnight)[source]

Updates and displays the digital time (either analog or decimal).

Return type:

None

utms.clock.update_clock(canvas_config, hands, tag_prefix, is_decimal=False)[source]

Updates the positions of the clock hands and the digital time display.

Uses the styles dictionary for colors and font.

Return type:

None

utms.clock.calculate_hand_geometry(center, length, angle, base_width)[source]

Calculates the geometry of the clock hand.

Parameters:
  • center (tuple) – Center of the clock (x, y).

  • length (int) – Length of the hand.

  • angle (float) – Angle of the hand in radians.

  • base_width (int) – Width of the hand base.

Returns:

Coordinates of the hand’s key points.

Return type:

dict

utms.clock.draw_hand(canvas_config, hand_config)[source]

Draws a clock hand with an arrow-like shape, where the tip is a single point, and the hand widens to its base near the center.

Parameters:
  • canvas (tk.Canvas) – Canvas to draw on.

  • center (tuple) – Center of the clock (x, y).

  • length (int) – Length of the hand.

  • angle (float) – Angle of the hand in radians.

  • base_width (int) – Maximum width of the hand at the middle.

  • color (str) – Color of the hand.

  • tag (str) – Unique tag for the hand.

Return type:

None

utms.clock.calculate_tick_coordinates(center, radius, angle, tick_length)[source]

Calculates the coordinates for the ends of a tick line.

Parameters:
  • center (tuple) – Center of the circle (x, y).

  • radius (int) – Radius of the circle.

  • angle (float) – Angle of the tick in radians.

  • tick_length (int) – Length of the tick.

Returns:

Coordinates of the tick line’s start and end points.

Return type:

tuple

utms.clock.calculate_digit_coordinates(center, tick_length, angle, offset=5)[source]

Calculates the coordinates for positioning a digit near a tick.

Parameters:
  • center (tuple) – Center of the circle (x, y).

  • tick_length (int) – Length of the tick.

  • angle (float) – Angle of the tick in radians.

  • offset (int) – Offset from the tick’s end for placing the digit.

Returns:

Coordinates for the digit’s placement.

Return type:

tuple

utms.clock.draw_inner_scale(canvas_config, radius, num_ticks, scale_tag)[source]

Draws an inner circular scale with ticks, using the styles dictionary for tick colors and font.

Parameters:
  • canvas_config (CanvasConfig) – Canvas and center configuration.

  • radius (int) – Radius of the scale.

  • num_ticks (int) – Number of ticks to draw.

  • scale_tag (str) – Tag for identifying scale elements.

  • scale_type (str) – Type of scale (e.g., “seconds”, “centidays”).

Return type:

None

utms.clock.draw_outer_frame(canvas_config, radius, tag)[source]

Draws the metallic outer frame of the clock.

Parameters:
  • canvas (tk.Canvas) – Canvas to draw on.

  • center (tuple) – Center of the clock (x, y).

  • radius (int) – Radius of the clock.

  • tag (str) – Unique tag for the outer frame.

Return type:

None

utms.clock.draw_inner_circle(canvas_config, radius, tag)[source]

Draws the inner circle of the clock (background).

Parameters:
  • canvas (tk.Canvas) – Canvas to draw on.

  • center (tuple) – Center of the clock (x, y).

  • radius (int) – Radius of the clock.

  • tag (str) – Unique tag for the inner circle.

Return type:

None

utms.clock.draw_tick(canvas_config, radius, angle, is_major, tag)[source]

Draws a single tick on the clock face.

Parameters:
  • canvas (tk.Canvas) – Canvas to draw on.

  • center (tuple) – Center of the clock (x, y).

  • radius (int) – Radius of the clock.

  • angle (float) – Angle of the tick in radians.

  • is_major (bool) – Whether the tick is a major (large) tick.

  • tag (str) – Unique tag for the ticks.

Return type:

None

utms.clock.draw_tick_label(canvas_config, radius, angle, label, tag)[source]

Draws a label (number) next to a major tick.

Parameters:
  • canvas (tk.Canvas) – Canvas to draw on.

  • center (tuple) – Center of the clock (x, y).

  • radius (int) – Radius of the clock.

  • angle (float) – Angle of the tick in radians.

  • label (str) – Label text.

  • tag (str) – Unique tag for the labels.

Return type:

None

utms.clock.draw_clock_face(canvas_config, radius, is_decimal=False)[source]

Draws the clock face with tick marks, labels, and a chrome-style frame.

Parameters:
  • canvas_config (CanvasConfig) – Canvas and center configuration.

  • radius (int) – Radius of the clock.

  • is_decimal (bool) – Whether this clock uses the decimal time system.

Return type:

None

utms.clock.update_clock_with_inner_scale(canvas_config, hands, tag_prefix, is_decimal=False)[source]

Updates the clock with an inner scale for tracking seconds within centiday with neon effects.

Parameters:
  • canvas (tk.Canvas) – The canvas to draw on.

  • width (int) – The width of the canvas.

  • height (int) – The height of the canvas.

  • center (tuple) – The center of the clock as (x, y).

  • hands (dict) – A dictionary with keys ‘hour’, ‘minute’, ‘second’ or ‘deciday’, ‘centiday’,

  • 'second'.

  • tag_prefix (str) – A unique tag prefix to manage hands and digital time for each clock.

  • is_decimal (bool) – Whether this clock uses the decimal time system.

Return type:

None

utms.clock.update_kiloseconds(canvas_config, scale_tag, clock_time)[source]

Update and display the kiloseconds at the bottom of the right clock, below the current time.

Parameters:
  • canvas (tk.Canvas) – The canvas to draw on.

  • center (tuple) – The center of the clock as (x, y).

  • radius (int) – The radius of the inner scale.

  • scale_tag (str) – A unique tag to manage the scale.

  • clock_time (int) – The number of seconds since midnight.

Return type:

None

utms.clock.update_decidays(canvas_config, scale_tag, clock_time)[source]

Update the display of decidays on a canvas.

This function calculates the decidays (1 deciday = 8640 seconds) based on the current clock_time, and updates the specified canvas with the calculated value. The deciday value is displayed below the kiloseconds on the canvas.

Parameters:
  • canvas_config (CanvasConfig) – A configuration object containing the canvas, center, and height information for rendering. - canvas: The drawing canvas where the decidays text will be displayed. - center: A tuple of (x, y) coordinates representing the center of the canvas. - height: The base height used for scaling the display radius.

  • scale_tag (str) – A unique tag used to identify and update the decidays text element on the canvas.

  • clock_time (int) – The current time in seconds since midnight.

Return type:

None

Returns:

None

Notes

  • The decidays are calculated as: decidays = (clock_time % 86400) / 8640 where 86400 seconds represents a full day.

  • The text is formatted to 5 decimal places for precision.

Example

Assuming canvas_config has a canvas centered at (100, 100) and a height of 50:

>>> update_decidays(canvas_config, "time_display", 43200)
# Displays "5.00000 dd" on the canvas centered at (100, 100 + 0.25 * radius).
utms.clock.run_clock()[source]

Main function to set up the clock window and start the clocks.

Return type:

None

utms.utils

Module for Time Calculations, Conversion, and Formatting.

This module provides various functions related to time calculations, including resolving dates, calculating Universal Planck Count (UPC), converting time into different units, and formatting the output for display. The module uses NTP (Network Time Protocol) to fetch accurate timestamps and offers utilities for handling time in both human-readable formats and scientific units such as petaseconds, teraseconds, and gigaseconds.

Key Features: - Fetching NTP time and converting to UTC datetime. - Calculating total time since the Big Bang and Universal Planck Count. - Converting time to different units and displaying it in human-readable formats. - Formatting and printing results with color coding for easier readability. - Resolving dates using dateparser and AI-based generation. - Supporting historical dates and future events resolution.

Dependencies: - socket: For network communication. - datetime: For working with date and time objects. - decimal: For precise time calculations. - ntplib: For querying time from NTP servers. - dateparser: For parsing date strings. - colorama: For styling the output with colors. - utms: For constants related to time units and their conversions.

Functions: - get_ntp_time(): Fetches the current time from an NTP server. - get_current_time_ntp(): Returns the current NTP time as a UTC datetime object. - calculate_total_time_seconds(): Computes the total time elapsed since the Big Bang. - calculate_upc(): Calculates the Universal Planck Count. - return_old_time_breakdown(): Converts time into a human-readable breakdown (years, days, etc.). - return_time_breakdown(): Converts time into various scientific units (petaseconds, etc.). - print_results(): Prints time breakdown in both human-readable and scientific units. - resolve_date_dateparser(): Resolves a date using the dateparser library. - resolve_date(): Resolves a date using dateparser and AI generation as a fallback. - print_datetime(): Prints time in various formats (CE, Millennium, Unix, UPC, etc.). - print_header(): Prints a header with cyan and bright styling. - old_unit(): Applies magenta styling to a unit string. - new_unit(): Applies green styling to a unit string.

Example usage:
  • Fetch current NTP time: get_ntp_time()

  • Convert time to UTC: get_current_time_ntp()

  • Calculate UPC: calculate_upc()

  • Print time breakdowns: print_results(total_seconds)

  • Resolve a date string: resolve_date(“2024-12-14”)

Notes: - The module applies different color styles (using colorama) to improve the display of time

breakdowns and units.

  • Date parsing includes fallback to AI-based date generation if parsing fails.

utms.utils.resolve_date_dateparser(input_text)[source]

Parses a string representing a date and returns the corresponding UTC datetime object.

This function uses the dateparser library to parse the input date string into a datetime object. If the parsed date is timezone-naive, it will be assumed to be in UTC and made timezone-aware. The result is then returned as a UTC timezone-aware datetime object.

Parameters:

input_text (str) – The input string containing the date to parse. The string should represent a date in a format supported by the dateparser library.

Returns:

A timezone-aware datetime object in UTC if

the parsing is successful. Returns None if the parsing fails.

Return type:

Optional[datetime]

Example

>>> resolve_date_dateparser("2024-12-11 14:30")
datetime.datetime(2024, 12, 11, 14, 30, tzinfo=datetime.timezone.utc)
Exceptions:
  • If the input string cannot be parsed into a valid date, None will be returned.

  • If the parsed date is timezone-naive, it is assumed to be in UTC and made timezone-aware.

Notes

  • This function depends on the dateparser library to parse the input string.

  • The function ensures the returned datetime is in UTC and timezone-aware, even if the input date is naive.

utms.utils.print_time(timestamp, config, anchors=None, breakdowns=None, plt=False)[source]

Prints the time-related calculations for a given timestamp or total seconds value in various formats: ‘CE Time’, ‘Millenium Time’, ‘Now Time’, ‘UPC Time’, and ‘Life Time’.

The function handles both datetime (in UTC) or Decimal representing seconds since the UNIX epoch.

Parameters:
  • timestamp (Union[datetime, Decimal]) – The input timestamp (in UTC) or total seconds since the UNIX epoch to be used for the calculations.

  • config (Config) – The configuration object containing time anchors and other settings.

Returns:

This function prints out the results of various time calculations.

Return type:

None

Example

>>> timestamp = datetime(2023, 1, 1, tzinfo=timezone.utc)
>>> print_time_related_data(timestamp, config)
# OR
>>> total_seconds = Decimal("1672531200")
>>> print_time_related_data(total_seconds, config)
utms.utils.print_header(header)[source]

Prints the given header in cyan color with bright styling.

Parameters:

header (str) – The header text to be printed.

Returns:

This function only prints the header with styling and has no return value.

Return type:

None

Example

>>> print_header("Important Notice")
# This will print "Important Notice" in cyan with bright styling.
utms.utils.old_unit(unit)[source]

Applies magenta color styling to the given unit string.

Parameters:

unit (str) – The unit name to be styled.

Returns:

The unit name wrapped in magenta color styling.

Return type:

str

Example

>>> old_unit("Seconds")
# This will return the string "Seconds" in magenta color.
utms.utils.new_unit(unit)[source]

Applies green color styling to the given unit string.

Parameters:

unit (str) – The unit name to be styled.

Returns:

The unit name wrapped in green color styling.

Return type:

str

Example

>>> new_unit("Years")
# This will return the string "Years" in green color.
utms.utils.calculate_decimal_time(seconds)[source]

Calculate deciday, centiday, decimal seconds, and decidays as a float.

Return type:

tuple[int, int, int, float]

utms.utils.calculate_standard_time(seconds)[source]

Calculate standard time in HH:MM:SS format.

Return type:

str

utms.utils.format_with_color(value, condition, color_code='\\x1b[31m')[source]

Format a value with color if the condition is met.

Return type:

str

utms.utils.generate_time_table()[source]

Generate a time table mapping seconds to decidays, centidays, standard time, and kiloseconds.

Returns:

Formatted table as a string.

Return type:

str

utms.utils.convert_time(input_time)[source]

Converts time between 24-hour format (HH:MM:SS or HH:MM) and decimal format (DD.CD.SSS or DD.CD).

Parameters:

input_time (str) – The input time in either 24-hour format or decimal format.

Returns:

The converted time in the opposite format.

Return type:

str

utms.utils.convert_to_decimal(time_24hr)[source]

Converts 24-hour format (HH:MM:SS or HH:MM) to decimal format (DD.CD.SSS or DD.CD).

Parameters:

time_24hr (str) – The time in 24-hour format (HH:MM:SS or HH:MM).

Returns:

The time in decimal format (DD.CD.SSS or DD.CD).

Return type:

str

utms.utils.convert_to_24hr(decimal_time)[source]

Converts decimal format (DD.CD.SSS or DD.CD) to 24-hour format (HH:MM:SS or HH:MM).

Parameters:

decimal_time (str) – The time in decimal format (DD.CD.SSS or DD.CD).

Returns:

The time in 24-hour format (HH:MM:SS or HH:MM).

Return type:

str

utms.utils.get_seconds_since_midnight()[source]

Get the number of seconds that have passed since midnight today.

Return type:

int

utms.utils.value_to_decimal(value)[source]

Converts a value to a Decimal representation.

This function accepts either a Decimal value or a datetime object. If the input is a datetime, it converts it into a Decimal representation of its timestamp. For dates before January 2, year 1 (UTC), it adjusts the timestamp by subtracting the number of seconds in a year to handle historical date ranges.

Parameters:

value (Union[Decimal, datetime]) – The value to be converted. Can be either: - A Decimal value (returned as-is). - A datetime object (converted to Decimal timestamp).

Returns:

The Decimal representation of the input value.

Return type:

Decimal

Raises:

TypeError – If the input value is neither a Decimal nor a datetime.

Notes

  • For historical dates (datetime objects earlier than 0001-01-02T00:00:00 UTC), an adjustment is made to account for historical date handling.

utms.utils.seconds_to_pplt(seconds)[source]

Converts seconds to Planck-Centric Planck Log Time (pPLT).

Return type:

Decimal

utms.utils.seconds_to_hplt(seconds)[source]

Converts seconds to Human-Centric Planck Log Time (hPLT).

Return type:

Decimal

utms.constants

Time Unit Management and Physical Constants Module.

This module provides utilities for handling time units, converting between them, and managing high-precision physical constants related to time and the universe. It uses Decimal for high-precision arithmetic and allows the user to define, add, and convert between various time units ranging from Planck time to multi-million-year scales.

Modules:

math: For mathematical constants and functions. datetime: For date and time handling. decimal: For high-precision decimal arithmetic. importlib.metadata: For fetching package version information. utms.units: For managing time units through the UnitManager.

Constants:
  • HBAR: Reduced Planck constant in Joule-seconds (J⋅s).

  • G_CONST: Gravitational constant in m^3⋅kg^−1⋅s^−2.

  • C_CONST: Speed of light in meters per second (m/s).

  • PLANCK_TIME_SECONDS: Planck time in seconds, a fundamental time scale in physics.

  • SECONDS_IN_*: Constants representing the number of seconds in various time periods, such as minutes, hours, days, weeks, months, years, etc.

  • AGE_OF_UNIVERSE_YEARS: The age of the universe in years.

  • UNIVERSE_MAX_LIFESPAN_YEARS: Estimated lifespan of the universe in years.

  • GALAXIAL_ERA: The estimated maximum lifespan of the universe in seconds.

  • PLANCK_TIME_EPOCH: Epoch time of Planck time, derived from the maximum lifespan of the universe.

Time Units:
  • The module includes definitions for common human time units like second, minute, hour, day, etc., as well as exotic time units such as Planck time, and units spanning multiple scales, including megaannum and galactical eras.

  • A dictionary TIME_UNITS maps each time unit name to its corresponding time in seconds, and HUMAN_TIME_UNITS offers more familiar human units.

Functions:
  • UnitManager instance to manage and convert between these units.

  • The manager is used to add custom time units, such as “Lunar cycle”, “Hubble time”, and others, to provide a comprehensive set of time units for conversions and calculations.

Version:
  • The module version is determined from the installed utms package, or set to “0.0.0” if the package is not found.

Precision:
  • The Decimal module is used for all constants and calculations to ensure high precision (up to 200 decimal places), avoiding floating-point errors, especially in scientific computations.

CLI modules

utms.cli

CLI package for UTMS.

Contains modules for interactive shell, argument parsing, and command handling.

utms.cli.shell

This module implements a Command Line Interface (CLI) for the Universal Time Measurement System (UTMS). It allows users to interactively input commands for time and date-related conversions, resolving and displaying formatted timestamps based on their input.

Key Features: 1. Interactive Shell: Provides a command-line interface with input

handling, autocompletion, and a stylish prompt for user commands.

  1. Command Handling: The CLI supports specific commands like .conv for various conversion tables and dynamic date resolution.

  2. Date/Time Resolution: The input can be processed to resolve specific dates or timestamps, including handling special terms like “yesterday”, “tomorrow”, or “now”.

  3. Error Handling: Gracefully handles invalid inputs and interruptions, providing helpful error messages to the user.

Dependencies: - prompt_toolkit: A library for building interactive CLI

applications, enabling features like autocompletion and input history.

  • utms.constants: Includes version information and manager for conversion functionality.

  • utms.utils: Contains utility functions like

    print_time, and

    resolve_date.

Usage Example: ```python >>> main() Welcome to UTMS CLI (Version 1.0.0)! Current time: 2024-12-14T20:00:00+00:00 Prompt> .conv concise

utms.cli.shell.add_global_arguments(command_manager)[source]

Adds global arguments to the main parser managed by CommandManager.

Parameters:

manager – The CommandManager instance.

Return type:

None

utms.cli.shell.print_prompt_help(parser)[source]

Custom print_help to modify the ‘usage’ line for the prompt help.

Return type:

None

utms.cli.shell.handle_help(input_text, command_manager)[source]

Handles the help command in the interactive shell.

Parameters:
  • input_text (str) – The input help command (e.g., ‘.help unit table’).

  • parser (argparse.ArgumentParser) – The top-level parser.

  • subparser_map (Dict[str, argparse.ArgumentParser]) – A map of

  • parsers. (registered commands to their)

Return type:

None

utms.cli.shell.get_word_completer(command_manager)[source]

Create a WordCompleter object for both top-level arguments and subcommands.

This function uses the subparser_map from the CommandManager to gather the subcommands.

Return type:

WordCompleter

utms.cli.shell.interactive_shell(command_manager)[source]

Starts an interactive command-line shell for the UTMS CLI.

This function enters a loop where it prompts the user for input, processes the input to invoke the corresponding command, and displays the output. The user can exit the shell by typing exit.

Parameters:
  • command_manager (CommandManager) – The manager responsible for handling and executing

  • commands.

Returns:

This function runs in an infinite loop until the user exits the shell.

Return type:

None

utms.cli.shell.main()[source]

Main entry point of the UTMS CLI application.

This function parses command-line arguments and starts the interactive shell if no immediate action (like argument processing) is required.

Parameters:
  • None – This function retrieves and processes command-line arguments, then initializes the

  • CLI.

Returns:

The function either starts the interactive shell or terminates if arguments are processed.

Return type:

None

utms.cli.commands

Module for command-related classes and management.

This module provides the core classes for defining, managing, and organizing commands. It includes abstractions for individual commands, command managers, and command hierarchies. These classes are imported and exposed through the __all__ variable for external use.

Imports:
  • Command: Class representing an individual command.

  • CommandManager: Class for managing and orchestrating commands.

  • CommandHierarchy: Class for organizing commands into hierarchical structures.

Exports:
  • Command: See command.py for implementation details.

  • CommandManager: See command_manager.py for implementation details.

  • CommandHierarchy: See hierarchy.py for implementation details.

Usage:
Import this module to work with commands, their management, and hierarchies:

from module_name import Command, CommandManager, CommandHierarchy

utms.cli.commands.register

Module for automatically discovering and registering all commands from the utms.cli.commands package.

This module provides functionality to automatically discover command categories and the respective command registration functions within those categories. It registers all commands with the given CommandManager instance.

Functions:
register_all_commands(command_manager: CommandManager) -> None:

Discovers and registers all commands in the utms.cli.commands package, including its subdirectories.

utms.cli.commands.register.register_all_commands(command_manager)[source]

Automatically discovers and registers all commands from the available command categories in the utms.cli.commands package.

This function dynamically loads all command categories (subdirectories) in the utms.cli.commands package and then registers the commands found in each category by calling the corresponding register_ functions in each module.

Parameters:

command_manager (CommandManager) – The command manager used to register commands.

Return type:

None

Returns:

None

Raises:
  • ImportError – If there is an issue importing any command category or module.

  • AttributeError – If any module does not contain the expected register_ functions.

utms.cli.commands.core.command

Module for defining the Command class used for CLI command management.

This module contains the Command class, which is used to represent a command in the UTMS CLI system. The class encapsulates the command name, subcommand (if any), handler function, and associated arguments. It also provides methods to set help and description text, add arguments, and configure argument parsers for each command.

Imports:
  • argparse: Standard library for command-line argument parsing.

  • Any, Callable, Dict, List, Optional, Tuple: Typing annotations for type hints.

Exports:
  • Command: Class for defining and managing CLI commands.

Usage:

The Command class can be used to define a command, specify its handler, and register it with the CommandManager for processing user input in the CLI.

class utms.cli.commands.core.command.Command(command, subcommand, handler, is_default=False)[source]

Represents a command in the UTMS CLI system.

The Command class is used to define a command in the CLI, including its name, optional subcommand, handler function, arguments, and related metadata (help text, description). It also provides methods for configuring the argument parser.

command

The name of the command (e.g., ‘config’, ‘anchor’).

Type:

str

subcommand

The name of the subcommand (e.g., ‘get’, ‘set’) or None if there is no subcommand.

Type:

Optional[str]

handler

The function to handle the command.

Type:

Callable[[argparse.Namespace], None]

help

The help text for the command.

Type:

str

description

The description text for the command.

Type:

str

arguments

The list of arguments for the command.

Type:

List[Tuple[Tuple[str, …], Dict[str, Any]]]

is_default

Whether this command is the default action for its category.

Type:

bool

__init__(command

str, subcommand: Optional[str], handler:

Callable[[argparse.Namespace], None], is_default

bool =

False) -> None

Initializes a new command with the given properties.

set_help(help_text

str) -> None: Sets the help text for the command.

set_description(description

str) -> None: Sets the description text for the command.

add_argument(*args

str, **kwargs: Any) -> None: Adds an argument to the command.

configure_parser(parser

argparse.ArgumentParser) -> argparse.ArgumentParser: Configures the argument parser with the command’s arguments and metadata.

set_help(help_text)[source]

Sets the help text for the command.

This text is displayed when the user requests help for the command in the CLI.

Parameters:

help_text (str) – The help text to be displayed for the command.

Return type:

None

set_description(description)[source]

Sets the description text for the command.

This description provides further information about the command’s purpose and behavior, typically shown in the CLI help output.

Parameters:

description (str) – The description to be displayed for the command.

Return type:

None

add_argument(*args, **kwargs)[source]

Adds an argument to the command.

This method allows defining the command-line arguments for the command, such as required flags or values.

Parameters:
  • *args (str) – The argument(s) to be added to the command (e.g., ‘key’, ‘–verbose’).

  • **kwargs (Any) – Additional keyword arguments for the argument configuration (e.g., type, help).

Return type:

None

configure_parser(parser)[source]

Configures the argument parser with the command’s arguments and metadata.

This method iterates over the command’s arguments and adds them to the provided argument parser. It also sets the help and description text for the command.

Parameters:

parser (argparse.ArgumentParser) – The argument parser to configure.

Returns:

The updated argument parser with the command’s

arguments and metadata.

Return type:

argparse.ArgumentParser

utms.cli.commands.core.command_manager

Module for managing and processing commands in the UTMS CLI.

This module defines the CommandManager class, which is responsible for registering, configuring, and processing commands in the UTMS CLI. It allows the definition of commands and subcommands, with handlers for executing the desired functionality. It also handles argument parsing and interaction via the argparse module, enabling both interactive and non-interactive command executions.

Imports:
  • argparse: Standard library for argument parsing.

  • pdb: Python debugger, used for debugging execution.

  • shlex: Used to split input text into arguments.

  • Dict, Optional: Typing annotations for type hints.

  • Config: Configuration object used in the CLI.

  • Command: The Command class for defining CLI commands.

  • CommandHierarchy: A class to manage the hierarchy and subcommands.

Exports:
  • CommandManager: Class for managing and processing commands.

class utms.cli.commands.core.command_manager.CommandManager(config)[source]

A class responsible for managing and processing commands in the UTMS CLI.

The CommandManager class handles registering commands, configuring their parsers, and processing command-line arguments. It supports both root commands and subcommands, and can execute the associated handler based on parsed arguments.

config

The configuration object.

Type:

Config

parser

Argument parser instance for CLI commands.

Type:

argparse.ArgumentParser

commands

A dictionary of commands and their associated subcommands.

Type:

Dict[str, Dict[Optional[str], Command]]

hierarchy

Manages the hierarchy and structure of commands.

Type:

CommandHierarchy

register_command(cmd

Command) -> None: Registers a command and its associated handler.

add_subparser(command

str, subcommands: Optional[bool] = True) -> argparse.ArgumentParser: Adds a subparser for a command or subcommand.

configure_parsers() None[source]

Configures argument parsers for all registered commands.

process_args(input_text

Optional[list[str]] = None) -> bool: Processes command-line arguments and executes the associated handler.

handle(input_text

str) -> bool: Handles input, processes arguments, and returns the result.

register_command(cmd)[source]

Registers a command and its associated handler.

This method registers a command with the CommandManager instance, along with its associated handler, subcommand (if any), and adds it to the command hierarchy.

Parameters:

cmd (Command) – The command to register.

Return type:

None

add_subparser(command, subcommands=True)[source]

Adds a subparser for the command to the main parser or a parent command.

This method configures a subparser for the specified command. It also optionally supports subcommands, adding them to the command parser if specified.

Parameters:
  • command (str) – The command to add a subparser for.

  • subcommands (Optional[bool]) – Whether the command should

  • True. (support subcommands. Defaults to)

Returns:

The subparser instance for the command.

Return type:

argparse.ArgumentParser

configure_parsers()[source]

Configures the parsers for each command and adds their arguments.

This method is called after all commands are registered to set up argument parsing for each command and subcommand. It ensures that each command has a parser with the appropriate arguments.

This is essential to ensure that arguments are correctly parsed and mapped to their respective handlers.

Return type:

None

process_args(input_text=None)[source]

Processes non-interactive execution based on command-line arguments.

This method parses the provided input text (if any) and resolves the correct command and subcommand. It then invokes the handler associated with the resolved command.

Parameters:

input_text (Optional[list[str]]) – The command-line arguments to process. If None, defaults to using sys.argv.

Returns:

True if an argument was processed successfully, False otherwise.

Return type:

bool

handle(input_text)[source]

Handles the input and processes the associated command.

This method processes a command string by splitting it into arguments and then handling the execution based on parsed arguments.

Parameters:

input_text (str) – The raw input text (command string) to handle.

Returns:

True if the command was processed successfully, False otherwise.

Return type:

bool

utms.cli.commands.core.hierarchy

Module for managing command hierarchy and handling in the UTMS CLI system.

This module defines the CommandHierarchy class, which is responsible for organizing commands and subcommands, managing their argument parsers, handling associated functions, and establishing default behaviors for commands. It allows the UTMS CLI system to parse and execute commands and subcommands effectively.

Imports:
  • argparse: Standard library for command-line argument parsing.

  • Any, Callable, Dict, Optional: Typing annotations for type hints.

Exports:
  • CommandHierarchy: Class that handles the management of commands, subcommands, parsers, and handlers in the CLI system.

Usage:

The CommandHierarchy class is used to define the structure and behavior of commands and subcommands in the UTMS CLI, including associating them with specific parsers and handlers.

class utms.cli.commands.core.hierarchy.CommandHierarchy[source]

Manages the hierarchy of commands and subcommands for the UTMS CLI system.

The CommandHierarchy class is responsible for organizing commands and their subcommands, associating them with argument parsers, and mapping them to their respective handler functions. It also allows for the definition of default subcommands for specific commands.

parent_parsers

A

Type:

Dict[str, argparse.ArgumentParser]

dictionary mapping top-level commands to their parsers.
child_parsers
Type:

Dict[str, Dict[str, argparse.ArgumentParser]]

A dictionary mapping commands to their subcommand parsers.
subparsers_actions (Dict[str,
argparse._SubParsersAction[Any]])

A dictionary storing

subparsers actions for commands.
default_subcommands

A dictionary mapping

Type:

Dict[str, str]

commands to their default subcommands.
handlers (Dict[str, Dict[Optional[str],
Callable[[argparse.Namespace], None]]])

A dictionary mapping

commands and subcommands to their handler functions.
__init__() None[source]

Initializes the command hierarchy.

add_parent_parser(command

str, parser: argparse.ArgumentParser) -> None: Adds a top-level command and its corresponding parser.

add_subcommand(command

str, subcommand: str, parser: argparse.ArgumentParser) -> None: Adds a subcommand and its associated parser.

add_handler(handler

Callable[[argparse.Namespace], None],

command()

str, subcommand: Optional[str] = None) -> None: Adds a handler function for a command or subcommand.

add_subparsers_actions(command

str, actions: argparse._SubParsersAction[Any]) -> None: Adds subparser actions for a command.

set_default_subcommand(command

str, subcommand: str) -> None: Sets the default subcommand for a given command.

get_handler(command

Optional[str], subcommand: Optional[str]

= None) -> Optional[Callable[[argparse.Namespace], None]]

Retrieves the handler function for a command or subcommand.

get_parser(command

str, subcommand: Optional[str] = None) ->

Optional[argparse, ArgumentParser]()

Retrieves the parser for a given command and subcommand.

get_action(command

str) -> argparse._SubParsersAction[Any]: Retrieves the subparser action for a command.

root_actions() argparse._SubParsersAction[Any]

Property that retrieves the root subparser actions for the CLI.

add_parent_parser(command, parser)[source]

Adds a top-level command and its corresponding parser to the hierarchy.

This method stores the parser for a top-level command (parent command) in the parent_parsers dictionary for later use.

Parameters:
  • command (str) – The name of the command (e.g., ‘config’, ‘anchor’).

  • parser (argparse.ArgumentParser) – The parser for the command.

Return type:

None

add_subcommand(command, subcommand, parser)[source]

Adds a subcommand and its associated parser to the hierarchy.

This method stores the parser for a subcommand under the relevant command in the child_parsers dictionary for later use.

Parameters:
  • command (str) – The name of the parent command (e.g., ‘config’).

  • subcommand (str) – The name of the subcommand (e.g., ‘get’).

  • parser (argparse.ArgumentParser) – The parser for the subcommand.

Return type:

None

add_handler(handler, command, subcommand=None)[source]

Adds a handler function for a command or subcommand.

This method stores the handler function for a given command and, if applicable, its subcommand, in the handlers dictionary.

Parameters:
  • handler (Callable[[argparse.Namespace], None]) – The

  • subcommand. (function that handles the command or)

  • command (str) – The name of the command (e.g., ‘config’).

  • subcommand (Optional[str]) – The name of the subcommand

  • (e.g.

  • None ('get'). If)

  • command. (it is for the parent)

Return type:

None

add_subparsers_actions(command, actions)[source]

Adds subparser actions for a command.

This method associates a command with its subparser actions, enabling the command to have subcommands that can be handled properly.

Parameters:
  • command (str) – The name of the command.

  • actions (argparse._SubParsersAction[Any]) – The subparser

  • command. (actions to add for the)

set_default_subcommand(command, subcommand)[source]

Sets the default subcommand for a given command.

This method allows for specifying a default subcommand that should be invoked if no subcommand is provided when invoking a command.

Parameters:
  • command (str) – The name of the command (e.g., ‘config’).

  • subcommand (str) – The name of the default subcommand (e.g., ‘list’).

Return type:

None

get_handler(command, subcommand=None)[source]

Retrieves the handler function for a command or subcommand.

This method looks up the appropriate handler function based on the provided command and, if applicable, subcommand.

Parameters:
  • command (Optional[str]) – The name of the command (e.g., ‘config’).

  • subcommand (Optional[str]) – The name of the subcommand

  • (e.g.

  • None ('get'). If)

  • the (it will fetch the handler for)

  • itself. (command)

Returns:

The handler function, or None if not found.

Return type:

Optional[Callable[[argparse.Namespace], None]]

get_parser(command, subcommand=None)[source]

Retrieves the parser for a given command and subcommand.

This method looks up the parser for the specified command and subcommand. If no subcommand is given, the method returns the parser for the command itself.

Parameters:
  • command (str) – The name of the command (e.g., ‘config’).

  • subcommand (Optional[str]) – The name of the subcommand

  • (e.g.

  • None ('get'). If)

  • returned. (the command's parser is)

Returns:

The associated argument parser, or None if not found.

Return type:

Optional[argparse.ArgumentParser]

get_action(command)[source]

Retrieves the subparser action for a command.

This method returns the subparser action object that manages the subcommands for the specified command.

Parameters:

command (str) – The name of the command.

Returns:

The subparser action associated with the command.

Return type:

argparse._SubParsersAction[Any]

property root_actions: argparse._SubParsersAction[Any]

Retrieves the root subparser actions for the CLI.

This property returns the subparser action for the root command, which is used to manage top-level commands and subcommands.

Returns:

The root subparser action for the CLI.

Return type:

argparse._SubParsersAction[Any]

Commands

utms.cli.commands.anchor

Module for registering anchor-related commands.

This module provides functions for registering anchor-related commands, such as fetching anchor data and listing anchors. The commands are organized into separate modules and exposed through the __all__ variable for easy access.

Imports:
  • register_anchor_get_command: Function to register the “get” command for anchors.

  • register_anchor_set_command: Function to register the “set” command for anchors.

  • register_anchor_list_command: Function to register the “list” command for anchors.

Exports:
  • register_anchor_get_command: See get.py for implementation details.

  • register_anchor_set_command: See set.py for implementation details.

  • register_anchor_list_command: See list.py for implementation details.

Usage:
Import this module to gain access to the registered commands:

from module_name import register_anchor_get_command, register_anchor_get_command, register_anchor_list_command

utms.cli.commands.anchor.create

Module for handling anchor creation commands within the utms command-line interface.

This module provides the functionality to create new anchors, including parsing input, resolving values, and saving anchor configurations.

Functions:
set_anchor(args: argparse.Namespace, config: Config) -> None:

Creates a new anchor based on the given command-line arguments and saves it.

register_anchor_create_command(command_manager: CommandManager) -> None:

Registers the “anchor create” command and its associated arguments with the command manager.

utms.cli.commands.anchor.create.set_anchor(args, config)[source]

Creates a new anchor based on the provided command-line arguments and saves it in the configuration.

This function checks if an anchor with the given label already exists. If it does, it notifies the user. If the label is new, it parses and resolves the anchor’s value, groups, precision, and breakdowns. If the value cannot be directly converted to a Decimal, it attempts to resolve it using AI or a date parser.

Parameters:
  • args (argparse.Namespace) – The parsed command-line arguments

  • details. (containing anchor)

  • config (Config) – The configuration object where the anchor will be saved.

Raises:
  • ValueError – If the value provided for the anchor cannot be

  • resolved into a valid timestamp or decimal.

Return type:

None

utms.cli.commands.anchor.create.register_anchor_create_command(command_manager)[source]

Registers the “anchor create” command with the provided command manager.

This function defines the arguments for the “anchor create” command, including the anchor’s label, name, value, groups, precision, and breakdowns. It associates the command with the set_anchor function that processes the input and creates a new anchor.

Parameters:
  • command_manager (CommandManager) – The command manager used to

  • command. (register the new)

Return type:

None

Returns:

None

utms.cli.commands.anchor.delete

Module for handling anchor deletion commands within the utms command-line interface.

This module provides the functionality to delete anchors by label, ensuring that dynamic anchors (which change on each run) cannot be deleted.

Functions:
delete_anchor(args: argparse.Namespace, config: Config) -> None:

Deletes an anchor based on the provided command-line arguments and saves the updated configuration.

register_anchor_delete_command(command_manager: CommandManager) -> None:

Registers the “anchor delete” command and its associated arguments with the command manager.

utms.cli.commands.anchor.delete.delete_anchor(args, config)[source]

Deletes an anchor based on the provided label and saves the updated configuration.

This function removes an anchor from the configuration by its label. Dynamic anchors, which change on each run, cannot be deleted.

Parameters:
  • args (argparse.Namespace) – The parsed command-line arguments

  • delete. (containing the label of the anchor to)

  • config (Config) – The configuration object from which the anchor will be deleted.

Return type:

None

Returns:

None

utms.cli.commands.anchor.delete.register_anchor_delete_command(command_manager)[source]

Registers the “anchor delete” command with the provided command manager.

This function defines the arguments for the “anchor delete” command, which allows the user to delete an anchor by its label. It associates the command with the delete_anchor function that handles the anchor deletion process.

Parameters:

command_manager (CommandManager) – The command manager used to register the new command.

Return type:

None

Returns:

None

utms.cli.commands.anchor.get

Module for registering the “anchor get” command.

This module provides functionality to register the “anchor get” command, which allows users to retrieve and print the properties of a specific anchor identified by its label. The command is registered using the CommandManager class from the core commands module.

Imports:
  • Command: Class used to define a command.

  • CommandManager: Class responsible for managing commands in the CLI.

Exports:
  • register_anchor_get_command: Function to register the “anchor get” command.

Usage:

Import this module and use the register_anchor_get_command function to add the “anchor get” command to your CommandManager instance:

from module_name import register_anchor_get_command

register_anchor_get_command(command_manager)

utms.cli.commands.anchor.get.get_anchors(args, config)[source]

Parses a comma-separated string and returns a sorted list of Anchor objects.

This method splits the input string by commas, retrieves Anchor objects associated with each item, and adds them to a list. It also includes additional anchors based on groups associated with each item. The resulting list is sorted by the value attribute of the Anchor objects.

Parameters:

input_text (str) – A comma-separated string of items, each representing an anchor or group identifier.

Returns:

A sorted list of Anchor objects.

Return type:

List[Anchor]

Raises:

ValueError – If any of the items in the input string cannot be resolved to an Anchor object.

Notes

  • The method first retrieves anchors using the get() method, and then appends anchors retrieved by group using get_anchors_by_group().

  • The sorting is done based on the value attribute of the Anchor objects.

utms.cli.commands.anchor.get.register_anchor_get_command(command_manager)[source]

Registers the “anchor get” command.

This function sets up and registers the “anchor get” command with the provided command manager. The command allows users to retrieve and print the properties of a specific anchor by its label.

Parameters:

command_manager (CommandManager) – The command manager responsible for registering and managing commands.

Return type:

None

Command Details:
  • Name: “anchor get”

  • Description: Prints the properties of a specific anchor identified by its label.

  • Help: “Get an anchor by label”

Command Arguments:
  • label (str): The label of the anchor to retrieve and print. This argument is required.

Example Usage:
Assuming command_manager is an instance of CommandManager:

register_anchor_get_command(command_manager)

In CLI:

anchor get <label>

utms.cli.commands.anchor.list

Module for registering the “anchor list” command.

This module provides functionality to register the “anchor list” command, which allows users to list and print all configured anchors. The command is registered through the CommandManager class from the core commands module.

Imports:
  • Command: Class used to define a command.

  • CommandManager: Class responsible for managing commands in the CLI.

Exports:
  • register_anchor_list_command: Function to register the “anchor list” command.

Usage:

Import this module and use the register_anchor_list_command function to add the “anchor list” command to your CommandManager instance:

from module_name import register_anchor_list_command

register_anchor_list_command(command_manager)

utms.cli.commands.anchor.list.register_anchor_list_command(command_manager)[source]

Registers the “anchor list” command.

This function sets up and registers the “anchor list” command with the provided command manager. The command allows users to list all configured anchors and print their details to the console.

Parameters:

command_manager (CommandManager) – The command manager responsible for registering and managing commands.

Return type:

None

Command Details:
  • Name: “anchor list”

  • Description: Lists all configured anchors.

  • Help: “Print anchors”

  • Default Command: This command is set as the default for the “anchor” group.

Example Usage:
Assuming command_manager is an instance of CommandManager:

register_anchor_list_command(command_manager)

In CLI:

anchor list

utms.cli.commands.anchor.set

Module for handling anchor setting commands within the utms command-line interface.

This module provides the functionality to modify an existing anchor’s parameters based on the given label. The parameters that can be updated include the anchor’s name, value, groups, precision, and breakdowns.

Functions:
set_anchor(args: argparse.Namespace, config: Config) -> None:

Updates the parameters of an existing anchor based on the provided command-line arguments.

register_anchor_set_command(command_manager: CommandManager) -> None:

Registers the “anchor set” command and its associated arguments with the command manager.

utms.cli.commands.anchor.set.set_anchor(args, config)[source]

Updates the parameters of an existing anchor based on the provided arguments.

This function allows the user to modify various properties of an anchor identified by its label. It supports updating the anchor’s name, value (resolved via dateparser/AI if necessary), groups, precision, and breakdowns. After updating the parameters, the changes are saved in the configuration.

Parameters:
  • args (argparse.Namespace) – The parsed command-line arguments, including the anchor label and updated values for its parameters.

  • config (Config) – The configuration object where anchors are stored.

Return type:

None

Returns:

None

Raises:

ValueError – If the anchor value cannot be resolved or cast to a valid type.

utms.cli.commands.anchor.set.register_anchor_set_command(command_manager)[source]

Registers the “anchor set” command with the provided command manager.

This function defines the arguments for the “anchor set” command, which allows the user to modify the parameters of an existing anchor by its label. It associates the command with the set_anchor function that handles the anchor modification process.

Parameters:
  • command_manager (CommandManager) – The command manager used to

  • command. (register the new)

Return type:

None

Returns:

None

utms.cli.commands.anchor.helper

Argument utilities for anchor-related CLI subcommands.

This module provides helper functions to add commonly used arguments to anchor-related subcommands in the UTMS CLI. These functions streamline the process of configuring command-line argument parsers by encapsulating reusable argument definitions.

utms.cli.commands.anchor.helper.add_anchor_list_argument(command)[source]

Add anchor_list argument to a anchor subcommand.

Return type:

None

utms.cli.commands.anchor.helper.add_label_argument(command)[source]

Add label argument to a anchor subcommand.

Return type:

None

utms.cli.commands.anchor.helper.add_name_argument(command, required=True)[source]

Add name argument to a anchor subcommand.

Return type:

None

utms.cli.commands.anchor.helper.add_value_argument(command, required=True)[source]

Add value argument to a anchor subcommand.

Return type:

None

utms.cli.commands.anchor.helper.add_groups_argument(command)[source]

Add groups argument to a anchor subcommand.

Return type:

None

utms.cli.commands.anchor.helper.add_precision_argument(command)[source]

Add precision argument to a anchor subcommand.

Return type:

None

utms.cli.commands.anchor.helper.add_breakdowns_argument(command)[source]

Add breakdowns argument to a anchor subcommand.

Return type:

None

utms.cli.commands.clock

Module for registering clock-related commands.

This module provides functionality to register commands related to clock operations. The primary function, register_clock_command, is imported and exposed through the __all__ variable for external use.

Imports:
  • register_clock_command: Function to register clock commands.

Exports:
  • register_clock_command: See clock.py for implementation details.

Usage:
Import this module to utilize the clock command registration:

from module_name import register_clock_command

utms.cli.commands.clock.clock

Module for registering the “clock” command.

This module provides functionality to register the “clock” command, which runs a clock displaying time both in decimal and duodecimal units. The command is registered using the CommandManager class from the core commands module.

Imports:
  • Command: Class used to define a command.

  • CommandManager: Class responsible for managing commands in the CLI.

  • run_clock: Function from the clock module that runs the clock.

Exports:
  • register_clock_command: Function to register the “clock” command.

Usage:

Import this module and use the register_clock_command function to add the “clock” command to your CommandManager instance:

from module_name import register_clock_command

register_clock_command(command_manager)

utms.cli.commands.clock.clock.register_clock_command(command_manager)[source]

Registers the “clock” command.

This function sets up and registers the “clock” command with the provided command manager. The command runs a clock that displays time in both decimal and duodecimal units.

Parameters:

command_manager (CommandManager) – The command manager responsible for registering and managing commands.

Return type:

None

Command Details:
  • Name: “clock”

  • Description: Runs a clock showing time in decimal and duodecimal formats.

  • Help: “Run clock”

  • Default Command: This command is set as the default for the “clock” group.

Example Usage:
Assuming command_manager is an instance of CommandManager:

register_clock_command(command_manager)

In CLI:

clock

utms.cli.commands.config

Module for registering configuration-related commands.

This module provides functions to register commands for handling configurations, including fetching, listing, and setting configuration options. These commands are imported from their respective modules and exposed through the __all__ variable for streamlined access.

Imports:
  • register_config_get_command: Function to register the “get” command for configurations.

  • register_config_list_command: Function to register the “list” command for configurations.

  • register_config_set_command: Function to register the “set” command for configurations.

Exports:
  • register_config_get_command: See get.py for implementation details.

  • register_config_list_command: See list.py for implementation details.

  • register_config_set_command: See set.py for implementation details.

Usage:
Import this module to access the configuration-related commands:
from module_name import (

register_config_get_command, register_config_list_command, register_config_set_command,

)

utms.cli.commands.config.get

Module for registering the “config get” command.

This module provides functionality to register the “config get” command, which allows users to retrieve a configuration value by its key. The command is registered using the CommandManager class from the core commands module.

Imports:
  • Command: Class used to define a command.

  • CommandManager: Class responsible for managing commands in the CLI.

Exports:
  • register_config_get_command: Function to register the “config get” command.

Usage:

Import this module and use the register_config_get_command function to add the “config get” command to your CommandManager instance:

from module_name import register_config_get_command

register_config_get_command(command_manager)

utms.cli.commands.config.get.register_config_get_command(command_manager)[source]

Registers the “config get” command.

This function sets up and registers the “config get” command with the provided command manager. The command allows users to retrieve and print the value of a specific configuration option based on its key.

Parameters:

command_manager (CommandManager) – The command manager responsible for registering and managing commands.

Return type:

None

Command Details:
  • Name: “config get”

  • Description: Retrieves a configuration value based on the provided key.

  • Help: “Get a configuration value”

Command Arguments:
  • key (str): The key of the configuration option to retrieve. This argument is required.

Example Usage:
Assuming command_manager is an instance of CommandManager:

register_config_get_command(command_manager)

In CLI:

config get <key>

utms.cli.commands.config.list

Module for registering the “config list” command.

This module provides functionality to register the “config list” command, which allows users to list all available configuration options. The command is registered using the CommandManager class from the core commands module.

Imports:
  • Command: Class used to define a command.

  • CommandManager: Class responsible for managing commands in the CLI.

Exports:
  • register_config_list_command: Function to register the “config list” command.

Usage:

Import this module and use the register_config_list_command function to add the “config list” command to your CommandManager instance:

from module_name import register_config_list_command

register_config_list_command(command_manager)

utms.cli.commands.config.list.register_config_list_command(command_manager)[source]

Registers the “config list” command.

This function sets up and registers the “config list” command with the provided command manager. The command allows users to print and list all available configuration options.

Parameters:

command_manager (CommandManager) – The command manager responsible for registering and managing commands.

Return type:

None

Command Details:
  • Name: “config list”

  • Description: Lists all available configuration options.

  • Help: “Print config”

  • Default Command: This command is set as the default for the “config” group.

Example Usage:
Assuming command_manager is an instance of CommandManager:

register_config_list_command(command_manager)

In CLI:

config list

utms.cli.commands.config.set

Module for registering the “config set” command.

This module provides functionality to register the “config set” command, which allows users to set a configuration value for a specific key. The command is registered using the CommandManager class from the core commands module.

Imports:
  • Command: Class used to define a command.

  • CommandManager: Class responsible for managing commands in the CLI.

Exports:
  • register_config_set_command: Function to register the “config set” command.

Usage:

Import this module and use the register_config_set_command function to add the “config set” command to your CommandManager instance:

from module_name import register_config_set_command

register_config_set_command(command_manager)

utms.cli.commands.config.set.register_config_set_command(command_manager)[source]

Registers the “config set” command.

This function sets up and registers the “config set” command with the provided command manager. The command allows users to set the value of a specific configuration option based on its key.

Parameters:

command_manager (CommandManager) – The command manager responsible for registering and managing commands.

Return type:

None

Command Details:
  • Name: “config set”

  • Description: Sets a configuration value based on the provided key and value.

  • Help: “Set a configuration value”

Command Arguments:
  • key (str): The key of the configuration option to set. This argument is required.

  • value (str): The value to assign to the specified configuration key. This argument is required.

Example Usage:
Assuming command_manager is an instance of CommandManager:

register_config_set_command(command_manager)

In CLI:

config set <key> <value>

utms.cli.commands.config.helper

Argument utilities for config-related CLI subcommands.

This module provides helper functions to add commonly used arguments to config-related subcommands in the UTMS CLI. These functions streamline the process of configuring command-line argument parsers by encapsulating reusable argument definitions.

utms.cli.commands.config.helper.add_key_argument(command)[source]

Add key argument to config subcommand.

Return type:

None

utms.cli.commands.config.helper.add_value_argument(command)[source]

Add value argument to config subcommand.

Return type:

None

utms.cli.commands.daytime

Module for registering daytime-related commands.

This module provides functions to register commands for handling daytime operations, such as timetable management and conversions. These commands are imported from their respective modules and exposed through the __all__ variable for streamlined access.

Imports:
  • register_daytime_convert_command: Function to register the “convert” command for daytime operations.

  • register_daytime_timetable_command: Function to register the “timetable” command for daytime scheduling.

Exports:
  • register_daytime_convert_command: See convert.py for implementation details.

  • register_daytime_timetable_command: See timetable.py for implementation details.

Usage:
Import this module to use the daytime-related commands:
from module_name import (

register_daytime_convert_command, register_daytime_timetable_command,

)

utms.cli.commands.daytime.timetable

Module for registering the daytime timetable command in the UTMS CLI system.

This module defines the function register_daytime_timetable_command, which registers the daytime timetable command to the UTMS CLI. The command outputs a formatted table that maps decimal time units to duodecimal time units.

Imports:
  • Command, CommandManager: Command-related classes used to register and manage commands.

  • generate_time_table: Utility function to generate the time table.

Exports:
  • register_daytime_timetable_command: Function to register the daytime timetable command.

utms.cli.commands.daytime.timetable.register_daytime_timetable_command(command_manager)[source]

Registers the ‘daytime timetable’ command with the given command manager.

This function creates a new Command for generating and printing a formatted table that maps decimal time units to duodecimal time units. The command is registered as the default action for the daytime command.

Parameters:
  • command_manager (CommandManager) – The manager responsible for

  • system. (registering commands in the UTMS CLI)

Return type:

None

Returns:

None

utms.cli.commands.daytime.convert

Module for registering the daytime conversion command in the UTMS CLI system.

This module defines the function register_daytime_convert_command, which registers the daytime convert command to the UTMS CLI. The command allows users to convert between decimal and duodecimal daytime units.

Imports:
  • Command, CommandManager: Command-related classes used to register and manage commands.

  • convert_time: Utility function for converting time units.

Exports:
  • register_daytime_convert_command: Function to register the daytime conversion command.

utms.cli.commands.daytime.convert.register_daytime_convert_command(command_manager)[source]

Registers the ‘daytime convert’ command with the given command manager.

This function creates a new Command for converting between decimal and duodecimal daytime units. It configures the command’s arguments, help text, and description before registering it with the provided CommandManager.

Parameters:
  • command_manager (CommandManager) – The manager responsible for

  • system. (registering commands in the UTMS CLI)

Return type:

None

Returns:

None

utms.cli.commands.daytime.helper

Argument utilities for daytime-related CLI subcommands.

This module provides helper functions to add commonly used arguments to daytime-related subcommands in the UTMS CLI. These functions streamline the process of configuring command-line argument parsers by encapsulating reusable argument definitions.

utms.cli.commands.daytime.helper.add_value_argument(command)[source]

Add value argument to daytime subcommand.

Return type:

None

utms.cli.commands.resolve

Module for registering resolve-related commands.

This module provides functionality to register commands for resolving various entities or conflicts. The register_resolve_command function is the main feature of this module and is exposed through the __all__ variable for external use.

Imports:
  • register_resolve_command: Function to register the resolve command.

Exports:
  • register_resolve_command: See resolve.py for implementation details.

Usage:
Import this module to utilize the resolve command registration:

from module_name import register_resolve_command

utms.cli.commands.resolve.resolve

Module for registering and handling the ‘resolve’ command in the UTMS CLI system.

This module defines the function register_resolve_command to register the ‘resolve’ command, and handle_resolve_command to process the command by resolving arbitrary strings into dates using either the dateparser library or an AI model. The result is then printed in a readable time format.

Imports:
  • argparse: For handling argument parsing.

  • datetime, Decimal: For managing date and time-related data types.

  • AI, Config: For utilizing AI and configuration-related functionality.

  • Command, CommandManager: For managing the commands in the CLI system.

  • print_time: Utility function for printing a formatted time.

Exports:
  • handle_resolve_command: Function to handle resolving the input string to a date.

  • register_resolve_command: Function to register the resolve command in the CLI.

utms.cli.commands.resolve.resolve.handle_resolve_command(args, config)[source]

Handles the ‘resolve’ command by resolving an input string into a datetime or decimal value.

This function uses the AI object to resolve a string input into a datetime or decimal object. If the resolution is successful, the timestamp is printed using the print_time utility function.

Parameters:
  • args (argparse.Namespace) – The parsed arguments containing the

  • resolve. (input string to)

  • config (Config) – The configuration object containing necessary

  • settings

  • formats. (such as time)

Return type:

None

Returns:

None

utms.cli.commands.resolve.resolve.register_resolve_command(command_manager)[source]

Registers the ‘resolve’ command with the given command manager.

This function creates and registers a command for resolving arbitrary strings into datetime values using either the dateparser library or the AI model. The command is set as the default action for the resolve command.

Parameters:
  • command_manager (CommandManager) – The manager responsible for

  • system. (registering commands in the UTMS CLI)

Return type:

None

Returns:

None

utms.cli.commands.resolve.helper

Argument utilities for resolve-related CLI subcommands.

This module provides helper functions to add commonly used arguments to resolve-related subcommands in the UTMS CLI. These functions streamline the process of configuring command-line argument parsers by encapsulating reusable argument definitions.

utms.cli.commands.resolve.helper.add_anchor_list_argument(command)[source]

Add anchor_list argument to resolve subcommand.

Return type:

None

utms.cli.commands.resolve.helper.add_units_argument(command)[source]

Add units argument to resolve subcommand.

Return type:

None

utms.cli.commands.resolve.helper.add_plt_argument(command)[source]

Add plt argument to resolve subcommand.

Return type:

None

utms.cli.commands.resolve.helper.add_input_argument(command)[source]

Add input argument to resolve subcommand.

Return type:

None

utms.cli.commands.unit

Module for registering unit-related commands in the UTMS CLI system.

This module imports and aggregates the functions for the following unit-related commands: - register_unit_convert_command: Registers the command to convert between units. - register_unit_list_command: Registers the command to list all available units. - register_unit_table_command: Registers the command to display a

conversion table for a specific unit.

By importing this module, the unit commands are made available for registration within the UTMS CLI system.

Exports:
  • register_unit_convert_command: Command for converting between units.

  • register_unit_list_command: Command for listing available units.

  • register_unit_table_command: Command for displaying a unit conversion table.

utms.cli.commands.unit.convert

Module for registering and handling the ‘unit convert’ command in the UTMS CLI system.

This module defines the function register_unit_convert_command to register the ‘unit convert’ command. It allows converting a numerical value from one unit to another. The target unit is optional and, if omitted, the conversion will display all possible unit conversions.

Imports:
  • Decimal: For handling precise numerical values during unit conversion.

  • Command, CommandManager: For managing commands in the CLI system.

Exports:
  • register_unit_convert_command: Function to register the unit conversion command.

utms.cli.commands.unit.convert.register_unit_convert_command(command_manager)[source]

Registers the ‘unit convert’ command with the given command manager.

This function creates and registers a command to convert a given value between units. The target unit is optional: if omitted, the system will perform conversions to all available units.

Parameters:
  • command_manager (CommandManager) – The manager responsible for

  • system. (registering commands in the UTMS CLI)

Return type:

None

Returns:

None

utms.cli.commands.unit.create

Unit creation commands for the UTMS CLI.

This module defines functionality for adding a new unit to the UTMS configuration. It includes the core logic for creating units and registering the associated CLI command to the command manager.

Functions:
create_unit(args: argparse.Namespace, config: Config) -> None

Creates a new unit and updates the configuration if the unit does not already exist.

register_unit_create_command(command_manager: CommandManager) -> None

Registers the ‘unit create’ command with the CommandManager, enabling users to add new units.

utms.cli.commands.unit.create.create_unit(args, config)[source]

Create a new unit and add it to the UTMS configuration.

This function checks if a unit with the given abbreviation already exists. If not, it adds the unit with the provided name, abbreviation, and value (in seconds) to the configuration and saves the changes.

Parameters:
  • args (argparse.Namespace) – Parsed command-line arguments containing the unit name, abbreviation, and value in seconds.

  • config (Config) – The UTMS configuration instance for managing units.

Return type:

None

utms.cli.commands.unit.create.register_unit_create_command(command_manager)[source]

Register the ‘unit create’ command with the CommandManager.

This function defines a new CLI command for creating units and associates it with the CommandManager. It configures the command’s arguments and their help text before registering the command.

Parameters:

command_manager (CommandManager) – The command manager instance to register the ‘unit create’ command with.

Return type:

None

utms.cli.commands.unit.get

Unit retrieval command for the UTMS CLI.

This module provides functionality to retrieve and display information about a specific unit in the UTMS configuration. It defines the CLI command and its associated arguments for fetching unit details.

Functions:
register_unit_get_command(command_manager: CommandManager) -> None

Registers the ‘unit get’ command with the CommandManager, enabling retrieval of unit details by abbreviation.

utms.cli.commands.unit.get.register_unit_get_command(command_manager)[source]

Register the ‘unit get’ command with the CommandManager.

This function defines a CLI command for retrieving details about a specific unit by its abbreviation. The command is registered with the provided CommandManager and includes argument configuration.

Parameters:

command_manager (CommandManager) – The command manager instance to register the ‘unit get’ command with.

Return type:

None

utms.cli.commands.unit.list

Module for registering and handling the ‘unit list’ command in the UTMS CLI system.

This module defines the function register_unit_list_command to register the ‘unit list’ command. It lists all available time units configured in the system.

Imports:
  • Command, CommandManager: For managing commands in the CLI system.

Exports:
  • register_unit_list_command: Function to register the unit list command.

utms.cli.commands.unit.list.register_unit_list_command(command_manager)[source]

Registers the ‘unit list’ command with the given command manager.

This function creates and registers a command to list all available time units in the system. The command is marked as the default action.

Parameters:
  • command_manager (CommandManager) – The manager responsible for

  • system. (registering commands in the UTMS CLI)

Return type:

None

Returns:

None

utms.cli.commands.unit.table

Module for registering and handling the ‘unit table’ command in the UTMS CLI system.

This module defines the function register_unit_table_command to register the ‘unit table’ command. It displays a conversion table for a specific unit, with optional parameters to customize the number of rows and columns.

Imports:
  • Command, CommandManager: For managing commands in the CLI system.

Exports:
  • register_unit_table_command: Function to register the unit table command.

utms.cli.commands.unit.table.register_unit_table_command(command_manager)[source]

Registers the ‘unit table’ command with the given command manager.

This function creates and registers a command to display a unit conversion table for a specific unit. It allows the user to specify the number of rows and columns for the table. The command is marked as the default action.

Parameters:
  • command_manager (CommandManager) – The manager responsible for

  • system. (registering commands in the UTMS CLI)

Return type:

None

Returns:

None

utms.cli.commands.unit.helper

Argument utilities for unit-related CLI subcommands.

This module provides helper functions to add commonly used arguments to unit-related subcommands in the UTMS CLI. These functions streamline the process of configuring command-line argument parsers by encapsulating reusable argument definitions.

utms.cli.commands.unit.helper.add_value_argument(command)[source]

Add value argument to unit subcommand.

Return type:

None

utms.cli.commands.unit.helper.add_value_seconds_argument(command)[source]

Add value in seconds argument to unit subcommand.

Return type:

None

utms.cli.commands.unit.helper.add_source_unit_argument(command)[source]

Add source_unit argument to unit subcommand.

Return type:

None

utms.cli.commands.unit.helper.add_target_unit_argument(command)[source]

Add target_unit argument to unit subcommand.

Return type:

None

utms.cli.commands.unit.helper.add_full_argument(command)[source]

Add full argument to unit subcommand.

Return type:

None

utms.cli.commands.unit.helper.add_precision_argument(command)[source]

Add precision argument to unit subcommand.

Return type:

None

utms.cli.commands.unit.helper.add_raw_argument(command)[source]

Add raw argument to unit subcommand.

Return type:

None

utms.cli.commands.unit.helper.add_plt_argument(command)[source]

Add plt argument to unit subcommand.

Return type:

None

utms.cli.commands.unit.helper.add_name_argument(command)[source]

Add name argument to unit subcommand.

Return type:

None

utms.cli.commands.unit.helper.add_abbreviation_argument(command)[source]

Add abbreviation argument to unit subcommand.

Return type:

None

utms.cli.commands.unit.helper.add_unit_argument(command)[source]

Add unit argument to unit subcommand.

Return type:

None

utms.cli.commands.unit.helper.add_rows_argument(command)[source]

Add rows argument to unit subcommand.

Return type:

None

utms.cli.commands.unit.helper.add_columns_argument(command)[source]

Add columns argument to unit subcommand.

Return type:

None