File size: 11,177 Bytes
8ebf922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
"""Verify Ideogram 4 JSON caption format."""

import json
import re
from pathlib import Path
from typing import Sequence

PathLike = str | Path

NON_ASCII_UNICODE_ESCAPE_RE = re.compile(
  r"\\u(?:00[89a-fA-F][0-9a-fA-F]|0[1-9a-fA-F][0-9a-fA-F]{2}|[1-9a-fA-F][0-9a-fA-F]{3})"
)


class CaptionVerifier:
  """Verify Ideogram 4 JSON caption format.

  All ``verify_*`` methods return a list of warning strings (empty means
  the input passed all checks).
  """

  top_level_known_keys: frozenset[str] = frozenset(
    {
      "high_level_description",
      "style_description",
      "compositional_deconstruction",
    }
  )

  style_description_key_order_photo: Sequence[str] = (
    "aesthetics",
    "lighting",
    "photo",
    "medium",
    "color_palette",
  )

  style_description_key_order_non_photo: Sequence[str] = (
    "aesthetics",
    "lighting",
    "medium",
    "art_style",
    "color_palette",
  )

  compositional_deconstruction_key_order: Sequence[str] = (
    "background",
    "elements",
  )

  element_key_order_obj: Sequence[str] = ("type", "bbox", "desc", "color_palette")
  element_key_order_text: Sequence[str] = (
    "type",
    "bbox",
    "text",
    "desc",
    "color_palette",
  )

  style_description_known_keys: frozenset[str] = frozenset(
    {
      "aesthetics",
      "lighting",
      "photo",
      "art_style",
      "medium",
      "color_palette",
    }
  )

  element_known_keys: frozenset[str] = frozenset(
    {
      "type",
      "bbox",
      "text",
      "desc",
      "color_palette",
    }
  )

  element_types: frozenset[str] = frozenset({"obj", "text"})

  bbox_min: int = 0
  bbox_max: int = 1000

  style_description_palette_max: int = 16
  element_palette_max: int = 5

  def verify(self, caption: dict) -> list[str]:
    """Verify a parsed caption dict. Returns a list of warnings."""
    warnings: list[str] = []

    if not isinstance(caption, dict):
      warnings.append(
        f"root: expected a JSON object (dict), got {type(caption).__name__}"
      )
      return warnings

    self._check_unknown_keys(caption, self.top_level_known_keys, "root", warnings)

    if "high_level_description" in caption:
      self._verify_high_level_description(caption["high_level_description"], warnings)

    if "style_description" in caption:
      self._verify_style_description(caption["style_description"], warnings)

    if "compositional_deconstruction" in caption:
      self._verify_compositional_deconstruction(
        caption["compositional_deconstruction"], warnings
      )
    else:
      warnings.append("root: 'compositional_deconstruction' must exist")

    return warnings

  def verify_raw(self, raw_text: str) -> list[str]:
    """Verify a raw JSON string. Includes ensure_ascii=False check."""
    warnings = self.check_ensure_ascii_false(raw_text)
    try:
      caption = json.loads(raw_text)
    except json.JSONDecodeError as e:
      warnings.append(f"invalid JSON: {e}")
      return warnings
    return warnings + self.verify(caption)

  def verify_file(self, path: PathLike) -> list[str]:
    """Verify a JSON file on disk."""
    raw = Path(path).read_text(encoding="utf-8")
    return self.verify_raw(raw)

  # Warn if raw text contains \uXXXX escapes for non-ASCII chars but no literal non-ASCII;
  # typically means the writer used ensure_ascii=True. Suppressed when both forms coexist
  # (escapes are then assumed intentional).
  @classmethod
  def check_ensure_ascii_false(cls, raw_text: str, max_examples: int = 3) -> list[str]:
    warnings: list[str] = []
    matches = NON_ASCII_UNICODE_ESCAPE_RE.findall(raw_text)
    if not matches:
      return warnings

    has_literal_non_ascii = any(ord(c) > 0x7F for c in raw_text)
    if has_literal_non_ascii:
      return warnings

    examples = ", ".join(sorted(set(matches))[:max_examples])
    extra = "" if len(set(matches)) <= max_examples else ", ..."
    warnings.append(
      f"raw text: found {len(matches)} non-ASCII unicode escape(s) "
      f"(e.g. {examples}{extra}) and no literal non-ASCII characters. "
      f"This usually means the file was saved with ensure_ascii=True; "
      f"please re-save with json.dump(..., ensure_ascii=False) so non-ASCII "
      f"characters are stored as literal UTF-8. "
      f"Note: this is a warning, not an error, because the escapes could "
      f"have been written intentionally — we cannot tell from the file alone."
    )
    return warnings

  def _verify_high_level_description(self, hld, warnings: list[str]) -> None:
    if not isinstance(hld, str):
      warnings.append(
        f"high_level_description: expected a string, got {type(hld).__name__}"
      )

  def _verify_style_description(self, sd, warnings: list[str]) -> None:
    if not isinstance(sd, dict):
      warnings.append("style_description: expected a dict")
      return
    self._check_unknown_keys(
      sd, self.style_description_known_keys, "style_description", warnings
    )
    has_photo = "photo" in sd
    has_art_style = "art_style" in sd
    if has_photo and has_art_style:
      warnings.append(
        "style_description: contains both 'photo' and 'art_style'; expected exactly one"
      )
      return
    elif not has_photo and not has_art_style:
      warnings.append(
        "style_description: expected one of 'photo' (for photo captions) "
        "or 'art_style' (for non-photo captions)"
      )
      return

    self._check_key_order(
      sd,
      self._style_description_key_order(sd),
      "style_description",
      warnings,
    )

    if "color_palette" in sd:
      self._verify_color_palette(
        sd["color_palette"],
        "style_description.color_palette",
        self.style_description_palette_max,
        warnings,
      )

  def _verify_compositional_deconstruction(self, cd, warnings: list[str]) -> None:
    if not isinstance(cd, dict):
      warnings.append("compositional_deconstruction: expected a dict")
      return
    if "background" not in cd:
      warnings.append("compositional_deconstruction: 'background' must exist")
      return
    elif not isinstance(cd["background"], str):
      warnings.append(
        f"compositional_deconstruction.background: expected a string, "
        f"got {type(cd['background']).__name__}"
      )
      return
    if "elements" not in cd:
      warnings.append("compositional_deconstruction: 'elements' must exist")
      return
    self._check_key_order(
      cd,
      self.compositional_deconstruction_key_order,
      "compositional_deconstruction",
      warnings,
    )
    elements = cd["elements"]
    if not isinstance(elements, list):
      warnings.append("compositional_deconstruction.elements: expected a list")
      return
    for i, elem in enumerate(elements):
      self._verify_element(i, elem, warnings)

  def _verify_element(self, i: int, elem, warnings: list[str]) -> None:
    if not isinstance(elem, dict):
      warnings.append(f"elements[{i}]: expected a dict")
      return
    self._check_unknown_keys(elem, self.element_known_keys, f"elements[{i}]", warnings)

    if "type" not in elem:
      warnings.append(f"elements[{i}]: 'type' must exist")
      return
    elif elem.get("type", None) not in self.element_types:
      warnings.append(f"elements[{i}]: 'type' must be one of {self.element_types}")
      return

    self._check_key_order(
      elem, self._element_key_order(elem), f"elements[{i}]", warnings
    )

    if "bbox" in elem:
      self._verify_bbox(i, elem["bbox"], warnings)

    if "color_palette" in elem:
      self._verify_color_palette(
        elem["color_palette"],
        f"elements[{i}].color_palette",
        self.element_palette_max,
        warnings,
      )

  def _verify_color_palette(
    self, palette, path: str, max_colors: int, warnings: list[str]
  ) -> None:
    if not isinstance(palette, list):
      warnings.append(f"{path}: expected a list")
      return
    if len(palette) > max_colors:
      warnings.append(
        f"{path}: too many colors ({len(palette)}), expected at most {max_colors}"
      )
      return

    for i, color in enumerate(palette):
      if (
        not isinstance(color, str)
        or len(color) != 7
        or color[0] != "#"
        or not all(c in "0123456789ABCDEF" for c in color[1:])
      ):
        warnings.append(f"{path}[{i}]: '{color}' is not a valid #RRGGBB hex color")

  def _verify_bbox(self, i: int, bbox, warnings: list[str]) -> None:
    if not isinstance(bbox, list) or len(bbox) != 4:
      warnings.append(f"elements[{i}].bbox: expected [ymin, xmin, ymax, xmax]")
      return
    if not all(isinstance(v, int) for v in bbox):
      warnings.append(f"elements[{i}].bbox: all values must be int")
      return
    ymin, xmin, ymax, xmax = bbox
    if not all(self.bbox_min <= v <= self.bbox_max for v in bbox):
      warnings.append(
        f"elements[{i}].bbox: values must be in "
        f"[{self.bbox_min}, {self.bbox_max}], got {bbox}"
      )
    if ymin > ymax:
      warnings.append(f"elements[{i}].bbox: ymin ({ymin}) > ymax ({ymax})")
    if xmin > xmax:
      warnings.append(f"elements[{i}].bbox: xmin ({xmin}) > xmax ({xmax})")

  def _element_key_order(self, element: dict) -> Sequence[str]:
    elem_type = element.get("type", None)

    if elem_type == "text":
      element_key_order = self.element_key_order_text
    elif elem_type == "obj":
      element_key_order = self.element_key_order_obj
    else:
      raise ValueError

    element_key_order_ = []
    for key in element_key_order:
      if key == "bbox":
        if "bbox" in element:
          element_key_order_.append(key)
      elif key == "color_palette":
        if "color_palette" in element:
          element_key_order_.append(key)
      else:
        element_key_order_.append(key)

    return tuple(element_key_order_)

  def _style_description_key_order(self, sd: dict) -> Sequence[str]:
    has_photo = "photo" in sd
    has_art_style = "art_style" in sd
    if has_art_style and not has_photo:
      key_order = self.style_description_key_order_non_photo
    elif not has_art_style and has_photo:
      key_order = self.style_description_key_order_photo
    else:
      raise ValueError

    key_order_ = []
    for key in key_order:
      if key == "color_palette":
        if "color_palette" in sd:
          key_order_.append(key)
      else:
        key_order_.append(key)

    return tuple(key_order_)

  @staticmethod
  def _check_key_order(
    obj: dict,
    expected_order: Sequence[str],
    path: str,
    warnings: list[str],
  ) -> None:
    present_keys = tuple([k for k in obj if k in expected_order])
    if present_keys != tuple(expected_order):
      warnings.append(f"{path}: key order is {present_keys}, expected {expected_order}")
    extra = [k for k in obj if k not in expected_order]
    if extra:
      warnings.append(f"{path}: keys {extra} are not allowed in this context")

  @staticmethod
  def _check_unknown_keys(
    obj: dict,
    known: frozenset[str],
    path: str,
    warnings: list[str],
  ) -> None:
    unknown = [k for k in obj if k not in known]
    if unknown:
      warnings.append(f"{path}: unknown keys {unknown} (not in schema)")