Spaces:
Running
Running
Upload telegram_bot.py with huggingface_hub
Browse files- telegram_bot.py +60 -9
telegram_bot.py
CHANGED
|
@@ -102,10 +102,58 @@ def test_telegram_connectivity() -> bool:
|
|
| 102 |
def send_telegram_message(chat_id: int, text: str):
|
| 103 |
send_telegram_request("sendMessage", {"chat_id": chat_id, "text": text})
|
| 104 |
|
| 105 |
-
def send_telegram_photo(chat_id: int,
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
if not res or not res.get("ok"):
|
| 108 |
-
send_telegram_message(chat_id, f"🎨 Image generated: {
|
| 109 |
|
| 110 |
def call_kora_chat(prompt: str, model: str = "kora-chat-0.5b") -> str:
|
| 111 |
# 1. Try direct in-memory generation if running within gateway process
|
|
@@ -161,13 +209,13 @@ def call_kora_chat(prompt: str, model: str = "kora-chat-0.5b") -> str:
|
|
| 161 |
continue
|
| 162 |
return "Hello! I am Kora AI. How can I assist you today?"
|
| 163 |
|
| 164 |
-
def call_kora_image(prompt: str) ->
|
| 165 |
# 1. Try direct in-memory local PyTorch Stable Diffusion generation
|
| 166 |
try:
|
| 167 |
from vision.image_generator import generate_image
|
| 168 |
res = generate_image(prompt)
|
| 169 |
if res and res.get("success"):
|
| 170 |
-
return res
|
| 171 |
except Exception as err:
|
| 172 |
print(f"ℹ️ In-memory image generation notice: {err}", flush=True)
|
| 173 |
|
|
@@ -178,10 +226,10 @@ def call_kora_image(prompt: str) -> str:
|
|
| 178 |
req = urllib.request.Request(url, data=req_data, headers={"Content-Type": "application/json"})
|
| 179 |
with urllib.request.urlopen(req, timeout=30) as resp:
|
| 180 |
data = json.loads(resp.read().decode("utf-8"))
|
| 181 |
-
return data["data"][0]["url"]
|
| 182 |
except Exception:
|
| 183 |
pass
|
| 184 |
-
return
|
| 185 |
|
| 186 |
def handle_update(update: dict, token: str = None):
|
| 187 |
global BOT_TOKEN
|
|
@@ -218,8 +266,11 @@ def handle_update(update: dict, token: str = None):
|
|
| 218 |
)
|
| 219 |
return
|
| 220 |
send_telegram_message(chat_id, f"🎨 Generating zero-watermark image for: {prompt}...")
|
| 221 |
-
|
| 222 |
-
|
|
|
|
|
|
|
|
|
|
| 223 |
elif text.startswith("/code"):
|
| 224 |
prompt = text.replace("/code", "").strip() or "Write a Python function to demonstrate binary search"
|
| 225 |
send_telegram_message(chat_id, "💻 Generating code with Kora Coder...")
|
|
|
|
| 102 |
def send_telegram_message(chat_id: int, text: str):
|
| 103 |
send_telegram_request("sendMessage", {"chat_id": chat_id, "text": text})
|
| 104 |
|
| 105 |
+
def send_telegram_photo(chat_id: int, photo_path_or_url: str, caption: str = ""):
|
| 106 |
+
if not BOT_TOKEN or not photo_path_or_url:
|
| 107 |
+
return
|
| 108 |
+
|
| 109 |
+
# 1. If photo_path_or_url is a local file or relative path, upload binary file bytes directly
|
| 110 |
+
local_file = photo_path_or_url
|
| 111 |
+
if not os.path.exists(local_file) and "generated_assets" in photo_path_or_url:
|
| 112 |
+
filename = photo_path_or_url.split("/")[-1]
|
| 113 |
+
potential = os.path.join("public", "generated_assets", filename)
|
| 114 |
+
if os.path.exists(potential):
|
| 115 |
+
local_file = potential
|
| 116 |
+
|
| 117 |
+
if os.path.exists(local_file):
|
| 118 |
+
try:
|
| 119 |
+
import mimetypes, uuid
|
| 120 |
+
boundary = f"----FormBoundary{uuid.uuid4().hex}"
|
| 121 |
+
|
| 122 |
+
with open(local_file, "rb") as f:
|
| 123 |
+
img_bytes = f.read()
|
| 124 |
+
|
| 125 |
+
filename = os.path.basename(local_file)
|
| 126 |
+
mime_type = mimetypes.guess_type(filename)[0] or "image/png"
|
| 127 |
+
|
| 128 |
+
body = bytearray()
|
| 129 |
+
# chat_id field
|
| 130 |
+
body.extend(f"--{boundary}\r\nContent-Disposition: form-data; name=\"chat_id\"\r\n\r\n{chat_id}\r\n".encode("utf-8"))
|
| 131 |
+
# caption field
|
| 132 |
+
if caption:
|
| 133 |
+
body.extend(f"--{boundary}\r\nContent-Disposition: form-data; name=\"caption\"\r\n\r\n{caption}\r\n".encode("utf-8"))
|
| 134 |
+
# photo file field
|
| 135 |
+
body.extend(f"--{boundary}\r\nContent-Disposition: form-data; name=\"photo\"; filename=\"{filename}\"\r\nContent-Type: {mime_type}\r\n\r\n".encode("utf-8"))
|
| 136 |
+
body.extend(img_bytes)
|
| 137 |
+
body.extend(f"\r\n--{boundary}--\r\n".encode("utf-8"))
|
| 138 |
+
|
| 139 |
+
headers = {
|
| 140 |
+
"Content-Type": f"multipart/form-data; boundary={boundary}",
|
| 141 |
+
"User-Agent": "KoraBot/1.0 (Kontyra AI Ecosystem)"
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
direct_url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendPhoto"
|
| 145 |
+
req = urllib.request.Request(direct_url, data=body, headers=headers)
|
| 146 |
+
with urllib.request.urlopen(req, timeout=25) as resp:
|
| 147 |
+
res = json.loads(resp.read().decode("utf-8"))
|
| 148 |
+
if res.get("ok"):
|
| 149 |
+
return
|
| 150 |
+
except Exception as e:
|
| 151 |
+
print(f"⚠️ Binary photo upload notice: {e}", flush=True)
|
| 152 |
+
|
| 153 |
+
# 2. Fallback to URL sendPhoto
|
| 154 |
+
res = send_telegram_request("sendPhoto", {"chat_id": chat_id, "photo": photo_path_or_url, "caption": caption}, timeout_sec=15.0)
|
| 155 |
if not res or not res.get("ok"):
|
| 156 |
+
send_telegram_message(chat_id, f"🎨 Image generated: {photo_path_or_url}")
|
| 157 |
|
| 158 |
def call_kora_chat(prompt: str, model: str = "kora-chat-0.5b") -> str:
|
| 159 |
# 1. Try direct in-memory generation if running within gateway process
|
|
|
|
| 209 |
continue
|
| 210 |
return "Hello! I am Kora AI. How can I assist you today?"
|
| 211 |
|
| 212 |
+
def call_kora_image(prompt: str) -> dict:
|
| 213 |
# 1. Try direct in-memory local PyTorch Stable Diffusion generation
|
| 214 |
try:
|
| 215 |
from vision.image_generator import generate_image
|
| 216 |
res = generate_image(prompt)
|
| 217 |
if res and res.get("success"):
|
| 218 |
+
return res
|
| 219 |
except Exception as err:
|
| 220 |
print(f"ℹ️ In-memory image generation notice: {err}", flush=True)
|
| 221 |
|
|
|
|
| 226 |
req = urllib.request.Request(url, data=req_data, headers={"Content-Type": "application/json"})
|
| 227 |
with urllib.request.urlopen(req, timeout=30) as resp:
|
| 228 |
data = json.loads(resp.read().decode("utf-8"))
|
| 229 |
+
return {"direct_url": data["data"][0]["url"]}
|
| 230 |
except Exception:
|
| 231 |
pass
|
| 232 |
+
return {}
|
| 233 |
|
| 234 |
def handle_update(update: dict, token: str = None):
|
| 235 |
global BOT_TOKEN
|
|
|
|
| 266 |
)
|
| 267 |
return
|
| 268 |
send_telegram_message(chat_id, f"🎨 Generating zero-watermark image for: {prompt}...")
|
| 269 |
+
img_res = call_kora_image(prompt)
|
| 270 |
+
file_path = img_res.get("file_path", "")
|
| 271 |
+
direct_url = img_res.get("direct_url", "")
|
| 272 |
+
photo_target = file_path if (file_path and os.path.exists(file_path)) else direct_url
|
| 273 |
+
send_telegram_photo(chat_id, photo_path_or_url=photo_target, caption=f"✨ {prompt}")
|
| 274 |
elif text.startswith("/code"):
|
| 275 |
prompt = text.replace("/code", "").strip() or "Write a Python function to demonstrate binary search"
|
| 276 |
send_telegram_message(chat_id, "💻 Generating code with Kora Coder...")
|