vigneshwar472 commited on
Commit
f78bbc4
·
verified ·
1 Parent(s): 7c5cb54

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +174 -0
app.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # import libraries and load the model
2
+ import random
3
+ import requests
4
+ from PIL import Image, ImageDraw, ImageFont
5
+ import numpy as np
6
+ import torch
7
+ from transformers import AutoProcessor, Owlv2ForObjectDetection
8
+ from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD
9
+
10
+ obj_processor = AutoProcessor.from_pretrained("google/owlv2-base-patch16-ensemble")
11
+ obj_model = Owlv2ForObjectDetection.from_pretrained("google/owlv2-base-patch16-ensemble")
12
+
13
+ colors = [
14
+ (255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 165, 0), (75, 0, 130),
15
+ (255, 255, 0), (0, 255, 255), (255, 105, 180), (138, 43, 226), (0, 128, 0),
16
+ (0, 128, 128), (255, 20, 147), (64, 224, 208), (128, 0, 128), (70, 130, 180),
17
+ (220, 20, 60), (255, 140, 0), (34, 139, 34), (218, 112, 214), (255, 99, 71),
18
+ (47, 79, 79), (186, 85, 211), (240, 230, 140), (169, 169, 169), (199, 21, 133)
19
+ ]
20
+
21
+ def detect_objects(image, objects):
22
+
23
+ texts = [objects]
24
+ inputs = obj_processor(text=texts, images=image, return_tensors="pt")
25
+
26
+ with torch.no_grad():
27
+ outputs = obj_model(**inputs)
28
+
29
+ target_sizes = torch.Tensor([image.size[::-1]])
30
+ results = obj_processor.post_process_object_detection(
31
+ outputs=outputs, threshold=0.2, target_sizes=target_sizes
32
+ )
33
+
34
+ i = 0
35
+ text = texts[i]
36
+ boxes, scores, labels = results[i]["boxes"], results[i]["scores"], results[i]["labels"]
37
+ return image, boxes, scores, labels
38
+
39
+ def annotate_image(image, boxes, scores, labels, objects):
40
+ draw = ImageDraw.Draw(image)
41
+ font = ImageFont.load_default()
42
+
43
+ for i, (box, score, label) in enumerate(zip(boxes, scores, labels)):
44
+ box = [round(coord, 2) for coord in box.tolist()]
45
+ color = colors[label % len(colors)]
46
+ draw.rectangle(box, outline=color, width=3)
47
+ draw.text((box[0], box[1]), f"{objects[label]}: {score:.2f}", font=font, fill=color)
48
+
49
+ return image
50
+
51
+ from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
52
+ from PIL import Image
53
+ import requests
54
+
55
+ cbt_processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct")
56
+ cbt_model = Qwen2VLForConditionalGeneration.from_pretrained("Qwen/Qwen2-VL-2B-Instruct", torch_dtype="auto", device_map="auto")
57
+
58
+ import random
59
+ import time
60
+ import gradio as gr
61
+
62
+ global history
63
+ history = [
64
+ {
65
+ "role": "system",
66
+ "content" : [
67
+ {
68
+ "type": "image",
69
+ },
70
+ {
71
+ "type": "text",
72
+ "text": "You are an conversation image recognition chatbot. Communicate with humans using natural language. Recognize the images, have a spatial understanding and answer the questions in a concise manner. Generate the best response for a user query. It must be correct lexically and grammatically.",
73
+ }
74
+ ]
75
+ }
76
+ ]
77
+
78
+ with gr.Blocks() as demo:
79
+
80
+ with gr.Row():
81
+
82
+ with gr.Column(scale=1):
83
+
84
+ #gr.Markdown("## Upload an Image")
85
+ image_input = gr.Image(type="pil", label="Upload your image here")
86
+ objects_input = gr.Textbox(label="Enter the objects to detect (comma-separated)", placeholder="e.g. 'cat, dog, car'")
87
+ image_output = gr.Image(type="pil", label="Detected Objects")
88
+
89
+ def run_object_detection(image, objects):
90
+ object_list = [obj.strip() for obj in objects.split(",")]
91
+ image, boxes, scores, labels = detect_objects(image, object_list)
92
+ annotated_image = annotate_image(image, boxes, scores, labels, object_list)
93
+ history.append({
94
+ 'role': 'system',
95
+ 'content': [
96
+ {
97
+ 'type': 'text',
98
+ 'text': f'In the image the objects detected are {labels}'
99
+ }
100
+ ]
101
+ })
102
+ return annotated_image
103
+
104
+ detect_button = gr.Button("Detect Objects")
105
+ detect_button.click(fn=run_object_detection, inputs=[image_input, objects_input], outputs=image_output)
106
+
107
+ with gr.Column(scale=2):
108
+
109
+ chatbot = gr.Chatbot()
110
+ msg = gr.Textbox()
111
+ clear = gr.ClearButton([msg, chatbot])
112
+
113
+ def user(message, chat_history):
114
+ return "", chat_history + [[message, ""]]
115
+
116
+ def chat_function(image, chat_history):
117
+
118
+ message = ''
119
+
120
+ if chat_history[-1][0] is not None:
121
+ message = str(chat_history[-1][0])
122
+
123
+ history.append({
124
+ "role": "user",
125
+ "content" : [
126
+ {
127
+ "type": "text",
128
+ "text": message
129
+ }
130
+ ]
131
+ })
132
+
133
+ text_prompt = cbt_processor.apply_chat_template(history, add_generation_prompt=True)
134
+
135
+ inputs = cbt_processor(
136
+ text = [text_prompt],
137
+ images = [image],
138
+ padding = True,
139
+ return_tensors = "pt"
140
+ )
141
+
142
+ inputs = inputs.to("cuda")
143
+
144
+ output_ids = cbt_model.generate(**inputs, max_new_tokens=1024)
145
+
146
+ generated_ids = [
147
+ output_ids[len(input_ids) :]
148
+ for input_ids, output_ids in zip(inputs.input_ids, output_ids)
149
+ ]
150
+
151
+ bot_output = cbt_processor.batch_decode(
152
+ generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True
153
+ )
154
+
155
+ history.append({
156
+ "role": "assistant",
157
+ "content" : [
158
+ {
159
+ "type": "text",
160
+ "text": bot_output
161
+ }
162
+ ]
163
+ })
164
+
165
+ bot_output_str = gr.Markdown(str(bot_output).replace('"', '').replace('[', '').replace(']', ''))
166
+ for character in bot_output_str:
167
+ chat_history[-1][1] += character
168
+ time.sleep(0.05)
169
+ yield chat_history
170
+
171
+ msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(chat_function, [image_input, chatbot], [chatbot])
172
+ clear.click(lambda :None, None, chatbot, queue=False)
173
+
174
+ demo.launch(debug=True)