Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 20 additions & 11 deletions compass/utilities/finalize.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,25 +324,34 @@ def _normalize_qualitative_rows(db):
they share a single output file and the ``quantitative`` flag is
not published.

Their ``summary`` is also copied into ``value`` where the value is
empty. The schemas ask the LLM for a summary and a null value on
most of these rows, so filling the value here means the model only
ever writes the requirement once, while readers still find it in
the column they expect. A value the model did supply (such as the
verbatim text of a definition) is kept.
For qualitative rows, blank strings in ``value`` (including
whitespace-only) are cleared to null. If ``value`` is then null
and ``summary`` is not blank, ``summary`` is copied into ``value``.
The schemas ask the LLM for a summary and a null value on most of
these rows, so filling the value here means the model only ever
writes the requirement once, while readers still find it in the
column they expect. A value the model did supply (such as a list
of entities or the verbatim text of a definition) is kept as-is.
"""
qualitative = ~db["quantitative"]
db.loc[qualitative, "units"] = QUALITATIVE_UNITS

# a numeric-only "value" column is float-typed, so it has to be
# widened before qualitative text can be written into it
db["value"] = db["value"].astype(object)
empty = db["value"].isna() | ~db["value"].astype(str).str.strip().astype(
bool
empty_value = db["value"].isna() | db["value"].map(
lambda v: isinstance(v, str) and not v.strip()
)
db.loc[qualitative & empty, "value"] = db.loc[
qualitative & empty, "summary"
]
db.loc[empty_value, "value"] = None

# Check summary without modifying it; convert to object to handle
# both numeric NaN and string blanks uniformly
summary_obj = db["summary"].astype(object)
empty_summary = summary_obj.isna() | summary_obj.map(
lambda v: isinstance(v, str) and not v.strip()
)
fill = qualitative & db["value"].isna() & ~empty_summary
db.loc[fill, "value"] = db.loc[fill, "summary"]
return db


Expand Down
151 changes: 151 additions & 0 deletions tests/python/unit/utilities/test_utilities_finalize.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from pathlib import Path
from types import SimpleNamespace

import numpy as np
import pandas as pd
import pytest

Expand Down Expand Up @@ -661,6 +662,156 @@ def _row(feature, quantitative, value, summary):
assert out["summary"].notna().all()


def test_save_db_keeps_llm_value_for_qualitative(tmp_path):
"""Keep a non-null LLM value on qualitative rows"""

out_cols = [col.name for col in COMPASSWindExtractor.OUTPUT_COLUMNS]

def _row(feature, value, summary):
row = dict.fromkeys([*out_cols, "quantitative"])
row.update(
{
"feature": feature,
"quantitative": False,
"value": value,
"summary": summary,
"ordinance_text": "quoted text",
}
)
return row

grantees = ["Dixie Electric Membership Corporation", "Louisiana P&L"]
df = pd.DataFrame(
[
_row("Franchise", grantees, "Electric franchises granted."),
_row("Signage", None, "Warning signs only."),
]
)
finalize.save_db(df, tmp_path, COMPASSWindExtractor.OUTPUT_COLUMNS)

out = pd.read_csv(tmp_path / "ordinances.csv").set_index("feature")

assert out.loc["Franchise", "value"] == str(grantees)
assert out.loc["Franchise", "summary"] == "Electric franchises granted."
assert out.loc["Signage", "value"] == "Warning signs only."


def test_save_db_handles_blank_string_values(tmp_path):
"""Blank strings in value are converted to empty; only filled if
summary is not blank"""

out_cols = [col.name for col in COMPASSWindExtractor.OUTPUT_COLUMNS]

def _row(feature, value, summary, quantitative=False):
row = dict.fromkeys([*out_cols, "quantitative"])
row.update(
{
"feature": feature,
"quantitative": quantitative,
"value": value,
"summary": summary,
"ordinance_text": "quoted text",
}
)
return row

df = pd.DataFrame(
[
_row("Both blank qual", " ", " "),
_row("Value blank, summary filled qual", "", "Real content"),
_row("Value filled, summary blank qual", "Real value", " "),
_row("Both blank quant", " ", " ", quantitative=True),
]
)
finalize.save_db(df, tmp_path, COMPASSWindExtractor.OUTPUT_COLUMNS)

out = pd.read_csv(tmp_path / "ordinances.csv").set_index("feature")

assert pd.isna(out.loc["Both blank qual", "value"])
assert out.loc["Value blank, summary filled qual", "value"] == "Real content"
assert out.loc["Value filled, summary blank qual", "value"] == "Real value"
assert pd.isna(out.loc["Both blank quant", "value"])


def test_save_db_blank_handling_edge_cases(tmp_path):
"""Whitespace and special values are handled correctly"""

out_cols = [col.name for col in COMPASSWindExtractor.OUTPUT_COLUMNS]

def _row(feature, value, summary):
row = dict.fromkeys([*out_cols, "quantitative"])
row.update(
{
"feature": feature,
"quantitative": False,
"value": value,
"summary": summary,
"ordinance_text": "quoted text",
}
)
return row

df = pd.DataFrame(
[
_row("Tab only", "\t", "Tab summary"),
_row("Newline only", "\n", "Newline summary"),
_row("Mixed whitespace", " \t\n ", "Mixed summary"),
_row("Zero value", 0, "Zero summary"),
_row("False value", False, "False summary"),
_row("Empty list", [], "List summary"),
]
)
finalize.save_db(df, tmp_path, COMPASSWindExtractor.OUTPUT_COLUMNS)

out = pd.read_csv(tmp_path / "ordinances.csv").set_index("feature")

# Whitespace-only values are filled from summary
assert out.loc["Tab only", "value"] == "Tab summary"
assert out.loc["Newline only", "value"] == "Newline summary"
assert out.loc["Mixed whitespace", "value"] == "Mixed summary"
# Falsy non-string values are kept
assert out.loc["Zero value", "value"] == "0"
assert out.loc["False value", "value"] == "False"
assert out.loc["Empty list", "value"] == "[]"


def test_save_db_does_not_copy_numeric_summary(tmp_path):
"""Non-string values in summary are treated as not-blank and are
copied to value when value is empty"""

out_cols = [col.name for col in COMPASSWindExtractor.OUTPUT_COLUMNS]

def _row(feature, value, summary):
row = dict.fromkeys([*out_cols, "quantitative"])
row.update(
{
"feature": feature,
"quantitative": False,
"value": value,
"summary": summary,
"ordinance_text": "quoted text",
}
)
return row

df = pd.DataFrame(
[
_row("Zero summary", None, 0),
_row("False summary", None, False),
_row("NaN summary", None, np.nan),
]
)
finalize.save_db(df, tmp_path, COMPASSWindExtractor.OUTPUT_COLUMNS)

out = pd.read_csv(tmp_path / "ordinances.csv").set_index("feature")

# Numeric/non-string summaries are copied (they're not "blank")
assert out.loc["Zero summary", "value"] == "0"
assert out.loc["False summary", "value"] == "False"
# Only actual NaN in summary results in no fill
assert pd.isna(out.loc["NaN summary", "value"])


def test_save_db_trims_long_ordinance_text(tmp_path):
"""Trim over-long excerpts on the way out to disk"""

Expand Down
Loading