jadechoghari commited on
Commit
59524ac
1 Parent(s): 6a5f217

Create inference.py

Browse files
Files changed (1) hide show
  1. inference.py +125 -0
inference.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from PIL import Image
3
+ from conversation import conv_templates
4
+ from builder import load_pretrained_model
5
+ from functools import partial
6
+ import numpy as np
7
+
8
+ # define the task categories
9
+ box_in_tasks = ['widgetcaptions', 'taperception', 'ocr', 'icon_recognition', 'widget_classification', 'example_0']
10
+ box_out_tasks = ['widget_listing', 'find_text', 'find_icons', 'find_widget', 'conversation_interaction']
11
+ no_box_tasks = ['screen2words', 'detailed_description', 'conversation_perception', 'gpt4']
12
+
13
+ # function to generate the mask
14
+ def generate_mask_for_feature(coor, raw_w, raw_h, mask=None):
15
+ """
16
+ Generates a region mask based on provided coordinates.
17
+ Handles both point and box input.
18
+ """
19
+ if mask is not None:
20
+ assert mask.shape[0] == raw_w and mask.shape[1] == raw_h
21
+ coor_mask = np.zeros((raw_w, raw_h))
22
+
23
+ # if it's a point (2 coordinates)
24
+ if len(coor) == 2:
25
+ span = 5 # Define the span for the point
26
+ x_min = max(0, coor[0] - span)
27
+ x_max = min(raw_w, coor[0] + span + 1)
28
+ y_min = max(0, coor[1] - span)
29
+ y_max = min(raw_h, coor[1] + span + 1)
30
+ coor_mask[int(x_min):int(x_max), int(y_min):int(y_max)] = 1
31
+ assert (coor_mask == 1).any(), f"coor: {coor}, raw_w: {raw_w}, raw_h: {raw_h}"
32
+
33
+ # if it's a box (4 coordinates)
34
+ elif len(coor) == 4:
35
+ coor_mask[coor[0]:coor[2]+1, coor[1]:coor[3]+1] = 1
36
+ if mask is not None:
37
+ coor_mask = coor_mask * mask
38
+
39
+ # Convert to torch tensor and ensure it contains non-zero values
40
+ coor_mask = torch.from_numpy(coor_mask)
41
+ assert len(coor_mask.nonzero()) != 0, "Generated mask is empty :("
42
+
43
+ return coor_mask
44
+
45
+
46
+ def infer_single_prompt(image_path, prompt, model_path, region=None, model_name="ferret_gemma", conv_mode="ferret_gemma_instruct"):
47
+ img = Image.open(image_path).convert('RGB')
48
+
49
+ # this loads the model, image processor and tokenizer
50
+ tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, None, model_name)
51
+
52
+ # define the image size (e.g., 224x224 or 336x336)
53
+ image_size = {"height": 336, "width": 336}
54
+
55
+ # process the image
56
+ image_tensor = image_processor.preprocess(
57
+ img,
58
+ return_tensors='pt',
59
+ do_resize=True,
60
+ do_center_crop=False,
61
+ size=(image_size['height'], image_size['width'])
62
+ )['pixel_values'][0].unsqueeze(0)
63
+
64
+ image_tensor = image_tensor.half().cuda()
65
+
66
+ # generate the prompt per template requirement
67
+ conv = conv_templates[conv_mode].copy()
68
+ conv.append_message(conv.roles[0], prompt)
69
+ conv.append_message(conv.roles[1], None)
70
+ prompt_input = conv.get_prompt()
71
+
72
+ # tokenize prompt
73
+ input_ids = tokenizer(prompt_input, return_tensors='pt')['input_ids'].cuda()
74
+
75
+ # region mask logic (if region is provided)
76
+ region_masks = None
77
+ if region is not None:
78
+ raw_w, raw_h = img.size
79
+ region_masks = generate_mask_for_feature(region, raw_w, raw_h).unsqueeze(0).cuda().half()
80
+ region_masks = [[region_masks]] # Wrap the mask in lists as expected by the model
81
+
82
+ # generate model output
83
+ with torch.inference_mode():
84
+ # Use region_masks in model's forward call
85
+ model.orig_forward = model.forward
86
+ model.forward = partial(
87
+ model.orig_forward,
88
+ region_masks=region_masks
89
+ )
90
+ output_ids = model.generate(
91
+ input_ids,
92
+ images=image_tensor,
93
+ max_new_tokens=1024,
94
+ num_beams=1,
95
+ region_masks=region_masks, # pass the region mask to the model
96
+ image_sizes=[img.size]
97
+ )
98
+ model.forward = model.orig_forward
99
+
100
+ # we decode the output
101
+ output_text = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0]
102
+ return output_text.strip()
103
+
104
+ # We also define a task-specific inference function
105
+ def infer_ui_task(image_path, prompt, model_path, task, region=None):
106
+ """
107
+ Handles task types: box_in_tasks, box_out_tasks, no_box_tasks.
108
+ """
109
+ if task in box_in_tasks and region is None:
110
+ raise ValueError(f"Task {task} requires a bounding box region.")
111
+
112
+ if task in box_in_tasks:
113
+ print(f"Processing {task} with bounding box region.")
114
+ return infer_single_prompt(image_path, prompt, model_path, region)
115
+
116
+ elif task in box_out_tasks:
117
+ print(f"Processing {task} without bounding box region.")
118
+ return infer_single_prompt(image_path, prompt, model_path)
119
+
120
+ elif task in no_box_tasks:
121
+ print(f"Processing {task} without image or bounding box.")
122
+ return infer_single_prompt(image_path, prompt, model_path)
123
+
124
+ else:
125
+ raise ValueError(f"Unknown task type: {task}")