File size: 7,013 Bytes
78efe79
440418c
f3985af
0093ef8
328c74a
 
 
 
 
 
f2ced47
 
95635e6
407a575
32c38ef
95635e6
440418c
328c74a
440418c
22dee1c
440418c
22dee1c
 
08baccf
a0d56d8
 
95635e6
876e0ce
 
328c74a
 
aa7be7c
 
 
328c74a
 
 
 
 
 
 
 
 
 
 
 
 
d87e79b
328c74a
a18e824
655b8e8
876e0ce
328c74a
 
d87e79b
 
 
 
 
 
 
328c74a
d87e79b
328c74a
 
56fcdd0
95635e6
 
 
 
 
56fcdd0
95635e6
 
 
 
 
 
 
 
 
 
 
 
 
 
56fcdd0
aa7be7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2ced47
 
56fcdd0
 
 
f2ced47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e071c6
a2aef79
4e071c6
328c74a
78efe79
08baccf
 
dc80b35
08baccf
78efe79
40d0e92
f2ced47
 
d87e79b
78efe79
dc80b35
 
6a30e5d
78efe79
dc80b35
 
 
 
328c74a
 
 
 
aa7be7c
 
 
dc80b35
 
 
6a30e5d
 
 
 
 
328c74a
 
d87e79b
56fcdd0
aa7be7c
 
6a30e5d
328c74a
 
a2aef79
328c74a
0926d14
34428f1
dc80b35
 
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
import discord
import logging
import os
import asyncio
from transformers import PaliGemmaForConditionalGeneration, PaliGemmaProcessor
import torch
import re
import requests
from PIL import Image
import io
import gradio as gr
import threading
from huggingface_hub import InferenceClient

# ๋กœ๊น… ์„ค์ •
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s:%(levelname)s:%(name)s:%(message)s', handlers=[logging.StreamHandler()])

# ๋””์Šค์ฝ”๋“œ ์ธํ…ํŠธ ์„ค์ •
intents = discord.Intents.default()
intents.message_content = True
intents.messages = True
intents.guilds = True
intents.guild_messages = True

# ์ถ”๋ก  API ํด๋ผ์ด์–ธํŠธ ์„ค์ •
hf_client = InferenceClient("CohereForAI/aya-23-35B", token=os.getenv("HF_TOKEN"))

# PaliGemma ๋ชจ๋ธ ์„ค์ • (CPU ๋ชจ๋“œ)
model = PaliGemmaForConditionalGeneration.from_pretrained("gokaygokay/sd3-long-captioner").to("cpu").eval()
processor = PaliGemmaProcessor.from_pretrained("gokaygokay/sd3-long-captioner")

# ๋Œ€ํ™” ํžˆ์Šคํ† ๋ฆฌ๋ฅผ ์ €์žฅํ•  ์ „์—ญ ๋ณ€์ˆ˜
conversation_history = []

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)

async def create_captions_rich(image: Image.Image) -> str:
    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]

    loop = asyncio.get_event_loop()
    generation = await loop.run_in_executor(
        None,
        lambda: 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

async def translate_to_korean(text: str) -> str:
    messages = [
        {"role": "system", "content": "Translate the following text from English to Korean."},
        {"role": "user", "content": text}
    ]

    loop = asyncio.get_event_loop()
    response = await loop.run_in_executor(
        None,
        lambda: hf_client.chat_completion(
            messages, max_tokens=1000, stream=True, temperature=0.7, top_p=0.85
        )
    )

    full_response = []
    for part in response:
        if part.choices and part.choices[0].delta and part.choices[0].delta.content:
            full_response.append(part.choices[0].delta.content)

    full_response_text = ''.join(full_response)
    return full_response_text.strip()

async def interact_with_model(user_input: str) -> str:
    global conversation_history
    conversation_history.append({"role": "user", "content": user_input})
    
    messages = [
        {"role": "system", "content": "Translate the following text from English to Korean and respond as if you are an assistant who provides detailed answers in Korean."},
    ] + conversation_history

    loop = asyncio.get_event_loop()
    response = await loop.run_in_executor(
        None,
        lambda: hf_client.chat_completion(
            messages, max_tokens=1000, stream=True, temperature=0.7, top_p=0.85
        )
    )

    full_response = []
    for part in response:
        if part.choices and part.choices[0].delta and part.choices[0].delta.content:
            full_response.append(part.choices[0].delta.content)

    full_response_text = ''.join(full_response)
    conversation_history.append({"role": "assistant", "content": full_response_text})
    return full_response_text.strip()

# Gradio ์ธํ„ฐํŽ˜์ด์Šค ์„ค์ •
def create_captions_rich_sync(image):
    caption = asyncio.run(create_captions_rich(image))
    translated_caption = asyncio.run(translate_to_korean(caption))
    return translated_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")

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

# Gradio ์„œ๋ฒ„๋ฅผ ๋น„๋™๊ธฐ์ ์œผ๋กœ ์‹คํ–‰
def run_gradio():
    demo.launch(
        server_name="0.0.0.0", 
        server_port=int(os.getenv("GRADIO_SERVER_PORT", 7861)), 
        inbrowser=True
    )

# ํŠน์ • ์ฑ„๋„ ID ์„ค์ •
SPECIFIC_CHANNEL_ID = int(os.getenv("DISCORD_CHANNEL_ID", "123456789012345678"))

# ๋””์Šค์ฝ”๋“œ ๋ด‡ ์„ค์ •
class MyClient(discord.Client):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.is_processing = False

    async def on_ready(self):
        logging.info(f'{self.user}๋กœ ๋กœ๊ทธ์ธ๋˜์—ˆ์Šต๋‹ˆ๋‹ค!')
        threading.Thread(target=run_gradio, daemon=True).start()
        logging.info("Gradio ์„œ๋ฒ„๊ฐ€ ์‹œ์ž‘๋˜์—ˆ์Šต๋‹ˆ๋‹ค.")

    async def on_message(self, message):
        if message.author == self.user:
            return
        if not self.is_message_in_specific_channel(message):
            return
        if self.is_processing:
            return
        self.is_processing = True
        try:
            if message.attachments:
                image_url = message.attachments[0].url
                response = await process_image(image_url, message)
                await message.channel.send(response)
            else:
                response = await interact_with_model(message.content)
                await message.channel.send(response)
        finally:
            self.is_processing = False

    def is_message_in_specific_channel(self, message):
        return message.channel.id == SPECIFIC_CHANNEL_ID or (
            isinstance(message.channel, discord.Thread) and message.channel.parent_id == SPECIFIC_CHANNEL_ID
        )

async def process_image(image_url, message):
    image = await download_image(image_url)
    caption = await create_captions_rich(image)
    translated_caption = await translate_to_korean(caption)
    intro_message = f"{message.author.mention}, ์ธ์‹๋œ ์ด๋ฏธ์ง€ ์„ค๋ช…: {translated_caption}\n\n์งˆ๋ฌธ์ด ์žˆ์œผ๋ฉด ๋ฌผ์–ด๋ณด์„ธ์š”!"
    return intro_message

async def download_image(url):
    response = requests.get(url)
    image = Image.open(io.BytesIO(response.content)).convert("RGB")
    return image

if __name__ == "__main__":
    discord_client = MyClient(intents=intents)
    discord_client.run(os.getenv('DISCORD_TOKEN'))