seed_vault.models package

Submodules

seed_vault.models.common module

class seed_vault.models.common.CircleArea(**data)[source]

Bases: BaseModel

Represents a circular geographic area for seismic data analysis.

This class is used to define circular constraints for selecting seismic data based on a central point and a radius.

lat

The latitude of the circle’s center.

Type:

float

lon

The longitude of the circle’s center.

Type:

float

max_radius

The maximum radius of the circle.

Type:

float

min_radius

The minimum radius of the circle. Defaults to 0.

Type:

float, optional

Properties:

color (str): Returns the predefined color associated with the area.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

property color: str
lat: float
lon: float
max_radius: float
min_radius: float
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class seed_vault.models.common.RectangleArea(**data)[source]

Bases: BaseModel

Represents a rectangular area defined by latitude and longitude boundaries.

This class is used to define geographic bounding boxes for seismic data analysis.

min_lat

The minimum latitude of the rectangle.

Type:

float

max_lat

The maximum latitude of the rectangle.

Type:

float

min_lon

The minimum longitude of the rectangle.

Type:

float

max_lon

The maximum longitude of the rectangle.

Type:

float

Properties:

color (str): Returns the predefined color associated with the area.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

property color: str
max_lat: float
max_lon: float
min_lat: float
min_lon: float
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class seed_vault.models.common.StatusHandler[source]

Bases: object

Manages warning, error, and log messages categorized by type.

This class provides methods for tracking and organizing status messages, including warnings, errors, and logs, to facilitate debugging and status reporting.

status

A dictionary storing messages categorized under “warnings”, “errors”, and “logs”.

Type:

Dict[str, Dict[str, List[str]]]

add_warning(category

str, message: str): Adds a warning message to a specific category.

add_error(category

str, message: str): Adds an error message to a specific category.

add_log(category

str, message: str, level: str = “info”): Adds a log message with an optional severity level.

get_status() Dict[str, Dict[str, List[str]]][source]

Returns the complete status dictionary.

has_errors() bool[source]

Checks if there are any recorded errors.

has_warnings() bool[source]

Checks if there are any recorded warnings.

display()[source]

Prints all warnings, errors, and logs stored in the status dictionary.

generate_status_report(level

str = None) -> str: Generates a formatted status report, optionally filtering by level.

Initializes the StatusHandler with empty dictionaries for warnings, errors, and logs.

add_error(category, message)[source]

Adds an error message to a specific category in the status dictionary.

Parameters:
  • category (str) – The category under which the error should be stored.

  • message (str) – The error message to add.

add_log(category, message, level='info')[source]

Adds a log message to a specific category with an optional severity level.

Parameters:
  • category (str) – The category under which the log should be stored.

  • message (str) – The log message to add.

  • level (str, optional) – The severity level of the log (e.g., “info”, “warning”, “error”). Defaults to “info”.

add_warning(category, message)[source]

Adds a warning message to a specific category in the status dictionary.

Parameters:
  • category (str) – The category under which the warning should be stored.

  • message (str) – The warning message to add.

display()[source]

Prints all warnings, errors, and logs stored in the status dictionary.

generate_status_report(level=None)[source]

Generates a formatted string report of the current status, optionally filtered by a specified level.

Parameters:

level (str, optional) – The status category to filter by (e.g., “warnings”, “errors”, “logs”). If None, includes all categories.

Returns:

A formatted status report containing warnings, errors, and logs.

Returns “No status messages available.” if no messages are found.

Return type:

str

get_status()[source]

Returns the full status dictionary containing warnings, errors, and logs.

Returns:

The complete status dictionary.

Return type:

Dict[str, Dict[str, List[str]]]

has_errors()[source]

Checks if there are any recorded error messages.

Returns:

True if there are errors, False otherwise.

Return type:

bool

has_warnings()[source]

Checks if there are any recorded warning messages.

Returns:

True if there are warnings, False otherwise.

Return type:

bool

seed_vault.models.config module

class seed_vault.models.config.AuthConfig(**data)[source]

