File size: 11,603 Bytes
7bf3214
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa48fd5
7bf3214
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
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

@spaces.GPU
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)