Spaces:
Runtime error
Runtime error
# img_bot.py | |
import discord, os, io, re, random, asyncio, logging, requests, replicate, subprocess | |
from transformers import pipeline as transformers_pipeline | |
from gradio_client import Client, handle_file | |
# ββ νκ²½ λ³μ ββββββββββββββββββββββββββββββββββββββββββββββββ | |
TOKEN = os.getenv("DISCORD_TOKEN") | |
CHANNEL_ID = int(os.getenv("DISCORD_CHANNEL_ID")) | |
REPL_TOKEN = (os.getenv("OPENAI_API_KEY") or "").strip() | |
HF_TOKEN = (os.getenv("HF_TOKEN") or "").strip() | |
if not TOKEN or not CHANNEL_ID: | |
raise RuntimeError("DISCORD_TOKEN κ³Ό DISCORD_CHANNEL_ID νκ²½ λ³μλ₯Ό λͺ¨λ μ§μ νμΈμ.") | |
if not REPL_TOKEN: | |
raise RuntimeError("OPENAI_API_KEY μ Replicate Personal Access Token κ°μ λ£μ΄μ£ΌμΈμ.") | |
os.environ["REPLICATE_API_TOKEN"] = REPL_TOKEN # ꡬ쑰 μ μ§ (Replicate λ―Έμ¬μ©) | |
# ββ Gradio μλ² βββββββββββββββββββββββββββββββββββββββββββββ | |
GRADIO_URL = "http://211.233.58.201:7971" | |
GRADIO_API = "/process_and_save_image" | |
DUMMY_IMG = "https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png" | |
# ββ λ²μ νμ΄νλΌμΈ (CPU) βββββββββββββββββββββββββββββββββββ | |
translator = transformers_pipeline( | |
"translation", | |
model="Helsinki-NLP/opus-mt-ko-en", | |
device=-1, | |
**({"token": HF_TOKEN} if HF_TOKEN else {}) | |
) | |
async def ko2en_async(text: str) -> str: | |
"""νκΈ ν¬ν¨ μ λ³λ μ°λ λμμ μμ΄ λ²μ.""" | |
if not re.search(r"[κ°-ν£]", text): | |
return text | |
loop = asyncio.get_running_loop() | |
try: | |
return await loop.run_in_executor( | |
None, | |
lambda: translator(text, max_length=256, num_beams=1)[0]["translation_text"].strip() | |
) | |
except Exception as e: | |
logging.warning(f"λ²μ μ€ν¨, μλ¬Έ μ¬μ©: {e}") | |
return text | |
# ββ λ‘κΉ ββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
logging.basicConfig(level=logging.INFO, | |
format="%(asctime)s [%(levelname)s] %(message)s", | |
handlers=[logging.StreamHandler()]) | |
# ββ Discord μΈν νΈ ββββββββββββββββββββββββββββββββββββββββββ | |
intents = discord.Intents.default() | |
intents.message_content = True # Portalμμλ Message-Content Intent ON | |
class ImageBot(discord.Client): | |
async def on_ready(self): | |
logging.info(f"Logged in as {self.user} (id={self.user.id})") | |
try: | |
subprocess.Popen(["python", "web.py"]) | |
logging.info("web.py server has been started.") | |
except Exception as e: | |
logging.warning(f"web.py μ€ν μ€ν¨: {e}") | |
async def on_message(self, message: discord.Message): | |
if message.author.id == self.user.id or message.channel.id != CHANNEL_ID: | |
return | |
prompt_raw = message.content.strip() | |
if not prompt_raw: | |
return | |
prompt_en = await ko2en_async(prompt_raw) | |
await message.channel.typing() | |
# ββ Gradio νΈμΆ ββββββββββββββββββββββββββββββββββββ | |
def generate_image(): | |
client = Client(GRADIO_URL) | |
return client.predict( | |
height=768, | |
width=768, | |
steps=30, # inference_steps β steps | |
scales=3.5, # guidance β scales | |
prompt=prompt_en, | |
seed=random.randint(0, 2**32 - 1), | |
api_name=GRADIO_API | |
)[0] # dict(path|url|β¦) | |
try: | |
img_info = await asyncio.get_running_loop().run_in_executor(None, generate_image) | |
except Exception as e: | |
logging.error(f"Gradio API error: {e}") | |
await message.reply("β οΈ μ΄λ―Έμ§ μμ± μ€ν¨!") | |
return | |
# ββ Discord μ μ‘ ββββββββββββββββββββββββββββββββββ | |
files = [] | |
try: | |
if isinstance(img_info, str): # κ²½μ° 1: λ¬Έμμ΄ κ²½λ‘/URL | |
data = requests.get(img_info).content if img_info.startswith("http") else open(img_info, "rb").read() | |
files.append(discord.File(io.BytesIO(data), filename="generated.webp")) | |
elif isinstance(img_info, dict): # κ²½μ° 2: dict(path|url) | |
if img_info.get("path"): | |
data = open(img_info["path"], "rb").read() | |
elif img_info.get("url"): | |
data = requests.get(img_info["url"]).content | |
else: | |
data = None | |
if data: | |
files.append(discord.File(io.BytesIO(data), filename="generated.webp")) | |
except Exception as e: | |
logging.warning(f"μ΄λ―Έμ§ μ²λ¦¬ μ€ν¨: {e}") | |
await message.reply( | |
files=files if files else None, | |
content=None if files else "β οΈ μ΄λ―Έμ§λ₯Ό μ μ‘ν μ μμ΅λλ€." | |
) | |
# ββ μ€ν ββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
if __name__ == "__main__": | |
replicate.Client(api_token=REPL_TOKEN) # ꡬ쑰 μ μ§(μ¬μ© μ ν¨) | |
ImageBot(intents=intents).run(TOKEN) | |