seawolf2357 commited on
Commit
b1c63d1
Β·
verified Β·
1 Parent(s): 0902fd4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -79
app.py CHANGED
@@ -1,11 +1,10 @@
1
  import discord
2
- from discord.ext import commands
3
- from gradio_client import Client
4
- import asyncio
5
- import os
6
  import logging
 
 
7
  import subprocess
8
- import sys
 
9
 
10
  # λ‘œκΉ… μ„€μ •
11
  logging.basicConfig(level=logging.DEBUG, format='%(asctime)s:%(levelname)s:%(name)s: %(message)s', handlers=[logging.StreamHandler()])
@@ -14,85 +13,93 @@ logging.basicConfig(level=logging.DEBUG, format='%(asctime)s:%(levelname)s:%(nam
14
  intents = discord.Intents.default()
15
  intents.message_content = True
16
 
17
- # Discord Bot μ„€μ •
18
- bot = commands.Bot(command_prefix='!', intents=intents)
19
-
20
  # Gradio API ν΄λΌμ΄μ–ΈνŠΈ μ„€μ •
21
- gradio_client = Client("http://211.233.58.202:7960/")
22
-
23
- # Discord 채널 ID
24
- CHANNEL_ID = 1269529561914413106
25
-
26
- @bot.event
27
- async def on_ready():
28
- logging.info(f'{bot.user.name} has connected to Discord!')
29
- try:
30
- # Gradio μ—°κ²° ν…ŒμŠ€νŠΈ
31
- response = gradio_client.predict("test", api_name="/infer_t2i")
32
- logging.info("Gradio API connection successful")
33
- except Exception as e:
34
- logging.error(f"Gradio API connection failed: {str(e)}")
35
-
36
- @bot.event
37
- async def on_message(message):
38
- if message.author == bot.user:
39
- return
40
-
41
- if message.channel.id != CHANNEL_ID and not isinstance(message.channel, discord.Thread):
42
- return
43
-
44
- try:
45
- result = await asyncio.wait_for(
46
- asyncio.to_thread(
47
- gradio_client.predict,
48
- prompt=message.content,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  seed=123,
50
  randomize_seed=False,
51
  width=1024,
52
  height=576,
53
  guidance_scale=5,
54
- num_inference_steps=30,
55
  api_name="/infer_t2i"
56
- ),
57
- timeout=60 # 60 seconds timeout
58
- )
59
-
60
- logging.debug(f"Predict result: {result}")
61
- if isinstance(result, tuple) and len(result) > 0:
62
- file_path = result[0]
63
- await message.channel.send(file=discord.File(file_path))
64
- else:
65
- logging.error("Unexpected result format from Gradio API")
66
- except asyncio.TimeoutError:
67
- await message.channel.send("Image generation timed out. Please try again.")
68
- except Exception as e:
69
- error_message = f"An error occurred: {str(e)}"
70
- await message.channel.send(error_message)
71
- logging.error(f"Error in on_message: {error_message}")
72
-
73
- @bot.event
74
- async def on_disconnect():
75
- logging.info("Bot disconnected. Attempting to reconnect...")
76
-
77
- @bot.event
78
- async def on_resume():
79
- logging.info("Bot connection resumed.")
80
-
81
- def run_web():
82
- subprocess.run([sys.executable, "web.py"])
83
-
84
- def run_discord_bot():
85
- discord_token = os.getenv('DISCORD_TOKEN')
86
- if discord_token:
87
- bot.run(discord_token)
88
- else:
89
- logging.error("Discord token is not set. Please check your environment variables.")
90
- sys.exit(1) # Exit if token is not set
91
-
92
  if __name__ == "__main__":
93
- web_process = subprocess.Popen([sys.executable, "web.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
94
- logging.info("Web server process started.")
95
-
96
- run_discord_bot()
97
-
98
- web_process.wait() # Ensure the web process completes
 
1
  import discord
 
 
 
 
2
  import logging
3
+ import os
4
+ import uuid
5
  import subprocess
6
+ from deep_translator import GoogleTranslator
7
+ from gradio_client import Client
8
 
9
  # λ‘œκΉ… μ„€μ •
10
  logging.basicConfig(level=logging.DEBUG, format='%(asctime)s:%(levelname)s:%(name)s: %(message)s', handlers=[logging.StreamHandler()])
 
13
  intents = discord.Intents.default()
14
  intents.message_content = True
15
 
 
 
 
16
  # Gradio API ν΄λΌμ΄μ–ΈνŠΈ μ„€μ •
17
+ client = Client("http://211.233.58.202:7960/")
18
+
19
+ # λ””μŠ€μ½”λ“œ 봇 클래슀
20
+ class MyClient(discord.Client):
21
+ def __init__(self, *args, **kwargs):
22
+ super().__init__(*args, **kwargs)
23
+ self.is_processing = False
24
+
25
+ async def on_ready(self):
26
+ logging.info(f'{self.user}둜 λ‘œκ·ΈμΈλ˜μ—ˆμŠ΅λ‹ˆλ‹€!')
27
+ subprocess.Popen(["python", "web.py"])
28
+ logging.info("web.py μ„œλ²„κ°€ μ‹œμž‘λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")
29
+ channel = self.get_channel(int(os.getenv("DISCORD_CHANNEL_ID", "123456789012345678")))
30
+ await channel.send("μ €λŠ” 이미지 생성을 μˆ˜ν–‰ν•  수 있으며, μƒμ„±λœ 이미지에 λŒ€ν•œ μ„€λͺ…을 ν•œκΈ€λ‘œ μ œκ³΅ν•˜κ³  μƒν˜Έ λŒ€ν™”λ₯Ό ν•  수 μžˆμŠ΅λ‹ˆλ‹€. '!image <ν”„λ‘¬ν”„νŠΈ>'λ₯Ό μ‚¬μš©ν•˜μ—¬ 이미지λ₯Ό μš”μ²­ν•˜μ„Έμš”.")
31
+
32
+ async def on_message(self, message):
33
+ if message.author == self.user:
34
+ return
35
+ if message.content.startswith('!image '):
36
+ if self.is_processing:
37
+ await message.channel.send("이미지 생성이 이미 μ§„ν–‰ μ€‘μž…λ‹ˆλ‹€. μž μ‹œλ§Œ κΈ°λ‹€λ € μ£Όμ„Έμš”.")
38
+ return
39
+ self.is_processing = True
40
+ try:
41
+ prompt = message.content[len('!image '):]
42
+ prompt_en = await translate_prompt(prompt)
43
+ image_path = await self.generate_image(prompt_en)
44
+ user_id = message.author.id
45
+ await message.channel.send(
46
+ f"<@{user_id}> λ‹˜μ΄ μš”μ²­ν•˜μ‹  μ΄λ―Έμ§€μž…λ‹ˆλ‹€.",
47
+ file=discord.File(image_path, 'generated_image.png')
48
+ )
49
+ await initiate_conversation(prompt, image_path, message)
50
+ except Exception as e:
51
+ logging.error(f'이미지 생성 쀑 였λ₯˜ λ°œμƒ: {e}')
52
+ await message.channel.send("이미지 생성 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€. λ‚˜μ€‘μ— λ‹€μ‹œ μ‹œλ„ν•΄ μ£Όμ„Έμš”.")
53
+ finally:
54
+ self.is_processing = False
55
+
56
+ async def generate_image(self, prompt):
57
+ if not prompt:
58
+ raise ValueError("Prompt is empty or None")
59
+
60
+ try:
61
+ result = client.predict(
62
+ prompt=prompt,
63
  seed=123,
64
  randomize_seed=False,
65
  width=1024,
66
  height=576,
67
  guidance_scale=5,
68
+ num_inference_steps=28,
69
  api_name="/infer_t2i"
70
+ )
71
+ logging.debug(f"API call result: {result}")
72
+
73
+ if 'path' in result:
74
+ image_path = result['path']
75
+ logging.debug(f"Image successfully retrieved from {image_path}")
76
+ return image_path
77
+ else:
78
+ raise RuntimeError("이미지 생성 μ‹€νŒ¨: κ²°κ³Όκ°€ λΉ„μ–΄ μžˆκ±°λ‚˜ κ²½λ‘œκ°€ ν¬ν•¨λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.")
79
+ except Exception as e:
80
+ logging.error(f'이미지 생성 도쀑 μ˜ˆμ™Έ λ°œμƒ: {e}')
81
+ raise RuntimeError(f"이미지 생성 도쀑 μ˜ˆμ™Έ λ°œμƒ: {str(e)}")
82
+
83
+ async def translate_prompt(prompt):
84
+ logging.debug(f'ν”„λ‘¬ν”„νŠΈ λ²ˆμ—­ 쀑: {prompt}')
85
+ translated_text = GoogleTranslator(source='ko', target='en').translate(prompt)
86
+ logging.debug(f'λ²ˆμ—­λœ ν…μŠ€νŠΈ: {translated_text}')
87
+ return translated_text
88
+
89
+ async def initiate_conversation(prompt, image_path, message):
90
+ logging.debug(f'λŒ€ν™” μ‹œμž‘ 쀑: {prompt}')
91
+ description = "μƒμ„±λœ μ΄λ―Έμ§€μž…λ‹ˆλ‹€."
92
+ logging.debug(f'이미지 μ„€λͺ…: {description}')
93
+
94
+ await message.channel.send(f"이미지 μ„€λͺ…: {description}")
95
+ await continue_conversation(prompt, message)
96
+
97
+ async def continue_conversation(prompt, message):
98
+ logging.debug(f'λŒ€ν™” 지속 쀑: {prompt}')
99
+ # 계속 λŒ€ν™” λ‚΄μš©μ„ λ°›μ•„ μƒν˜Έμž‘μš©ν•˜λ„λ‘ κ΅¬ν˜„
100
+
101
+ # λ””μŠ€μ½”λ“œ 토큰 및 봇 μ‹€ν–‰
 
 
 
 
102
  if __name__ == "__main__":
103
+ discord_token = os.getenv('DISCORD_TOKEN')
104
+ discord_client = MyClient(intents=intents)
105
+ discord_client.run(discord_token)