imednet.utils package¶
Utils init module.
Submodules¶
imednet.utils.arrow module¶
PyArrow serialization helpers.
- imednet.utils.arrow.to_arrow_table(data_records, schema=None)[source]¶
Serialize record dictionaries (or Pydantic-like objects) into a
pyarrow.Table.- Parameters:
data_records (list[dict[str, Any] | _ModelDumpable]) – Record payloads to serialize. Each item must be a dictionary or expose a
model_dump()method that returns a dictionary.schema (Schema | None) – Optional explicit Arrow schema. When provided, output columns follow schema order and types; when omitted, columns and types are inferred. Naive
datetimevalues are interpreted as UTC. When schema inference is used, datetime columns use microsecond precision. Boolean strings accepttrue/false,1/0,yes/no,y/n, andt/f.
- Returns:
A fully initialized
pyarrow.Tablewith deterministic columns and null values for missing or empty-string inputs.- Raises:
ImportError – If
pyarrowis not installed.TypeError – If a record is not dict-like and does not expose
model_dump.
- Return type:
Table
imednet.utils.ast_eval module¶
Restricted AST evaluation engine re-exports.
imednet.utils.async_bridge module¶
Async-first execution bridge and sync-to-async facade adapter.
Provides runtime helpers that allow synchronous wrappers on ImednetSDK
to delegate to canonical async engines safely across standard scripts,
Jupyter notebooks, FastAPI/asyncio services, and WebAssembly Pyodide runtimes.
- class imednet.utils.async_bridge.SyncToAsyncFacadeAdapter[source]¶
Bases:
objectAdapts a synchronous
ImednetFacadeto satisfyAsyncImednetFacade.Never instantiates
httpx.AsyncClient; all operations delegate to the caller’s synchronous SDK or mock facade.- __init__(sync_sdk, *, offload_threads=False)[source]¶
Initialize the adapter around
sync_sdk.- Parameters:
sync_sdk (ImednetFacade) –
offload_threads (bool) –
- Return type:
None
- property auth: AuthStrategy | None¶
Return the authentication provider from the wrapped SDK.
- property config: Any¶
Return the configuration object from the wrapped SDK if available.
- async create_record(*args, **kwargs)[source]¶
Delegate
create_recordto the wrapped synchronous facade.- Parameters:
args (Any) –
kwargs (Any) –
- Return type:
Any
- async create_records_batch(*args, **kwargs)[source]¶
Delegate
create_records_batchto the wrapped synchronous facade.- Parameters:
args (Any) –
kwargs (Any) –
- Return type:
Any
- async get_codings(*args, **kwargs)[source]¶
Delegate
get_codingsto the wrapped synchronous facade.- Parameters:
args (Any) –
kwargs (Any) –
- Return type:
list[Any]
- async get_forms(*args, **kwargs)[source]¶
Delegate
get_formsto the wrapped synchronous facade.- Parameters:
args (Any) –
kwargs (Any) –
- Return type:
list[Any]
- async get_intervals(*args, **kwargs)[source]¶
Delegate
get_intervalsto the wrapped synchronous facade.- Parameters:
args (Any) –
kwargs (Any) –
- Return type:
list[Any]
- async get_job(*args, **kwargs)[source]¶
Delegate
get_jobto the wrapped synchronous facade.- Parameters:
args (Any) –
kwargs (Any) –
- Return type:
Any
- async get_queries(*args, **kwargs)[source]¶
Delegate
get_queriesto the wrapped synchronous facade.- Parameters:
args (Any) –
kwargs (Any) –
- Return type:
list[Any]
- async get_record_revisions(*args, **kwargs)[source]¶
Delegate
get_record_revisionsto the wrapped synchronous facade.- Parameters:
args (Any) –
kwargs (Any) –
- Return type:
list[Any]
- async get_records(*args, **kwargs)[source]¶
Delegate
get_recordsto the wrapped synchronous facade.- Parameters:
args (Any) –
kwargs (Any) –
- Return type:
list[Any]
- async get_sites(*args, **kwargs)[source]¶
Delegate
get_sitesto the wrapped synchronous facade.- Parameters:
args (Any) –
kwargs (Any) –
- Return type:
list[Any]
- async get_studies(*args, **kwargs)[source]¶
Delegate
get_studiesto the wrapped synchronous facade.- Parameters:
args (Any) –
kwargs (Any) –
- Return type:
list[Any]
- async get_subjects(*args, **kwargs)[source]¶
Delegate
get_subjectsto the wrapped synchronous facade.- Parameters:
args (Any) –
kwargs (Any) –
- Return type:
list[Any]
- async get_users(*args, **kwargs)[source]¶
Delegate
get_usersto the wrapped synchronous facade.- Parameters:
args (Any) –
kwargs (Any) –
- Return type:
list[Any]
- async get_variables(*args, **kwargs)[source]¶
Delegate
get_variablesto the wrapped synchronous facade.- Parameters:
args (Any) –
kwargs (Any) –
- Return type:
list[Any]
- async get_visits(*args, **kwargs)[source]¶
Delegate
get_visitsto the wrapped synchronous facade.- Parameters:
args (Any) –
kwargs (Any) –
- Return type:
list[Any]
- async poll_job(*args, **kwargs)[source]¶
Delegate
poll_jobto the wrapped synchronous facade.- Parameters:
args (Any) –
kwargs (Any) –
- Return type:
Any
- async poll_jobs(*args, **kwargs)[source]¶
Delegate
poll_jobsto the wrapped synchronous facade.- Parameters:
args (Any) –
kwargs (Any) –
- Return type:
Any
- study_context(study_key)[source]¶
Enter the wrapped SDK’s
study_contextif available, else corestudy_context.- Parameters:
study_key (str) –
- Return type:
Iterator[SyncToAsyncFacadeAdapter]
- property sync_sdk: ImednetFacade¶
Return the wrapped synchronous SDK facade.
- async imednet.utils.async_bridge.call_async_facade_method(sdk, canonical_name, *args, **kwargs)[source]¶
Invoke
await sdk.<canonical_name>(...)with legacyasync_*mock fallback.- Parameters:
sdk (Any) –
canonical_name (str) –
args (Any) –
kwargs (Any) –
- Return type:
Any
- imednet.utils.async_bridge.is_async_facade(sdk)[source]¶
Return True when
sdkis anAsyncImednetSDKorAsyncImednetFacade.Correctly distinguishes synchronous and asynchronous SDK instances, mocks with
spec=ImednetFacadevsspec=AsyncImednetFacade, and minimal test stubs.- Parameters:
sdk (object) –
- Return type:
bool
- async imednet.utils.async_bridge.maybe_to_thread(func, /, *args, **kwargs)[source]¶
Run
func(*args, **kwargs)in a worker thread withContextVarpropagation.Falls back to inline execution on WebAssembly/Emscripten (Pyodide) or constrained environments where OS threads cannot be spawned.
- Parameters:
func (Callable[..., T]) –
args (Any) –
kwargs (Any) –
- Return type:
T
- imednet.utils.async_bridge.run_sync_over_async(coro_factory)[source]¶
Execute an async coroutine factory synchronously, even inside active event loops.
When no event loop is running on the current thread, calls
asyncio.rundirectly.When an event loop is already running (e.g. Jupyter, FastAPI,
pytest-asyncio):On CPython, executes
asyncio.runinside a dedicated worker thread with fullcontextvarspropagation so the outer event loop is never re-entered.On Pyodide / Emscripten (where OS threads are unavailable), runs an isolated
SelectorEventLoopto completion and restores the activeWebLoop.
- Parameters:
coro_factory (Callable[[], Coroutine[Any, Any, T]]) –
- Return type:
T
imednet.utils.batch_coordinator module¶
Centralized chunked batch submission and validation coordinator.
- class imednet.utils.batch_coordinator.AsyncBatchCoordinator[source]¶
Bases:
objectAsynchronously coordinate single-pass validation, bounded chunking, and job polling.
- __init__(chunk_size=100, *, sdk=None)[source]¶
Initialize the asynchronous batch coordinator.
- Parameters:
chunk_size (int) –
sdk (Any) –
- Return type:
None
- async submit(study_key, records_data, submit_chunk, *, schema=None, validate_batch_fn=None, skip_validation=False, skipped_count=0, wait_for_completion=False, poll_single=None, poll_many=None, on_progress=None, require_batch_id=False, raise_on_poll_failure=True, dry_run=False, collect_errors=False, sdk=None, prefer_poll_many=False)[source]¶
Validate once, asynchronously submit bounded chunks, and optionally poll.
- Parameters:
study_key (str) –
records_data (list[dict[str, Any]]) –
submit_chunk (Callable[[list[dict[str, Any]]], Awaitable[Job]]) –
schema (ValidationSchemaProtocol | None) –
validate_batch_fn (Callable[..., Awaitable[Any]] | None) –
skip_validation (bool) –
skipped_count (int) –
wait_for_completion (bool) –
poll_single (Callable[..., Awaitable[JobStatus]] | None) –
poll_many (Callable[..., Awaitable[JobPollSummary]] | None) –
on_progress (JobProgressCallback | Callable[[JobStatusEvent], None] | None) –
require_batch_id (bool) –
raise_on_poll_failure (bool) –
dry_run (bool) –
collect_errors (bool) –
sdk (Any) –
prefer_poll_many (bool) –
- Return type:
- class imednet.utils.batch_coordinator.BatchCoordinator[source]¶
Bases:
objectCoordinate single-pass validation, bounded chunking, and job polling.
- __init__(chunk_size=100, *, sdk=None)[source]¶
Initialize the synchronous batch coordinator.
- Parameters:
chunk_size (int) –
sdk (Any) –
- Return type:
None
- submit(study_key, records_data, submit_chunk, *, schema=None, validate_batch_fn=None, skip_validation=False, skipped_count=0, wait_for_completion=False, poll_single=None, poll_many=None, on_progress=None, require_batch_id=False, raise_on_poll_failure=True, dry_run=False, collect_errors=False, sdk=None, prefer_poll_many=False)[source]¶
Validate once, submit in bounded chunks, and optionally poll to completion.
- Parameters:
study_key (str) –
records_data (list[dict[str, Any]]) –
submit_chunk (Callable[[list[dict[str, Any]]], Job]) –
schema (ValidationSchemaProtocol | None) –
validate_batch_fn (Callable[..., Any] | None) –
skip_validation (bool) –
skipped_count (int) –
wait_for_completion (bool) –
poll_single (Callable[..., JobStatus] | None) –
poll_many (Callable[..., JobPollSummary] | None) –
on_progress (JobProgressCallback | Callable[[JobStatusEvent], None] | None) –
require_batch_id (bool) –
raise_on_poll_failure (bool) –
dry_run (bool) –
collect_errors (bool) –
sdk (Any) –
prefer_poll_many (bool) –
- Return type:
- class imednet.utils.batch_coordinator.BatchSubmissionSummary[source]¶
Bases:
objectSummary of a chunked batch submission and optional job polling.
- study_key: str¶
Required.
- chunk_sizes: list[int]¶
Required.
- total_records: int¶
Required.
- skipped_count: int = 0¶
- poll_summary: JobPollSummary | None = None¶
- dry_run: bool = False¶
- validation_report: BatchValidationReport | None = None¶
- unsubmitted_chunks: list[list[dict[str, Any]]] = list()¶
- wait_for_completion: bool = False¶
- has_error: bool = False¶
- property all_successful: bool¶
Return True if validation and all chunks succeeded without failed or unpolled jobs.
- property batch_ids: list[str]¶
Return all non-empty batch IDs created across submitted chunks.
- property chunk_count: int¶
Return the number of submitted chunks.
- property created_record_ids: list[int]¶
Return server-assigned integer
recordIdvalues across successful records.
- property enrolled_subject_keys: list[str]¶
Return sanitized
subjectKeyvalues across successful records.
- property record_errors: list[dict[str, Any]]¶
Return sanitized per-record and variable-level error dicts across polled jobs.
- property successful_records: list[dict[str, Any]]¶
Return sanitized successful record result dicts across polled jobs.
- property unsubmitted_records: list[dict[str, Any]]¶
Return flattened unsubmitted record slices across all unsubmitted chunks.
- imednet.utils.batch_coordinator.chunk_records(records_data, chunk_size=100)[source]¶
Split
records_datainto bounded chunks of at mostchunk_sizeitems.- Parameters:
records_data (list[dict[str, Any]]) –
chunk_size (int) –
- Return type:
list[list[dict[str, Any]]]
- imednet.utils.batch_coordinator.extract_single_submitted_job(summary, *, method_name, batch_method_name)[source]¶
Return the single submitted Job from
summaryor raiseValidationError.- Parameters:
summary (BatchSubmissionSummary) –
method_name (str) –
batch_method_name (str) –
- Return type:
- async imednet.utils.batch_coordinator.poll_facade_many_async(sdk, study_key, batch_ids, *, timeout, poll_interval, on_progress=None, resolve_results=False)[source]¶
Asynchronously poll multiple batch IDs via
sdk.poll_jobswith fallback.- Parameters:
sdk (Any) –
study_key (str) –
batch_ids (list[str]) –
timeout (float) –
poll_interval (float) –
on_progress (JobProgressCallback | Callable[[JobStatusEvent], None] | None) –
resolve_results (bool) –
- Return type:
- imednet.utils.batch_coordinator.poll_facade_many_sync(sdk, study_key, batch_ids, *, timeout, poll_interval, on_progress=None, resolve_results=False)[source]¶
Poll multiple batch IDs via
sdk.poll_jobswith fallback tosdk.poll_job.- Parameters:
sdk (Any) –
study_key (str) –
batch_ids (list[str]) –
timeout (float) –
poll_interval (float) –
on_progress (JobProgressCallback | Callable[[JobStatusEvent], None] | None) –
resolve_results (bool) –
- Return type:
- async imednet.utils.batch_coordinator.poll_facade_single_async(sdk, study_key, batch_id, *, timeout, poll_interval, on_progress=None, resolve_results=False)[source]¶
Asynchronously poll a single batch ID via
sdk.poll_job.- Parameters:
sdk (Any) –
study_key (str) –
batch_id (str) –
timeout (float) –
poll_interval (float) –
on_progress (JobProgressCallback | Callable[[JobStatusEvent], None] | None) –
resolve_results (bool) –
- Return type:
Any
- imednet.utils.batch_coordinator.poll_facade_single_sync(sdk, study_key, batch_id, *, timeout, poll_interval, on_progress=None, resolve_results=False)[source]¶
Poll a single batch ID via
sdk.poll_job, omittingon_progresswhenNone.- Parameters:
sdk (Any) –
study_key (str) –
batch_id (str) –
timeout (float) –
poll_interval (float) –
on_progress (JobProgressCallback | Callable[[JobStatusEvent], None] | None) –
resolve_results (bool) –
- Return type:
Any
- imednet.utils.batch_coordinator.sanitize_job_diagnostics(job)[source]¶
Return a copy of
jobwith diagnostic results redacted for secrets and PHI.
- imednet.utils.batch_coordinator.validate_single_job_preflight(records_data, *, chunk_size, dry_run, method_name, batch_method_name)[source]¶
Guard single-Job workflow methods against dry-run, empty, and multi-chunk inputs.
- Parameters:
records_data (list[dict[str, Any]]) –
chunk_size (int) –
dry_run (bool) –
method_name (str) –
batch_method_name (str) –
- Return type:
None
imednet.utils.dates module¶
Utility functions for parsing and formatting ISO date/time strings.
- imednet.utils.dates.format_iso_datetime(dt)[source]¶
Format a datetime object into a whole-second UTC ISO 8601 string ending with ‘Z’.
Fractional seconds are truncated toward the floor second so inclusive
>=bounds never skip records modified within the boundary second.- Parameters:
dt (datetime) – datetime object (naive or timezone-aware).
- Returns:
A string representing the UTC datetime in
YYYY-MM-DDTHH:MM:SSZformat.- Return type:
str
- imednet.utils.dates.normalize_iso_date(value, *, date_order=None)[source]¶
Normalize a date, datetime, or date-like string into a canonical ISO 8601 string.
Use only for explicitly selected date fields. Invalid, ambiguous and partial strings are returned unchanged; no components are imputed. Slash dates with two possible interpretations require date_order. Timezone offsets and source fractional precision are preserved.
- Parameters:
value (Any) – Input value to normalize.
date_order (Literal['MDY', 'DMY'] | None) – Explicit ordering for ambiguous slash dates.
- Returns:
ISO 8601 formatted date/datetime string, or original value if not a date.
- Return type:
Any
- imednet.utils.dates.normalize_utc_timestamp_bound(value, *, is_end=False)[source]¶
Normalize a date or timestamp string to an ISO 8601 UTC timestamp bound.
Date-only inputs expand to
T00:00:00Zwhenis_endisFalseandT23:59:59Zwhenis_endisTrue. Full timestamps are converted to UTC ending withZ.- Parameters:
value (str) – Date or ISO 8601 datetime string.
is_end (bool) – Whether to use end-of-day time for date-only inputs.
- Returns:
Canonical ISO 8601 UTC timestamp string ending with
Z.- Raises:
ValueError – If
valueis empty or cannot be parsed as a valid date or datetime.- Return type:
str
- imednet.utils.dates.parse_iso_datetime(date_str)[source]¶
Parse an ISO 8601 date/time string into a datetime object.
Handles timestamps ending with ‘Z’ as UTC.
- Parameters:
date_str (str) – ISO 8601 formatted date/time string.
- Returns:
A timezone-aware datetime object.
- Raises:
ValueError – If the input string is not a valid ISO format.
- Return type:
datetime
imednet.utils.db module¶
Centralized database connection utilities.
- imednet.utils.db.get_db_init_lock(db_path)[source]¶
Return the reentrant initialization lock for
db_path.- Parameters:
db_path (str | Path) –
- Return type:
<function RLock at 0x7c41603a2fc0>
- imednet.utils.db.get_sqlite_connection(db_path, timeout=30.0, busy_timeout_ms=30000, foreign_keys=False, *, check_same_thread=True)[source]¶
Return a SQLite connection configured for concurrent access.
- Parameters:
db_path (str | Path) –
timeout (float) –
busy_timeout_ms (int) –
foreign_keys (bool) –
check_same_thread (bool) –
- Return type:
Connection
- imednet.utils.db.sqlite_connection(db_path, timeout=30.0, busy_timeout_ms=30000, foreign_keys=False, *, check_same_thread=True)[source]¶
Context manager yielding a safely configured SQLite connection.
- Parameters:
db_path (str | Path) –
timeout (float) –
busy_timeout_ms (int) –
foreign_keys (bool) –
check_same_thread (bool) –
- Return type:
Iterator[Connection]
imednet.utils.enrollment module¶
Shared subject enrollment normalization and site eligibility helpers.
- imednet.utils.enrollment.extract_candidate_subject_key(item, *, payload=None, subject_key_field=None)[source]¶
Extract an optional subject key or OID candidate for enrollment deduplication.
- Parameters:
item (RegisterSubjectRequest | Mapping[str, Any]) –
payload (Mapping[str, Any] | None) –
subject_key_field (str | None) –
- Return type:
str | None
- imednet.utils.enrollment.filter_existing_subject_registrations(normalized_pairs, existing_subjects=None, *, should_filter=False, subject_key_field=None)[source]¶
Dump normalized subject requests and optionally filter already-enrolled/duplicate keys.
- Parameters:
normalized_pairs (Sequence[tuple[RegisterSubjectRequest | dict[str, Any], RegisterSubjectRequest]]) –
existing_subjects (Iterable[Subject] | None) –
should_filter (bool) –
subject_key_field (str | None) –
- Return type:
tuple[list[dict[str, Any]], int]
- imednet.utils.enrollment.normalize_subject_registration_inputs(subjects, *, default_form_key=None, default_form_id=None, default_site_name=None, default_site_id=None, schema=None, study_key=None)[source]¶
Normalize registration requests from models, dicts, DataFrame, or CSV/JSON file path.
- Parameters:
subjects (Sequence[RegisterSubjectRequest | dict[str, Any]] | Any) –
default_form_key (str | None) –
default_form_id (int | None) –
default_site_name (str | None) –
default_site_id (int | None) –
schema (ValidationSchemaProtocol | None) –
study_key (str | None) –
- Return type:
list[tuple[RegisterSubjectRequest | dict[str, Any], RegisterSubjectRequest]]
- imednet.utils.enrollment.validate_local_subject_registration_sites(normalized_pairs)[source]¶
Validate local
siteNameorsiteIdpresence without issuing remote site queries.- Parameters:
normalized_pairs (Sequence[tuple[RegisterSubjectRequest | dict[str, Any], RegisterSubjectRequest]]) –
- Return type:
None
- imednet.utils.enrollment.validate_subject_registration_sites(normalized_pairs, sites)[source]¶
Validate that every registration request targets an existing, enrollment-eligible site.
When
sitesisNone(offline dry-run), only verifies that a site identifier (siteNameorsiteId) is present on each request.- Parameters:
normalized_pairs (Sequence[tuple[RegisterSubjectRequest | dict[str, Any], RegisterSubjectRequest]]) –
sites (Iterable[Site] | None) –
- Return type:
None
imednet.utils.evaluator module¶
Restricted AST evaluation engine for safe study business logic execution.
- class imednet.utils.evaluator.RestrictedAstEvaluator[source]¶
Bases:
objectObject-oriented interface for restricted expression parsing and evaluation.
- __init__(expr)[source]¶
Initialize and validate the expression.
- Parameters:
expr (str) – The expression string to parse and validate.
- Return type:
None
- evaluate(env=None, default=None, fallback=None, raise_on_error=False)[source]¶
Evaluate the pre-parsed AST expression.
- Parameters:
env (dict[str, Any] | None) – Variable environment mapping identifiers to values.
default (Any) – Default value if evaluation fails.
fallback (Any) – Alternative default value.
raise_on_error (bool) – Whether to raise errors on failure.
- Returns:
The evaluated expression result or fallback.
- Return type:
Any
- imednet.utils.evaluator.evaluate_expression(expr, env=None, default=None, fallback=None, raise_on_error=False)[source]¶
Evaluate a Python expression safely using restricted AST traversal.
- Parameters:
expr (str | AST) – Python expression string or pre-parsed AST node.
env (dict[str, Any] | None) – Variable environment mapping identifiers to values.
default (Any) – Default value returned if evaluation fails and raise_on_error is False.
fallback (Any) – Alternative name for default value (used if default is None).
raise_on_error (bool) – If True, raise EvaluationError/RestrictedEvaluationError on error.
- Returns:
The result of the evaluated expression, or default/fallback value if evaluation fails.
- Return type:
Any
- imednet.utils.evaluator.parse_expression(expr)[source]¶
Parse and validate an expression string into a restricted AST.
- Parameters:
expr (str) – Python expression string to parse.
- Returns:
The validated ast.Expression tree.
- Raises:
EvaluationError – If parsing fails due to syntax error or empty input.
RestrictedEvaluationError – If forbidden syntax or attributes are found.
- Return type:
Expression
- imednet.utils.evaluator.validate_ast(node, allowed_functions=None)[source]¶
Validate that an AST contains only safe and permitted syntax nodes.
- Parameters:
node (AST) – The AST node or tree to validate.
allowed_functions (set[str] | None) – Optional set of allowed callable function names.
- Raises:
RestrictedEvaluationError – If an unsafe node, private attribute, or unapproved callable is detected.
- Return type:
None
imednet.utils.filters module¶
Utility functions for building API filter strings.
This module provides functionality to construct filter query parameters for iMednet API endpoints based on the reference documentation.
- imednet.utils.filters.build_filter_string(filters, and_connector=';', or_connector=',', *, model=None)[source]¶
Return a filter string constructed according to iMednet rules.
Each key in
filtersis converted to camelCase. Raw values imply equality, tuples allow explicit operators, lists of(operator, value)tuples on one key join withand_connector, and lists of scalars generate multiple equality filters joined byor_connector. Conditions across keys are joined byand_connector.Example: >>> from imednet.utils.filters import build_filter_string >>> build_filter_string({‘age’: (‘>’, 30), ‘status’: ‘active’}) ‘age>30;status==active’ >>> build_filter_string({‘type’: [‘A’, ‘B’]}) ‘type==A,type==B’
- Parameters:
filters (dict[str, Any | tuple[str, Any] | list[Any]]) –
and_connector (str) –
or_connector (str) –
model (type[Any] | None) –
- Return type:
str
- imednet.utils.filters.coerce_query_status(val, *, param_name='status')[source]¶
Coerce val into a validated
QueryStatusenum member.- Parameters:
val (Any) –
param_name (str) –
- Return type:
Any
- imednet.utils.filters.compile_raw_filter_expression(filter_str, *, model=None)[source]¶
Validate and compile a raw
filterstring, normalizing connectors and date bounds.- Parameters:
filter_str (str) –
model (type[Any] | None) –
- Return type:
str
- imednet.utils.filters.compile_sort_parameter(sort_value, *, sort_attributes=None, model=None, allow_record_data=None, endpoint_name=None)[source]¶
Validate and compile a
sortargument into wire<property>,<asc|desc>parameter(s).Normalizes
snake_caseproperty names tocamelCase(preserving<Variable>casing onrecordData.<Variable>when permitted), validates against endpointsort_attributes(ormodelscalar aliases), and returns alist[str]when multiple sort clauses are specified so HTTP clients emit repeatedsortparameters.- Raises:
ConfigurationError – If syntax, direction, or attribute validation fails.
- Parameters:
sort_value (str | Sequence[str]) –
sort_attributes (Collection[str] | None) –
model (type[Any] | None) –
allow_record_data (bool | None) –
endpoint_name (str | None) –
- Return type:
str | list[str]
- imednet.utils.filters.derive_model_sort_attributes(model, *, local_attributes=None)[source]¶
Derive canonical camelCase sortable property names from scalar
MODELaliases.- Parameters:
model (type[Any]) –
local_attributes (Collection[str] | None) –
- Return type:
frozenset[str]
- imednet.utils.filters.extract_filter_attributes(filter_str)[source]¶
Extract attribute names from a raw filter expression.
- Parameters:
filter_str (str) –
- Return type:
list[str]
- imednet.utils.filters.matches_query_status_bounds(item, local_predicates)[source]¶
Return True when item satisfies all local
(op, target)status predicates.- Parameters:
item (Any) –
local_predicates (Sequence[tuple[str, Any]]) –
- Return type:
bool
- imednet.utils.filters.matches_revision_date_bound(rev_dt, op, bound_val, *, attr_name='dateCreated')[source]¶
Evaluate a local date comparison operator against a parsed UTC timestamp.
- Parameters:
rev_dt (datetime | None) –
op (str) –
bound_val (Any) –
attr_name (str) –
- Return type:
bool
- imednet.utils.filters.matches_revision_date_bounds(item, local_bounds)[source]¶
Return True if item satisfies all
(snake_attr, op, bound_val)local date bounds.- Parameters:
item (Any) –
local_bounds (Sequence[tuple[str, str, Any]]) –
- Return type:
bool
- imednet.utils.filters.normalize_filter_connectors(filter_str)[source]¶
Normalize word connectors (‘and’/’or’) to canonical ‘;’ or ‘,’ delimiters.
- Parameters:
filter_str (str) –
- Return type:
str
- imednet.utils.filters.parse_filter_expression(filter_str, *, model=None, allowed_attributes=None, local_attributes=None, allow_regex=False)[source]¶
Parse a single filter expression string into
(key, value_or_operator_tuple).Matches two-character comparison operators (
<=,>=,!=,==, and=~whenallow_regex=True) and single-character inequalities (<,>) before single=equality shorthand per the iMednet Common API specification.- Parameters:
filter_str (str) – Raw filter expression string.
model (type[Any] | None) – Optional Pydantic model class used for scalar coercion and fallback key checks.
allowed_attributes (Collection[str] | None) – Optional endpoint filter attribute allowlist.
local_attributes (Collection[str] | None) – Optional client-side filter attributes accepted alongside
allowed_attributes.allow_regex (bool) – Whether to permit
=~(Table 7recordDataFilteronly).
- Returns:
Tuple of
(key, parsed_value)whereparsed_valueis(operator, scalar)for explicit operators orscalarfor=shorthand.- Raises:
ValueError – If syntax, operator, or key validation fails.
- Return type:
tuple[str, Any]
- imednet.utils.filters.parse_filter_expressions(expressions, *, model=None, allowed_attributes=None, local_attributes=None, allow_regex=False, multi_bound_attributes=None)[source]¶
Parse multiple filter expressions into a filter dictionary.
Supports compound
;(AND) and,(OR) expressions, quote-aware values, endpointallowed_attributesallowlists, and resourcemodelscalar coercion. Duplicate attributes in;(AND) clauses are rejected after normalizingsnake_casetocamelCaseunless listed inmulti_bound_attributes(which accumulate intolist[tuple[str, Any]]). Comma-separated OR expressions return{"filter": formatted_or_string}.- Parameters:
expressions (Sequence[str]) –
model (type[Any] | None) –
allowed_attributes (Collection[str] | None) –
local_attributes (Collection[str] | None) –
allow_regex (bool) –
multi_bound_attributes (Collection[str] | None) –
- Return type:
dict[str, Any]
- imednet.utils.filters.parse_revision_timestamp_utc(raw)[source]¶
Parse a revision timestamp or date into a UTC-aware datetime.
- Parameters:
raw (Any) –
- Return type:
datetime | None
- imednet.utils.filters.resolve_query_status(query)[source]¶
Resolve
QueryStatusfrom explicit model/dict status orqueryComments.- Parameters:
query (Any) –
- Return type:
Any
- imednet.utils.filters.split_query_status_filters(filters)[source]¶
Split client-side
statuspredicates from upstreamQueriesEndpointfilters.- Parameters:
filters (dict[str, Any] | Any) –
- Return type:
tuple[dict[str, Any], list[tuple[str, Any]]]
- imednet.utils.filters.split_revision_date_bounds(filters, *, start_date=None, end_date=None)[source]¶
Split secondary
dateCreatedandlastUpdatedAND bounds for local evaluation.Ensures upstream requests contain at most one
dateCreatedclause and at most onelastUpdatedclause perANDfilter while evaluating all remaining date bounds locally.- Parameters:
filters (Mapping[str, Any]) –
start_date (str | datetime | date | None) –
end_date (str | datetime | date | None) –
- Return type:
tuple[dict[str, Any], list[tuple[str, str, Any]]]
- imednet.utils.filters.validate_connector_exclusivity(filter_str)[source]¶
Validate that a filter expression does not combine both ‘;’ and ‘,’ connectors.
Connectors inside double quotation marks are ignored. The literal string ‘none’ (case-insensitive) bypasses validation.
- Parameters:
filter_str (str) – The filter expression string to validate.
- Raises:
ValueError – If both ‘;’ and ‘,’ connectors appear outside quotation marks, or if quotation marks are unclosed.
- Return type:
None
- imednet.utils.filters.validate_filter_key(key, *, model=None, allowed_attributes=None, local_attributes=None)[source]¶
Validate that a filter key is non-empty, operator-free, and allowed.
- Parameters:
key (str) – The key string to validate.
model (type[Any] | None) – Optional Pydantic resource model class to validate attribute names against.
allowed_attributes (Collection[str] | None) – Optional endpoint filter attribute allowlist. When provided, takes precedence over
modelattribute membership while preservingsnake_caseandcamelCaseforms.local_attributes (Collection[str] | None) – Optional client-side filter attributes accepted alongside
allowed_attributes.
- Raises:
ValueError – If key is empty, contains whitespace or operator characters, or is not permitted by
allowed_attributes/model.- Return type:
None
- imednet.utils.filters.validate_filter_operator(operator, *, allow_regex=False)[source]¶
Validate that an operator matches allowed tokens and contains no whitespace.
- Parameters:
operator (str) – The operator string to validate.
allow_regex (bool) – Whether to allow the
=~operator (forrecordDataFilter).
- Raises:
ValueError – If operator contains whitespace or is not in the allowed set.
- Return type:
None
- imednet.utils.filters.validate_filter_syntax(filter_str)[source]¶
Validate a standard
filterexpression for syntax, operators, and uniqueness.Verifies connector exclusivity, ensures no whitespace exists outside of double-quoted strings, restricts operators to Table 2 (excluding
=~), and rejects duplicate attributes in;(AND) clauses.- Parameters:
filter_str (str) – The filter expression string to validate.
- Raises:
ValueError – If syntax, operator, or attribute uniqueness rules are violated.
- Return type:
None
- imednet.utils.filters.validate_record_filter(filter_str)[source]¶
Validate a
recordDataFilterexpression for syntax, operators, and uniqueness.Allows
=~per Common API Table 7 while enforcing connector exclusivity, quote/whitespace rules, and unique attributes in;(AND) clauses.- Parameters:
filter_str (str) – The recordDataFilter expression string to validate.
- Raises:
ValueError – If syntax, operator, or attribute uniqueness rules are violated.
- Return type:
None
imednet.utils.job_poller module¶
Utility for polling job status.
- class imednet.utils.job_poller.AsyncJobPoller[source]¶
Bases:
BaseJobPollerAsynchronously poll a job until completion.
- __init__(get_job, fetch_result=None)[source]¶
Initialize the asynchronous job poller.
- Parameters:
get_job (Callable[[str, str], Awaitable[JobStatus]]) – Awaitable callable that takes study_key and batch_id and returns JobStatus.
fetch_result (Callable[[str], Awaitable[Any]] | None) – Optional awaitable callable to fetch the result data.
- Return type:
None
- async async_poll_many(study_key, batch_ids, interval=5.0, timeout=300.0, *, on_progress=None, fail_fast=False)[source]¶
Asynchronously poll multiple jobs concurrently with cooperative cancellation.
All jobs are polled in parallel. Results are collected regardless of individual failures unless fail_fast=True, which cancels and awaits pending sibling tasks before raising the triggering exception.
- Parameters:
study_key (str) –
batch_ids (list[str]) –
interval (float) –
timeout (float) –
on_progress (JobProgressCallback | Callable[[JobStatusEvent], None] | None) –
fail_fast (bool) –
- Return type:
- async run(study_key, batch_id, interval=5.0, timeout=300.0, *, on_progress=None)[source]¶
Asynchronously poll a job until completion.
- Parameters:
study_key (str) –
batch_id (str) –
interval (float) –
timeout (float) –
on_progress (JobProgressCallback | Callable[[JobStatusEvent], None] | None) –
- Return type:
- class imednet.utils.job_poller.BaseJobPoller[source]¶
Bases:
objectBase class for polling a job until it reaches a terminal state.
- exception imednet.utils.job_poller.JobFailedError[source]¶
Bases:
ImednetErrorRaised when a job fails, is cancelled, has failed records, or fails fetching resultUrl.
- __init__(message, status, *, record_errors=None, result_error=None, poll_summary=None, partial_summary=None)[source]¶
Initialize the JobFailedError with attached record and batch diagnostics.
- Parameters:
message (str) –
status (JobStatus) –
record_errors (list[dict[str, Any]] | None) –
result_error (str | None) –
poll_summary (JobPollSummary | None) –
partial_summary (Any | None) –
- Return type:
None
- property attempt_count: int | None¶
Return the number of attempts executed before failure, if present.
- property cause_type: str | None¶
Return the underlying exception class name, if present.
- property method: str | None¶
Return the HTTP method from
diagnostic_context, if present.
- property retry_after: float | None¶
Return the parsed
Retry-Afterdelay in seconds, if present.
- property url: str | None¶
Return the sanitized request URL from
diagnostic_context, if present.
- class imednet.utils.job_poller.JobPollSummary[source]¶
Bases:
objectAggregate result of polling multiple jobs.
- study_key: str¶
Required.
- failures: dict[str, Exception]¶
Required.
- elapsed_total: float¶
Required.
- property all_successful: bool¶
Return True if all jobs were successful with zero failed records.
- property any_failed: bool¶
Return True if any job failed, timed out, or reported failed records.
- property terminal_statuses: dict[str, imednet.models.jobs.JobStatus]¶
Return all terminal JobStatus objects across completed results and failed batches.
- class imednet.utils.job_poller.JobPoller[source]¶
Bases:
BaseJobPollerSynchronously poll a job until completion.
- __init__(get_job, fetch_result=None)[source]¶
Initialize the synchronous job poller.
- Parameters:
get_job (Callable[[str, str], JobStatus]) – Callable that takes study_key and batch_id and returns JobStatus.
fetch_result (Callable[[str], Any] | None) – Optional callable to fetch the result data from the result URL.
- Return type:
None
- poll_many(study_key, batch_ids, interval=5.0, timeout=300.0, *, on_progress=None, fail_fast=False)[source]¶
Poll multiple jobs concurrently using threading.
Parameters¶
- study_keystr
The study key.
- batch_idsList[str]
The batch IDs to monitor.
- intervalfloat
Seconds between poll cycles.
- timeoutfloat
Seconds before a job is considered timed out.
- fail_fastbool
If True, wake sibling worker threads cooperatively and raise the triggering exception (such as JobFailedError or JobTimeoutError) as soon as any single job fails or times out. If False (default), continue polling remaining jobs and collect all failures into JobPollSummary.failures.
- on_progressOptional[JobProgressCallback]
Called for each job on each poll cycle. Thread-safe: the callback must be safe to call from multiple threads simultaneously.
- Parameters:
study_key (str) –
batch_ids (list[str]) –
interval (float) –
timeout (float) –
on_progress (JobProgressCallback | Callable[[JobStatusEvent], None] | None) –
fail_fast (bool) –
- Return type:
- run(study_key, batch_id, interval=5.0, timeout=300.0, *, on_progress=None)[source]¶
Synchronously poll a job until completion.
- Parameters:
study_key (str) –
batch_id (str) –
interval (float) –
timeout (float) –
on_progress (JobProgressCallback | Callable[[JobStatusEvent], None] | None) –
- Return type:
- class imednet.utils.job_poller.JobProgressCallback[source]¶
Bases:
ProtocolCallable invoked on each poll cycle with the current job status.
Parameters¶
- batch_idstr
The batch ID being polled.
- statusJobStatus
The current status object from the jobs endpoint.
- elapsedfloat
Seconds elapsed since polling started for this job.
- class imednet.utils.job_poller.JobStatusEvent[source]¶
Bases:
objectStructured event for job status updates.
- batch_id: str¶
Required.
- poll_number: int¶
Required.
- elapsed: float¶
Required.
- is_terminal: bool¶
Required.
- exception imednet.utils.job_poller.JobTimeoutError[source]¶
Bases:
ImednetError,TimeoutErrorRaised when a job does not finish before the timeout.
- __init__(message='', status_code=None, code=None, status=None, *, diagnostic_context=None)¶
Initialize the error.
- Parameters:
message (str) –
status_code (int | None) –
code (int | None) –
status (Any) –
diagnostic_context (DiagnosticContext | None) –
- Return type:
None
- property attempt_count: int | None¶
Return the number of attempts executed before failure, if present.
- property cause_type: str | None¶
Return the underlying exception class name, if present.
- property method: str | None¶
Return the HTTP method from
diagnostic_context, if present.
- property retry_after: float | None¶
Return the parsed
Retry-Afterdelay in seconds, if present.
- property url: str | None¶
Return the sanitized request URL from
diagnostic_context, if present.
- imednet.utils.job_poller.evaluate_job_state(job, previous_state=None)[source]¶
Evaluate a job’s status.
Verifies monotonic state progression before raising errors.
- Parameters:
- Returns:
True if the job completed successfully. False if the job is still in progress.
- Raises:
InvalidJobStateError – If the job state string is unrecognized.
InvalidJobTransitionError – If the transition from previous_state to current state is invalid.
JobFailedError – If the job ended in a failed or cancelled state.
- Return type:
bool
imednet.utils.json_logging module¶
JSON logging configuration utility.
imednet.utils.pandas module¶
Pandas helpers for working with iMednet models.
- imednet.utils.pandas.check_pandas(feature_name=None)[source]¶
Validate that pandas is installed, raising an ImportError if missing.
- Parameters:
feature_name (str | None) – Optional name of the feature or function requiring pandas.
- Raises:
ImportError – If pandas is not installed.
- Return type:
None
- imednet.utils.pandas.dataframe_to_records(df, *, schema=None, study_key=None, default_form_key=None, default_form_id=None)[source]¶
Convert a
pandas.DataFrameinto REST create-records payload dicts.Strips read-only
Recordsystem audit columns, preserves record update identifiers and metadata (recordId,recordOid,visitId,recordStatus,reasonForChange), maps snake_case and camelCase identifiers (formKey/formId,subjectKey/subjectOid/subjectId,siteName/siteId,intervalName/intervalId), dropsNaNand blank cells, coerces integer-valued floats (45.0 -> 45), and raisesValidationErrorif any cell contains***MASKED***.- Parameters:
df (DataFrame) –
schema (ValidationSchemaProtocol | None) –
study_key (str | None) –
default_form_key (str | None) –
default_form_id (int | None) –
- Return type:
list[dict[str, Any]]
- imednet.utils.pandas.export_records_csv(sdk, study_key, file_path, *, flatten=True, mask_phi=True, use_labels_as_columns=False)[source]¶
Fetch all records for
study_keyand write them tofile_path.Parameters are passed to
records_to_dataframe()and the resulting DataFrame is written withpandas.DataFrame.to_csv()usingindex=False.- Parameters:
sdk (ImednetSDK) –
study_key (str) –
file_path (str | PathLike[str]) –
flatten (bool) –
mask_phi (bool) –
use_labels_as_columns (bool) –
- Return type:
None
- imednet.utils.pandas.forms_to_dataframe(forms, *, mask_phi=True, study_key=None)[source]¶
Convert a list of
Formto a DataFrame.Each form model is serialized using
pydantic.BaseModel.model_dump()withby_alias=Falseand returned as apandas.DataFrame.- Parameters:
forms (list[Form]) –
mask_phi (bool) –
study_key (str | None) –
- Return type:
DataFrame
- imednet.utils.pandas.import_records_csv(sdk, study_key, file_path, *, email_notify=None, schema=None, chunk_size=100, skip_validation=False, wait_for_completion=False, timeout=300.0, interval=5.0, on_progress=None, dry_run=False, collect_errors=False, resolve_results=True)[source]¶
Import records from a CSV file into
study_keyusing stdlib CSV parsing.Preserves
recordId,recordOid,visitId,recordStatus, andreasonForChangefor symmetric round-trip updates. Works inpackages/coreeven whenpandasis not installed, and rejects***MASKED***sentinels before any HTTP request is sent.- Parameters:
sdk (ImednetSDK) –
study_key (str) –
file_path (str | PathLike[str]) –
email_notify (bool | str | None) –
schema (ValidationSchemaProtocol | None) –
chunk_size (int) –
skip_validation (bool) –
wait_for_completion (bool) –
timeout (float) –
interval (float) –
on_progress (JobProgressCallback | Callable[[JobStatusEvent], None] | None) –
dry_run (bool) –
collect_errors (bool) –
resolve_results (bool) –
- Return type:
- imednet.utils.pandas.intervals_to_dataframe(intervals, *, mask_phi=True, study_key=None)[source]¶
Convert a list of
Intervalto a DataFrame.Each interval model is serialized using
pydantic.BaseModel.model_dump()withby_alias=Falseand returned as apandas.DataFrame.- Parameters:
intervals (list[Interval]) –
mask_phi (bool) –
study_key (str | None) –
- Return type:
DataFrame
- imednet.utils.pandas.queries_to_dataframe(queries, *, mask_phi=True, study_key=None)[source]¶
Convert a list of
Queryto a DataFrame.Each query model is serialized using
pydantic.BaseModel.model_dump()withby_alias=Falseand returned as apandas.DataFrame.- Parameters:
queries (list[Query]) –
mask_phi (bool) –
study_key (str | None) –
- Return type:
DataFrame
- imednet.utils.pandas.records_to_dataframe(records, *, flatten=False, mask_phi=True, study_key=None, label_map=None)[source]¶
Convert a list of
Recordto a DataFrame.Each record is converted using
pydantic.BaseModel.model_dump()withby_alias=False. IfflattenisTruetherecord_datacolumn is expanded usingpandas.json_normalize()so that each variable becomes a column in the resulting DataFrame. Whenlabel_mapis provided withflatten=True, flattened variable columns are renamed to their mapped labels after PHI checks. Whenmask_phiisTrue(default), sensitive PHI fields and mapped variable labels insiderecord_dataare replaced with***MASKED***.- Parameters:
records (list[Record]) –
flatten (bool) –
mask_phi (bool) –
study_key (str | None) –
label_map (Mapping[str, str] | None) –
- Return type:
DataFrame
- imednet.utils.pandas.sites_to_dataframe(sites, *, mask_phi=True, study_key=None)[source]¶
Convert a list of
Siteto a DataFrame.Each site model is serialized using
pydantic.BaseModel.model_dump()withby_alias=Falseand returned as apandas.DataFrame.- Parameters:
sites (list[Site]) –
mask_phi (bool) –
study_key (str | None) –
- Return type:
DataFrame
- imednet.utils.pandas.subjects_to_dataframe(subjects, *, mask_phi=True, study_key=None)[source]¶
Convert a list of
Subjectto a DataFrame.Each subject model is serialized using
pydantic.BaseModel.model_dump()withby_alias=Falseand returned as apandas.DataFrame.- Parameters:
subjects (list[Subject]) –
mask_phi (bool) –
study_key (str | None) –
- Return type:
DataFrame
- imednet.utils.pandas.users_to_dataframe(users, *, mask_phi=True, study_key=None)[source]¶
Convert a list of
Userto a DataFrame.Each user model is serialized using
pydantic.BaseModel.model_dump()withby_alias=False(plus thenameconvenience property) and returned as apandas.DataFrame.- Parameters:
users (list[User]) –
mask_phi (bool) –
study_key (str | None) –
- Return type:
DataFrame
- imednet.utils.pandas.variables_to_dataframe(variables, *, mask_phi=True, study_key=None)[source]¶
Convert a list of
Variableto a DataFrame.Each variable model is serialized using
pydantic.BaseModel.model_dump()withby_alias=Falseand returned as apandas.DataFrame.- Parameters:
variables (list[Variable]) –
mask_phi (bool) –
study_key (str | None) –
- Return type:
DataFrame
- imednet.utils.pandas.visits_to_dataframe(visits, *, mask_phi=True, study_key=None)[source]¶
Convert a list of
Visitto a DataFrame.Each visit model is serialized using
pydantic.BaseModel.model_dump()withby_alias=Falseand returned as apandas.DataFrame.- Parameters:
visits (list[Visit]) –
mask_phi (bool) –
study_key (str | None) –
- Return type:
DataFrame
imednet.utils.record_filter_eval module¶
Client-side Record filter and recordDataFilter compilation and evaluation.
- class imednet.utils.record_filter_eval.CompiledRecordPredicate[source]¶
Bases:
objectCompiled Record metadata and recordData predicate with optional projection.
- meta_groups: tuple[tuple[str, tuple[_CompiledClause, ...]], ...] = ()¶
- data_connector: str = 'and'¶
- data_clauses: tuple[_CompiledClause, ...] = ()¶
- project_empty_record_data: bool = False¶
- always_empty: bool = False¶
imednet.utils.secrets module¶
Secret redaction utilities.
imednet.utils.security module¶
Security utilities.
- class imednet.utils.security.SensitivityRegistry[source]¶
Bases:
objectRegistry for managing sensitive fields (PHI) that should be masked in logs.
- __init__()[source]¶
Initialize the registry with default sensitive and exempt keys.
- Return type:
None
- add_exempt_key(key)[source]¶
Add a key to the exemption list.
- Parameters:
key (Any) –
- Return type:
None
- add_sensitive_key(key)[source]¶
Add a key to the sensitive list if it is not exempted.
- Parameters:
key (Any) –
- Return type:
None
- is_exempt(key)[source]¶
Check if a key is explicitly exempted from PHI masking.
- Parameters:
key (Any) –
- Return type:
bool
- is_sensitive(key)[source]¶
Check if a key is considered sensitive and not exempted.
- Parameters:
key (Any) –
- Return type:
bool
- remove_exempt_key(key)[source]¶
Remove a key from the exemption list.
- Parameters:
key (Any) –
- Return type:
None
- imednet.utils.security.build_study_sensitivity_registry(custom_phi_keys=None)[source]¶
Return a SensitivityRegistry combining global rules with custom_phi_keys.
- Parameters:
custom_phi_keys (Collection[str] | None) –
- Return type:
- imednet.utils.security.mask_clinical_phi(value, *, registry=None)[source]¶
Recursively mask sensitive keys in unstructured data.
- Parameters:
value (Any) –
registry (SensitivityRegistry | None) –
- Return type:
Any
- imednet.utils.security.sanitize_csv_formula(value)[source]¶
Sanitize a value to prevent CSV/Excel Formula Injection.
Prefixes strings starting with =, +, -, or @ (even after whitespace) with a single quote. Lists and tuples are recursively sanitized.
- Parameters:
value (Any) –
- Return type:
Any
- imednet.utils.security.sanitize_diagnostic_payload(value, *, registry=None)[source]¶
Deep-sanitize structured payloads by redacting credentials and masking clinical PHI.
- Parameters:
value (Any) –
registry (SensitivityRegistry | None) –
- Return type:
Any
- imednet.utils.security.sanitize_diagnostic_text(value, *, registry=None, _depth=0)[source]¶
Redact credentials, URL filters, multiline JSON, and inline PHI expressions in text.
- Parameters:
value (Any) –
registry (SensitivityRegistry | None) –
_depth (int) –
- Return type:
str
- imednet.utils.security.validate_header_value(value)[source]¶
Validate that a header value does not contain newline characters.
- Parameters:
value (str) – The header value to validate.
- Raises:
ClientError – If the value contains newline characters.
- Return type:
None
imednet.utils.serialization module¶
Data serialization and flattening utilities.
imednet.utils.tabular module¶
Standard-library CSV and tabular record normalization utilities.
- imednet.utils.tabular.csv_text_to_records(raw_csv, *, schema=None, study_key=None, default_form_key=None, default_form_id=None)[source]¶
Parse CSV text into REST create-records payload dicts.
- Parameters:
raw_csv (str) –
schema (ValidationSchemaProtocol | None) –
study_key (str | None) –
default_form_key (str | None) –
default_form_id (int | None) –
- Return type:
list[dict[str, Any]]
- imednet.utils.tabular.csv_to_records(path, *, encoding='utf-8-sig', schema=None, study_key=None, default_form_key=None, default_form_id=None)[source]¶
Load a CSV file into REST create-records payload dicts using the standard library.
Works in
packages/coreeven whenpandasis not installed.- Parameters:
path (str | PathLike[str]) –
encoding (str) –
schema (ValidationSchemaProtocol | None) –
study_key (str | None) –
default_form_key (str | None) –
default_form_id (int | None) –
- Return type:
list[dict[str, Any]]
- imednet.utils.tabular.dataframe_rows_to_records(df, *, schema=None, study_key=None, default_form_key=None, default_form_id=None)[source]¶
Convert a
pandas.DataFrameinto REST create-records payload dicts.- Parameters:
df (Any) –
schema (ValidationSchemaProtocol | None) –
study_key (str | None) –
default_form_key (str | None) –
default_form_id (int | None) –
- Return type:
list[dict[str, Any]]
- imednet.utils.tabular.ensure_no_masked_sentinel(records)[source]¶
Raise
ValidationErrorif any record model or mapping contains***MASKED***.- Parameters:
records (Sequence[BaseModel | Mapping[str, Any]]) –
- Return type:
None
- imednet.utils.tabular.normalize_record_mapping(item, *, default_form_key=None, default_form_id=None, convert_record_data_alias=True)[source]¶
Normalize a single record request model or mapping into a canonical
camelCasedict.- Parameters:
item (BaseModel | Mapping[str, Any]) –
default_form_key (str | None) –
default_form_id (int | None) –
convert_record_data_alias (bool) –
- Return type:
dict[str, Any]
- imednet.utils.tabular.normalize_record_payload_item(item)[source]¶
Normalize a
BaseRecordRequestor mapping into a camelCaseJsonDict.- Parameters:
item (BaseRecordRequest | Mapping[str, Any]) –
- Return type:
dict[str, Any]
- imednet.utils.tabular.normalize_record_sequence(records, *, default_form_key=None, default_form_id=None, convert_record_data_alias=True, skip_validation=False)[source]¶
Validate sentinels and normalize a sequence of record models or mappings to
camelCase.- Parameters:
records (Sequence[Any]) –
default_form_key (str | None) –
default_form_id (int | None) –
convert_record_data_alias (bool) –
skip_validation (bool) –
- Return type:
list[dict[str, Any]]
- imednet.utils.tabular.normalize_records_input(records_data, *, schema=None, study_key=None, default_form_key=None, default_form_id=None, skip_validation=False)[source]¶
Normalize
DataFrame, CSV path, or sequence of requests/mappings into record payload dicts.- Parameters:
records_data (Sequence[BaseRecordRequest | Mapping[str, Any]] | DataFrameLike | str | PathLike[str]) –
schema (ValidationSchemaProtocol | None) –
study_key (str | None) –
default_form_key (str | None) –
default_form_id (int | None) –
skip_validation (bool) –
- Return type:
list[dict[str, Any]]
- imednet.utils.tabular.normalize_tabular_row(raw_row, *, row_index=0, from_csv_str=False, schema=None, study_key=None, default_form_key=None, default_form_id=None)[source]¶
Normalize a single DataFrame or CSV row into a REST create-records payload dict.
Returns
Noneif every cell in the row is empty.- Parameters:
raw_row (Mapping[str, Any]) –
row_index (int) –
from_csv_str (bool) –
schema (ValidationSchemaProtocol | None) –
study_key (str | None) –
default_form_key (str | None) –
default_form_id (int | None) –
- Return type:
dict[str, Any] | None
imednet.utils.typing module¶
Type definitions for imednet SDK utilities.
imednet.utils.url module¶
URL manipulation and sanitization utilities.
- imednet.utils.url.build_safe_path(base_path, *segments)[source]¶
Build a normalized relative URL path with strict segment validation and encoding.
- Parameters:
base_path (str) – Static base path prefix to start from.
*segments (Any) – Additional path segments. Non-string values are stringified.
- Returns:
A slash-normalized relative path with each segment validated and percent-encoded (preserving
@unencoded).- Raises:
PathTraversalValidationError – If any segment contains
?,#,\\, control characters, decoded/, or raw/decoded.or..parts.- Return type:
str
- imednet.utils.url.normalize_cache_origin(url)[source]¶
Normalize an SDK base URL into a canonical cache partition key.
- Parameters:
url (str | None) –
- Return type:
str
- imednet.utils.url.redact_sensitive_text(text, *, registry=None, _depth=0)[source]¶
Scan and redact sensitive URIs, connection strings, and query parameters in text.
- Parameters:
text (Any) –
registry (SensitivityRegistry | None) –
_depth (int) –
- Return type:
str
- imednet.utils.url.redact_url_query(url, sensitive_params=None, *, registry=None, _depth=0)[source]¶
Return URL with sensitive credential and clinical PHI query parameters redacted.
- Parameters:
url (str) –
sensitive_params (set[str] | None) –
registry (SensitivityRegistry | None) –
_depth (int) –
- Return type:
str
- imednet.utils.url.resolve_sdk_base_url(sdk)[source]¶
Resolve and normalize the configured EDC origin URL for an SDK or facade instance.
- Parameters:
sdk (Any) –
- Return type:
str
- imednet.utils.url.sanitize_base_url(url)[source]¶
Return base URL without trailing slashes or
/api,/api/v1, or/api/v1/edcsuffix.- Parameters:
url (str) –
- Return type:
str
- imednet.utils.url.validate_path_segment(segment, *, name='segment')[source]¶
Validate and percent-encode a single dynamic URL path segment.
- Parameters:
segment (Any) – Single dynamic identifier (e.g.,
study_key,batch_id,item_id).name (str) – Parameter label included in error diagnostics.
- Returns:
Strictly percent-encoded single segment preserving
@unencoded.- Raises:
PathTraversalValidationError – If the segment is empty, boolean, contains control characters or
/,\\,?,#, or resolves to.or...- Return type:
str
imednet.utils.validators module¶
Validation and normalization utilities for API response data.
- imednet.utils.validators.is_boolean_token(value)[source]¶
Check if a string represents a boolean value (e.g., ‘true’, ‘yes’, ‘0’).
- Parameters:
value (str) –
- Return type:
bool
- imednet.utils.validators.is_missing_value(value)[source]¶
Check if a value is None or an empty/whitespace-only string.
- Parameters:
value (Any) –
- Return type:
bool
- imednet.utils.validators.parse_bool(v, strict=None)[source]¶
Normalize boolean values from various representations.
Accepts bool, str, int, and finite float values in permissive mode and returns
Falsefor unknown, unparsable,NaN, or infinite inputs. RaisesValueErroronNaN, infinity, or invalid boolean inputs in strict mode.Example
>>> from imednet.utils.validators import parse_bool >>> parse_bool("yes") True >>> parse_bool("1.0") True >>> parse_bool(None) False
- Parameters:
v (Any) –
strict (bool | None) –
- Return type:
bool
- imednet.utils.validators.parse_datetime(v: datetime, *, strict: bool | None = None) datetime[source]¶
- imednet.utils.validators.parse_datetime(v: Any, *, strict: Literal[True]) datetime
- imednet.utils.validators.parse_datetime(v: str | int | float | datetime | None, *, strict: bool | None = None) datetime | None
Parse an ISO datetime string or numeric timestamp, returning
Nonewhen blank.In permissive mode, returns
Nonewhen a timestamp field is empty, missing, boolean, non-finite, or out of range. In strict mode, raisesValueErroron empty or invalid values.- Parameters:
v – Date string, numeric timestamp (seconds since epoch), datetime object, or None. Numeric values are assumed to be UTC timestamps.
strict – Optional explicit strict-mode override.
- imednet.utils.validators.parse_dict_or_default(v, default_factory=<class 'dict'>, *, strict=None)[source]¶
Normalize dictionary values, defaulting if None in permissive mode.
Raises
ValueErrorin strict mode whenvis not adict.- Parameters:
v (Any) –
default_factory (Callable[[], dict[str, Any]]) –
strict (bool | None) –
- Return type:
dict[str, Any]
- imednet.utils.validators.parse_int_or_default(v, default=0, strict=None)[source]¶
Normalize integer values, defaulting if None or empty string in permissive mode.
Rejects
boolinputs across all modes, and raisesValueError(orOverflowErroron string infinity) whenstrict=Trueor strict mode is active.- Parameters:
v (Any) –
default (int) –
strict (bool | None) –
- Return type:
int
- imednet.utils.validators.parse_list_or_default(v, default_factory=<class 'list'>, *, strict=None)[source]¶
Normalize list values, defaulting if None in permissive mode.
Raises
ValueErrorin strict mode whenvis not alist.- Parameters:
v (Any) –
default_factory (Callable[[], list[T]]) –
strict (bool | None) –
- Return type:
list[T]
- imednet.utils.validators.parse_str_or_default(v, default='', strict=None)[source]¶
Normalize string values, defaulting if None.
Guards against list and dict container values by emitting a drift warning and raising ValueError when strict=True or IMEDNET_STRICT_MODE is enabled.
- Parameters:
v (Any) –
default (str) –
strict (bool | None) –
- Return type:
str