Bases: BaseModel

The AuthConfig class defines attributes for network.station.location.channel code, username, and password.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

nslc_code: str
password: str
username: str
class seed_vault.models.config.DateConfig(**data)[source]

Bases: BaseModel

This class defines a DateConfig with optional start and end times, as well as optional before and after time definition used for events.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

end_after: Union[date, Any, None]
end_before: Union[date, Any, None]
end_time: Union[date, Any, None]
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

start_after: Union[date, Any, None]
start_before: Union[date, Any, None]
start_time: Union[date, Any, None]
class seed_vault.models.config.EventConfig(**data)[source]

Bases: BaseModel

The EventConfig class defines parameters for configuring earthquake event queries with default values. It is designed to store criteria for filtering earthquake events.

client

The FDSN client to use for retrieving earthquake data. Defaults to “EARTHSCOPE”.

Type:

Optional[str]

date_config

The date range for querying earthquake events.

Type:

DateConfig

model

The seismic velocity model to use. Defaults to “IASP91”.

Type:

str

min_depth

The minimum earthquake depth in kilometers. Defaults to -5.0.

Type:

float

max_depth

The maximum earthquake depth in kilometers. Defaults to 1000.0.

Type:

float

min_magnitude

The minimum earthquake magnitude. Defaults to 5.5.

Type:

float

max_magnitude

The maximum earthquake magnitude. Defaults to 10.0.

Type:

float

min_radius

The minimum distance from the event in degrees. Defaults to 30.0.

Type:

float

max_radius

The maximum distance from the event in degrees. Defaults to 90.0.

Type:

float

before_p_sec

The number of seconds before the P-wave arrival. Defaults to 10.

Type:

int

after_p_sec

The number of seconds after the P-wave arrival. Defaults to 130.

Type:

int

include_all_origins

Whether to include all origins of an event. Defaults to False.

Type:

bool

include_all_magnitudes

Whether to include all magnitude values for an event. Defaults to False.

Type:

bool

include_arrivals

Whether to include phase arrivals in the results. Defaults to False.

Type:

bool

local_catalog

The local earthquake catalog name, if applicable.

Type:

Optional[str]

eventtype

The type of earthquake event (e.g., “earthquake”, “explosion”).

Type:

Optional[str]

catalog

The name of the earthquake catalog used for querying events.

Type:

Optional[str]

contributor

The name of the contributor providing the earthquake data.

Type:

Optional[str]

updatedafter

The UTC timestamp indicating the last update time for event selection.

Type:

Optional[str]

limit

The maximum number of events to retrieve.

Type:

Optional[str]

offset

The offset for paginated earthquake data retrieval.

Type:

Optional[str]

selected_catalogs

A list of user-selected earthquake catalogs.

Type:

Optional[Any]

geo_constraint

Geospatial constraints on earthquake events.

Type:

Optional[List[GeometryConstraint]]

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

class Config[source]

Bases: object

exclude = {'selected_catalogs'}
json_encoders = {typing.Any: <function EventConfig.Config.<lambda>>}
after_p_sec: int
before_p_sec: int
catalog: Optional[str]
client: Optional[str]
contributor: Optional[str]
date_config: DateConfig
eventtype: Optional[str]
geo_constraint: Optional[List[GeometryConstraint]]
include_all_magnitudes: bool
include_all_origins: bool
include_arrivals: bool
limit: Optional[str]
local_catalog: Optional[str]
max_depth: float
max_magnitude: float
max_radius: float
min_depth: float
min_magnitude: float
min_radius: float
model: str
model_config: ClassVar[ConfigDict] = {'exclude': {'selected_catalogs'}, 'json_encoders': {typing.Any: <function EventConfig.Config.<lambda>>}}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

offset: Optional[str]
selected_catalogs: Optional[Any]
set_default()[source]

Resets all fields to their default values.

updatedafter: Optional[str]
class seed_vault.models.config.GeometryConstraint(*, geo_type: GeoConstraintType | None = GeoConstraintType.NONE, coords: RectangleArea | CircleArea | None = None)[source]

