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
import torchvision.transforms as T
|
| 10 |
+
from torchvision.transforms.functional import InterpolationMode
|
| 11 |
+
from transformers import AutoModel, AutoTokenizer
|
| 12 |
+
from decord import VideoReader, cpu
|
| 13 |
+
|
| 14 |
+
# =============================================================================
|
| 15 |
+
# InternVL ์ ์ฒ๋ฆฌ/๋ก๋ฉ ์ฝ๋ (์๋ณธ ์์์์ ๋ฐ์ท)
|
| 16 |
+
# =============================================================================
|
| 17 |
+
IMAGENET_MEAN = (0.485, 0.456, 0.406)
|
| 18 |
+
IMAGENET_STD = (0.229, 0.224, 0.225)
|
| 19 |
+
|
| 20 |
+
def build_transform(input_size):
|
| 21 |
+
MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
|
| 22 |
+
transform = T.Compose([
|
| 23 |
+
T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
|
| 24 |
+
T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
|
| 25 |
+
T.ToTensor(),
|
| 26 |
+
T.Normalize(mean=MEAN, std=STD)
|
| 27 |
+
])
|
| 28 |
+
return transform
|
| 29 |
+
|
| 30 |
+
def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
|
| 31 |
+
best_ratio_diff = float('inf')
|
| 32 |
+
best_ratio = (1, 1)
|
| 33 |
+
area = width * height
|
| 34 |
+
for ratio in target_ratios:
|
| 35 |
+
target_aspect_ratio = ratio[0] / ratio[1]
|
| 36 |
+
ratio_diff = abs(aspect_ratio - target_aspect_ratio)
|
| 37 |
+
if ratio_diff < best_ratio_diff:
|
| 38 |
+
best_ratio_diff = ratio_diff
|
| 39 |
+
best_ratio = ratio
|
| 40 |
+
elif ratio_diff == best_ratio_diff:
|
| 41 |
+
# ์ด๋ฏธ์ง ๋ฉด์ ๊ธฐ์ค์ผ๋ก ์ข ๋ ํฐ ์ชฝ ์ ํ
|
| 42 |
+
if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
|
| 43 |
+
best_ratio = ratio
|
| 44 |
+
return best_ratio
|
| 45 |
+
|
| 46 |
+
def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
|
| 47 |
+
orig_width, orig_height = image.size
|
| 48 |
+
aspect_ratio = orig_width / orig_height
|
| 49 |
+
|
| 50 |
+
target_ratios = set(
|
| 51 |
+
(i, j) for n in range(min_num, max_num + 1)
|
| 52 |
+
for i in range(1, n + 1)
|
| 53 |
+
for j in range(1, n + 1)
|
| 54 |
+
if i * j <= max_num and i * j >= min_num
|
| 55 |
+
)
|
| 56 |
+
target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
|
| 57 |
+
target_aspect_ratio = find_closest_aspect_ratio(
|
| 58 |
+
aspect_ratio, target_ratios, orig_width, orig_height, image_size
|
| 59 |
+
)
|
| 60 |
+
target_width = image_size * target_aspect_ratio[0]
|
| 61 |
+
target_height = image_size * target_aspect_ratio[1]
|
| 62 |
+
blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
|
| 63 |
+
|
| 64 |
+
resized_img = image.resize((target_width, target_height))
|
| 65 |
+
processed_images = []
|
| 66 |
+
for i in range(blocks):
|
| 67 |
+
box = (
|
| 68 |
+
(i % (target_width // image_size)) * image_size,
|
| 69 |
+
(i // (target_width // image_size)) * image_size,
|
| 70 |
+
((i % (target_width // image_size)) + 1) * image_size,
|
| 71 |
+
((i // (target_width // image_size)) + 1) * image_size
|
| 72 |
+
)
|
| 73 |
+
split_img = resized_img.crop(box)
|
| 74 |
+
processed_images.append(split_img)
|
| 75 |
+
|
| 76 |
+
if use_thumbnail and len(processed_images) != 1:
|
| 77 |
+
thumbnail_img = image.resize((image_size, image_size))
|
| 78 |
+
processed_images.append(thumbnail_img)
|
| 79 |
+
return processed_images
|
| 80 |
+
|
| 81 |
+
def load_image(image_file, input_size=448, max_num=12):
|
| 82 |
+
image = Image.open(image_file).convert('RGB')
|
| 83 |
+
transform = build_transform(input_size=input_size)
|
| 84 |
+
images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
|
| 85 |
+
pixel_values = [transform(img) for img in images]
|
| 86 |
+
pixel_values = torch.stack(pixel_values)
|
| 87 |
+
return pixel_values
|
| 88 |
+
|
| 89 |
+
def get_index(bound, fps, max_frame, first_idx=0, num_segments=32):
|
| 90 |
+
if bound:
|
| 91 |
+
start, end = bound[0], bound[1]
|
| 92 |
+
else:
|
| 93 |
+
start, end = -100000, 100000
|
| 94 |
+
start_idx = max(first_idx, round(start * fps))
|
| 95 |
+
end_idx = min(round(end * fps), max_frame)
|
| 96 |
+
seg_size = float(end_idx - start_idx) / num_segments
|
| 97 |
+
frame_indices = np.array([
|
| 98 |
+
int(start_idx + (seg_size / 2) + np.round(seg_size * idx))
|
| 99 |
+
for idx in range(num_segments)
|
| 100 |
+
])
|
| 101 |
+
return frame_indices
|
| 102 |
+
|
| 103 |
+
def load_video(video_path, bound=None, input_size=448, max_num=1, num_segments=8):
|
| 104 |
+
"""
|
| 105 |
+
InternVL ์์ ์ฝ๋ ์ฐธ๊ณ : ์ฌ๋ฌ ํ๋ ์์ ์ถ์ถํ์ฌ dynamic_preprocess ์ ์ฉ.
|
| 106 |
+
์ฌ๊ธฐ์๋ ๊ธฐ๋ณธ์ ์ผ๋ก num_segments=8๋ก ์ค์ .
|
| 107 |
+
"""
|
| 108 |
+
vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)
|
| 109 |
+
max_frame = len(vr) - 1
|
| 110 |
+
fps = float(vr.get_avg_fps())
|
| 111 |
+
|
| 112 |
+
pixel_values_list, num_patches_list = [], []
|
| 113 |
+
transform = build_transform(input_size=input_size)
|
| 114 |
+
frame_indices = get_index(bound, fps, max_frame, first_idx=0, num_segments=num_segments)
|
| 115 |
+
|
| 116 |
+
for frame_index in frame_indices:
|
| 117 |
+
frame = vr[frame_index]
|
| 118 |
+
img = Image.fromarray(frame.asnumpy()).convert('RGB')
|
| 119 |
+
processed_imgs = dynamic_preprocess(img, image_size=input_size, use_thumbnail=True, max_num=max_num)
|
| 120 |
+
tile_values = [transform(tile) for tile in processed_imgs]
|
| 121 |
+
tile_values = torch.stack(tile_values)
|
| 122 |
+
num_patches_list.append(tile_values.shape[0])
|
| 123 |
+
pixel_values_list.append(tile_values)
|
| 124 |
+
|
| 125 |
+
# ์ฌ๋ฌ ํ๋ ์์ ์ด์ด ๋ถ์ฌ ์ต์ข
pixel_values ์์ฑ
|
| 126 |
+
pixel_values = torch.cat(pixel_values_list, dim=0) # (sum(num_patches_list), 3, H, W)
|
| 127 |
+
return pixel_values, num_patches_list
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
# =============================================================================
|
| 131 |
+
# InternVL ๋ชจ๋ธ ๋ก๋ฉ
|
| 132 |
+
# =============================================================================
|
| 133 |
+
MODEL_ID = "OpenGVLab/InternVL2_5-8B"
|
| 134 |
+
|
| 135 |
+
model = AutoModel.from_pretrained(
|
| 136 |
+
MODEL_ID,
|
| 137 |
+
torch_dtype=torch.bfloat16,
|
| 138 |
+
low_cpu_mem_usage=True,
|
| 139 |
+
use_flash_attn=True,
|
| 140 |
+
trust_remote_code=True
|
| 141 |
+
).eval().cuda()
|
| 142 |
+
|
| 143 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 144 |
+
MODEL_ID,
|
| 145 |
+
trust_remote_code=True,
|
| 146 |
+
use_fast=False
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
# Gradio ์๋จ์ ํ์ํ ์ค๋ช
๋ฌธ๊ตฌ
|
| 150 |
+
DESCRIPTION = "[InternVL2_5-8B Demo](https://github.com/OpenGVLab/InternVL) - Using the InternVL2_5-8B"
|
| 151 |
+
|
| 152 |
+
image_extensions = Image.registered_extensions()
|
| 153 |
+
video_extensions = ("avi", "mp4", "mov", "mkv", "flv", "wmv", "mjpeg", "wav", "gif", "webm", "m4v", "3gp")
|
| 154 |
+
|
| 155 |
+
def identify_and_save_blob(blob_path):
|
| 156 |
+
"""
|
| 157 |
+
Qwen ์์ ์ฝ๋์ ๋์ผ: blob์ ์ด์ด๋ณด๊ณ ์ด๋ฏธ์ง์ธ์ง ์์์ธ์ง ํ์ธ ํ,
|
| 158 |
+
์์ ํ์ผ๋ก ์ ์ฅํ์ฌ ๊ฒฝ๋ก ๋ฆฌํด
|
| 159 |
+
"""
|
| 160 |
+
try:
|
| 161 |
+
with open(blob_path, 'rb') as file:
|
| 162 |
+
blob_content = file.read()
|
| 163 |
+
# Try to identify if it's an image
|
| 164 |
+
try:
|
| 165 |
+
Image.open(io.BytesIO(blob_content)).verify() # Check if it's a valid image
|
| 166 |
+
extension = ".png" # Default to PNG for saving
|
| 167 |
+
media_type = "image"
|
| 168 |
+
except (IOError, SyntaxError):
|
| 169 |
+
# If it's not a valid image, assume it's a video
|
| 170 |
+
extension = ".mp4" # Default to MP4 for saving
|
| 171 |
+
media_type = "video"
|
| 172 |
+
|
| 173 |
+
# Create a unique filename
|
| 174 |
+
filename = f"temp_{uuid.uuid4()}_media{extension}"
|
| 175 |
+
with open(filename, "wb") as f:
|
| 176 |
+
f.write(blob_content)
|
| 177 |
+
return filename, media_type
|
| 178 |
+
except FileNotFoundError:
|
| 179 |
+
raise ValueError(f"The file {blob_path} was not found.")
|
| 180 |
+
except Exception as e:
|
| 181 |
+
raise ValueError(f"An error occurred while processing the file: {e}")
|
| 182 |
+
|
| 183 |
+
def process_file_upload(file_path):
|
| 184 |
+
"""
|
| 185 |
+
ํ์ผ ์
๋ก๋ ์ ์ด๋ฏธ์ง/์์ ๋ฏธ๋ฆฌ๋ณด๊ธฐ ํน์ ๊ทธ๋๋ก ํจ์ค.
|
| 186 |
+
"""
|
| 187 |
+
if isinstance(file_path, str):
|
| 188 |
+
if file_path.endswith(tuple([i for i, f in image_extensions.items()])):
|
| 189 |
+
# ์ด๋ฏธ์ง๋ฅผ ์ด์ด์ preview๋ก ๋๊น
|
| 190 |
+
return file_path, Image.open(file_path)
|
| 191 |
+
elif file_path.endswith(video_extensions):
|
| 192 |
+
# ์์์ preview๋ฅผ None์ผ๋ก
|
| 193 |
+
return file_path, None
|
| 194 |
+
else:
|
| 195 |
+
# blob ํ์ผ์ธ ๊ฒฝ์ฐ ์ฒ๋ฆฌ
|
| 196 |
+
try:
|
| 197 |
+
media_path, media_type = identify_and_save_blob(file_path)
|
| 198 |
+
if media_type == "image":
|
| 199 |
+
return media_path, Image.open(media_path)
|
| 200 |
+
return media_path, None
|
| 201 |
+
except Exception as e:
|
| 202 |
+
print(e)
|
| 203 |
+
raise ValueError("Unsupported media type. Please upload an image or video.")
|
| 204 |
+
return None, None
|
| 205 |
+
|
| 206 |
+
@spaces.GPU
|
| 207 |
+
def internvl_inference(media_input, text_input=None):
|
| 208 |
+
"""
|
| 209 |
+
Qwen ์์ ์ qwen_inference ๋์ InternVL์ ์ด์ฉํ ์ถ๋ก ํจ์.
|
| 210 |
+
- ์ด๋ฏธ์ง/์์ ํ์ผ์ InternVL์์ ์๊ตฌํ๋ pixel_values๋ก ๋ณํ ํ
|
| 211 |
+
model.chat() ํธ์ถํ์ฌ ๋ต๋ณ ์์ฑ.
|
| 212 |
+
"""
|
| 213 |
+
if isinstance(media_input, str): # If it's a filepath
|
| 214 |
+
media_path = media_input
|
| 215 |
+
|
| 216 |
+
# ๋ฏธ๋์ด ์ข
๋ฅ ์๋ณ
|
| 217 |
+
if media_path.endswith(tuple([i for i, f in image_extensions.items()])):
|
| 218 |
+
media_type = "image"
|
| 219 |
+
elif media_path.endswith(video_extensions):
|
| 220 |
+
media_type = "video"
|
| 221 |
+
else:
|
| 222 |
+
# blob์ธ์ง ์ฒดํฌ
|
| 223 |
+
try:
|
| 224 |
+
media_path, media_type = identify_and_save_blob(media_input)
|
| 225 |
+
except Exception as e:
|
| 226 |
+
print(e)
|
| 227 |
+
raise ValueError("Unsupported media type. Please upload an image or video.")
|
| 228 |
+
else:
|
| 229 |
+
return "No media input found"
|
| 230 |
+
|
| 231 |
+
# ์ด๋ฏธ์ง vs ์์ ์ฒ๋ฆฌ
|
| 232 |
+
if media_type == "image":
|
| 233 |
+
# ๋จ์ผ ์ด๋ฏธ์ง๋ง ์ฒ๋ฆฌํ๋ค๊ณ ๊ฐ์ (๋ฉํฐ-์ด๋ฏธ์ง๋ ํ์ฅ ๊ฐ๋ฅ)
|
| 234 |
+
pixel_values = load_image(media_path, max_num=12)
|
| 235 |
+
pixel_values = pixel_values.to(torch.bfloat16).cuda() # (N, 3, H, W)
|
| 236 |
+
# InternVL ๋ํ
|
| 237 |
+
question = f"<image>\n{text_input}" if text_input else "<image>\n"
|
| 238 |
+
generation_config = dict(max_new_tokens=1024, do_sample=True)
|
| 239 |
+
|
| 240 |
+
response = model.chat(
|
| 241 |
+
tokenizer,
|
| 242 |
+
pixel_values,
|
| 243 |
+
question,
|
| 244 |
+
generation_config
|
| 245 |
+
)
|
| 246 |
+
return response
|
| 247 |
+
|
| 248 |
+
elif media_type == "video":
|
| 249 |
+
# ์์: ์์๋ก ์ฒซ 8ํ๋ ์์ ๋ํด ์ฒ๋ฆฌ
|
| 250 |
+
pixel_values, num_patches_list = load_video(
|
| 251 |
+
media_path,
|
| 252 |
+
num_segments=8,
|
| 253 |
+
max_num=1
|
| 254 |
+
)
|
| 255 |
+
pixel_values = pixel_values.to(torch.bfloat16).cuda()
|
| 256 |
+
question_prefix = "".join([f"Frame{i+1}: <image>\n" for i in range(len(num_patches_list))])
|
| 257 |
+
question = question_prefix + (text_input if text_input else "")
|
| 258 |
+
generation_config = dict(max_new_tokens=1024, do_sample=True)
|
| 259 |
+
|
| 260 |
+
# ์์์์๋ ๋์ผํ chat() ํจ์ ์ฌ์ฉ
|
| 261 |
+
response = model.chat(
|
| 262 |
+
tokenizer,
|
| 263 |
+
pixel_values,
|
| 264 |
+
question,
|
| 265 |
+
generation_config,
|
| 266 |
+
num_patches_list=num_patches_list
|
| 267 |
+
)
|
| 268 |
+
return response
|
| 269 |
+
|
| 270 |
+
return "Unsupported media type"
|
| 271 |
+
|
| 272 |
+
# ๊ฐ๋จํ CSS
|
| 273 |
+
css = """
|
| 274 |
+
#output {
|
| 275 |
+
height: 500px;
|
| 276 |
+
overflow: auto;
|
| 277 |
+
border: 1px solid #ccc;
|
| 278 |
+
}
|
| 279 |
+
"""
|
| 280 |
+
|
| 281 |
+
# Gradio ๋ฐ๋ชจ ๊ตฌ์ฑ
|
| 282 |
+
with gr.Blocks(css=css) as demo:
|
| 283 |
+
gr.Markdown(DESCRIPTION)
|
| 284 |
+
|
| 285 |
+
with gr.Tab(label="Image/Video Input"):
|
| 286 |
+
with gr.Row():
|
| 287 |
+
with gr.Column():
|
| 288 |
+
input_media = gr.File(
|
| 289 |
+
label="Upload Image or Video", type="filepath"
|
| 290 |
+
)
|
| 291 |
+
preview_image = gr.Image(label="Preview", visible=True)
|
| 292 |
+
text_input = gr.Textbox(label="Question")
|
| 293 |
+
submit_btn = gr.Button(value="Submit")
|
| 294 |
+
with gr.Column():
|
| 295 |
+
output_text = gr.Textbox(label="Output Text")
|
| 296 |
+
|
| 297 |
+
input_media.change(
|
| 298 |
+
fn=process_file_upload,
|
| 299 |
+
inputs=[input_media],
|
| 300 |
+
outputs=[input_media, preview_image]
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
submit_btn.click(
|
| 304 |
+
internvl_inference,
|
| 305 |
+
[input_media, text_input],
|
| 306 |
+
[output_text]
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
demo.launch(debug=True)
|