fantos commited on
Commit
b0940a1
·
verified ·
1 Parent(s): dccfa35

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -24
app.py CHANGED
@@ -1,7 +1,8 @@
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, handle_file
5
 
6
  # ── 환경 변수 ────────────────────────────────────────────────
7
  TOKEN = os.getenv("DISCORD_TOKEN")
@@ -19,7 +20,6 @@ os.environ["REPLICATE_API_TOKEN"] = REPL_TOKEN # 구조 유지 (Repli
19
  # ── Gradio 서버 ─────────────────────────────────────────────
20
  GRADIO_URL = "http://211.233.58.201:7971"
21
  GRADIO_API = "/process_and_save_image"
22
- DUMMY_IMG = "https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png"
23
 
24
  # ── 번역 파이프라인 (CPU) ───────────────────────────────────
25
  translator = transformers_pipeline(
@@ -30,7 +30,6 @@ translator = transformers_pipeline(
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()
@@ -50,7 +49,7 @@ logging.basicConfig(level=logging.INFO,
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):
@@ -78,15 +77,16 @@ class ImageBot(discord.Client):
78
  return client.predict(
79
  height=768,
80
  width=768,
81
- steps=30, # inference_steps → steps
82
- scales=3.5, # guidance → scales
83
  prompt=prompt_en,
84
  seed=random.randint(0, 2**32 - 1),
85
  api_name=GRADIO_API
86
- )[0] # dict(path|url|…)
87
 
88
  try:
89
  img_info = await asyncio.get_running_loop().run_in_executor(None, generate_image)
 
90
  except Exception as e:
91
  logging.error(f"Gradio API error: {e}")
92
  await message.reply("⚠️ 이미지 생성 실패!")
@@ -94,21 +94,37 @@ class ImageBot(discord.Client):
94
 
95
  # ── Discord 전송 ──────────────────────────────────
96
  files = []
97
- try:
98
- if isinstance(img_info, str): # 경우 1: 문자열 경로/URL
99
- data = requests.get(img_info).content if img_info.startswith("http") else open(img_info, "rb").read()
100
- files.append(discord.File(io.BytesIO(data), filename="generated.webp"))
101
- elif isinstance(img_info, dict): # 경우 2: dict(path|url)
102
- if img_info.get("path"):
103
- data = open(img_info["path"], "rb").read()
104
- elif img_info.get("url"):
105
- data = requests.get(img_info["url"]).content
106
- else:
107
- data = None
108
- if data:
109
- files.append(discord.File(io.BytesIO(data), filename="generated.webp"))
110
- except Exception as e:
111
- logging.warning(f"이미지 처리 실패: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
  await message.reply(
114
  files=files if files else None,
@@ -117,5 +133,5 @@ class ImageBot(discord.Client):
117
 
118
  # ── 실행 ────────────────────────────────────────────────────
119
  if __name__ == "__main__":
120
- replicate.Client(api_token=REPL_TOKEN) # 구조 유지(사용 안 함)
121
  ImageBot(intents=intents).run(TOKEN)
 
1
  # img_bot.py
2
+ import discord, os, io, re, random, asyncio, logging, requests, replicate, subprocess, base64
3
+ from urllib.parse import urljoin
4
  from transformers import pipeline as transformers_pipeline
5
+ from gradio_client import Client
6
 
7
  # ── 환경 변수 ────────────────────────────────────────────────
8
  TOKEN = os.getenv("DISCORD_TOKEN")
 
20
  # ── Gradio 서버 ─────────────────────────────────────────────
21
  GRADIO_URL = "http://211.233.58.201:7971"
22
  GRADIO_API = "/process_and_save_image"
 
23
 
24
  # ── 번역 파이프라인 (CPU) ───────────────────────────────────
25
  translator = transformers_pipeline(
 
30
  )
31
 
32
  async def ko2en_async(text: str) -> str:
 
33
  if not re.search(r"[가-힣]", text):
34
  return text
35
  loop = asyncio.get_running_loop()
 
49
 
50
  # ── Discord 인텐트 ──────────────────────────────────────────
51
  intents = discord.Intents.default()
52
+ intents.message_content = True
53
 
54
  class ImageBot(discord.Client):
55
  async def on_ready(self):
 
77
  return client.predict(
78
  height=768,
79
  width=768,
80
+ steps=30,
81
+ scales=3.5,
82
  prompt=prompt_en,
83
  seed=random.randint(0, 2**32 - 1),
84
  api_name=GRADIO_API
85
+ )[0] # list → dict
86
 
87
  try:
88
  img_info = await asyncio.get_running_loop().run_in_executor(None, generate_image)
89
+ logging.info(f"Gradio result: {img_info}")
90
  except Exception as e:
91
  logging.error(f"Gradio API error: {e}")
92
  await message.reply("⚠️ 이미지 생성 실패!")
 
94
 
95
  # ── Discord 전송 ──────────────────────────────────
96
  files = []
97
+ data = None
98
+
99
+ # 1️⃣ url 필드 우선
100
+ url = img_info.get("url")
101
+ if url:
102
+ if url.startswith("data:"): # base64 data URI
103
+ b64 = re.sub(r"^data:image/[^;]+;base64,", "", url)
104
+ try:
105
+ data = base64.b64decode(b64)
106
+ except Exception as e:
107
+ logging.warning(f"base64 디코딩 실패: {e}")
108
+ else:
109
+ if url.startswith("/"): # 상대 URL
110
+ url = urljoin(GRADIO_URL, url)
111
+ try:
112
+ data = requests.get(url, timeout=10).content
113
+ except Exception as e:
114
+ logging.warning(f"URL 다운로드 실패: {e}")
115
+
116
+ # 2️⃣ path 필드 (파일 존재할 때만)
117
+ if data is None:
118
+ path = img_info.get("path")
119
+ if path and os.path.isfile(path):
120
+ try:
121
+ with open(path, "rb") as f:
122
+ data = f.read()
123
+ except Exception as e:
124
+ logging.warning(f"파일 열기 실패: {e}")
125
+
126
+ if data:
127
+ files.append(discord.File(io.BytesIO(data), filename="generated.webp"))
128
 
129
  await message.reply(
130
  files=files if files else None,
 
133
 
134
  # ── 실행 ────────────────────────────────────────────────────
135
  if __name__ == "__main__":
136
+ replicate.Client(api_token=REPL_TOKEN) # 구조 유지
137
  ImageBot(intents=intents).run(TOKEN)