Bases: BaseModel

The GeometryConstraint class defines a geometry constraint with a specified type and coordinates, automatically determining the constraint type based on the provided coordinates.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

coords: Union[RectangleArea, CircleArea, None]
geo_type: Optional[GeoConstraintType]
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class seed_vault.models.config.PredictionData(**data)[source]

Bases: BaseModel

The PredictionData class stores predicted arrival times of seismic waves at a given station.

This class represents the association between an event and a station, including estimated P-wave and S-wave arrival times.

resource_id

The unique identifier for the seismic event.

Type:

str

station_id

The identifier of the seismic station where arrivals are recorded.

Type:

str

p_arrival

The predicted arrival time of the primary (P) wave.

Type:

datetime

s_arrival

The predicted arrival time of the secondary (S) wave.

Type:

datetime

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

p_arrival: datetime
resource_id: str
s_arrival: datetime
station_id: str
class seed_vault.models.config.ProcessingConfig(**data)[source]

Bases: BaseModel

This class defines a configuration for processing with default values for the number of processes, gap tolerance, and logging.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

gap_tolerance: Optional[int]
logging: Optional[str]
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

num_processes: Optional[int]
class seed_vault.models.config.SeismoLoaderSettings(**data)[source]

Bases: BaseModel

The SeismoLoaderSettings class defines configuration settings for managing seismic data retrieval, processing, and storage. It provides attributes to control how seismic waveforms, station metadata, and event data are handled.

This class also includes methods for configuring download types, reading settings from a configuration file, managing authentication, and persisting settings to disk.

sds_path

The directory path for the Seismic Data Structure (SDS). Defaults to data/SDS.

Type:

str

db_path

The database file path for tracking downloaded data. Defaults to data/database.sqlite.

Type:

str

download_type

The type of download to perform (e.g., event-based or continuous).

Type:

DownloadType

selected_workflow

The selected workflow type (e.g., event-based, station-based).

Type:

WorkflowType

processing

Configuration settings for data processing. Defaults to None.

Type:

ProcessingConfig

client_url_mapping

A mapping of client URLs for data retrieval.

Type:

Optional[UrlMappings]

extra_clients

A dictionary of additional clients for querying seismic data.

Type:

Optional[dict]

auths

A list of authentication configurations.

Type:

Optional[List[AuthConfig]]

waveform

Configuration for waveform retrieval. Defaults to None.

Type:

WaveformConfig

station

Configuration for station metadata retrieval. Defaults to None.

Type:

StationConfig

event

Configuration for event data retrieval. Defaults to None.

Type:

EventConfig

predictions

A dictionary mapping event-station pairs to arrival time predictions.

Type:

Dict[str, PredictionData]

status_handler

A handler for tracking status messages and errors.

Type:

StatusHandler

set_download_type_from_workflow()[source]

Sets the download_type attribute based on the selected workflow.

from_cfg_file(cls, cfg_source

Union[str, IO]) -> “SeismoLoaderSettings”: Loads and initializes a SeismoLoaderSettings instance from a configuration file.

add_prediction(resource_id

str, station_id: str, p_arrival: datetime, s_arrival: datetime): Adds a predicted P-wave and S-wave arrival time for a given event and station.

get_prediction(resource_id

str, station_id: str) -> Optional[PredictionData]: Retrieves the predicted arrival time for a given event and station.

to_pickle(pickle_path

str) -> None: Serializes the SeismoLoaderSettings instance to a pickle file.

from_pickle_file(cls, pickle_path

str) -> “SeismoLoaderSettings”: Loads a SeismoLoaderSettings instance from a pickle file.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

class Config[source]

Bases: object

arbitrary_types_allowed = True
json_encoders = {<class 'datetime.datetime'>: <function SeismoLoaderSettings.Config.<lambda>>}
add_prediction(resource_id, station_id, p_arrival, s_arrival)[source]

Adds a predicted P-wave and S-wave arrival time for a given event and station.

