fantos commited on
Commit
9d6ae27
Β·
verified Β·
1 Parent(s): 7ad5100

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -31
app.py CHANGED
@@ -5,16 +5,16 @@ from transformers import pipeline as transformers_pipeline # λ²ˆμ—­ νŒŒμ΄ν”„
5
  # ── ν™˜κ²½ λ³€μˆ˜ ────────────────────────────────────────────────
6
  TOKEN = os.getenv("DISCORD_TOKEN") # Discord 봇 토큰
7
  CHANNEL_ID = int(os.getenv("DISCORD_CHANNEL_ID")) # κ°μ‹œν•  채널 ID
8
- REPL_TOKEN = (os.getenv("OPENAI_API_KEY") or "").strip() # Replicate 토큰(동일 λ³€μˆ˜ μ‚¬μš©)
9
- HF_TOKEN = (os.getenv("HF_TOKEN") or "").strip() # Hugging Face Personal Access Token
 
10
 
11
  if not TOKEN or not CHANNEL_ID:
12
  raise RuntimeError("DISCORD_TOKEN κ³Ό DISCORD_CHANNEL_ID ν™˜κ²½ λ³€μˆ˜λ₯Ό λͺ¨λ‘ μ§€μ •ν•˜μ„Έμš”.")
13
  if not REPL_TOKEN:
14
  raise RuntimeError("OPENAI_API_KEY ν™˜κ²½ λ³€μˆ˜μ— Replicate Personal Access Token 값을 λ„£μ–΄μ£Όμ„Έμš”.")
15
 
16
- # Replicate λΌμ΄λΈŒλŸ¬λ¦¬κ°€ μ°Έμ‘°ν•˜λ„λ‘ 토큰 μ£Όμž…
17
- os.environ["REPLICATE_API_TOKEN"] = REPL_TOKEN
18
 
19
  # ── 이미지 생성 λͺ¨λΈ (Flux Schnell) ─────────────────────────
20
  MODEL = "black-forest-labs/flux-schnell"
@@ -23,15 +23,12 @@ MODEL = "black-forest-labs/flux-schnell"
23
  translator_kwargs = {"device": -1}
24
  if HF_TOKEN:
25
  translator_kwargs["token"] = HF_TOKEN
26
-
27
  translator = transformers_pipeline(
28
- "translation",
29
- model="Helsinki-NLP/opus-mt-ko-en",
30
- **translator_kwargs
31
  )
32
 
33
  def ko2en(text: str) -> str:
34
- """ν”„λ‘¬ν”„νŠΈμ— ν•œκΈ€μ΄ 있으면 μ˜μ–΄λ‘œ λ²ˆμ—­ν•˜μ—¬ λ°˜ν™˜."""
35
  if re.search(r"[κ°€-힣]", text):
36
  try:
37
  return translator(text, max_length=512)[0]["translation_text"].strip()
@@ -40,15 +37,17 @@ def ko2en(text: str) -> str:
40
  return text
41
 
42
  # ── λ‘œκΉ… ────────────────────────────────────────────────────
43
- logging.basicConfig(
44
- level=logging.INFO,
45
- format="%(asctime)s [%(levelname)s] %(message)s",
46
- handlers=[logging.StreamHandler()]
47
- )
48
 
49
- # ── Discord μ„€μ • ────────────────────────────────────────────
50
  intents = discord.Intents.default()
51
- intents.message_content = True # λ©”μ‹œμ§€ μ½˜ν…μΈ  읽기
 
 
 
 
 
52
 
53
  class ImageBot(discord.Client):
54
  async def on_ready(self):
@@ -61,7 +60,9 @@ class ImageBot(discord.Client):
61
  logging.warning(f"web.py μ‹€ν–‰ μ‹€νŒ¨: {e}")
62
 
63
  async def on_message(self, message: discord.Message):
64
- # 봇 μžμ‹ μ˜ λ©”μ‹œμ§€ ν˜Ήμ€ λŒ€μƒ μ•„λ‹Œ 채널 β†’ λ¬΄μ‹œ
 
 
65
  if message.author.id == self.user.id or message.channel.id != CHANNEL_ID:
66
  return
67
 
@@ -69,17 +70,12 @@ class ImageBot(discord.Client):
69
  if not prompt_raw:
70
  return
71
 
72
- prompt_en = ko2en(prompt_raw) # ν•œκΈ€μ΄λ©΄ μ˜μ–΄λ‘œ λ³€ν™˜
73
  await message.channel.typing()
74
 
75
- # ── Replicate 호좜 ──────────────────────────────────
76
  def run_replicate():
77
- return list(
78
- replicate.run(
79
- MODEL,
80
- input={"prompt": prompt_en}
81
- )
82
- )
83
 
84
  try:
85
  images = await asyncio.get_running_loop().run_in_executor(None, run_replicate)
@@ -88,7 +84,7 @@ class ImageBot(discord.Client):
88
  await message.reply("⚠️ 이미지 생성 μ‹€νŒ¨!")
89
  return
90
 
91
- # ── 이미지 Discord 전솑 ─────────────────────────────
92
  files = []
93
  for idx, item in enumerate(images):
94
  try:
@@ -97,12 +93,10 @@ class ImageBot(discord.Client):
97
  except Exception as e:
98
  logging.warning(f"[IMG {idx}] 처리 μ‹€νŒ¨: {e}")
99
 
100
- await message.reply(
101
- files=files if files else None,
102
- content=None if files else "⚠️ 이미지λ₯Ό 전솑할 수 μ—†μŠ΅λ‹ˆλ‹€."
103
- )
104
 
