Skip to content
oribi-ossPublic

About

Python library for generating AI-ready data context without sharing raw data.

Topics

Resources

Contributing

Stars

24 stars

Watchers

0 watching

Forks

Repository files navigation

Oribi logo

Give AI a useful picture of your data before it starts analyzing it.

Oribi is an open source Python library that profiles a pandas DataFrame and turns what it finds into structured analytical context. The result describes the dataset, its columns, likely semantic roles, candidate keys, possible grain, relationships, and analytical warnings.

Use that context as a starting point for AI assisted analysis, SQL generation, charting, or your own data exploration. Oribi profiles the DataFrame locally. It does not send your rows to an AI provider, and it does not require a specific model or AI service.

Get started

Install Oribi from PyPI:

python -m pip install oribi

Then inspect a DataFrame:

import pandas as pd
from oribi import inspect

df = pd.DataFrame({
    "order_id": [101, 101, 102, 102],
    "product_id": [7, 8, 7, 8],
    "revenue": [25.0, 40.0, 30.0, -5.0],
})

context = inspect(df)

print(context.summary())
print(context.to_context(max_chars=2_000))

summary() reports the dataset shape, likely grain, duplicate-row and warning counts when present, and up to three distinct warning messages in severity order. It takes no arguments and omits sampled values. to_context() creates a compact representation that you can include in an AI prompt.

What Oribi reports

The capabilities in this section are implemented in the current release. Oribi records measurements from the DataFrame and keeps its interpretations tied to evidence. Work that is not implemented is listed under Roadmap.

Area What it reports
Dataset Row and column counts, duplicate rows when pandas can compare them, and index information
Columns Missingness, distinct counts, per-column cardinality, numeric summaries, categorical top values, and datetime bounds
Semantic roles Likely identifiers, measures, dimensions, categories, temporal fields, booleans, text, or unknown columns
Numeric semantic types Name- or declaration-supported latitude, longitude, counts, identifiers, or summary statistics, independently of the broad role
Keys and grain Candidate single- and two-column keys, plus an estimate of what one row may represent
Relationships Observed value relationships within the same DataFrame
Analytical metrics Evidence-backed SQL metric definitions such as entity counts, additive totals, per-entity averages, and ratios
Analysis guidance Aggregation recommendations for likely measures, identifier counts, dimensions, and categories
Warnings Duplicate rows, missingness, non-unique identifiers, negative, non-finite, or highly skewed measures, high-cardinality categories and text, and possible gaps in regular datetime series

The column.cardinality.constancy field marks a column as constant when at least two non-missing observations share one value. A near-constant column has one value in at least 95% of non-missing rows and at least one exception. The evidence reports counts without including the dominant value. Ambiguous object equality and string-based counting fallbacks do not establish constancy.

Numeric columns can also expose column.semantic.semantic_type and semantic_type_evidence without changing column.semantic.role, aggregation guidance, or metrics. Supported types are latitude, longitude, count, identifier, and summary_statistic. Name and compatible value-shape hints can support a type: for example, a pair of similarly named coordinate axes within their respective ranges, or a count name such as population with non-negative whole values. A name-based result is a hypothesis, not proof of units or business meaning. Validate it against the data source. A type can differ from the broad role, and existing metrics do not use the type to change their behavior.

To supply source knowledge for an opaque column, set df.attrs["oribi_semantic_types"] = {"field_name": "count"} before inspection. Declarations are restricted to the supported values above and still require compatible observed values. Declared counts and identifiers must be non-negative whole numbers. Existing oribi_summary_statistics declarations can also support the summary type. For a name such as avg_item_count, an explicit summary declaration describes the result; without it, the count and summary hints remain unresolved. At least three values must be observed, no more than one quarter may be missing, the values must be finite, and at least two must differ. Count, identifier, coordinate, and summary hints without a declaration need at least three distinct values. For count, identifier, and coordinate hints, when five or fewer distinct values each repeat three times on average, the type is left unresolved. This conservative guard can also withhold a genuine low-range count, which source metadata can clarify; it does not identify every coded category. Named coordinate inference additionally needs a compatible matching axis, at least three jointly observed rows, and excludes known prefixes such as error, delta, and has. Short qualifiers such as d, sd, and se can also be place abbreviations, so this guard can withhold real coordinates. Unrecognized qualifiers and misleading names can still produce false hints. Unsupported declarations, conflicting signals, sparse data, and incompatible domains leave the type unresolved (None); a declaration does not override a conflicting name signal. Non-mapping type metadata and keys that do not match a column are ignored. Dictionary and JSON exports add these two fields to the semantic object. Markdown and compact context distinguish name hints from declarations and identify rejected declarations when space allows.