Parameters:
  • resource_id (str) – The unique identifier of the seismic event.

  • station_id (str) – The identifier of the seismic station.

  • p_arrival (datetime) – The predicted arrival time of the P-wave.

  • s_arrival (datetime) – The predicted arrival time of the S-wave.

add_to_config()[source]
auths: Optional[List[AuthConfig]]
client_url_mapping: Optional[UrlMappings]
classmethod create_default()[source]

Creates an instance of SeismoLoaderSettings with default values.

db_path: str
download_type: DownloadType
event: Optional[EventConfig]
extra_clients: Optional[dict]
classmethod from_cfg_file(cfg_source)[source]

Loads a SeismoLoaderSettings instance from a configuration file.

Parameters:

cfg_source (Union[str, IO]) – The path to the configuration file or a file-like object.

Returns:

A populated instance of the class.

Return type:

SeismoLoaderSettings

classmethod from_pickle_file(pickle_path)[source]

Loads a SeismoLoaderSettings instance from a pickle file.

Parameters:

pickle_path (str) – The file path from which the object should be loaded.

Returns:

The loaded instance of the class.

Return type:

SeismoLoaderSettings

get_prediction(resource_id, station_id)[source]

Retrieves the predicted arrival time for a given event and station.

Parameters:
  • resource_id (str) – The unique identifier of the seismic event.

  • station_id (str) – The identifier of the seismic station.

Returns:

The predicted arrival time data, or None if not found.

Return type:

Optional[PredictionData]

has_changed(old_settings)[source]

Compare self with old_settings and return a dictionary indicating which parts have changed.

Parameters:

old_settings (SeismoLoaderSettings) – The old settings to compare against.

Returns:

A dictionary with keys indicating which properties changed.

Return type:

Dict[str, bool]

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'json_encoders': {<class 'datetime.datetime'>: <function SeismoLoaderSettings.Config.<lambda>>}}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

static parse_optional(value)[source]
predictions: Dict[str, PredictionData]
processing: ProcessingConfig
sds_path: str
selected_workflow: WorkflowType
set_download_type_from_workflow()[source]

Sets the download type based on the selected workflow.

If selected_workflow is EVENT_BASED or STATION_BASED, sets download_type to EVENT. If selected_workflow is CONTINUOUS, sets download_type to CONTINUOUS.

station: StationConfig
status_handler: StatusHandler
to_cfg()[source]

Converts the SeismoLoaderSettings instance into a ConfigParser object.

This method constructs a configuration file representation of the current settings stored in the SeismoLoaderSettings instance. It organizes the settings into sections such as SDS, DATABASE, PROCESSING, AUTH, WAVEFORM, STATION, and EVENT.

Returns:

A ConfigParser object representing the current settings.

Return type:

configparser.ConfigParser

to_pickle(pickle_path)[source]

Serializes the SeismoLoaderSettings instance to a pickle file.

Parameters:

pickle_path (str) – The file path where the object should be saved.

Return type:

None

waveform: WaveformConfig
class seed_vault.models.config.SeismoQuery(cmb_str_n_s=None, *, network: str | None = None, station: str | None = None, location: str | None = None, channel: str | None = None, starttime: datetime | None = None, endtime: datetime | None = None)[source]

Bases: BaseModel

This Python class SeismoQuery represents a seismic query params with properties for network, station, location, channel, start time, and end time, along with methods to convert combined network and station string to individual properties.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

channel: Optional[str]
property cmb_str
cmb_str_n_s_to_props(cmb_n_s)[source]
endtime: Optional[datetime]
location: Optional[str]
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

network: Optional[str]
starttime: Optional[datetime]
station: Optional[str]
class seed_vault.models.config.StationConfig(**data)[source]

Bases: BaseModel

The StationConfig class defines configuration settings for querying seismic stations.

This class allows users to specify parameters such as the seismic network, station selection, and geographical constraints while retrieving station metadata.

client

The FDSN client for retrieving station metadata. Defaults to “EARTHSCOPE”.

Type:

