tokenization_tapas.py 116 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793
  1. # coding=utf-8
  2. # Copyright 2020 Google Research and The HuggingFace Inc. team.
  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. """Tokenization class for TAPAS model."""
  16. import collections
  17. import datetime
  18. import enum
  19. import itertools
  20. import math
  21. import os
  22. import re
  23. import unicodedata
  24. from collections.abc import Generator
  25. from dataclasses import dataclass
  26. from typing import Callable, Optional, Union
  27. import numpy as np
  28. from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
  29. from ...tokenization_utils_base import (
  30. ENCODE_KWARGS_DOCSTRING,
  31. VERY_LARGE_INTEGER,
  32. BatchEncoding,
  33. EncodedInput,
  34. PreTokenizedInput,
  35. TextInput,
  36. )
  37. from ...utils import ExplicitEnum, PaddingStrategy, TensorType, add_end_docstrings, is_pandas_available, logging
  38. if is_pandas_available():
  39. import pandas as pd
  40. logger = logging.get_logger(__name__)
  41. VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
  42. class TapasTruncationStrategy(ExplicitEnum):
  43. """
  44. Possible values for the `truncation` argument in [`~TapasTokenizer.__call__`]. Useful for tab-completion in an IDE.
  45. """
  46. DROP_ROWS_TO_FIT = "drop_rows_to_fit"
  47. DO_NOT_TRUNCATE = "do_not_truncate"
  48. TableValue = collections.namedtuple("TokenValue", ["token", "column_id", "row_id"])
  49. @dataclass(frozen=True)
  50. class TokenCoordinates:
  51. column_index: int
  52. row_index: int
  53. token_index: int
  54. @dataclass
  55. class TokenizedTable:
  56. rows: list[list[list[str]]]
  57. selected_tokens: list[TokenCoordinates]
  58. @dataclass(frozen=True)
  59. class SerializedExample:
  60. tokens: list[str]
  61. column_ids: list[int]
  62. row_ids: list[int]
  63. segment_ids: list[int]
  64. def _is_inner_wordpiece(token: str):
  65. return token.startswith("##")
  66. def load_vocab(vocab_file):
  67. """Loads a vocabulary file into a dictionary."""
  68. vocab = collections.OrderedDict()
  69. with open(vocab_file, "r", encoding="utf-8") as reader:
  70. tokens = reader.readlines()
  71. for index, token in enumerate(tokens):
  72. token = token.rstrip("\n")
  73. vocab[token] = index
  74. return vocab
  75. def whitespace_tokenize(text):
  76. """Runs basic whitespace cleaning and splitting on a piece of text."""
  77. text = text.strip()
  78. if not text:
  79. return []
  80. tokens = text.split()
  81. return tokens
  82. TAPAS_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING = r"""
  83. add_special_tokens (`bool`, *optional*, defaults to `True`):
  84. Whether or not to encode the sequences with the special tokens relative to their model.
  85. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
  86. Activates and controls padding. Accepts the following values:
  87. - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
  88. sequence if provided).
  89. - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
  90. acceptable input length for the model if that argument is not provided.
  91. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
  92. lengths).
  93. truncation (`bool`, `str` or [`TapasTruncationStrategy`], *optional*, defaults to `False`):
  94. Activates and controls truncation. Accepts the following values:
  95. - `True` or `'drop_rows_to_fit'`: Truncate to a maximum length specified with the argument `max_length`
  96. or to the maximum acceptable input length for the model if that argument is not provided. This will
  97. truncate row by row, removing rows from the table.
  98. - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
  99. greater than the model maximum admissible input size).
  100. max_length (`int`, *optional*):
  101. Controls the maximum length to use by one of the truncation/padding parameters.
  102. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length
  103. is required by one of the truncation/padding parameters. If the model has no specific maximum input
  104. length (like XLNet) truncation/padding to a maximum length will be deactivated.
  105. is_split_into_words (`bool`, *optional*, defaults to `False`):
  106. Whether or not the input is already pre-tokenized (e.g., split into words). If set to `True`, the
  107. tokenizer assumes the input is already split into words (for instance, by splitting it on whitespace)
  108. which it will tokenize. This is useful for NER or token classification.
  109. pad_to_multiple_of (`int`, *optional*):
  110. If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
  111. the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).
  112. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  113. If set, will return tensors instead of list of python integers. Acceptable values are:
  114. - `'tf'`: Return TensorFlow `tf.constant` objects.
  115. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  116. - `'np'`: Return Numpy `np.ndarray` objects.
  117. """
  118. class TapasTokenizer(PreTrainedTokenizer):
  119. r"""
  120. Construct a TAPAS tokenizer. Based on WordPiece. Flattens a table and one or more related sentences to be used by
  121. TAPAS models.
  122. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  123. this superclass for more information regarding those methods. [`TapasTokenizer`] creates several token type ids to
  124. encode tabular structure. To be more precise, it adds 7 token type ids, in the following order: `segment_ids`,
  125. `column_ids`, `row_ids`, `prev_labels`, `column_ranks`, `inv_column_ranks` and `numeric_relations`:
  126. - segment_ids: indicate whether a token belongs to the question (0) or the table (1). 0 for special tokens and
  127. padding.
  128. - column_ids: indicate to which column of the table a token belongs (starting from 1). Is 0 for all question
  129. tokens, special tokens and padding.
  130. - row_ids: indicate to which row of the table a token belongs (starting from 1). Is 0 for all question tokens,
  131. special tokens and padding. Tokens of column headers are also 0.
  132. - prev_labels: indicate whether a token was (part of) an answer to the previous question (1) or not (0). Useful in
  133. a conversational setup (such as SQA).
  134. - column_ranks: indicate the rank of a table token relative to a column, if applicable. For example, if you have a
  135. column "number of movies" with values 87, 53 and 69, then the column ranks of these tokens are 3, 1 and 2
  136. respectively. 0 for all question tokens, special tokens and padding.
  137. - inv_column_ranks: indicate the inverse rank of a table token relative to a column, if applicable. For example, if
  138. you have a column "number of movies" with values 87, 53 and 69, then the inverse column ranks of these tokens are
  139. 1, 3 and 2 respectively. 0 for all question tokens, special tokens and padding.
  140. - numeric_relations: indicate numeric relations between the question and the tokens of the table. 0 for all
  141. question tokens, special tokens and padding.
  142. [`TapasTokenizer`] runs end-to-end tokenization on a table and associated sentences: punctuation splitting and
  143. wordpiece.
  144. Args:
  145. vocab_file (`str`):
  146. File containing the vocabulary.
  147. do_lower_case (`bool`, *optional*, defaults to `True`):
  148. Whether or not to lowercase the input when tokenizing.
  149. do_basic_tokenize (`bool`, *optional*, defaults to `True`):
  150. Whether or not to do basic tokenization before WordPiece.
  151. never_split (`Iterable`, *optional*):
  152. Collection of tokens which will never be split during tokenization. Only has an effect when
  153. `do_basic_tokenize=True`
  154. unk_token (`str`, *optional*, defaults to `"[UNK]"`):
  155. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  156. token instead.
  157. sep_token (`str`, *optional*, defaults to `"[SEP]"`):
  158. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  159. sequence classification or for a text and a question for question answering. It is also used as the last
  160. token of a sequence built with special tokens.
  161. pad_token (`str`, *optional*, defaults to `"[PAD]"`):
  162. The token used for padding, for example when batching sequences of different lengths.
  163. cls_token (`str`, *optional*, defaults to `"[CLS]"`):
  164. The classifier token which is used when doing sequence classification (classification of the whole sequence
  165. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  166. mask_token (`str`, *optional*, defaults to `"[MASK]"`):
  167. The token used for masking values. This is the token used when training this model with masked language
  168. modeling. This is the token which the model will try to predict.
  169. empty_token (`str`, *optional*, defaults to `"[EMPTY]"`):
  170. The token used for empty cell values in a table. Empty cell values include "", "n/a", "nan" and "?".
  171. tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
  172. Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see this
  173. [issue](https://github.com/huggingface/transformers/issues/328)).
  174. strip_accents (`bool`, *optional*):
  175. Whether or not to strip all accents. If this option is not specified, then it will be determined by the
  176. value for `lowercase` (as in the original BERT).
  177. cell_trim_length (`int`, *optional*, defaults to -1):
  178. If > 0: Trim cells so that the length is <= this value. Also disables further cell trimming, should thus be
  179. used with `truncation` set to `True`.
  180. max_column_id (`int`, *optional*):
  181. Max column id to extract.
  182. max_row_id (`int`, *optional*):
  183. Max row id to extract.
  184. strip_column_names (`bool`, *optional*, defaults to `False`):
  185. Whether to add empty strings instead of column names.
  186. update_answer_coordinates (`bool`, *optional*, defaults to `False`):
  187. Whether to recompute the answer coordinates from the answer text.
  188. min_question_length (`int`, *optional*):
  189. Minimum length of each question in terms of tokens (will be skipped otherwise).
  190. max_question_length (`int`, *optional*):
  191. Maximum length of each question in terms of tokens (will be skipped otherwise).
  192. clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
  193. Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
  194. extra spaces.
  195. """
  196. vocab_files_names = VOCAB_FILES_NAMES
  197. def __init__(
  198. self,
  199. vocab_file,
  200. do_lower_case=True,
  201. do_basic_tokenize=True,
  202. never_split=None,
  203. unk_token="[UNK]",
  204. sep_token="[SEP]",
  205. pad_token="[PAD]",
  206. cls_token="[CLS]",
  207. mask_token="[MASK]",
  208. empty_token="[EMPTY]",
  209. tokenize_chinese_chars=True,
  210. strip_accents=None,
  211. cell_trim_length: int = -1,
  212. max_column_id: Optional[int] = None,
  213. max_row_id: Optional[int] = None,
  214. strip_column_names: bool = False,
  215. update_answer_coordinates: bool = False,
  216. min_question_length=None,
  217. max_question_length=None,
  218. model_max_length: int = 512,
  219. additional_special_tokens: Optional[list[str]] = None,
  220. clean_up_tokenization_spaces=True,
  221. **kwargs,
  222. ):
  223. if not is_pandas_available():
  224. raise ImportError("Pandas is required for the TAPAS tokenizer.")
  225. if additional_special_tokens is not None:
  226. if empty_token not in additional_special_tokens:
  227. additional_special_tokens.append(empty_token)
  228. else:
  229. additional_special_tokens = [empty_token]
  230. if not os.path.isfile(vocab_file):
  231. raise ValueError(
  232. f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
  233. " model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
  234. )
  235. self.vocab = load_vocab(vocab_file)
  236. self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
  237. self.do_basic_tokenize = do_basic_tokenize
  238. if do_basic_tokenize:
  239. self.basic_tokenizer = BasicTokenizer(
  240. do_lower_case=do_lower_case,
  241. never_split=never_split,
  242. tokenize_chinese_chars=tokenize_chinese_chars,
  243. strip_accents=strip_accents,
  244. )
  245. self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
  246. # Additional properties
  247. self.cell_trim_length = cell_trim_length
  248. self.max_column_id = (
  249. max_column_id
  250. if max_column_id is not None
  251. else model_max_length
  252. if model_max_length is not None
  253. else VERY_LARGE_INTEGER
  254. )
  255. self.max_row_id = (
  256. max_row_id
  257. if max_row_id is not None
  258. else model_max_length
  259. if model_max_length is not None
  260. else VERY_LARGE_INTEGER
  261. )
  262. self.strip_column_names = strip_column_names
  263. self.update_answer_coordinates = update_answer_coordinates
  264. self.min_question_length = min_question_length
  265. self.max_question_length = max_question_length
  266. super().__init__(
  267. do_lower_case=do_lower_case,
  268. do_basic_tokenize=do_basic_tokenize,
  269. never_split=never_split,
  270. unk_token=unk_token,
  271. sep_token=sep_token,
  272. pad_token=pad_token,
  273. cls_token=cls_token,
  274. mask_token=mask_token,
  275. empty_token=empty_token,
  276. tokenize_chinese_chars=tokenize_chinese_chars,
  277. strip_accents=strip_accents,
  278. cell_trim_length=cell_trim_length,
  279. max_column_id=max_column_id,
  280. max_row_id=max_row_id,
  281. strip_column_names=strip_column_names,
  282. update_answer_coordinates=update_answer_coordinates,
  283. min_question_length=min_question_length,
  284. max_question_length=max_question_length,
  285. model_max_length=model_max_length,
  286. additional_special_tokens=additional_special_tokens,
  287. clean_up_tokenization_spaces=clean_up_tokenization_spaces,
  288. **kwargs,
  289. )
  290. @property
  291. def do_lower_case(self):
  292. return self.basic_tokenizer.do_lower_case
  293. @property
  294. def vocab_size(self):
  295. return len(self.vocab)
  296. def get_vocab(self):
  297. return dict(self.vocab, **self.added_tokens_encoder)
  298. def _tokenize(self, text):
  299. if format_text(text) == EMPTY_TEXT:
  300. return [self.additional_special_tokens[0]]
  301. split_tokens = []
  302. if self.do_basic_tokenize:
  303. for token in self.basic_tokenizer.tokenize(text, never_split=self.all_special_tokens):
  304. # If the token is part of the never_split set
  305. if token in self.basic_tokenizer.never_split:
  306. split_tokens.append(token)
  307. else:
  308. split_tokens += self.wordpiece_tokenizer.tokenize(token)
  309. else:
  310. split_tokens = self.wordpiece_tokenizer.tokenize(text)
  311. return split_tokens
  312. def _convert_token_to_id(self, token):
  313. """Converts a token (str) in an id using the vocab."""
  314. return self.vocab.get(token, self.vocab.get(self.unk_token))
  315. def _convert_id_to_token(self, index):
  316. """Converts an index (integer) in a token (str) using the vocab."""
  317. return self.ids_to_tokens.get(index, self.unk_token)
  318. def convert_tokens_to_string(self, tokens):
  319. """Converts a sequence of tokens (string) in a single string."""
  320. out_string = " ".join(tokens).replace(" ##", "").strip()
  321. return out_string
  322. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
  323. index = 0
  324. if os.path.isdir(save_directory):
  325. vocab_file = os.path.join(
  326. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  327. )
  328. else:
  329. vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
  330. with open(vocab_file, "w", encoding="utf-8") as writer:
  331. for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
  332. if index != token_index:
  333. logger.warning(
  334. f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
  335. " Please check that the vocabulary is not corrupted!"
  336. )
  337. index = token_index
  338. writer.write(token + "\n")
  339. index += 1
  340. return (vocab_file,)
  341. def create_attention_mask_from_sequences(self, query_ids: list[int], table_values: list[TableValue]) -> list[int]:
  342. """
  343. Creates the attention mask according to the query token IDs and a list of table values.
  344. Args:
  345. query_ids (`list[int]`): list of token IDs corresponding to the ID.
  346. table_values (`list[TableValue]`): lift of table values, which are named tuples containing the
  347. token value, the column ID and the row ID of said token.
  348. Returns:
  349. `list[int]`: List of ints containing the attention mask values.
  350. """
  351. return [1] * (1 + len(query_ids) + 1 + len(table_values))
  352. def create_segment_token_type_ids_from_sequences(
  353. self, query_ids: list[int], table_values: list[TableValue]
  354. ) -> list[int]:
  355. """
  356. Creates the segment token type IDs according to the query token IDs and a list of table values.
  357. Args:
  358. query_ids (`list[int]`): list of token IDs corresponding to the ID.
  359. table_values (`list[TableValue]`): lift of table values, which are named tuples containing the
  360. token value, the column ID and the row ID of said token.
  361. Returns:
  362. `list[int]`: List of ints containing the segment token type IDs values.
  363. """
  364. table_ids = list(zip(*table_values))[0] if table_values else []
  365. return [0] * (1 + len(query_ids) + 1) + [1] * len(table_ids)
  366. def create_column_token_type_ids_from_sequences(
  367. self, query_ids: list[int], table_values: list[TableValue]
  368. ) -> list[int]:
  369. """
  370. Creates the column token type IDs according to the query token IDs and a list of table values.
  371. Args:
  372. query_ids (`list[int]`): list of token IDs corresponding to the ID.
  373. table_values (`list[TableValue]`): lift of table values, which are named tuples containing the
  374. token value, the column ID and the row ID of said token.
  375. Returns:
  376. `list[int]`: List of ints containing the column token type IDs values.
  377. """
  378. table_column_ids = list(zip(*table_values))[1] if table_values else []
  379. return [0] * (1 + len(query_ids) + 1) + list(table_column_ids)
  380. def create_row_token_type_ids_from_sequences(
  381. self, query_ids: list[int], table_values: list[TableValue]
  382. ) -> list[int]:
  383. """
  384. Creates the row token type IDs according to the query token IDs and a list of table values.
  385. Args:
  386. query_ids (`list[int]`): list of token IDs corresponding to the ID.
  387. table_values (`list[TableValue]`): lift of table values, which are named tuples containing the
  388. token value, the column ID and the row ID of said token.
  389. Returns:
  390. `list[int]`: List of ints containing the row token type IDs values.
  391. """
  392. table_row_ids = list(zip(*table_values))[2] if table_values else []
  393. return [0] * (1 + len(query_ids) + 1) + list(table_row_ids)
  394. def build_inputs_with_special_tokens(
  395. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
  396. ) -> list[int]:
  397. """
  398. Build model inputs from a question and flattened table for question answering or sequence classification tasks
  399. by concatenating and adding special tokens.
  400. Args:
  401. token_ids_0 (`list[int]`): The ids of the question.
  402. token_ids_1 (`list[int]`, *optional*): The ids of the flattened table.
  403. Returns:
  404. `list[int]`: The model input with special tokens.
  405. """
  406. if token_ids_1 is None:
  407. raise ValueError("With TAPAS, you must provide both question IDs and table IDs.")
  408. return [self.cls_token_id] + token_ids_0 + [self.sep_token_id] + token_ids_1
  409. def get_special_tokens_mask(
  410. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
  411. ) -> list[int]:
  412. """
  413. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  414. special tokens using the tokenizer `prepare_for_model` method.
  415. Args:
  416. token_ids_0 (`list[int]`):
  417. List of question IDs.
  418. token_ids_1 (`list[int]`, *optional*):
  419. List of flattened table IDs.
  420. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  421. Whether or not the token list is already formatted with special tokens for the model.
  422. Returns:
  423. `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  424. """
  425. if already_has_special_tokens:
  426. return super().get_special_tokens_mask(
  427. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  428. )
  429. if token_ids_1 is not None:
  430. return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1))
  431. return [1] + ([0] * len(token_ids_0)) + [1]
  432. @add_end_docstrings(TAPAS_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
  433. def __call__(
  434. self,
  435. table: "pd.DataFrame",
  436. queries: Optional[
  437. Union[
  438. TextInput,
  439. PreTokenizedInput,
  440. EncodedInput,
  441. list[TextInput],
  442. list[PreTokenizedInput],
  443. list[EncodedInput],
  444. ]
  445. ] = None,
  446. answer_coordinates: Optional[Union[list[tuple], list[list[tuple]]]] = None,
  447. answer_text: Optional[Union[list[TextInput], list[list[TextInput]]]] = None,
  448. add_special_tokens: bool = True,
  449. padding: Union[bool, str, PaddingStrategy] = False,
  450. truncation: Union[bool, str, TapasTruncationStrategy] = False,
  451. max_length: Optional[int] = None,
  452. pad_to_multiple_of: Optional[int] = None,
  453. padding_side: Optional[str] = None,
  454. return_tensors: Optional[Union[str, TensorType]] = None,
  455. return_token_type_ids: Optional[bool] = None,
  456. return_attention_mask: Optional[bool] = None,
  457. return_overflowing_tokens: bool = False,
  458. return_special_tokens_mask: bool = False,
  459. return_offsets_mapping: bool = False,
  460. return_length: bool = False,
  461. verbose: bool = True,
  462. **kwargs,
  463. ) -> BatchEncoding:
  464. """
  465. Main method to tokenize and prepare for the model one or several sequence(s) related to a table.
  466. Args:
  467. table (`pd.DataFrame`):
  468. Table containing tabular data. Note that all cell values must be text. Use *.astype(str)* on a Pandas
  469. dataframe to convert it to string.
  470. queries (`str` or `list[str]`):
  471. Question or batch of questions related to a table to be encoded. Note that in case of a batch, all
  472. questions must refer to the **same** table.
  473. answer_coordinates (`list[Tuple]` or `list[list[Tuple]]`, *optional*):
  474. Answer coordinates of each table-question pair in the batch. In case only a single table-question pair
  475. is provided, then the answer_coordinates must be a single list of one or more tuples. Each tuple must
  476. be a (row_index, column_index) pair. The first data row (not the column header row) has index 0. The
  477. first column has index 0. In case a batch of table-question pairs is provided, then the
  478. answer_coordinates must be a list of lists of tuples (each list corresponding to a single
  479. table-question pair).
  480. answer_text (`list[str]` or `list[list[str]]`, *optional*):
  481. Answer text of each table-question pair in the batch. In case only a single table-question pair is
  482. provided, then the answer_text must be a single list of one or more strings. Each string must be the
  483. answer text of a corresponding answer coordinate. In case a batch of table-question pairs is provided,
  484. then the answer_coordinates must be a list of lists of strings (each list corresponding to a single
  485. table-question pair).
  486. """
  487. assert isinstance(table, pd.DataFrame), "Table must be of type pd.DataFrame"
  488. # Input type checking for clearer error
  489. valid_query = False
  490. # Check that query has a valid type
  491. if queries is None or isinstance(queries, str):
  492. valid_query = True
  493. elif isinstance(queries, (list, tuple)):
  494. if len(queries) == 0 or isinstance(queries[0], str):
  495. valid_query = True
  496. if not valid_query:
  497. raise ValueError(
  498. "queries input must of type `str` (single example), `list[str]` (batch or single pretokenized"
  499. " example). "
  500. )
  501. is_batched = isinstance(queries, (list, tuple))
  502. if is_batched:
  503. return self.batch_encode_plus(
  504. table=table,
  505. queries=queries,
  506. answer_coordinates=answer_coordinates,
  507. answer_text=answer_text,
  508. add_special_tokens=add_special_tokens,
  509. padding=padding,
  510. truncation=truncation,
  511. max_length=max_length,
  512. pad_to_multiple_of=pad_to_multiple_of,
  513. padding_side=padding_side,
  514. return_tensors=return_tensors,
  515. return_token_type_ids=return_token_type_ids,
  516. return_attention_mask=return_attention_mask,
  517. return_overflowing_tokens=return_overflowing_tokens,
  518. return_special_tokens_mask=return_special_tokens_mask,
  519. return_offsets_mapping=return_offsets_mapping,
  520. return_length=return_length,
  521. verbose=verbose,
  522. **kwargs,
  523. )
  524. else:
  525. return self.encode_plus(
  526. table=table,
  527. query=queries,
  528. answer_coordinates=answer_coordinates,
  529. answer_text=answer_text,
  530. add_special_tokens=add_special_tokens,
  531. padding=padding,
  532. truncation=truncation,
  533. max_length=max_length,
  534. pad_to_multiple_of=pad_to_multiple_of,
  535. padding_side=padding_side,
  536. return_tensors=return_tensors,
  537. return_token_type_ids=return_token_type_ids,
  538. return_attention_mask=return_attention_mask,
  539. return_overflowing_tokens=return_overflowing_tokens,
  540. return_special_tokens_mask=return_special_tokens_mask,
  541. return_offsets_mapping=return_offsets_mapping,
  542. return_length=return_length,
  543. verbose=verbose,
  544. **kwargs,
  545. )
  546. @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPAS_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
  547. def batch_encode_plus(
  548. self,
  549. table: "pd.DataFrame",
  550. queries: Optional[
  551. Union[
  552. list[TextInput],
  553. list[PreTokenizedInput],
  554. list[EncodedInput],
  555. ]
  556. ] = None,
  557. answer_coordinates: Optional[list[list[tuple]]] = None,
  558. answer_text: Optional[list[list[TextInput]]] = None,
  559. add_special_tokens: bool = True,
  560. padding: Union[bool, str, PaddingStrategy] = False,
  561. truncation: Union[bool, str, TapasTruncationStrategy] = False,
  562. max_length: Optional[int] = None,
  563. pad_to_multiple_of: Optional[int] = None,
  564. padding_side: Optional[str] = None,
  565. return_tensors: Optional[Union[str, TensorType]] = None,
  566. return_token_type_ids: Optional[bool] = None,
  567. return_attention_mask: Optional[bool] = None,
  568. return_overflowing_tokens: bool = False,
  569. return_special_tokens_mask: bool = False,
  570. return_offsets_mapping: bool = False,
  571. return_length: bool = False,
  572. verbose: bool = True,
  573. **kwargs,
  574. ) -> BatchEncoding:
  575. """
  576. Prepare a table and a list of strings for the model.
  577. <Tip warning={true}>
  578. This method is deprecated, `__call__` should be used instead.
  579. </Tip>
  580. Args:
  581. table (`pd.DataFrame`):
  582. Table containing tabular data. Note that all cell values must be text. Use *.astype(str)* on a Pandas
  583. dataframe to convert it to string.
  584. queries (`list[str]`):
  585. Batch of questions related to a table to be encoded. Note that all questions must refer to the **same**
  586. table.
  587. answer_coordinates (`list[Tuple]` or `list[list[Tuple]]`, *optional*):
  588. Answer coordinates of each table-question pair in the batch. Each tuple must be a (row_index,
  589. column_index) pair. The first data row (not the column header row) has index 0. The first column has
  590. index 0. The answer_coordinates must be a list of lists of tuples (each list corresponding to a single
  591. table-question pair).
  592. answer_text (`list[str]` or `list[list[str]]`, *optional*):
  593. Answer text of each table-question pair in the batch. In case a batch of table-question pairs is
  594. provided, then the answer_coordinates must be a list of lists of strings (each list corresponding to a
  595. single table-question pair). Each string must be the answer text of a corresponding answer coordinate.
  596. """
  597. if return_token_type_ids is not None and not add_special_tokens:
  598. raise ValueError(
  599. "Asking to return token_type_ids while setting add_special_tokens to False "
  600. "results in an undefined behavior. Please set add_special_tokens to True or "
  601. "set return_token_type_ids to None."
  602. )
  603. if (answer_coordinates and not answer_text) or (not answer_coordinates and answer_text):
  604. raise ValueError("In case you provide answers, both answer_coordinates and answer_text should be provided")
  605. elif answer_coordinates is None and answer_text is None:
  606. answer_coordinates = answer_text = [None] * len(queries)
  607. if "is_split_into_words" in kwargs:
  608. raise NotImplementedError("Currently TapasTokenizer only supports questions as strings.")
  609. if return_offsets_mapping:
  610. raise NotImplementedError(
  611. "return_offset_mapping is not available when using Python tokenizers. "
  612. "To use this feature, change your tokenizer to one deriving from "
  613. "transformers.PreTrainedTokenizerFast."
  614. )
  615. return self._batch_encode_plus(
  616. table=table,
  617. queries=queries,
  618. answer_coordinates=answer_coordinates,
  619. answer_text=answer_text,
  620. add_special_tokens=add_special_tokens,
  621. padding=padding,
  622. truncation=truncation,
  623. max_length=max_length,
  624. pad_to_multiple_of=pad_to_multiple_of,
  625. padding_side=padding_side,
  626. return_tensors=return_tensors,
  627. return_token_type_ids=return_token_type_ids,
  628. return_attention_mask=return_attention_mask,
  629. return_overflowing_tokens=return_overflowing_tokens,
  630. return_special_tokens_mask=return_special_tokens_mask,
  631. return_offsets_mapping=return_offsets_mapping,
  632. return_length=return_length,
  633. verbose=verbose,
  634. **kwargs,
  635. )
  636. def _get_question_tokens(self, query):
  637. """Tokenizes the query, taking into account the max and min question length."""
  638. query_tokens = self.tokenize(query)
  639. if self.max_question_length is not None and len(query_tokens) > self.max_question_length:
  640. logger.warning("Skipping query as its tokens are longer than the max question length")
  641. return "", []
  642. if self.min_question_length is not None and len(query_tokens) < self.min_question_length:
  643. logger.warning("Skipping query as its tokens are shorter than the min question length")
  644. return "", []
  645. return query, query_tokens
  646. def _batch_encode_plus(
  647. self,
  648. table,
  649. queries: Union[
  650. list[TextInput],
  651. list[PreTokenizedInput],
  652. list[EncodedInput],
  653. ],
  654. answer_coordinates: Optional[list[list[tuple]]] = None,
  655. answer_text: Optional[list[list[TextInput]]] = None,
  656. add_special_tokens: bool = True,
  657. padding: Union[bool, str, PaddingStrategy] = False,
  658. truncation: Union[bool, str, TapasTruncationStrategy] = False,
  659. max_length: Optional[int] = None,
  660. pad_to_multiple_of: Optional[int] = None,
  661. padding_side: Optional[str] = None,
  662. return_tensors: Optional[Union[str, TensorType]] = None,
  663. return_token_type_ids: Optional[bool] = True,
  664. return_attention_mask: Optional[bool] = None,
  665. return_overflowing_tokens: bool = False,
  666. return_special_tokens_mask: bool = False,
  667. return_offsets_mapping: bool = False,
  668. return_length: bool = False,
  669. verbose: bool = True,
  670. **kwargs,
  671. ) -> BatchEncoding:
  672. table_tokens = self._tokenize_table(table)
  673. queries_tokens = []
  674. for idx, query in enumerate(queries):
  675. query, query_tokens = self._get_question_tokens(query)
  676. queries[idx] = query
  677. queries_tokens.append(query_tokens)
  678. batch_outputs = self._batch_prepare_for_model(
  679. table,
  680. queries,
  681. tokenized_table=table_tokens,
  682. queries_tokens=queries_tokens,
  683. answer_coordinates=answer_coordinates,
  684. padding=padding,
  685. truncation=truncation,
  686. answer_text=answer_text,
  687. add_special_tokens=add_special_tokens,
  688. max_length=max_length,
  689. pad_to_multiple_of=pad_to_multiple_of,
  690. padding_side=padding_side,
  691. return_tensors=return_tensors,
  692. prepend_batch_axis=True,
  693. return_attention_mask=return_attention_mask,
  694. return_token_type_ids=return_token_type_ids,
  695. return_overflowing_tokens=return_overflowing_tokens,
  696. return_special_tokens_mask=return_special_tokens_mask,
  697. return_length=return_length,
  698. verbose=verbose,
  699. )
  700. return BatchEncoding(batch_outputs)
  701. def _batch_prepare_for_model(
  702. self,
  703. raw_table: "pd.DataFrame",
  704. raw_queries: Union[
  705. list[TextInput],
  706. list[PreTokenizedInput],
  707. list[EncodedInput],
  708. ],
  709. tokenized_table: Optional[TokenizedTable] = None,
  710. queries_tokens: Optional[list[list[str]]] = None,
  711. answer_coordinates: Optional[list[list[tuple]]] = None,
  712. answer_text: Optional[list[list[TextInput]]] = None,
  713. add_special_tokens: bool = True,
  714. padding: Union[bool, str, PaddingStrategy] = False,
  715. truncation: Union[bool, str, TapasTruncationStrategy] = False,
  716. max_length: Optional[int] = None,
  717. pad_to_multiple_of: Optional[int] = None,
  718. padding_side: Optional[str] = None,
  719. return_tensors: Optional[Union[str, TensorType]] = None,
  720. return_token_type_ids: Optional[bool] = True,
  721. return_attention_mask: Optional[bool] = True,
  722. return_special_tokens_mask: bool = False,
  723. return_offsets_mapping: bool = False,
  724. return_length: bool = False,
  725. verbose: bool = True,
  726. prepend_batch_axis: bool = False,
  727. **kwargs,
  728. ) -> BatchEncoding:
  729. batch_outputs = {}
  730. for index, example in enumerate(zip(raw_queries, queries_tokens, answer_coordinates, answer_text)):
  731. raw_query, query_tokens, answer_coords, answer_txt = example
  732. outputs = self.prepare_for_model(
  733. raw_table,
  734. raw_query,
  735. tokenized_table=tokenized_table,
  736. query_tokens=query_tokens,
  737. answer_coordinates=answer_coords,
  738. answer_text=answer_txt,
  739. add_special_tokens=add_special_tokens,
  740. padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterwards
  741. truncation=truncation,
  742. max_length=max_length,
  743. pad_to_multiple_of=None, # we pad in batch afterwards
  744. padding_side=None, # we pad in batch afterward
  745. return_attention_mask=False, # we pad in batch afterwards
  746. return_token_type_ids=return_token_type_ids,
  747. return_special_tokens_mask=return_special_tokens_mask,
  748. return_length=return_length,
  749. return_tensors=None, # We convert the whole batch to tensors at the end
  750. prepend_batch_axis=False,
  751. verbose=verbose,
  752. prev_answer_coordinates=answer_coordinates[index - 1] if index != 0 else None,
  753. prev_answer_text=answer_text[index - 1] if index != 0 else None,
  754. )
  755. for key, value in outputs.items():
  756. if key not in batch_outputs:
  757. batch_outputs[key] = []
  758. batch_outputs[key].append(value)
  759. batch_outputs = self.pad(
  760. batch_outputs,
  761. padding=padding,
  762. max_length=max_length,
  763. pad_to_multiple_of=pad_to_multiple_of,
  764. padding_side=padding_side,
  765. return_attention_mask=return_attention_mask,
  766. )
  767. batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)
  768. return batch_outputs
  769. @add_end_docstrings(ENCODE_KWARGS_DOCSTRING)
  770. def encode(
  771. self,
  772. table: "pd.DataFrame",
  773. query: Optional[
  774. Union[
  775. TextInput,
  776. PreTokenizedInput,
  777. EncodedInput,
  778. ]
  779. ] = None,
  780. add_special_tokens: bool = True,
  781. padding: Union[bool, str, PaddingStrategy] = False,
  782. truncation: Union[bool, str, TapasTruncationStrategy] = False,
  783. max_length: Optional[int] = None,
  784. return_tensors: Optional[Union[str, TensorType]] = None,
  785. **kwargs,
  786. ) -> list[int]:
  787. """
  788. Prepare a table and a string for the model. This method does not return token type IDs, attention masks, etc.
  789. which are necessary for the model to work correctly. Use that method if you want to build your processing on
  790. your own, otherwise refer to `__call__`.
  791. Args:
  792. table (`pd.DataFrame`):
  793. Table containing tabular data. Note that all cell values must be text. Use *.astype(str)* on a Pandas
  794. dataframe to convert it to string.
  795. query (`str` or `list[str]`):
  796. Question related to a table to be encoded.
  797. """
  798. encoded_inputs = self.encode_plus(
  799. table,
  800. query=query,
  801. add_special_tokens=add_special_tokens,
  802. padding=padding,
  803. truncation=truncation,
  804. max_length=max_length,
  805. return_tensors=return_tensors,
  806. **kwargs,
  807. )
  808. return encoded_inputs["input_ids"]
  809. @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPAS_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
  810. def encode_plus(
  811. self,
  812. table: "pd.DataFrame",
  813. query: Optional[
  814. Union[
  815. TextInput,
  816. PreTokenizedInput,
  817. EncodedInput,
  818. ]
  819. ] = None,
  820. answer_coordinates: Optional[list[tuple]] = None,
  821. answer_text: Optional[list[TextInput]] = None,
  822. add_special_tokens: bool = True,
  823. padding: Union[bool, str, PaddingStrategy] = False,
  824. truncation: Union[bool, str, TapasTruncationStrategy] = False,
  825. max_length: Optional[int] = None,
  826. pad_to_multiple_of: Optional[int] = None,
  827. padding_side: Optional[str] = None,
  828. return_tensors: Optional[Union[str, TensorType]] = None,
  829. return_token_type_ids: Optional[bool] = None,
  830. return_attention_mask: Optional[bool] = None,
  831. return_special_tokens_mask: bool = False,
  832. return_offsets_mapping: bool = False,
  833. return_length: bool = False,
  834. verbose: bool = True,
  835. **kwargs,
  836. ) -> BatchEncoding:
  837. """
  838. Prepare a table and a string for the model.
  839. Args:
  840. table (`pd.DataFrame`):
  841. Table containing tabular data. Note that all cell values must be text. Use *.astype(str)* on a Pandas
  842. dataframe to convert it to string.
  843. query (`str` or `list[str]`):
  844. Question related to a table to be encoded.
  845. answer_coordinates (`list[Tuple]` or `list[list[Tuple]]`, *optional*):
  846. Answer coordinates of each table-question pair in the batch. The answer_coordinates must be a single
  847. list of one or more tuples. Each tuple must be a (row_index, column_index) pair. The first data row
  848. (not the column header row) has index 0. The first column has index 0.
  849. answer_text (`list[str]` or `list[list[str]]`, *optional*):
  850. Answer text of each table-question pair in the batch. The answer_text must be a single list of one or
  851. more strings. Each string must be the answer text of a corresponding answer coordinate.
  852. """
  853. if return_token_type_ids is not None and not add_special_tokens:
  854. raise ValueError(
  855. "Asking to return token_type_ids while setting add_special_tokens to False "
  856. "results in an undefined behavior. Please set add_special_tokens to True or "
  857. "set return_token_type_ids to None."
  858. )
  859. if (answer_coordinates and not answer_text) or (not answer_coordinates and answer_text):
  860. raise ValueError("In case you provide answers, both answer_coordinates and answer_text should be provided")
  861. if "is_split_into_words" in kwargs:
  862. raise NotImplementedError("Currently TapasTokenizer only supports questions as strings.")
  863. if return_offsets_mapping:
  864. raise NotImplementedError(
  865. "return_offset_mapping is not available when using Python tokenizers. "
  866. "To use this feature, change your tokenizer to one deriving from "
  867. "transformers.PreTrainedTokenizerFast."
  868. )
  869. return self._encode_plus(
  870. table=table,
  871. query=query,
  872. answer_coordinates=answer_coordinates,
  873. answer_text=answer_text,
  874. add_special_tokens=add_special_tokens,
  875. truncation=truncation,
  876. padding=padding,
  877. max_length=max_length,
  878. pad_to_multiple_of=pad_to_multiple_of,
  879. padding_side=padding_side,
  880. return_tensors=return_tensors,
  881. return_token_type_ids=return_token_type_ids,
  882. return_attention_mask=return_attention_mask,
  883. return_special_tokens_mask=return_special_tokens_mask,
  884. return_offsets_mapping=return_offsets_mapping,
  885. return_length=return_length,
  886. verbose=verbose,
  887. **kwargs,
  888. )
  889. def _encode_plus(
  890. self,
  891. table: "pd.DataFrame",
  892. query: Union[
  893. TextInput,
  894. PreTokenizedInput,
  895. EncodedInput,
  896. ],
  897. answer_coordinates: Optional[list[tuple]] = None,
  898. answer_text: Optional[list[TextInput]] = None,
  899. add_special_tokens: bool = True,
  900. padding: Union[bool, str, PaddingStrategy] = False,
  901. truncation: Union[bool, str, TapasTruncationStrategy] = False,
  902. max_length: Optional[int] = None,
  903. pad_to_multiple_of: Optional[int] = None,
  904. padding_side: Optional[str] = None,
  905. return_tensors: Optional[Union[str, TensorType]] = None,
  906. return_token_type_ids: Optional[bool] = True,
  907. return_attention_mask: Optional[bool] = True,
  908. return_special_tokens_mask: bool = False,
  909. return_offsets_mapping: bool = False,
  910. return_length: bool = False,
  911. verbose: bool = True,
  912. **kwargs,
  913. ):
  914. if query is None:
  915. query = ""
  916. logger.warning(
  917. "TAPAS is a question answering model but you have not passed a query. Please be aware that the "
  918. "model will probably not behave correctly."
  919. )
  920. table_tokens = self._tokenize_table(table)
  921. query, query_tokens = self._get_question_tokens(query)
  922. return self.prepare_for_model(
  923. table,
  924. query,
  925. tokenized_table=table_tokens,
  926. query_tokens=query_tokens,
  927. answer_coordinates=answer_coordinates,
  928. answer_text=answer_text,
  929. add_special_tokens=add_special_tokens,
  930. truncation=truncation,
  931. padding=padding,
  932. max_length=max_length,
  933. pad_to_multiple_of=pad_to_multiple_of,
  934. padding_side=padding_side,
  935. return_tensors=return_tensors,
  936. prepend_batch_axis=True,
  937. return_attention_mask=return_attention_mask,
  938. return_token_type_ids=return_token_type_ids,
  939. return_special_tokens_mask=return_special_tokens_mask,
  940. return_length=return_length,
  941. verbose=verbose,
  942. )
  943. @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPAS_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
  944. def prepare_for_model(
  945. self,
  946. raw_table: "pd.DataFrame",
  947. raw_query: Union[
  948. TextInput,
  949. PreTokenizedInput,
  950. EncodedInput,
  951. ],
  952. tokenized_table: Optional[TokenizedTable] = None,
  953. query_tokens: Optional[TokenizedTable] = None,
  954. answer_coordinates: Optional[list[tuple]] = None,
  955. answer_text: Optional[list[TextInput]] = None,
  956. add_special_tokens: bool = True,
  957. padding: Union[bool, str, PaddingStrategy] = False,
  958. truncation: Union[bool, str, TapasTruncationStrategy] = False,
  959. max_length: Optional[int] = None,
  960. pad_to_multiple_of: Optional[int] = None,
  961. padding_side: Optional[str] = None,
  962. return_tensors: Optional[Union[str, TensorType]] = None,
  963. return_token_type_ids: Optional[bool] = True,
  964. return_attention_mask: Optional[bool] = True,
  965. return_special_tokens_mask: bool = False,
  966. return_offsets_mapping: bool = False,
  967. return_length: bool = False,
  968. verbose: bool = True,
  969. prepend_batch_axis: bool = False,
  970. **kwargs,
  971. ) -> BatchEncoding:
  972. """
  973. Prepares a sequence of input id so that it can be used by the model. It adds special tokens, truncates
  974. sequences if overflowing while taking into account the special tokens.
  975. Args:
  976. raw_table (`pd.DataFrame`):
  977. The original table before any transformation (like tokenization) was applied to it.
  978. raw_query (`TextInput` or `PreTokenizedInput` or `EncodedInput`):
  979. The original query before any transformation (like tokenization) was applied to it.
  980. tokenized_table (`TokenizedTable`):
  981. The table after tokenization.
  982. query_tokens (`list[str]`):
  983. The query after tokenization.
  984. answer_coordinates (`list[Tuple]` or `list[list[Tuple]]`, *optional*):
  985. Answer coordinates of each table-question pair in the batch. The answer_coordinates must be a single
  986. list of one or more tuples. Each tuple must be a (row_index, column_index) pair. The first data row
  987. (not the column header row) has index 0. The first column has index 0.
  988. answer_text (`list[str]` or `list[list[str]]`, *optional*):
  989. Answer text of each table-question pair in the batch. The answer_text must be a single list of one or
  990. more strings. Each string must be the answer text of a corresponding answer coordinate.
  991. """
  992. if isinstance(padding, bool):
  993. if padding and (max_length is not None or pad_to_multiple_of is not None):
  994. padding = PaddingStrategy.MAX_LENGTH
  995. else:
  996. padding = PaddingStrategy.DO_NOT_PAD
  997. elif not isinstance(padding, PaddingStrategy):
  998. padding = PaddingStrategy(padding)
  999. if isinstance(truncation, bool):
  1000. if truncation:
  1001. truncation = TapasTruncationStrategy.DROP_ROWS_TO_FIT
  1002. else:
  1003. truncation = TapasTruncationStrategy.DO_NOT_TRUNCATE
  1004. elif not isinstance(truncation, TapasTruncationStrategy):
  1005. truncation = TapasTruncationStrategy(truncation)
  1006. encoded_inputs = {}
  1007. is_part_of_batch = False
  1008. prev_answer_coordinates, prev_answer_text = None, None
  1009. if "prev_answer_coordinates" in kwargs and "prev_answer_text" in kwargs:
  1010. is_part_of_batch = True
  1011. prev_answer_coordinates = kwargs["prev_answer_coordinates"]
  1012. prev_answer_text = kwargs["prev_answer_text"]
  1013. num_rows = self._get_num_rows(raw_table, truncation != TapasTruncationStrategy.DO_NOT_TRUNCATE)
  1014. num_columns = self._get_num_columns(raw_table)
  1015. _, _, num_tokens = self._get_table_boundaries(tokenized_table)
  1016. if truncation != TapasTruncationStrategy.DO_NOT_TRUNCATE:
  1017. num_rows, num_tokens = self._get_truncated_table_rows(
  1018. query_tokens, tokenized_table, num_rows, num_columns, max_length, truncation_strategy=truncation
  1019. )
  1020. table_data = list(self._get_table_values(tokenized_table, num_columns, num_rows, num_tokens))
  1021. query_ids = self.convert_tokens_to_ids(query_tokens)
  1022. table_ids = list(zip(*table_data))[0] if len(table_data) > 0 else list(zip(*table_data))
  1023. table_ids = self.convert_tokens_to_ids(list(table_ids))
  1024. if "return_overflowing_tokens" in kwargs and kwargs["return_overflowing_tokens"]:
  1025. raise ValueError("TAPAS does not return overflowing tokens as it works on tables.")
  1026. if add_special_tokens:
  1027. input_ids = self.build_inputs_with_special_tokens(query_ids, table_ids)
  1028. else:
  1029. input_ids = query_ids + table_ids
  1030. if max_length is not None and len(input_ids) > max_length:
  1031. raise ValueError(
  1032. "Could not encode the query and table header given the maximum length. Encoding the query and table "
  1033. f"header results in a length of {len(input_ids)} which is higher than the max_length of {max_length}"
  1034. )
  1035. encoded_inputs["input_ids"] = input_ids
  1036. segment_ids = self.create_segment_token_type_ids_from_sequences(query_ids, table_data)
  1037. column_ids = self.create_column_token_type_ids_from_sequences(query_ids, table_data)
  1038. row_ids = self.create_row_token_type_ids_from_sequences(query_ids, table_data)
  1039. if not is_part_of_batch or (prev_answer_coordinates is None and prev_answer_text is None):
  1040. # simply set the prev_labels to zeros
  1041. prev_labels = [0] * len(row_ids)
  1042. else:
  1043. prev_labels = self.get_answer_ids(
  1044. column_ids, row_ids, table_data, prev_answer_text, prev_answer_coordinates
  1045. )
  1046. # FIRST: parse both the table and question in terms of numeric values
  1047. raw_table = add_numeric_table_values(raw_table)
  1048. raw_query = add_numeric_values_to_question(raw_query)
  1049. # SECOND: add numeric-related features (and not parse them in these functions):
  1050. column_ranks, inv_column_ranks = self._get_numeric_column_ranks(column_ids, row_ids, raw_table)
  1051. numeric_relations = self._get_numeric_relations(raw_query, column_ids, row_ids, raw_table)
  1052. # Load from model defaults
  1053. if return_token_type_ids is None:
  1054. return_token_type_ids = "token_type_ids" in self.model_input_names
  1055. if return_attention_mask is None:
  1056. return_attention_mask = "attention_mask" in self.model_input_names
  1057. if return_attention_mask:
  1058. attention_mask = self.create_attention_mask_from_sequences(query_ids, table_data)
  1059. encoded_inputs["attention_mask"] = attention_mask
  1060. if answer_coordinates is not None and answer_text is not None:
  1061. labels = self.get_answer_ids(column_ids, row_ids, table_data, answer_text, answer_coordinates)
  1062. numeric_values = self._get_numeric_values(raw_table, column_ids, row_ids)
  1063. numeric_values_scale = self._get_numeric_values_scale(raw_table, column_ids, row_ids)
  1064. encoded_inputs["labels"] = labels
  1065. encoded_inputs["numeric_values"] = numeric_values
  1066. encoded_inputs["numeric_values_scale"] = numeric_values_scale
  1067. if return_token_type_ids:
  1068. token_type_ids = [
  1069. segment_ids,
  1070. column_ids,
  1071. row_ids,
  1072. prev_labels,
  1073. column_ranks,
  1074. inv_column_ranks,
  1075. numeric_relations,
  1076. ]
  1077. token_type_ids = [list(ids) for ids in list(zip(*token_type_ids))]
  1078. encoded_inputs["token_type_ids"] = token_type_ids
  1079. if return_special_tokens_mask:
  1080. if add_special_tokens:
  1081. encoded_inputs["special_tokens_mask"] = self.get_special_tokens_mask(query_ids, table_ids)
  1082. else:
  1083. encoded_inputs["special_tokens_mask"] = [0] * len(input_ids)
  1084. # Check lengths
  1085. if max_length is None and len(encoded_inputs["input_ids"]) > self.model_max_length and verbose:
  1086. if not self.deprecation_warnings.get("sequence-length-is-longer-than-the-specified-maximum", False):
  1087. logger.warning(
  1088. "Token indices sequence length is longer than the specified maximum sequence length "
  1089. f"for this model ({len(encoded_inputs['input_ids'])} > {self.model_max_length}). Running this "
  1090. "sequence through the model will result in indexing errors."
  1091. )
  1092. self.deprecation_warnings["sequence-length-is-longer-than-the-specified-maximum"] = True
  1093. # Padding
  1094. if padding != PaddingStrategy.DO_NOT_PAD or return_attention_mask:
  1095. encoded_inputs = self.pad(
  1096. encoded_inputs,
  1097. max_length=max_length,
  1098. padding=padding.value,
  1099. pad_to_multiple_of=pad_to_multiple_of,
  1100. padding_side=padding_side,
  1101. return_attention_mask=return_attention_mask,
  1102. )
  1103. if return_length:
  1104. encoded_inputs["length"] = len(encoded_inputs["input_ids"])
  1105. batch_outputs = BatchEncoding(
  1106. encoded_inputs, tensor_type=return_tensors, prepend_batch_axis=prepend_batch_axis
  1107. )
  1108. return batch_outputs
  1109. def _get_truncated_table_rows(
  1110. self,
  1111. query_tokens: list[str],
  1112. tokenized_table: TokenizedTable,
  1113. num_rows: int,
  1114. num_columns: int,
  1115. max_length: int,
  1116. truncation_strategy: Union[str, TapasTruncationStrategy],
  1117. ) -> tuple[int, int]:
  1118. """
  1119. Truncates a sequence pair in-place following the strategy.
  1120. Args:
  1121. query_tokens (`list[str]`):
  1122. List of strings corresponding to the tokenized query.
  1123. tokenized_table (`TokenizedTable`):
  1124. Tokenized table
  1125. num_rows (`int`):
  1126. Total number of table rows
  1127. num_columns (`int`):
  1128. Total number of table columns
  1129. max_length (`int`):
  1130. Total maximum length.
  1131. truncation_strategy (`str` or [`TapasTruncationStrategy]`):
  1132. Truncation strategy to use. Seeing as this method should only be called when truncating, the only
  1133. available strategy is the `"drop_rows_to_fit"` strategy.
  1134. Returns:
  1135. `Tuple(int, int)`: tuple containing the number of rows after truncation, and the number of tokens available
  1136. for each table element.
  1137. """
  1138. if not isinstance(truncation_strategy, TapasTruncationStrategy):
  1139. truncation_strategy = TapasTruncationStrategy(truncation_strategy)
  1140. if max_length is None:
  1141. max_length = self.model_max_length
  1142. if truncation_strategy == TapasTruncationStrategy.DROP_ROWS_TO_FIT:
  1143. while True:
  1144. num_tokens = self._get_max_num_tokens(
  1145. query_tokens, tokenized_table, num_rows=num_rows, num_columns=num_columns, max_length=max_length
  1146. )
  1147. if num_tokens is not None:
  1148. # We could fit the table.
  1149. break
  1150. # Try to drop a row to fit the table.
  1151. num_rows -= 1
  1152. if num_rows < 1:
  1153. break
  1154. elif truncation_strategy != TapasTruncationStrategy.DO_NOT_TRUNCATE:
  1155. raise ValueError(f"Unknown truncation strategy {truncation_strategy}.")
  1156. return num_rows, num_tokens or 1
  1157. def _tokenize_table(
  1158. self,
  1159. table=None,
  1160. ):
  1161. """
  1162. Tokenizes column headers and cell texts of a table.
  1163. Args:
  1164. table (`pd.Dataframe`):
  1165. Table. Returns: `TokenizedTable`: TokenizedTable object.
  1166. """
  1167. tokenized_rows = []
  1168. tokenized_row = []
  1169. # tokenize column headers
  1170. for column in table:
  1171. if self.strip_column_names:
  1172. tokenized_row.append(self.tokenize(""))
  1173. else:
  1174. tokenized_row.append(self.tokenize(column))
  1175. tokenized_rows.append(tokenized_row)
  1176. # tokenize cell values
  1177. for idx, row in table.iterrows():
  1178. tokenized_row = []
  1179. for cell in row:
  1180. tokenized_row.append(self.tokenize(cell))
  1181. tokenized_rows.append(tokenized_row)
  1182. token_coordinates = []
  1183. for row_index, row in enumerate(tokenized_rows):
  1184. for column_index, cell in enumerate(row):
  1185. for token_index, _ in enumerate(cell):
  1186. token_coordinates.append(
  1187. TokenCoordinates(
  1188. row_index=row_index,
  1189. column_index=column_index,
  1190. token_index=token_index,
  1191. )
  1192. )
  1193. return TokenizedTable(
  1194. rows=tokenized_rows,
  1195. selected_tokens=token_coordinates,
  1196. )
  1197. def _question_encoding_cost(self, question_tokens):
  1198. # Two extra spots of SEP and CLS.
  1199. return len(question_tokens) + 2
  1200. def _get_token_budget(self, question_tokens, max_length=None):
  1201. """
  1202. Computes the number of tokens left for the table after tokenizing a question, taking into account the max
  1203. sequence length of the model.
  1204. Args:
  1205. question_tokens (`list[String]`):
  1206. List of question tokens. Returns: `int`: the number of tokens left for the table, given the model max
  1207. length.
  1208. """
  1209. return (max_length if max_length is not None else self.model_max_length) - self._question_encoding_cost(
  1210. question_tokens
  1211. )
  1212. def _get_table_values(self, table, num_columns, num_rows, num_tokens) -> Generator[TableValue, None, None]:
  1213. """Iterates over partial table and returns token, column and row indexes."""
  1214. for tc in table.selected_tokens:
  1215. # First row is header row.
  1216. if tc.row_index >= num_rows + 1:
  1217. continue
  1218. if tc.column_index >= num_columns:
  1219. continue
  1220. cell = table.rows[tc.row_index][tc.column_index]
  1221. token = cell[tc.token_index]
  1222. word_begin_index = tc.token_index
  1223. # Don't add partial words. Find the starting word piece and check if it
  1224. # fits in the token budget.
  1225. while word_begin_index >= 0 and _is_inner_wordpiece(cell[word_begin_index]):
  1226. word_begin_index -= 1
  1227. if word_begin_index >= num_tokens:
  1228. continue
  1229. yield TableValue(token, tc.column_index + 1, tc.row_index)
  1230. def _get_table_boundaries(self, table):
  1231. """Return maximal number of rows, columns and tokens."""
  1232. max_num_tokens = 0
  1233. max_num_columns = 0
  1234. max_num_rows = 0
  1235. for tc in table.selected_tokens:
  1236. max_num_columns = max(max_num_columns, tc.column_index + 1)
  1237. max_num_rows = max(max_num_rows, tc.row_index + 1)
  1238. max_num_tokens = max(max_num_tokens, tc.token_index + 1)
  1239. max_num_columns = min(self.max_column_id, max_num_columns)
  1240. max_num_rows = min(self.max_row_id, max_num_rows)
  1241. return max_num_rows, max_num_columns, max_num_tokens
  1242. def _get_table_cost(self, table, num_columns, num_rows, num_tokens):
  1243. return sum(1 for _ in self._get_table_values(table, num_columns, num_rows, num_tokens))
  1244. def _get_max_num_tokens(self, question_tokens, tokenized_table, num_columns, num_rows, max_length):
  1245. """Computes max number of tokens that can be squeezed into the budget."""
  1246. token_budget = self._get_token_budget(question_tokens, max_length)
  1247. _, _, max_num_tokens = self._get_table_boundaries(tokenized_table)
  1248. if self.cell_trim_length >= 0 and max_num_tokens > self.cell_trim_length:
  1249. max_num_tokens = self.cell_trim_length
  1250. num_tokens = 0
  1251. for num_tokens in range(max_num_tokens + 1):
  1252. cost = self._get_table_cost(tokenized_table, num_columns, num_rows, num_tokens + 1)
  1253. if cost > token_budget:
  1254. break
  1255. if num_tokens < max_num_tokens:
  1256. if self.cell_trim_length >= 0:
  1257. # We don't allow dynamic trimming if a cell_trim_length is set.
  1258. return None
  1259. if num_tokens == 0:
  1260. return None
  1261. return num_tokens
  1262. def _get_num_columns(self, table):
  1263. num_columns = table.shape[1]
  1264. if num_columns >= self.max_column_id:
  1265. raise ValueError("Too many columns")
  1266. return num_columns
  1267. def _get_num_rows(self, table, drop_rows_to_fit):
  1268. num_rows = table.shape[0]
  1269. if num_rows >= self.max_row_id:
  1270. if drop_rows_to_fit:
  1271. num_rows = self.max_row_id - 1
  1272. else:
  1273. raise ValueError("Too many rows")
  1274. return num_rows
  1275. def _serialize_text(self, question_tokens):
  1276. """Serializes texts in index arrays."""
  1277. tokens = []
  1278. segment_ids = []
  1279. column_ids = []
  1280. row_ids = []
  1281. # add [CLS] token at the beginning
  1282. tokens.append(self.cls_token)
  1283. segment_ids.append(0)
  1284. column_ids.append(0)
  1285. row_ids.append(0)
  1286. for token in question_tokens:
  1287. tokens.append(token)
  1288. segment_ids.append(0)
  1289. column_ids.append(0)
  1290. row_ids.append(0)
  1291. return tokens, segment_ids, column_ids, row_ids
  1292. def _serialize(
  1293. self,
  1294. question_tokens,
  1295. table,
  1296. num_columns,
  1297. num_rows,
  1298. num_tokens,
  1299. ):
  1300. """Serializes table and text."""
  1301. tokens, segment_ids, column_ids, row_ids = self._serialize_text(question_tokens)
  1302. # add [SEP] token between question and table tokens
  1303. tokens.append(self.sep_token)
  1304. segment_ids.append(0)
  1305. column_ids.append(0)
  1306. row_ids.append(0)
  1307. for token, column_id, row_id in self._get_table_values(table, num_columns, num_rows, num_tokens):
  1308. tokens.append(token)
  1309. segment_ids.append(1)
  1310. column_ids.append(column_id)
  1311. row_ids.append(row_id)
  1312. return SerializedExample(
  1313. tokens=tokens,
  1314. segment_ids=segment_ids,
  1315. column_ids=column_ids,
  1316. row_ids=row_ids,
  1317. )
  1318. def _get_column_values(self, table, col_index):
  1319. table_numeric_values = {}
  1320. for row_index, row in table.iterrows():
  1321. cell = row[col_index]
  1322. if cell.numeric_value is not None:
  1323. table_numeric_values[row_index] = cell.numeric_value
  1324. return table_numeric_values
  1325. def _get_cell_token_indexes(self, column_ids, row_ids, column_id, row_id):
  1326. for index in range(len(column_ids)):
  1327. if column_ids[index] - 1 == column_id and row_ids[index] - 1 == row_id:
  1328. yield index
  1329. def _get_numeric_column_ranks(self, column_ids, row_ids, table):
  1330. """Returns column ranks for all numeric columns."""
  1331. ranks = [0] * len(column_ids)
  1332. inv_ranks = [0] * len(column_ids)
  1333. # original code from tf_example_utils.py of the original implementation
  1334. if table is not None:
  1335. for col_index in range(len(table.columns)):
  1336. table_numeric_values = self._get_column_values(table, col_index)
  1337. if not table_numeric_values:
  1338. continue
  1339. try:
  1340. key_fn = get_numeric_sort_key_fn(table_numeric_values.values())
  1341. except ValueError:
  1342. continue
  1343. table_numeric_values = {row_index: key_fn(value) for row_index, value in table_numeric_values.items()}
  1344. table_numeric_values_inv = collections.defaultdict(list)
  1345. for row_index, value in table_numeric_values.items():
  1346. table_numeric_values_inv[value].append(row_index)
  1347. unique_values = sorted(table_numeric_values_inv.keys())
  1348. for rank, value in enumerate(unique_values):
  1349. for row_index in table_numeric_values_inv[value]:
  1350. for index in self._get_cell_token_indexes(column_ids, row_ids, col_index, row_index):
  1351. ranks[index] = rank + 1
  1352. inv_ranks[index] = len(unique_values) - rank
  1353. return ranks, inv_ranks
  1354. def _get_numeric_sort_key_fn(self, table_numeric_values, value):
  1355. """
  1356. Returns the sort key function for comparing value to table values. The function returned will be a suitable
  1357. input for the key param of the sort(). See number_annotation_utils._get_numeric_sort_key_fn for details
  1358. Args:
  1359. table_numeric_values: Numeric values of a column
  1360. value: Numeric value in the question
  1361. Returns:
  1362. A function key function to compare column and question values.
  1363. """
  1364. if not table_numeric_values:
  1365. return None
  1366. all_values = list(table_numeric_values.values())
  1367. all_values.append(value)
  1368. try:
  1369. return get_numeric_sort_key_fn(all_values)
  1370. except ValueError:
  1371. return None
  1372. def _get_numeric_relations(self, question, column_ids, row_ids, table):
  1373. """
  1374. Returns numeric relations embeddings
  1375. Args:
  1376. question: Question object.
  1377. column_ids: Maps word piece position to column id.
  1378. row_ids: Maps word piece position to row id.
  1379. table: The table containing the numeric cell values.
  1380. """
  1381. numeric_relations = [0] * len(column_ids)
  1382. # first, we add any numeric value spans to the question:
  1383. # Create a dictionary that maps a table cell to the set of all relations
  1384. # this cell has with any value in the question.
  1385. cell_indices_to_relations = collections.defaultdict(set)
  1386. if question is not None and table is not None:
  1387. for numeric_value_span in question.numeric_spans:
  1388. for value in numeric_value_span.values:
  1389. for column_index in range(len(table.columns)):
  1390. table_numeric_values = self._get_column_values(table, column_index)
  1391. sort_key_fn = self._get_numeric_sort_key_fn(table_numeric_values, value)
  1392. if sort_key_fn is None:
  1393. continue
  1394. for row_index, cell_value in table_numeric_values.items():
  1395. relation = get_numeric_relation(value, cell_value, sort_key_fn)
  1396. if relation is not None:
  1397. cell_indices_to_relations[column_index, row_index].add(relation)
  1398. # For each cell add a special feature for all its word pieces.
  1399. for (column_index, row_index), relations in cell_indices_to_relations.items():
  1400. relation_set_index = 0
  1401. for relation in relations:
  1402. assert relation.value >= Relation.EQ.value
  1403. relation_set_index += 2 ** (relation.value - Relation.EQ.value)
  1404. for cell_token_index in self._get_cell_token_indexes(column_ids, row_ids, column_index, row_index):
  1405. numeric_relations[cell_token_index] = relation_set_index
  1406. return numeric_relations
  1407. def _get_numeric_values(self, table, column_ids, row_ids):
  1408. """Returns numeric values for computation of answer loss."""
  1409. numeric_values = [float("nan")] * len(column_ids)
  1410. if table is not None:
  1411. num_rows = table.shape[0]
  1412. num_columns = table.shape[1]
  1413. for col_index in range(num_columns):
  1414. for row_index in range(num_rows):
  1415. numeric_value = table.iloc[row_index, col_index].numeric_value
  1416. if numeric_value is not None:
  1417. if numeric_value.float_value is None:
  1418. continue
  1419. float_value = numeric_value.float_value
  1420. if float_value == float("inf"):
  1421. continue
  1422. for index in self._get_cell_token_indexes(column_ids, row_ids, col_index, row_index):
  1423. numeric_values[index] = float_value
  1424. return numeric_values
  1425. def _get_numeric_values_scale(self, table, column_ids, row_ids):
  1426. """Returns a scale to each token to down weigh the value of long words."""
  1427. numeric_values_scale = [1.0] * len(column_ids)
  1428. if table is None:
  1429. return numeric_values_scale
  1430. num_rows = table.shape[0]
  1431. num_columns = table.shape[1]
  1432. for col_index in range(num_columns):
  1433. for row_index in range(num_rows):
  1434. indices = list(self._get_cell_token_indexes(column_ids, row_ids, col_index, row_index))
  1435. num_indices = len(indices)
  1436. if num_indices > 1:
  1437. for index in indices:
  1438. numeric_values_scale[index] = float(num_indices)
  1439. return numeric_values_scale
  1440. def _pad_to_seq_length(self, inputs):
  1441. while len(inputs) > self.model_max_length:
  1442. inputs.pop()
  1443. while len(inputs) < self.model_max_length:
  1444. inputs.append(0)
  1445. def _get_all_answer_ids_from_coordinates(
  1446. self,
  1447. column_ids,
  1448. row_ids,
  1449. answers_list,
  1450. ):
  1451. """Maps lists of answer coordinates to token indexes."""
  1452. answer_ids = [0] * len(column_ids)
  1453. found_answers = set()
  1454. all_answers = set()
  1455. for answers in answers_list:
  1456. column_index, row_index = answers
  1457. all_answers.add((column_index, row_index))
  1458. for index in self._get_cell_token_indexes(column_ids, row_ids, column_index, row_index):
  1459. found_answers.add((column_index, row_index))
  1460. answer_ids[index] = 1
  1461. missing_count = len(all_answers) - len(found_answers)
  1462. return answer_ids, missing_count
  1463. def _get_all_answer_ids(self, column_ids, row_ids, answer_coordinates):
  1464. """
  1465. Maps answer coordinates of a question to token indexes.
  1466. In the SQA format (TSV), the coordinates are given as (row, column) tuples. Here, we first swap them to
  1467. (column, row) format before calling _get_all_answer_ids_from_coordinates.
  1468. """
  1469. def _to_coordinates(answer_coordinates_question):
  1470. return [(coords[1], coords[0]) for coords in answer_coordinates_question]
  1471. return self._get_all_answer_ids_from_coordinates(
  1472. column_ids, row_ids, answers_list=(_to_coordinates(answer_coordinates))
  1473. )
  1474. def _find_tokens(self, text, segment):
  1475. """Return start index of segment in text or None."""
  1476. logging.info(f"text: {text} {segment}")
  1477. for index in range(1 + len(text) - len(segment)):
  1478. for seg_index, seg_token in enumerate(segment):
  1479. if text[index + seg_index].piece != seg_token.piece:
  1480. break
  1481. else:
  1482. return index
  1483. return None
  1484. def _find_answer_coordinates_from_answer_text(
  1485. self,
  1486. tokenized_table,
  1487. answer_text,
  1488. ):
  1489. """Returns all occurrences of answer_text in the table."""
  1490. logging.info(f"answer text: {answer_text}")
  1491. for row_index, row in enumerate(tokenized_table.rows):
  1492. if row_index == 0:
  1493. # We don't search for answers in the header.
  1494. continue
  1495. for col_index, cell in enumerate(row):
  1496. token_index = self._find_tokens(cell, answer_text)
  1497. if token_index is not None:
  1498. yield TokenCoordinates(
  1499. row_index=row_index,
  1500. column_index=col_index,
  1501. token_index=token_index,
  1502. )
  1503. def _find_answer_ids_from_answer_texts(
  1504. self,
  1505. column_ids,
  1506. row_ids,
  1507. tokenized_table,
  1508. answer_texts,
  1509. ):
  1510. """Maps question with answer texts to the first matching token indexes."""
  1511. answer_ids = [0] * len(column_ids)
  1512. for answer_text in answer_texts:
  1513. for coordinates in self._find_answer_coordinates_from_answer_text(
  1514. tokenized_table,
  1515. answer_text,
  1516. ):
  1517. # Maps answer coordinates to indexes this can fail if tokens / rows have
  1518. # been pruned.
  1519. indexes = list(
  1520. self._get_cell_token_indexes(
  1521. column_ids,
  1522. row_ids,
  1523. column_id=coordinates.column_index,
  1524. row_id=coordinates.row_index - 1,
  1525. )
  1526. )
  1527. indexes.sort()
  1528. coordinate_answer_ids = []
  1529. if indexes:
  1530. begin_index = coordinates.token_index + indexes[0]
  1531. end_index = begin_index + len(answer_text)
  1532. for index in indexes:
  1533. if index >= begin_index and index < end_index:
  1534. coordinate_answer_ids.append(index)
  1535. if len(coordinate_answer_ids) == len(answer_text):
  1536. for index in coordinate_answer_ids:
  1537. answer_ids[index] = 1
  1538. break
  1539. return answer_ids
  1540. def _get_answer_ids(self, column_ids, row_ids, answer_coordinates):
  1541. """Maps answer coordinates of a question to token indexes."""
  1542. answer_ids, missing_count = self._get_all_answer_ids(column_ids, row_ids, answer_coordinates)
  1543. if missing_count:
  1544. raise ValueError("Couldn't find all answers")
  1545. return answer_ids
  1546. def get_answer_ids(self, column_ids, row_ids, tokenized_table, answer_texts_question, answer_coordinates_question):
  1547. if self.update_answer_coordinates:
  1548. return self._find_answer_ids_from_answer_texts(
  1549. column_ids,
  1550. row_ids,
  1551. tokenized_table,
  1552. answer_texts=[self.tokenize(at) for at in answer_texts_question],
  1553. )
  1554. return self._get_answer_ids(column_ids, row_ids, answer_coordinates_question)
  1555. def _pad(
  1556. self,
  1557. encoded_inputs: Union[dict[str, EncodedInput], BatchEncoding],
  1558. max_length: Optional[int] = None,
  1559. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  1560. pad_to_multiple_of: Optional[int] = None,
  1561. padding_side: Optional[str] = None,
  1562. return_attention_mask: Optional[bool] = None,
  1563. ) -> dict:
  1564. """
  1565. Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
  1566. Args:
  1567. encoded_inputs:
  1568. Dictionary of tokenized inputs (`list[int]`) or batch of tokenized inputs (`list[list[int]]`).
  1569. max_length: maximum length of the returned list and optionally padding length (see below).
  1570. Will truncate by taking into account the special tokens.
  1571. padding_strategy: PaddingStrategy to use for padding.
  1572. - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
  1573. - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
  1574. - PaddingStrategy.DO_NOT_PAD: Do not pad
  1575. The tokenizer padding sides are defined in self.padding_side:
  1576. - 'left': pads on the left of the sequences
  1577. - 'right': pads on the right of the sequences
  1578. pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
  1579. This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
  1580. `>= 7.5` (Volta).
  1581. padding_side:
  1582. The side on which the model should have padding applied. Should be selected between ['right', 'left'].
  1583. Default value is picked from the class attribute of the same name.
  1584. return_attention_mask:
  1585. (optional) Set to False to avoid returning attention mask (default: set to model specifics)
  1586. """
  1587. # Load from model defaults
  1588. if return_attention_mask is None:
  1589. return_attention_mask = "attention_mask" in self.model_input_names
  1590. if padding_strategy == PaddingStrategy.LONGEST:
  1591. max_length = len(encoded_inputs["input_ids"])
  1592. if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
  1593. max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
  1594. needs_to_be_padded = (
  1595. padding_strategy != PaddingStrategy.DO_NOT_PAD and len(encoded_inputs["input_ids"]) != max_length
  1596. )
  1597. # Initialize attention mask if not present.
  1598. if return_attention_mask and "attention_mask" not in encoded_inputs:
  1599. encoded_inputs["attention_mask"] = [1] * len(encoded_inputs["input_ids"])
  1600. if needs_to_be_padded:
  1601. difference = max_length - len(encoded_inputs["input_ids"])
  1602. padding_side = padding_side if padding_side is not None else self.padding_side
  1603. if padding_side == "right":
  1604. if return_attention_mask:
  1605. encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
  1606. if "token_type_ids" in encoded_inputs:
  1607. encoded_inputs["token_type_ids"] = (
  1608. encoded_inputs["token_type_ids"] + [[self.pad_token_type_id] * 7] * difference
  1609. )
  1610. if "labels" in encoded_inputs:
  1611. encoded_inputs["labels"] = encoded_inputs["labels"] + [0] * difference
  1612. if "numeric_values" in encoded_inputs:
  1613. encoded_inputs["numeric_values"] = encoded_inputs["numeric_values"] + [float("nan")] * difference
  1614. if "numeric_values_scale" in encoded_inputs:
  1615. encoded_inputs["numeric_values_scale"] = (
  1616. encoded_inputs["numeric_values_scale"] + [1.0] * difference
  1617. )
  1618. if "special_tokens_mask" in encoded_inputs:
  1619. encoded_inputs["special_tokens_mask"] = encoded_inputs["special_tokens_mask"] + [1] * difference
  1620. encoded_inputs["input_ids"] = encoded_inputs["input_ids"] + [self.pad_token_id] * difference
  1621. elif padding_side == "left":
  1622. if return_attention_mask:
  1623. encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
  1624. if "token_type_ids" in encoded_inputs:
  1625. encoded_inputs["token_type_ids"] = [[self.pad_token_type_id] * 7] * difference + encoded_inputs[
  1626. "token_type_ids"
  1627. ]
  1628. if "labels" in encoded_inputs:
  1629. encoded_inputs["labels"] = [0] * difference + encoded_inputs["labels"]
  1630. if "numeric_values" in encoded_inputs:
  1631. encoded_inputs["numeric_values"] = [float("nan")] * difference + encoded_inputs["numeric_values"]
  1632. if "numeric_values_scale" in encoded_inputs:
  1633. encoded_inputs["numeric_values_scale"] = [1.0] * difference + encoded_inputs[
  1634. "numeric_values_scale"
  1635. ]
  1636. if "special_tokens_mask" in encoded_inputs:
  1637. encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
  1638. encoded_inputs["input_ids"] = [self.pad_token_id] * difference + encoded_inputs["input_ids"]
  1639. else:
  1640. raise ValueError("Invalid padding strategy:" + str(padding_side))
  1641. return encoded_inputs
  1642. # Everything related to converting logits to predictions
  1643. def _get_cell_token_probs(self, probabilities, segment_ids, row_ids, column_ids):
  1644. for i, p in enumerate(probabilities):
  1645. segment_id = segment_ids[i]
  1646. col = column_ids[i] - 1
  1647. row = row_ids[i] - 1
  1648. if col >= 0 and row >= 0 and segment_id == 1:
  1649. yield i, p
  1650. def _get_mean_cell_probs(self, probabilities, segment_ids, row_ids, column_ids):
  1651. """Computes average probability per cell, aggregating over tokens."""
  1652. coords_to_probs = collections.defaultdict(list)
  1653. for i, prob in self._get_cell_token_probs(probabilities, segment_ids, row_ids, column_ids):
  1654. col = column_ids[i] - 1
  1655. row = row_ids[i] - 1
  1656. coords_to_probs[(col, row)].append(prob)
  1657. return {coords: np.array(cell_probs).mean() for coords, cell_probs in coords_to_probs.items()}
  1658. def convert_logits_to_predictions(self, data, logits, logits_agg=None, cell_classification_threshold=0.5):
  1659. """
  1660. Converts logits of [`TapasForQuestionAnswering`] to actual predicted answer coordinates and optional
  1661. aggregation indices.
  1662. The original implementation, on which this function is based, can be found
  1663. [here](https://github.com/google-research/tapas/blob/4908213eb4df7aa988573350278b44c4dbe3f71b/tapas/experiments/prediction_utils.py#L288).
  1664. Args:
  1665. data (`dict`):
  1666. Dictionary mapping features to actual values. Should be created using [`TapasTokenizer`].
  1667. logits (`torch.Tensor` or `tf.Tensor` of shape `(batch_size, sequence_length)`):
  1668. Tensor containing the logits at the token level.
  1669. logits_agg (`torch.Tensor` or `tf.Tensor` of shape `(batch_size, num_aggregation_labels)`, *optional*):
  1670. Tensor containing the aggregation logits.
  1671. cell_classification_threshold (`float`, *optional*, defaults to 0.5):
  1672. Threshold to be used for cell selection. All table cells for which their probability is larger than
  1673. this threshold will be selected.
  1674. Returns:
  1675. `tuple` comprising various elements depending on the inputs:
  1676. - predicted_answer_coordinates (`list[list[[tuple]]` of length `batch_size`): Predicted answer coordinates
  1677. as a list of lists of tuples. Each element in the list contains the predicted answer coordinates of a
  1678. single example in the batch, as a list of tuples. Each tuple is a cell, i.e. (row index, column index).
  1679. - predicted_aggregation_indices (`list[int]`of length `batch_size`, *optional*, returned when
  1680. `logits_aggregation` is provided): Predicted aggregation operator indices of the aggregation head.
  1681. """
  1682. # converting to numpy arrays to work with PT/TF
  1683. logits = logits.numpy()
  1684. if logits_agg is not None:
  1685. logits_agg = logits_agg.numpy()
  1686. data = {key: value.numpy() for key, value in data.items() if key != "training"}
  1687. # input data is of type float32
  1688. # np.log(np.finfo(np.float32).max) = 88.72284
  1689. # Any value over 88.72284 will overflow when passed through the exponential, sending a warning
  1690. # We disable this warning by truncating the logits.
  1691. logits[logits < -88.7] = -88.7
  1692. # Compute probabilities from token logits
  1693. probabilities = 1 / (1 + np.exp(-logits)) * data["attention_mask"]
  1694. token_types = [
  1695. "segment_ids",
  1696. "column_ids",
  1697. "row_ids",
  1698. "prev_labels",
  1699. "column_ranks",
  1700. "inv_column_ranks",
  1701. "numeric_relations",
  1702. ]
  1703. # collect input_ids, segment ids, row ids and column ids of batch. Shape (batch_size, seq_len)
  1704. input_ids = data["input_ids"]
  1705. segment_ids = data["token_type_ids"][:, :, token_types.index("segment_ids")]
  1706. row_ids = data["token_type_ids"][:, :, token_types.index("row_ids")]
  1707. column_ids = data["token_type_ids"][:, :, token_types.index("column_ids")]
  1708. # next, get answer coordinates for every example in the batch
  1709. num_batch = input_ids.shape[0]
  1710. predicted_answer_coordinates = []
  1711. for i in range(num_batch):
  1712. probabilities_example = probabilities[i].tolist()
  1713. segment_ids_example = segment_ids[i]
  1714. row_ids_example = row_ids[i]
  1715. column_ids_example = column_ids[i]
  1716. max_width = column_ids_example.max()
  1717. max_height = row_ids_example.max()
  1718. if max_width == 0 and max_height == 0:
  1719. continue
  1720. cell_coords_to_prob = self._get_mean_cell_probs(
  1721. probabilities_example,
  1722. segment_ids_example.tolist(),
  1723. row_ids_example.tolist(),
  1724. column_ids_example.tolist(),
  1725. )
  1726. # Select the answers above the classification threshold.
  1727. answer_coordinates = []
  1728. for col in range(max_width):
  1729. for row in range(max_height):
  1730. cell_prob = cell_coords_to_prob.get((col, row), None)
  1731. if cell_prob is not None:
  1732. if cell_prob > cell_classification_threshold:
  1733. answer_coordinates.append((row, col))
  1734. answer_coordinates = sorted(answer_coordinates)
  1735. predicted_answer_coordinates.append(answer_coordinates)
  1736. output = (predicted_answer_coordinates,)
  1737. if logits_agg is not None:
  1738. predicted_aggregation_indices = logits_agg.argmax(axis=-1)
  1739. output = (predicted_answer_coordinates, predicted_aggregation_indices.tolist())
  1740. return output
  1741. # End of everything related to converting logits to predictions
  1742. # Copied from transformers.models.bert.tokenization_bert.BasicTokenizer
  1743. class BasicTokenizer:
  1744. """
  1745. Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
  1746. Args:
  1747. do_lower_case (`bool`, *optional*, defaults to `True`):
  1748. Whether or not to lowercase the input when tokenizing.
  1749. never_split (`Iterable`, *optional*):
  1750. Collection of tokens which will never be split during tokenization. Only has an effect when
  1751. `do_basic_tokenize=True`
  1752. tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
  1753. Whether or not to tokenize Chinese characters.
  1754. This should likely be deactivated for Japanese (see this
  1755. [issue](https://github.com/huggingface/transformers/issues/328)).
  1756. strip_accents (`bool`, *optional*):
  1757. Whether or not to strip all accents. If this option is not specified, then it will be determined by the
  1758. value for `lowercase` (as in the original BERT).
  1759. do_split_on_punc (`bool`, *optional*, defaults to `True`):
  1760. In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
  1761. the full context of the words, such as contractions.
  1762. """
  1763. def __init__(
  1764. self,
  1765. do_lower_case=True,
  1766. never_split=None,
  1767. tokenize_chinese_chars=True,
  1768. strip_accents=None,
  1769. do_split_on_punc=True,
  1770. ):
  1771. if never_split is None:
  1772. never_split = []
  1773. self.do_lower_case = do_lower_case
  1774. self.never_split = set(never_split)
  1775. self.tokenize_chinese_chars = tokenize_chinese_chars
  1776. self.strip_accents = strip_accents
  1777. self.do_split_on_punc = do_split_on_punc
  1778. def tokenize(self, text, never_split=None):
  1779. """
  1780. Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
  1781. Args:
  1782. never_split (`List[str]`, *optional*)
  1783. Kept for backward compatibility purposes. Now implemented directly at the base class level (see
  1784. [`PreTrainedTokenizer.tokenize`]) List of token not to split.
  1785. """
  1786. # union() returns a new set by concatenating the two sets.
  1787. never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
  1788. text = self._clean_text(text)
  1789. # This was added on November 1st, 2018 for the multilingual and Chinese
  1790. # models. This is also applied to the English models now, but it doesn't
  1791. # matter since the English models were not trained on any Chinese data
  1792. # and generally don't have any Chinese data in them (there are Chinese
  1793. # characters in the vocabulary because Wikipedia does have some Chinese
  1794. # words in the English Wikipedia.).
  1795. if self.tokenize_chinese_chars:
  1796. text = self._tokenize_chinese_chars(text)
  1797. # prevents treating the same character with different unicode codepoints as different characters
  1798. unicode_normalized_text = unicodedata.normalize("NFC", text)
  1799. orig_tokens = whitespace_tokenize(unicode_normalized_text)
  1800. split_tokens = []
  1801. for token in orig_tokens:
  1802. if token not in never_split:
  1803. if self.do_lower_case:
  1804. token = token.lower()
  1805. if self.strip_accents is not False:
  1806. token = self._run_strip_accents(token)
  1807. elif self.strip_accents:
  1808. token = self._run_strip_accents(token)
  1809. split_tokens.extend(self._run_split_on_punc(token, never_split))
  1810. output_tokens = whitespace_tokenize(" ".join(split_tokens))
  1811. return output_tokens
  1812. def _run_strip_accents(self, text):
  1813. """Strips accents from a piece of text."""
  1814. text = unicodedata.normalize("NFD", text)
  1815. output = []
  1816. for char in text:
  1817. cat = unicodedata.category(char)
  1818. if cat == "Mn":
  1819. continue
  1820. output.append(char)
  1821. return "".join(output)
  1822. def _run_split_on_punc(self, text, never_split=None):
  1823. """Splits punctuation on a piece of text."""
  1824. if not self.do_split_on_punc or (never_split is not None and text in never_split):
  1825. return [text]
  1826. chars = list(text)
  1827. i = 0
  1828. start_new_word = True
  1829. output = []
  1830. while i < len(chars):
  1831. char = chars[i]
  1832. if _is_punctuation(char):
  1833. output.append([char])
  1834. start_new_word = True
  1835. else:
  1836. if start_new_word:
  1837. output.append([])
  1838. start_new_word = False
  1839. output[-1].append(char)
  1840. i += 1
  1841. return ["".join(x) for x in output]
  1842. def _tokenize_chinese_chars(self, text):
  1843. """Adds whitespace around any CJK character."""
  1844. output = []
  1845. for char in text:
  1846. cp = ord(char)
  1847. if self._is_chinese_char(cp):
  1848. output.append(" ")
  1849. output.append(char)
  1850. output.append(" ")
  1851. else:
  1852. output.append(char)
  1853. return "".join(output)
  1854. def _is_chinese_char(self, cp):
  1855. """Checks whether CP is the codepoint of a CJK character."""
  1856. # This defines a "chinese character" as anything in the CJK Unicode block:
  1857. # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
  1858. #
  1859. # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
  1860. # despite its name. The modern Korean Hangul alphabet is a different block,
  1861. # as is Japanese Hiragana and Katakana. Those alphabets are used to write
  1862. # space-separated words, so they are not treated specially and handled
  1863. # like the all of the other languages.
  1864. if (
  1865. (cp >= 0x4E00 and cp <= 0x9FFF)
  1866. or (cp >= 0x3400 and cp <= 0x4DBF)
  1867. or (cp >= 0x20000 and cp <= 0x2A6DF)
  1868. or (cp >= 0x2A700 and cp <= 0x2B73F)
  1869. or (cp >= 0x2B740 and cp <= 0x2B81F)
  1870. or (cp >= 0x2B820 and cp <= 0x2CEAF)
  1871. or (cp >= 0xF900 and cp <= 0xFAFF)
  1872. or (cp >= 0x2F800 and cp <= 0x2FA1F)
  1873. ):
  1874. return True
  1875. return False
  1876. def _clean_text(self, text):
  1877. """Performs invalid character removal and whitespace cleanup on text."""
  1878. output = []
  1879. for char in text:
  1880. cp = ord(char)
  1881. if cp == 0 or cp == 0xFFFD or _is_control(char):
  1882. continue
  1883. if _is_whitespace(char):
  1884. output.append(" ")
  1885. else:
  1886. output.append(char)
  1887. return "".join(output)
  1888. # Copied from transformers.models.bert.tokenization_bert.WordpieceTokenizer
  1889. class WordpieceTokenizer:
  1890. """Runs WordPiece tokenization."""
  1891. def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
  1892. self.vocab = vocab
  1893. self.unk_token = unk_token
  1894. self.max_input_chars_per_word = max_input_chars_per_word
  1895. def tokenize(self, text):
  1896. """
  1897. Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
  1898. tokenization using the given vocabulary.
  1899. For example, `input = "unaffable"` will return as output `["un", "##aff", "##able"]`.
  1900. Args:
  1901. text: A single token or whitespace separated tokens. This should have
  1902. already been passed through *BasicTokenizer*.
  1903. Returns:
  1904. A list of wordpiece tokens.
  1905. """
  1906. output_tokens = []
  1907. for token in whitespace_tokenize(text):
  1908. chars = list(token)
  1909. if len(chars) > self.max_input_chars_per_word:
  1910. output_tokens.append(self.unk_token)
  1911. continue
  1912. is_bad = False
  1913. start = 0
  1914. sub_tokens = []
  1915. while start < len(chars):
  1916. end = len(chars)
  1917. cur_substr = None
  1918. while start < end:
  1919. substr = "".join(chars[start:end])
  1920. if start > 0:
  1921. substr = "##" + substr
  1922. if substr in self.vocab:
  1923. cur_substr = substr
  1924. break
  1925. end -= 1
  1926. if cur_substr is None:
  1927. is_bad = True
  1928. break
  1929. sub_tokens.append(cur_substr)
  1930. start = end
  1931. if is_bad:
  1932. output_tokens.append(self.unk_token)
  1933. else:
  1934. output_tokens.extend(sub_tokens)
  1935. return output_tokens
  1936. # Below: utilities for TAPAS tokenizer (independent from PyTorch/Tensorflow).
  1937. # This includes functions to parse numeric values (dates and numbers) from both the table and questions in order
  1938. # to create the column_ranks, inv_column_ranks, numeric_values, numeric values_scale and numeric_relations in
  1939. # prepare_for_model of TapasTokenizer.
  1940. # These are meant to be used in an academic setup, for production use cases Gold mine or Aqua should be used.
  1941. # taken from constants.py of the original implementation
  1942. # URL: https://github.com/google-research/tapas/blob/master/tapas/utils/constants.py
  1943. class Relation(enum.Enum):
  1944. HEADER_TO_CELL = 1 # Connects header to cell.
  1945. CELL_TO_HEADER = 2 # Connects cell to header.
  1946. QUERY_TO_HEADER = 3 # Connects query to headers.
  1947. QUERY_TO_CELL = 4 # Connects query to cells.
  1948. ROW_TO_CELL = 5 # Connects row to cells.
  1949. CELL_TO_ROW = 6 # Connects cells to row.
  1950. EQ = 7 # Annotation value is same as cell value
  1951. LT = 8 # Annotation value is less than cell value
  1952. GT = 9 # Annotation value is greater than cell value
  1953. @dataclass
  1954. class Date:
  1955. year: Optional[int] = None
  1956. month: Optional[int] = None
  1957. day: Optional[int] = None
  1958. @dataclass
  1959. class NumericValue:
  1960. float_value: Optional[float] = None
  1961. date: Optional[Date] = None
  1962. @dataclass
  1963. class NumericValueSpan:
  1964. begin_index: Optional[int] = None
  1965. end_index: Optional[int] = None
  1966. values: list[NumericValue] = None
  1967. @dataclass
  1968. class Cell:
  1969. text: str
  1970. numeric_value: Optional[NumericValue] = None
  1971. @dataclass
  1972. class Question:
  1973. original_text: str # The original raw question string.
  1974. text: str # The question string after normalization.
  1975. numeric_spans: Optional[list[NumericValueSpan]] = None
  1976. # Below: all functions from number_utils.py as well as 2 functions (namely get_all_spans and normalize_for_match)
  1977. # from text_utils.py of the original implementation. URL's:
  1978. # - https://github.com/google-research/tapas/blob/master/tapas/utils/number_utils.py
  1979. # - https://github.com/google-research/tapas/blob/master/tapas/utils/text_utils.py
  1980. # Constants for parsing date expressions.
  1981. # Masks that specify (by a bool) which of (year, month, day) will be populated.
  1982. _DateMask = collections.namedtuple("_DateMask", ["year", "month", "day"])
  1983. _YEAR = _DateMask(True, False, False)
  1984. _YEAR_MONTH = _DateMask(True, True, False)
  1985. _YEAR_MONTH_DAY = _DateMask(True, True, True)
  1986. _MONTH = _DateMask(False, True, False)
  1987. _MONTH_DAY = _DateMask(False, True, True)
  1988. # Pairs of patterns to pass to 'datetime.strptime' and masks specifying which
  1989. # fields will be set by the corresponding pattern.
  1990. _DATE_PATTERNS = (
  1991. ("%B", _MONTH),
  1992. ("%Y", _YEAR),
  1993. ("%Ys", _YEAR),
  1994. ("%b %Y", _YEAR_MONTH),
  1995. ("%B %Y", _YEAR_MONTH),
  1996. ("%B %d", _MONTH_DAY),
  1997. ("%b %d", _MONTH_DAY),
  1998. ("%d %b", _MONTH_DAY),
  1999. ("%d %B", _MONTH_DAY),
  2000. ("%B %d, %Y", _YEAR_MONTH_DAY),
  2001. ("%d %B %Y", _YEAR_MONTH_DAY),
  2002. ("%m-%d-%Y", _YEAR_MONTH_DAY),
  2003. ("%Y-%m-%d", _YEAR_MONTH_DAY),
  2004. ("%Y-%m", _YEAR_MONTH),
  2005. ("%B %Y", _YEAR_MONTH),
  2006. ("%d %b %Y", _YEAR_MONTH_DAY),
  2007. ("%Y-%m-%d", _YEAR_MONTH_DAY),
  2008. ("%b %d, %Y", _YEAR_MONTH_DAY),
  2009. ("%d.%m.%Y", _YEAR_MONTH_DAY),
  2010. ("%A, %b %d", _MONTH_DAY),
  2011. ("%A, %B %d", _MONTH_DAY),
  2012. )
  2013. # This mapping is used to convert date patterns to regex patterns.
  2014. _FIELD_TO_REGEX = (
  2015. ("%A", r"\w+"), # Weekday as locale’s full name.
  2016. ("%B", r"\w+"), # Month as locale’s full name.
  2017. ("%Y", r"\d{4}"), # Year with century as a decimal number.
  2018. ("%b", r"\w{3}"), # Month as locale’s abbreviated name.
  2019. ("%d", r"\d{1,2}"), # Day of the month as a zero-padded decimal number.
  2020. ("%m", r"\d{1,2}"), # Month as a zero-padded decimal number.
  2021. )
  2022. def _process_date_pattern(dp):
  2023. """Compute a regex for each date pattern to use as a prefilter."""
  2024. pattern, mask = dp
  2025. regex = pattern
  2026. regex = regex.replace(".", re.escape("."))
  2027. regex = regex.replace("-", re.escape("-"))
  2028. regex = regex.replace(" ", r"\s+")
  2029. for field, field_regex in _FIELD_TO_REGEX:
  2030. regex = regex.replace(field, field_regex)
  2031. # Make sure we didn't miss any of the fields.
  2032. assert "%" not in regex, regex
  2033. return pattern, mask, re.compile("^" + regex + "$")
  2034. def _process_date_patterns():
  2035. return tuple(_process_date_pattern(dp) for dp in _DATE_PATTERNS)
  2036. _PROCESSED_DATE_PATTERNS = _process_date_patterns()
  2037. _MAX_DATE_NGRAM_SIZE = 5
  2038. # Following DynSp:
  2039. # https://github.com/Microsoft/DynSP/blob/master/util.py#L414.
  2040. _NUMBER_WORDS = [
  2041. "zero",
  2042. "one",
  2043. "two",
  2044. "three",
  2045. "four",
  2046. "five",
  2047. "six",
  2048. "seven",
  2049. "eight",
  2050. "nine",
  2051. "ten",
  2052. "eleven",
  2053. "twelve",
  2054. ]
  2055. _ORDINAL_WORDS = [
  2056. "zeroth",
  2057. "first",
  2058. "second",
  2059. "third",
  2060. "fourth",
  2061. "fifth",
  2062. "sixth",
  2063. "seventh",
  2064. "eighth",
  2065. "ninth",
  2066. "tenth",
  2067. "eleventh",
  2068. "twelfth",
  2069. ]
  2070. _ORDINAL_SUFFIXES = ["st", "nd", "rd", "th"]
  2071. _NUMBER_PATTERN = re.compile(r"((^|\s)[+-])?((\.\d+)|(\d+(,\d\d\d)*(\.\d*)?))")
  2072. # Following DynSp:
  2073. # https://github.com/Microsoft/DynSP/blob/master/util.py#L293.
  2074. _MIN_YEAR = 1700
  2075. _MAX_YEAR = 2016
  2076. _INF = float("INF")
  2077. def _get_numeric_value_from_date(date, mask):
  2078. """Converts date (datetime Python object) to a NumericValue object with a Date object value."""
  2079. if date.year < _MIN_YEAR or date.year > _MAX_YEAR:
  2080. raise ValueError(f"Invalid year: {date.year}")
  2081. new_date = Date()
  2082. if mask.year:
  2083. new_date.year = date.year
  2084. if mask.month:
  2085. new_date.month = date.month
  2086. if mask.day:
  2087. new_date.day = date.day
  2088. return NumericValue(date=new_date)
  2089. def _get_span_length_key(span):
  2090. """Sorts span by decreasing length first and increasing first index second."""
  2091. return span[1] - span[0], -span[0]
  2092. def _get_numeric_value_from_float(value):
  2093. """Converts float (Python) to a NumericValue object with a float value."""
  2094. return NumericValue(float_value=value)
  2095. # Doesn't parse ordinal expressions such as '18th of february 1655'.
  2096. def _parse_date(text):
  2097. """Attempts to format a text as a standard date string (yyyy-mm-dd)."""
  2098. text = re.sub(r"Sept\b", "Sep", text)
  2099. for in_pattern, mask, regex in _PROCESSED_DATE_PATTERNS:
  2100. if not regex.match(text):
  2101. continue
  2102. try:
  2103. date = datetime.datetime.strptime(text, in_pattern).date()
  2104. except ValueError:
  2105. continue
  2106. try:
  2107. return _get_numeric_value_from_date(date, mask)
  2108. except ValueError:
  2109. continue
  2110. return None
  2111. def _parse_number(text):
  2112. """Parses simple cardinal and ordinals numbers."""
  2113. for suffix in _ORDINAL_SUFFIXES:
  2114. if text.endswith(suffix):
  2115. text = text[: -len(suffix)]
  2116. break
  2117. text = text.replace(",", "")
  2118. try:
  2119. value = float(text)
  2120. except ValueError:
  2121. return None
  2122. if math.isnan(value):
  2123. return None
  2124. if value == _INF:
  2125. return None
  2126. return value
  2127. def get_all_spans(text, max_ngram_length):
  2128. """
  2129. Split a text into all possible ngrams up to 'max_ngram_length'. Split points are white space and punctuation.
  2130. Args:
  2131. text: Text to split.
  2132. max_ngram_length: maximal ngram length.
  2133. Yields:
  2134. Spans, tuples of begin-end index.
  2135. """
  2136. start_indexes = []
  2137. for index, char in enumerate(text):
  2138. if not char.isalnum():
  2139. continue
  2140. if index == 0 or not text[index - 1].isalnum():
  2141. start_indexes.append(index)
  2142. if index + 1 == len(text) or not text[index + 1].isalnum():
  2143. for start_index in start_indexes[-max_ngram_length:]:
  2144. yield start_index, index + 1
  2145. def normalize_for_match(text):
  2146. return " ".join(text.lower().split())
  2147. def format_text(text):
  2148. """Lowercases and strips punctuation."""
  2149. text = text.lower().strip()
  2150. if text == "n/a" or text == "?" or text == "nan":
  2151. text = EMPTY_TEXT
  2152. text = re.sub(r"[^\w\d]+", " ", text).replace("_", " ")
  2153. text = " ".join(text.split())
  2154. text = text.strip()
  2155. if text:
  2156. return text
  2157. return EMPTY_TEXT
  2158. def parse_text(text):
  2159. """
  2160. Extracts longest number and date spans.
  2161. Args:
  2162. text: text to annotate
  2163. Returns:
  2164. List of longest numeric value spans.
  2165. """
  2166. span_dict = collections.defaultdict(list)
  2167. for match in _NUMBER_PATTERN.finditer(text):
  2168. span_text = text[match.start() : match.end()]
  2169. number = _parse_number(span_text)
  2170. if number is not None:
  2171. span_dict[match.span()].append(_get_numeric_value_from_float(number))
  2172. for begin_index, end_index in get_all_spans(text, max_ngram_length=1):
  2173. if (begin_index, end_index) in span_dict:
  2174. continue
  2175. span_text = text[begin_index:end_index]
  2176. number = _parse_number(span_text)
  2177. if number is not None:
  2178. span_dict[begin_index, end_index].append(_get_numeric_value_from_float(number))
  2179. for number, word in enumerate(_NUMBER_WORDS):
  2180. if span_text == word:
  2181. span_dict[begin_index, end_index].append(_get_numeric_value_from_float(float(number)))
  2182. break
  2183. for number, word in enumerate(_ORDINAL_WORDS):
  2184. if span_text == word:
  2185. span_dict[begin_index, end_index].append(_get_numeric_value_from_float(float(number)))
  2186. break
  2187. for begin_index, end_index in get_all_spans(text, max_ngram_length=_MAX_DATE_NGRAM_SIZE):
  2188. span_text = text[begin_index:end_index]
  2189. date = _parse_date(span_text)
  2190. if date is not None:
  2191. span_dict[begin_index, end_index].append(date)
  2192. spans = sorted(span_dict.items(), key=lambda span_value: _get_span_length_key(span_value[0]), reverse=True)
  2193. selected_spans = []
  2194. for span, value in spans:
  2195. for selected_span, _ in selected_spans:
  2196. if selected_span[0] <= span[0] and span[1] <= selected_span[1]:
  2197. break
  2198. else:
  2199. selected_spans.append((span, value))
  2200. selected_spans.sort(key=lambda span_value: span_value[0][0])
  2201. numeric_value_spans = []
  2202. for span, values in selected_spans:
  2203. numeric_value_spans.append(NumericValueSpan(begin_index=span[0], end_index=span[1], values=values))
  2204. return numeric_value_spans
  2205. # Below: all functions from number_annotation_utils.py and 2 functions (namely filter_invalid_unicode
  2206. # and filter_invalid_unicode_from_table) from text_utils.py of the original implementation. URL's:
  2207. # - https://github.com/google-research/tapas/blob/master/tapas/utils/number_annotation_utils.py
  2208. # - https://github.com/google-research/tapas/blob/master/tapas/utils/text_utils.py
  2209. _PrimitiveNumericValue = Union[float, tuple[Optional[float], Optional[float], Optional[float]]]
  2210. _SortKeyFn = Callable[[NumericValue], tuple[float, Ellipsis]]
  2211. _DATE_TUPLE_SIZE = 3
  2212. EMPTY_TEXT = "EMPTY"
  2213. NUMBER_TYPE = "number"
  2214. DATE_TYPE = "date"
  2215. def _get_value_type(numeric_value):
  2216. if numeric_value.float_value is not None:
  2217. return NUMBER_TYPE
  2218. elif numeric_value.date is not None:
  2219. return DATE_TYPE
  2220. raise ValueError(f"Unknown type: {numeric_value}")
  2221. def _get_value_as_primitive_value(numeric_value):
  2222. """Maps a NumericValue proto to a float or tuple of float."""
  2223. if numeric_value.float_value is not None:
  2224. return numeric_value.float_value
  2225. if numeric_value.date is not None:
  2226. date = numeric_value.date
  2227. value_tuple = [None, None, None]
  2228. # All dates fields are cased to float to produce a simple primitive value.
  2229. if date.year is not None:
  2230. value_tuple[0] = float(date.year)
  2231. if date.month is not None:
  2232. value_tuple[1] = float(date.month)
  2233. if date.day is not None:
  2234. value_tuple[2] = float(date.day)
  2235. return tuple(value_tuple)
  2236. raise ValueError(f"Unknown type: {numeric_value}")
  2237. def _get_all_types(numeric_values):
  2238. return {_get_value_type(value) for value in numeric_values}
  2239. def get_numeric_sort_key_fn(numeric_values):
  2240. """
  2241. Creates a function that can be used as a sort key or to compare the values. Maps to primitive types and finds the
  2242. biggest common subset. Consider the values "05/05/2010" and "August 2007". With the corresponding primitive values
  2243. (2010.,5.,5.) and (2007.,8., None). These values can be compared by year and date so we map to the sequence (2010.,
  2244. 5.), (2007., 8.). If we added a third value "2006" with primitive value (2006., None, None), we could only compare
  2245. by the year so we would map to (2010.,), (2007.,) and (2006.,).
  2246. Args:
  2247. numeric_values: Values to compare
  2248. Returns:
  2249. A function that can be used as a sort key function (mapping numeric values to a comparable tuple)
  2250. Raises:
  2251. ValueError if values don't have a common type or are not comparable.
  2252. """
  2253. value_types = _get_all_types(numeric_values)
  2254. if len(value_types) != 1:
  2255. raise ValueError(f"No common value type in {numeric_values}")
  2256. value_type = next(iter(value_types))
  2257. if value_type == NUMBER_TYPE:
  2258. # Primitive values are simple floats, nothing to do here.
  2259. return _get_value_as_primitive_value
  2260. # The type can only be Date at this point which means the primitive type
  2261. # is a float triple.
  2262. valid_indexes = set(range(_DATE_TUPLE_SIZE))
  2263. for numeric_value in numeric_values:
  2264. value = _get_value_as_primitive_value(numeric_value)
  2265. assert isinstance(value, tuple)
  2266. for tuple_index, inner_value in enumerate(value):
  2267. if inner_value is None:
  2268. valid_indexes.discard(tuple_index)
  2269. if not valid_indexes:
  2270. raise ValueError(f"No common value in {numeric_values}")
  2271. def _sort_key_fn(numeric_value):
  2272. value = _get_value_as_primitive_value(numeric_value)
  2273. return tuple(value[index] for index in valid_indexes)
  2274. return _sort_key_fn
  2275. def _consolidate_numeric_values(row_index_to_values, min_consolidation_fraction, debug_info):
  2276. """
  2277. Finds the most common numeric values in a column and returns them
  2278. Args:
  2279. row_index_to_values:
  2280. For each row index all the values in that cell.
  2281. min_consolidation_fraction:
  2282. Fraction of cells that need to have consolidated value.
  2283. debug_info:
  2284. Additional information only used for logging
  2285. Returns:
  2286. For each row index the first value that matches the most common value. Rows that don't have a matching value
  2287. are dropped. Empty list if values can't be consolidated.
  2288. """
  2289. type_counts = collections.Counter()
  2290. for numeric_values in row_index_to_values.values():
  2291. type_counts.update(_get_all_types(numeric_values))
  2292. if not type_counts:
  2293. return {}
  2294. max_count = max(type_counts.values())
  2295. if max_count < len(row_index_to_values) * min_consolidation_fraction:
  2296. # logging.log_every_n(logging.INFO, f'Can\'t consolidate types: {debug_info} {row_index_to_values} {max_count}', 100)
  2297. return {}
  2298. valid_types = set()
  2299. for value_type, count in type_counts.items():
  2300. if count == max_count:
  2301. valid_types.add(value_type)
  2302. if len(valid_types) > 1:
  2303. assert DATE_TYPE in valid_types
  2304. max_type = DATE_TYPE
  2305. else:
  2306. max_type = next(iter(valid_types))
  2307. new_row_index_to_value = {}
  2308. for index, values in row_index_to_values.items():
  2309. # Extract the first matching value.
  2310. for value in values:
  2311. if _get_value_type(value) == max_type:
  2312. new_row_index_to_value[index] = value
  2313. break
  2314. return new_row_index_to_value
  2315. def _get_numeric_values(text):
  2316. """Parses text and returns numeric values."""
  2317. numeric_spans = parse_text(text)
  2318. return itertools.chain(*(span.values for span in numeric_spans))
  2319. def _get_column_values(table, col_index):
  2320. """
  2321. Parses text in column and returns a dict mapping row_index to values. This is the _get_column_values function from
  2322. number_annotation_utils.py of the original implementation
  2323. Args:
  2324. table: Pandas dataframe
  2325. col_index: integer, indicating the index of the column to get the numeric values of
  2326. """
  2327. index_to_values = {}
  2328. for row_index, row in table.iterrows():
  2329. text = normalize_for_match(row[col_index].text)
  2330. index_to_values[row_index] = list(_get_numeric_values(text))
  2331. return index_to_values
  2332. def get_numeric_relation(value, other_value, sort_key_fn):
  2333. """Compares two values and returns their relation or None."""
  2334. value = sort_key_fn(value)
  2335. other_value = sort_key_fn(other_value)
  2336. if value == other_value:
  2337. return Relation.EQ
  2338. if value < other_value:
  2339. return Relation.LT
  2340. if value > other_value:
  2341. return Relation.GT
  2342. return None
  2343. def add_numeric_values_to_question(question):
  2344. """Adds numeric value spans to a question."""
  2345. original_text = question
  2346. question = normalize_for_match(question)
  2347. numeric_spans = parse_text(question)
  2348. return Question(original_text=original_text, text=question, numeric_spans=numeric_spans)
  2349. def filter_invalid_unicode(text):
  2350. """Return an empty string and True if 'text' is in invalid unicode."""
  2351. return ("", True) if isinstance(text, bytes) else (text, False)
  2352. def filter_invalid_unicode_from_table(table):
  2353. """
  2354. Removes invalid unicode from table. Checks whether a table cell text contains an invalid unicode encoding. If yes,
  2355. reset the table cell text to an empty str and log a warning for each invalid cell
  2356. Args:
  2357. table: table to clean.
  2358. """
  2359. # to do: add table id support
  2360. if not hasattr(table, "table_id"):
  2361. table.table_id = 0
  2362. for row_index, row in table.iterrows():
  2363. for col_index, cell in enumerate(row):
  2364. cell, is_invalid = filter_invalid_unicode(cell)
  2365. if is_invalid:
  2366. logging.warning(
  2367. f"Scrub an invalid table body @ table_id: {table.table_id}, row_index: {row_index}, "
  2368. f"col_index: {col_index}",
  2369. )
  2370. for col_index, column in enumerate(table.columns):
  2371. column, is_invalid = filter_invalid_unicode(column)
  2372. if is_invalid:
  2373. logging.warning(f"Scrub an invalid table header @ table_id: {table.table_id}, col_index: {col_index}")
  2374. def add_numeric_table_values(table, min_consolidation_fraction=0.7, debug_info=None):
  2375. """
  2376. Parses text in table column-wise and adds the consolidated values. Consolidation refers to finding values with a
  2377. common types (date or number)
  2378. Args:
  2379. table:
  2380. Table to annotate.
  2381. min_consolidation_fraction:
  2382. Fraction of cells in a column that need to have consolidated value.
  2383. debug_info:
  2384. Additional information used for logging.
  2385. """
  2386. table = table.copy()
  2387. # First, filter table on invalid unicode
  2388. filter_invalid_unicode_from_table(table)
  2389. # Second, replace cell values by Cell objects
  2390. for row_index, row in table.iterrows():
  2391. for col_index, cell in enumerate(row):
  2392. table.iloc[row_index, col_index] = Cell(text=cell)
  2393. # Third, add numeric_value attributes to these Cell objects
  2394. for col_index, column in enumerate(table.columns):
  2395. column_values = _consolidate_numeric_values(
  2396. _get_column_values(table, col_index),
  2397. min_consolidation_fraction=min_consolidation_fraction,
  2398. debug_info=(debug_info, column),
  2399. )
  2400. for row_index, numeric_value in column_values.items():
  2401. table.iloc[row_index, col_index].numeric_value = numeric_value
  2402. return table
  2403. __all__ = ["TapasTokenizer"]