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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -35
app.py CHANGED
@@ -1,13 +1,11 @@
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
6
- 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")
@@ -19,7 +17,7 @@ if not TOKEN or not CHANNEL_ID:
19
  raise RuntimeError("DISCORD_TOKEN κ³Ό DISCORD_CHANNEL_ID ν™˜κ²½ λ³€μˆ˜λ₯Ό λͺ¨λ‘ μ§€μ •ν•˜μ„Έμš”.")
20
  if not REPL_TOKEN:
21
  raise RuntimeError("OPENAI_API_KEY 에 Replicate Personal Access Token 값을 λ„£μ–΄μ£Όμ„Έμš”.")
22
- os.environ["REPLICATE_API_TOKEN"] = REPL_TOKEN # Replicate λ―Έμ‚¬μš©μ΄μ§€λ§Œ ꡬ쑰 μœ μ§€
23
 
24
  # ────────────────── Gradio μ„œλ²„ ─────────────────
25
  GRADIO_URL = "http://211.233.58.201:7971"
@@ -34,7 +32,6 @@ translator = transformers_pipeline(
34
  )
35
 
36
  async def ko2en_async(text: str) -> str:
37
- """ν•œκΈ€ 포함 μ‹œ μ˜μ–΄ λ²ˆμ—­(비동기)."""
38
  if not re.search(r"[κ°€-힣]", text):
39
  return text
40
  loop = asyncio.get_running_loop()
@@ -98,40 +95,34 @@ class ImageBot(discord.Client):
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:
@@ -140,22 +131,22 @@ class ImageBot(discord.Client):
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:
@@ -173,7 +164,6 @@ class ImageBot(discord.Client):
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
  # ────────────────── μ‹€ν–‰ ────────────────────────
 
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
  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
  )
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
  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
121
 
122
+ # str κ²°κ³Ό
123
  elif isinstance(result, str):
124
  s = result.strip()
125
  if s.startswith("data:"):
 
126
  try:
127
  data = base64.b64decode(re.sub(r"^data:image/[^;]+;base64,", "", s))
128
  except Exception as e:
 
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:
139
  data = f.read()
140
+ except Exception:
141
+ pass
142
 
143
+ # URL λ‹€μš΄λ‘œλ“œ (β˜… 헀더 검사 제거)
144
  for u in candidate_urls:
145
  if data:
146
  break
147
  try:
148
  r = requests.get(u, timeout=10)
149
+ if r.ok and r.content:
150
  data = r.content
151
  break
152
  except Exception as e:
 
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
  # ────────────────── μ‹€ν–‰ ────────────────────────