Optional[str]

force_stations

A list of stations to forcefully include in the query.

Type:

Optional[List[SeismoQuery]]

exclude_stations

A list of stations to exclude from the query.

Type:

Optional[List[SeismoQuery]]

date_config

The date range for station availability queries.

Type:

DateConfig

local_inventory

Path to a local station inventory file, if applicable.

Type:

Optional[str]

network

The seismic network code (e.g., “IU”, “NE”) to filter stations.

Type:

Optional[str]

station

The station code to filter results.

Type:

Optional[str]

location

The location code for further filtering.

Type:

Optional[str]

channel

The channel code (e.g., “BHZ”, “HHZ”) to specify station channels.

Type:

Optional[str]

highest_samplerate_only

Whether to select only the station with the highest sample rate. Defaults to False.

Type:

bool

selected_invs

A list of pre-selected inventories.

Type:

Optional[Any]

geo_constraint

Geospatial constraints to filter stations.

Type:

Optional[List[GeometryConstraint]]

include_restricted

Whether to include restricted (non-public) stations. Defaults to False.

Type:

bool

level

The level of station metadata detail to retrieve. Defaults to Levels.CHANNEL.

Type:

Levels

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

class Config[source]

Bases: object

exclude = {'selected_invs'}
json_encoders = {typing.Any: <function StationConfig.Config.<lambda>>}
channel: Optional[str]
client: Optional[str]
date_config: DateConfig
exclude_stations: Optional[List[SeismoQuery]]
force_stations: Optional[List[SeismoQuery]]
geo_constraint: Optional[List[GeometryConstraint]]
highest_samplerate_only: bool
include_restricted: bool
level: Levels
local_inventory: Optional[str]
location: Optional[str]
model_config: ClassVar[ConfigDict] = {'exclude': {'selected_invs'}, 'json_encoders': {typing.Any: <function StationConfig.Config.<lambda>>}}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

network: Optional[str]
selected_invs: Optional[Any]
set_default()[source]

Resets all fields to their default values.

station: Optional[str]
class seed_vault.models.config.WaveformConfig(**data)[source]

Bases: BaseModel

The WaveformConfig class defines a data model with optional fields for configuring waveform data requests, with a method to reset all fields to their default values.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

channel_pref: Optional[str]
client: Optional[str]
days_per_request: Optional[int]
force_redownload: Optional[bool]
location_pref: Optional[str]
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

set_default()[source]

Resets all fields to their default values.

seed_vault.models.config.convert_to_str(val)[source]

The function convert_to_str converts various types of values to strings, handling different cases and providing error handling.

Parameters:

val – The convert_to_str function takes a value val as input and attempts to convert it to a string representation. It handles different types of values such as None, Enum, strings, integers, floats, booleans, objects with __str__ method, and other unsupported

Returns:

The function convert_to_str returns a string representation of the input value val. It handles different types of input values and converts them to a string using various methods based on their type. If the conversion fails, it catches the exception and returns an empty string.

seed_vault.models.config.parse_time(time_str)[source]

The function parse_time attempts to parse a given time string in various formats and return it in ISO format.

Parameters:

time_str – The date-time in string format. Some acceptable input formats are: ‘2014,2,1’ | ‘2014001’ | ‘2014,3,2,0,0,5’

Returns:

The parse_time function is attempting to parse a time string using different formats. If successful, it returns the parsed time in ISO format. If parsing fails for all formats, it returns None.

seed_vault.models.config.safe_add_to_config(config, section, key, value)[source]

The function safe_add_to_config safely adds key-value pairs to a configuration dictionary, handling any exceptions that may occur.

Parameters:
  • config – Config is a dictionary that stores configuration settings. It typically has sections as keys, where each section contains key-value pairs representing specific configuration settings.

  • section – Section refers to a specific section within the configuration file where the key-value pair will be added. It helps organize and categorize different settings or options within the configuration file.

  • key – The key parameter in the safe_add_to_config function refers to the key of the key-value pair that you want to add to the configuration. It is used to uniquely identify the value associated with it within a specific section of the configuration.

  • value – Value is the data that you want to add to the configuration file under the specified section and key. It could be a string, integer, boolean, or any other data type that you want to store in the configuration.