105
  # ── μ‹€ν–‰ ────────────────────────────────────────────────────
106
  if __name__ == "__main__":
107
- replicate.Client(api_token=REPL_TOKEN) # Replicate 인증
108
  ImageBot(intents=intents).run(TOKEN)
 
5
  # ── ν™˜κ²½ λ³€μˆ˜ ────────────────────────────────────────────────
6
  TOKEN = os.getenv("DISCORD_TOKEN") # Discord 봇 토큰
7
  CHANNEL_ID = int(os.getenv("DISCORD_CHANNEL_ID")) # κ°μ‹œν•  채널 ID
8
+ REPL_TOKEN = (os.getenv("OPENAI_API_KEY") or "").strip() # Replicate 토큰 μž¬μ‚¬μš©
9
+ HF_TOKEN = (os.getenv("HF_TOKEN") or "").strip() # Hugging Face 토큰
10
+ USE_MSG_INTENT = os.getenv("MESSAGE_CONTENT_INTENT", "1") != "0" # 1=ON(κΈ°λ³Έ), 0=OFF
11
 
12
  if not TOKEN or not CHANNEL_ID:
13
  raise RuntimeError("DISCORD_TOKEN κ³Ό DISCORD_CHANNEL_ID ν™˜κ²½ λ³€μˆ˜λ₯Ό λͺ¨λ‘ μ§€μ •ν•˜μ„Έμš”.")
14
  if not REPL_TOKEN:
15
  raise RuntimeError("OPENAI_API_KEY ν™˜κ²½ λ³€μˆ˜μ— Replicate Personal Access Token 값을 λ„£μ–΄μ£Όμ„Έμš”.")
16
 
17
+ os.environ["REPLICATE_API_TOKEN"] = REPL_TOKEN # Replicate κ°€ μ°Έμ‘°ν•  토큰
 
18
 
19
  # ── 이미지 생성 λͺ¨λΈ (Flux Schnell) ─────────────────────────
20
  MODEL = "black-forest-labs/flux-schnell"
 
23
  translator_kwargs = {"device": -1}
24
  if HF_TOKEN:
25
  translator_kwargs["token"] = HF_TOKEN
 
26
  translator = transformers_pipeline(
27
+ "translation", model="Helsinki-NLP/opus-mt-ko-en", **translator_kwargs
 
 
28
  )
29
 
30
  def ko2en(text: str) -> str:
31
+ """ν”„λ‘¬ν”„νŠΈμ— ν•œκΈ€ 포함 μ‹œ μ˜μ–΄ λ²ˆμ—­."""
32
  if re.search(r"[κ°€-힣]", text):
33
  try:
34
  return translator(text, max_length=512)[0]["translation_text"].strip()
 
37
  return text
38
 
39
  # ── λ‘œκΉ… ────────────────────────────────────────────────────
40
+ logging.basicConfig(level=logging.INFO,
41
+ format="%(asctime)s [%(levelname)s] %(message)s")
 
 
 
42
 
43
+ # ── Discord μΈν…νŠΈ μ„€μ • ────────────────────────────────────
44
  intents = discord.Intents.default()
45
+ if USE_MSG_INTENT:
46
+ intents.message_content = True
47
+ logging.info("Message Content Intent = ON "
48
+ "(Developer Portal β†’ Bot β†’ Privileged Intents μ—μ„œ ON ν•„μš”)")
49
+ else:
50
+ logging.info("Message Content Intent = OFF (MESSAGE_CONTENT_INTENT=0)")
51
 
52
  class ImageBot(discord.Client):
53
  async def on_ready(self):
 
60
  logging.warning(f"web.py μ‹€ν–‰ μ‹€νŒ¨: {e}")
61
 
62
  async def on_message(self, message: discord.Message):
63
+ # λ©”μ‹œμ§€ λ‚΄μš© 읽을 κΆŒν•œμ΄ μ—†μœΌλ©΄ λ°”λ‘œ λ°˜ν™˜
64
+ if not USE_MSG_INTENT:
65
+ return
66
  if message.author.id == self.user.id or message.channel.id != CHANNEL_ID:
67
  return
68
 
 
70
  if not prompt_raw:
71
  return
72
 
73
+ prompt_en = ko2en(prompt_raw)
74
  await message.channel.typing()
75
 
76
+ # ── Replicate μš”μ²­ ─────────────────────────────────
77
  def run_replicate():
78
+ return list(replicate.run(MODEL, input={"prompt": prompt_en}))
 
 
 
 
 
79
 
80
  try:
81
  images = await asyncio.get_running_loop().run_in_executor(None, run_replicate)
 
84
  await message.reply("⚠️ 이미지 생성 μ‹€νŒ¨!")
85
  return
86
 
87
+ # ��─ Discord 전솑 ──────────────────────────────────
88
  files = []
89
  for idx, item in enumerate(images):
90
  try:
 
93
  except Exception as e:
94
  logging.warning(f"[IMG {idx}] 처리 μ‹€νŒ¨: {e}")
95
 
96
+ await message.reply(files=files if files else None,
97
+ content=None if files else "⚠️ 이미지λ₯Ό 전솑할 수 μ—†μŠ΅λ‹ˆλ‹€.")
 
 
98
 
99
  # ── μ‹€ν–‰ ────────────────────────────────────────────────────
100
  if __name__ == "__main__":
101
+ replicate.Client(api_token=REPL_TOKEN) # Replicate 인증
102
  ImageBot(intents=intents).run(TOKEN)