A dimension role is a current inference for reusable low-cardinality values, including some numeric columns. A temporal-gap warning is also current, and only when a datetime column supports a regular cadence. Oribi does not flag individual outlier rows.

Oribi withholds temporal-gap warnings when consecutive observations tie more often than they match the inferred cadence. A verified time-and-entity grain with one record per entity at every observed timestamp can account for those ties. For such panels, warnings describe gaps shared by all entities. Confirm the sampling schedule before treating an inferred gap as missing data.

A role, key, relationship, or grain estimate is an inference, not a guarantee about business meaning. Oribi includes evidence so an analyst or downstream system can judge how much to trust each result.

Measure names ending in balance or balances, including accountBalance, receive snapshot-specific aggregation cautions rather than an unconditional total. Balances can be summed across entities at a common as-of time, but successive snapshots should not be summed across time. This is a name-based hint; confirm the meaning and entity grain. Additive transaction amounts such as deposit_amount and balance_change retain ordinary SUM guidance.

Columns named as geographic coordinates (latitude, longitude, lat, lon, lng, or a compound name ending in one of these) receive no additive total and no negative-value caution, because signed coordinates are expected positions rather than refunds or adjustments. Averages are qualified as rough component-wise centroids that are unreliable across the antimeridian. This is also a name-based hint; confirm the meaning and entity grain. Ordinary additive measures keep their totals and negative-value cautions.

Columns whose names end in temperature, optionally followed by a unit (for example air_temperature, temperature_f, or Temperature(°C)), receive no additive total and no negative-value caution, because summed readings are not a meaningful temperature and readings below zero are expected. Mean, median, and range guidance still applies. Abbreviations such as temp are ambiguous and are not matched. Confirm the meaning, since this is also a name-based hint.

Declare limits on measure additivity

Names beginning or ending with cumulative or running_total can trigger a caution when the data corroborates the hint. Oribi checks for one time axis with at least three distinct timestamps. For repeated timestamps, it requires a verified entity and timestamp key and one reading per entity at every timestamp. All readings must be finite, vary within each series, and never decrease in timestamp order. Oribi withholds inferred totals for matching columns and advises checking the intervals and resets. Explicit source declarations take precedence.

When a source documents what each value represents, set frame.attrs["oribi_measure_additivity"] before calling inspect(). For example:

frame.attrs["oribi_measure_additivity"] = {
    "meter_reading": "cumulative",
    "available_stock": "snapshot",
    "reported_index": "non_additive",
    "unmapped_measure": "unknown",
}

Oribi withholds inferred totals from these measures. Cumulative readings already include earlier activity, so check intervals and resets before calculating changes. Snapshots can be summed across distinct entities at a common as-of time after checking their grain. For unknown, confirm the measure's meaning and valid aggregation dimensions before using SUM or MEAN. Declarations qualify aggregation guidance without changing the column role. Existing SUM prohibitions and validated group-summary guidance still apply.

When each row already summarizes a group

For numeric columns such as mean_income, housing_median_age, or latency_p95, inspect() records the likely statistic in column.semantic.evidence and withholds additive totals. The average of district means gives each district equal weight. A median of district medians describes a typical district. Recovering a population median or percentile generally requires the underlying observations or their distributions.

To request a pooled mean when the source establishes the population and units, attach its metadata before calling inspect(). In this example, each household contributes one income observation to exactly one district.

districts = pd.DataFrame({
    "district": ["A", "B", "C"],
    "household_count": [10, 100, 1000],
    "mean_income": [10.5, 20.5, 100.5],
})
districts.attrs["oribi_summary_statistics"] = {
    "mean_income": {
        "statistic": "mean",
        "comparable": True,
        "partition_by": "district",
        "count": "household_count",
    }
}
income = inspect(districts).get_column("mean_income")
weighted = next(r for r in income.recommendations if r.operation == "WEIGHTED MEAN")

comparable=True declares that every row uses the same measure definition and units. partition_by names the column or list of columns that identify groups the source declares disjoint. For example, use ["district", "age_band"] for one row per district and age band. Composite partitions must fit max_key_columns and max_exact_rows. count names the denominator actually used for each arithmetic mean. Oribi checks for one row per complete group key, finite means, and complete positive whole counts. With those inputs, sum(mean × count) / sum(count) gives 92.48 across households in the example above. The simple average across the three districts is 43.83. Rounding the source means limits the precision of the pooled result. Distinct district labels and a nearby count column alone leave pooling unresolved.

