File size: 2,459 Bytes
0530853
234a076
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0530853
234a076
 
0530853
234a076
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0530853
234a076
0530853
5e3e01a
 
 
 
 
 
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
import gradio as gr
from transformers import PaliGemmaForConditionalGeneration, PaliGemmaProcessor
import torch
import re

# 모델 로드 및 전처리 설정
model = PaliGemmaForConditionalGeneration.from_pretrained("gokaygokay/sd3-long-captioner").to("cpu").eval()
processor = PaliGemmaProcessor.from_pretrained("gokaygokay/sd3-long-captioner")

def modify_caption(caption: str) -> str:
    prefix_substrings = [
        ('captured from ', ''),
        ('captured at ', '')
    ]
    pattern = '|'.join([re.escape(opening) for opening, _ in prefix_substrings])
    replacers = {opening: replacer for opening, replacer in prefix_substrings}
    
    def replace_fn(match):
        return replacers[match.group(0)]
    
    return re.sub(pattern, replace_fn, caption, count=1, flags=re.IGNORECASE)

def create_captions_rich(image):
    prompt = "caption en"
    image_tensor = processor(images=image, return_tensors="pt").pixel_values.to("cpu")
    image_tensor = (image_tensor * 255).type(torch.uint8)
    model_inputs = processor(text=prompt, images=image_tensor, return_tensors="pt").to("cpu")
    input_len = model_inputs["input_ids"].shape[-1]

    with torch.no_grad():
        generation = model.generate(**model_inputs, max_new_tokens=256, do_sample=False)
        generation = generation[0][input_len:]
        decoded = processor.decode(generation, skip_special_tokens=True)
        modified_caption = modify_caption(decoded)
    return modified_caption

css = """
  #mkd {
    height: 500px; 
    overflow: auto; 
    border: 1px solid #ccc; 
  }
"""

with gr.Blocks(css=css) as demo:
    gr.HTML("<h1><center>PaliGemma Fine-tuned for Long Captioning<center><h1>")
    with gr.Tab(label="PaliGemma Long Captioner"):
        with gr.Row():
            with gr.Column():
                input_img = gr.Image(label="Input Picture")
                submit_btn = gr.Button(value="Submit")
            output = gr.Text(label="Caption")

        gr.Examples(
            [["image1.jpg"], ["image2.jpg"], ["image3.png"], ["image4.jpg"], ["image5.jpg"], ["image6.PNG"]],
            inputs=[input_img],
            outputs=[output],
            fn=create_captions_rich,
            label='Try captioning on examples'
        )

        submit_btn.click(create_captions_rich, [input_img], [output])

# 포트 변경 및 launch 수정
demo.launch(
    server_name="0.0.0.0", 
    server_port=int(os.getenv("GRADIO_SERVER_PORT", 7861)), 
    inbrowser=True
)