Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,24 +1,25 @@
|
|
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 |
|
23 |
# ── 번역 파이프라인 (CPU) ───────────────────────────────────
|
24 |
translator = transformers_pipeline(
|
@@ -29,6 +30,7 @@ translator = transformers_pipeline(
|
|
29 |
)
|
30 |
|
31 |
def ko2en(text: str) -> str:
|
|
|
32 |
if re.search(r"[가-힣]", text):
|
33 |
try:
|
34 |
return translator(text, max_length=512)[0]["translation_text"].strip()
|
@@ -38,16 +40,17 @@ def ko2en(text: str) -> str:
|
|
38 |
|
39 |
# ── 로깅 ────────────────────────────────────────────────────
|
40 |
logging.basicConfig(level=logging.INFO,
|
41 |
-
format="%(asctime)s [%(levelname)s] %(message)s"
|
|
|
42 |
|
43 |
-
# ── Discord 인텐트
|
44 |
intents = discord.Intents.default()
|
45 |
-
intents.message_content = True
|
46 |
-
logging.info("Message Content Intent = ON (Portal → Bot → Privileged Intents 에서도 ON 필요)")
|
47 |
|
48 |
class ImageBot(discord.Client):
|
49 |
async def on_ready(self):
|
50 |
logging.info(f"Logged in as {self.user} (id={self.user.id})")
|
|
|
51 |
try:
|
52 |
subprocess.Popen(["python", "web.py"])
|
53 |
logging.info("web.py server has been started.")
|
@@ -77,12 +80,12 @@ class ImageBot(discord.Client):
|
|
77 |
inference_steps=30,
|
78 |
seed=seed,
|
79 |
do_img2img=False,
|
80 |
-
init_image={},
|
81 |
image2image_strength=0.8,
|
82 |
resize_img=True,
|
83 |
api_name=GRADIO_API
|
84 |
)
|
85 |
-
return result[0]
|
86 |
|
87 |
try:
|
88 |
img_info = await asyncio.get_running_loop().run_in_executor(None, generate_image)
|
@@ -100,8 +103,6 @@ class ImageBot(discord.Client):
|
|
100 |
elif img_info.get("url"):
|
101 |
data = requests.get(img_info["url"]).content
|
102 |
files.append(discord.File(io.BytesIO(data), filename="generated.webp"))
|
103 |
-
else:
|
104 |
-
raise ValueError("No image data returned")
|
105 |
except Exception as e:
|
106 |
logging.warning(f"이미지 처리 실패: {e}")
|
107 |
|
@@ -110,5 +111,5 @@ class ImageBot(discord.Client):
|
|
110 |
|
111 |
# ── 실행 ────────────────────────────────────────────────────
|
112 |
if __name__ == "__main__":
|
113 |
-
replicate.Client(api_token=REPL_TOKEN)
|
114 |
ImageBot(intents=intents).run(TOKEN)
|
|
|
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 # Gradio API
|
5 |
|
6 |
# ── 환경 변수 ────────────────────────────────────────────────
|
7 |
+
TOKEN = os.getenv("DISCORD_TOKEN") # Discord 봇 토큰
|
8 |
+
CHANNEL_ID = int(os.getenv("DISCORD_CHANNEL_ID")) # 감시할 채널 ID
|
9 |
+
REPL_TOKEN = (os.getenv("OPENAI_API_KEY") or "").strip()# Replicate 토큰(구조 유지)
|
10 |
+
HF_TOKEN = (os.getenv("HF_TOKEN") or "").strip() # Hugging-Face 토큰(옵션)
|
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(
|
|
|
30 |
)
|
31 |
|
32 |
def ko2en(text: str) -> str:
|
33 |
+
"""한글 포함 시 영어로 번역."""
|
34 |
if re.search(r"[가-힣]", text):
|
35 |
try:
|
36 |
return translator(text, max_length=512)[0]["translation_text"].strip()
|
|
|
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 # 항상 ON (포털에서도 Message-Content Intent ON)
|
|
|
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.")
|
|
|
80 |
inference_steps=30,
|
81 |
seed=seed,
|
82 |
do_img2img=False,
|
83 |
+
init_image={"url": DUMMY_IMG}, # 필수 placeholder
|
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)
|
|
|
103 |
elif img_info.get("url"):
|
104 |
data = requests.get(img_info["url"]).content
|
105 |
files.append(discord.File(io.BytesIO(data), filename="generated.webp"))
|
|
|
|
|
106 |
except Exception as e:
|
107 |
logging.warning(f"이미지 처리 실패: {e}")
|
108 |
|
|
|
111 |
|
112 |
# ── 실행 ────────────────────────────────────────────────────
|
113 |
if __name__ == "__main__":
|
114 |
+
replicate.Client(api_token=REPL_TOKEN) # 구조 유지(실제 사용 안 함)
|
115 |
ImageBot(intents=intents).run(TOKEN)
|