JosephZ commited on
Commit
9d7a635
·
verified ·
1 Parent(s): 504813f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +211 -0
app.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from PIL import Image
3
+
4
+ from transformers import Qwen2VLForConditionalGeneration, GenerationConfig
5
+ import base64
6
+ from io import BytesIO
7
+ from PIL import Image
8
+ import re
9
+
10
+
11
+ def extract_answer_content(text: str) -> str:
12
+ """
13
+ Extracts the content between <answer> and </answer> tags.
14
+ If no closing tag is found, extracts everything after the first <answer>.
15
+
16
+ Returns:
17
+ str: The extracted content.
18
+ """
19
+ text = text.replace("```", " ").replace("json", " ").strip()
20
+
21
+ # Try to find full <answer>...</answer>
22
+ match = re.search(r"<answer>(.*?)</answer>", text, re.DOTALL)
23
+ if match:
24
+ return match.group(1).strip()
25
+ # Fallback: everything after the first <answer>
26
+ match = re.search(r"<answer>(.*)", text, re.DOTALL)
27
+ return match.group(1).strip() if match else text
28
+
29
+
30
+ def encode_image_to_base64(image: Image.Image, format: str = "PNG") -> str:
31
+ """
32
+ Encode a PIL Image to a base64 string.
33
+
34
+ Args:
35
+ image (PIL.Image): The image to encode.
36
+ format (str): Image format to use (e.g., "PNG", "JPEG"). Default is "PNG".
37
+
38
+ Returns:
39
+ str: Base64-encoded string of the image.
40
+ """
41
+ buffer = BytesIO()
42
+ image.save(buffer, format=format)
43
+ buffer.seek(0)
44
+ encoded_string = base64.b64encode(buffer.read()).decode("utf-8")
45
+ return encoded_string
46
+
47
+
48
+
49
+ SYSTEM_PROMPT = (
50
+ "A conversation between User and Assistant. The user asks a question, and the Assistant solves it. The assistant "
51
+ "first thinks about the reasoning process in the mind and then provides the user with the answer. The reasoning "
52
+ "process and answer are enclosed within <think> </think> and <answer> </answer> tags, respectively, i.e., "
53
+ "<think> reasoning process here </think><answer> answer here </answer>"
54
+ )
55
+
56
+
57
+
58
+ # Load model and processor
59
+ processor = AutoProcessor.from_pretrained("JosephZ/qwen2vl-7b-sft-grpo-close-sgg", max_pixels=1024*28*28)
60
+
61
+ device='cuda' if torch.cuda.is_available() else "cpu"
62
+ model = Qwen2VLForConditionalGeneration.from_pretrained("JosephZ/qwen2vl-7b-sft-grpo-close-sgg",
63
+ torch_dtype=torch.bfloat16,
64
+ device_map=device)
65
+
66
+ generation_config=GenerationConfig(
67
+ do_sample=True,
68
+ temperature=0.01,
69
+ top_k=1,
70
+ top_p=0.001,
71
+ repetition_penalty=1.0,
72
+ max_new_tokens=2048,
73
+ )
74
+
75
+ def build_prompt(image, use_text):
76
+ #base64_image = encode_image_to_base64(image)
77
+ messages = [
78
+ {
79
+ "role": "system",
80
+ "content": SYSTEM_PROMPT
81
+ },
82
+ {
83
+ "role": "user",
84
+ "content": [
85
+ #{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}},
86
+ {"type": "image"},
87
+ {"type": "text", "text": user_text},
88
+ ],
89
+ },
90
+ ]
91
+ return messages
92
+
93
+ PROMPT_CLOSE="""Generate a structured scene graph for an image using the specified object and relationship categories.
94
+
95
+ ### **Output Format:**
96
+ ```json
97
+ {
98
+ "objects": [
99
+ {"id": "object_name.number", "bbox": [x1, y1, x2, y2]},
100
+ ...
101
+ ],
102
+ "relationships": [
103
+ {"subject": "object_name.number", "predicate": "relationship_type", "object": "object_name.number"},
104
+ ...
105
+ ]
106
+ }
107
+ ```
108
+
109
+ ### **Guidelines:**
110
+ - **Objects:**
111
+ - Assign unique IDs in the format `"object_name.number"` (e.g., `"person.1"`). The **object_name** must belong to the predefined object set: `["airplane", "animal", "arm", "bag", "banana", "basket", "beach", "bear", "bed", "bench", "bike", "bird", "board", "boat", "book", "boot", "bottle", "bowl", "box", "boy", "branch", "building", "bus", "cabinet", "cap", "car", "cat", "chair", "child", "clock", "coat", "counter", "cow", "cup", "curtain", "desk", "dog", "door", "drawer", "ear", "elephant", "engine", "eye", "face", "fence", "finger", "flag", "flower", "food", "fork", "fruit", "giraffe", "girl", "glass", "glove", "guy", "hair", "hand", "handle", "hat", "head", "helmet", "hill", "horse", "house", "jacket", "jean", "kid", "kite", "lady", "lamp", "laptop", "leaf", "leg", "letter", "light", "logo", "man", "men", "motorcycle", "mountain", "mouth", "neck", "nose", "number", "orange", "pant", "paper", "paw", "people", "person", "phone", "pillow", "pizza", "plane", "plant", "plate", "player", "pole", "post", "pot", "racket", "railing", "rock", "roof", "room", "screen", "seat", "sheep", "shelf", "shirt", "shoe", "short", "sidewalk", "sign", "sink", "skateboard", "ski", "skier", "sneaker", "snow", "sock", "stand", "street", "surfboard", "table", "tail", "tie", "tile", "tire", "toilet", "towel", "tower", "track", "train", "tree", "truck", "trunk", "umbrella", "vase", "vegetable", "vehicle", "wave", "wheel", "window", "windshield", "wing", "wire", "woman", "zebra"]`.
112
+ - Provide a bounding box `[x1, y1, x2, y2]` in integer pixel format.
113
+ - Include all visible objects, even if they have no relationships.
114
+
115
+ - **Relationships:**
116
+ - Define relationships using `"subject"`, `"predicate"`, and `"object"`.
117
+ - The **predicate** must belong to the predefined relationship set: `["above", "across", "against", "along", "and", "at", "attached to", "behind", "belonging to", "between", "carrying", "covered in", "covering", "eating", "flying in", "for", "from", "growing on", "hanging from", "has", "holding", "in", "in front of", "laying on", "looking at", "lying on", "made of", "mounted on", "near", "of", "on", "on back of", "over", "painted on", "parked on", "part of", "playing", "riding", "says", "sitting on", "standing on", "to", "under", "using", "walking in", "walking on", "watching", "wearing", "wears", "with"]`.
118
+ - Omit relationships for orphan objects.
119
+
120
+ ### **Example Output:**
121
+ ```json
122
+ {
123
+ "objects": [
124
+ {"id": "person.1", "bbox": [120, 200, 350, 700]},
125
+ {"id": "bike.2", "bbox": [100, 600, 400, 800]},
126
+ {"id": "helmet.3", "bbox": [150, 150, 280, 240]},
127
+ {"id": "tree.4", "bbox": [500, 100, 750, 700]}
128
+ ],
129
+ "relationships": [
130
+ {"subject": "person.1", "predicate": "riding", "object": "bike.2"},
131
+ {"subject": "person.1", "predicate": "wearing", "object": "helmet.3"}
132
+ ]
133
+ }
134
+ ```
135
+
136
+ Now, generate the complete scene graph for the provided image:
137
+ """
138
+
139
+ def is_box(item):
140
+ return (
141
+ isinstance(item, (list, tuple)) and
142
+ len(item) == 4 and
143
+ all(isinstance(e, (int, float)) for e in item)
144
+ )
145
+
146
+ def scale_box(box, scale):
147
+ sw, sh = scale
148
+ return [int(box[0]*sw), int(box[1]*sh), int(box[2]*sw), int(box[3]*sh)]
149
+
150
+
151
+ def generate_sgg(image):
152
+ iw, ih = image.size
153
+ scale_factors = (iw / 1000.0, ih / 1000.0)
154
+
155
+ conversation = build_prompt(image, PROMPT_CLOSE)
156
+ text_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
157
+
158
+ inputs = processor(
159
+ text=[text_prompt], images=[image], padding=True, return_tensors="pt"
160
+ )
161
+ inputs = inputs.to(model.device)
162
+
163
+ output_ids = model.generate(**inputs, generation_config=generation_config)
164
+ generated_ids = [
165
+ output_ids[len(input_ids) :]
166
+ for input_ids, output_ids in zip(inputs.input_ids, output_ids)
167
+ ]
168
+ output_text = processor.batch_decode(
169
+ generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True
170
+ )[0]
171
+
172
+ resp = extract_answer_content(output_text)
173
+
174
+ try:
175
+ resp = json.loads(resp)
176
+ pred_objs = resp['objects']
177
+ pred_rels = resp['relationships']
178
+ new_objs = []
179
+ for obj in pred_objs:
180
+ assert len(obj['bbox']) == 4, "len(obj['bbox']) != 4"
181
+ assert is_box(obj['bbox']), "invalid box :{}".format(obj['bbox'])
182
+ assert 'id' in obj, "invalid obj:{}".format(obj)
183
+ obj['bbox'] = scale_box(obj['bbox'], scale_factors)
184
+ new_objs.append(obj)
185
+ pred_objs = new_objs
186
+ resp = {"objects": pred_objs, "relationships": pred_rels}
187
+
188
+ # visualize pred_objs
189
+ draw = ImageDraw.Draw(image)
190
+ try:
191
+ font = ImageFont.truetype("arial.ttf", 16)
192
+ except:
193
+ font = ImageFont.load_default()
194
+
195
+ for obj in pred_objs:
196
+ bbox = obj["bbox"]
197
+ label = obj["id"]
198
+ draw.rectangle(bbox, outline="red", width=3)
199
+ draw.text((bbox[0], bbox[1] - 15), label, fill="red", font=font)
200
+ except:
201
+ pass
202
+
203
+ return json.dumps(resp) if not isinstance(resp, str) else resp
204
+
205
+ gr.Interface(
206
+ fn=generate_sgg,
207
+ inputs=gr.Image(type="pil"),
208
+ outputs="text",
209
+ title="R1-SGG: Compile Scene Graphs with Reinforcement Learning",
210
+ description="Upload an image and generate a structured scene graph in JSON format."
211
+ ).launch()