processing_kosmos2.py 30 KB

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