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
42 changes: 41 additions & 1 deletion src/extract_bench/inference/providers/extract/datalab.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import os
import time
from collections.abc import Mapping, Sequence
from copy import deepcopy
from datetime import datetime
from pathlib import Path
from typing import Any, Literal
Expand Down Expand Up @@ -77,6 +78,45 @@ class ConfidencePollingStatusValues:
POLL_ERROR: ConfidencePollingStatus = "poll_error"


def _fast_request_schema(schema: dict[str, Any]) -> dict[str, Any]:
"""Fast accepts nullable string array elements when their types are expressed with anyOf."""
result = deepcopy(schema)
pending = [result]
while len(pending) > 0:
node = pending.pop()
if not isinstance(node, dict):
continue
items = node.get("items")
if isinstance(items, dict) and items.get("type") == ["string", "null"] and "anyOf" not in items:
del items["type"]
items["anyOf"] = [{"type": "string"}, {"type": "null"}]

# Follow subschemas, including local definitions. Property names and literal
# values (such as examples, defaults and const) can themselves look like schemas.
for key, value in node.items():
if key in ("properties", "patternProperties", "$defs", "definitions", "dependentSchemas", "dependencies"):
if isinstance(value, dict):
pending.extend(value.values())
elif key in ("allOf", "anyOf", "oneOf", "prefixItems", "items") and isinstance(value, list):
pending.extend(value)
elif key in (
"items",
"contains",
"additionalItems",
"unevaluatedItems",
"additionalProperties",
"unevaluatedProperties",
"propertyNames",
"contentSchema",
"if",
"then",
"else",
"not",
):
pending.append(value)
return result


@register_provider("datalab_extract")
class DatalabExtractProvider(Provider):
"""
Expand Down Expand Up @@ -154,7 +194,7 @@ async def _extract_pdf_async(self, pdf_path: str, schema: dict[str, Any]) -> dic
extraction_started = time.perf_counter()
pdf_page_count = _read_pdf_page_count(pdf_path)
options = ExtractOptions(
page_schema=json.dumps(schema),
page_schema=json.dumps(_fast_request_schema(schema) if self._extraction_mode == "fast" else schema),
citation_granularity="phrase",
mode=self._parse_mode,
output_format=self._output_format,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import asyncio
import json
from copy import deepcopy
from pathlib import Path
from types import SimpleNamespace

Expand Down Expand Up @@ -58,9 +59,19 @@ async def run() -> None:
"type": "object",
"properties": {
"total": {"type": ["number", "null"]},
"items": {"type": ["string", "null"]},
"rows": {"type": "array", "items": {"$ref": "#/$defs/Row"}},
"bank": {"type": ["object", "null"], "properties": {"name": {"type": "string"}}},
},
}
schema["$defs"] = {
"Row": {
"type": "array",
"items": {"type": ["string", "null"], "maxLength": 12},
"examples": [{"items": {"type": ["string", "null"]}}],
},
}
original = deepcopy(schema)
submitted_schemas = []
calls = {"submit": 0, "poll": 0}
clock = {"now": 0.0}
Expand Down Expand Up @@ -165,7 +176,11 @@ async def download(request: web.Request) -> web.Response:
return
with budget.activate():
result = await budget.run_async(provider._extract_pdf_async(str(source), schema))
assert submitted_schemas == [schema]
assert schema == original
expected = deepcopy(original)
if extraction_mode == "fast":
expected["$defs"]["Row"]["items"] = {"anyOf": [{"type": "string"}, {"type": "null"}], "maxLength": 12}
assert submitted_schemas == [expected]
assert json.loads(result["extraction_schema_json"])["total"] == 10
assert result["_config"]["citation_granularity"] == "phrase"
assert calls["submit"] == 1
Expand Down
Loading