fantos commited on
Commit
898a986
·
verified ·
1 Parent(s): 2edcd19

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -27
app.py CHANGED
@@ -1,33 +1,32 @@
1
  # img_bot.py
2
  import discord, os, io, re, asyncio, logging, requests, replicate, subprocess
3
- from transformers import pipeline as transformers_pipeline
4
 
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
- # message_content 인텐트 사용 여부(1 = ON, 0 = OFF)
11
- USE_MSG_INTENT = os.getenv("MESSAGE_CONTENT_INTENT", "1") != "0"
12
 
13
  if not TOKEN or not CHANNEL_ID:
14
  raise RuntimeError("DISCORD_TOKEN 과 DISCORD_CHANNEL_ID 환경 변수를 모두 지정하세요.")
15
  if not REPL_TOKEN:
16
- raise RuntimeError("OPENAI_API_KEY Replicate Personal Access Token 값을 넣어주세요.")
17
 
18
  # Replicate 라이브러리가 참조하도록 토큰 주입
19
  os.environ["REPLICATE_API_TOKEN"] = REPL_TOKEN
20
 
21
- # ── 모델 ────────────────────────────────────────────────────
22
  MODEL = (
23
- "bytedance/sdxl-lightning-4step:"
24
- "6f7a773af6fc3e8de9d5a3c00be77c17308914bf67772726aff83496ba1e3bbe"
25
  )
26
 
27
  # ── 번역 파이프라인 (CPU) ───────────────────────────────────
28
  translator_kwargs = {"device": -1}
29
  if HF_TOKEN:
30
- translator_kwargs["token"] = HF_TOKEN
 
