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

# ๋กœ๊น… ์„ค์ •
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 ๋ชจ๋ธ ์„ค์ •
model = PaliGemmaForConditionalGeneration.from_pretrained("gokaygokay/sd3-long-captioner").to("cuda").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: Image.Image) -> str:
    prompt = "caption en"
    image_tensor = processor(image, return_tensors="pt").pixel_values.to("cuda")
    model_inputs = processor(text=prompt, images=image_tensor, return_tensors="pt").to("cuda")
    input_len = model_inputs["input_ids"].shape[-1]

    with torch.inference_mode():
        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

# ๋””์Šค์ฝ”๋“œ ๋ด‡ ์„ค์ •
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}๋กœ ๋กœ๊ทธ์ธ๋˜์—ˆ์Šต๋‹ˆ๋‹ค!')
        subprocess.Popen(["python", "web.py"])
        logging.info("Web.py ์„œ๋ฒ„๊ฐ€ ์‹œ์ž‘๋˜์—ˆ์Šต๋‹ˆ๋‹ค.")

    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 = 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))
    return image

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