If oribi_measure_additivity restricts the contributing count, Oribi withholds the pooled mean. A cumulative count or snapshot cannot establish how many observations contributed to each group mean without further information.

Supported statistic values are mean, median, percentile, min, and max. Comparable group minima and maxima with complete finite values support the matching bound across the represented groups, even when populations overlap. For unfamiliar numeric column names, the same metadata can identify the statistic. The source supplies the population definitions and units.

Declare relationships between counts

When source documentation establishes how two counts relate, add a declaration before calling inspect(). For example, each row below describes a different housing area, and the room and household counts cover the same area.

housing = pd.DataFrame({
    "area_id": [1, 2, 3],
    "total_rooms": [2.0, 30.0, 0.0],
    "households": [1.0, 10.0, 0.0],
})
housing.attrs["oribi_measure_pairs"] = [{
    "kind": "count_ratio",
    "numerator": "total_rooms",
    "denominator": "households",
    "numerator_unit": "rooms",
    "denominator_unit": "household",
    "comparable": True,
    "partition_by": "area_id",
}]
context = inspect(housing)

comparable=True declares consistent count definitions and a common population for the two counts on each row. partition_by identifies disjoint observations and can be a column name or a list of names for a composite grain. Oribi checks for complete, unique keys and complete nonnegative whole counts. Source metadata establishes comparability and non-overlap. Uniqueness and correlation alone cannot establish either.

  • part_to_whole reports a directional relationship when the units match, each part is at most its whole, and at least one part is smaller.
  • count_ratio requires two additive counts. It produces a ratio of totals, 32 / 11 rooms per household in this example. Zero denominators are valid on rows where both counts are zero. An entirely zero denominator, a positive numerator with a zero denominator, missing counts, or evidence of a coarser measure grain causes Oribi to omit the declared ratio. Generated SQL also guards a zero denominator total with NULLIF.

Declarations use the profile's exact row and key-width limits and the remaining relationship budget. Oribi requires at least two rows and skips all declarations if the list exceeds the remaining budget or half of max_relationship_columns. This keeps a later conflicting declaration from being ignored. Ratios attach their units and verified grain as evidence.

Choose an output format

A DatasetContext can be rendered for different uses:

# Short overview
print(context.summary())

# Full report for people
markdown = context.to_markdown()

# Structured data for an application
payload = context.to_dict()
json_text = context.to_json()

# Compact context for an AI prompt
prompt_context = context.to_context(max_chars=8_000)

summary() is that short overview and accepts no options. to_markdown(), to_dict(), to_json(), and to_context() render the same computed profile. Those serializers do not re-read the DataFrame or run new inferences.

Data handling

Oribi profiles the DataFrame in memory and does not keep a reference to it in the returned context. The in-memory DatasetContext retains local top_values and exact bounds for inspection.

Top values are ranked by frequency using pandas equality and counts. Ties use a stable value order for supported types, including strings, built-in numbers, and common date and time values. Tied opaque objects without a stable value key follow pandas count order, so reordering rows or categories can change which of them appears at the cutoff. Profiling does not call their repr() to rank them.

to_dict, to_json, to_markdown, and to_context accept include_values. summary() does not. With the default include_values=False, those four exports omit sampled cell values and exact bounds. Dictionary and JSON exports still keep top_frequencies (the counts, without the sampled values) and omit strings in evidence details. They also omit means, medians, standard deviations, skewness, and quantiles when fewer than three non-missing values were observed. This includes standard deviations repeated in semantic and recommendation evidence; the statement that values vary remains available.

You can explicitly include local values and bounds when exporting:

json_text = context.to_json(include_values=True)

to_dict, to_markdown, and to_context accept the same include_values option. summary() takes no arguments and never includes sampled values. Treat opt-in output as containing raw data details. Column and index names and aggregates can disclose information, so review context before sharing it, especially when the source is sensitive.

Opt-in text reports quote string category labels to distinguish them from numeric values. Compact reports include category lists only when space remains after analytical guidance, evidence, and numeric semantic type details.

Since Oribi 0.2.0, dictionary and JSON exports use schema_version: "2". Update consumers that expect schema version 1 or depend on the previous Markdown or compact text layout. Use include_values=True when callers need local samples and bounds in version 2.

Oribi 0.3.0 adds metric definitions and profiling fields to schema version 2. Opt-in dictionary and JSON exports raise ValueError if two sampled mapping keys would serialize to the same key.

Configure a profile

Use ProfileOptions to control parts of the analysis:

import pandas as pd
from oribi import ProfileOptions, inspect

df = pd.DataFrame({"amount": [12.5, 18.0, 20.0]})

