kai-flx-id / app.py
fantaxy's picture
Update app.py
0f268ec verified
import discord
import logging
import os
import asyncio
import aiohttp
from gradio_client import Client, handle_file
from aiohttp import web
# ๋กœ๊น… ์„ค์ •
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
# API ํด๋ผ์ด์–ธํŠธ ์„ค์ •
api_client = Client("http://hugpu.ai:7889")
# ๋””์Šค์ฝ”๋“œ ๋ด‡ ํด๋ž˜์Šค
class MyClient(discord.Client):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.is_processing = False
self.web_app = None
async def start_web_server(self):
app = web.Application()
app.router.add_get('/', self.handle_index)
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, 'localhost', 8080)
await site.start()
self.web_app = app
logging.info("Web server started on http://localhost:8080")
async def handle_index(self, request):
return web.Response(text="Server is running")
async def on_ready(self):
logging.info(f'{self.user}๋กœ ๋กœ๊ทธ์ธ๋˜์—ˆ์Šต๋‹ˆ๋‹ค!')
channel = self.get_channel(int(os.getenv("DISCORD_CHANNEL_ID", "123456789012345678")))
await channel.send("์ด๋ฏธ์ง€์™€ ํ”„๋กฌํ”„ํŠธ๋ฅผ ์ž…๋ ฅํ•ด ์ด๋ฏธ์ง€ ์ƒ์„ฑ์„ ์š”์ฒญํ•˜์„ธ์š”. ์‚ฌ์šฉ ์˜ˆ: '!image [ํ”„๋กฌํ”„ํŠธ]' (์ด๋ฏธ์ง€ ์ฒจ๋ถ€)")
# Web ์„œ๋ฒ„ ์‹œ์ž‘
await self.start_web_server()
async def on_message(self, message):
if message.author == self.user:
return
if message.content.startswith('!image '):
if self.is_processing:
await message.channel.send("์ด๋ฏธ์ง€ ์ƒ์„ฑ ์ค‘์ž…๋‹ˆ๋‹ค. ์ž ์‹œ๋งŒ ๊ธฐ๋‹ค๋ ค ์ฃผ์„ธ์š”.")
return
self.is_processing = True
try:
if len(message.attachments) > 0:
image_url = message.attachments[0].url
prompt = message.content[7:].strip()
generated_images = await self.generate_image(prompt, image_url)
user_id = message.author.id
if generated_images and len(generated_images) > 0:
image_path = generated_images[0]['image']
await message.channel.send(
f"<@{user_id}> ๋‹˜์ด ์š”์ฒญํ•˜์‹  ์ด๋ฏธ์ง€์ž…๋‹ˆ๋‹ค.\n"
f"ํ”„๋กฌํ”„ํŠธ: {prompt}",
file=discord.File(image_path)
)
else:
await message.channel.send("์ด๋ฏธ์ง€ ์ƒ์„ฑ์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค.")
else:
await message.channel.send("์ด๋ฏธ์ง€๋ฅผ ์ฒจ๋ถ€ํ•ด ์ฃผ์„ธ์š”.")
except Exception as e:
logging.error(f'์ด๋ฏธ์ง€ ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {e}')
finally:
self.is_processing = False
async def generate_image(self, prompt, image_url):
if not prompt or not image_url:
raise ValueError("Prompt or image URL is empty")
logging.debug(f"Sending request to API with prompt: {prompt} and image URL: {image_url}")
try:
result = api_client.predict(
images=[handle_file(image_url)],
prompt=prompt,
negative_prompt="",
preserve_face_structure=True,
face_strength=1.3,
likeness_strength=1,
nfaa_negative_prompt="naked, bikini, skimpy, scanty, bare skin, lingerie, swimsuit, exposed, see-through",
api_name="/generate_image"
)
logging.debug(f"API response received: {result}")
return result
except Exception as e:
logging.error(f'API ์š”์ฒญ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {e}', exc_info=True)
raise RuntimeError(f"API ์š”์ฒญ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}")
async def main():
discord_token = os.getenv('DISCORD_TOKEN')
client = MyClient(intents=intents)
try:
await client.start(discord_token)
except KeyboardInterrupt:
await client.close()
if __name__ == "__main__":
asyncio.run(main())