File size: 3,914 Bytes
78efe79
440418c
f3985af
22dee1c
328c74a
 
 
 
 
 
d87e79b
407a575
32c38ef
f3985af
440418c
328c74a
440418c
22dee1c
440418c
22dee1c
 
08baccf
876e0ce
 
328c74a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d87e79b
328c74a
a18e824
655b8e8
876e0ce
328c74a
 
d87e79b
 
 
 
 
 
 
328c74a
d87e79b
328c74a
 
4e071c6
 
 
328c74a
78efe79
08baccf
 
dc80b35
08baccf
78efe79
40d0e92
d87e79b
328c74a
6a30e5d
d87e79b
 
 
78efe79
dc80b35
 
6a30e5d
78efe79
dc80b35
 
 
 
328c74a
 
 
 
dc80b35
 
 
6a30e5d
 
 
 
 
328c74a
 
d87e79b
328c74a
6a30e5d
328c74a
 
a18e824
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
import discord
import logging
import os
import subprocess
from transformers import PaliGemmaForConditionalGeneration, PaliGemmaProcessor
import torch
import re
import requests
from PIL import Image
import io
import asyncio

# λ‘œκΉ… μ„€μ •
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

# PaliGemma λͺ¨λΈ μ„€μ • (CPU λͺ¨λ“œ)
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)

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

# νŠΉμ • 채널 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}둜 λ‘œκ·ΈμΈλ˜μ—ˆμŠ΅λ‹ˆλ‹€!')
        asyncio.create_task(self.start_gradio_server())
        logging.info("Web.py μ„œλ²„κ°€ μ‹œμž‘λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")

    async def start_gradio_server(self):
        subprocess.run(["python", "web.py"], check=True)

    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)
        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)
    return f"{message.author.mention}, μΈμ‹λœ 이미지 μ„€λͺ…: {caption}"

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'))