fantos commited on
Commit
2cfdf65
Β·
verified Β·
1 Parent(s): b0940a1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -36
app.py CHANGED
@@ -1,6 +1,6 @@
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
 
@@ -30,6 +30,7 @@ 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()
@@ -44,8 +45,8 @@ async def ko2en_async(text: str) -> str:
44
 
45
  # ── λ‘œκΉ… ────────────────────────────────────────────────────
46
  logging.basicConfig(level=logging.INFO,
47
- format="%(asctime)s [%(levelname)s] %(message)s",
48
- handlers=[logging.StreamHandler()])
49
 
50
  # ── Discord μΈν…νŠΈ ──────────────────────────────────────────
51
  intents = discord.Intents.default()
@@ -82,54 +83,73 @@ class ImageBot(discord.Client):
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("⚠️ 이미지 생성 μ‹€νŒ¨!")
93
  return
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,
131
- content=None if files else "⚠️ 이미지λ₯Ό 전솑할 수 μ—†μŠ΅λ‹ˆλ‹€."
132
- )
133
 
134
  # ── μ‹€ν–‰ ────────────────────────────────────────────────────
135
  if __name__ == "__main__":
 
1
  # img_bot.py
2
  import discord, os, io, re, random, asyncio, logging, requests, replicate, subprocess, base64
3
+ from urllib.parse import urljoin, quote_plus
4
  from transformers import pipeline as transformers_pipeline
5
  from gradio_client import Client
6
 
 
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()
 
45
 
46
  # ── λ‘œκΉ… ────────────────────────────────────────────────────
47
  logging.basicConfig(level=logging.INFO,
48
+ format="%(asctime)s [%(levelname)s] %(message)s",
49
+ handlers=[logging.StreamHandler()])
50
 
51
  # ── Discord μΈν…νŠΈ ──────────────────────────────────────────
52
  intents = discord.Intents.default()
 
83
  prompt=prompt_en,
84
  seed=random.randint(0, 2**32 - 1),
85
  api_name=GRADIO_API
86
+ ) # ❗ λ¦¬μŠ€νŠΈλ‚˜ dictΒ·str κ·ΈλŒ€λ‘œ λ°˜ν™˜
87
 
88
  try:
89
  img_info = await asyncio.get_running_loop().run_in_executor(None, generate_image)
90
+ logging.info(f"Gradio result type={type(img_info)} β†’ {img_info}")
91
  except Exception as e:
92
  logging.error(f"Gradio API error: {e}")
93
  await message.reply("⚠️ 이미지 생성 μ‹€νŒ¨!")
94
  return
95
 
96
+ # ── Discord 파일 μ€€λΉ„ ──────────────────────────────
 
97
  data = None
98
+ filename = "generated.webp"
99
+
100
+ def download(url: str) -> bytes | None:
101
+ try:
102
+ return requests.get(url, timeout=10).content
103
+ except Exception as err:
104
+ logging.warning(f"URL λ‹€μš΄λ‘œλ“œ μ‹€νŒ¨({url}): {err}")
105
+ return None
106
+
107
+ # β‘  `img_info` κ°€ 리슀트면 첫 μš”μ†Œ μ‚¬μš©
108
+ if isinstance(img_info, list) and img_info:
109
+ img_info = img_info[0]
110
+
111
+ # β‘‘ dict
112
+ if isinstance(img_info, dict):
113
+ # url μš°μ„ 
114
+ url = img_info.get("url")
115
+ if url:
116
+ if url.startswith("data:"):
117
+ try:
118
+ data = base64.b64decode(re.sub(r"^data:image/[^;]+;base64,", "", url))
119
+ except Exception as e:
120
+ logging.warning(f"base64 λ””μ½”λ”© μ‹€νŒ¨: {e}")
121
+ else:
122
+ if url.startswith("/"):
123
+ url = urljoin(GRADIO_URL, url)
124
+ data = download(url)
125
+ # path 보쑰
126
+ if data is None:
127
+ path = img_info.get("path")
128
+ if path:
129
+ # 원격 Gradio 파일 end-point
130
+ remote_url = urljoin(GRADIO_URL, f"/gradio_api/file={quote_plus(path)}")
131
+ data = download(remote_url) or (open(path, "rb").read() if os.path.isfile(path) else None)
132
+
133
+ # β‘’ str (둜컬 경둜/URL/data URI)
134
+ elif isinstance(img_info, str):
135
+ s = img_info.strip()
136
+ if s.startswith("data:"):
137
  try:
138
+ data = base64.b64decode(re.sub(r"^data:image/[^;]+;base64,", "", s))
139
  except Exception as e:
140
  logging.warning(f"base64 λ””μ½”λ”© μ‹€νŒ¨: {e}")
141
+ elif s.startswith("http"):
142
+ data = download(s)
143
  else:
144
+ # 원격 파일둜 κ°„μ£Ό
145
+ remote_url = urljoin(GRADIO_URL, f"/gradio_api/file={quote_plus(s)}")
146
+ data = download(remote_url) or (open(s, "rb").read() if os.path.isfile(s) else None)
 
 
 
 
 
 
 
 
 
 
 
 
 
147
 
148
+ # ── Discord 전솑 ──────────────────────────────────
149
  if data:
150
+ await message.reply(files=[discord.File(io.BytesIO(data), filename=filename)])
151
+ else:
152
+ await message.reply("⚠️ 이미지λ₯Ό 전솑할 수 μ—†μŠ΅λ‹ˆλ‹€.")
 
 
 
153
 
154
  # ── μ‹€ν–‰ ────────────────────────────────────────────────────
155
  if __name__ == "__main__":