processing_kosmos2.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. # Copyright 2023 Microsoft Research and The HuggingFace Inc. team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Processor class for KOSMOS-2."""
  15. import copy
  16. import math
  17. import re
  18. from ...image_processing_utils import BatchFeature
  19. from ...image_utils import ImageInput
  20. from ...processing_utils import ImagesKwargs, ProcessingKwargs, ProcessorMixin, TextKwargs, Unpack
  21. from ...tokenization_python import AddedToken
  22. from ...tokenization_utils_base import BatchEncoding, TextInput
  23. from ...utils import auto_docstring
  24. BboxInput = (
  25. list[tuple[int, int]]
  26. | list[tuple[float, float, float, float]]
  27. | list[list[tuple[int, int]]]
  28. | list[list[tuple[float, float, float]]]
  29. )
  30. NestedList = list[tuple | None | list[tuple | None | list[tuple | None | list[tuple | None]]]]
  31. class Kosmos2ImagesKwargs(ImagesKwargs, total=False):
  32. """
  33. bboxes (`Union[list[tuple[int]], list[tuple[float]], list[list[tuple[int]]], list[list[tuple[float]]]]`, *optional*):
  34. The bounding bboxes associated to `texts`.
  35. num_image_tokens (`int`, *optional* defaults to 64):
  36. The number of (consecutive) places that are used to mark the placeholders to store image information.
  37. This should be the same as `latent_query_num` in the instance of `Kosmos2Config` you are using.
  38. first_image_token_id (`int`, *optional*):
  39. The token id that will be used for the first place of the subsequence that is reserved to store image
  40. information. If unset, will default to `self.tokenizer.unk_token_id + 1`.
  41. """
  42. bboxes: NestedList | None # NOTE: hub validators can't accept `Sequence`
  43. num_image_tokens: int
  44. first_image_token_id: int | None
  45. class Kosmos2TextKwargs(TextKwargs, total=False):
  46. """
  47. add_eos_token (`bool`, defaults to `False`):
  48. Whether or not to include `EOS` token id in the encoding when `add_special_tokens=True`.
  49. """
  50. add_eos_token: bool
  51. class Kosmos2ProcessorKwargs(ProcessingKwargs, total=False):
  52. text_kwargs: Kosmos2TextKwargs
  53. images_kwargs: Kosmos2ImagesKwargs
  54. _defaults = {
  55. "text_kwargs": {
  56. "add_special_tokens": True,
  57. "padding": False,
  58. "stride": 0,
  59. "return_overflowing_tokens": False,
  60. "return_special_tokens_mask": False,
  61. "return_offsets_mapping": False,
  62. "return_token_type_ids": False,
  63. "verbose": True,
  64. "add_eos_token": False,
  65. },
  66. "images_kwargs": {
  67. "num_image_tokens": 64,
  68. },
  69. }
  70. @auto_docstring
  71. class Kosmos2Processor(ProcessorMixin):
  72. def __init__(self, image_processor, tokenizer, num_patch_index_tokens=1024, *kwargs):
  73. r"""
  74. num_patch_index_tokens (`int`, *optional*, defaults to 1024):
  75. The number of tokens that represent patch indices.
  76. """
  77. tokenizer.return_token_type_ids = False
  78. self.eod_token = "</doc>"
  79. self.boi_token = "<image>"
  80. self.eoi_token = "</image>"
  81. self.eoc_token = "</chunk>"
  82. self.eol_token = "</line>"
  83. self.bop_token = "<phrase>"
  84. self.eop_token = "</phrase>"
  85. self.boo_token = "<object>"
  86. self.eoo_token = "</object>"
  87. self.dom_token = "</delimiter_of_multi_objects/>"
  88. self.grd_token = "<grounding>"
  89. self.tag_tokens = [
  90. self.eod_token,
  91. self.boi_token,
  92. self.eoi_token,
  93. self.eoc_token,
  94. self.eol_token,
  95. self.bop_token,
  96. self.eop_token,
  97. self.boo_token,
  98. self.eoo_token,
  99. self.dom_token,
  100. self.grd_token,
  101. ]
  102. self.num_patch_index_tokens = num_patch_index_tokens
  103. patch_index_tokens = [f"<patch_index_{str(x).zfill(4)}>" for x in range(self.num_patch_index_tokens)]
  104. tokens_to_add = []
  105. for token in self.tag_tokens + patch_index_tokens:
  106. tokens_to_add.append(AddedToken(token, lstrip=True, rstrip=False, normalized=False))
  107. tokenizer.add_tokens(tokens_to_add)
  108. super().__init__(image_processor, tokenizer)
  109. @auto_docstring
  110. def __call__(
  111. self,
  112. images: ImageInput | None = None,
  113. text: TextInput | list[TextInput] = None,
  114. **kwargs: Unpack[Kosmos2ProcessorKwargs],
  115. ) -> BatchFeature:
  116. if images is None and text is None:
  117. raise ValueError("You have to specify either images or text.")
  118. output_kwargs = self._merge_kwargs(
  119. Kosmos2ProcessorKwargs,
  120. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  121. **kwargs,
  122. )
  123. bboxes = output_kwargs["images_kwargs"].pop("bboxes", None)
  124. num_image_tokens = output_kwargs["images_kwargs"].pop("num_image_tokens", 64)
  125. first_image_token_id = output_kwargs["images_kwargs"].pop("first_image_token_id", None)
  126. add_eos_token = output_kwargs["text_kwargs"].pop("add_eos_token", False)
  127. add_special_tokens = output_kwargs["text_kwargs"]["add_special_tokens"]
  128. padding = output_kwargs["text_kwargs"]["padding"]
  129. return_tensors = output_kwargs["text_kwargs"].setdefault("return_tensors", None)
  130. encoding = BatchFeature()
  131. if images is not None:
  132. image_encoding = self.image_processor(images, **output_kwargs["images_kwargs"])
  133. encoding.update(image_encoding)
  134. if text is not None:
  135. text = self.preprocess_examples(text, images, bboxes, num_image_tokens=num_image_tokens)
  136. if add_special_tokens and not add_eos_token:
  137. if isinstance(text, str):
  138. text = f"{self.tokenizer.bos_token}{text}"
  139. elif isinstance(text, list):
  140. text = [f"{self.tokenizer.bos_token}{s}" for s in text]
  141. output_kwargs["text_kwargs"]["add_special_tokens"] = (
  142. output_kwargs["text_kwargs"]["add_special_tokens"] and add_eos_token
  143. )
  144. output_kwargs["text_kwargs"]["padding"] = padding if images is None else False
  145. output_kwargs["text_kwargs"]["return_tensors"] = return_tensors if images is None else None
  146. text_encoding = self.tokenizer(text=text, **output_kwargs["text_kwargs"])
  147. encoding.update(text_encoding)
  148. output_kwargs["text_kwargs"]["add_special_tokens"] = add_special_tokens
  149. output_kwargs["text_kwargs"]["padding"] = padding
  150. output_kwargs["text_kwargs"]["return_tensors"] = return_tensors
  151. if text is not None and images is not None:
  152. # Use the id of the first token after <unk>
  153. if first_image_token_id is None:
  154. first_image_token_id = self.tokenizer.unk_token_id + 1
  155. # To see if we need one more `0` (for `<s>`) at the beginning of `image_embeds_position_mask`.
  156. with_bos = add_special_tokens
  157. # The first (actual) `<image>` token is always at the 1st or 2nd place (after `<s>` if any). Here we look
  158. # for the second `<image>` token (which indicate the first image token).
  159. start_index = int(with_bos) + 1
  160. # Add `image_embeds_position_mask`: the leading and trailing `0` are for `boi` and `eoi` tokens. The `1` indicates
  161. # the places of image tokens.
  162. image_token_ids = list(range(first_image_token_id, first_image_token_id + num_image_tokens))
  163. base_image_embeds_position_mask = [0] + [1] * num_image_tokens + [0]
  164. # loop over `encoding["input_ids"]`
  165. input_ids = []
  166. image_embeds_position_mask = []
  167. all_input_ids = encoding["input_ids"]
  168. # not batched -> (changed to) batch of size 1
  169. if isinstance(text, str):
  170. all_input_ids = [all_input_ids]
  171. encoding["attention_mask"] = [encoding["attention_mask"]]
  172. for text_ids in all_input_ids:
  173. # change the ids for the fake `<image>` tokens in `input_ids`
  174. text_ids = text_ids[:start_index] + image_token_ids + text_ids[start_index + num_image_tokens :]
  175. input_ids.append(text_ids)
  176. mask = copy.copy(base_image_embeds_position_mask)
  177. if with_bos:
  178. # for `<s>`
  179. mask = [0] + mask
  180. # trailing part (which are not related to the image)
  181. mask += [0] * (len(text_ids) - len(mask))
  182. image_embeds_position_mask.append(mask)
  183. if isinstance(text, list):
  184. sorted_length = sorted(
  185. [(idx, len(x)) for idx, x in enumerate(text_encoding.input_ids)], key=lambda x: x[-1]
  186. )
  187. _, min_len_not_padded = sorted_length[0]
  188. idx, _ = sorted_length[-1]
  189. output_kwargs["text_kwargs"]["add_special_tokens"] = (
  190. output_kwargs["text_kwargs"]["add_special_tokens"] and add_eos_token
  191. )
  192. output_kwargs["text_kwargs"]["return_tensors"] = None
  193. text_encoding = self.tokenizer(text=[text[idx]], **output_kwargs["text_kwargs"])
  194. max_len_padded = len(text_encoding.input_ids[0])
  195. if min_len_not_padded != max_len_padded:
  196. if self.tokenizer.padding_side == "right":
  197. input_ids = [x + [self.tokenizer.pad_token_id] * (max_len_padded - len(x)) for x in input_ids]
  198. image_embeds_position_mask = [
  199. x + [0] * (max_len_padded - len(x)) for x in image_embeds_position_mask
  200. ]
  201. encoding["attention_mask"] = [
  202. x + [0] * (max_len_padded - len(x)) for x in encoding["attention_mask"]
  203. ]
  204. elif self.tokenizer.padding_side == "left":
  205. input_ids = [[self.tokenizer.pad_token_id] * (max_len_padded - len(x)) + x for x in input_ids]
  206. image_embeds_position_mask = [
  207. [0] * (max_len_padded - len(x)) + x for x in image_embeds_position_mask
  208. ]
  209. encoding["attention_mask"] = [
  210. [0] * (max_len_padded - len(x)) + x for x in encoding["attention_mask"]
  211. ]
  212. # un-batch if necessary
  213. if isinstance(text, str) and return_tensors is None:
  214. input_ids = input_ids[0]
  215. encoding["attention_mask"] = encoding["attention_mask"][0]
  216. image_embeds_position_mask = image_embeds_position_mask[0]
  217. # update (with the target tensor type if specified)
  218. encoding.update(
  219. BatchEncoding(
  220. data={
  221. "input_ids": input_ids,
  222. "attention_mask": encoding["attention_mask"],
  223. "image_embeds_position_mask": image_embeds_position_mask,
  224. },
  225. tensor_type=return_tensors,
  226. )
  227. )
  228. return encoding
  229. def _check_bboxes_for_single_text(self, bboxes):
  230. """
  231. Check `bboxes` for a single text example. It could be
  232. - `None`: no bounding box associated to a text.
  233. - A list with each element being the bounding boxes associated to one `<phrase> ... </phrase>` pair found
  234. in a text. This could be:
  235. - `None`: no bounding box associated to a `<phrase> ... </phrase>` pair.
  236. - A tuple of 2 integers: A single bounding box specified by patch indices.
  237. - A tuple of 4 float point number: A single bounding box specified by (normalized) coordinates.
  238. - A list containing the above 2 tuple types: Multiple bounding boxes for a
  239. `<phrase> ... </phrase>` pair.
  240. """
  241. if bboxes is None:
  242. return
  243. elif not isinstance(bboxes, list):
  244. raise ValueError("`bboxes` (for a single text example) should be `None` or a list.")
  245. # `bbox` is the bounding boxes for a single <phrase> </phrase> pair
  246. for bbox in bboxes:
  247. if bbox is None:
  248. continue
  249. elif not isinstance(bbox, list):
  250. bbox = [bbox]
  251. for element in bbox:
  252. if not isinstance(element, tuple) or not (
  253. (len(element) == 2 and all(isinstance(x, int) for x in element))
  254. or (len(element) == 4 and all(isinstance(x, float) for x in element))
  255. ):
  256. raise ValueError(
  257. "Each element in `bboxes` (for a single text example) should be either `None`, a tuple containing "
  258. "2 integers or 4 float point numbers, or a list containing such tuples. Also "
  259. "make sure the arguments `texts` and `bboxes` passed to `preprocess_text` are both in "
  260. "batches or both for a single example."
  261. )
  262. def _preprocess_single_example(self, text, image, bboxes, img_info_tokens):
  263. text = text.strip()
  264. if image is not None:
  265. # Add `<image> ... (fake) image tokens ... </image>`
  266. text = f"{img_info_tokens} {text}"
  267. # Add `<object> <patch_idx_xxxx> <patch_idx_yyy> </object>` after `<phrase> phrase text </phrase>`
  268. text = self._insert_patch_index_tokens(text, bboxes)
  269. return text
  270. def preprocess_examples(
  271. self,
  272. texts: TextInput | list[TextInput],
  273. images: ImageInput | None = None,
  274. bboxes: BboxInput = None,
  275. num_image_tokens: int | None = 64,
  276. ) -> str | list[str]:
  277. """Add image and bounding box information to `texts` as image and patch index tokens.
  278. Args:
  279. texts (`Union[TextInput, list[TextInput]]`): The texts to be processed.
  280. images (`ImageInput`, *optional*): The images associated to `texts`.
  281. bboxes (`Union[list[tuple[int]], list[tuple[float]], list[list[tuple[int]]], list[list[tuple[float]]]]`, *optional*):
  282. The bounding bboxes associated to `texts`.
  283. num_image_tokens (`int`, *optional*, defaults to 64):
  284. The number of image tokens (used as latent queries). This should corresponds to the `latent_query_num`
  285. attribute in `Kosmos2Config`.
  286. Returns:
  287. `Union[TextInput, list[TextInput]]`: The processed texts with image and patch index tokens.
  288. """
  289. # These are fake `<image>` tokens enclosed between (the actual) `<image>` token and `</image>`.
  290. img_tokens = [self.boi_token] * num_image_tokens
  291. img_info_tokens = " ".join([self.boi_token] + img_tokens + [self.eoi_token])
  292. # make batch to simplify processing logic
  293. batched = True
  294. if isinstance(texts, str):
  295. batched = False
  296. texts = [texts]
  297. if images is None:
  298. images = [None] * len(texts)
  299. elif not isinstance(images, list):
  300. images = [images]
  301. if len(texts) != len(images):
  302. raise ValueError(
  303. f"The number of examples in `texts` and `images` should be the same. Got {len(texts)} v.s. {len(images)} instead."
  304. )
  305. if not batched:
  306. self._check_bboxes_for_single_text(bboxes)
  307. bboxes = [bboxes]
  308. elif bboxes is not None:
  309. if not isinstance(bboxes, list):
  310. raise ValueError("`bboxes` should be `None` or a list (as a batch) when `texts` is passed as a batch.")
  311. for x in bboxes:
  312. self._check_bboxes_for_single_text(x)
  313. else:
  314. bboxes = [None] * len(texts)
  315. if len(bboxes) != len(texts):
  316. raise ValueError(
  317. f"The number of examples in `texts` and `bboxes` should be the same. Got {len(texts)} v.s. {len(bboxes)} instead."
  318. )
  319. result = [
  320. self._preprocess_single_example(text, image, bbox, img_info_tokens)
  321. for text, image, bbox in zip(texts, images, bboxes)
  322. ]
  323. # un-batch if necessary
  324. if not batched:
  325. result = result[0]
  326. return result
  327. def post_process_generation(self, text, cleanup_and_extract=True):
  328. caption = text.split(self.eoi_token)[-1]
  329. if cleanup_and_extract:
  330. return clean_text_and_extract_entities_with_bboxes(caption)
  331. return caption
  332. def post_process_image_text_to_text(self, generated_outputs, skip_special_tokens=True, **kwargs):
  333. """
  334. Post-process the output of the model to decode the text.
  335. Args:
  336. generated_outputs (`torch.Tensor` or `np.ndarray`):
  337. The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`
  338. or `(sequence_length,)`.
  339. skip_special_tokens (`bool`, *optional*, defaults to `True`):
  340. Whether or not to remove special tokens in the output. Argument passed to the tokenizer's `batch_decode` method.
  341. **kwargs:
  342. Additional arguments to be passed to the tokenizer's `batch_decode method`.
  343. Returns:
  344. `list[str]`: The decoded text.
  345. """
  346. generated_texts = self.batch_decode(generated_outputs, skip_special_tokens=skip_special_tokens, **kwargs)
  347. return [self.post_process_generation(text, cleanup_and_extract=False) for text in generated_texts]
  348. @property
  349. def model_input_names(self):
  350. tokenizer_input_names = self.tokenizer.model_input_names
  351. image_processor_input_names = self.image_processor.model_input_names
  352. return tokenizer_input_names + image_processor_input_names + ["image_embeds_position_mask"]
  353. def _insert_patch_index_tokens(self, text: str, bboxes: list[tuple[int]] | list[tuple[float]]) -> str:
  354. if bboxes is None or len(bboxes) == 0:
  355. return text
  356. matched_phrases = list(re.finditer(r"<phrase>.+?</phrase>", string=text))
  357. if len(matched_phrases) != len(bboxes):
  358. raise ValueError(
  359. f"The number of elements in `bboxes` should be the same as the number of `<phrase> ... </phrase>` pairs in `text`. Got {len(matched_phrases)} v.s. {len(bboxes)} instead."
  360. )
  361. # insert object's patch index tokens
  362. # the found `<phrase> ... </phrase>` pairs.
  363. curr_pos = 0
  364. buffer = []
  365. for matched, bbox in zip(matched_phrases, bboxes):
  366. _, end = matched.span()
  367. buffer.append(text[curr_pos:end])
  368. curr_pos = end
  369. # A phrase without bbox
  370. if bbox is None:
  371. continue
  372. # A phrase with a single bbox
  373. if isinstance(bbox, tuple):
  374. bbox = [bbox]
  375. patch_index_strings = []
  376. # A phrase could have multiple bboxes
  377. if not all(box is not None for box in bbox):
  378. raise ValueError(
  379. "The multiple bounding boxes for a single phrase should not contain any `None` value."
  380. )
  381. for box in bbox:
  382. patch_index_1, patch_index_2 = self._convert_bbox_to_patch_index_tokens(box)
  383. patch_index_strings.append(f"{patch_index_1} {patch_index_2}")
  384. # `bbox` being an empty list
  385. if len(patch_index_strings) == 0:
  386. continue
  387. position_str = " </delimiter_of_multi_objects/> ".join(patch_index_strings)
  388. buffer.append(f"<object> {position_str} </object>")
  389. # remaining
  390. if curr_pos < len(text):
  391. buffer.append(text[curr_pos:])
  392. text = "".join(buffer)
  393. return text
  394. def _convert_bbox_to_patch_index_tokens(
  395. self, bbox: tuple[int, int] | tuple[float, float, float, float]
  396. ) -> tuple[str, str]:
  397. # already computed patch indices
  398. if len(bbox) == 2:
  399. idx_1, idx_2 = bbox
  400. # bbox specified with (normalized) coordinates
  401. else:
  402. # use `self.tokenizer` to get `num_patches_per_side`
  403. num_patches_per_side = int(math.sqrt(self.num_patch_index_tokens))
  404. idx_1, idx_2 = coordinate_to_patch_index(bbox, num_patches_per_side)
  405. token_1 = f"<patch_index_{str(idx_1).zfill(4)}>"
  406. token_2 = f"<patch_index_{str(idx_2).zfill(4)}>"
  407. return token_1, token_2
  408. def coordinate_to_patch_index(bbox: tuple[float, float, float, float], num_patches_per_side: int) -> tuple[int, int]:
  409. """Convert a bounding box to a pair of patch indices.
  410. Args:
  411. bbox (`tuple[float, float, float, float]`):
  412. The 4 coordinates of the bounding box, with the format being (x1, y1, x2, y2) specifying the upper-left and
  413. lower-right corners of the box. It should have x2 > x1 and y2 > y1.
  414. num_patches_per_side (`int`): the number of patches along each side.
  415. Returns:
  416. `tuple[int, int]`: A pair of patch indices representing the upper-left patch and lower-right patch.
  417. """
  418. (x1, y1, x2, y2) = bbox
  419. if not (x2 > x1 and y2 > y1):
  420. raise ValueError("The coordinates in `bbox` should be `(x1, y1, x2, y2)` with `x2 > x1` and `y2 > y1`.")
  421. ul_x = math.floor(x1 * num_patches_per_side)
  422. ul_y = math.floor(y1 * num_patches_per_side)
  423. lr_x = math.ceil(x2 * num_patches_per_side - 1)
  424. lr_y = math.ceil(y2 * num_patches_per_side - 1)
  425. ul_idx = ul_y * num_patches_per_side + ul_x
  426. lr_idx = lr_y * num_patches_per_side + lr_x
  427. return ul_idx, lr_idx
  428. # copied from https://github.com/microsoft/unilm/blob/97e4923e97d3ee10b57e97013556e3fd0d207a9b/kosmos-2/demo/decode_string.py#L35C1-L75C38
  429. # (with format modifications)
  430. def patch_index_to_coordinate(ul_idx: int, lr_idx: int, num_patches_per_side: int):
  431. """
  432. Given a grid of length `num_patches_per_side` and the indices of the upper-left and lower-right corners of a
  433. bounding box, returns the normalized coordinates of the bounding box, in the form (x1, y1, x2, y2).
  434. Args:
  435. ul_idx (`int`): the index of the grid cell that corresponds to the upper-left corner of the bounding box.
  436. lr_idx (`int`): the index of the grid cell that corresponds to the lower-right corner of the bounding box.
  437. num_patches_per_side (`int`): the number of patches along each side.
  438. Returns:
  439. `tuple[float]`: the normalized coordinates of the bounding box, in the form (x1, y1, x2, y2).
  440. """
  441. # Compute the size of each cell in the grid
  442. cell_size = 1.0 / num_patches_per_side
  443. # Compute the x and y indices of the upper-left and lower-right corners of the bounding box
  444. ul_x = ul_idx % num_patches_per_side
  445. ul_y = ul_idx // num_patches_per_side
  446. lr_x = lr_idx % num_patches_per_side
  447. lr_y = lr_idx // num_patches_per_side
  448. # Compute the normalized coordinates of the bounding box
  449. if ul_idx == lr_idx:
  450. x1 = ul_x * cell_size
  451. y1 = ul_y * cell_size
  452. x2 = lr_x * cell_size + cell_size
  453. y2 = lr_y * cell_size + cell_size
  454. elif ul_x == lr_x or ul_y == lr_y:
  455. x1 = ul_x * cell_size
  456. y1 = ul_y * cell_size
  457. x2 = lr_x * cell_size + cell_size
  458. y2 = lr_y * cell_size + cell_size
  459. else:
  460. x1 = ul_x * cell_size + cell_size / 2
  461. y1 = ul_y * cell_size + cell_size / 2
  462. x2 = lr_x * cell_size + cell_size / 2
  463. y2 = lr_y * cell_size + cell_size / 2
  464. return x1, y1, x2, y2
  465. # copied from https://github.com/microsoft/unilm/blob/97e4923e97d3ee10b57e97013556e3fd0d207a9b/kosmos-2/demo/decode_string.py#L4-L33
  466. # (with format modifications)
  467. def extract_entities_with_patch_indices(text):
  468. """Extract entities contained in `text`. The bounding bboxes is given in the form of patch indices.
  469. This function is only intended to be used within `clean_text_and_extract_entities_with_bboxes` where further
  470. processing happens, including converting to normalized coordinates and whitespace character cleaning up.
  471. Examples:
  472. ```python
  473. >>> text = "<grounding> An image of<phrase> a snowman</phrase><object><patch_index_0044><patch_index_0863></object> warming himself by<phrase> a fire</phrase><object><patch_index_0005><patch_index_0911></object>."
  474. >>> entities = extract_entities_with_patch_indices(text)
  475. >>> entities
  476. [(' a snowman', (31, 41), [(44, 863)]), (' a fire', (130, 137), [(5, 911)])]
  477. ```"""
  478. # The regular expression pattern for matching the required formats
  479. pattern = r"(?:(<phrase>([^<]+)</phrase>))?<object>((?:<patch_index_\d+><patch_index_\d+></delimiter_of_multi_objects/>)*<patch_index_\d+><patch_index_\d+>)</object>"
  480. # Find all matches in the given string
  481. matches = re.finditer(pattern, text)
  482. # Initialize an empty list to store the valid patch_index combinations
  483. entities_with_patch_indices = []
  484. for match in matches:
  485. # span of a `phrase` that is between <phrase> and </phrase>
  486. span = match.span(2)
  487. phrase_tag, phrase, match_content = match.groups()
  488. if not phrase_tag:
  489. phrase = None
  490. # We take the starting position of `<object>`
  491. span = (match.span(0)[0], match.span(0)[0])
  492. # Split the match_content by the delimiter to get individual patch_index pairs
  493. patch_index_pairs = match_content.split("</delimiter_of_multi_objects/>")
  494. entity_bboxes = []
  495. for pair in patch_index_pairs:
  496. # Extract the xxxx and yyyy values from the patch_index pair
  497. x = re.search(r"<patch_index_(\d+)>", pair)
  498. y = re.search(r"<patch_index_(\d+)>", pair[1:])
  499. if x and y:
  500. if phrase:
  501. entity_bboxes.append((int(x.group(1)), int(y.group(1))))
  502. else:
  503. entity_bboxes.append((int(x.group(1)), int(y.group(1))))
  504. if phrase:
  505. entities_with_patch_indices.append((phrase, span, entity_bboxes))
  506. else:
  507. for bbox in entity_bboxes:
  508. # fake entity name
  509. entity = f"<patch_index_{bbox[0]}><patch_index_{bbox[1]}>"
  510. entities_with_patch_indices.append((entity, span, [bbox]))
  511. return entities_with_patch_indices
  512. def adjust_entity_positions(entity, text):
  513. """Adjust the positions of the entities in `text` to be relative to the text with special fields removed."""
  514. entity_name, (start, end) = entity
  515. # computed the length of strings with special fields (tag tokens, patch index tokens, etc.) removed
  516. adjusted_start = len(re.sub("<.*?>", "", text[:start]))
  517. adjusted_end = len(re.sub("<.*?>", "", text[:end]))
  518. adjusted_entity = (entity_name, (adjusted_start, adjusted_end))
  519. return adjusted_entity
  520. def _cleanup_spaces(text, entities):
  521. """Remove the spaces around the text and the entities in it."""
  522. new_text = text.strip()
  523. leading_spaces = len(text) - len(text.lstrip())
  524. new_entities = []
  525. for entity_name, (start, end), bboxes in entities:
  526. entity_name_leading_spaces = len(entity_name) - len(entity_name.lstrip())
  527. entity_name_trailing_spaces = len(entity_name) - len(entity_name.rstrip())
  528. start = start - leading_spaces + entity_name_leading_spaces
  529. end = end - leading_spaces - entity_name_trailing_spaces
  530. entity_name = entity_name.strip()
  531. new_entities.append((entity_name, (start, end), bboxes))
  532. return new_text, new_entities
  533. # copied from https://github.com/microsoft/unilm/blob/97e4923e97d3ee10b57e97013556e3fd0d207a9b/kosmos-2/demo/decode_string.py#L77-L87
  534. # (with format modifications)
  535. def clean_text_and_extract_entities_with_bboxes(text, num_patches_per_side=32):
  536. """Remove the tag tokens from `text`, extract entities in it with some cleaning up of white characters.
  537. Examples:
  538. ```python
  539. >>> text = "<grounding> An image of<phrase> a snowman</phrase><object><patch_index_0044><patch_index_0863></object> warming himself by<phrase> a fire</phrase><object><patch_index_0005><patch_index_0911></object>."
  540. >>> clean_text, entities = clean_text_and_extract_entities_with_bboxes(text)
  541. >>> clean_text
  542. 'An image of a snowman warming himself by a fire.'
  543. >>> entities
  544. [('a snowman', (12, 21), [(0.390625, 0.046875, 0.984375, 0.828125)]), ('a fire', (41, 47), [(0.171875, 0.015625, 0.484375, 0.890625)])]
  545. ```"""
  546. # remove special fields (tag tokens, patch index tokens, etc.)
  547. processed_text = re.sub("<.*?>", "", text)
  548. entities_with_patch_indices = extract_entities_with_patch_indices(text)
  549. entities = []
  550. for item in entities_with_patch_indices:
  551. entity, bboxes = item[0:2], item[2]
  552. adjusted_entity = adjust_entity_positions(entity, text)
  553. bboxes_in_coords = [patch_index_to_coordinate(bbox[0], bbox[1], num_patches_per_side) for bbox in bboxes]
  554. entities.append(adjusted_entity + (bboxes_in_coords,))
  555. return _cleanup_spaces(processed_text, entities)
  556. __all__ = ["Kosmos2Processor"]