context = inspect(
    df,
    options=ProfileOptions(
        top_k=5,
        max_exact_rows=50_000,
    ),
)

Options include top_k, include_quantiles, max_exact_rows, max_key_columns, max_relationships, max_relationship_columns, max_gap_examples, and max_gap_warnings.

max_exact_rows is an inclusive row-count limit on numeric quantiles, composite-key pair scans, and observed relationship scans. At or below the limit, each calculation also depends on its own options and on eligible input. Above the limit, quantiles are omitted, composite-key pairs are skipped, and the observed relationship collection is empty. Single-column observations, cardinalities, and semantic inference still run.

Check context.profile.exact_row_limit_exceeded (also present in dictionary and JSON exports) to identify when the row limit skipped those calculations. A false value means the row limit did not skip them. Individual options and eligibility can still produce empty results. When the grain remains undetermined above the limit, its evidence reports key_search_bounded.

How to interpret the results

Oribi uses deterministic heuristics based on observed values, data types, and supporting evidence. Column names can contribute to role inference, but they cannot establish a relationship by themselves.

  • A candidate key with verified_unique=True has no observed collisions or null components. Approximate candidates can have collisions or missing values. For composite candidates, distinct pairs and collisions count only rows with both components present; uniqueness is the number of distinct complete pairs divided by all rows. A verified candidate still needs domain validation before it can be used as a business key.
  • A likely grain describes a pattern in the observed rows. It can remain undetermined when the evidence is weak or ambiguous.
  • Grain evidence can report an unverified named identifier with separate duplicate and missing counts, even below the usual candidate-key uniqueness cutoff. A verified pair of repeating fields can establish a more meaningful grain than a weak unique field. If a named identifier is mostly distinct and no supported pair resolves it, an incidental unique field can leave grain undetermined. Repeating an entity label can be normal in transaction or event data.
  • Oribi treats an index-like name such as Unnamed: 0, index, or row_id and a complete zero- or one-based integer range as evidence of row numbering. The column remains a verified candidate key. Grain stays undetermined unless other columns provide independent evidence. A sequential business identifier such as order_id can still establish grain.
  • Composite keys containing an independently unique native timestamp remain available as diagnostics, but do not displace that timestamp as the grain. Verified identifiers retain priority, and multiple independent unique timestamps can leave the grain ambiguous.
  • A relationship within one DataFrame does not prove that a join to another table is valid or safe.
  • An exact functional dependency points from the determining column to the dependent column. Its mapping_cardinality distinguishes many-to-one from one-to-one. One-to-many links point from group to entity and require a verified entity key. Mapping coverage is the fraction of observed determinant values with exactly one partner. For one-to-many links the entity is the determinant, so coverage is measured from the target back to the source. Missing pairs or conflicting partners cannot establish an exact dependency.
  • Confidence scores describe heuristic strength. They are not calibrated probabilities. Directional mapping repetition and generalization support count complete source-target pairs before deduplication; rows missing either value do not add support. Mapping coverage still uses all observed determinant values, and paired/missing row counts remain available separately.
  • Row-level measure ratios are withheld when their measures have no jointly observed rows; standalone totals remain available. Positive paired counts appear in metric evidence without changing the aggregate SQL to filter individual rows. Pair checks use the metric-grain scan's row and additive-column limits. An unchecked pair gets an explicit caveat rather than a zero count. Ratios deduplicated at an entity grain retain their grain-specific interpretation.
  • Inferred per-entity averages for integer measures promote each input with 1.0 * before SUM() (SUM(1.0 * ...)) so engines with 64-bit integer accumulators such as SQLite do not overflow when an intermediate sum exceeds signed 64-bit bounds. On engines that evaluate 1.0 * integer in IEEE-754 float64 (such as SQLite), conversion and running sums are exact up to 2**53, while values or intermediate partial sums reaching 2**53 (for example [2**62 + 1, -(2**62)] or below-2**53 inputs whose running sum crosses 2**53 on SQLite < 3.43) can lose low-order residual precision when opposite-sign values nearly cancel and produce an explicit metric caveat. Engines that evaluate 1.0 * integer as exact DECIMAL/NUMERIC (such as PostgreSQL, DuckDB, MySQL, Snowflake, and SQL Server) preserve exact integer summation, subject to each dialect's division precision/scale rules (for example, SQL Server's SUM(numeric) returns decimal(38, s), yielding decimal(38, 6) after division). Standalone SUM() totals and Decimal measures retain their existing SQL.

Use the profile as evidence for further analysis, and check whether each inference fits the dataset's actual domain. For a runnable Python example that inspects context.candidate_keys (columns and verified_unique) alongside context.grain, see examples/quickstart.py (python -m examples.quickstart).

