fantos commited on
Commit
2473562
Β·
verified Β·
1 Parent(s): c3a9e90

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -31
app.py CHANGED
@@ -7,7 +7,7 @@ import requests
7
  import replicate
8
  from transformers import pipeline as transformers_pipeline
9
  from gradio_client import Client
10
- from PIL import Image # WEBP β†’ PNG λ³€ν™˜μš©
11
 
12
  # ────────────────── ν™˜κ²½ λ³€μˆ˜ ──────────────────
13
  TOKEN = os.getenv("DISCORD_TOKEN")
@@ -98,57 +98,82 @@ class ImageBot(discord.Client):
98
  await message.reply("⚠️ 이미지 생성 μ‹€νŒ¨!")
99
  return
100
 
101
- # Gradio κ²°κ³Ό β†’ list / dict / str 쀑 첫 μš”μ†Œλ‘œ μ •κ·œν™”
102
  if isinstance(result, list):
103
  result = result[0]
104
 
105
- # ───────────── URL 있으면 링크둜 전솑 ─────────────
106
- url = None
107
- if isinstance(result, dict):
108
- url = result.get("url")
109
- if url and url.startswith("/"):
110
- url = urljoin(GRADIO_URL, url)
111
- elif isinstance(result, str) and result.startswith(("http", "/")):
112
- url = result if result.startswith("http") else urljoin(GRADIO_URL, result)
113
-
114
- if url:
115
- await message.reply(content=url) # Discordκ°€ embed 미리보기
116
- return
117
-
118
- # ───────────── 첨뢀 파일 μ€€λΉ„ ─────────────
119
  data = None
120
- # dict β†’ path
 
 
121
  if isinstance(result, dict):
 
 
 
 
 
 
 
122
  path = result.get("path")
123
  if path:
124
- # Gradio 파일 λ‹€μš΄λ‘œλ“œ μš°μ„ 
125
- remote = urljoin(GRADIO_URL, f"/gradio_api/file={quote_plus(path)}")
126
- try:
127
- data = requests.get(remote, timeout=10).content
128
- except Exception:
129
- if os.path.isfile(path):
130
  with open(path, "rb") as f:
131
  data = f.read()
132
- # str β†’ data URI
133
- elif isinstance(result, str) and result.startswith("data:"):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  try:
135
- b64 = re.sub(r"^data:image/[^;]+;base64,", "", result)
136
- data = base64.b64decode(b64)
 
 
137
  except Exception as e:
138
- logging.warning(f"base64 λ””μ½”λ”© μ‹€νŒ¨: {e}")
139
 
140
  if not data:
141
  await message.reply("⚠️ 이미지λ₯Ό 전솑할 수 μ—†μŠ΅λ‹ˆλ‹€.")
142
  return
143
 
144
- # ───────────── WEBP β†’ PNG λ³€ν™˜ (미리보기용) ─────────────
145
  buf = io.BytesIO()
146
  try:
147
  Image.open(io.BytesIO(data)).convert("RGB").save(buf, format="PNG")
148
  buf.seek(0)
149
  await message.reply(files=[discord.File(buf, filename="image.png")])
150
- except Exception:
151
- # λ³€ν™˜ μ‹€νŒ¨ μ‹œ 원본 κ·ΈλŒ€λ‘œ
 
152
  await message.reply(files=[discord.File(io.BytesIO(data), filename="image.webp")])
153
 
154
  # ────────────────── μ‹€ν–‰ ────────────────────────
 
7
  import replicate
8
  from transformers import pipeline as transformers_pipeline
9
  from gradio_client import Client
10
+ from PIL import Image # WEBP β†’ PNG λ³€ν™˜μš©
11
 
12
  # ────────────────── ν™˜κ²½ λ³€μˆ˜ ──────────────────
13
  TOKEN = os.getenv("DISCORD_TOKEN")
 
98
  await message.reply("⚠️ 이미지 생성 μ‹€νŒ¨!")
