Re-upload current cxr_auditor package with salvage parsing (robustness fix)
Browse files- cxr_auditor/inference.py +368 -54
- cxr_auditor/parser.py +1 -1
- cxr_auditor/render.py +131 -20
- cxr_auditor/schema.py +119 -48
cxr_auditor/inference.py
CHANGED
|
@@ -18,9 +18,18 @@ the grounding turn). That same ``generate_fn`` shape is exactly what
|
|
| 18 |
its documented injected-callable contract rather than re-implemented here, and the
|
| 19 |
whole orchestration is testable with a fake ``generate_fn`` and no model.
|
| 20 |
|
| 21 |
-
A retry-on-invalid-JSON
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
The heavy stack (torch, transformers) is imported lazily via ``importlib`` inside
|
| 26 |
``load_model`` and ``_generate_text`` so importing this module on a pure-logic
|
|
@@ -41,6 +50,8 @@ safe to call from a GPU worker.
|
|
| 41 |
from __future__ import annotations
|
| 42 |
|
| 43 |
import importlib
|
|
|
|
|
|
|
| 44 |
from collections.abc import Callable
|
| 45 |
from dataclasses import dataclass
|
| 46 |
from typing import TYPE_CHECKING, Any
|
|
@@ -75,6 +86,99 @@ DEFAULT_MAX_NEW_TOKENS: int = 512
|
|
| 75 |
# this many additional re-generations.
|
| 76 |
DEFAULT_MAX_RETRIES: int = 2
|
| 77 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
@dataclass(frozen=True, slots=True)
|
| 80 |
class AuditOutcome:
|
|
@@ -89,10 +193,14 @@ class AuditOutcome:
|
|
| 89 |
result: The canonical ``AuditResult`` (image findings, draft findings,
|
| 90 |
label-only audit, disclaimer, box format).
|
| 91 |
comparison: The per-item comparator detail (boxes, urgency, draft spans).
|
|
|
|
|
|
|
|
|
|
| 92 |
"""
|
| 93 |
|
| 94 |
result: AuditResult
|
| 95 |
comparison: ComparisonReport
|
|
|
|
| 96 |
|
| 97 |
|
| 98 |
def grounded_dicts_to_image_findings(grounded: list[dict[str, Any]]) -> list[ImageFinding]:
|
|
@@ -186,29 +294,34 @@ def _coerce_confidence(raw: Any) -> float | None:
|
|
| 186 |
|
| 187 |
|
| 188 |
def run_with_retry(
|
| 189 |
-
|
| 190 |
prompt: str,
|
| 191 |
parse_fn: Callable[[str], list[Any]],
|
| 192 |
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
|
|
|
|
|
| 193 |
) -> list[Any]:
|
| 194 |
-
"""Generate then parse,
|
| 195 |
|
| 196 |
The model occasionally emits prose, a truncated array, or otherwise
|
| 197 |
-
unparseable text
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
``
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
|
| 206 |
Args:
|
| 207 |
-
|
| 208 |
-
|
|
|
|
|
|
|
| 209 |
parse_fn: A tolerant parser turning raw text into a list (raises
|
| 210 |
``SchemaParseError`` on unparseable text).
|
| 211 |
max_retries: Number of additional attempts after the first. Must be >= 0.
|
|
|
|
| 212 |
|
| 213 |
Returns:
|
| 214 |
The first successfully parsed list.
|
|
@@ -221,42 +334,75 @@ def run_with_retry(
|
|
| 221 |
raise ValueError(f"max_retries must be non-negative, got {max_retries}")
|
| 222 |
|
| 223 |
last_error: SchemaParseError | None = None
|
| 224 |
-
for
|
| 225 |
-
|
|
|
|
|
|
|
|
|
|
| 226 |
try:
|
| 227 |
return parse_fn(raw_text)
|
| 228 |
except SchemaParseError as exc:
|
| 229 |
last_error = exc
|
|
|
|
| 230 |
assert last_error is not None # loop runs at least once, so an error was set
|
| 231 |
raise last_error
|
| 232 |
|
| 233 |
|
| 234 |
-
def make_generate_fn(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
"""Build an image-bound ``generate_fn`` over a loaded model and processor.
|
| 236 |
|
| 237 |
-
The returned closure captures the model, processor,
|
| 238 |
-
text-in/text-out ``GenerateFn`` shape that the
|
| 239 |
-
and ``cxr_auditor.parser.parse_draft`` all
|
| 240 |
-
|
| 241 |
-
``generate_fn`` - reuse the same single-turn
|
| 242 |
-
|
| 243 |
-
model.
|
| 244 |
|
| 245 |
Args:
|
| 246 |
model: A loaded vision-language model exposing ``generate``.
|
| 247 |
processor: The matching transformers processor.
|
| 248 |
image: The chest X-ray bound to every generation through this closure.
|
|
|
|
|
|
|
| 249 |
|
| 250 |
Returns:
|
| 251 |
A ``GenerateFn`` mapping a rendered prompt to the model's raw completion.
|
| 252 |
"""
|
| 253 |
|
| 254 |
def _generate(prompt: str) -> str:
|
| 255 |
-
return _generate_text(model, processor, prompt, image)
|
| 256 |
|
| 257 |
return _generate
|
| 258 |
|
| 259 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
def generate_findings(
|
| 261 |
image: Image.Image,
|
| 262 |
*,
|
|
@@ -266,8 +412,8 @@ def generate_findings(
|
|
| 266 |
) -> list[ImageFinding]:
|
| 267 |
"""Ground an image into validated ``ImageFinding`` objects.
|
| 268 |
|
| 269 |
-
Builds the pinned image-grounding prompt, generates through the
|
| 270 |
-
retry
|
| 271 |
point the app uses when it wants only the grounded findings (for example to
|
| 272 |
draw boxes before a draft is supplied).
|
| 273 |
|
|
@@ -275,7 +421,7 @@ def generate_findings(
|
|
| 275 |
image: The chest X-ray as a PIL image.
|
| 276 |
model: A loaded vision-language model (keyword-only).
|
| 277 |
processor: The matching transformers processor (keyword-only).
|
| 278 |
-
max_retries: Retry budget for the invalid-JSON
|
| 279 |
|
| 280 |
Returns:
|
| 281 |
The image-grounded findings with bounding-box evidence.
|
|
@@ -283,8 +429,13 @@ def generate_findings(
|
|
| 283 |
Raises:
|
| 284 |
SchemaParseError: If grounding output cannot be parsed after all retries.
|
| 285 |
"""
|
| 286 |
-
|
| 287 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 288 |
return grounded_dicts_to_image_findings(grounded)
|
| 289 |
|
| 290 |
|
|
@@ -300,10 +451,13 @@ def run_audit(
|
|
| 300 |
|
| 301 |
Steps:
|
| 302 |
1. Ground the image into validated ``ImageFinding`` objects
|
| 303 |
-
(``generate_findings``), through the
|
| 304 |
2. If a non-blank draft is supplied, parse it into the same label space via
|
| 305 |
``cxr_auditor.parser.parse_draft``, driven by an image-bound
|
| 306 |
-
``generate_fn``
|
|
|
|
|
|
|
|
|
|
| 307 |
3. Run the deterministic comparator (``cxr_auditor.comparator.compare``) and
|
| 308 |
bundle everything into an ``AuditOutcome``.
|
| 309 |
|
|
@@ -318,15 +472,17 @@ def run_audit(
|
|
| 318 |
image-side findings (and urgent flags).
|
| 319 |
model: A loaded vision-language model exposing ``generate`` (keyword-only).
|
| 320 |
processor: The matching transformers processor (keyword-only).
|
| 321 |
-
max_retries: Retry budget for
|
|
|
|
|
|
|
| 322 |
|
| 323 |
Returns:
|
| 324 |
-
An ``AuditOutcome`` carrying the canonical ``AuditResult``
|
| 325 |
-
``ComparisonReport``.
|
| 326 |
|
| 327 |
Raises:
|
| 328 |
ValueError: If ``model`` or ``processor`` is not supplied.
|
| 329 |
-
SchemaParseError: If the
|
| 330 |
finding list after all retries.
|
| 331 |
"""
|
| 332 |
if model is None or processor is None:
|
|
@@ -335,10 +491,16 @@ def run_audit(
|
|
| 335 |
image_findings = generate_findings(image, model=model, processor=processor, max_retries=max_retries)
|
| 336 |
|
| 337 |
draft_findings: list[DraftFinding] = []
|
|
|
|
| 338 |
cleaned_draft = (draft_text or "").strip()
|
| 339 |
if cleaned_draft:
|
| 340 |
-
|
| 341 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 342 |
|
| 343 |
comparison = compare(image_findings, draft_findings)
|
| 344 |
result = AuditResult(
|
|
@@ -346,24 +508,46 @@ def run_audit(
|
|
| 346 |
draft_findings=draft_findings,
|
| 347 |
audit=comparison.audit,
|
| 348 |
)
|
| 349 |
-
return AuditOutcome(result=result, comparison=comparison)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 350 |
|
| 351 |
|
| 352 |
def _parse_draft_with_retry(
|
| 353 |
draft_text: str,
|
| 354 |
-
|
| 355 |
-
max_retries: int =
|
| 356 |
) -> list[DraftFinding]:
|
| 357 |
-
"""Parse a draft through ``parser.parse_draft`` with
|
| 358 |
|
| 359 |
-
Wraps the draft parser's injected-callable contract in the same
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
|
|
|
| 363 |
|
| 364 |
Args:
|
| 365 |
draft_text: The non-empty draft impression to parse.
|
| 366 |
-
|
|
|
|
| 367 |
max_retries: Number of additional attempts after the first. Must be >= 0.
|
| 368 |
|
| 369 |
Returns:
|
|
@@ -377,11 +561,16 @@ def _parse_draft_with_retry(
|
|
| 377 |
raise ValueError(f"max_retries must be non-negative, got {max_retries}")
|
| 378 |
|
| 379 |
last_error: SchemaParseError | None = None
|
| 380 |
-
for
|
|
|
|
|
|
|
|
|
|
|
|
|
| 381 |
try:
|
| 382 |
return parse_draft(draft_text, generate_fn)
|
| 383 |
except SchemaParseError as exc:
|
| 384 |
last_error = exc
|
|
|
|
| 385 |
assert last_error is not None
|
| 386 |
raise last_error
|
| 387 |
|
|
@@ -451,15 +640,23 @@ def load_model(model_id: str = DEFAULT_MODEL_ID) -> tuple[Any, Any]:
|
|
| 451 |
return model, processor
|
| 452 |
|
| 453 |
|
| 454 |
-
def _generate_text(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 455 |
"""Run one single-turn multimodal generation and return the decoded reply.
|
| 456 |
|
| 457 |
This is the only function that touches the model at inference time, and the
|
| 458 |
single seam tests patch to drive the orchestration without a real model. It
|
| 459 |
builds a single-turn chat message with the image and the prompt text, applies
|
| 460 |
-
the processor's chat template, generates
|
| 461 |
-
generated tokens (slicing off the prompt) so the
|
| 462 |
-
model's reply (a plain ``str``, never a tensor
|
|
|
|
|
|
|
| 463 |
|
| 464 |
Heavy imports are local to keep module import free of the vision stack. The
|
| 465 |
chat-message construction follows the transformers image-text-to-text
|
|
@@ -471,6 +668,7 @@ def _generate_text(model: Any, processor: Any, prompt: str, image: Image.Image)
|
|
| 471 |
processor: The matching processor.
|
| 472 |
prompt: The fully rendered text prompt.
|
| 473 |
image: The chest X-ray as a PIL image.
|
|
|
|
| 474 |
|
| 475 |
Returns:
|
| 476 |
The model's decoded reply text (prompt tokens stripped).
|
|
@@ -494,19 +692,135 @@ def _generate_text(model: Any, processor: Any, prompt: str, image: Image.Image)
|
|
| 494 |
return_tensors="pt",
|
| 495 |
).to(model.device)
|
| 496 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 497 |
input_len = inputs["input_ids"].shape[-1]
|
| 498 |
with torch.inference_mode():
|
| 499 |
-
generated = model.generate(**inputs,
|
| 500 |
new_tokens = generated[0][input_len:]
|
| 501 |
return processor.decode(new_tokens, skip_special_tokens=True)
|
| 502 |
|
| 503 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 504 |
__all__ = [
|
| 505 |
"DEFAULT_MAX_NEW_TOKENS",
|
| 506 |
"DEFAULT_MAX_RETRIES",
|
| 507 |
"DEFAULT_MODEL_ID",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 508 |
"AuditOutcome",
|
|
|
|
|
|
|
| 509 |
"audit",
|
|
|
|
| 510 |
"generate_findings",
|
| 511 |
"grounded_dicts_to_image_findings",
|
| 512 |
"load_model",
|
|
|
|
| 18 |
its documented injected-callable contract rather than re-implemented here, and the
|
| 19 |
whole orchestration is testable with a fake ``generate_fn`` and no model.
|
| 20 |
|
| 21 |
+
A retry-on-invalid-JSON ladder (``run_with_retry``) wraps each generation. Each
|
| 22 |
+
attempt changes the conditions so a deterministic failure mode cannot simply
|
| 23 |
+
repeat: attempt one decodes greedily with the base prompt, attempt two appends a
|
| 24 |
+
corrective instruction (``RETRY_CORRECTIVE_SUFFIX``), and attempt three switches
|
| 25 |
+
to sampling (``RETRY_SAMPLING_SETTINGS``). Every parse failure is logged to
|
| 26 |
+
stdout with its full traceback and the offending raw model text, and the final
|
| 27 |
+
``SchemaParseError`` carries the last raw text for inspection. Draft parsing
|
| 28 |
+
degrades gracefully: when the draft cannot be parsed after its retries, the audit
|
| 29 |
+
proceeds image-only and records ``AuditOutcome.draft_parse_note`` so the user
|
| 30 |
+
interface can say so prominently. ``categorize_serving_error`` maps the
|
| 31 |
+
exceptions an audit call can surface (including the string-transported ZeroGPU
|
| 32 |
+
platform errors) to honest, user-facing messages.
|
| 33 |
|
| 34 |
The heavy stack (torch, transformers) is imported lazily via ``importlib`` inside
|
| 35 |
``load_model`` and ``_generate_text`` so importing this module on a pure-logic
|
|
|
|
| 50 |
from __future__ import annotations
|
| 51 |
|
| 52 |
import importlib
|
| 53 |
+
import sys
|
| 54 |
+
import traceback
|
| 55 |
from collections.abc import Callable
|
| 56 |
from dataclasses import dataclass
|
| 57 |
from typing import TYPE_CHECKING, Any
|
|
|
|
| 86 |
# this many additional re-generations.
|
| 87 |
DEFAULT_MAX_RETRIES: int = 2
|
| 88 |
|
| 89 |
+
# Draft-parsing retry budget: one initial attempt plus this many retries. Smaller
|
| 90 |
+
# than the grounding budget because draft parsing degrades gracefully (the audit
|
| 91 |
+
# proceeds image-only), and the combined worst case of grounding plus draft
|
| 92 |
+
# attempts must stay inside the GPU duration the serving app declares.
|
| 93 |
+
DRAFT_MAX_RETRIES: int = 1
|
| 94 |
+
|
| 95 |
+
# User-facing note recorded on the outcome when a supplied draft could not be
|
| 96 |
+
# parsed after all retries and the audit proceeded image-only.
|
| 97 |
+
DRAFT_PARSE_FAILURE_NOTE: str = "The draft text could not be parsed; results show image findings only."
|
| 98 |
+
|
| 99 |
+
# Corrective instruction appended to the prompt on retry attempts, so a retry
|
| 100 |
+
# never repeats the exact conditions that already failed deterministically.
|
| 101 |
+
RETRY_CORRECTIVE_SUFFIX: str = (
|
| 102 |
+
"\nIMPORTANT: your previous reply was not one valid JSON array. "
|
| 103 |
+
"Reply with ONE complete JSON array, starting with '[' and ending with ']'. "
|
| 104 |
+
"Do not repeat elements. No prose."
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
# Truncation bound for raw model text echoed into stdout logs on parse failures.
|
| 108 |
+
_RAW_TEXT_LOG_LIMIT: int = 2000
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
@dataclass(frozen=True, slots=True)
|
| 112 |
+
class GenerationSettings:
|
| 113 |
+
"""Decoding settings for one model generation.
|
| 114 |
+
|
| 115 |
+
Attributes:
|
| 116 |
+
do_sample: Whether to sample instead of decoding greedily.
|
| 117 |
+
temperature: Sampling temperature; only forwarded when ``do_sample``.
|
| 118 |
+
top_p: Nucleus-sampling probability mass; only forwarded when
|
| 119 |
+
``do_sample``.
|
| 120 |
+
"""
|
| 121 |
+
|
| 122 |
+
do_sample: bool = False
|
| 123 |
+
temperature: float | None = None
|
| 124 |
+
top_p: float | None = None
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
# Deterministic greedy decoding: the default for every first attempt.
|
| 128 |
+
GREEDY_SETTINGS: GenerationSettings = GenerationSettings()
|
| 129 |
+
|
| 130 |
+
# Mild sampling for the final retry attempt: enough randomness to escape a
|
| 131 |
+
# deterministic degenerate completion while keeping the constrained JSON shape
|
| 132 |
+
# likely.
|
| 133 |
+
RETRY_SAMPLING_SETTINGS: GenerationSettings = GenerationSettings(do_sample=True, temperature=0.4, top_p=0.9)
|
| 134 |
+
|
| 135 |
+
# A factory producing a ``GenerateFn`` bound to specific decoding settings. The
|
| 136 |
+
# retry ladder requests a fresh ``GenerateFn`` per attempt so attempt three can
|
| 137 |
+
# switch from greedy decoding to sampling.
|
| 138 |
+
type GenerateFnFactory = Callable[[GenerationSettings], GenerateFn]
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def _attempt_settings(attempt: int) -> tuple[GenerationSettings, bool]:
|
| 142 |
+
"""Return the decoding plan for a 1-based retry-ladder attempt.
|
| 143 |
+
|
| 144 |
+
Attempt 1 decodes greedily with the base prompt; attempt 2 keeps greedy
|
| 145 |
+
decoding but appends the corrective suffix; attempt 3 and beyond switch to
|
| 146 |
+
sampling (still with the suffix) so a deterministic failure cannot repeat
|
| 147 |
+
verbatim.
|
| 148 |
+
|
| 149 |
+
Args:
|
| 150 |
+
attempt: The 1-based attempt number.
|
| 151 |
+
|
| 152 |
+
Returns:
|
| 153 |
+
A ``(settings, append_corrective_suffix)`` pair.
|
| 154 |
+
"""
|
| 155 |
+
if attempt == 1:
|
| 156 |
+
return GREEDY_SETTINGS, False
|
| 157 |
+
if attempt == 2:
|
| 158 |
+
return GREEDY_SETTINGS, True
|
| 159 |
+
return RETRY_SAMPLING_SETTINGS, True
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def _log_parse_failure(stage: str, attempt: int, error: SchemaParseError) -> None:
|
| 163 |
+
"""Print a parse failure's traceback and raw model text to stdout.
|
| 164 |
+
|
| 165 |
+
Worker stdout reaches the serving platform's run logs, so this is the durable
|
| 166 |
+
diagnostic channel for malformed model output: the full traceback shows where
|
| 167 |
+
parsing failed and the delimited block shows exactly what the model emitted
|
| 168 |
+
(truncated to ``_RAW_TEXT_LOG_LIMIT`` characters to keep log entries bounded).
|
| 169 |
+
|
| 170 |
+
Args:
|
| 171 |
+
stage: The pipeline stage that failed (for example ``"image_grounding"``).
|
| 172 |
+
attempt: The 1-based attempt number that produced the failure.
|
| 173 |
+
error: The parse error carrying the offending raw model text.
|
| 174 |
+
"""
|
| 175 |
+
print(f"[cxr-auditor] parse failure: stage={stage} attempt={attempt}", flush=True)
|
| 176 |
+
traceback.print_exception(error, file=sys.stdout)
|
| 177 |
+
raw = error.raw_text
|
| 178 |
+
if len(raw) > _RAW_TEXT_LOG_LIMIT:
|
| 179 |
+
raw = f"{raw[:_RAW_TEXT_LOG_LIMIT]} ...[truncated]"
|
| 180 |
+
print(f"[cxr-auditor] raw model text (stage={stage} attempt={attempt}) >>>\n{raw}\n<<<", flush=True)
|
| 181 |
+
|
| 182 |
|
| 183 |
@dataclass(frozen=True, slots=True)
|
| 184 |
class AuditOutcome:
|
|
|
|
| 193 |
result: The canonical ``AuditResult`` (image findings, draft findings,
|
| 194 |
label-only audit, disclaimer, box format).
|
| 195 |
comparison: The per-item comparator detail (boxes, urgency, draft spans).
|
| 196 |
+
draft_parse_note: A user-facing note set when a supplied draft could not
|
| 197 |
+
be parsed after all retries, so the audit proceeded image-only.
|
| 198 |
+
``None`` when no draft was supplied or the draft parsed.
|
| 199 |
"""
|
| 200 |
|
| 201 |
result: AuditResult
|
| 202 |
comparison: ComparisonReport
|
| 203 |
+
draft_parse_note: str | None = None
|
| 204 |
|
| 205 |
|
| 206 |
def grounded_dicts_to_image_findings(grounded: list[dict[str, Any]]) -> list[ImageFinding]:
|
|
|
|
| 294 |
|
| 295 |
|
| 296 |
def run_with_retry(
|
| 297 |
+
generate_fn_factory: GenerateFnFactory,
|
| 298 |
prompt: str,
|
| 299 |
parse_fn: Callable[[str], list[Any]],
|
| 300 |
max_retries: int = DEFAULT_MAX_RETRIES,
|
| 301 |
+
*,
|
| 302 |
+
stage: str = "generation",
|
| 303 |
) -> list[Any]:
|
| 304 |
+
"""Generate then parse, escalating the retry conditions on each failure.
|
| 305 |
|
| 306 |
The model occasionally emits prose, a truncated array, or otherwise
|
| 307 |
+
unparseable text - and a greedy decode of the same prompt fails the same way
|
| 308 |
+
every time. Each attempt therefore changes the conditions per
|
| 309 |
+
``_attempt_settings``: attempt 1 is greedy with the base prompt, attempt 2 is
|
| 310 |
+
greedy with ``RETRY_CORRECTIVE_SUFFIX`` appended, and attempt 3 onward samples
|
| 311 |
+
(``RETRY_SAMPLING_SETTINGS``) with the suffix. Every failed attempt is logged
|
| 312 |
+
to stdout with its traceback and raw model text. If every attempt fails, the
|
| 313 |
+
last ``SchemaParseError`` is raised so its ``raw_text`` (the final raw
|
| 314 |
+
completion) is available to the caller.
|
| 315 |
|
| 316 |
Args:
|
| 317 |
+
generate_fn_factory: Factory returning a ``GenerateFn`` for the decoding
|
| 318 |
+
settings of each attempt.
|
| 319 |
+
prompt: The rendered base prompt (the corrective suffix is appended to it
|
| 320 |
+
on retry attempts).
|
| 321 |
parse_fn: A tolerant parser turning raw text into a list (raises
|
| 322 |
``SchemaParseError`` on unparseable text).
|
| 323 |
max_retries: Number of additional attempts after the first. Must be >= 0.
|
| 324 |
+
stage: Stage label used in failure logs (keyword-only).
|
| 325 |
|
| 326 |
Returns:
|
| 327 |
The first successfully parsed list.
|
|
|
|
| 334 |
raise ValueError(f"max_retries must be non-negative, got {max_retries}")
|
| 335 |
|
| 336 |
last_error: SchemaParseError | None = None
|
| 337 |
+
for attempt in range(1, max_retries + 2):
|
| 338 |
+
settings, corrective = _attempt_settings(attempt)
|
| 339 |
+
generate_fn = generate_fn_factory(settings)
|
| 340 |
+
attempt_prompt = prompt + RETRY_CORRECTIVE_SUFFIX if corrective else prompt
|
| 341 |
+
raw_text = generate_fn(attempt_prompt)
|
| 342 |
try:
|
| 343 |
return parse_fn(raw_text)
|
| 344 |
except SchemaParseError as exc:
|
| 345 |
last_error = exc
|
| 346 |
+
_log_parse_failure(stage, attempt, exc)
|
| 347 |
assert last_error is not None # loop runs at least once, so an error was set
|
| 348 |
raise last_error
|
| 349 |
|
| 350 |
|
| 351 |
+
def make_generate_fn(
|
| 352 |
+
model: Any,
|
| 353 |
+
processor: Any,
|
| 354 |
+
image: Image.Image,
|
| 355 |
+
settings: GenerationSettings = GREEDY_SETTINGS,
|
| 356 |
+
) -> GenerateFn:
|
| 357 |
"""Build an image-bound ``generate_fn`` over a loaded model and processor.
|
| 358 |
|
| 359 |
+
The returned closure captures the model, processor, image, and decoding
|
| 360 |
+
settings, exposing the text-in/text-out ``GenerateFn`` shape that the
|
| 361 |
+
grounding path, the retry ladder, and ``cxr_auditor.parser.parse_draft`` all
|
| 362 |
+
consume. Binding the image into the closure lets the draft parser - which
|
| 363 |
+
only knows about a text-prompt ``generate_fn`` - reuse the same single-turn
|
| 364 |
+
multimodal model the grounding step uses, so the draft is parsed with the
|
| 365 |
+
SAME model rather than a separate text-only stack.
|
| 366 |
|
| 367 |
Args:
|
| 368 |
model: A loaded vision-language model exposing ``generate``.
|
| 369 |
processor: The matching transformers processor.
|
| 370 |
image: The chest X-ray bound to every generation through this closure.
|
| 371 |
+
settings: Decoding settings bound to every generation through this
|
| 372 |
+
closure.
|
| 373 |
|
| 374 |
Returns:
|
| 375 |
A ``GenerateFn`` mapping a rendered prompt to the model's raw completion.
|
| 376 |
"""
|
| 377 |
|
| 378 |
def _generate(prompt: str) -> str:
|
| 379 |
+
return _generate_text(model, processor, prompt, image, settings=settings)
|
| 380 |
|
| 381 |
return _generate
|
| 382 |
|
| 383 |
|
| 384 |
+
def _generate_fn_factory(model: Any, processor: Any, image: Image.Image) -> GenerateFnFactory:
|
| 385 |
+
"""Build a settings-to-``GenerateFn`` factory bound to one model and image.
|
| 386 |
+
|
| 387 |
+
This is the shape the retry ladder consumes: each attempt requests a
|
| 388 |
+
``GenerateFn`` for its own decoding settings while the model, processor, and
|
| 389 |
+
image stay fixed.
|
| 390 |
+
|
| 391 |
+
Args:
|
| 392 |
+
model: A loaded vision-language model exposing ``generate``.
|
| 393 |
+
processor: The matching transformers processor.
|
| 394 |
+
image: The chest X-ray bound to every generation.
|
| 395 |
+
|
| 396 |
+
Returns:
|
| 397 |
+
A factory mapping ``GenerationSettings`` to an image-bound ``GenerateFn``.
|
| 398 |
+
"""
|
| 399 |
+
|
| 400 |
+
def _factory(settings: GenerationSettings) -> GenerateFn:
|
| 401 |
+
return make_generate_fn(model, processor, image, settings=settings)
|
| 402 |
+
|
| 403 |
+
return _factory
|
| 404 |
+
|
| 405 |
+
|
| 406 |
def generate_findings(
|
| 407 |
image: Image.Image,
|
| 408 |
*,
|
|
|
|
| 412 |
) -> list[ImageFinding]:
|
| 413 |
"""Ground an image into validated ``ImageFinding`` objects.
|
| 414 |
|
| 415 |
+
Builds the pinned image-grounding prompt, generates through the escalating
|
| 416 |
+
retry ladder, and assembles validated findings. This is the image-side entry
|
| 417 |
point the app uses when it wants only the grounded findings (for example to
|
| 418 |
draw boxes before a draft is supplied).
|
| 419 |
|
|
|
|
| 421 |
image: The chest X-ray as a PIL image.
|
| 422 |
model: A loaded vision-language model (keyword-only).
|
| 423 |
processor: The matching transformers processor (keyword-only).
|
| 424 |
+
max_retries: Retry budget for the invalid-JSON ladder (keyword-only).
|
| 425 |
|
| 426 |
Returns:
|
| 427 |
The image-grounded findings with bounding-box evidence.
|
|
|
|
| 429 |
Raises:
|
| 430 |
SchemaParseError: If grounding output cannot be parsed after all retries.
|
| 431 |
"""
|
| 432 |
+
grounded = run_with_retry(
|
| 433 |
+
_generate_fn_factory(model, processor, image),
|
| 434 |
+
build_image_grounding_prompt(),
|
| 435 |
+
extract_finding_list,
|
| 436 |
+
max_retries=max_retries,
|
| 437 |
+
stage="image_grounding",
|
| 438 |
+
)
|
| 439 |
return grounded_dicts_to_image_findings(grounded)
|
| 440 |
|
| 441 |
|
|
|
|
| 451 |
|
| 452 |
Steps:
|
| 453 |
1. Ground the image into validated ``ImageFinding`` objects
|
| 454 |
+
(``generate_findings``), through the escalating retry ladder.
|
| 455 |
2. If a non-blank draft is supplied, parse it into the same label space via
|
| 456 |
``cxr_auditor.parser.parse_draft``, driven by an image-bound
|
| 457 |
+
``generate_fn`` through the same ladder (with the ``DRAFT_MAX_RETRIES``
|
| 458 |
+
budget). A draft that still cannot be parsed never fails the audit: the
|
| 459 |
+
audit proceeds image-only and ``AuditOutcome.draft_parse_note`` records
|
| 460 |
+
the degradation for the user interface.
|
| 461 |
3. Run the deterministic comparator (``cxr_auditor.comparator.compare``) and
|
| 462 |
bundle everything into an ``AuditOutcome``.
|
| 463 |
|
|
|
|
| 472 |
image-side findings (and urgent flags).
|
| 473 |
model: A loaded vision-language model exposing ``generate`` (keyword-only).
|
| 474 |
processor: The matching transformers processor (keyword-only).
|
| 475 |
+
max_retries: Retry budget for the image-grounding ladder (keyword-only).
|
| 476 |
+
Draft parsing uses the fixed ``DRAFT_MAX_RETRIES`` budget because it
|
| 477 |
+
degrades gracefully instead of failing.
|
| 478 |
|
| 479 |
Returns:
|
| 480 |
+
An ``AuditOutcome`` carrying the canonical ``AuditResult``, the per-item
|
| 481 |
+
``ComparisonReport``, and the draft-degradation note when it applies.
|
| 482 |
|
| 483 |
Raises:
|
| 484 |
ValueError: If ``model`` or ``processor`` is not supplied.
|
| 485 |
+
SchemaParseError: If the image-grounding output cannot be parsed into a
|
| 486 |
finding list after all retries.
|
| 487 |
"""
|
| 488 |
if model is None or processor is None:
|
|
|
|
| 491 |
image_findings = generate_findings(image, model=model, processor=processor, max_retries=max_retries)
|
| 492 |
|
| 493 |
draft_findings: list[DraftFinding] = []
|
| 494 |
+
draft_parse_note: str | None = None
|
| 495 |
cleaned_draft = (draft_text or "").strip()
|
| 496 |
if cleaned_draft:
|
| 497 |
+
try:
|
| 498 |
+
draft_findings = _parse_draft_with_retry(cleaned_draft, _generate_fn_factory(model, processor, image))
|
| 499 |
+
except SchemaParseError:
|
| 500 |
+
# Per-attempt details are already logged by _log_parse_failure; the
|
| 501 |
+
# audit degrades to image-only rather than failing on the draft.
|
| 502 |
+
print("[cxr-auditor] draft parsing failed after all retries; auditing image only", flush=True)
|
| 503 |
+
draft_parse_note = DRAFT_PARSE_FAILURE_NOTE
|
| 504 |
|
| 505 |
comparison = compare(image_findings, draft_findings)
|
| 506 |
result = AuditResult(
|
|
|
|
| 508 |
draft_findings=draft_findings,
|
| 509 |
audit=comparison.audit,
|
| 510 |
)
|
| 511 |
+
return AuditOutcome(result=result, comparison=comparison, draft_parse_note=draft_parse_note)
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
def _with_corrective_suffix(generate_fn: GenerateFn) -> GenerateFn:
|
| 515 |
+
"""Wrap a ``GenerateFn`` so every prompt carries the corrective suffix.
|
| 516 |
+
|
| 517 |
+
``parser.parse_draft`` builds its prompt internally, so retry attempts inject
|
| 518 |
+
``RETRY_CORRECTIVE_SUFFIX`` by wrapping the callable rather than editing the
|
| 519 |
+
prompt directly.
|
| 520 |
+
|
| 521 |
+
Args:
|
| 522 |
+
generate_fn: The inner ``GenerateFn`` to wrap.
|
| 523 |
+
|
| 524 |
+
Returns:
|
| 525 |
+
A ``GenerateFn`` that appends the corrective suffix to every prompt.
|
| 526 |
+
"""
|
| 527 |
+
|
| 528 |
+
def _generate(prompt: str) -> str:
|
| 529 |
+
return generate_fn(prompt + RETRY_CORRECTIVE_SUFFIX)
|
| 530 |
+
|
| 531 |
+
return _generate
|
| 532 |
|
| 533 |
|
| 534 |
def _parse_draft_with_retry(
|
| 535 |
draft_text: str,
|
| 536 |
+
generate_fn_factory: GenerateFnFactory,
|
| 537 |
+
max_retries: int = DRAFT_MAX_RETRIES,
|
| 538 |
) -> list[DraftFinding]:
|
| 539 |
+
"""Parse a draft through ``parser.parse_draft`` with the escalating ladder.
|
| 540 |
|
| 541 |
+
Wraps the draft parser's injected-callable contract in the same attempt plan
|
| 542 |
+
the grounding path uses (``_attempt_settings``): each attempt re-runs the full
|
| 543 |
+
``parse_draft`` (build prompt, generate, validate), retry attempts append the
|
| 544 |
+
corrective suffix via a wrapped ``GenerateFn``, the first successful parse
|
| 545 |
+
wins, and the final ``SchemaParseError`` propagates if all attempts fail.
|
| 546 |
|
| 547 |
Args:
|
| 548 |
draft_text: The non-empty draft impression to parse.
|
| 549 |
+
generate_fn_factory: Factory returning an image-bound ``GenerateFn`` for
|
| 550 |
+
each attempt's decoding settings.
|
| 551 |
max_retries: Number of additional attempts after the first. Must be >= 0.
|
| 552 |
|
| 553 |
Returns:
|
|
|
|
| 561 |
raise ValueError(f"max_retries must be non-negative, got {max_retries}")
|
| 562 |
|
| 563 |
last_error: SchemaParseError | None = None
|
| 564 |
+
for attempt in range(1, max_retries + 2):
|
| 565 |
+
settings, corrective = _attempt_settings(attempt)
|
| 566 |
+
generate_fn = generate_fn_factory(settings)
|
| 567 |
+
if corrective:
|
| 568 |
+
generate_fn = _with_corrective_suffix(generate_fn)
|
| 569 |
try:
|
| 570 |
return parse_draft(draft_text, generate_fn)
|
| 571 |
except SchemaParseError as exc:
|
| 572 |
last_error = exc
|
| 573 |
+
_log_parse_failure("draft_parsing", attempt, exc)
|
| 574 |
assert last_error is not None
|
| 575 |
raise last_error
|
| 576 |
|
|
|
|
| 640 |
return model, processor
|
| 641 |
|
| 642 |
|
| 643 |
+
def _generate_text(
|
| 644 |
+
model: Any,
|
| 645 |
+
processor: Any,
|
| 646 |
+
prompt: str,
|
| 647 |
+
image: Image.Image,
|
| 648 |
+
settings: GenerationSettings = GREEDY_SETTINGS,
|
| 649 |
+
) -> str:
|
| 650 |
"""Run one single-turn multimodal generation and return the decoded reply.
|
| 651 |
|
| 652 |
This is the only function that touches the model at inference time, and the
|
| 653 |
single seam tests patch to drive the orchestration without a real model. It
|
| 654 |
builds a single-turn chat message with the image and the prompt text, applies
|
| 655 |
+
the processor's chat template, generates with the supplied decoding settings,
|
| 656 |
+
and decodes only the newly generated tokens (slicing off the prompt) so the
|
| 657 |
+
returned text is just the model's reply (a plain ``str``, never a tensor
|
| 658 |
+
across a worker boundary). ``pad_token_id`` is pinned to the tokenizer's
|
| 659 |
+
end-of-sequence token so generation runs without a pad-token warning.
|
| 660 |
|
| 661 |
Heavy imports are local to keep module import free of the vision stack. The
|
| 662 |
chat-message construction follows the transformers image-text-to-text
|
|
|
|
| 668 |
processor: The matching processor.
|
| 669 |
prompt: The fully rendered text prompt.
|
| 670 |
image: The chest X-ray as a PIL image.
|
| 671 |
+
settings: Decoding settings for this generation.
|
| 672 |
|
| 673 |
Returns:
|
| 674 |
The model's decoded reply text (prompt tokens stripped).
|
|
|
|
| 692 |
return_tensors="pt",
|
| 693 |
).to(model.device)
|
| 694 |
|
| 695 |
+
generate_kwargs: dict[str, Any] = {
|
| 696 |
+
"max_new_tokens": DEFAULT_MAX_NEW_TOKENS,
|
| 697 |
+
"do_sample": settings.do_sample,
|
| 698 |
+
"pad_token_id": processor.tokenizer.eos_token_id,
|
| 699 |
+
}
|
| 700 |
+
# Sampling knobs are forwarded only when sampling; transformers warns when
|
| 701 |
+
# they accompany greedy decoding.
|
| 702 |
+
if settings.do_sample:
|
| 703 |
+
if settings.temperature is not None:
|
| 704 |
+
generate_kwargs["temperature"] = settings.temperature
|
| 705 |
+
if settings.top_p is not None:
|
| 706 |
+
generate_kwargs["top_p"] = settings.top_p
|
| 707 |
+
|
| 708 |
input_len = inputs["input_ids"].shape[-1]
|
| 709 |
with torch.inference_mode():
|
| 710 |
+
generated = model.generate(**inputs, **generate_kwargs)
|
| 711 |
new_tokens = generated[0][input_len:]
|
| 712 |
return processor.decode(new_tokens, skip_special_tokens=True)
|
| 713 |
|
| 714 |
|
| 715 |
+
# Titles the ZeroGPU scheduler attaches to the quota and scheduling errors it
|
| 716 |
+
# raises in the serving app's main process. These failures are platform-side: the
|
| 717 |
+
# uploaded image is never the cause, so the user message must not blame it.
|
| 718 |
+
_GPU_SCHEDULING_ERROR_TITLES: frozenset[str] = frozenset(
|
| 719 |
+
{
|
| 720 |
+
"ZeroGPU quota exceeded",
|
| 721 |
+
"ZeroGPU illegal duration",
|
| 722 |
+
"ZeroGPU pending credits exceeded",
|
| 723 |
+
"ZeroGPU queue timeout",
|
| 724 |
+
"ZeroGPU client error",
|
| 725 |
+
}
|
| 726 |
+
)
|
| 727 |
+
|
| 728 |
+
# Title the ZeroGPU platform attaches when a worker exception was converted to a
|
| 729 |
+
# string-transported error whose message body is the worker exception class name.
|
| 730 |
+
_WORKER_ERROR_TITLE: str = "ZeroGPU worker error"
|
| 731 |
+
|
| 732 |
+
# Worker exception class names that mean "the model output could not be parsed".
|
| 733 |
+
_PARSE_ERROR_CLASS_NAMES: frozenset[str] = frozenset({"SchemaParseError"})
|
| 734 |
+
|
| 735 |
+
# Message body the ZeroGPU platform uses when it cuts a GPU task short.
|
| 736 |
+
_GPU_TASK_ABORTED_BODY: str = "GPU task aborted"
|
| 737 |
+
|
| 738 |
+
_GPU_QUOTA_MESSAGE: str = (
|
| 739 |
+
"**GPU quota reached.** Free ZeroGPU time is temporarily exhausted, so this audit could not get a "
|
| 740 |
+
"GPU slot - the image is not the problem. Wait a few minutes and press Run audit again."
|
| 741 |
+
)
|
| 742 |
+
|
| 743 |
+
_GPU_INTERRUPTED_MESSAGE: str = (
|
| 744 |
+
"**GPU task was interrupted.** The platform cut the GPU run short before the audit finished. "
|
| 745 |
+
"Please press Run audit again."
|
| 746 |
+
)
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
def _parse_failure_message(class_name: str) -> str:
|
| 750 |
+
"""Return the user-facing message for an unparseable-model-output failure."""
|
| 751 |
+
return (
|
| 752 |
+
f"**Could not analyze this image.** The model returned output that could not be parsed ({class_name}). "
|
| 753 |
+
"Please try again, or use a clearer frontal chest X-ray."
|
| 754 |
+
)
|
| 755 |
+
|
| 756 |
+
|
| 757 |
+
def _generic_failure_message(detail: str) -> str:
|
| 758 |
+
"""Return the user-facing message for an uncategorized failure."""
|
| 759 |
+
return (
|
| 760 |
+
f"**Audit failed.** An unexpected error occurred ({detail}). "
|
| 761 |
+
"Please try again; if this keeps happening, check the Space logs."
|
| 762 |
+
)
|
| 763 |
+
|
| 764 |
+
|
| 765 |
+
def categorize_serving_error(error: Exception) -> str:
|
| 766 |
+
"""Map an audit-time exception to an honest, user-facing Markdown message.
|
| 767 |
+
|
| 768 |
+
The ZeroGPU platform never pickles worker exceptions across the process
|
| 769 |
+
boundary: it transports the worker exception's class name as the message body
|
| 770 |
+
of a gradio error object whose own class ``__name__`` is literally ``"Error"``
|
| 771 |
+
and whose ``title`` attribute names the failure source. This categorizer
|
| 772 |
+
therefore classifies on the exception's class name, ``title`` attribute, and
|
| 773 |
+
message body - never on ``isinstance`` against gradio types - so it stays
|
| 774 |
+
importable and unit-testable without gradio installed.
|
| 775 |
+
|
| 776 |
+
Categories:
|
| 777 |
+
- Quota and scheduling errors (a title in the known ZeroGPU set, or any
|
| 778 |
+
title or body mentioning "quota") produce a GPU-quota message that
|
| 779 |
+
never blames the image.
|
| 780 |
+
- An aborted GPU task (body ``"GPU task aborted"``) produces a transient
|
| 781 |
+
interrupted-please-retry message.
|
| 782 |
+
- A worker error whose body names a parse-failure class, or a directly
|
| 783 |
+
raised ``SchemaParseError``, produces the could-not-parse message
|
| 784 |
+
naming the real exception class.
|
| 785 |
+
- Anything else produces a generic failure message naming the true type.
|
| 786 |
+
|
| 787 |
+
Args:
|
| 788 |
+
error: The exception caught around the GPU audit call.
|
| 789 |
+
|
| 790 |
+
Returns:
|
| 791 |
+
A Markdown message suitable for the audit panel.
|
| 792 |
+
"""
|
| 793 |
+
if isinstance(error, SchemaParseError):
|
| 794 |
+
return _parse_failure_message(type(error).__name__)
|
| 795 |
+
|
| 796 |
+
body = str(error)
|
| 797 |
+
if type(error).__name__ == "Error":
|
| 798 |
+
title = str(getattr(error, "title", ""))
|
| 799 |
+
if title in _GPU_SCHEDULING_ERROR_TITLES or "quota" in title.lower() or "quota" in body.lower():
|
| 800 |
+
return _GPU_QUOTA_MESSAGE
|
| 801 |
+
if _GPU_TASK_ABORTED_BODY in body:
|
| 802 |
+
return _GPU_INTERRUPTED_MESSAGE
|
| 803 |
+
if title == _WORKER_ERROR_TITLE:
|
| 804 |
+
if body in _PARSE_ERROR_CLASS_NAMES:
|
| 805 |
+
return _parse_failure_message(body)
|
| 806 |
+
return _generic_failure_message(body or type(error).__name__)
|
| 807 |
+
return _generic_failure_message(type(error).__name__)
|
| 808 |
+
|
| 809 |
+
|
| 810 |
__all__ = [
|
| 811 |
"DEFAULT_MAX_NEW_TOKENS",
|
| 812 |
"DEFAULT_MAX_RETRIES",
|
| 813 |
"DEFAULT_MODEL_ID",
|
| 814 |
+
"DRAFT_MAX_RETRIES",
|
| 815 |
+
"DRAFT_PARSE_FAILURE_NOTE",
|
| 816 |
+
"GREEDY_SETTINGS",
|
| 817 |
+
"RETRY_CORRECTIVE_SUFFIX",
|
| 818 |
+
"RETRY_SAMPLING_SETTINGS",
|
| 819 |
"AuditOutcome",
|
| 820 |
+
"GenerateFnFactory",
|
| 821 |
+
"GenerationSettings",
|
| 822 |
"audit",
|
| 823 |
+
"categorize_serving_error",
|
| 824 |
"generate_findings",
|
| 825 |
"grounded_dicts_to_image_findings",
|
| 826 |
"load_model",
|
cxr_auditor/parser.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
"""
|
| 2 |
Draft-report parser: map a draft impression into the canonical label space.
|
| 3 |
|
| 4 |
-
This is
|
| 5 |
pinned draft-parsing prompt) to extract which canonical findings a draft
|
| 6 |
impression asserts present and which it explicitly denies, then validates the
|
| 7 |
model's JSON list into ``DraftFinding`` objects.
|
|
|
|
| 1 |
"""
|
| 2 |
Draft-report parser: map a draft impression into the canonical label space.
|
| 3 |
|
| 4 |
+
This is the PRIMARY draft parser. It prompts the same MedGemma model (via the
|
| 5 |
pinned draft-parsing prompt) to extract which canonical findings a draft
|
| 6 |
impression asserts present and which it explicitly denies, then validates the
|
| 7 |
model's JSON list into ``DraftFinding`` objects.
|
cxr_auditor/render.py
CHANGED
|
@@ -32,12 +32,22 @@ the others. ``cluster_overlay_boxes`` merges spatially-overlapping boxes into on
|
|
| 32 |
is drawn exactly once with the correct, order-independent color and a single
|
| 33 |
combined label.
|
| 34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
Unsupported claims are draft-only and have no image box, so they appear in the
|
| 36 |
table and the audit panel rather than as overlay boxes.
|
| 37 |
"""
|
| 38 |
|
| 39 |
from __future__ import annotations
|
| 40 |
|
|
|
|
| 41 |
from dataclasses import dataclass
|
| 42 |
from enum import Enum
|
| 43 |
|
|
@@ -64,6 +74,13 @@ _MAX_OVERLAY_LONG_SIDE = 1280
|
|
| 64 |
_MIN_LABEL_FONT_SIZE = 14
|
| 65 |
_MAX_LABEL_FONT_SIZE = 28
|
| 66 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
# RGB colors for each evidence category. Chosen for contrast on a grayscale X-ray.
|
| 68 |
_SUPPORTED_COLOR = (46, 204, 113)
|
| 69 |
_MISSING_COLOR = (243, 156, 18)
|
|
@@ -317,6 +334,64 @@ def _combined_label(cluster: OverlayBox) -> str:
|
|
| 317 |
return text
|
| 318 |
|
| 319 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 320 |
def _draw_label(
|
| 321 |
draw: ImageDraw.ImageDraw,
|
| 322 |
box_xyxy: XYXYBox,
|
|
@@ -325,14 +400,17 @@ def _draw_label(
|
|
| 325 |
color: tuple[int, int, int],
|
| 326 |
font: LoadedFont,
|
| 327 |
image_size: tuple[int, int],
|
| 328 |
-
|
|
|
|
| 329 |
"""Draw a filled, high-contrast label band anchored to a box, clamped on-image.
|
| 330 |
|
| 331 |
The label sits just above the box top by default, but flips to just below the
|
| 332 |
box top when there is no room above (the box touches the top edge), and its
|
| 333 |
left edge is clamped so the band never runs off the right side of the image.
|
| 334 |
-
|
| 335 |
-
|
|
|
|
|
|
|
| 336 |
|
| 337 |
Args:
|
| 338 |
draw: The active drawing context.
|
|
@@ -341,6 +419,11 @@ def _draw_label(
|
|
| 341 |
color: The band fill color (the cluster's status color).
|
| 342 |
font: The scaled font to measure and render with.
|
| 343 |
image_size: ``(width, height)`` of the canvas, for on-image clamping.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 344 |
"""
|
| 345 |
image_width, image_height = image_size
|
| 346 |
x_min, y_min, _x_max, _y_max = box_xyxy
|
|
@@ -361,11 +444,12 @@ def _draw_label(
|
|
| 361 |
band_left = max(0, image_width - band_width)
|
| 362 |
band_top = max(0, min(band_top, image_height - band_height))
|
| 363 |
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
)
|
| 368 |
-
draw.text((
|
|
|
|
| 369 |
|
| 370 |
|
| 371 |
def _contrast_ink(color: tuple[int, int, int]) -> tuple[int, int, int]:
|
|
@@ -390,7 +474,9 @@ def annotate_evidence(image: Image.Image, outcome: AuditOutcome) -> Image.Image:
|
|
| 390 |
(see ``cluster_overlay_boxes``) so each region is drawn exactly once, colored by
|
| 391 |
audit status (see the module color legend). Urgent regions are drawn in red with
|
| 392 |
a doubled, thicker border and an "(URGENT)" tag so they stand out. Every label
|
| 393 |
-
uses the human-readable display name
|
|
|
|
|
|
|
| 394 |
contribute no drawing (they still appear in the table and panel).
|
| 395 |
|
| 396 |
Args:
|
|
@@ -414,6 +500,8 @@ def annotate_evidence(image: Image.Image, outcome: AuditOutcome) -> Image.Image:
|
|
| 414 |
# stay proportionate on both tiny test fixtures and canvas-capped X-rays.
|
| 415 |
base_width = max(2, round(max(width, height) / 320))
|
| 416 |
|
|
|
|
|
|
|
| 417 |
for cluster in cluster_overlay_boxes(categorize_image_findings(outcome)):
|
| 418 |
box_xyxy = normalized_to_xyxy_abs(cluster.box, width, height)
|
| 419 |
x_min, y_min, x_max, y_max = box_xyxy
|
|
@@ -428,7 +516,17 @@ def annotate_evidence(image: Image.Image, outcome: AuditOutcome) -> Image.Image:
|
|
| 428 |
outline=color,
|
| 429 |
width=max(1, base_width),
|
| 430 |
)
|
| 431 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 432 |
|
| 433 |
return canvas
|
| 434 |
|
|
@@ -495,11 +593,13 @@ def _status_word(status: FindingStatus) -> str:
|
|
| 495 |
def audit_panel_markdown(outcome: AuditOutcome) -> str:
|
| 496 |
"""Render the audit verdict as a plain-English Markdown panel.
|
| 497 |
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
|
|
|
|
|
|
| 503 |
|
| 504 |
Args:
|
| 505 |
outcome: The audit outcome.
|
|
@@ -508,11 +608,22 @@ def audit_panel_markdown(outcome: AuditOutcome) -> str:
|
|
| 508 |
A Markdown string.
|
| 509 |
"""
|
| 510 |
audit = outcome.result.audit
|
| 511 |
-
lines: list[str] = [
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 516 |
|
| 517 |
if audit.urgent_review_flags:
|
| 518 |
lines.append("### URGENT - needs radiologist review")
|
|
|
|
| 32 |
is drawn exactly once with the correct, order-independent color and a single
|
| 33 |
combined label.
|
| 34 |
|
| 35 |
+
Label collision avoidance
|
| 36 |
+
-------------------------
|
| 37 |
+
Distinct regions can still carry long labels at nearly the same height (for
|
| 38 |
+
example bilateral opacities over the two lung fields), where independently
|
| 39 |
+
placed label bands would overlap and clip each other. Each band is therefore
|
| 40 |
+
checked against the bands already drawn on the canvas and nudged vertically
|
| 41 |
+
(below its own box first) until it overlaps none of them, always staying
|
| 42 |
+
clamped on-image; a lone label keeps its exact anchored position.
|
| 43 |
+
|
| 44 |
Unsupported claims are draft-only and have no image box, so they appear in the
|
| 45 |
table and the audit panel rather than as overlay boxes.
|
| 46 |
"""
|
| 47 |
|
| 48 |
from __future__ import annotations
|
| 49 |
|
| 50 |
+
from collections.abc import Sequence
|
| 51 |
from dataclasses import dataclass
|
| 52 |
from enum import Enum
|
| 53 |
|
|
|
|
| 74 |
_MIN_LABEL_FONT_SIZE = 14
|
| 75 |
_MAX_LABEL_FONT_SIZE = 28
|
| 76 |
|
| 77 |
+
# Vertical search budget for nudging a colliding label band: this many
|
| 78 |
+
# band-height steps downward and again upward. At the tallest band a capped
|
| 79 |
+
# canvas produces (about 37 px) eight steps sweep roughly 300 px each way -
|
| 80 |
+
# ample clearance for the handful of labels one audit draws - while keeping
|
| 81 |
+
# the candidate count, and therefore the worst-case drawing work, bounded.
|
| 82 |
+
_LABEL_NUDGE_ATTEMPTS = 8
|
| 83 |
+
|
| 84 |
# RGB colors for each evidence category. Chosen for contrast on a grayscale X-ray.
|
| 85 |
_SUPPORTED_COLOR = (46, 204, 113)
|
| 86 |
_MISSING_COLOR = (243, 156, 18)
|
|
|
|
| 334 |
return text
|
| 335 |
|
| 336 |
|
| 337 |
+
def _rects_overlap(a: XYXYBox, b: XYXYBox) -> bool:
|
| 338 |
+
"""Return whether two pixel rectangles share interior area.
|
| 339 |
+
|
| 340 |
+
Rectangles are ``(left, top, right, bottom)``. Edge-touching rectangles do
|
| 341 |
+
not count as overlapping, so nudged label bands may sit flush against one
|
| 342 |
+
another without triggering a further nudge.
|
| 343 |
+
"""
|
| 344 |
+
a_left, a_top, a_right, a_bottom = a
|
| 345 |
+
b_left, b_top, b_right, b_bottom = b
|
| 346 |
+
return a_left < b_right and b_left < a_right and a_top < b_bottom and b_top < a_bottom
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def _resolve_band_rect(
|
| 350 |
+
desired: XYXYBox,
|
| 351 |
+
box_xyxy: XYXYBox,
|
| 352 |
+
image_height: int,
|
| 353 |
+
placed_bands: Sequence[XYXYBox],
|
| 354 |
+
) -> XYXYBox:
|
| 355 |
+
"""Return the label-band rectangle to draw, nudged vertically clear of placed bands.
|
| 356 |
+
|
| 357 |
+
A desired rectangle that overlaps no already-placed band is returned
|
| 358 |
+
unchanged, so a lone label renders exactly at its anchored position. On
|
| 359 |
+
collision the band keeps its horizontal extent (it stays anchored to its
|
| 360 |
+
box) and tries vertical positions in order: just below the box's bottom
|
| 361 |
+
edge, then band-height steps downward from there, then band-height steps
|
| 362 |
+
upward from the desired position, up to ``_LABEL_NUDGE_ATTEMPTS`` steps per
|
| 363 |
+
direction. Every candidate is clamped fully on-image; when no candidate
|
| 364 |
+
clears all placed bands the last clamped candidate is returned, so the
|
| 365 |
+
result is always an on-image rectangle and rendering never fails.
|
| 366 |
+
|
| 367 |
+
Args:
|
| 368 |
+
desired: The preferred band rectangle ``(left, top, right, bottom)``,
|
| 369 |
+
already clamped on-image by the caller.
|
| 370 |
+
box_xyxy: The owning box in absolute pixels ``(x_min, y_min, x_max,
|
| 371 |
+
y_max)``, anchoring the below-box candidate.
|
| 372 |
+
image_height: The canvas height in pixels, for vertical clamping.
|
| 373 |
+
placed_bands: Band rectangles already drawn on this canvas.
|
| 374 |
+
|
| 375 |
+
Returns:
|
| 376 |
+
The chosen band rectangle ``(left, top, right, bottom)``.
|
| 377 |
+
"""
|
| 378 |
+
left, desired_top, right, desired_bottom = desired
|
| 379 |
+
band_height = desired_bottom - desired_top
|
| 380 |
+
lowest_top = max(0.0, image_height - band_height)
|
| 381 |
+
below_box_top = min(box_xyxy[3], lowest_top)
|
| 382 |
+
|
| 383 |
+
candidate_tops = [desired_top, below_box_top]
|
| 384 |
+
candidate_tops.extend(min(below_box_top + step * band_height, lowest_top) for step in range(1, _LABEL_NUDGE_ATTEMPTS + 1))
|
| 385 |
+
candidate_tops.extend(max(0.0, desired_top - step * band_height) for step in range(1, _LABEL_NUDGE_ATTEMPTS + 1))
|
| 386 |
+
|
| 387 |
+
band = desired
|
| 388 |
+
for top in candidate_tops:
|
| 389 |
+
band = (left, top, right, top + band_height)
|
| 390 |
+
if not any(_rects_overlap(band, placed) for placed in placed_bands):
|
| 391 |
+
return band
|
| 392 |
+
return band
|
| 393 |
+
|
| 394 |
+
|
| 395 |
def _draw_label(
|
| 396 |
draw: ImageDraw.ImageDraw,
|
| 397 |
box_xyxy: XYXYBox,
|
|
|
|
| 400 |
color: tuple[int, int, int],
|
| 401 |
font: LoadedFont,
|
| 402 |
image_size: tuple[int, int],
|
| 403 |
+
placed_bands: Sequence[XYXYBox],
|
| 404 |
+
) -> XYXYBox:
|
| 405 |
"""Draw a filled, high-contrast label band anchored to a box, clamped on-image.
|
| 406 |
|
| 407 |
The label sits just above the box top by default, but flips to just below the
|
| 408 |
box top when there is no room above (the box touches the top edge), and its
|
| 409 |
left edge is clamped so the band never runs off the right side of the image.
|
| 410 |
+
When the resulting band would overlap a band already drawn on this canvas it
|
| 411 |
+
is nudged vertically clear (see ``_resolve_band_rect``) so neighboring labels
|
| 412 |
+
never clip each other. The band is filled with ``color`` and the text is
|
| 413 |
+
drawn in a contrasting ink so it is legible over a grayscale X-ray.
|
| 414 |
|
| 415 |
Args:
|
| 416 |
draw: The active drawing context.
|
|
|
|
| 419 |
color: The band fill color (the cluster's status color).
|
| 420 |
font: The scaled font to measure and render with.
|
| 421 |
image_size: ``(width, height)`` of the canvas, for on-image clamping.
|
| 422 |
+
placed_bands: Band rectangles already drawn on this canvas, used to
|
| 423 |
+
resolve collisions; the caller records the returned rectangle.
|
| 424 |
+
|
| 425 |
+
Returns:
|
| 426 |
+
The band rectangle ``(left, top, right, bottom)`` actually drawn.
|
| 427 |
"""
|
| 428 |
image_width, image_height = image_size
|
| 429 |
x_min, y_min, _x_max, _y_max = box_xyxy
|
|
|
|
| 444 |
band_left = max(0, image_width - band_width)
|
| 445 |
band_top = max(0, min(band_top, image_height - band_height))
|
| 446 |
|
| 447 |
+
desired = (band_left, band_top, band_left + band_width, band_top + band_height)
|
| 448 |
+
band = _resolve_band_rect(desired, box_xyxy, image_height, placed_bands)
|
| 449 |
+
|
| 450 |
+
draw.rectangle(band, fill=color)
|
| 451 |
+
draw.text((band[0] + pad, band[1] + pad), text, fill=_contrast_ink(color), font=font)
|
| 452 |
+
return band
|
| 453 |
|
| 454 |
|
| 455 |
def _contrast_ink(color: tuple[int, int, int]) -> tuple[int, int, int]:
|
|
|
|
| 474 |
(see ``cluster_overlay_boxes``) so each region is drawn exactly once, colored by
|
| 475 |
audit status (see the module color legend). Urgent regions are drawn in red with
|
| 476 |
a doubled, thicker border and an "(URGENT)" tag so they stand out. Every label
|
| 477 |
+
uses the human-readable display name, and label bands that would overlap an
|
| 478 |
+
earlier band are nudged vertically clear of it (see ``_resolve_band_rect``) so
|
| 479 |
+
neighboring labels stay readable. Findings without a localizable box
|
| 480 |
contribute no drawing (they still appear in the table and panel).
|
| 481 |
|
| 482 |
Args:
|
|
|
|
| 500 |
# stay proportionate on both tiny test fixtures and canvas-capped X-rays.
|
| 501 |
base_width = max(2, round(max(width, height) / 320))
|
| 502 |
|
| 503 |
+
# Bands already drawn on this canvas; each new label is nudged clear of them.
|
| 504 |
+
placed_bands: list[XYXYBox] = []
|
| 505 |
for cluster in cluster_overlay_boxes(categorize_image_findings(outcome)):
|
| 506 |
box_xyxy = normalized_to_xyxy_abs(cluster.box, width, height)
|
| 507 |
x_min, y_min, x_max, y_max = box_xyxy
|
|
|
|
| 516 |
outline=color,
|
| 517 |
width=max(1, base_width),
|
| 518 |
)
|
| 519 |
+
placed_bands.append(
|
| 520 |
+
_draw_label(
|
| 521 |
+
draw,
|
| 522 |
+
box_xyxy,
|
| 523 |
+
_combined_label(cluster),
|
| 524 |
+
color=color,
|
| 525 |
+
font=font,
|
| 526 |
+
image_size=(width, height),
|
| 527 |
+
placed_bands=placed_bands,
|
| 528 |
+
)
|
| 529 |
+
)
|
| 530 |
|
| 531 |
return canvas
|
| 532 |
|
|
|
|
| 593 |
def audit_panel_markdown(outcome: AuditOutcome) -> str:
|
| 594 |
"""Render the audit verdict as a plain-English Markdown panel.
|
| 595 |
|
| 596 |
+
When the outcome carries a draft-degradation note (the draft could not be
|
| 597 |
+
parsed and the audit proceeded image-only), that note leads the panel so the
|
| 598 |
+
user re-checks the draft manually. Then comes a short "How to read this"
|
| 599 |
+
orientation line, urgent flags first (most important), missing findings,
|
| 600 |
+
and unsupported claims, with per-item detail (draft spans for unsupported
|
| 601 |
+
claims). Every finding is shown by its human-readable display name. When
|
| 602 |
+
nothing is flagged, reports agreement.
|
| 603 |
|
| 604 |
Args:
|
| 605 |
outcome: The audit outcome.
|
|
|
|
| 608 |
A Markdown string.
|
| 609 |
"""
|
| 610 |
audit = outcome.result.audit
|
| 611 |
+
lines: list[str] = []
|
| 612 |
+
if outcome.draft_parse_note is not None:
|
| 613 |
+
lines.extend(
|
| 614 |
+
[
|
| 615 |
+
f"**Draft not analyzed:** {outcome.draft_parse_note} "
|
| 616 |
+
"This audit reflects the image only - re-check the draft text manually.",
|
| 617 |
+
"",
|
| 618 |
+
]
|
| 619 |
+
)
|
| 620 |
+
lines.extend(
|
| 621 |
+
[
|
| 622 |
+
"**How to read this:** this panel compares what the AI sees in the image against the draft text. "
|
| 623 |
+
"It is a research aid, not a diagnosis - always confirm with a qualified radiologist.",
|
| 624 |
+
"",
|
| 625 |
+
]
|
| 626 |
+
)
|
| 627 |
|
| 628 |
if audit.urgent_review_flags:
|
| 629 |
lines.append("### URGENT - needs radiologist review")
|
cxr_auditor/schema.py
CHANGED
|
@@ -202,33 +202,39 @@ class SchemaParseError(ValueError):
|
|
| 202 |
super().__init__(message)
|
| 203 |
self.raw_text = raw_text
|
| 204 |
|
|
|
|
|
|
|
| 205 |
|
| 206 |
-
|
| 207 |
-
|
|
|
|
| 208 |
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
|
| 214 |
Args:
|
| 215 |
-
text:
|
|
|
|
|
|
|
|
|
|
| 216 |
|
| 217 |
Returns:
|
| 218 |
-
The
|
| 219 |
-
|
| 220 |
-
Raises:
|
| 221 |
-
SchemaParseError: If no balanced JSON object is found, or the candidate
|
| 222 |
-
slice is not valid JSON, or the top-level value is not an object.
|
| 223 |
"""
|
| 224 |
-
start = text.find("{")
|
| 225 |
-
if start == -1:
|
| 226 |
-
raise SchemaParseError("no JSON object found in model text", text)
|
| 227 |
-
|
| 228 |
depth = 0
|
| 229 |
in_string = False
|
| 230 |
escaped = False
|
| 231 |
-
end = -1
|
| 232 |
for index in range(start, len(text)):
|
| 233 |
char = text[index]
|
| 234 |
if in_string:
|
|
@@ -241,14 +247,38 @@ def extract_first_json_object(text: str) -> dict[str, Any]:
|
|
| 241 |
continue
|
| 242 |
if char == '"':
|
| 243 |
in_string = True
|
| 244 |
-
elif char ==
|
| 245 |
depth += 1
|
| 246 |
-
elif char ==
|
| 247 |
depth -= 1
|
| 248 |
if depth == 0:
|
| 249 |
-
|
| 250 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
if end == -1:
|
| 253 |
raise SchemaParseError("no balanced JSON object found in model text", text)
|
| 254 |
|
|
@@ -295,13 +325,70 @@ def _strip_code_fences(text: str) -> str:
|
|
| 295 |
return text
|
| 296 |
|
| 297 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
def extract_finding_list(text: str) -> list[dict[str, Any]]:
|
| 299 |
"""Extract a JSON array of finding dicts from raw model text.
|
| 300 |
|
| 301 |
MedGemma's native grounding output is a JSON *list* of ``{label, box_2d}``
|
| 302 |
objects rather than a wrapping object. This finds the first balanced
|
| 303 |
top-level JSON array and parses it. A bare object is tolerated and wrapped in
|
| 304 |
-
a single-element list.
|
|
|
|
|
|
|
| 305 |
|
| 306 |
Args:
|
| 307 |
text: Raw model output containing a JSON array (or a single object).
|
|
@@ -310,8 +397,9 @@ def extract_finding_list(text: str) -> list[dict[str, Any]]:
|
|
| 310 |
A list of dicts (one per finding). Non-dict array elements are rejected.
|
| 311 |
|
| 312 |
Raises:
|
| 313 |
-
SchemaParseError: If no balanced JSON array/object is found
|
| 314 |
-
|
|
|
|
| 315 |
"""
|
| 316 |
stripped = _strip_code_fences(text)
|
| 317 |
|
|
@@ -322,37 +410,20 @@ def extract_finding_list(text: str) -> list[dict[str, Any]]:
|
|
| 322 |
if array_start == -1 or (object_start != -1 and object_start < array_start):
|
| 323 |
return [extract_first_json_object(stripped)]
|
| 324 |
|
| 325 |
-
|
| 326 |
-
in_string = False
|
| 327 |
-
escaped = False
|
| 328 |
-
end = -1
|
| 329 |
-
for index in range(array_start, len(stripped)):
|
| 330 |
-
char = stripped[index]
|
| 331 |
-
if in_string:
|
| 332 |
-
if escaped:
|
| 333 |
-
escaped = False
|
| 334 |
-
elif char == "\\":
|
| 335 |
-
escaped = True
|
| 336 |
-
elif char == '"':
|
| 337 |
-
in_string = False
|
| 338 |
-
continue
|
| 339 |
-
if char == '"':
|
| 340 |
-
in_string = True
|
| 341 |
-
elif char == "[":
|
| 342 |
-
depth += 1
|
| 343 |
-
elif char == "]":
|
| 344 |
-
depth -= 1
|
| 345 |
-
if depth == 0:
|
| 346 |
-
end = index
|
| 347 |
-
break
|
| 348 |
-
|
| 349 |
if end == -1:
|
|
|
|
|
|
|
|
|
|
| 350 |
raise SchemaParseError("no balanced JSON array found in model text", text)
|
| 351 |
|
| 352 |
candidate = stripped[array_start : end + 1]
|
| 353 |
try:
|
| 354 |
parsed = json.loads(candidate)
|
| 355 |
except json.JSONDecodeError as exc:
|
|
|
|
|
|
|
|
|
|
| 356 |
raise SchemaParseError(f"candidate JSON array is invalid: {exc}", text) from exc
|
| 357 |
|
| 358 |
if not isinstance(parsed, list):
|
|
|
|
| 202 |
super().__init__(message)
|
| 203 |
self.raw_text = raw_text
|
| 204 |
|
| 205 |
+
def __reduce__(self) -> tuple[type[SchemaParseError], tuple[str, str]]:
|
| 206 |
+
"""Support pickling across process boundaries (for example a GPU worker).
|
| 207 |
|
| 208 |
+
The default exception reduction re-invokes the class with ``self.args``
|
| 209 |
+
only, which omits the required ``raw_text`` argument; returning both
|
| 210 |
+
constructor arguments keeps the error fully reconstructable.
|
| 211 |
|
| 212 |
+
Returns:
|
| 213 |
+
The ``(callable, args)`` pair pickle uses to rebuild the error.
|
| 214 |
+
"""
|
| 215 |
+
return (type(self), (str(self.args[0]) if self.args else "", self.raw_text))
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def _find_balanced_end(text: str, start: int, open_char: str, close_char: str) -> int:
|
| 219 |
+
"""Find the index of the close delimiter balancing ``text[start]``.
|
| 220 |
+
|
| 221 |
+
Walks the string from ``start`` (which must point at ``open_char``) tracking
|
| 222 |
+
nesting depth while respecting JSON string literals and escape sequences, so
|
| 223 |
+
a delimiter inside a quoted string never affects the depth count.
|
| 224 |
|
| 225 |
Args:
|
| 226 |
+
text: The text to scan.
|
| 227 |
+
start: Index of the opening delimiter to balance.
|
| 228 |
+
open_char: The opening delimiter (for example ``"{"`` or ``"["``).
|
| 229 |
+
close_char: The matching closing delimiter (``"}"`` or ``"]"``).
|
| 230 |
|
| 231 |
Returns:
|
| 232 |
+
The index of the balancing close delimiter, or ``-1`` when the text ends
|
| 233 |
+
before the delimiter closes.
|
|
|
|
|
|
|
|
|
|
| 234 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
depth = 0
|
| 236 |
in_string = False
|
| 237 |
escaped = False
|
|
|
|
| 238 |
for index in range(start, len(text)):
|
| 239 |
char = text[index]
|
| 240 |
if in_string:
|
|
|
|
| 247 |
continue
|
| 248 |
if char == '"':
|
| 249 |
in_string = True
|
| 250 |
+
elif char == open_char:
|
| 251 |
depth += 1
|
| 252 |
+
elif char == close_char:
|
| 253 |
depth -= 1
|
| 254 |
if depth == 0:
|
| 255 |
+
return index
|
| 256 |
+
return -1
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def extract_first_json_object(text: str) -> dict[str, Any]:
|
| 260 |
+
"""Extract the first balanced top-level JSON object from raw model text.
|
| 261 |
+
|
| 262 |
+
Vision-language models frequently wrap their JSON in prose, markdown code
|
| 263 |
+
fences, or trailing commentary. This scans for the first ``{`` and walks the
|
| 264 |
+
string tracking brace depth (while respecting JSON string literals and escape
|
| 265 |
+
sequences) to find the matching close brace, then parses that slice.
|
| 266 |
|
| 267 |
+
Args:
|
| 268 |
+
text: Raw model output that contains a JSON object somewhere inside it.
|
| 269 |
+
|
| 270 |
+
Returns:
|
| 271 |
+
The parsed object as a dict.
|
| 272 |
+
|
| 273 |
+
Raises:
|
| 274 |
+
SchemaParseError: If no balanced JSON object is found, or the candidate
|
| 275 |
+
slice is not valid JSON, or the top-level value is not an object.
|
| 276 |
+
"""
|
| 277 |
+
start = text.find("{")
|
| 278 |
+
if start == -1:
|
| 279 |
+
raise SchemaParseError("no JSON object found in model text", text)
|
| 280 |
+
|
| 281 |
+
end = _find_balanced_end(text, start, "{", "}")
|
| 282 |
if end == -1:
|
| 283 |
raise SchemaParseError("no balanced JSON object found in model text", text)
|
| 284 |
|
|
|
|
| 325 |
return text
|
| 326 |
|
| 327 |
|
| 328 |
+
# Upper bound on elements recovered by ``salvage_finding_list``. A degenerate
|
| 329 |
+
# repetition loop can emit the same element until the token budget is exhausted;
|
| 330 |
+
# the cap bounds the salvage work while comfortably exceeding any realistic
|
| 331 |
+
# finding count for one image.
|
| 332 |
+
_SALVAGE_MAX_ELEMENTS: int = 64
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def salvage_finding_list(text: str) -> list[dict[str, Any]]:
|
| 336 |
+
"""Recover the complete leading elements of a truncated or malformed array.
|
| 337 |
+
|
| 338 |
+
A generation that exhausts its token budget mid-array leaves the JSON array
|
| 339 |
+
unclosed (or its tail malformed), which would otherwise discard every element
|
| 340 |
+
the model emitted. This walks the array's elements from the first ``[``,
|
| 341 |
+
extracting each balanced ``{...}`` slice and parsing it independently, and
|
| 342 |
+
stops at the first incomplete or invalid element, at the array's closing
|
| 343 |
+
bracket, or after ``_SALVAGE_MAX_ELEMENTS`` elements - so the complete
|
| 344 |
+
leading elements survive a broken tail. Markdown code fences are stripped
|
| 345 |
+
before scanning.
|
| 346 |
+
|
| 347 |
+
Args:
|
| 348 |
+
text: Raw model output containing at least the head of a JSON array.
|
| 349 |
+
|
| 350 |
+
Returns:
|
| 351 |
+
The successfully recovered element dicts, possibly empty.
|
| 352 |
+
"""
|
| 353 |
+
stripped = _strip_code_fences(text)
|
| 354 |
+
array_start = stripped.find("[")
|
| 355 |
+
if array_start == -1:
|
| 356 |
+
return []
|
| 357 |
+
|
| 358 |
+
elements: list[dict[str, Any]] = []
|
| 359 |
+
cursor = array_start + 1
|
| 360 |
+
while len(elements) < _SALVAGE_MAX_ELEMENTS:
|
| 361 |
+
element_start = stripped.find("{", cursor)
|
| 362 |
+
if element_start == -1:
|
| 363 |
+
break
|
| 364 |
+
# A closing bracket between elements means the array ended; anything
|
| 365 |
+
# after it lies outside the array and must not be salvaged into it.
|
| 366 |
+
if "]" in stripped[cursor:element_start]:
|
| 367 |
+
break
|
| 368 |
+
element_end = _find_balanced_end(stripped, element_start, "{", "}")
|
| 369 |
+
if element_end == -1:
|
| 370 |
+
break
|
| 371 |
+
candidate = stripped[element_start : element_end + 1]
|
| 372 |
+
try:
|
| 373 |
+
parsed = json.loads(candidate)
|
| 374 |
+
except json.JSONDecodeError:
|
| 375 |
+
break
|
| 376 |
+
if not isinstance(parsed, dict):
|
| 377 |
+
break
|
| 378 |
+
elements.append(parsed)
|
| 379 |
+
cursor = element_end + 1
|
| 380 |
+
return elements
|
| 381 |
+
|
| 382 |
+
|
| 383 |
def extract_finding_list(text: str) -> list[dict[str, Any]]:
|
| 384 |
"""Extract a JSON array of finding dicts from raw model text.
|
| 385 |
|
| 386 |
MedGemma's native grounding output is a JSON *list* of ``{label, box_2d}``
|
| 387 |
objects rather than a wrapping object. This finds the first balanced
|
| 388 |
top-level JSON array and parses it. A bare object is tolerated and wrapped in
|
| 389 |
+
a single-element list. When the array never closes or its slice is invalid
|
| 390 |
+
JSON (a truncated or degenerate generation), the complete leading elements
|
| 391 |
+
are recovered via ``salvage_finding_list`` before declaring failure.
|
| 392 |
|
| 393 |
Args:
|
| 394 |
text: Raw model output containing a JSON array (or a single object).
|
|
|
|
| 397 |
A list of dicts (one per finding). Non-dict array elements are rejected.
|
| 398 |
|
| 399 |
Raises:
|
| 400 |
+
SchemaParseError: If no balanced JSON array/object is found and nothing
|
| 401 |
+
can be salvaged, the slice is invalid JSON and nothing can be
|
| 402 |
+
salvaged, or a well-formed array contains a non-object element.
|
| 403 |
"""
|
| 404 |
stripped = _strip_code_fences(text)
|
| 405 |
|
|
|
|
| 410 |
if array_start == -1 or (object_start != -1 and object_start < array_start):
|
| 411 |
return [extract_first_json_object(stripped)]
|
| 412 |
|
| 413 |
+
end = _find_balanced_end(stripped, array_start, "[", "]")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 414 |
if end == -1:
|
| 415 |
+
salvaged = salvage_finding_list(text)
|
| 416 |
+
if salvaged:
|
| 417 |
+
return salvaged
|
| 418 |
raise SchemaParseError("no balanced JSON array found in model text", text)
|
| 419 |
|
| 420 |
candidate = stripped[array_start : end + 1]
|
| 421 |
try:
|
| 422 |
parsed = json.loads(candidate)
|
| 423 |
except json.JSONDecodeError as exc:
|
| 424 |
+
salvaged = salvage_finding_list(text)
|
| 425 |
+
if salvaged:
|
| 426 |
+
return salvaged
|
| 427 |
raise SchemaParseError(f"candidate JSON array is invalid: {exc}", text) from exc
|
| 428 |
|
| 429 |
if not isinstance(parsed, list):
|