Current scope and limitations

Oribi currently works with in memory pandas DataFrames. It does not connect to databases or remote data sources, and it does not include an AI provider integration. You choose where the generated context goes.

  • Python 3.10–3.14 and pandas 1.5.3 or newer, below pandas 4. Use NumPy 1.x with pandas 1.5.3.
  • Column labels must be unique strings.
  • Consistent ISO calendar dates or timestamps in text and Python date or datetime objects can support a temporal role. Text requires at least two distinct non-missing values, and every distinct string must be valid. Oribi preserves the stored dtype and values. Convert the column to a pandas datetime dtype to use it for datetime bounds, gap checks, or structural inference.
  • Object logical-type detection checks all observed values, including values after the first 100 rows. This check still runs above max_exact_rows.
  • Native complex valued columns are unsupported and raise InvalidInputError.
  • Profiling may require several full column scans. Exact composite key and relationship checks are bounded by configured row and column limits.
  • If pandas cannot compare cell values, the duplicate-row count is omitted and Oribi records a duplicate_check_unavailable warning.

Resetting indexes with colliding or repeated names

Oribi profiles non-default DataFrame index metadata separately in context.profile.index (and summarizes it in Markdown and compact context reports) rather than treating index levels as columns. Index levels only participate in column profiling, semantic roles, candidate keys, and relationships after you explicitly move them into columns.

Both text reports suggest using the DataFrame index or calling reset_index(). A bare df.reset_index() raises ValueError when an index level shares a name with an existing column or repeats a level name in a MultiIndex. Pass names=... (supported across Oribi's pandas>=1.5.3,<4 range) with one unique string label per index level to move the index into columns while preserving both the index values and existing columns:

import pandas as pd
from oribi import inspect

# Single index whose name collides with an existing column
df = pd.DataFrame({"batch": [1, 2]}, index=pd.Index([10, 20], name="batch"))
print(inspect(df).profile.index.names)  # ('batch',)

# df.reset_index() raises ValueError: cannot insert batch, already exists
reset_df = df.reset_index(names=["batch_index"])
print(reset_df.columns.tolist())  # ['batch_index', 'batch']
print(reset_df.to_dict(orient="list"))  # {'batch_index': [10, 20], 'batch': [1, 2]}
context = inspect(reset_df)

# Repeated-name MultiIndex (and an existing column with the same name):
# supply one unique output name per index level
multi_df = pd.DataFrame(
    {"group": [100, 200]},
    index=pd.MultiIndex.from_tuples([("a", "x"), ("b", "y")], names=["group", "group"]),
)
reset_multi = multi_df.reset_index(names=["group_outer", "group_inner"])
print(reset_multi.columns.tolist())  # ['group_outer', 'group_inner', 'group']
multi_context = inspect(reset_multi)

Development

Clone the repository and install the development dependencies:

git clone https://github.com/samhoon000/Oribi.git
cd Oribi

python -m venv .venv

# macOS / Linux
source .venv/bin/activate

# Windows PowerShell
# .venv\Scripts\Activate.ps1

python -m pip install -e ".[dev]"
pytest
ruff check .
mypy oribi

See CONTRIBUTING.md for the contribution workflow and DESIGN.md for architecture notes. To run the end-to-end profiling example:

python -m examples.quickstart

For a small profile-to-visualization workflow, install Matplotlib with python -m pip install matplotlib, then run:

python -m examples.visualize_profiled_data

Releases

The package version is defined in project.version in pyproject.toml. Releases use GitHub tags matching v<version>. The release workflow runs the test matrix, builds and validates the wheel and source distribution, then publishes those artifacts to PyPI through GitHub Actions Trusted Publishing.

See CONTRIBUTING.md for release steps and repository setup.

Roadmap

These items are not implemented. They are not part of the current profiling, reasoning, or serialization behavior.

  • Outlier or anomaly detection. A high-skew warning on a likely measure says the mean may be sensitive to large values. It does not flag individual outlier rows.
  • Automatic parsing of datetime-like text.
  • Connections to databases or other remote data sources.
  • An AI provider integration.
  • User-configurable semantic rules.
  • Cross-table foreign-key analysis. Relationships stay inside one DataFrame.
  • Profiling options beyond the ProfileOptions fields documented above.

The current release is the in-memory pandas profile in What Oribi reports, including dimension roles and temporal-gap warnings for regular datetime series.

License

MIT. See LICENSE.

About

Python library for generating AI-ready data context without sharing raw data.

Topics

Resources

Contributing

Stars

24 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages