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
 
41e0760
 
 
 
 
 
 
 
 
 
 
 
30a0d3e
 
 
 
 
 
b785f7c
 
30a0d3e
 
 
 
 
 
 
 
 
 
b785f7c
 
 
30a0d3e
 
 
3b85b9a
40ccb44
41e0760
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
#!/usr/bin/env python

import os
import string
import gradio as gr
import PIL.Image
import spaces
import torch
from transformers import AutoProcessor, BitsAndBytesConfig, Blip2ForConditionalGeneration

# μŠ€νƒ€μΌ μƒμˆ˜ μ •μ˜
CUSTOM_CSS = """
.container {
    max-width: 1000px;
    margin: auto;
    padding: 2rem;
    background: linear-gradient(to bottom right, #ffffff, #f8f9fa);
    border-radius: 15px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.title {
    font-size: 2.5rem;
    color: #1a73e8;
    text-align: center;
    margin-bottom: 2rem;
    font-weight: bold;
}

.tab-nav {
    background: #f8f9fa;
    border-radius: 10px;
    padding: 0.5rem;
    margin-bottom: 1rem;
}

.input-box {
    border: 2px solid #e0e0e0;
    border-radius: 8px;
    transition: all 0.3s ease;
}

.input-box:focus {
    border-color: #1a73e8;
    box-shadow: 0 0 0 2px rgba(26, 115, 232, 0.2);
}

.button-primary {
    background: #1a73e8;
    color: white;
    padding: 0.75rem 1.5rem;
    border-radius: 8px;
    border: none;
    cursor: pointer;
    transition: all 0.3s ease;
}

.button-primary:hover {
    background: #1557b0;
    transform: translateY(-1px);
}

.button-secondary {
    background: #f8f9fa;
    color: #1a73e8;
    border: 1px solid #1a73e8;
    padding: 0.75rem 1.5rem;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.button-secondary:hover {
    background: #e8f0fe;
}

.output-box {
    background: #ffffff;
    border-radius: 8px;
    padding: 1rem;
    margin-top: 1rem;
    border: 1px solid #e0e0e0;
}

.chatbot-message {
    padding: 1rem;
    margin: 0.5rem 0;
    border-radius: 8px;
    background: #f8f9fa;
}

.advanced-settings {
    background: #ffffff;
    border-radius: 8px;
    padding: 1rem;
    margin-top: 1rem;
}

.slider-container {
    padding: 0.5rem;
    background: #f8f9fa;
    border-radius: 6px;
}

.examples-container {
    margin-top: 2rem;
    padding: 1rem;
    background: #ffffff;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}
"""

DESCRIPTION = """
<div class="title">
    πŸ–ΌοΈ BLIP-2 Visual Intelligence System
</div>
<p style='text-align: center; color: #666;'>
    Advanced AI system for image understanding and natural conversation
</p>
"""

if not torch.cuda.is_available():
    DESCRIPTION += "\n<p style='color: #dc3545;'>Running on CPU πŸ₯Ά This demo requires GPU to function properly.</p>"

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

MODEL_ID_OPT_2_7B = "Salesforce/blip2-opt-2.7b"
MODEL_ID_OPT_6_7B = "Salesforce/blip2-opt-6.7b"
MODEL_ID_FLAN_T5_XL = "Salesforce/blip2-flan-t5-xl"
MODEL_ID_FLAN_T5_XXL = "Salesforce/blip2-flan-t5-xxl"
MODEL_ID = os.getenv("MODEL_ID", MODEL_ID_FLAN_T5_XXL)

if MODEL_ID not in [MODEL_ID_OPT_2_7B, MODEL_ID_OPT_6_7B, MODEL_ID_FLAN_T5_XL, MODEL_ID_FLAN_T5_XXL]:
    error_message = f"Invalid MODEL_ID: {MODEL_ID}"
    raise ValueError(error_message)

if torch.cuda.is_available():
    processor = AutoProcessor.from_pretrained(MODEL_ID)
    model = Blip2ForConditionalGeneration.from_pretrained(
        MODEL_ID,
        device_map="auto",
        quantization_config=BitsAndBytesConfig(load_in_8bit=True)
    )

