Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,27 +1,27 @@
|
|
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
|
5 |
|
6 |
# ── 환경 변수 ────────────────────────────────────────────────
|
7 |
-
TOKEN = os.getenv("DISCORD_TOKEN")
|
8 |
-
CHANNEL_ID = int(os.getenv("DISCORD_CHANNEL_ID"))
|
9 |
-
REPL_TOKEN = (os.getenv("OPENAI_API_KEY") or "").strip()
|
10 |
-
HF_TOKEN = (os.getenv("HF_TOKEN") or "").strip()
|
11 |
|
12 |
if not TOKEN or not CHANNEL_ID:
|
13 |
raise RuntimeError("DISCORD_TOKEN 과 DISCORD_CHANNEL_ID 환경 변수를 모두 지정하세요.")
|
14 |
if not REPL_TOKEN:
|
15 |
raise RuntimeError("OPENAI_API_KEY 에 Replicate Personal Access Token 값을 넣어주세요.")
|
16 |
|
17 |
-
os.environ["REPLICATE_API_TOKEN"] = REPL_TOKEN
|
18 |
|
19 |
# ── Gradio 서버 ─────────────────────────────────────────────
|
20 |
GRADIO_URL = "http://211.233.58.201:7896"
|
21 |
GRADIO_API = "/generate_image"
|
22 |
DUMMY_IMG = "https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png"
|
23 |
|
24 |
-
# ── 번역 파이프라인
|
25 |
translator = transformers_pipeline(
|
26 |
"translation",
|
27 |
model="Helsinki-NLP/opus-mt-ko-en",
|
@@ -29,28 +29,32 @@ translator = transformers_pipeline(
|
|
29 |
**({"token": HF_TOKEN} if HF_TOKEN else {})
|
30 |
)
|
31 |
|
32 |
-
def
|
33 |
-
"""한글 포함 시
|
34 |
-
if re.search(r"[가-힣]", text):
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
40 |
|
41 |
# ── 로깅 ────────────────────────────────────────────────────
|
42 |
logging.basicConfig(level=logging.INFO,
|
43 |
-
format="%(asctime)s [%(levelname)s] %(message)s"
|
44 |
-
handlers=[logging.StreamHandler()])
|
45 |
|
46 |
# ── Discord 인텐트 ──────────────────────────────────────────
|
47 |
intents = discord.Intents.default()
|
48 |
-
intents.message_content = True #
|
49 |
|
50 |
class ImageBot(discord.Client):
|
51 |
async def on_ready(self):
|
52 |
logging.info(f"Logged in as {self.user} (id={self.user.id})")
|
53 |
-
# web.py 병렬 실행
|
54 |
try:
|
55 |
subprocess.Popen(["python", "web.py"])
|
56 |
logging.info("web.py server has been started.")
|
@@ -65,27 +69,23 @@ class ImageBot(discord.Client):
|
|
65 |
if not prompt_raw:
|
66 |
return
|
67 |
|
68 |
-
prompt_en =
|
69 |
await message.channel.typing()
|
70 |
|
71 |
-
# ── Gradio 호출
|
72 |
def generate_image():
|
73 |
client = Client(GRADIO_URL)
|
74 |
-
|
75 |
-
result = client.predict(
|
76 |
prompt=prompt_en,
|
77 |
-
width=768,
|
78 |
-
|
79 |
-
|
80 |
-
inference_steps=30,
|
81 |
-
seed=seed,
|
82 |
do_img2img=False,
|
83 |
-
init_image={"url": DUMMY_IMG},
|
84 |
image2image_strength=0.8,
|
85 |
resize_img=True,
|
86 |
api_name=GRADIO_API
|
87 |
-
)
|
88 |
-
return result[0] # dict(path|url)
|
89 |
|
90 |
try:
|
91 |
img_info = await asyncio.get_running_loop().run_in_executor(None, generate_image)
|
|
|
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
|
5 |
|
6 |
# ── 환경 변수 ────────────────────────────────────────────────
|
7 |
+
TOKEN = os.getenv("DISCORD_TOKEN")
|
8 |
+
CHANNEL_ID = int(os.getenv("DISCORD_CHANNEL_ID"))
|
9 |
+
REPL_TOKEN = (os.getenv("OPENAI_API_KEY") or "").strip()
|
10 |
+
HF_TOKEN = (os.getenv("HF_TOKEN") or "").strip()
|
11 |
|
12 |
if not TOKEN or not CHANNEL_ID:
|
13 |
raise RuntimeError("DISCORD_TOKEN 과 DISCORD_CHANNEL_ID 환경 변수를 모두 지정하세요.")
|
14 |
if not REPL_TOKEN:
|
15 |
raise RuntimeError("OPENAI_API_KEY 에 Replicate Personal Access Token 값을 넣어주세요.")
|
16 |
|
17 |
+
os.environ["REPLICATE_API_TOKEN"] = REPL_TOKEN # 구조 유지
|
18 |
|
19 |
# ── Gradio 서버 ─────────────────────────────────────────────
|
20 |
GRADIO_URL = "http://211.233.58.201:7896"
|
21 |
GRADIO_API = "/generate_image"
|
22 |
DUMMY_IMG = "https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png"
|
23 |
|
24 |
+
# ── 번역 파이프라인(마리안, CPU) ────────────────────────────
|
25 |
translator = transformers_pipeline(
|
26 |
"translation",
|
27 |
model="Helsinki-NLP/opus-mt-ko-en",
|
|
|
29 |
**({"token": HF_TOKEN} if HF_TOKEN else {})
|
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()
|
37 |
+
try:
|
38 |
+
result = await loop.run_in_executor(
|
39 |
+
None,
|
40 |
+
lambda: translator(text, max_length=256, num_beams=1)[0]["translation_text"].strip()
|
41 |
+
)
|
42 |
+
return result
|
43 |
+
except Exception as e:
|
44 |
+
logging.warning(f"번역 실패, 원문 사용: {e}")
|
45 |
+
return text
|
46 |
|
47 |
# ── 로깅 ────────────────────────────────────────────────────
|
48 |
logging.basicConfig(level=logging.INFO,
|
49 |
+
format="%(asctime)s [%(levelname)s] %(message)s")
|
|
|
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):
|
57 |
logging.info(f"Logged in as {self.user} (id={self.user.id})")
|
|
|
58 |
try:
|
59 |
subprocess.Popen(["python", "web.py"])
|
60 |
logging.info("web.py server has been started.")
|
|
|
69 |
if not prompt_raw:
|
70 |
return
|
71 |
|
72 |
+
prompt_en = await ko2en_async(prompt_raw) # ✔️ 비동기 번역
|
73 |
await message.channel.typing()
|
74 |
|
75 |
+
# ── Gradio 호출 (블로킹 → executor) ─────────────────
|
76 |
def generate_image():
|
77 |
client = Client(GRADIO_URL)
|
78 |
+
return client.predict(
|
|
|
79 |
prompt=prompt_en,
|
80 |
+
width=768, height=768,
|
81 |
+
guidance=3.5, inference_steps=30,
|
82 |
+
seed=random.randint(0, 2**32 - 1),
|
|
|
|
|
83 |
do_img2img=False,
|
84 |
+
init_image={"url": DUMMY_IMG},
|
85 |
image2image_strength=0.8,
|
86 |
resize_img=True,
|
87 |
api_name=GRADIO_API
|
88 |
+
)[0] # dict(path|url)
|
|
|
89 |
|
90 |
try:
|
91 |
img_info = await asyncio.get_running_loop().run_in_executor(None, generate_image)
|