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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
+
import torch
|
3 |
+
import boto3
|
4 |
+
import requests
|
5 |
+
import re
|
6 |
+
from bs4 import BeautifulSoup
|
7 |
+
from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
|
8 |
+
from qwen_vl_utils import process_vision_info
|
9 |
+
import os
|
10 |
+
from PIL import Image, ImageDraw, ImageFont
|
11 |
+
import numpy as np
|
12 |
+
import hashlib
|
13 |
|
|
|
|
|
14 |
|
15 |
+
#First output the thinking process in <think> </think> tags and then output the final answer in <answer> </answer> tags.
|
16 |
+
#Answer the following question based on the information above and the given image, and provide citations for your response.
|
17 |
+
|
18 |
+
|
19 |
+
# Cache for storing recognition results
|
20 |
+
recognition_cache = {}
|
21 |
+
|
22 |
+
# Function to calculate image hash for caching
|
23 |
+
def calculate_image_hash(image):
|
24 |
+
"""Calculate a hash for the image to use as a cache key"""
|
25 |
+
if image is None:
|
26 |
+
return None
|
27 |
+
img_array = np.array(image)
|
28 |
+
# Use a simple hash of the image data
|
29 |
+
return hashlib.md5(img_array.tobytes()).hexdigest()
|
30 |
+
|
31 |
+
# Helper function to remove numbers from brackets
|
32 |
+
def remove_bracketed_nums(input_string):
|
33 |
+
"""
|
34 |
+
Removes all occurrences of [num] from the input string.
|
35 |
+
"""
|
36 |
+
return re.sub(r'\[\d+\]', '', input_string)
|
37 |
+
|
38 |
+
# Function to get Wikipedia links
|
39 |
+
def fetch_wikipedia_links(entity_id):
|
40 |
+
url = f"https://www.wikidata.org/wiki/Special:EntityData/{entity_id}.json"
|
41 |
+
links = {}
|
42 |
+
try:
|
43 |
+
response = requests.get(url)
|
44 |
+
response.raise_for_status()
|
45 |
+
data = response.json()
|
46 |
+
entity_data = data.get("entities", {}).get(entity_id, {})
|
47 |
+
if not entity_data:
|
48 |
+
print("No data found for the given entity ID.")
|
49 |
+
return links
|
50 |
+
|
51 |
+
sitelinks = entity_data.get("sitelinks", {})
|
52 |
+
if not sitelinks:
|
53 |
+
print("No sitelinks found for the given entity ID.")
|
54 |
+
return links
|
55 |
+
|
56 |
+
wikipedia_links = {}
|
57 |
+
for site, site_info in sitelinks.items():
|
58 |
+
if site.endswith("wiki"):
|
59 |
+
language = site.replace("wiki", "")
|
60 |
+
url = site_info.get("url")
|
61 |
+
wikipedia_links[language] = url
|
62 |
+
|
63 |
+
for lang, link in wikipedia_links.items():
|
64 |
+
links[lang] = link
|
65 |
+
|
66 |
+
except requests.RequestException as e:
|
67 |
+
print(f"Error fetching data: {e}")
|
68 |
+
return links
|
69 |
+
|
70 |
+
# Function to get Wikipedia information
|
71 |
+
def fetch_wikipedia_info(url):
|
72 |
+
try:
|
73 |
+
# Send HTTP request
|
74 |
+
response = requests.get(url)
|
75 |
+
response.raise_for_status()
|
76 |
+
|
77 |
+
# Parse HTML content using BeautifulSoup
|
78 |
+
soup = BeautifulSoup(response.content, 'html.parser')
|
79 |
+
|
80 |
+
# Try multiple methods to find the title
|
81 |
+
title = None
|
82 |
+
|
83 |
+
# Method 1: Find title in the <title> tag of the page
|
84 |
+
if not title:
|
85 |
+
title_tag = soup.find('title')
|
86 |
+
if title_tag:
|
87 |
+
title = title_tag.text.replace(' - Wikipedia', '').strip()
|
88 |
+
|
89 |
+
# Method 2: Find title in h1 tag
|
90 |
+
if not title:
|
91 |
+
title_tag = soup.find('h1', {'id': 'firstHeading'})
|
92 |
+
if title_tag:
|
93 |
+
title = title_tag.text.strip()
|
94 |
+
|
95 |
+
# Method 3: If previous methods fail, use a more flexible method
|
96 |
+
if not title:
|
97 |
+
title_tag = soup.find('h1')
|
98 |
+
if title_tag:
|
99 |
+
title = title_tag.text.strip()
|
100 |
+
|
101 |
+
# Extract sections and their content
|
102 |
+
sections = {}
|
103 |
+
current_section = None
|
104 |
+
paragraphs = soup.find_all('p')
|
105 |
+
|
106 |
+
# Traverse all headings and paragraphs, mapping sections to content
|
107 |
+
for element in soup.find_all(['h2', 'p']):
|
108 |
+
if element.name == 'h2':
|
109 |
+
# New section starts, get section title
|
110 |
+
section_title = element.text.strip()
|
111 |
+
current_section = section_title
|
112 |
+
sections[current_section] = []
|
113 |
+
elif element.name == 'p' and current_section:
|
114 |
+
# Add paragraph to current section
|
115 |
+
paragraph_text = element.text.strip()
|
116 |
+
if paragraph_text:
|
117 |
+
sections[current_section].append(paragraph_text)
|
118 |
+
|
119 |
+
# Convert section content to format where each section is connected into a single string
|
120 |
+
sections = {section: '\n'.join(content) for section, content in sections.items()}
|
121 |
+
|
122 |
+
return {
|
123 |
+
'title': title or 'No title found',
|
124 |
+
'sections': sections
|
125 |
+
}
|
126 |
+
|
127 |
+
except requests.RequestException as e:
|
128 |
+
return {'error': f'Request failed: {e}'}
|
129 |
+
except Exception as e:
|
130 |
+
return {'error': f'An error occurred: {e}'}
|
131 |
+
|
132 |
+
# Use AWS Rekognition to recognize celebrities in the image
|
133 |
+
def recognize_celebrities(image_path, confidence_threshold=90):
|
134 |
+
client = boto3.client(
|
135 |
+
"rekognition",
|
136 |
+
aws_access_key_id=,
|
137 |
+
aws_secret_access_key=,
|
138 |
+
region_name='us-east-1'
|
139 |
+
)
|
140 |
+
|
141 |
+
with open(image_path, 'rb') as image:
|
142 |
+
response = client.recognize_celebrities(Image={'Bytes': image.read()})
|
143 |
+
|
144 |
+
# Filter out celebrities with None or low confidence
|
145 |
+
filtered_celebs = [cele for cele in response.get('CelebrityFaces', [])
|
146 |
+
if cele.get('MatchConfidence') is not None and cele.get('MatchConfidence') > confidence_threshold]
|
147 |
+
|
148 |
+
names = [cele['Name'] for cele in filtered_celebs]
|
149 |
+
bounding_boxes = [cele['Face']['BoundingBox'] for cele in filtered_celebs]
|
150 |
+
wikidatas = [cele['Urls'][0] for cele in filtered_celebs]
|
151 |
+
|
152 |
+
return names, bounding_boxes, wikidatas
|
153 |
+
|
154 |
+
# Draw bounding boxes on the image
|
155 |
+
def draw_bounding_boxes(image_path, bounding_boxes, names):
|
156 |
+
img = Image.open(image_path)
|
157 |
+
draw = ImageDraw.Draw(img)
|
158 |
+
|
159 |
+
width, height = img.size
|
160 |
+
|
161 |
+
for i, bbox in enumerate(bounding_boxes):
|
162 |
+
left = int(bbox['Left'] * width)
|
163 |
+
top = int(bbox['Top'] * height)
|
164 |
+
right = int((bbox['Left'] + bbox['Width']) * width)
|
165 |
+
bottom = int((bbox['Top'] + bbox['Height']) * height)
|
166 |
+
|
167 |
+
# Draw rectangle
|
168 |
+
draw.rectangle([(left, top), (right, bottom)], outline="red", width=3)
|
169 |
+
|
170 |
+
# Add name label
|
171 |
+
text = f"[{i+1}]: {names[i]}"
|
172 |
+
font = ImageFont.truetype("arial.ttf", 20) # Adjust font and size as needed
|
173 |
+
text_bbox = draw.textbbox((left, top - 20), text, font=font)
|
174 |
+
draw.rectangle(text_bbox, fill="white")
|
175 |
+
draw.text((left, top - 20), text, fill="red", font=font)
|
176 |
+
return np.array(img)
|
177 |
+
|
178 |
+
# Resize the image to a smaller size for display
|
179 |
+
def resize_image_for_display(img_array, max_width=500):
|
180 |
+
img = Image.fromarray(img_array)
|
181 |
+
width, height = img.size
|
182 |
+
if width > max_width:
|
183 |
+
ratio = max_width / width
|
184 |
+
new_height = int(height * ratio)
|
185 |
+
img = img.resize((max_width, new_height), Image.LANCZOS)
|
186 |
+
return np.array(img)
|
187 |
+
|
188 |
+
model = Qwen2VLForConditionalGeneration.from_pretrained(
|
189 |
+
"weihongliang/RC-Qwen2VL-2b",
|
190 |
+
torch_dtype=torch.float16,
|
191 |
+
device_map="auto"
|
192 |
+
)
|
193 |
+
processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct")
|
194 |
+
|
195 |
+
# Use Qwen model for Q&A
|
196 |
+
def qwen_qa(image_path, question, names, bounding_boxes, en_wiki_pedia_links, en_intros):
|
197 |
+
# Prepare prompt text
|
198 |
+
prompt = '\n'.join([
|
199 |
+
f"[{i+1}]: The information of the person located at <|box_start|>({int(bbox['Left']*1000)},{int(bbox['Top']*1000)}),"
|
200 |
+
f"({int((bbox['Left']+bbox['Width'])*1000)},{int((bbox['Top']+bbox['Height'])*1000)})<|box_end|> in the image: {intro}"
|
201 |
+
for i, (name, intro, bbox) in enumerate(zip(
|
202 |
+
names,
|
203 |
+
[remove_bracketed_nums(intro).replace('\n','') for intro in en_intros],
|
204 |
+
bounding_boxes
|
205 |
+
))
|
206 |
+
])
|
207 |
+
print(prompt)
|
208 |
+
# Prepare messages
|
209 |
+
messages = [
|
210 |
+
{
|
211 |
+
"role": "user",
|
212 |
+
"content": [
|
213 |
+
{
|
214 |
+
"type": "image",
|
215 |
+
"image": image_path,
|
216 |
+
},
|
217 |
+
{"type": "text", "text": f"{prompt}\nAnswer the following question based on the information above and the given image, and provide citations for your response.\n{question}"},
|
218 |
+
],
|
219 |
+
}
|
220 |
+
]
|
221 |
+
|
222 |
+
# Prepare inference
|
223 |
+
text = processor.apply_chat_template(
|
224 |
+
messages, tokenize=False, add_generation_prompt=True
|
225 |
+
)
|
226 |
+
image_inputs, video_inputs = process_vision_info(messages)
|
227 |
+
|
228 |
+
inputs = processor(
|
229 |
+
text=[text],
|
230 |
+
images=image_inputs,
|
231 |
+
videos=None,
|
232 |
+
padding=True,
|
233 |
+
return_tensors="pt",
|
234 |
+
)
|
235 |
+
|
236 |
+
inputs = inputs.to("cuda")
|
237 |
+
|
238 |
+
# Inference: generate output
|
239 |
+
generated_ids = model.generate(**inputs, max_new_tokens=4096)
|
240 |
+
generated_ids_trimmed = [
|
241 |
+
out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
|
242 |
+
]
|
243 |
+
output_text = processor.batch_decode(
|
244 |
+
generated_ids_trimmed, skip_special_tokens=False, clean_up_tokenization_spaces=False
|
245 |
+
)[0]
|
246 |
+
print(output_text)
|
247 |
+
return output_text, en_wiki_pedia_links, prompt
|
248 |
+
|
249 |
+
# Compare image with examples by filename or content when available
|
250 |
+
def is_example_image(image, examples):
|
251 |
+
if isinstance(image, str) and os.path.exists(image):
|
252 |
+
# If we have a path, try to match by filename
|
253 |
+
image_name = os.path.basename(image)
|
254 |
+
for example in examples:
|
255 |
+
example_name = os.path.basename(example[0])
|
256 |
+
if image_name == example_name:
|
257 |
+
print(f"Matched example by filename: {image_name}")
|
258 |
+
return True, example
|
259 |
+
|
260 |
+
# If we couldn't match by filename or if image is an object, return False
|
261 |
+
return False, None
|
262 |
+
|
263 |
+
# Main processing function
|
264 |
+
def process_image(image, question, confidence_threshold, examples=None):
|
265 |
+
if image is None:
|
266 |
+
return None, "Please upload an image", []
|
267 |
+
|
268 |
+
# Calculate image hash for caching
|
269 |
+
image_hash = calculate_image_hash(image)
|
270 |
+
|
271 |
+
# Check if we already have cached recognition results for this image
|
272 |
+
cache_key = f"{image_hash}_{confidence_threshold}"
|
273 |
+
if cache_key in recognition_cache:
|
274 |
+
print("Using cached recognition results")
|
275 |
+
names, bounding_boxes, en_wiki_pedia_links, en_intros, result_image = recognition_cache[cache_key]
|
276 |
+
else:
|
277 |
+
print("Performing new recognition")
|
278 |
+
# Save uploaded image
|
279 |
+
temp_image_path = "temp_image.jpg"
|
280 |
+
image.save(temp_image_path)
|
281 |
+
|
282 |
+
# Check if this image matches one of our example images
|
283 |
+
# First, get original filename from gradio image object if available
|
284 |
+
original_filename = None
|
285 |
+
if hasattr(image, 'name'):
|
286 |
+
original_filename = image.name
|
287 |
+
|
288 |
+
# For each example, check if the file exists and compare
|
289 |
+
example_match = None
|
290 |
+
if examples:
|
291 |
+
for example in examples:
|
292 |
+
example_path = example[0]
|
293 |
+
if os.path.exists(example_path):
|
294 |
+
example_img = Image.open(example_path)
|
295 |
+
# Compare images by size first (quick check)
|
296 |
+
if example_img.size == image.size:
|
297 |
+
# More thorough comparison - hash the pixels
|
298 |
+
example_hash = calculate_image_hash(example_img)
|
299 |
+
if example_hash == image_hash:
|
300 |
+
example_match = example
|
301 |
+
break
|
302 |
+
example_img.close()
|
303 |
+
|
304 |
+
if example_match:
|
305 |
+
print("Using example data instead of recognition")
|
306 |
+
names = example_match[2]
|
307 |
+
bounding_boxes = example_match[3]
|
308 |
+
wikidatas = example_match[4]
|
309 |
+
print(f"Example data: {names}, {bounding_boxes}, {wikidatas}")
|
310 |
+
else:
|
311 |
+
# Recognize celebrities with adjusted confidence threshold
|
312 |
+
names, bounding_boxes, wikidatas = recognize_celebrities(temp_image_path, confidence_threshold)
|
313 |
+
|
314 |
+
print(f'θ―ε«_{names}_{bounding_boxes}_{wikidatas}')
|
315 |
+
en_wiki_pedia_links = []
|
316 |
+
en_intros = []
|
317 |
+
|
318 |
+
for wikidata_url in wikidatas:
|
319 |
+
entity_id = wikidata_url.split('/')[-1]
|
320 |
+
links = fetch_wikipedia_links(entity_id)
|
321 |
+
|
322 |
+
if 'en' in links:
|
323 |
+
en_link = links['en']
|
324 |
+
en_wiki_pedia_links.append(en_link)
|
325 |
+
|
326 |
+
wiki_info = fetch_wikipedia_info(en_link)
|
327 |
+
# Try to get 'Contents' section, if it doesn't exist, try to get the first section
|
328 |
+
intro = wiki_info['sections'].get('Contents', '')
|
329 |
+
if not intro and wiki_info['sections']:
|
330 |
+
intro = next(iter(wiki_info['sections'].values()), '')
|
331 |
+
|
332 |
+
en_intros.append(intro)
|
333 |
+
else:
|
334 |
+
en_wiki_pedia_links.append("No English Wikipedia link found")
|
335 |
+
en_intros.append("No information available")
|
336 |
+
|
337 |
+
if not names:
|
338 |
+
if os.path.exists(temp_image_path):
|
339 |
+
os.remove(temp_image_path)
|
340 |
+
return None, f"No celebrities could be recognized with confidence threshold {confidence_threshold}%", []
|
341 |
+
|
342 |
+
indices = list(range(len(en_intros)))
|
343 |
+
|
344 |
+
# Sort indices by the length of en_intros elements
|
345 |
+
indices.sort(key=lambda i: len(en_intros[i]))
|
346 |
+
|
347 |
+
# Use sorted indices to rearrange the three lists
|
348 |
+
names = [names[i] for i in indices]
|
349 |
+
bounding_boxes = [bounding_boxes[i] for i in indices]
|
350 |
+
en_intros = [en_intros[i] for i in indices]
|
351 |
+
en_wiki_pedia_links = [en_wiki_pedia_links[i] for i in indices]
|
352 |
+
|
353 |
+
# Draw bounding boxes on the image
|
354 |
+
result_image = draw_bounding_boxes(temp_image_path, bounding_boxes, names)
|
355 |
+
|
356 |
+
# Cache the recognition results
|
357 |
+
recognition_cache[cache_key] = (names, bounding_boxes, en_wiki_pedia_links, en_intros, result_image)
|
358 |
+
|
359 |
+
# Clean up temporary files
|
360 |
+
if os.path.exists(temp_image_path):
|
361 |
+
os.remove(temp_image_path)
|
362 |
+
|
363 |
+
# Save image for qwen_qa (it requires a file path)
|
364 |
+
temp_image_path = "temp_image_for_qa.jpg"
|
365 |
+
Image.fromarray(result_image if isinstance(image, np.ndarray) else np.array(image)).save(temp_image_path)
|
366 |
+
|
367 |
+
# Resize the result image for display
|
368 |
+
resized_image = resize_image_for_display(result_image, max_width=500)
|
369 |
+
|
370 |
+
# Use Qwen model for Q&A
|
371 |
+
answer, wiki_links, prompt = qwen_qa(temp_image_path, question, names, bounding_boxes, en_wiki_pedia_links, en_intros)
|
372 |
+
|
373 |
+
# Prepare recognized person information for frontend
|
374 |
+
people_info = [[prompt]]
|
375 |
+
[people_info.append([f"{name}: {link}"]) for name, link in zip(names, en_wiki_pedia_links)]
|
376 |
+
|
377 |
+
# Clean up temporary files
|
378 |
+
if os.path.exists(temp_image_path):
|
379 |
+
os.remove(temp_image_path)
|
380 |
+
|
381 |
+
return resized_image, answer, people_info
|
382 |
+
|
383 |
+
# Create Gradio interface
|
384 |
+
def create_interface():
|
385 |
+
# Define examples - with proper wikidata URLs
|
386 |
+
examples = [
|
387 |
+
["./musk_and_huang.jpg", "What is Jensen doing?",
|
388 |
+
['Jen-Hsun Huang', 'Elon Musk'],
|
389 |
+
[{'Width': 0.14037726819515228, 'Height': 0.20855841040611267, 'Left': 0.20549052953720093, 'Top': 0.05287889018654823},
|
390 |
+
{'Width': 0.07806053012609482, 'Height': 0.12407417595386505, 'Left': 0.7048892974853516, 'Top': 0.12597641348838806}],
|
391 |
+
['https://www.wikidata.org/wiki/Q305177', 'https://www.wikidata.org/wiki/Q317521']],
|
392 |
+
["./dtms.jpg", "Describe the image.",
|
393 |
+
['Claude Shannon', 'John McCarthy', 'Marvin Minsky'],
|
394 |
+
[{'Width': 0.06745696812868118, 'Height': 0.1393456608057022, 'Left': 0.8298415541648865, 'Top': 0.2935926616191864},
|
395 |
+
{'Width': 0.058158036321401596, 'Height': 0.10835719853639603, 'Left': 0.7029165029525757, 'Top': 0.16815270483493805},
|
396 |
+
{'Width': 0.05310939624905586, 'Height': 0.1121278703212738, 'Left': 0.4884793162345886, 'Top': 0.19025743007659912}],
|
397 |
+
['https://www.wikidata.org/wiki/Q92760', 'https://www.wikidata.org/wiki/Q92739', 'https://www.wikidata.org/wiki/Q204815']],
|
398 |
+
["./hinton.jpeg", "Describe the image in detail.",
|
399 |
+
['Yoshua Bengio', 'Geoffrey Hinton', 'Yann LeCun'],
|
400 |
+
[{'Width': 0.077728271484375, 'Height': 0.16116079688072205, 'Left': 0.8799420595169067, 'Top': 0.4856656789779663},
|
401 |
+
{'Width': 0.07422236353158951, 'Height': 0.15943190455436707, 'Left': 0.4633428454399109, 'Top': 0.07901764661073685},
|
402 |
+
{'Width': 0.07562466710805893, 'Height': 0.13936467468738556, 'Left': 0.025178398936986923, 'Top': 0.4953641891479492}],
|
403 |
+
['https://www.wikidata.org/wiki/Q3572699', 'https://www.wikidata.org/wiki/Q92894', 'https://www.wikidata.org/wiki/Q3571662']],
|
404 |
+
["./clinton.jpg", "Who are the people in the picture, and what is the relationship between them?",
|
405 |
+
['Bill Clinton', 'Monica Lewinsky'],
|
406 |
+
[{'Width': 0.07620880007743835, 'Height': 0.16198107600212097, 'Left': 0.5074607729911804, 'Top': 0.14220821857452393},
|
407 |
+
{'Width': 0.0722670778632164, 'Height': 0.1512720286846161, 'Left': 0.3914872407913208, 'Top': 0.24376636743545532}],
|
408 |
+
['https://www.wikidata.org/wiki/Q1124', 'https://www.wikidata.org/wiki/Q212659']],
|
409 |
+
["./epst.jpeg", "Provide image description.",
|
410 |
+
['Lisa Randall', 'Kip S. Thorne', 'David Gross', 'Stephen Hawking', 'Brenda Chapman'],
|
411 |
+
[{'Width': 0.09916354715824127, 'Height': 0.166521355509758, 'Left': 0.7962431311607361, 'Top': 0.4121580123901367},
|
412 |
+
{'Width': 0.07940348237752914, 'Height': 0.1626593917608261, 'Left': 0.6891748905181885, 'Top': 0.33117005228996277},
|
413 |
+
{'Width': 0.06350294500589371, 'Height': 0.12757645547389984, 'Left': 0.544218122959137, 'Top': 0.1575603038072586},
|
414 |
+
{'Width': 0.06830617040395737, 'Height': 0.1128319799900055, 'Left': 0.2937725782394409, 'Top': 0.30404558777809143},
|
415 |
+
{'Width': 0.03966952860355377, 'Height': 0.11658532917499542, 'Left': 0.18093101680278778, 'Top': 0.31299835443496704}],
|
416 |
+
['https://www.wikidata.org/wiki/Q450404', 'https://www.wikidata.org/wiki/Q323320', 'https://www.wikidata.org/wiki/Q40262', 'https://www.wikidata.org/wiki/Q17714', 'https://www.wikidata.org/wiki/Q429715']]
|
417 |
+
]
|
418 |
+
|
419 |
+
# Filter examples to only include files that exist
|
420 |
+
existing_examples = []
|
421 |
+
for example in examples:
|
422 |
+
if os.path.exists(example[0]):
|
423 |
+
existing_examples.append(example)
|
424 |
+
|
425 |
+
with gr.Blocks(title="Celebrity Recognition and Q&A System") as app:
|
426 |
+
gr.Markdown("<div style='text-align: center;'><h1 style=' font-size: 28px; '>Celebrity Recognition and Q&A System</h1></div>")
|
427 |
+
gr.Markdown("**RC-MLLM** model is developed based on the Qwen2-VL model through a novel method called **RCVIT (Region-level Context-aware Visual Instruction Tuning)**, using the specially constructed **RCMU dataset** for training. Its core feature is the capability for **Region-level Context-aware Multimodal Understanding (RCMU)**. This means it can simultaneously understand both the visual content of specific regions/objects within an image and their associated textual information (utilizing bounding boxes coordinates), allowing it to respond to user instructions in a more context-aware manner. Simply put, RC-MLLM not only understands images but can also integrate the textual information linked to specific objects within the image for understanding. It achieves outstanding performance on RCMU tasks and is suitable for applications like personalized conversation.")
|
428 |
+
|
429 |
+
markdown_content = """
|
430 |
+
π [Arxiv](https://arxiv.org/abs/your-paper-id) |
|
431 |
+
π€ [Checkpoint]() |
|
432 |
+
π [Dataset](https://huggingface.co/your-model-name) |
|
433 |
+
[Github](https://github.com/your-username/your-repo) |
|
434 |
+
π [Personalized Conversation](https://your-project-url.com)
|
435 |
+
"""
|
436 |
+
gr.Markdown(markdown_content)
|
437 |
+
gr.Markdown("π Upload an image containing celebrities, the system will recognize them and provide Wikipedia-based Q&A using the RC-Qwen2-VL model.")
|
438 |
+
|
439 |
+
with gr.Row():
|
440 |
+
with gr.Column(scale=1):
|
441 |
+
image_input = gr.Image(type="pil", label="Upload Image")
|
442 |
+
question_input = gr.Textbox(label="Question", placeholder="Enter your question...")
|
443 |
+
confidence_slider = gr.Slider(
|
444 |
+
minimum=50,
|
445 |
+
maximum=100,
|
446 |
+
value=90,
|
447 |
+
step=1,
|
448 |
+
label="Confidence Threshold (%)",
|
449 |
+
info="Adjust the minimum confidence level for celebrity recognition"
|
450 |
+
)
|
451 |
+
submit_button = gr.Button("Ask RC-Qwen2-VL")
|
452 |
+
|
453 |
+
# Add examples section
|
454 |
+
if existing_examples:
|
455 |
+
gr.Examples(
|
456 |
+
examples=[[example[0], example[1]] for example in existing_examples],
|
457 |
+
inputs=[image_input, question_input],
|
458 |
+
label="Example Images with Questions",
|
459 |
+
fn=None
|
460 |
+
)
|
461 |
+
with gr.Column(scale=1):
|
462 |
+
image_output = gr.Image(label="Recognition Result")
|
463 |
+
answer_output = gr.Textbox(label="RC-Qwen2-VL Answer")
|
464 |
+
|
465 |
+
people_info = gr.Dataframe(
|
466 |
+
headers=["Recognized Person Information and Wikipedia Links"],
|
467 |
+
datatype=["str"],
|
468 |
+
label="Person Information",
|
469 |
+
wrap=True, # Enable text wrapping
|
470 |
+
)
|
471 |
+
|
472 |
+
# Function to clear the cache
|
473 |
+
def clear_cache():
|
474 |
+
global recognition_cache
|
475 |
+
old_count = len(recognition_cache)
|
476 |
+
recognition_cache = {}
|
477 |
+
return f"Cache cleared. {old_count} entries were removed."
|
478 |
+
|
479 |
+
# Handle image upload - clear cache when new image is uploaded
|
480 |
+
def on_image_upload(image):
|
481 |
+
if image is not None:
|
482 |
+
clear_cache()
|
483 |
+
return f"New image detected. Cache has been cleared."
|
484 |
+
return f"No image uploaded. Cache status unchanged."
|
485 |
+
|
486 |
+
# Modified submit function to handle examples without the current_example parameter
|
487 |
+
def submit_fn(image, question, confidence_threshold):
|
488 |
+
# Process image using the recognition system
|
489 |
+
return process_image(image, question, confidence_threshold, examples=examples)
|
490 |
+
|
491 |
+
# Connect buttons to functions
|
492 |
+
submit_button.click(
|
493 |
+
fn=submit_fn,
|
494 |
+
inputs=[image_input, question_input, confidence_slider],
|
495 |
+
outputs=[image_output, answer_output, people_info]
|
496 |
+
)
|
497 |
+
|
498 |
+
# Clear cache automatically when new image is uploaded
|
499 |
+
image_input.change(
|
500 |
+
fn=on_image_upload,
|
501 |
+
inputs=[image_input],
|
502 |
+
)
|
503 |
+
|
504 |
+
gr.Markdown("## Instructions")
|
505 |
+
gr.Markdown("""
|
506 |
+
1. Upload an image containing celebrities
|
507 |
+
2. Enter your question, for example:
|
508 |
+
- "Who are the people in the image?"
|
509 |
+
- "What achievements does the person on the left have?"
|
510 |
+
- "What is the relationship between these people?"
|
511 |
+
3. Adjust the confidence threshold slider if needed (lower values will recognize more faces but might be less accurate)
|
512 |
+
4. Click the submit button to get the answer
|
513 |
+
5. Or try one of the examples below
|
514 |
+
6. The system caches recognition results for each image and confidence threshold combination
|
515 |
+
7. Cache is automatically cleared when you upload a new image
|
516 |
+
""")
|
517 |
+
|
518 |
+
return app
|
519 |
+
|
520 |
+
# Launch the application
|
521 |
+
if __name__ == "__main__":
|
522 |
+
app = create_interface()
|
523 |
+
app.launch(share=True)
|