@spaces.GPU
def generate_caption(
    image: PIL.Image.Image,
    decoding_method: str = "Nucleus sampling",
    temperature: float = 1.0,
    length_penalty: float = 1.0,
    repetition_penalty: float = 1.5,
    max_length: int = 50,
    min_length: int = 1,
    num_beams: int = 5,
    top_p: float = 0.9,
) -> str:
    inputs = processor(images=image, return_tensors="pt").to(device, torch.float16)
    generated_ids = model.generate(
        pixel_values=inputs.pixel_values,
        do_sample=decoding_method == "Nucleus sampling",
        temperature=temperature,
        length_penalty=length_penalty,
        repetition_penalty=repetition_penalty,
        max_length=max_length,
        min_length=min_length,
        num_beams=num_beams,
        top_p=top_p,
    )
    return processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()

@spaces.GPU
def answer_question(
    image: PIL.Image.Image,
    prompt: str,
    decoding_method: str = "Nucleus sampling",
    temperature: float = 1.0,
    length_penalty: float = 1.0,
    repetition_penalty: float = 1.5,
    max_length: int = 50,
    min_length: int = 1,
    num_beams: int = 5,
    top_p: float = 0.9,
) -> str:
    inputs = processor(images=image, text=prompt, return_tensors="pt").to(device, torch.float16)
    generated_ids = model.generate(
        **inputs,
        do_sample=decoding_method == "Nucleus sampling",
        temperature=temperature,
        length_penalty=length_penalty,
        repetition_penalty=repetition_penalty,
        max_length=max_length,
        min_length=min_length,
        num_beams=num_beams,
        top_p=top_p,
    )
    return processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()

def postprocess_output(output: str) -> str:
    if output and output[-1] not in string.punctuation:
        output += "."
    return output

def chat(
    image: PIL.Image.Image,
    text: str,
    decoding_method: str = "Nucleus sampling",
    temperature: float = 1.0,
    length_penalty: float = 1.0,
    repetition_penalty: float = 1.5,
    max_length: int = 50,
    min_length: int = 1,
    num_beams: int = 5,
    top_p: float = 0.9,
    history_orig: list[str] | None = None,
    history_qa: list[str] | None = None,
) -> tuple[list[tuple[str, str]], list[str], list[str]]:
    history_orig = history_orig or []
    history_qa = history_qa or []
    history_orig.append(text)
    text_qa = f"Question: {text} Answer:"
    history_qa.append(text_qa)
    prompt = " ".join(history_qa)

    output = answer_question(
        image=image,
        prompt=prompt,
        decoding_method=decoding_method,
        temperature=temperature,
        length_penalty=length_penalty,
        repetition_penalty=repetition_penalty,
        max_length=max_length,
        min_length=min_length,
        num_beams=num_beams,
        top_p=top_p,
    )
    output = postprocess_output(output)
    history_orig.append(output)
    history_qa.append(output)

    chat_val = list(zip(history_orig[0::2], history_orig[1::2], strict=False))
    return chat_val, history_orig, history_qa

chat.zerogpu = True  # type: ignore

examples = [
    [
        "images/house.png",
        "How could someone get out of the house?",
    ],
    [
        "images/flower.jpg",
        "What is this flower and where is it's origin?",
    ],
    [
        "images/pizza.jpg",
        "What are steps to cook it?",
    ],
    [
        "images/sunset.jpg",
        "Here is a romantic message going along the photo:",
    ],
    [
        "images/forbidden_city.webp",
        "In what dynasties was this place built?",
    ],
]

