Upload 2 files
Browse files- README-75m.md +38 -0
- get_bigdocs_75m.py +357 -57
README-75m.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# BigDocs-7.5M
|
| 2 |
+
#### Training data for the paper: [BigDocs: An Open and Permissively-Licensed Dataset for Training Multimodal Models on Document and Code Tasks](https://huggingface.co/datasets/ServiceNow/BigDocs-Bench-Collections/)
|
| 3 |
+
|
| 4 |
+
🌐 [Homepage](https://bigdocs.github.io) | 📖 [arXiv](https://arxiv.org/pdf/2412.04626)
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
## Guide on Data Loading
|
| 8 |
+
Some parts of BigDocs-7.5M are distributed without their "image" column, and instead have an "img_id" column. The file `get_bigdocs_75m.py`, part of this repository, provides tooling to substitutes such images back in.
|
| 9 |
+
|
| 10 |
+
```python
|
| 11 |
+
from get_bigdocs_75m import get_bigdocs_75m
|
| 12 |
+
|
| 13 |
+
arxivocr = get_bigdocs_75m("ArxivOCR")
|
| 14 |
+
arxivtablecap = get_bigdocs_75m("ArxivTableCap")
|
| 15 |
+
cocotext = get_bigdocs_75m("COCOtext", user_local_path=".../train2014")
|
| 16 |
+
pubtables1m = get_bigdocs_75m("pubtables-1m", user_local_path=".../PubTables-1M-Detection/images")
|
| 17 |
+
textocr = get_bigdocs_75m("TextOCR", user_local_path=".../train")
|
| 18 |
+
tabfact = get_bigdocs_75m("TabFact", user_local_path=".../Table-Fact-Checking")
|
| 19 |
+
open4business = get_bigdocs_75m("Open4Business", user_local_path=".../Open4Business")
|
| 20 |
+
wikitq = get_bigdocs_75m("WikiTQ", user_local_path=".../WikiTableQuestions")
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
When specified, `user_local_path` must point to one of the third-party datasets listed below.
|
| 24 |
+
|
| 25 |
+
- COCOtext: http://images.cocodataset.org/zips/train2014.zip
|
| 26 |
+
- pubtables-1m: https://www.microsoft.com/en-us/research/publication/pubtables-1m
|
| 27 |
+
- TextOCR: https://dl.fbaipublicfiles.com/textvqa/images/train_val_images.zip
|
| 28 |
+
- TabFact: https://github.com/wenhuchen/Table-Fact-Checking
|
| 29 |
+
- Open4Business: https://github.com/amanpreet692/Open4Business
|
| 30 |
+
- WikiTQ: https://github.com/ppasupat/WikiTableQuestions
|
| 31 |
+
|
| 32 |
+
You may specify `num_proc` as you would for `datasets.map`. See the docstring in `get_bigdocs_75m.py` for more details.
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
## Licensing
|
| 36 |
+
The part of this repository generated by us is Copyright ServiceNow 2024 and licensed under the [CC-BY-4.0](https://creativecommons.org/licenses/by/4.0/) license.
|
| 37 |
+
|
| 38 |
+
Multiple datasets, documents, and tools were involved in the generation of BigDocs-Bench. We document these dependencies on a per-sample basis through the `query_info`, `annotation_info` and `image_info` fields, respectively documenting the `query`, `annotations` and `image` fields of our datasets.
|
get_bigdocs_75m.py
CHANGED
|
@@ -1,13 +1,34 @@
|
|
|
|
|
| 1 |
from typing import Optional
|
| 2 |
import datasets
|
| 3 |
import io
|
| 4 |
-
import PIL
|
| 5 |
-
import PIL.PngImagePlugin
|
| 6 |
import os
|
|
|
|
| 7 |
import hashlib
|
| 8 |
import warnings
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
|
|
|
|
| 11 |
ASSEMBLED_COLUMNS = (
|
| 12 |
'sample_id',
|
| 13 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: Optional[bool]=None,
|
| 37 |
-
|
| 38 |
-
bigdocs_load_dataset_kwargs: Optional[dict]=None
|
|
|
|
| 39 |
) -> datasets.DatasetDict:
|
| 40 |
"""
|
| 41 |
Get a subset of BigDocs-7.5M
|
|
@@ -50,76 +369,57 @@ def get_bigdocs_75m(
|
|
| 50 |
- COCOtext: http://images.cocodataset.org/zips/train2014.zip
|
| 51 |
- pubtables-1m: https://www.microsoft.com/en-us/research/publication/pubtables-1m
|
| 52 |
- TextOCR: https://dl.fbaipublicfiles.com/textvqa/images/train_val_images.zip
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
Args:
|
| 55 |
-
formal_name (`
|
| 56 |
-
user_local_path (`Optional[str]
|
| 57 |
-
load_from_cache_file (`Optional[bool]
|
| 58 |
-
num_proc (`Optional[int]
|
| 59 |
-
|
|
|
|
| 60 |
Determines what to do when there is an error loading an image.
|
| 61 |
- `True`: raise an error.
|
| 62 |
- `None`: print a warning and skip the sample (default).
|
| 63 |
- `False`: silently skip the sample.
|
| 64 |
-
use_bad_sha256 (`Optional[bool]
|
| 65 |
Determines what to do when the sha256 integrity test fails.
|
| 66 |
- `True`: ignore the sha256 integrity test.
|
| 67 |
- `None`: print a warning and skip samples with bad sha256 (default).
|
| 68 |
- `False`: silently skip entries with bad sha256.
|
| 69 |
-
|
|
|
|
| 70 |
"""
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
except Exception as e:
|
| 81 |
-
if raise_on_missing:
|
| 82 |
-
raise RuntimeError(f"Error loading image at {img_path}\n{e}")
|
| 83 |
-
if raise_on_missing is None:
|
| 84 |
-
warnings.warn(f"Skipping due to error loading image {img_path}", RuntimeWarning)
|
| 85 |
-
image = None # Sample will be filtered out
|
| 86 |
-
if image is not None:
|
| 87 |
-
# Place into `buffer` using PNG image format
|
| 88 |
-
buffer = io.BytesIO()
|
| 89 |
-
image.save(buffer, "png")
|
| 90 |
-
# Reload the image with guaranteed PNG format
|
| 91 |
-
image = PIL.Image.open(buffer)
|
| 92 |
-
# Check sha256
|
| 93 |
-
if not skip_bad_sha256:
|
| 94 |
-
sha256 = _hash_bytes(buffer.getvalue())
|
| 95 |
-
if sha256 != sample["image_sha256"]:
|
| 96 |
-
image = None # Sample will be filtered out
|
| 97 |
-
if skip_bad_sha256 is None:
|
| 98 |
-
warnings.warn(f"Skipping due to bad sha256 for {img_path}", RuntimeWarning)
|
| 99 |
-
return {"image": image}
|
| 100 |
-
|
| 101 |
# Get the correct processor
|
| 102 |
try:
|
| 103 |
-
|
| 104 |
-
"COCOtext": on_disk_processor,
|
| 105 |
-
"pubtables-1m": on_disk_processor,
|
| 106 |
-
"TextOCR": on_disk_processor,
|
| 107 |
-
}[formal_name]
|
| 108 |
except KeyError:
|
| 109 |
raise ValueError(f"Unknown formal_name: {formal_name}")
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
if processor is None:
|
| 114 |
processed = unprocessed
|
| 115 |
else:
|
|
|
|
| 116 |
processed = unprocessed.map(
|
| 117 |
processor,
|
| 118 |
remove_columns="img_id",
|
| 119 |
load_from_cache_file=load_from_cache_file,
|
| 120 |
-
num_proc=num_proc
|
|
|
|
| 121 |
)
|
| 122 |
-
# Drop missing images.
|
| 123 |
if not raise_on_missing:
|
| 124 |
processed = processed.filter((lambda image: image is not None), input_columns="image", num_proc=num_proc)
|
| 125 |
# Column order
|
|
|
|
| 1 |
+
import abc
|
| 2 |
from typing import Optional
|
| 3 |
import datasets
|
| 4 |
import io
|
|
|
|
|
|
|
| 5 |
import os
|
| 6 |
+
import json
|
| 7 |
import hashlib
|
| 8 |
import warnings
|
| 9 |
+
import csv
|
| 10 |
+
import textwrap
|
| 11 |
+
|
| 12 |
+
# Tested with pandas=2.2.2
|
| 13 |
+
import pandas as pd
|
| 14 |
+
|
| 15 |
+
# Tested with pillow==10.4.0
|
| 16 |
+
import PIL
|
| 17 |
+
import PIL.Image
|
| 18 |
+
import PIL.PngImagePlugin
|
| 19 |
+
|
| 20 |
+
# Tested with PyMuPDF==1.24.7 PyMuPDFb==1.24.6
|
| 21 |
+
import pymupdf
|
| 22 |
+
|
| 23 |
+
# Tested with reportlab==4.2.2
|
| 24 |
+
import reportlab
|
| 25 |
+
import reportlab.lib.colors
|
| 26 |
+
import reportlab.lib.pagesizes
|
| 27 |
+
import reportlab.platypus
|
| 28 |
+
import reportlab.pdfgen
|
| 29 |
|
| 30 |
|
| 31 |
+
# Once properly assembled, the datasets should have these columns
|
| 32 |
ASSEMBLED_COLUMNS = (
|
| 33 |
'sample_id',
|
| 34 |
'dataset_name',
|
|
|
|
| 42 |
'image_sha256'
|
| 43 |
)
|
| 44 |
|
| 45 |
+
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
| 46 |
+
# Now scroll down to the very bottom for `get_bigdocs_75m`! #
|
| 47 |
+
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def pdf_to_image(pdf_stream, crop: bool=False) -> PIL.PngImagePlugin.PngImageFile:
|
| 51 |
+
doc = pymupdf.open(stream=pdf_stream)
|
| 52 |
+
# Render each page to an image in a list of images
|
| 53 |
+
images = [
|
| 54 |
+
PIL.Image.open(io.BytesIO(page.get_pixmap(dpi=144).tobytes("png")))
|
| 55 |
+
for page in doc
|
| 56 |
+
]
|
| 57 |
+
# Crop the footer if crop is True
|
| 58 |
+
if crop:
|
| 59 |
+
for i in range(len(images)):
|
| 60 |
+
images[i] = images[i].crop(
|
| 61 |
+
(120, 120, images[i].width - 120, images[i].height - 140)
|
| 62 |
+
)
|
| 63 |
+
# Determine the total width and height of the combined image
|
| 64 |
+
total_width = max(im.width for im in images)
|
| 65 |
+
total_height = sum(im.height for im in images)
|
| 66 |
+
# Create a new image with the combined size
|
| 67 |
+
combined_image = PIL.Image.new("RGB", (total_width, total_height), "white")
|
| 68 |
+
# Paste each page image into the combined image
|
| 69 |
+
y_offset = 0
|
| 70 |
+
for im in images:
|
| 71 |
+
combined_image.paste(im, (0, y_offset))
|
| 72 |
+
y_offset += im.height
|
| 73 |
+
# At this point combined_image is what we want, but under the wrong Python type
|
| 74 |
+
# Place into buffer using PNG image format
|
| 75 |
+
buffer = io.BytesIO()
|
| 76 |
+
combined_image.save(buffer, "png")
|
| 77 |
+
# Reload as PIL.PngImagePlugin.PngImageFile
|
| 78 |
+
return PIL.Image.open(buffer)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
WHITE = reportlab.lib.colors.white
|
| 82 |
+
BLACK = reportlab.lib.colors.black
|
| 83 |
+
TABLE_STYLE = reportlab.platypus.TableStyle([
|
| 84 |
+
("BACKGROUND", (0, 0), (-1, 0), WHITE),
|
| 85 |
+
("TEXTCOLOR", (0, 0), (-1, 0), BLACK),
|
| 86 |
+
("ALIGN", (0, 0), (-1, -1), "CENTER"),
|
| 87 |
+
("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
|
| 88 |
+
("BOTTOMPADDING", (0, 0), (-1, 0), 12),
|
| 89 |
+
("BACKGROUND", (0, 1), (-1, -1), WHITE),
|
| 90 |
+
("GRID", (0, 0), (-1, -1), 1, BLACK),
|
| 91 |
+
])
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def csv_to_image(csv_path: str) -> PIL.PngImagePlugin.PngImageFile:
|
| 95 |
+
# Load the data
|
| 96 |
+
with open(csv_path, newline="") as csv_stream:
|
| 97 |
+
reader = csv.reader(csv_stream, delimiter="#")
|
| 98 |
+
data = [row for row in reader]
|
| 99 |
+
# Create a table with CSV data
|
| 100 |
+
table = reportlab.platypus.Table(data)
|
| 101 |
+
table.setStyle(TABLE_STYLE)
|
| 102 |
+
# Virtual PDF file
|
| 103 |
+
pdf_stream = io.BytesIO()
|
| 104 |
+
# Build a document from the table
|
| 105 |
+
reportlab.platypus.SimpleDocTemplate(pdf_stream, pagesize=reportlab.lib.pagesizes.letter).build([table])
|
| 106 |
+
|
| 107 |
+
return pdf_to_image(pdf_stream)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def text_to_image(text: str, font_size: int = 10) -> PIL.PngImagePlugin.PngImageFile:
|
| 111 |
+
pdf_stream = io.BytesIO()
|
| 112 |
+
c = reportlab.pdfgen.canvas.Canvas(
|
| 113 |
+
pdf_stream,
|
| 114 |
+
pagesize=reportlab.lib.pagesizes.letter
|
| 115 |
+
)
|
| 116 |
+
c.setFont("Helvetica", font_size)
|
| 117 |
+
|
| 118 |
+
# Wrap the text for better handling in PDF
|
| 119 |
+
wrapped_text = textwrap.wrap(text, width=100)
|
| 120 |
+
|
| 121 |
+
# Starting position on the page
|
| 122 |
+
x_position = 72 # 1 inch from the left margin
|
| 123 |
+
y_position = 11 * 72 - 72 # Start 1 inch from the top of an 11-inch page
|
| 124 |
+
|
| 125 |
+
text_height = font_size * 1.2 # Approximate line height
|
| 126 |
|
| 127 |
+
for line in wrapped_text:
|
| 128 |
+
if y_position < 72: # Check if we're near the bottom of the page
|
| 129 |
+
c.showPage()
|
| 130 |
+
c.setFont("Helvetica", font_size)
|
| 131 |
+
y_position = 11 * 72 - 72 # Reset position to top of new page
|
| 132 |
+
|
| 133 |
+
c.drawString(x_position, y_position, line)
|
| 134 |
+
y_position -= text_height # Move down for next line
|
| 135 |
+
|
| 136 |
+
c.save()
|
| 137 |
+
|
| 138 |
+
return pdf_to_image(pdf_stream, crop=True)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def csv_to_markdown(csv_path: str, sep: str) -> str:
|
| 142 |
+
# Format with pandas, but ensure there are no consecutive spaces
|
| 143 |
+
df = pd.read_csv(csv_path, sep=sep)
|
| 144 |
+
return " ".join(df.to_markdown(index=False).split())
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def get_sha256(
|
| 148 |
+
image: PIL.PngImagePlugin.PngImageFile,
|
| 149 |
+
b: Optional[bytes]=None
|
| 150 |
+
) -> str:
|
| 151 |
+
# Ignore image if bytes representation b is already provided
|
| 152 |
+
if b is None:
|
| 153 |
+
buffer = io.BytesIO()
|
| 154 |
+
image.save(buffer, "png")
|
| 155 |
+
b = buffer.getvalue()
|
| 156 |
m = hashlib.sha256()
|
| 157 |
m.update(b)
|
| 158 |
return m.hexdigest()
|
| 159 |
|
| 160 |
|
| 161 |
+
class Assembler(abc.ABC):
|
| 162 |
+
def __init__(
|
| 163 |
+
self,
|
| 164 |
+
user_local_path: Optional[str],
|
| 165 |
+
raise_on_missing: Optional[bool],
|
| 166 |
+
use_bad_sha256: Optional[bool]
|
| 167 |
+
):
|
| 168 |
+
self.user_local_path = user_local_path
|
| 169 |
+
self.raise_on_missing = raise_on_missing
|
| 170 |
+
self.use_bad_sha256 = use_bad_sha256
|
| 171 |
+
|
| 172 |
+
@abc.abstractmethod
|
| 173 |
+
def __call__(self, sample) -> dict:
|
| 174 |
+
"""Processor called by `map` on each sample"""
|
| 175 |
+
|
| 176 |
+
def keep_image(
|
| 177 |
+
self,
|
| 178 |
+
image: Optional[PIL.PngImagePlugin.PngImageFile],
|
| 179 |
+
expected_sha256: str,
|
| 180 |
+
b: Optional[bytes]=None
|
| 181 |
+
) -> bool:
|
| 182 |
+
if image is None:
|
| 183 |
+
# No image to check
|
| 184 |
+
return False
|
| 185 |
+
if self.use_bad_sha256:
|
| 186 |
+
# We're going to use the image whether or not the sha256 is good
|
| 187 |
+
return True
|
| 188 |
+
sha256 = get_sha256(image, b)
|
| 189 |
+
if sha256 != expected_sha256:
|
| 190 |
+
# Give warning if didn't explicitly set use_bad_sha256 to False
|
| 191 |
+
if self.use_bad_sha256 is None:
|
| 192 |
+
warnings.warn(f"Skipping due to bad sha256", RuntimeWarning)
|
| 193 |
+
# Sample will be filtered out
|
| 194 |
+
return False
|
| 195 |
+
else:
|
| 196 |
+
# Sample will be used
|
| 197 |
+
return True
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class AssembleFromDisk(Assembler):
|
| 201 |
+
def __init__(self, *args, **kwargs):
|
| 202 |
+
super().__init__(*args, **kwargs)
|
| 203 |
+
assert self.user_local_path is not None, f"user_local_path is mandatory for this dataset"
|
| 204 |
+
|
| 205 |
+
def __call__(self, sample) -> dict:
|
| 206 |
+
img_path = os.path.join(self.user_local_path, sample['img_id'])
|
| 207 |
+
# Load the image
|
| 208 |
+
try:
|
| 209 |
+
image = PIL.Image.open(img_path)
|
| 210 |
+
except Exception as e:
|
| 211 |
+
if self.raise_on_missing:
|
| 212 |
+
raise RuntimeError(f"Error loading image at {img_path}\n{e}")
|
| 213 |
+
if self.raise_on_missing is None:
|
| 214 |
+
warnings.warn(f"Skipping due to error loading image {img_path}\n{e}", RuntimeWarning)
|
| 215 |
+
image = None # Sample will be filtered out
|
| 216 |
+
if image is not None:
|
| 217 |
+
# Place into `buffer` using PNG image format
|
| 218 |
+
buffer = io.BytesIO()
|
| 219 |
+
image.save(buffer, "png")
|
| 220 |
+
# Reload the image with guaranteed PNG format
|
| 221 |
+
image = PIL.Image.open(buffer)
|
| 222 |
+
# Check sha256
|
| 223 |
+
if not self.keep_image(image, sample["image_sha256"], b=buffer.getvalue()):
|
| 224 |
+
image = None
|
| 225 |
+
return {"image": image}
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
class AssembleTabFact(Assembler):
|
| 229 |
+
def __init__(self, *args, **kwargs):
|
| 230 |
+
super().__init__(*args, **kwargs)
|
| 231 |
+
# Get annotations
|
| 232 |
+
json_path = os.path.join(self.user_local_path, "tokenized_data/total_examples.json")
|
| 233 |
+
with open(json_path, "rt") as fp:
|
| 234 |
+
self.tables_data = json.load(fp)
|
| 235 |
+
|
| 236 |
+
def __call__(self, sample) -> dict:
|
| 237 |
+
csv_path = os.path.join(self.user_local_path, "data/all_csv", sample["img_id"])
|
| 238 |
+
image = csv_to_image(csv_path)
|
| 239 |
+
# Check sha256
|
| 240 |
+
if not self.keep_image(image, sample["image_sha256"]):
|
| 241 |
+
# Skip both image and annotations (will be filtered out)
|
| 242 |
+
return {"image": None, "annotations": [""]}
|
| 243 |
+
# Annotations
|
| 244 |
+
if sample["task_name"] == "table_parsing2md":
|
| 245 |
+
annotations = [csv_to_markdown(csv_path, sep="#")]
|
| 246 |
+
else:
|
| 247 |
+
facts, entails, title = self.tables_data[sample["img_id"]]
|
| 248 |
+
if sample["task_name"] == "caption":
|
| 249 |
+
# The "caption" is the table's title
|
| 250 |
+
annotations = [title]
|
| 251 |
+
else:
|
| 252 |
+
assert sample["task_name"] == "summary"
|
| 253 |
+
# select only entries in facts with entailment label as 1
|
| 254 |
+
facts = [fact for fact, entailment in zip(facts, entails) if entailment == 1]
|
| 255 |
+
# concat facts with numbered bullets and new lines
|
| 256 |
+
annotations = ["\n".join([f"{i+1}. {fact}" for i, fact in enumerate(facts)])]
|
| 257 |
+
return {"image": image, "annotations": annotations}
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
class AssembleOpen4Business(Assembler):
|
| 261 |
+
def __init__(self, *args, **kwargs):
|
| 262 |
+
super().__init__(*args, **kwargs)
|
| 263 |
+
# Get annotations
|
| 264 |
+
self.texts, self.summaries = {}, {}
|
| 265 |
+
for split in ["train", "val", "test"]:
|
| 266 |
+
with open(os.path.join(self.user_local_path, f"{split}.source"), "rt") as fp:
|
| 267 |
+
# Don't strip here because that may alter the image sha256
|
| 268 |
+
self.texts[split] = list(line for line in fp)
|
| 269 |
+
with open(os.path.join(self.user_local_path, f"{split}.target"), "rt") as fp:
|
| 270 |
+
self.summaries[split] = list(line.strip() for line in fp)
|
| 271 |
+
|
| 272 |
+
def __call__(self, sample) -> dict:
|
| 273 |
+
split, line_number = sample["img_id"].split("_")
|
| 274 |
+
line_number = int(line_number)
|
| 275 |
+
print(split, line_number, sample["task_name"])
|
| 276 |
+
try:
|
| 277 |
+
text = self.texts[split][line_number]
|
| 278 |
+
image = text_to_image(text)
|
| 279 |
+
# Check sha256
|
| 280 |
+
if not self.keep_image(image, sample["image_sha256"]):
|
| 281 |
+
# Skip both image and annotations (will be filtered out)
|
| 282 |
+
return {"image": None, "annotations": [""]}
|
| 283 |
+
# Annotations
|
| 284 |
+
if sample["task_name"] == "extraction":
|
| 285 |
+
# Don't forget the strip!
|
| 286 |
+
annotations = [text.strip()]
|
| 287 |
+
else:
|
| 288 |
+
assert sample["task_name"] == "summary"
|
| 289 |
+
annotations = [self.summaries[split][line_number]]
|
| 290 |
+
except Exception as e:
|
| 291 |
+
print(f"EXCEPTION on {split}, {line_number}, {sample['task_name']}. Original error: {e.__str__}")
|
| 292 |
+
raise e
|
| 293 |
+
return {"image": image, "annotations": annotations}
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
class AssembleWikiTQ(Assembler):
|
| 297 |
+
def __init__(self, *args, **kwargs):
|
| 298 |
+
super().__init__(*args, **kwargs)
|
| 299 |
+
# Get annotations
|
| 300 |
+
self.annotations = pd.concat([
|
| 301 |
+
pd.read_csv(
|
| 302 |
+
os.path.join(self.user_local_path, "data", tsv_file),
|
| 303 |
+
sep="\t", on_bad_lines="skip", index_col="id"
|
| 304 |
+
) for tsv_file in {
|
| 305 |
+
"training.tsv",
|
| 306 |
+
"pristine-seen-tables.tsv",
|
| 307 |
+
"pristine-unseen-tables.tsv"
|
| 308 |
+
}
|
| 309 |
+
])
|
| 310 |
+
|
| 311 |
+
def __call__(self, sample) -> dict:
|
| 312 |
+
question, context, answer = self.annotations.loc[sample["img_id"]]
|
| 313 |
+
csv_path = os.path.join(self.user_local_path, context)
|
| 314 |
+
image = csv_to_image(csv_path)
|
| 315 |
+
# Check sha256
|
| 316 |
+
if not self.keep_image(image, sample["image_sha256"]):
|
| 317 |
+
# Skip both image and annotations (will be filtered out)
|
| 318 |
+
return {"image": None, "annotations": [""]}
|
| 319 |
+
# Annotations
|
| 320 |
+
if sample["task_name"] == "table_parsing2md":
|
| 321 |
+
annotations = [csv_to_markdown(csv_path, sep=",")]
|
| 322 |
+
return {"image": image, "annotations": annotations}
|
| 323 |
+
else:
|
| 324 |
+
assert sample["task_name"] == "qa"
|
| 325 |
+
query = [sample["query"][0].format(question=question)]
|
| 326 |
+
answers = str(answer).split("|")
|
| 327 |
+
answer = " or ".join(answers) if len(answers) > 1 else answers[0]
|
| 328 |
+
annotations = [sample["annotations"][0].format(answer=answer)]
|
| 329 |
+
return {"image": image, "query": query, "annotations": annotations}
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
KNOWN_ASSEMBLERS = {
|
| 333 |
+
"ArxivOCR": None,
|
| 334 |
+
"ArxivTableCap": None,
|
| 335 |
+
"COCOtext": AssembleFromDisk,
|
| 336 |
+
"pubtables-1m": AssembleFromDisk,
|
| 337 |
+
"TextOCR": AssembleFromDisk,
|
| 338 |
+
"TabFact": AssembleTabFact,
|
| 339 |
+
"Open4Business": AssembleOpen4Business,
|
| 340 |
+
"WikiTQ": AssembleWikiTQ,
|
| 341 |
+
}
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
# # # # # # # # # # # # # # # # # # # # # # #
|
| 345 |
+
# This is the function you are looking for! #
|
| 346 |
+
# # # # # # # # # # # # # # # # # # # # # # #
|
| 347 |
def get_bigdocs_75m(
|
| 348 |
+
formal_name: str,
|
| 349 |
+
user_local_path: Optional[str]=None,
|
| 350 |
+
*,
|
| 351 |
+
load_from_cache_file: Optional[bool]=None,
|
| 352 |
+
num_proc: Optional[int]=4,
|
| 353 |
+
writer_batch_size: int=100,
|
| 354 |
raise_on_missing: Optional[bool]=None,
|
| 355 |
+
use_bad_sha256: Optional[bool]=None,
|
| 356 |
+
bigdocs_load_dataset_kwargs: Optional[dict]=None,
|
| 357 |
+
unprocessed: Optional[datasets.DatasetDict]=None
|
| 358 |
) -> datasets.DatasetDict:
|
| 359 |
"""
|
| 360 |
Get a subset of BigDocs-7.5M
|
|
|
|
| 369 |
- COCOtext: http://images.cocodataset.org/zips/train2014.zip
|
| 370 |
- pubtables-1m: https://www.microsoft.com/en-us/research/publication/pubtables-1m
|
| 371 |
- TextOCR: https://dl.fbaipublicfiles.com/textvqa/images/train_val_images.zip
|
| 372 |
+
- TabFact: https://github.com/wenhuchen/Table-Fact-Checking
|
| 373 |
+
- Open4Business: https://github.com/amanpreet692/Open4Business
|
| 374 |
+
- WikiTQ: https://github.com/ppasupat/WikiTableQuestions
|
| 375 |
|
| 376 |
Args:
|
| 377 |
+
formal_name (`str`): The desired subset of BigDocs-7.5M .
|
| 378 |
+
user_local_path (`Optional[str]`): The local path containing the images to be linked.
|
| 379 |
+
load_from_cache_file (`Optional[bool]): Passed to `map`, `filter` and the likes.
|
| 380 |
+
num_proc (`Optional[int]): Passed to `map`, `filter` and the likes.
|
| 381 |
+
writer_batch_size (`int`, defaults to 100): Passed to `map`. Too large values may cause OOM.
|
| 382 |
+
raise_on_missing (`Optional[bool]`):
|
| 383 |
Determines what to do when there is an error loading an image.
|
| 384 |
- `True`: raise an error.
|
| 385 |
- `None`: print a warning and skip the sample (default).
|
| 386 |
- `False`: silently skip the sample.
|
| 387 |
+
use_bad_sha256 (`Optional[bool]):
|
| 388 |
Determines what to do when the sha256 integrity test fails.
|
| 389 |
- `True`: ignore the sha256 integrity test.
|
| 390 |
- `None`: print a warning and skip samples with bad sha256 (default).
|
| 391 |
- `False`: silently skip entries with bad sha256.
|
| 392 |
+
bigdocs_load_dataset_kwargs (`Optional[dict]`): Arguments passed to datasets.load_dataset when retrieving ServiceNow/BigDocs-7.5M .
|
| 393 |
+
unprocessed (Optional[datasets.DatasetDict]): If provided, will be used in stead of ServiceNow/BigDocs-7.5M .
|
| 394 |
"""
|
| 395 |
+
# Get the unprocessed ServiceNow/BigDocs-7.5M
|
| 396 |
+
if unprocessed is None:
|
| 397 |
+
if bigdocs_load_dataset_kwargs is None:
|
| 398 |
+
bigdocs_load_dataset_kwargs = {}
|
| 399 |
+
unprocessed = datasets.load_dataset(
|
| 400 |
+
"ServiceNow/BigDocs-7.5M",
|
| 401 |
+
formal_name,
|
| 402 |
+
**bigdocs_load_dataset_kwargs
|
| 403 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 404 |
# Get the correct processor
|
| 405 |
try:
|
| 406 |
+
assembler = KNOWN_ASSEMBLERS[formal_name]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 407 |
except KeyError:
|
| 408 |
raise ValueError(f"Unknown formal_name: {formal_name}")
|
| 409 |
+
# Do the processing
|
| 410 |
+
if assembler is None:
|
| 411 |
+
assert user_local_path is None
|
|
|
|
| 412 |
processed = unprocessed
|
| 413 |
else:
|
| 414 |
+
processor = assembler(user_local_path, raise_on_missing, use_bad_sha256)
|
| 415 |
processed = unprocessed.map(
|
| 416 |
processor,
|
| 417 |
remove_columns="img_id",
|
| 418 |
load_from_cache_file=load_from_cache_file,
|
| 419 |
+
num_proc=num_proc,
|
| 420 |
+
writer_batch_size=writer_batch_size
|
| 421 |
)
|
| 422 |
+
# Drop missing images (we can skip if we raised on missing images).
|
| 423 |
if not raise_on_missing:
|
| 424 |
processed = processed.filter((lambda image: image is not None), input_columns="image", num_proc=num_proc)
|
| 425 |
# Column order
|