fantos commited on
Commit
c48780b
Β·
verified Β·
1 Parent(s): b08146f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -31
app.py CHANGED
@@ -1,11 +1,20 @@
1
- # img_bot.py (λ³€κ²½λœ λΆ€λΆ„ β˜…ν‘œμ‹œ)
 
 
2
  import os, io, re, random, asyncio, logging, subprocess, base64
3
  from urllib.parse import urljoin, quote_plus
4
 
5
- import discord, requests, replicate
 
 
6
  from transformers import pipeline as transformers_pipeline
7
  from gradio_client import Client
8
- from PIL import Image # WEBP β†’ PNG λ³€ν™˜μš©
 
 
 
 
 
9
 
10
  # ────────────────── ν™˜κ²½ λ³€μˆ˜ ──────────────────
11
  TOKEN = os.getenv("DISCORD_TOKEN")
@@ -17,7 +26,8 @@ if not TOKEN or not CHANNEL_ID:
17
  raise RuntimeError("DISCORD_TOKEN κ³Ό DISCORD_CHANNEL_ID ν™˜κ²½ λ³€μˆ˜λ₯Ό λͺ¨λ‘ μ§€μ •ν•˜μ„Έμš”.")
18
  if not REPL_TOKEN:
19
  raise RuntimeError("OPENAI_API_KEY 에 Replicate Personal Access Token 값을 λ„£μ–΄μ£Όμ„Έμš”.")
20
- os.environ["REPLICATE_API_TOKEN"] = REPL_TOKEN # Replicate λ―Έμ‚¬μš©μ΄μ§€λ§Œ ꡬ쑰 μœ μ§€
 
21
 
22
  # ────────────────── Gradio μ„œλ²„ ─────────────────
23
  GRADIO_URL = "http://211.233.58.201:7971"
@@ -32,6 +42,7 @@ translator = transformers_pipeline(
32
  )
33
 
34
  async def ko2en_async(text: str) -> str:
 
35
  if not re.search(r"[κ°€-힣]", text):
36
  return text
37
  loop = asyncio.get_running_loop()
@@ -95,26 +106,34 @@ class ImageBot(discord.Client):
95
  await message.reply("⚠️ 이미지 생성 μ‹€νŒ¨!")
96
  return
97
 
98
- if isinstance(result, list): # 리슀트면 첫 ν•­λͺ©
 
99
  result = result[0]
100
 
101
  # ───────────── 이미지 데이터 확보 ─────────────
102
  data = None
103
- candidate_urls = []
 
104
 
105
- def add_remote(path: str):
106
- candidate_urls.append(urljoin(GRADIO_URL, f"/gradio_api/file={quote_plus(path)}"))
 
 
107
 
108
  # dict κ²°κ³Ό
109
  if isinstance(result, dict):
110
- if result.get("url"):
111
- u = result["url"]
112
- candidate_urls.append(urljoin(GRADIO_URL, u) if u.startswith("/") else u)
113
- if result.get("path"):
114
- add_remote(result["path"])
115
- if os.path.isfile(result["path"]):
 
 
 
 
116
  try:
117
- with open(result["path"], "rb") as f:
118
  data = f.read()
119
  except Exception:
120
  pass
@@ -129,10 +148,11 @@ class ImageBot(discord.Client):
129
  logging.warning(f"base64 λ””μ½”λ”© μ‹€νŒ¨: {e}")
130
  elif s.startswith("http"):
131
  candidate_urls.append(s)
132
- elif s.startswith("/"):
133
- candidate_urls.append(urljoin(GRADIO_URL, s))
134
  else:
135
- add_remote(s)
 
 
136
  if os.path.isfile(s):
137
  try:
138
  with open(s, "rb") as f:
@@ -140,7 +160,7 @@ class ImageBot(discord.Client):
140
  except Exception:
141
  pass
142
 
143
- # URL λ‹€μš΄λ‘œλ“œ (β˜… 헀더 검사 제거)
144
  for u in candidate_urls:
145
  if data:
146
  break
@@ -152,21 +172,28 @@ class ImageBot(discord.Client):
152
  except Exception as e:
153
  logging.warning(f"URL λ‹€μš΄λ‘œλ“œ μ‹€νŒ¨({u}): {e}")
154
 
155
- if not data:
156
- await message.reply("⚠️ 이미지λ₯Ό 전솑할 수 μ—†μŠ΅λ‹ˆλ‹€.")
 
 
 
 
 
 
 
 
 
 
 
157
  return
158
 
159
- # ───────────── WEBP β†’ PNG λ³€ν™˜ ─────────────
160
- buf = io.BytesIO()
161
- try:
162
- Image.open(io.BytesIO(data)).convert("RGB").save(buf, format="PNG")
163
- buf.seek(0)
164
- await message.reply(files=[discord.File(buf, filename="image.png")])
165
- except Exception as e:
166
- logging.warning(f"PNG λ³€ν™˜ μ‹€νŒ¨: {e}")
167
- await message.reply(files=[discord.File(io.BytesIO(data), filename="image.webp")])
168
 
169
  # ────────────────── μ‹€ν–‰ ────────────────────────
170
  if __name__ == "__main__":
171
- replicate.Client(api_token=REPL_TOKEN) # ꡬ쑰 μœ μ§€
172
  ImageBot(intents=intents).run(TOKEN)
 
1
+ # img_bot.py
2
+ # β€œμ΄λ―Έμ§€ 첨뢀 β†’ μ‹€νŒ¨ μ‹œ URL 좜λ ₯” μ™„κ²°νŒ
3
+
4
  import os, io, re, random, asyncio, logging, subprocess, base64
