from typing importDict, List, Anyfrom transformers import LayoutLMForTokenClassification, LayoutLMv2Processor
import torch
from subprocess import run
# install tesseract-ocr and pytesseract
run("apt install -y tesseract-ocr", shell=True, check=True)
run("pip install pytesseract", shell=True, check=True)
# helper function to unnormalize bboxes for drawing onto the imagedefunnormalize_box(bbox, width, height):
return [
width * (bbox[0] / 1000),
height * (bbox[1] / 1000),
width * (bbox[2] / 1000),
height * (bbox[3] / 1000),
]
# set device
device = torch.device("cuda"if torch.cuda.is_available() else"cpu")
classEndpointHandler:
def__init__(self, path=""):
# load model and processor from path
self.model = LayoutLMForTokenClassification.from_pretrained(path).to(device)
self.processor = LayoutLMv2Processor.from_pretrained(path)
def__call__(self, data: Dict[str, bytes]) -> Dict[str, List[Any]]:
""" Args: data (:obj:): includes the deserialized image file as PIL.Image """# process input
image = data.pop("inputs", data)
# process image
encoding = self.processor(image, return_tensors="pt")
# run predictionwith torch.inference_mode():
outputs = self.model(
input_ids=encoding.input_ids.to(device),
bbox=encoding.bbox.to(device),
attention_mask=encoding.attention_mask.to(device),
token_type_ids=encoding.token_type_ids.to(device),
)
predictions = outputs.logits.softmax(-1)
# post process output
result = []
for item, inp_ids, bbox inzip(
predictions.squeeze(0).cpu(), encoding.input_ids.squeeze(0).cpu(), encoding.bbox.squeeze(0).cpu()
):
label = self.model.config.id2label[int(item.argmax().cpu())]
if label == "O":
continue
score = item.max().item()
text = self.processor.tokenizer.decode(inp_ids)
bbox = unnormalize_box(bbox.tolist(), image.width, image.height)
result.append({"label": label, "score": score, "text": text, "bbox": bbox})
return {"predictions": result}
2. Send HTTP request using Python
Hugging Face Inference endpoints can directly work with binary data, this means that we can directly send our image from our document to the endpoint. We are going to use
requests
to send our requests. (make your you have it installed
pip install requests
)
import json
import requests as r
import mimetypes
ENDPOINT_URL=""# url of your endpoint
HF_TOKEN=""# organization token where you deployed your endpointdefpredict(path_to_image:str=None):
withopen(path_to_image, "rb") as i:
b = i.read()
headers= {
"Authorization": f"Bearer {HF_TOKEN}",
"Content-Type": mimetypes.guess_type(path_to_image)[0]
}
response = r.post(ENDPOINT_URL, headers=headers, data=b)
return response.json()
prediction = predict(path_to_image="path_to_your_image.png")
print(prediction)
# {'predictions': [{'label': 'I-ANSWER', 'score': 0.4823932945728302, 'text': '[CLS]', 'bbox': [0.0, 0.0, 0.0, 0.0]}, {'label': 'B-HEADER', 'score': 0.992474377155304, 'text': 'your', 'bbox': [1712.529, 181.203, 1859.949, 228.88799999999998]},
3. Draw result on image
To get a better understanding of what the model predicted you can also draw the predictions on the provided image.
from PIL import Image, ImageDraw, ImageFont
# draw results on imagedefdraw_result(path_to_image,result):
image = Image.open(path_to_image)
label2color = {
"B-HEADER": "blue",
"B-QUESTION": "red",
"B-ANSWER": "green",
"I-HEADER": "blue",
"I-QUESTION": "red",
"I-ANSWER": "green",
}
# draw predictions over the image
draw = ImageDraw.Draw(image)
font = ImageFont.load_default()
for res in result:
draw.rectangle(res["bbox"], outline="black")
draw.rectangle(res["bbox"], outline=label2color[res["label"]])
draw.text((res["bbox"][0] + 10, res["bbox"][1] - 10), text=res["label"], fill=label2color[res["label"]], font=font)
return image
draw_result("path_to_your_image.png", prediction["predictions"])
Runs of philschmid layoutlm-funsd on huggingface.co
53
Total runs
0
24-hour runs
-2
3-day runs
-51
7-day runs
-47
30-day runs
More Information About layoutlm-funsd huggingface.co Model
layoutlm-funsd huggingface.co
layoutlm-funsd huggingface.co is an AI model on huggingface.co that provides layoutlm-funsd's model effect (), which can be used instantly with this philschmid layoutlm-funsd model. huggingface.co supports a free trial of the layoutlm-funsd model, and also provides paid use of the layoutlm-funsd. Support call layoutlm-funsd model through api, including Node.js, Python, http.
layoutlm-funsd huggingface.co is an online trial and call api platform, which integrates layoutlm-funsd's modeling effects, including api services, and provides a free online trial of layoutlm-funsd, you can try layoutlm-funsd online for free by clicking the link below.
philschmid layoutlm-funsd online free url in huggingface.co:
layoutlm-funsd is an open source model from GitHub that offers a free installation service, and any user can find layoutlm-funsd on GitHub to install. At the same time, huggingface.co provides the effect of layoutlm-funsd install, users can directly use layoutlm-funsd installed effect in huggingface.co for debugging and trial. It also supports api for free installation.