Spaces:
Runtime error
Runtime error
File size: 5,103 Bytes
78efe79 440418c f3985af 328c74a f2ced47 407a575 32c38ef f3985af 440418c 328c74a 440418c 22dee1c 440418c 22dee1c 08baccf 876e0ce 328c74a d87e79b 328c74a a18e824 655b8e8 876e0ce 328c74a d87e79b 328c74a d87e79b 328c74a f2ced47 4e071c6 328c74a 78efe79 08baccf dc80b35 08baccf 78efe79 40d0e92 f2ced47 d87e79b 78efe79 dc80b35 6a30e5d 78efe79 dc80b35 328c74a dc80b35 6a30e5d 328c74a d87e79b 328c74a 6a30e5d 328c74a a18e824 328c74a 0926d14 34428f1 dc80b35 f2ced47 |
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 |
import discord
import logging
import os
from transformers import PaliGemmaForConditionalGeneration, PaliGemmaProcessor
import torch
import re
import requests
from PIL import Image
import io
import gradio as gr
import threading
# ๋ก๊น
์ค์
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
# Gradio ์ธํฐํ์ด์ค ์ค์
def create_captions_rich_sync(image):
return asyncio.run(create_captions_rich(image))
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_sync,
label='Try captioning on examples'
)
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)
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'))
discord_client = MyClient(intents=intents)
discord_client.run(os.getenv('DISCORD_TOKEN'))
|