5
  from urllib.parse import urljoin, quote_plus
6
 
7
+ import discord
8
+ import requests
9
+ import replicate
10
  from transformers import pipeline as transformers_pipeline
11
  from gradio_client import Client
12
+
13
+ try:
14
+ from PIL import Image # WEBP β†’ PNG λ³€ν™˜
15
+ PIL_OK = True
16
+ except Exception:
17
+ PIL_OK = False # Pillow λ―Έμ„€μΉ˜ μ‹œ λ³€ν™˜ μƒλž΅
18
 
19
  # ────────────────── ν™˜κ²½ λ³€μˆ˜ ──────────────────
20
  TOKEN = os.getenv("DISCORD_TOKEN")
 
26
  raise RuntimeError("DISCORD_TOKEN κ³Ό DISCORD_CHANNEL_ID ν™˜κ²½ λ³€μˆ˜λ₯Ό λͺ¨λ‘ μ§€μ •ν•˜μ„Έμš”.")
27
  if not REPL_TOKEN:
28
  raise RuntimeError("OPENAI_API_KEY 에 Replicate Personal Access Token 값을 λ„£μ–΄μ£Όμ„Έμš”.")
29
+
30
+ os.environ["REPLICATE_API_TOKEN"] = REPL_TOKEN # (Replicate λ―Έμ‚¬μš©)
31
 
32
  # ────────────────── Gradio μ„œλ²„ ─────────────────
33
  GRADIO_URL = "http://211.233.58.201:7971"
 
42
  )
43
 
44
  async def ko2en_async(text: str) -> str:
45
+ """ν•œκΈ€ 포함 μ‹œ μ˜μ–΄ λ²ˆμ—­."""
46
  if not re.search(r"[κ°€-힣]", text):
47
  return text
48
  loop = asyncio.get_running_loop()
 
106
  await message.reply("⚠️ 이미지 생성 μ‹€νŒ¨!")
107
  return
108
 
109
+ # 리슀트 κ²°κ³Ό β†’ 첫 μš”μ†Œ
110
+ if isinstance(result, list):
111
  result = result[0]
112
 
113
  # ───────────── 이미지 데이터 확보 ─────────────
114
  data = None
115
+ remote_path = None # μ‹€νŒ¨ μ‹œ μ‚¬μš©μžμ—κ²Œ 보여쀄 URL
116
+ candidate_urls: list[str] = []
117
 
118
+ def add_remote(p: str):
119
+ url = urljoin(GRADIO_URL, f"/gradio_api/file={quote_plus(p)}")
120
+ candidate_urls.append(url)
121
+ return url
122
 
123
  # dict κ²°κ³Ό
124
  if isinstance(result, dict):
125
+ u = result.get("url")
126
+ if u:
127
+ if u.startswith("/"):
128
+ u = urljoin(GRADIO_URL, u)
129
+ candidate_urls.append(u)
130
+ remote_path = u
131
+ p = result.get("path")
132
+ if p:
133
+ remote_path = add_remote(p)
134
+ if os.path.isfile(p):
135
  try:
136
+ with open(p, "rb") as f:
137
  data = f.read()
138
  except Exception:
139
  pass
 
148
  logging.warning(f"base64 λ””μ½”λ”© μ‹€νŒ¨: {e}")
149
  elif s.startswith("http"):
150
  candidate_urls.append(s)
151
+ remote_path = s
 
152
  else:
153
+ remote_path = add_remote(s)
154
+ if s.startswith("/"):
155
+ candidate_urls.append(urljoin(GRADIO_URL, s))
156
  if os.path.isfile(s):
157
  try:
158
  with open(s, "rb") as f:
 
160
  except Exception:
161
  pass
162
 
163
+ # URL λ‹€μš΄λ‘œλ“œ (헀더 λ¬΄μ‹œ, 200 OK 만 확인)
164
  for u in candidate_urls:
165
  if data:
166
  break
 
172
  except Exception as e:
173
  logging.warning(f"URL λ‹€μš΄λ‘œλ“œ μ‹€νŒ¨({u}): {e}")
174
 
175
+ # ───────────── Discord 전솑 ─────────────
176
+ if data:
177
+ if PIL_OK: # WEBP β†’ PNG λ³€ν™˜
178
+ try:
179
+ buf = io.BytesIO()
180
+ Image.open(io.BytesIO(data)).convert("RGB").save(buf, format="PNG")
181
+ buf.seek(0)
182
+ await message.reply(files=[discord.File(buf, filename="image.png")])
183
+ return
184
+ except Exception as e:
185
+ logging.warning(f"PNG λ³€ν™˜ μ‹€νŒ¨: {e}")
186
+ # λ³€ν™˜ μ‹€νŒ¨ λ˜λŠ” Pillow μ—†μŒ β†’ 원본 전솑
187
+ await message.reply(files=[discord.File(io.BytesIO(data), filename="image.webp")])
188
  return
189
 
190
+ # ───────────── μ‹€νŒ¨ μ‹œ URL 좜λ ₯ ─────────────
191
+ if remote_path:
192
+ await message.reply(content=remote_path)
193
+ else:
194
+ await message.reply("⚠️ 이미지λ₯Ό 전솑할 수 μ—†μŠ΅λ‹ˆλ‹€.")
 
 
 
 
195
 
196
  # ────────────────── μ‹€ν–‰ ────────────────────────
197
  if __name__ == "__main__":
198
+ replicate.Client(api_token=REPL_TOKEN) # ꡬ쑰 μœ μ§€
199
  ImageBot(intents=intents).run(TOKEN)