31
  translator = transformers_pipeline(
32
  "translation",
33
  model="Helsinki-NLP/opus-mt-ko-en",
@@ -35,7 +34,7 @@ translator = transformers_pipeline(
35
  )
36
 
37
  def ko2en(text: str) -> str:
38
- """프롬프트에 한글이 있으면 영어로 번역하여 반환."""
39
  if re.search(r"[가-힣]", text):
40
  try:
41
  return translator(text, max_length=512)[0]["translation_text"].strip()
@@ -52,12 +51,7 @@ logging.basicConfig(
52
 
53
  # ── Discord 설정 ────────────────────────────────────────────
54
  intents = discord.Intents.default()
55
- if USE_MSG_INTENT:
56
- intents.message_content = True
57
- logging.info("Message Content Intent = ON "
58
- "(Discord Developer Portal → Bot → Privileged Intents 에서 활성화 필요)")
59
- else:
60
- logging.info("Message Content Intent = OFF (MESSAGE_CONTENT_INTENT=0)")
61
 
62
  class ImageBot(discord.Client):
63
  async def on_ready(self):
@@ -70,23 +64,29 @@ class ImageBot(discord.Client):
70
  logging.warning(f"web.py 실행 실패: {e}")
71
 
72
  async def on_message(self, message: discord.Message):
73
- # 인텐트 OFF 프롬프트를 읽을 없으므로 즉시 반환
74
- if not USE_MSG_INTENT:
75
- return
76
- # 봇 자신의 메시지 또는 다른 채널 메시지 → 무시
77
  if message.author.id == self.user.id or message.channel.id != CHANNEL_ID:
78
  return
79
 
80
  prompt_raw = message.content.strip()
81
  if not prompt_raw:
82
  return
83
- prompt_en = ko2en(prompt_raw)
84
 
 
85
  await message.channel.typing()
86
 
87
  # ── Replicate 호출 ──────────────────────────────────
88
  def run_replicate():
89
- return list(replicate.run(MODEL, input={"prompt": prompt_en}))
 
 
 
 
 
 
 
 
 
90
 
91
  try:
92
  images = await asyncio.get_running_loop().run_in_executor(None, run_replicate)
@@ -95,12 +95,12 @@ class ImageBot(discord.Client):
95
  await message.reply("⚠️ 이미지 생성 실패!")
96
  return
97
 
98
- # ── Discord 파일 업로드 ─────────────────────────────
99
  files = []
100
  for idx, item in enumerate(images):
101
  try:
102
  data = item.read() if hasattr(item, "read") else requests.get(item).content
103
- files.append(discord.File(io.BytesIO(data), filename=f"img_{idx}.png"))
104
  except Exception as e:
105
  logging.warning(f"[IMG {idx}] 처리 실패: {e}")
106
 
 
1
  # img_bot.py
2
  import discord, os, io, re, asyncio, logging, requests, replicate, subprocess
3
+ from transformers import pipeline as transformers_pipeline # 번역 파이프라인
4
 
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
+ # ── 이미지 생성 모델 (변경된 부분) ────────────────────────────
20
  MODEL = (
21
+ "nvidia/sana-sprint-1.6b:"
22
+ "6ed1ce77cdc8db65550e76d5ab82556d0cb31ac8ab3c4947b168a0bda7b962e4"
23
  )
24
 
25
  # ── 번역 파이프라인 (CPU) ───────────────────────────────────
26
  translator_kwargs = {"device": -1}
27
  if HF_TOKEN:
28
+ translator_kwargs["token"] = HF_TOKEN # 인증 토큰 전달
29
+
30
  translator = transformers_pipeline(
31
  "translation",
32
  model="Helsinki-NLP/opus-mt-ko-en",
 
34
  )
35
 
36
  def ko2en(text: str) -> str:
37
+ """한글 포함 영어 번역, 그렇지 않으면 원문 반환."""
38
  if re.search(r"[가-힣]", text):
39
  try:
40
  return translator(text, max_length=512)[0]["translation_text"].strip()
 
51
 
52
  # ── Discord 설정 ────────────────────────────────────────────
53
  intents = discord.Intents.default()
54
+ intents.message_content = True # 메시지 콘텐츠 읽기
 
 
 
 
 
55
 
56
  class ImageBot(discord.Client):
57
  async def on_ready(self):
 
64
  logging.warning(f"web.py 실행 실패: {e}")
65
 
66
  async def on_message(self, message: discord.Message):
67
+ # 자신의 메시지 혹은 대상 아닌 채널 무시
 
 
 
68
  if message.author.id == self.user.id or message.channel.id != CHANNEL_ID:
69
  return
70
 
71
  prompt_raw = message.content.strip()
72
  if not prompt_raw:
73
  return
 
74
 
75
+ prompt_en = ko2en(prompt_raw) # 한글이면 영어로 변환
76
  await message.channel.typing()
77
 
78
  # ── Replicate 호출 ──────────────────────────────────
79
  def run_replicate():
80
+ # 모델에 따라 필요한 입력 파라미터 이름이 다를 수 있습니다.
81
+ # 일반적으로 "prompt" 키를 사용하지만 필요하면 수정하세요.
82
+ try:
83
+ result = replicate.run(MODEL, input={"prompt": prompt_en})
84
+ except replicate.exceptions.ReplicateError:
85
+ # 파라미터 이름이 다를 경우 빈 dict로 재시도
86
+ result = replicate.run(MODEL, input={})
87
+
88
+ # 결과가 리스트가 아닐 수 있으므로 리스트로 감싸 반환
89
+ return result if isinstance(result, list) else [result]
90
 
91
  try:
92
  images = await asyncio.get_running_loop().run_in_executor(None, run_replicate)
 
95
  await message.reply("⚠️ 이미지 생성 실패!")
96
  return
97
 
98
+ # ── 이미지 Discord 전송 ─────────────────────────────
99
  files = []
100
  for idx, item in enumerate(images):
101
  try:
102
  data = item.read() if hasattr(item, "read") else requests.get(item).content
103
+ files.append(discord.File(io.BytesIO(data), filename=f"img_{idx}.jpg"))
104
  except Exception as e:
105
  logging.warning(f"[IMG {idx}] 처리 실패: {e}")
106