Update app.py
Browse files
app.py
CHANGED
|
@@ -1,3 +1,110 @@
|
|
|
|
|
| 1 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
import gradio as gr
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from paddleocr import PaddleOCR
|
| 6 |
+
from PIL import Image
|
| 7 |
+
from transformers import AutoTokenizer, LayoutLMForQuestionAnswering
|
| 8 |
+
from transformers.pipelines.document_question_answering import apply_tesseract
|
| 9 |
|
| 10 |
+
model_tag = "impira/layoutlm-document-qa"
|
| 11 |
+
MODEL = LayoutLMForQuestionAnswering.from_pretrained(model_tag).eval()
|
| 12 |
+
TOKENIZER = AutoTokenizer.from_pretrained(model_tag)
|
| 13 |
+
OCR = PaddleOCR(
|
| 14 |
+
lang="en",
|
| 15 |
+
det_limit_side_len=10_000,
|
| 16 |
+
det_db_score_mode="slow",
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
PADDLE_OCR_LABEL = "PaddleOCR (en)"
|
| 21 |
+
TESSERACT_LABEL = "Tesseract (HF default)"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def predict(image: Image.Image, question: str, ocr_engine: str):
|
| 25 |
+
image_np = np.array(image)
|
| 26 |
+
|
| 27 |
+
if ocr_engine == PADDLE_OCR_LABEL:
|
| 28 |
+
ocr_result = OCR.ocr(image_np, cls=False)[0]
|
| 29 |
+
words = [x[1][0] for x in ocr_result]
|
| 30 |
+
boxes = np.asarray([x[0] for x in ocr_result]) # (n_boxes, 4, 2)
|
| 31 |
+
|
| 32 |
+
for box in boxes:
|
| 33 |
+
cv2.polylines(image_np, [box.reshape(-1, 1, 2).astype(int)], True, (0, 255, 255), 3)
|
| 34 |
+
|
| 35 |
+
x1 = boxes[:, :, 0].min(1) * 1000 / image.width
|
| 36 |
+
y1 = boxes[:, :, 1].min(1) * 1000 / image.height
|
| 37 |
+
x2 = boxes[:, :, 0].max(1) * 1000 / image.width
|
| 38 |
+
y2 = boxes[:, :, 1].max(1) * 1000 / image.height
|
| 39 |
+
|
| 40 |
+
# (n_boxes, 4) in xyxy format
|
| 41 |
+
boxes = np.stack([x1, y1, x2, y2], axis=1).astype(int)
|
| 42 |
+
|
| 43 |
+
elif ocr_engine == TESSERACT_LABEL:
|
| 44 |
+
words, boxes = apply_tesseract(image, None, "")
|
| 45 |
+
|
| 46 |
+
for x1, y1, x2, y2 in boxes:
|
| 47 |
+
x1 = int(x1 * image.width / 1000)
|
| 48 |
+
y1 = int(y1 * image.height / 1000)
|
| 49 |
+
x2 = int(x2 * image.width / 1000)
|
| 50 |
+
y2 = int(y2 * image.height / 1000)
|
| 51 |
+
cv2.rectangle(image_np, (x1, y1), (x2, y2), (0, 255, 255), 3)
|
| 52 |
+
|
| 53 |
+
else:
|
| 54 |
+
raise ValueError(f"Unsupported ocr_engine={ocr_engine}")
|
| 55 |
+
|
| 56 |
+
token_ids = TOKENIZER(question)["input_ids"]
|
| 57 |
+
token_boxes = [[0] * 4] * (len(token_ids) - 1) + [[1000] * 4]
|
| 58 |
+
n_question_tokens = len(token_ids)
|
| 59 |
+
|
| 60 |
+
token_ids.append(TOKENIZER.sep_token_id)
|
| 61 |
+
token_boxes.append([1000] * 4)
|
| 62 |
+
|
| 63 |
+
for word, box in zip(words, boxes):
|
| 64 |
+
new_ids = TOKENIZER(word, add_special_tokens=False)["input_ids"]
|
| 65 |
+
token_ids.extend(new_ids)
|
| 66 |
+
token_boxes.extend([box] * len(new_ids))
|
| 67 |
+
|
| 68 |
+
token_ids.append(TOKENIZER.sep_token_id)
|
| 69 |
+
token_boxes.append([1000] * 4)
|
| 70 |
+
|
| 71 |
+
with torch.inference_mode():
|
| 72 |
+
outputs = MODEL(
|
| 73 |
+
input_ids=torch.tensor(token_ids).unsqueeze(0),
|
| 74 |
+
bbox=torch.tensor(token_boxes).unsqueeze(0),
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
start_scores = outputs.start_logits.squeeze(0).softmax(-1)[n_question_tokens:]
|
| 78 |
+
end_scores = outputs.end_logits.squeeze(0).softmax(-1)[n_question_tokens:]
|
| 79 |
+
|
| 80 |
+
span_scores = start_scores.view(-1, 1) * end_scores.view(1, -1)
|
| 81 |
+
span_scores = torch.triu(span_scores) # don't allow start < end
|
| 82 |
+
|
| 83 |
+
score, indices = span_scores.flatten().max(-1)
|
| 84 |
+
start_idx = n_question_tokens + indices // span_scores.shape[1]
|
| 85 |
+
end_idx = n_question_tokens + indices % span_scores.shape[1]
|
| 86 |
+
|
| 87 |
+
answer = TOKENIZER.decode(token_ids[start_idx : end_idx + 1])
|
| 88 |
+
|
| 89 |
+
return answer, score, image_np
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
gr.Interface(
|
| 93 |
+
fn=predict,
|
| 94 |
+
inputs=[
|
| 95 |
+
gr.Image(type="pil"),
|
| 96 |
+
"text",
|
| 97 |
+
gr.Radio([PADDLE_OCR_LABEL, TESSERACT_LABEL]),
|
| 98 |
+
],
|
| 99 |
+
outputs=[
|
| 100 |
+
gr.Textbox(label="Answer"),
|
| 101 |
+
gr.Number(label="Score"),
|
| 102 |
+
gr.Image(label="OCR results"),
|
| 103 |
+
],
|
| 104 |
+
examples=[
|
| 105 |
+
["example_01.jpg", "When did the sample take place?", PADDLE_OCR_LABEL],
|
| 106 |
+
["example_02.jpg", "What is the ID number?", PADDLE_OCR_LABEL],
|
| 107 |
+
],
|
| 108 |
+
).launch(server_name="0.0.0.0", server_port=7860)
|
| 109 |
+
|
| 110 |
+
// gr.load("models/PrimWong/layout_qa_hparam_tuning").launch()
|