99
  return
100
 
101
+ # κ²°κ³Ό μ •κ·œν™”(list β†’ 첫 μš”μ†Œ)
102
  if isinstance(result, list):
103
  result = result[0]
104
 
105
+ # ───────────── 이미지 데이터 확보 ─────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  data = None
107
+ candidate_urls = []
108
+
109
+ # dict 결과 처리
110
  if isinstance(result, dict):
111
+ # url ν•„λ“œ
112
+ url = result.get("url")
113
+ if url:
114
+ if url.startswith("/"):
115
+ url = urljoin(GRADIO_URL, url)
116
+ candidate_urls.append(url)
117
+ # path ν•„λ“œ
118
  path = result.get("path")
119
  if path:
120
+ # β‘  원격 Gradio 파일 경둜
121
+ candidate_urls.append(urljoin(GRADIO_URL, f"/gradio_api/file={quote_plus(path)}"))
122
+ # β‘‘ 둜컬 파일 경둜
123
+ if os.path.isfile(path):
124
+ try:
 
125
  with open(path, "rb") as f:
126
  data = f.read()
127
+ except Exception as e:
128
+ logging.warning(f"둜컬 파일 μ—΄κΈ° μ‹€νŒ¨: {e}")
129
+
130
+ # str 결과 처리
131
+ elif isinstance(result, str):
132
+ s = result.strip()
133
+ if s.startswith("data:"):
134
+ # data URI
135
+ try:
136
+ data = base64.b64decode(re.sub(r"^data:image/[^;]+;base64,", "", s))
137
+ except Exception as e:
138
+ logging.warning(f"base64 λ””μ½”λ”© μ‹€νŒ¨: {e}")
139
+ elif s.startswith("http"):
140
+ candidate_urls.append(s)
141
+ elif s.startswith("/"):
142
+ candidate_urls.append(urljoin(GRADIO_URL, s))
143
+ else: # 둜컬/원격 tmp 경둜
144
+ candidate_urls.append(urljoin(GRADIO_URL, f"/gradio_api/file={quote_plus(s)}"))
145
+ if os.path.isfile(s):
146
+ try:
147
+ with open(s, "rb") as f:
148
+ data = f.read()
149
+ except Exception as e:
150
+ logging.warning(f"둜컬 파일 μ—΄κΈ° μ‹€νŒ¨: {e}")
151
+
152
+ # URL λͺ©λ‘μ—μ„œ λ‹€μš΄λ‘œλ“œ
153
+ for u in candidate_urls:
154
+ if data:
155
+ break
156
  try:
157
+ r = requests.get(u, timeout=10)
158
+ if r.ok and r.headers.get("content-type", "").startswith("image/"):
159
+ data = r.content
160
+ break
161
  except Exception as e:
162
+ logging.warning(f"URL λ‹€μš΄λ‘œλ“œ μ‹€νŒ¨({u}): {e}")
163
 
164
  if not data:
165
  await message.reply("⚠️ 이미지λ₯Ό 전솑할 수 μ—†μŠ΅λ‹ˆλ‹€.")
166
  return
167
 
168
+ # ───────────── WEBP β†’ PNG λ³€ν™˜ ─────────────
169
  buf = io.BytesIO()
170
  try:
171
  Image.open(io.BytesIO(data)).convert("RGB").save(buf, format="PNG")
172
  buf.seek(0)
173
  await message.reply(files=[discord.File(buf, filename="image.png")])
174
+ except Exception as e:
175
+ logging.warning(f"PNG λ³€ν™˜ μ‹€νŒ¨: {e}")
176
+ # λ³€ν™˜ μ‹€νŒ¨ β†’ 원본 ν™•μž₯자 μœ μ§€
177
  await message.reply(files=[discord.File(io.BytesIO(data), filename="image.webp")])
178
 
179
  # ────────────────── μ‹€ν–‰ ────────────────────────