with gr.Blocks(css=CUSTOM_CSS) as demo:
    gr.Markdown(DESCRIPTION)
    
    with gr.Group(elem_classes="container"):
        with gr.Row():
            with gr.Column(scale=1):
                image = gr.Image(
                    type="pil",
                    label="Upload Image",
                    elem_classes="input-box"
                )
            
            with gr.Column(scale=2):
                with gr.Tabs(elem_classes="tab-nav"):
                    with gr.Tab(label="✨ Image Captioning"):
                        caption_button = gr.Button(
                            "Generate Caption",
                            elem_classes="button-primary"
                        )
                        caption_output = gr.Textbox(
                            label="Generated Caption",
                            elem_classes="output-box"
                        )
                        
                    with gr.Tab(label="πŸ’­ Visual Q&A"):
                        chatbot = gr.Chatbot(
                            elem_classes="chatbot-message"
                        )
                        history_orig = gr.State(value=[])
                        history_qa = gr.State(value=[])
                        vqa_input = gr.Textbox(
                            placeholder="Ask me anything about the image...",
                            elem_classes="input-box"
                        )
                        
                        with gr.Row():
                            clear_button = gr.Button(
                                "Clear Chat",
                                elem_classes="button-secondary"
                            )
                            submit_button = gr.Button(
                                "Send Message",
                                elem_classes="button-primary"
                            )

        with gr.Accordion("πŸ› οΈ Advanced Settings", open=False, elem_classes="advanced-settings"):
            with gr.Row():
                with gr.Column():
                    text_decoding_method = gr.Radio(
                        choices=["Beam search", "Nucleus sampling"],
                        value="Nucleus sampling",
                        label="Decoding Method"
                    )
                    temperature = gr.Slider(
                        minimum=0.5,
                        maximum=1.0,
                        value=1.0,
                        label="Temperature",
                        info="Used with nucleus sampling",
                        elem_classes="slider-container"
                    )
                    length_penalty = gr.Slider(
                        minimum=-1.0,
                        maximum=2.0,
                        value=1.0,
                        label="Length Penalty",
                        info="Set to larger for longer sequence",
                        elem_classes="slider-container"
                    )
                with gr.Column():
                    repetition_penalty = gr.Slider(
                        minimum=1.0,
                        maximum=5.0,
                        value=1.5,
                        label="Repetition Penalty",
                        info="Larger value prevents repetition",
                        elem_classes="slider-container"
                    )
                    max_length = gr.Slider(
                        minimum=20,
                        maximum=512,
                        value=50,
                        label="Max Length",
                        elem_classes="slider-container"
                    )
                    min_length = gr.Slider(
                        minimum=1,
                        maximum=100,
                        value=1,
                        label="Min Length",
                        elem_classes="slider-container"
                    )
                    num_beams = gr.Slider(
                        minimum=1,
                        maximum=10,
                        value=5,
                        label="Number of Beams",
                        elem_classes="slider-container"
                    )
                    top_p = gr.Slider(
                        minimum=0.5,
                        maximum=1.0,
                        value=0.9,
                        label="Top P",
                        info="Used with nucleus sampling",
                        elem_classes="slider-container"
                    )

    with gr.Group(elem_classes="examples-container"):
        gr.Examples(
            examples=examples,
            inputs=[image, vqa_input],
            label="Try these examples"
        )

    # Event handlers
    caption_button.click(
        fn=generate_caption,
        inputs=[
            image,
            text_decoding_method,
            temperature,
            length_penalty,
            repetition_penalty,
            max_length,
            min_length,
            num_beams,
            top_p,
        ],
        outputs=caption_output,
        api_name="caption"
    )

    chat_inputs = [
        image,
        vqa_input,
        text_decoding_method,
        temperature,
        length_penalty,
        repetition_penalty,
        max_length,
        min_length,
        num_beams,
        top_p,
        history_orig,
        history_qa,
    ]
    chat_outputs = [
        chatbot,
        history_orig,
        history_qa,
    ]

    vqa_input.submit(
        fn=chat,
        inputs=chat_inputs,
        outputs=chat_outputs
    ).success(
        fn=lambda: "",
        outputs=vqa_input,
        queue=False,
        api_name=False
    )

    submit_button.click(
        fn=chat,
        inputs=chat_inputs,
        outputs=chat_outputs,
        api_name="chat"
    ).success(
        fn=lambda: "",
        outputs=vqa_input,
        queue=False,
        api_name=False
    )

    clear_button.click(
        fn=lambda: ("", [], [], []),
        inputs=None,
        outputs=[
            vqa_input,
            chatbot,
            history_orig,
            history_qa,
        ],
        queue=False,
        api_name="clear"
    )

    image.change(
        fn=lambda: ("", [], [], []),
        inputs=None,
        outputs=[
            caption_output,
            chatbot,
            history_orig,
            history_qa,
        ],
        queue=False
    )

if __name__ == "__main__":
    demo.queue(max_size=10).launch()