Spaces:
Runtime error
Runtime error
import gradio as gr | |
import spaces | |
import torch | |
import os | |
import uuid | |
import io | |
import numpy as np | |
from PIL import Image | |
import torchvision.transforms as T | |
from torchvision.transforms.functional import InterpolationMode | |
from transformers import AutoModel, AutoTokenizer | |
from decord import VideoReader, cpu | |
# ============================================================================= | |
# InternVL ์ ์ฒ๋ฆฌ/๋ก๋ฉ ์ฝ๋ (์๋ณธ ์์์์ ๋ฐ์ท) | |
# ============================================================================= | |
IMAGENET_MEAN = (0.485, 0.456, 0.406) | |
IMAGENET_STD = (0.229, 0.224, 0.225) | |
def build_transform(input_size): | |
MEAN, STD = IMAGENET_MEAN, IMAGENET_STD | |
transform = T.Compose([ | |
T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img), | |
T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC), | |
T.ToTensor(), | |
T.Normalize(mean=MEAN, std=STD) | |
]) | |
return transform | |
def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size): | |
best_ratio_diff = float('inf') | |
best_ratio = (1, 1) | |
area = width * height | |
for ratio in target_ratios: | |
target_aspect_ratio = ratio[0] / ratio[1] | |
ratio_diff = abs(aspect_ratio - target_aspect_ratio) | |
if ratio_diff < best_ratio_diff: | |
best_ratio_diff = ratio_diff | |
best_ratio = ratio | |
elif ratio_diff == best_ratio_diff: | |
# ์ด๋ฏธ์ง ๋ฉด์ ๊ธฐ์ค์ผ๋ก ์ข ๋ ํฐ ์ชฝ ์ ํ | |
if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]: | |
best_ratio = ratio | |
return best_ratio | |
def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False): | |
orig_width, orig_height = image.size | |
aspect_ratio = orig_width / orig_height | |
target_ratios = set( | |
(i, j) for n in range(min_num, max_num + 1) | |
for i in range(1, n + 1) | |
for j in range(1, n + 1) | |
if i * j <= max_num and i * j >= min_num | |
) | |
target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1]) | |
target_aspect_ratio = find_closest_aspect_ratio( | |
aspect_ratio, target_ratios, orig_width, orig_height, image_size | |
) | |
target_width = image_size * target_aspect_ratio[0] | |
target_height = image_size * target_aspect_ratio[1] | |
blocks = target_aspect_ratio[0] * target_aspect_ratio[1] | |
resized_img = image.resize((target_width, target_height)) | |
processed_images = [] | |
for i in range(blocks): | |
box = ( | |
(i % (target_width // image_size)) * image_size, | |
(i // (target_width // image_size)) * image_size, | |
((i % (target_width // image_size)) + 1) * image_size, | |
((i // (target_width // image_size)) + 1) * image_size | |
) | |
split_img = resized_img.crop(box) | |
processed_images.append(split_img) | |
if use_thumbnail and len(processed_images) != 1: | |
thumbnail_img = image.resize((image_size, image_size)) | |
processed_images.append(thumbnail_img) | |
return processed_images | |
def load_image(image_file, input_size=448, max_num=12): | |
image = Image.open(image_file).convert('RGB') | |
transform = build_transform(input_size=input_size) | |
images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num) | |
pixel_values = [transform(img) for img in images] | |
pixel_values = torch.stack(pixel_values) | |
return pixel_values | |
def get_index(bound, fps, max_frame, first_idx=0, num_segments=32): | |
if bound: | |
start, end = bound[0], bound[1] | |
else: | |
start, end = -100000, 100000 | |
start_idx = max(first_idx, round(start * fps)) | |
end_idx = min(round(end * fps), max_frame) | |
seg_size = float(end_idx - start_idx) / num_segments | |
frame_indices = np.array([ | |
int(start_idx + (seg_size / 2) + np.round(seg_size * idx)) | |
for idx in range(num_segments) | |
]) | |
return frame_indices | |
def load_video(video_path, bound=None, input_size=448, max_num=1, num_segments=8): | |
""" | |
InternVL ์์ ์ฝ๋ ์ฐธ๊ณ : ์ฌ๋ฌ ํ๋ ์์ ์ถ์ถํ์ฌ dynamic_preprocess ์ ์ฉ. | |
์ฌ๊ธฐ์๋ ๊ธฐ๋ณธ์ ์ผ๋ก num_segments=8๋ก ์ค์ . | |
""" | |
vr = VideoReader(video_path, ctx=cpu(0), num_threads=1) | |
max_frame = len(vr) - 1 | |
fps = float(vr.get_avg_fps()) | |
pixel_values_list, num_patches_list = [], [] | |
transform = build_transform(input_size=input_size) | |
frame_indices = get_index(bound, fps, max_frame, first_idx=0, num_segments=num_segments) | |
for frame_index in frame_indices: | |
frame = vr[frame_index] | |
img = Image.fromarray(frame.asnumpy()).convert('RGB') | |
processed_imgs = dynamic_preprocess(img, image_size=input_size, use_thumbnail=True, max_num=max_num) | |
tile_values = [transform(tile) for tile in processed_imgs] | |
tile_values = torch.stack(tile_values) | |
num_patches_list.append(tile_values.shape[0]) | |
pixel_values_list.append(tile_values) | |
# ์ฌ๋ฌ ํ๋ ์์ ์ด์ด ๋ถ์ฌ ์ต์ข pixel_values ์์ฑ | |
pixel_values = torch.cat(pixel_values_list, dim=0) # (sum(num_patches_list), 3, H, W) | |
return pixel_values, num_patches_list | |
# ============================================================================= | |
# InternVL ๋ชจ๋ธ ๋ก๋ฉ | |
# ============================================================================= | |
MODEL_ID = "OpenGVLab/InternVL2_5-2B" | |
model = AutoModel.from_pretrained( | |
MODEL_ID, | |
torch_dtype=torch.bfloat16, | |
low_cpu_mem_usage=True, | |
use_flash_attn=True, | |
trust_remote_code=True | |
).eval().cuda() | |
tokenizer = AutoTokenizer.from_pretrained( | |
MODEL_ID, | |
trust_remote_code=True, | |
use_fast=False | |
) | |
# Gradio ์๋จ์ ํ์ํ ์ค๋ช ๋ฌธ๊ตฌ | |
DESCRIPTION = "[InternVL2_5-2B Demo](https://github.com/OpenGVLab/InternVL) - Using the InternVL2_5-2B" | |
image_extensions = Image.registered_extensions() | |
video_extensions = ("avi", "mp4", "mov", "mkv", "flv", "wmv", "mjpeg", "wav", "gif", "webm", "m4v", "3gp") | |
def identify_and_save_blob(blob_path): | |
""" | |
Qwen ์์ ์ฝ๋์ ๋์ผ: blob์ ์ด์ด๋ณด๊ณ ์ด๋ฏธ์ง์ธ์ง ์์์ธ์ง ํ์ธ ํ, | |
์์ ํ์ผ๋ก ์ ์ฅํ์ฌ ๊ฒฝ๋ก ๋ฆฌํด | |
""" | |
try: | |
with open(blob_path, 'rb') as file: | |
blob_content = file.read() | |
# Try to identify if it's an image | |
try: | |
Image.open(io.BytesIO(blob_content)).verify() # Check if it's a valid image | |
extension = ".png" # Default to PNG for saving | |
media_type = "image" | |
except (IOError, SyntaxError): | |
# If it's not a valid image, assume it's a video | |
extension = ".mp4" # Default to MP4 for saving | |
media_type = "video" | |
# Create a unique filename | |
filename = f"temp_{uuid.uuid4()}_media{extension}" | |
with open(filename, "wb") as f: | |
f.write(blob_content) | |
return filename, media_type | |
except FileNotFoundError: | |
raise ValueError(f"The file {blob_path} was not found.") | |
except Exception as e: | |
raise ValueError(f"An error occurred while processing the file: {e}") | |
def process_file_upload(file_path): | |
""" | |
ํ์ผ ์ ๋ก๋ ์ ์ด๋ฏธ์ง/์์ ๋ฏธ๋ฆฌ๋ณด๊ธฐ ํน์ ๊ทธ๋๋ก ํจ์ค. | |
""" | |
if isinstance(file_path, str): | |
if file_path.endswith(tuple([i for i, f in image_extensions.items()])): | |
# ์ด๋ฏธ์ง๋ฅผ ์ด์ด์ preview๋ก ๋๊น | |
return file_path, Image.open(file_path) | |
elif file_path.endswith(video_extensions): | |
# ์์์ preview๋ฅผ None์ผ๋ก | |
return file_path, None | |
else: | |
# blob ํ์ผ์ธ ๊ฒฝ์ฐ ์ฒ๋ฆฌ | |
try: | |
media_path, media_type = identify_and_save_blob(file_path) | |
if media_type == "image": | |
return media_path, Image.open(media_path) | |
return media_path, None | |
except Exception as e: | |
print(e) | |
raise ValueError("Unsupported media type. Please upload an image or video.") | |
return None, None | |
def internvl_inference(media_input, text_input=None): | |
""" | |
Qwen ์์ ์ qwen_inference ๋์ InternVL์ ์ด์ฉํ ์ถ๋ก ํจ์. | |
- ์ด๋ฏธ์ง/์์ ํ์ผ์ InternVL์์ ์๊ตฌํ๋ pixel_values๋ก ๋ณํ ํ | |
model.chat() ํธ์ถํ์ฌ ๋ต๋ณ ์์ฑ. | |
""" | |
if isinstance(media_input, str): # If it's a filepath | |
media_path = media_input | |
# ๋ฏธ๋์ด ์ข ๋ฅ ์๋ณ | |
if media_path.endswith(tuple([i for i, f in image_extensions.items()])): | |
media_type = "image" | |
elif media_path.endswith(video_extensions): | |
media_type = "video" | |
else: | |
# blob์ธ์ง ์ฒดํฌ | |
try: | |
media_path, media_type = identify_and_save_blob(media_input) | |
except Exception as e: | |
print(e) | |
raise ValueError("Unsupported media type. Please upload an image or video.") | |
else: | |
return "No media input found" | |
# ์ด๋ฏธ์ง vs ์์ ์ฒ๋ฆฌ | |
if media_type == "image": | |
# ๋จ์ผ ์ด๋ฏธ์ง๋ง ์ฒ๋ฆฌํ๋ค๊ณ ๊ฐ์ (๋ฉํฐ-์ด๋ฏธ์ง๋ ํ์ฅ ๊ฐ๋ฅ) | |
pixel_values = load_image(media_path, max_num=12) | |
pixel_values = pixel_values.to(torch.bfloat16).cuda() # (N, 3, H, W) | |
# InternVL ๋ํ | |
question = f"<image>\n{text_input}" if text_input else "<image>\n" | |
generation_config = dict(max_new_tokens=1024, do_sample=True) | |
response = model.chat( | |
tokenizer, | |
pixel_values, | |
question, | |
generation_config | |
) | |
return response | |
elif media_type == "video": | |
# ์์: ์์๋ก ์ฒซ 8ํ๋ ์์ ๋ํด ์ฒ๋ฆฌ | |
pixel_values, num_patches_list = load_video( | |
media_path, | |
num_segments=8, | |
max_num=1 | |
) | |
pixel_values = pixel_values.to(torch.bfloat16).cuda() | |
question_prefix = "".join([f"Frame{i+1}: <image>\n" for i in range(len(num_patches_list))]) | |
question = question_prefix + (text_input if text_input else "") | |
generation_config = dict(max_new_tokens=1024, do_sample=True) | |
# ์์์์๋ ๋์ผํ chat() ํจ์ ์ฌ์ฉ | |
response = model.chat( | |
tokenizer, | |
pixel_values, | |
question, | |
generation_config, | |
num_patches_list=num_patches_list | |
) | |
return response | |
return "Unsupported media type" | |
# ๊ฐ๋จํ CSS | |
css = """ | |
#output { | |
height: 500px; | |
overflow: auto; | |
border: 1px solid #ccc; | |
} | |
""" | |
# Gradio ๋ฐ๋ชจ ๊ตฌ์ฑ | |
with gr.Blocks(css=css) as demo: | |
gr.Markdown(DESCRIPTION) | |
with gr.Tab(label="Image/Video Input"): | |
with gr.Row(): | |
with gr.Column(): | |
input_media = gr.File( | |
label="Upload Image or Video", type="filepath" | |
) | |
preview_image = gr.Image(label="Preview", visible=True) | |
text_input = gr.Textbox(label="Question") | |
submit_btn = gr.Button(value="Submit") | |
with gr.Column(): | |
output_text = gr.Textbox(label="Output Text") | |
input_media.change( | |
fn=process_file_upload, | |
inputs=[input_media], | |
outputs=[input_media, preview_image] | |
) | |
submit_btn.click( | |
internvl_inference, | |
[input_media, text_input], | |
[output_text] | |
) | |
demo.launch(debug=True) | |