Metadata¶
Variable metadata parsing and enrichment functionality.
Schema¶
Core data structures for representing variables and codebooks.
Pydantic models for metadata representation.
This module defines the core data structures for variables and codebooks, providing type-safe, validated models with rich metadata support.
- class statqa.metadata.schema.VariableType(*values)[source]¶
Bases:
StrEnumStatistical type of a variable.
- NUMERIC_CONTINUOUS = 'numeric_continuous'¶
- NUMERIC_DISCRETE = 'numeric_discrete'¶
- CATEGORICAL_NOMINAL = 'categorical_nominal'¶
- CATEGORICAL_ORDINAL = 'categorical_ordinal'¶
- DATETIME = 'datetime'¶
- TEXT = 'text'¶
- BOOLEAN = 'boolean'¶
- UNKNOWN = 'unknown'¶
- class statqa.metadata.schema.DataGeneratingProcess(*values)[source]¶
Bases:
StrEnumHow the data was generated.
- OBSERVATIONAL = 'observational'¶
- EXPERIMENTAL = 'experimental'¶
- QUASI_EXPERIMENTAL = 'quasi_experimental'¶
- SURVEY = 'survey'¶
- ADMINISTRATIVE = 'administrative'¶
- SIMULATION = 'simulation'¶
- UNKNOWN = 'unknown'¶
- class statqa.metadata.schema.MissingPattern(*values)[source]¶
Bases:
StrEnumPattern of missing data.
- MCAR = 'mcar'¶
- MAR = 'mar'¶
- MNAR = 'mnar'¶
- UNKNOWN = 'unknown'¶
- class statqa.metadata.schema.Variable(*, name, label, var_type=VariableType.UNKNOWN, dtype=None, description=None, valid_values=<factory>, missing_values=<factory>, missing_pattern=MissingPattern.UNKNOWN, units=None, range_min=None, range_max=None, is_ordinal=False, dgp=DataGeneratingProcess.UNKNOWN, is_treatment=False, is_outcome=False, is_confounder=False, temporal_variable=None, notes=None, source=None, enriched_metadata=<factory>)[source]¶
Bases:
BaseModelRepresents a single variable/column in a dataset.
- Variables:
name (str) – Variable identifier (e.g., ‘VCF0101’, ‘age’, ‘income’)
label (str) – Human-readable label/description
var_type (statqa.metadata.schema.VariableType) – Statistical type of the variable
dtype (str | None) – Raw data type (from pandas/numpy)
description (str | None) – Detailed description of what this variable measures
valid_values (dict[int | str, str]) – Mapping of codes to descriptions (e.g., {1: “Male”, 2: “Female”})
missing_values (set[int | str]) – Set of codes representing missing data (e.g., {-1, 999})
missing_pattern (statqa.metadata.schema.MissingPattern) – Pattern of missingness
units (str | None) – Measurement units (e.g., “years”, “USD”, “percentage”)
range_min (float | None) – Minimum valid value (for numeric)
range_max (float | None) – Maximum valid value (for numeric)
is_ordinal (bool) – Whether categorical variable has meaningful order
dgp (statqa.metadata.schema.DataGeneratingProcess) – Data generating process
is_treatment (bool) – Whether this is a treatment/intervention variable
is_outcome (bool) – Whether this is an outcome/dependent variable
is_confounder (bool) – Whether this is a potential confounder
temporal_variable (str | None) – Name of associated time variable (if longitudinal)
notes (str | None) – Additional metadata notes
source (str | None) – Data source or survey question text
enriched_metadata (dict[str, Any]) – LLM-generated enrichment information
- Parameters:
name (str)
label (str)
var_type (VariableType)
dtype (str | None)
description (str | None)
missing_pattern (MissingPattern)
units (str | None)
range_min (float | None)
range_max (float | None)
is_ordinal (bool)
dgp (DataGeneratingProcess)
is_treatment (bool)
is_outcome (bool)
is_confounder (bool)
temporal_variable (str | None)
notes (str | None)
source (str | None)
- var_type: VariableType¶
- missing_pattern: MissingPattern¶
- model_config = {'use_enum_values': True, 'validate_assignment': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class statqa.metadata.schema.Codebook(*, name, description=None, variables=<factory>, dataset_info=<factory>, citation=None, version=None, last_updated=None)[source]¶
Bases:
BaseModelRepresents a complete codebook/data dictionary.
- Variables:
name (str) – Codebook name/identifier
description (str | None) – Overall dataset description
variables (dict[str, statqa.metadata.schema.Variable]) – Mapping of variable names to Variable objects
citation (str | None) – How to cite this dataset
version (str | None) – Codebook version
last_updated (str | None) – Last update date
- Parameters:
- add_variable(variable)[source]¶
Add a variable to the codebook.
- Parameters:
variable (Variable)
- Return type:
None
- classmethod from_dict(data, name='codebook')[source]¶
Build a codebook from a parsed JSON mapping, accepting either shape.
A full codebook carries its own metadata and nests the variables under a variables key. Exports written straight from a variable mapping – which is what the bundled example codebooks contain – are a bare {variable_name: {…}} map with no surrounding metadata. Both are accepted so that either can be handed to the CLI.
- model_config = {'validate_assignment': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
Parsers¶
Base Parser¶
Base parser interface for codebook parsing.
Defines the abstract interface that all codebook parsers must implement.
- class statqa.metadata.parsers.base.BaseParser(**kwargs)[source]¶
Bases:
ABCAbstract base class for codebook parsers.
- Parameters:
kwargs (Any)
- abstractmethod parse(source)[source]¶
Parse a codebook from the given source.
- Parameters:
source (str | Path) – Path to codebook file or string content
- Returns:
Parsed Codebook object
- Raises:
ValueError – If source format is invalid
FileNotFoundError – If source file doesn’t exist
- Return type:
CSV Parser¶
CSV-based codebook parser.
Parses codebooks stored in CSV format with columns like: - variable_name - label - type - description - valid_values - missing_values - units - etc.
Text Parser¶
Text-based codebook parser.
Parses structured text codebooks with variable definitions. Supports formats like:
# Variable: age
Label: Respondent Age
Type: numeric_continuous
Units: years
Range: 18-99
Missing: -1, 999
Description: Age of respondent at time of survey
# Variable: gender
Label: Gender
Type: categorical_nominal
Values:
1: Male
2: Female
3: Other
Missing: 0
Statistical Formats Parser¶
Statistical format parser for SPSS, Stata, and SAS files.
Uses pyreadstat library to parse statistical data files and extract rich metadata including variable labels, value labels, and missing value definitions.
Enricher¶
LLM-powered metadata enhancement.
LLM-based metadata enrichment.
Uses language models to verify, infer, and enrich variable metadata including: - Type inference and validation - Relationship suggestions - Causal structure hints - Missing pattern detection - Variable importance ranking
- class statqa.metadata.enricher.MetadataEnricher(provider='openai', model=None, api_key=None, **kwargs)[source]¶
Bases:
objectEnrich metadata using LLM capabilities.
Supports both OpenAI and Anthropic models.
- Parameters:
- enrich_variable(variable, dataset_context=None)[source]¶
Enrich a single variable’s metadata.
- Parameters:
- Returns:
Enriched Variable with updated metadata
- Raises:
EnrichmentError – If enrichment process fails
LLMConnectionError – If LLM connection fails
LLMResponseError – If LLM response is invalid
- Return type: