fantos commited on
Commit
444fc48
·
verified ·
1 Parent(s): ded0e5f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -31
app.py CHANGED
@@ -1,27 +1,27 @@
1
  # img_bot.py
2
  import discord, os, io, re, random, asyncio, logging, requests, replicate, subprocess
3
  from transformers import pipeline as transformers_pipeline
4
- from gradio_client import Client # Gradio API
5
 
6
  # ── 환경 변수 ────────────────────────────────────────────────
7
- TOKEN = os.getenv("DISCORD_TOKEN") # Discord 봇 토큰
8
- CHANNEL_ID = int(os.getenv("DISCORD_CHANNEL_ID")) # 감시할 채널 ID
9
- REPL_TOKEN = (os.getenv("OPENAI_API_KEY") or "").strip()# Replicate 토큰(구조 유지)
10
- HF_TOKEN = (os.getenv("HF_TOKEN") or "").strip() # Hugging-Face 토큰(옵션)
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 # 구조 유지
18
 
19
  # ── Gradio 서버 ─────────────────────────────────────────────
20
  GRADIO_URL = "http://211.233.58.201:7896"
21
  GRADIO_API = "/generate_image"
22
  DUMMY_IMG = "https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png"
23
 
24
- # ── 번역 파이프라인 (CPU) ───────────────────────────────────
25
  translator = transformers_pipeline(
26
  "translation",
27
  model="Helsinki-NLP/opus-mt-ko-en",
@@ -29,28 +29,32 @@ translator = transformers_pipeline(
29
  **({"token": HF_TOKEN} if HF_TOKEN else {})
30
  )
31
 
32
- def ko2en(text: str) -> str:
33
- """한글 포함 시 영어로 번역."""
34
- if re.search(r"[가-힣]", text):
35
- try:
36
- return translator(text, max_length=512)[0]["translation_text"].strip()
37
- except Exception as e:
38
- logging.warning(f"번역 실패, 원문 사용: {e}")
39
- return text
 
 
 
 
 
 
40
 
41
  # ── 로깅 ────────────────────────────────────────────────────
42
  logging.basicConfig(level=logging.INFO,
43
- format="%(asctime)s [%(levelname)s] %(message)s",
44
- handlers=[logging.StreamHandler()])
45
 
46
  # ── Discord 인텐트 ──────────────────────────────────────────
47
  intents = discord.Intents.default()
48
- intents.message_content = True # 항상 ON (포털에서도 Message-Content Intent ON)
49
 
50
  class ImageBot(discord.Client):
51
  async def on_ready(self):
52
  logging.info(f"Logged in as {self.user} (id={self.user.id})")
53
- # web.py 병렬 실행
54
  try:
55
  subprocess.Popen(["python", "web.py"])
56
  logging.info("web.py server has been started.")
@@ -65,27 +69,23 @@ class ImageBot(discord.Client):
65
  if not prompt_raw:
66
  return
67
 
68
- prompt_en = ko2en(prompt_raw)
69
  await message.channel.typing()
70
 
71
- # ── Gradio 호출 ────────────────────────────────────
72
  def generate_image():
73
  client = Client(GRADIO_URL)
74
- seed = random.randint(0, 2**32 - 1)
75
- result = client.predict(
76
  prompt=prompt_en,
77
- width=768,
78
- height=768,
79
- guidance=3.5,
80
- inference_steps=30,
81
- seed=seed,
82
  do_img2img=False,
83
- init_image={"url": DUMMY_IMG}, # 필수 placeholder
84
  image2image_strength=0.8,
85
  resize_img=True,
86
  api_name=GRADIO_API
87
- )
88
- return result[0] # dict(path|url)
89
 
90
  try:
91
  img_info = await asyncio.get_running_loop().run_in_executor(None, generate_image)
 
1
  # img_bot.py
2
  import discord, os, io, re, random, asyncio, logging, requests, replicate, subprocess
3
  from transformers import pipeline as transformers_pipeline
4
+ from gradio_client import Client
5
 
6
  # ── 환경 변수 ────────────────────────────────────────────────
7
+ TOKEN = os.getenv("DISCORD_TOKEN")
8
+ CHANNEL_ID = int(os.getenv("DISCORD_CHANNEL_ID"))
9
+ REPL_TOKEN = (os.getenv("OPENAI_API_KEY") or "").strip()
10
+ HF_TOKEN = (os.getenv("HF_TOKEN") or "").strip()
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 # 구조 유지
18
 
19
  # ── Gradio 서버 ─────────────────────────────────────────────
20
  GRADIO_URL = "http://211.233.58.201:7896"
21
  GRADIO_API = "/generate_image"
22
  DUMMY_IMG = "https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png"
23
 
24
+ # ── 번역 파이프라인(마리안, CPU) ────────────────────────────
25
  translator = transformers_pipeline(
26
  "translation",
27
  model="Helsinki-NLP/opus-mt-ko-en",
 
29
  **({"token": HF_TOKEN} if HF_TOKEN else {})
30
  )
31
 
32
+ async def ko2en_async(text: str) -> str:
33
+ """한글 포함 시 별도 쓰레드에서 영어 번역."""
34
+ if not re.search(r"[가-힣]", text):
35
+ return text
36
+ loop = asyncio.get_running_loop()
37
+ try:
38
+ result = await loop.run_in_executor(
39
+ None,
40
+ lambda: translator(text, max_length=256, num_beams=1)[0]["translation_text"].strip()
41
+ )
42
+ return result
43
+ except Exception as e:
44
+ logging.warning(f"번역 실패, 원문 사용: {e}")
45
+ return text
46
 
47
  # ── 로깅 ────────────────────────────────────────────────────
48
  logging.basicConfig(level=logging.INFO,
49
+ format="%(asctime)s [%(levelname)s] %(message)s")
 
50
 
51
  # ── Discord 인텐트 ──────────────────────────────────────────
52
  intents = discord.Intents.default()
53
+ intents.message_content = True # Portal에서도 Message-Content Intent ON
54
 
55
  class ImageBot(discord.Client):
56
  async def on_ready(self):
57
  logging.info(f"Logged in as {self.user} (id={self.user.id})")
 
58
  try:
59
  subprocess.Popen(["python", "web.py"])
60
  logging.info("web.py server has been started.")
 
69
  if not prompt_raw:
70
  return
71
 
72
+ prompt_en = await ko2en_async(prompt_raw) # ✔️ 비동기 번역
73
  await message.channel.typing()
74
 
75
+ # ── Gradio 호출 (블로킹 → executor) ─────────────────
76
  def generate_image():
77
  client = Client(GRADIO_URL)
78
+ return client.predict(
 
79
  prompt=prompt_en,
80
+ width=768, height=768,
81
+ guidance=3.5, inference_steps=30,
82
+ seed=random.randint(0, 2**32 - 1),
 
 
83
  do_img2img=False,
84
+ init_image={"url": DUMMY_IMG},
85
  image2image_strength=0.8,
86
  resize_img=True,
87
  api_name=GRADIO_API
88
+ )[0] # dict(path|url)
 
89
 
90
  try:
91
  img_info = await asyncio.get_running_loop().run_in_executor(None, generate_image)