File size: 1,500 Bytes
7825400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""JSON Schema used to constrain hosted detection responses."""

import copy
import hashlib
import json


DETECTION_ARRAY_SCHEMA: dict = {
    "type": "array",
    "maxItems": 50,
    "items": {
        "type": "object",
        "properties": {
            "category_id": {"type": "integer", "minimum": 1, "maximum": 97},
            "bbox": {
                "type": "array",
                "items": {"type": "number"},
                "minItems": 4,
                "maxItems": 4,
            },
            "score": {"type": "number", "minimum": 0.0, "maximum": 1.0},
        },
        "required": ["category_id", "bbox", "score"],
        "additionalProperties": False,
    },
}


def detection_response_format(*, omit_array_cap: bool = False) -> dict:
    """OpenAI-compatible strict response format for a detection array."""
    schema = copy.deepcopy(DETECTION_ARRAY_SCHEMA)
    if omit_array_cap:
        schema.pop("maxItems")
    return {
        "type": "json_schema",
        "json_schema": {
            "name": "municipal_detections",
            "strict": True,
            "schema": schema,
        },
    }


def detection_schema_hash(*, omit_array_cap: bool = False) -> str:
    """Stable identity of the schema, independent of dict formatting."""
    encoded = json.dumps(
        detection_response_format(omit_array_cap=omit_array_cap)["json_schema"]["schema"],
        sort_keys=True, separators=(",", ":")
    ).encode("utf-8")
    return hashlib.sha256(encoded).hexdigest()