Create README.md
Browse files
README.md
ADDED
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# LayoutXLM finetuned on XFUN.ja
|
2 |
+
|
3 |
+
```python
|
4 |
+
import torch
|
5 |
+
import numpy as np
|
6 |
+
from PIL import Image, ImageDraw, ImageFont
|
7 |
+
from pathlib import Path
|
8 |
+
from itertools import chain
|
9 |
+
from tqdm.notebook import tqdm
|
10 |
+
from pdf2image import convert_from_path
|
11 |
+
from transformers import LayoutXLMProcessor, LayoutLMv2ForTokenClassification
|
12 |
+
|
13 |
+
import os
|
14 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
15 |
+
|
16 |
+
labels = [
|
17 |
+
'O',
|
18 |
+
'B-QUESTION',
|
19 |
+
'B-ANSWER',
|
20 |
+
'B-HEADER',
|
21 |
+
'I-ANSWER',
|
22 |
+
'I-QUESTION',
|
23 |
+
'I-HEADER'
|
24 |
+
]
|
25 |
+
id2label = {v: k for v, k in enumerate(labels)}
|
26 |
+
label2id = {k: v for v, k in enumerate(labels)}
|
27 |
+
|
28 |
+
def unnormalize_box(bbox, width, height):
|
29 |
+
return [
|
30 |
+
width * (bbox[0] / 1000),
|
31 |
+
height * (bbox[1] / 1000),
|
32 |
+
width * (bbox[2] / 1000),
|
33 |
+
height * (bbox[3] / 1000),
|
34 |
+
]
|
35 |
+
|
36 |
+
def iob_to_label(label):
|
37 |
+
label = label[2:]
|
38 |
+
if not label:
|
39 |
+
return 'other'
|
40 |
+
return label
|
41 |
+
|
42 |
+
label2color = {'question':'blue', 'answer':'green', 'header':'orange', 'other':'violet'}
|
43 |
+
|
44 |
+
def infer(image, processor, model, label2color):
|
45 |
+
# Use this if you're loading images
|
46 |
+
# image = Image.open(img_path).convert("RGB")
|
47 |
+
|
48 |
+
image = image.convert("RGB") # loading PDFs
|
49 |
+
encoding = processor(image, return_offsets_mapping=True, return_tensors="pt", truncation=True, max_length=514)
|
50 |
+
offset_mapping = encoding.pop('offset_mapping')
|
51 |
+
outputs = model(**encoding)
|
52 |
+
predictions = outputs.logits.argmax(-1).squeeze().tolist()
|
53 |
+
token_boxes = encoding.bbox.squeeze().tolist()
|
54 |
+
|
55 |
+
width, height = image.size
|
56 |
+
is_subword = np.array(offset_mapping.squeeze().tolist())[:,0] != 0
|
57 |
+
|
58 |
+
true_predictions = [id2label[pred] for idx, pred in enumerate(predictions) if not is_subword[idx]]
|
59 |
+
true_boxes = [unnormalize_box(box, width, height) for idx, box in enumerate(token_boxes) if not is_subword[idx]]
|
60 |
+
draw = ImageDraw.Draw(image)
|
61 |
+
|
62 |
+
font = ImageFont.load_default()
|
63 |
+
|
64 |
+
for prediction, box in zip(true_predictions, true_boxes):
|
65 |
+
predicted_label = iob_to_label(prediction).lower()
|
66 |
+
draw.rectangle(box, outline=label2color[predicted_label])
|
67 |
+
draw.text((box[0]+10, box[1]-10), text=predicted_label, fill=label2color[predicted_label], font=font)
|
68 |
+
|
69 |
+
return image
|
70 |
+
|
71 |
+
processor = LayoutXLMProcessor.from_pretrained('beomus/layoutxlm')
|
72 |
+
model = LayoutLMv2ForTokenClassification.from_pretrained("beomus/layoutxlm")
|
73 |
+
|
74 |
+
|
75 |
+
# imgs = [img_path for img_path in Path('/your/path/imgs/').glob('*.jpg')]
|
76 |
+
|
77 |
+
imgs = [convert_from_path(img_path) for img_path in Path('/your/path/pdfs/').glob('*.pdf')]
|
78 |
+
imgs = list(chain.from_iterable(imgs))
|
79 |
+
|
80 |
+
|
81 |
+
outputs = [infer(img_path, processor, model, label2color) for img_path in tqdm(imgs)]
|
82 |
+
|
83 |
+
# type(outputs[0]) -> PIL.Image.Image
|
84 |
+
```
|