merve HF staff commited on
Commit
4eb7414
β€’
1 Parent(s): b935097

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -0
app.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import torch
4
+ from PIL import Image
5
+ from gradio_image_prompter import ImagePrompter
6
+ from transformers import AutoProcessor, UdopForConditionalGeneration
7
+ import easyocr
8
+ from PIL import Image
9
+ import spaces
10
+
11
+ processor = AutoProcessor.from_pretrained("microsoft/udop-large", apply_ocr=False)
12
+ model = UdopForConditionalGeneration.from_pretrained("microsoft/udop-large")
13
+
14
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
15
+
16
+ @spaces.GPU
17
+ def udop_box_inference(image, text_prompt, box_coordinates):
18
+ box_coordinates = [box_coordinates[0], box_coordinates[1], box_coordinates[3], box_coordinates[4]]
19
+
20
+ extracted_image = extract_box(image_path, box_coordinates)
21
+ extracted_image.save("cropped_image.png")
22
+
23
+ reader = easyocr.Reader(['en'])
24
+ result = reader.readtext('cropped_image.png')
25
+ texts = []
26
+ bboxs = []
27
+ for (bbox, text, prob) in result:
28
+ texts.append(text)
29
+ bboxs.append([bbox[0][0], bbox[0][1], bbox[2][0], bbox[2][1]])
30
+
31
+ height = image.size[1]
32
+ width = image.size[0]
33
+ image = image.convert("RGB")
34
+ norm_boxes = []
35
+ for box in bboxs:
36
+ norm_boxes.append(normalize_bbox(box, width, height))
37
+
38
+ encoding = processor(image, text_prompt, texts, boxes=norm_boxes, return_tensors="pt")
39
+ predicted_ids = model.generate(**encoding)
40
+ return processor.batch_decode(predicted_ids, skip_special_tokens=True)[0]
41
+
42
+
43
+ def normalize_bbox(bbox, width, height):
44
+ return [
45
+ int(1000 * (bbox[0] / width)),
46
+ int(1000 * (bbox[1] / height)),
47
+ int(1000 * (bbox[2] / width)),
48
+ int(1000 * (bbox[3] / height)),
49
+ ]
50
+
51
+
52
+ def extract_box(image_path, coordinates):
53
+ image = Image.open(image_path)
54
+ x, y, x2, y2 = coordinates
55
+ cropped_image = image.crop((x, y, x2, y2))
56
+ return cropped_image
57
+
58
+
59
+
60
+ def infer_box(prompts, text_prompts):
61
+ # background (original image) layers[0] ( point prompt) composite (total image)
62
+ image = prompts["image"]
63
+ if image is None:
64
+ gr.Error("Please upload an image and draw a box before submitting")
65
+ points = prompts["points"][0]
66
+ if points is None:
67
+ gr.Error("Please draw a box before submitting.")
68
+ return udop_box_inference(image, text_prompts, points)
69
+
70
+
71
+ with gr.Blocks(title="UDOP") as demo:
72
+ gr.Markdown("# UDOP")
73
+ gr.Markdown("UDOP is a cutting-edge foundation model for a document understanding and generation.")
74
+ gr.Markdown("Try UDOP in this demo.")
75
+
76
+ with gr.Row():
77
+ with gr.Column(scale=1):
78
+ # Title
79
+ gr.Markdown("To try box prompting, simply upload and image and draw a box on it.")
80
+ with gr.Row():
81
+ with gr.Column():
82
+ im = ImagePrompter(type="pil")
83
+ text_prompt = gr.Textbox()
84
+ btn = gr.Button("Submit")
85
+ with gr.Column():
86
+ output = gr.Textbox(label="UDOP Output")
87
+
88
+
89
+ btn.click(infer_box, inputs=[im,text_prompt], outputs=[output])
90
+
91
+ demo.launch(debug=True)