seed_vault.models.exception module

exception seed_vault.models.exception.NotFoundError(message='Record Not found!')[source]

Bases: Exception

Exception raised when a specific entity is not found.

seed_vault.models.url_mapping module

class seed_vault.models.url_mapping.UrlMapping(**data)[source]

Bases: BaseModel

Represents a mapping between a seismic data client and its corresponding URL.

client

The name of the seismic data client.

Type:

str

url

The associated URL for retrieving seismic data.

Type:

str

is_original

Indicates whether the client is an original one from URL_MAPPINGS.

Type:

bool

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

client: str
is_original: bool
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

url: str
class seed_vault.models.url_mapping.UrlMappings(**data)[source]

Bases: BaseModel

Manages and synchronizes client URL mappings for seismic data retrieval.

This class maintains a list of known clients, checks for updates, and allows users to add new clients. It also provides functionality to load, save, and sync mappings with URL_MAPPINGS.

maps

A dictionary mapping client names to URLs.

Type:

Optional[dict]

df_maps

A Pandas DataFrame storing the client mapping data.

Type:

Optional[Any]

save_path

The file path where client mappings are stored (default: clients.csv).

Type:

Path

check_saved_clients(df

pd.DataFrame) -> pd.DataFrame: Validates and updates the saved client list by checking against URL_MAPPINGS.

save(extra_clients

List[dict] = None): Saves the client mappings to a CSV file and synchronizes them with URL_MAPPINGS.

sync_maps(df_maps

pd.DataFrame): Synchronizes the maps dictionary with the latest client mappings from a dataframe.

load()[source]

Loads the client mappings from the saved file and ensures synchronization.

get_clients(client_type

ClientType = ClientType.ALL) -> Union[List[str], Dict[str, str]]: Retrieves a list of clients based on the specified client_type.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

check_saved_clients(df)[source]

Validates and updates the saved client list by checking against URL_MAPPINGS.

This method ensures that: - Clients marked as original but no longer exist in URL_MAPPINGS are removed. - New clients found in URL_MAPPINGS that are not in the saved list are added.

Parameters:

df (pd.DataFrame) – The dataframe containing the saved client mappings.

Returns:

The updated dataframe with verified client mappings.

Return type:

pd.DataFrame

df_maps: Optional[Any]
get_clients(client_type=ClientType.ALL)[source]

Retrieves a list of clients based on the specified client_type.

Parameters:

client_type (ClientType, optional) – The type of clients to retrieve. - ClientType.ALL: Returns all clients. - ClientType.ORIGINAL: Returns only the original clients. - ClientType.EXTRA: Returns only the extra clients.

Returns:

A list of client names or a dictionary of client URLs.

Return type:

Union[List[str], Dict[str, str]]

Raises:

ValueError – If an unknown client_type is provided.

load()[source]

Loads the client mappings from the saved file and ensures synchronization.

This method: - Initializes the maps dictionary. - Calls save() to ensure the client mappings are properly saved and updated.

maps: Optional[dict]
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

save(extra_clients=None)[source]

Saves the client mappings to a CSV file and synchronizes them with URL_MAPPINGS.

This method: - Loads the existing client mappings if a saved file exists. - Updates the list with newly added extra_clients if provided. - Removes outdated extra clients that are no longer in use. - Writes the updated mappings back to disk. - Synchronizes the mappings with URL_MAPPINGS.

Parameters:

extra_clients (List[dict], optional) – A list of additional client mappings to add.

save_path: Path
sync_maps(df_maps)[source]

Synchronizes the maps dictionary with the latest client mappings from the dataframe.

This method updates both the instance’s maps dictionary and the global URL_MAPPINGS to reflect the latest client URL assignments.

Parameters:

df_maps (pd.DataFrame) – The dataframe containing the client mapping information.

Module contents