Download bot.py from YourWeirdSenpai0709/deploythis: direct link, hf CLI and curl.
- Browser
- Download file 29.2 kB
-
https://huggingface.co/YourWeirdSenpai0709/deploythis/resolve/main/bot.py
- Command line
-
hf download hf://YourWeirdSenpai0709/deploythis/bot.py
-
curl -L -o bot.py https://huggingface.co/YourWeirdSenpai0709/deploythis/resolve/main/bot.py
29.2 kB
| #!/usr/bin/env python3 | |
| """Telegram front-end for ComfyUI running on the same pod. | |
| export TELEGRAM_TOKEN=... ALLOWED_CHAT_IDS=123456,789012 | |
| python bot.py | |
| Send a photo (as a file, not a photo β see below), then send text to generate. | |
| /settings opens the menus. Menus are built from ComfyUI's live /object_info, so | |
| a LoRA dropped into models/loras shows up with no restart. | |
| """ | |
| from __future__ import annotations | |
| import asyncio | |
| import functools | |
| import html | |
| import io | |
| import json | |
| import logging | |
| import os | |
| import pathlib | |
| import time | |
| from telegram import (InlineKeyboardButton, InlineKeyboardMarkup, InputFile, | |
| Update) | |
| from telegram.constants import ChatAction | |
| from telegram.ext import (Application, CallbackQueryHandler, CommandHandler, | |
| ContextTypes, MessageHandler, filters) | |
| from comfy_client import ComfyClient, ComfyError | |
| logging.basicConfig(level=logging.INFO, | |
| format="%(asctime)s %(levelname)s %(message)s") | |
| # httpx logs full request URLs at INFO, and Telegram's file endpoints embed the | |
| # bot token in the path β that would write your token into bot.log on every | |
| # download. Keep it at WARNING. | |
| logging.getLogger("httpx").setLevel(logging.WARNING) | |
| logging.getLogger("telegram.ext.Updater").setLevel(logging.WARNING) | |
| log = logging.getLogger("bot") | |
| TOKEN = os.environ["TELEGRAM_TOKEN"] | |
| ALLOWED = {int(x) for x in os.environ.get("ALLOWED_CHAT_IDS", "").split(",") if x} | |
| WORKFLOW = os.environ.get("WORKFLOW", "workflow_api.json") | |
| MAP = os.environ.get("WORKFLOW_MAP", "workflow_map.json") | |
| STATE_FILE = pathlib.Path(os.environ.get("STATE_FILE", "/workspace/bot_state.json")) | |
| # system_prompt None means "leave whatever the workflow file already has", | |
| # which is different from "" (explicitly blank). | |
| DEFAULTS = {"system_prompt": None, | |
| "aspect": None, "unet": None, "sampler_name": None, | |
| "scheduler": None, "steps": 13, "ref_boost": 6, "denoise": 1.0, | |
| "grounding_px": 768, "loras": [], "image": None} | |
| # name -> (node class to read the enum from, its field, settings key) | |
| # Anything whose options ComfyUI already knows goes here; the keyboard, the | |
| # text setter and /status all come for free. | |
| PICKERS = { | |
| "model": ("UNETLoader", "unet_name", "unet"), | |
| "aspect": ("ResolutionSelector", "aspect_ratio", "aspect"), | |
| "sampler": ("KSampler", "sampler_name", "sampler_name"), | |
| "scheduler": ("KSampler", "scheduler", "scheduler"), | |
| } | |
| MAX_BUTTONS = 20 | |
| # command -> (settings key, step, min, max, type) | |
| # Drives the text commands, the tap steppers and clamping from one place. | |
| NUMERICS = { | |
| "steps": ("steps", 1, 1, 60, int), | |
| "boost": ("ref_boost", 0.5, 0.0, 12.0, float), | |
| "grounding": ("grounding_px", 64, 256, 1536, int), | |
| "denoise": ("denoise", 0.05, 0.05, 1.0, float), | |
| } | |
| def clamp(name: str, value): | |
| _key, _step, lo, hi, cast = NUMERICS[name] | |
| v = cast(value) | |
| v = max(lo, min(hi, v)) | |
| return round(v, 2) if cast is float else v | |
| # Colon-separated. Point at every folder ComfyUI loads LoRAs from, including | |
| # any extra_model_paths entries. | |
| LORA_DIRS = [d for d in os.environ.get( | |
| "LORA_DIRS", "/workspace/comfy/ComfyUI/models/loras").split(":") if d] | |
| comfy = ComfyClient(host=os.environ.get("COMFY_HOST", "127.0.0.1:8188"), | |
| map_path=MAP, lora_dirs=LORA_DIRS) | |
| # One GPU, one job. Without this, two users queue simultaneously and the | |
| # websocket progress events interleave into the wrong chats. | |
| gpu = asyncio.Lock() | |
| # ------------------------------------------------------------------- state | |
| def load_state() -> dict: | |
| try: | |
| return json.loads(STATE_FILE.read_text()) | |
| except Exception: | |
| return {} | |
| def save_state(state: dict) -> None: | |
| try: | |
| STATE_FILE.write_text(json.dumps(state, indent=2)) | |
| except Exception as exc: | |
| log.warning("could not persist state: %s", exc) | |
| STATE = load_state() | |
| def settings_for(chat_id: int) -> dict: | |
| s = STATE.setdefault(str(chat_id), dict(DEFAULTS)) | |
| for k, v in DEFAULTS.items(): | |
| s.setdefault(k, v) | |
| return s | |
| def guard(fn): | |
| async def wrapper(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| chat = update.effective_chat | |
| if ALLOWED and chat.id not in ALLOWED: | |
| log.warning("rejected chat %s", chat.id) | |
| await chat.send_message( | |
| f"Not authorised. Your chat id is {chat.id}.") | |
| return | |
| return await fn(update, context) | |
| return wrapper | |
| # ------------------------------------------------------------------ menus | |
| async def options_of(picker: str) -> list[str]: | |
| cls, field, _key = PICKERS[picker] | |
| return await asyncio.to_thread(comfy.options_for, cls, field) | |
| async def pick_keyboard(picker: str, current) -> InlineKeyboardMarkup: | |
| opts = await options_of(picker) | |
| # Model filenames are long; short enums fit two per row. | |
| wide = max((len(o) for o in opts[:MAX_BUTTONS]), default=0) > 18 | |
| per_row = 1 if wide else 2 | |
| rows, row = [], [] | |
| for i, o in enumerate(opts[:MAX_BUTTONS]): | |
| mark = "\u2022 " if o == current else "" | |
| row.append(InlineKeyboardButton(f"{mark}{o[-36:]}", | |
| callback_data=f"pick:{picker}:{i}")) | |
| if len(row) == per_row: | |
| rows.append(row) | |
| row = [] | |
| if row: | |
| rows.append(row) | |
| if len(opts) > MAX_BUTTONS: | |
| rows.append([InlineKeyboardButton( | |
| f"...{len(opts) - MAX_BUTTONS} more \u2014 use /{picker} <text>", | |
| callback_data="close")]) | |
| return InlineKeyboardMarkup(rows) | |
| def menu_keyboard() -> InlineKeyboardMarkup: | |
| return InlineKeyboardMarkup( | |
| [[InlineKeyboardButton(p, callback_data=f"menu:{p}")] | |
| for p in PICKERS] + | |
| [[InlineKeyboardButton("numbers", callback_data="menu:numbers")], | |
| [InlineKeyboardButton("loras", callback_data="menu:loras")]]) | |
| def numbers_keyboard(chat_id: int) -> InlineKeyboardMarkup: | |
| """A -/+ row per numeric setting. The middle button is a live label, so | |
| tapping it does nothing but the value is always visible.""" | |
| s = settings_for(chat_id) | |
| rows = [] | |
| for name, (key, step, _lo, _hi, cast) in NUMERICS.items(): | |
| val = s[key] | |
| label = f"{name} {val:g}" if cast is float else f"{name} {val}" | |
| rows.append([ | |
| InlineKeyboardButton("\u2212", callback_data=f"num:{name}:-1"), | |
| InlineKeyboardButton(label, callback_data="noop"), | |
| InlineKeyboardButton("+", callback_data=f"num:{name}:1"), | |
| ]) | |
| rows.append([InlineKeyboardButton("done", callback_data="close")]) | |
| return InlineKeyboardMarkup(rows) | |
| async def lora_keyboard(chat_id: int) -> InlineKeyboardMarkup: | |
| available = await asyncio.to_thread(comfy.list_loras) | |
| active = {l["lora"]: l for l in settings_for(chat_id)["loras"]} | |
| rows = [] | |
| for i, name in enumerate(available[:40]): | |
| on = name in active | |
| strength = active[name]["strength"] if on else 1.0 | |
| label = f"{'β ' if on else 'β«οΈ'} {name.split('/')[-1][:28]}" | |
| if on: | |
| label += f" ({strength:g})" | |
| rows.append([InlineKeyboardButton(label, callback_data=f"lora:{i}")]) | |
| rows.append([InlineKeyboardButton("done", callback_data="close")]) | |
| return InlineKeyboardMarkup(rows) | |
| # --------------------------------------------------------------- commands | |
| async def cmd_start(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| await update.message.reply_text( | |
| "Send me a source photo (attach it as a *file*, not a photo β " | |
| "Telegram re-encodes photos and the artifacts hurt identity " | |
| "preservation). Then send text to generate.\n\n" | |
| "/settings β all menus\n/model /aspect /sampler /scheduler β pick " | |
| "from ComfyUI's live lists (add text to filter, e.g. `/model realism`)\n" | |
| "/numbers β tap \u2212/+ for steps, ref_boost, grounding_px, denoise\n" | |
| "/system β set a permanent system prompt (or just send a .txt file)\n" | |
| "/loras β toggle LoRAs\n/status β current settings\n" | |
| "/diag β check the map against the workflow\n" | |
| "/refresh β compare ComfyUI's LoRA list against what's on disk\n" | |
| "/reset β settings back to defaults (add `all` for every chat)\n" | |
| "/cancel β interrupt the running job", | |
| parse_mode="Markdown") | |
| async def cmd_status(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| s = settings_for(update.effective_chat.id) | |
| loras = "\n".join(f" β’ {l['lora']} @ {l['strength']:g}" | |
| for l in s["loras"]) or " (none)" | |
| await update.message.reply_text( | |
| f"image: {s['image'] or 'β none uploaded β'}\n" | |
| f"model: {s['unet'] or 'workflow default'}\n" | |
| f"aspect: {s['aspect'] or 'workflow default'}\n" | |
| f"sampler: {s['sampler_name'] or 'default'} " | |
| f"scheduler: {s['scheduler'] or 'default'}\n" | |
| f"steps: {s['steps']} ref_boost: {s['ref_boost']} " | |
| f"denoise: {s['denoise']}\ngrounding_px: {s['grounding_px']}\n" | |
| f"loras:\n{loras}") | |
| async def cmd_settings(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| await update.message.reply_text("What do you want to change?", | |
| reply_markup=menu_keyboard()) | |
| async def cmd_pick(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| """/model, /aspect, /sampler, /scheduler. | |
| Bare -> keyboard. With an argument -> substring match, which is how you | |
| reach options past the button limit without paging on a phone. | |
| """ | |
| picker = update.message.text.split()[0].lstrip("/").split("@")[0] | |
| key = PICKERS[picker][2] | |
| s = settings_for(update.effective_chat.id) | |
| if not context.args: | |
| await update.message.reply_text( | |
| f"{picker}: {s[key] or 'workflow default'}", | |
| reply_markup=await pick_keyboard(picker, s[key])) | |
| return | |
| needle = " ".join(context.args).lower() | |
| opts = await options_of(picker) | |
| hits = [o for o in opts if needle in o.lower()] | |
| if not hits: | |
| await update.message.reply_text( | |
| f"nothing matches {needle!r}. {len(opts)} available.") | |
| return | |
| if len(hits) > 1: | |
| exact = [o for o in hits if o.lower() == needle] | |
| if not exact: | |
| listing = "\n".join(f" {o}" for o in hits[:15]) | |
| await update.message.reply_text(f"ambiguous:\n{listing}") | |
| return | |
| hits = exact | |
| s[key] = hits[0] | |
| save_state(STATE) | |
| await update.message.reply_text(f"{picker} = {hits[0]}") | |
| async def cmd_loras(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| await update.message.reply_text( | |
| "Tap to toggle. Set strength with /strength <name> <value>.", | |
| reply_markup=await lora_keyboard(update.effective_chat.id)) | |
| def system_keyboard() -> InlineKeyboardMarkup: | |
| return InlineKeyboardMarkup([ | |
| [InlineKeyboardButton("set (send next message)", | |
| callback_data="sys:capture")], | |
| [InlineKeyboardButton("revert to workflow default", | |
| callback_data="sys:default")], | |
| [InlineKeyboardButton("clear (empty)", callback_data="sys:clear")], | |
| [InlineKeyboardButton("close", callback_data="close")], | |
| ]) | |
| def workflow_system_prompt() -> str | None: | |
| """Whatever the workflow file itself carries, via the map.""" | |
| target = comfy.map.get("system_prompt") | |
| if not target: | |
| return None | |
| try: | |
| wf = comfy.load_workflow(WORKFLOW) | |
| return wf[str(target["node"])]["inputs"].get(target["input"]) | |
| except Exception: | |
| return None | |
| async def cmd_system(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| """/system β show + buttons. /system <text> β set it now.""" | |
| s = settings_for(update.effective_chat.id) | |
| if context.args: | |
| arg = " ".join(context.args) | |
| if arg.strip().lower() == "default": | |
| s["system_prompt"] = None | |
| elif arg.strip().lower() == "clear": | |
| s["system_prompt"] = "" | |
| else: | |
| s["system_prompt"] = arg | |
| save_state(STATE) | |
| await update.message.reply_text( | |
| f"system prompt set ({len(s['system_prompt'] or '')} chars)" | |
| if s["system_prompt"] is not None else | |
| "system prompt reverted to the workflow's own value") | |
| return | |
| current = s["system_prompt"] | |
| if current is None: | |
| current = workflow_system_prompt() or "" | |
| source = "from workflow file" | |
| else: | |
| source = "custom" | |
| shown = current if len(current) <= 3000 else current[:3000] + "\nβ¦" | |
| body = html.escape(shown) or "(empty)" | |
| await update.message.reply_text( | |
| f"<b>system prompt</b> ({source}, {len(current)} chars)\n" | |
| f"<pre>{body}</pre>", | |
| parse_mode="HTML", reply_markup=system_keyboard()) | |
| async def on_text_file(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| """A .txt attachment becomes the system prompt β the practical way to move | |
| a 2000-character block onto the bot without typing it on a phone.""" | |
| doc = update.message.document | |
| tg_file = await doc.get_file() | |
| buf = io.BytesIO() | |
| await tg_file.download_to_memory(buf) | |
| text = buf.getvalue().decode("utf-8", errors="replace").strip() | |
| s = settings_for(update.effective_chat.id) | |
| s["system_prompt"] = text | |
| save_state(STATE) | |
| await update.message.reply_text( | |
| f"system prompt set from {doc.file_name} ({len(text)} chars)") | |
| async def cmd_numbers(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| await update.message.reply_text( | |
| "Tap to adjust:", reply_markup=numbers_keyboard(update.effective_chat.id)) | |
| async def cmd_set(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| """/steps 13, /boost 4, /denoise 1.0, /grounding 960 β bare shows the | |
| stepper instead of just reporting the value.""" | |
| name = update.message.text.split()[0].lstrip("/").split("@")[0] | |
| key, _step, lo, hi, cast = NUMERICS[name] | |
| s = settings_for(update.effective_chat.id) | |
| if not context.args: | |
| await update.message.reply_text( | |
| f"{name} is {s[key]} (range {lo}\u2013{hi})", | |
| reply_markup=numbers_keyboard(update.effective_chat.id)) | |
| return | |
| try: | |
| raw = cast(context.args[0]) | |
| except ValueError: | |
| await update.message.reply_text(f"{name} needs a {cast.__name__}") | |
| return | |
| s[key] = clamp(name, raw) | |
| save_state(STATE) | |
| note = "" if s[key] == raw else f" (clamped from {raw:g})" | |
| await update.message.reply_text(f"{name} = {s[key]}{note}") | |
| async def cmd_strength(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| if len(context.args) != 2: | |
| await update.message.reply_text("usage: /strength <lora-substring> <value>") | |
| return | |
| needle, value = context.args[0].lower(), float(context.args[1]) | |
| s = settings_for(update.effective_chat.id) | |
| hits = [l for l in s["loras"] if needle in l["lora"].lower()] | |
| if not hits: | |
| await update.message.reply_text("no active LoRA matches that") | |
| return | |
| for l in hits: | |
| l["strength"] = value | |
| save_state(STATE) | |
| await update.message.reply_text( | |
| "\n".join(f"{l['lora']} @ {l['strength']:g}" for l in hits)) | |
| async def cmd_diag(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| """Cross-check workflow_map.json against the loaded workflow.""" | |
| try: | |
| wf = comfy.load_workflow(WORKFLOW) | |
| except Exception as exc: | |
| await update.message.reply_text(f"cannot load {WORKFLOW}: {exc}") | |
| return | |
| lines = await asyncio.to_thread(comfy.diagnose, wf) | |
| bad = [l for l in lines if l.startswith("BAD")] | |
| body = "\n".join(lines) | |
| await update.message.reply_text( | |
| f"<pre>{html.escape(body)}</pre>\n" | |
| f"{len(bad)} problem(s)", parse_mode="HTML") | |
| async def cmd_reset(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| """/reset β settings for this chat. /reset all β every chat.""" | |
| scope = "all" if context.args and context.args[0].lower() == "all" else "chat" | |
| await update.message.reply_text( | |
| "Reset " + ("EVERY chat's settings" if scope == "all" | |
| else "this chat's settings") + | |
| " back to defaults?\nThis clears your system prompt, LoRA " | |
| "selection and uploaded image.", | |
| reply_markup=InlineKeyboardMarkup([[ | |
| InlineKeyboardButton("yes, reset", callback_data=f"reset:{scope}"), | |
| InlineKeyboardButton("cancel", callback_data="close")]])) | |
| async def cmd_refresh(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| """Show what ComfyUI reports vs what is actually on disk.""" | |
| reported, on_disk = await asyncio.to_thread(comfy.lora_sources) | |
| only_disk = [n for n in on_disk if n not in reported] | |
| lines = [f"ComfyUI reports: {len(reported)}", | |
| f"on disk: {len(on_disk)} ({', '.join(LORA_DIRS)})"] | |
| if only_disk: | |
| lines.append("") | |
| lines.append("not yet in ComfyUI's cache (usable anyway via the " | |
| "Power Lora Loader):") | |
| lines += [f" {n}" for n in only_disk[:20]] | |
| elif not on_disk: | |
| lines.append("") | |
| lines.append("Nothing found on disk β LORA_DIRS is probably wrong.") | |
| await update.message.reply_text("\n".join(lines)) | |
| async def cmd_cancel(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| await asyncio.to_thread(comfy.interrupt) | |
| await update.message.reply_text("interrupt sent") | |
| # --------------------------------------------------------------- callbacks | |
| async def on_button(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| q = update.callback_query | |
| await q.answer() | |
| chat_id = q.message.chat_id | |
| s = settings_for(chat_id) | |
| if q.data == "close": | |
| await q.edit_message_text("Saved.") | |
| return | |
| kind, rest = q.data.split(":", 1) | |
| if q.data == "noop": | |
| return | |
| if q.data.startswith("reset:"): | |
| scope = q.data.split(":", 1)[1] | |
| if scope == "all": | |
| STATE.clear() | |
| else: | |
| STATE.pop(str(chat_id), None) | |
| save_state(STATE) | |
| context.user_data.pop("awaiting", None) | |
| await q.edit_message_text( | |
| "Reset. " + ("All chats are back to defaults." | |
| if scope == "all" else | |
| "Send a new source image to start again.")) | |
| return | |
| if q.data.startswith("sys:"): | |
| what = q.data.split(":", 1)[1] | |
| if what == "capture": | |
| context.user_data["awaiting"] = "system_prompt" | |
| await q.edit_message_text( | |
| "Send the system prompt as your next message, or attach it as " | |
| "a .txt file. /cancelinput to abort.") | |
| elif what == "default": | |
| s["system_prompt"] = None | |
| save_state(STATE) | |
| await q.edit_message_text("Reverted to the workflow's own value.") | |
| elif what == "clear": | |
| s["system_prompt"] = "" | |
| save_state(STATE) | |
| await q.edit_message_text("System prompt cleared.") | |
| return | |
| if kind == "num": | |
| name, direction = rest.split(":", 1) | |
| key, step, _lo, _hi, _cast = NUMERICS[name] | |
| s[key] = clamp(name, s[key] + step * int(direction)) | |
| save_state(STATE) | |
| await q.edit_message_reply_markup(numbers_keyboard(chat_id)) | |
| return | |
| if kind == "menu": | |
| if rest == "numbers": | |
| await q.edit_message_text("Tap to adjust:", | |
| reply_markup=numbers_keyboard(chat_id)) | |
| elif rest == "loras": | |
| await q.edit_message_text( | |
| "Tap to toggle.", reply_markup=await lora_keyboard(chat_id)) | |
| else: | |
| await q.edit_message_text( | |
| f"{rest}: {s[PICKERS[rest][2]] or 'workflow default'}", | |
| reply_markup=await pick_keyboard(rest, s[PICKERS[rest][2]])) | |
| return | |
| if kind == "pick": | |
| picker, idx = rest.split(":", 1) | |
| key = PICKERS[picker][2] | |
| s[key] = (await options_of(picker))[int(idx)] | |
| save_state(STATE) | |
| await q.edit_message_text(f"{picker} = {s[key]}") | |
| return | |
| idx = rest | |
| if kind == "lora": | |
| available = await asyncio.to_thread(comfy.list_loras) | |
| name = available[int(idx)] | |
| active = [l for l in s["loras"] if l["lora"] == name] | |
| if active: | |
| s["loras"] = [l for l in s["loras"] if l["lora"] != name] | |
| else: | |
| s["loras"].append({"lora": name, "strength": 1.0}) | |
| save_state(STATE) | |
| await q.edit_message_reply_markup(await lora_keyboard(chat_id)) | |
| # ------------------------------------------------------------------ images | |
| async def on_image(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| msg = update.message | |
| doc = msg.document | |
| warn = None | |
| if doc: | |
| tg_file = await doc.get_file() | |
| filename = doc.file_name or "upload.png" | |
| else: | |
| # Telegram already re-encoded this to JPEG at reduced size. | |
| tg_file = await msg.photo[-1].get_file() | |
| filename = "upload.jpg" | |
| warn = ("\n\nβ οΈ Sent as a photo, so Telegram compressed it. Attach as " | |
| "a file instead for better identity preservation.") | |
| buf = io.BytesIO() | |
| await tg_file.download_to_memory(buf) | |
| name = await asyncio.to_thread(comfy.upload_image, buf.getvalue(), filename) | |
| s = settings_for(msg.chat_id) | |
| s["image"] = name | |
| save_state(STATE) | |
| await msg.reply_text(f"Source set: {name}{warn or ''}\n" | |
| f"Now send the edit instruction as text.") | |
| # -------------------------------------------------------------- generation | |
| async def cmd_reset(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| """/reset β settings for this chat. /reset all β every chat.""" | |
| scope = "all" if context.args and context.args[0].lower() == "all" else "chat" | |
| await update.message.reply_text( | |
| "Reset " + ("EVERY chat's settings" if scope == "all" | |
| else "this chat's settings") + | |
| " back to defaults?\nThis clears your system prompt, LoRA " | |
| "selection and uploaded image.", | |
| reply_markup=InlineKeyboardMarkup([[ | |
| InlineKeyboardButton("yes, reset", callback_data=f"reset:{scope}"), | |
| InlineKeyboardButton("cancel", callback_data="close")]])) | |
| async def cmd_refresh(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| """Show what ComfyUI reports vs what is actually on disk.""" | |
| reported, on_disk = await asyncio.to_thread(comfy.lora_sources) | |
| only_disk = [n for n in on_disk if n not in reported] | |
| lines = [f"ComfyUI reports: {len(reported)}", | |
| f"on disk: {len(on_disk)} ({', '.join(LORA_DIRS)})"] | |
| if only_disk: | |
| lines.append("") | |
| lines.append("not yet in ComfyUI's cache (usable anyway via the " | |
| "Power Lora Loader):") | |
| lines += [f" {n}" for n in only_disk[:20]] | |
| elif not on_disk: | |
| lines.append("") | |
| lines.append("Nothing found on disk β LORA_DIRS is probably wrong.") | |
| await update.message.reply_text("\n".join(lines)) | |
| async def cmd_cancelinput(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| context.user_data.pop("awaiting", None) | |
| await update.message.reply_text("Back to normal β text will generate again.") | |
| async def on_prompt(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| msg = update.message | |
| s = settings_for(msg.chat_id) | |
| # Capture mode: this message is the system prompt, not an edit instruction. | |
| if context.user_data.pop("awaiting", None) == "system_prompt": | |
| s["system_prompt"] = msg.text | |
| save_state(STATE) | |
| await msg.reply_text(f"system prompt set ({len(msg.text)} chars)") | |
| return | |
| if not s["image"]: | |
| await msg.reply_text("Send a source image first.") | |
| return | |
| if gpu.locked(): | |
| await msg.reply_text("A job is already running β queued behind it.") | |
| status = await msg.reply_text("Waiting for GPUβ¦") | |
| async with gpu: | |
| loop = asyncio.get_running_loop() | |
| last_edit = 0.0 | |
| def on_progress(done: int, total: int) -> None: | |
| """Called from the worker thread by the websocket loop.""" | |
| nonlocal last_edit | |
| now = time.monotonic() | |
| # Telegram rate-limits edits; more than one every couple of | |
| # seconds gets us throttled and the bar stops updating. | |
| if now - last_edit < 2.5 or not total: | |
| return | |
| last_edit = now | |
| filled = int(12 * done / total) | |
| bar = "β" * filled + "β" * (12 - filled) | |
| asyncio.run_coroutine_threadsafe( | |
| status.edit_text(f"{bar} {done}/{total}"), loop) | |
| def work(): | |
| wf = comfy.load_workflow(WORKFLOW) | |
| params = {"image": s["image"], "prompt": msg.text, | |
| "steps": s["steps"], "ref_boost": s["ref_boost"], | |
| "denoise": s["denoise"], | |
| "grounding_px": s["grounding_px"]} | |
| for key in ("aspect", "unet", "sampler_name", "scheduler"): | |
| if s.get(key): | |
| params[key] = s[key] | |
| # None means leave the workflow's own value; "" is a real choice. | |
| if s.get("system_prompt") is not None: | |
| params["system_prompt"] = s["system_prompt"] | |
| skipped = comfy.apply(params, wf, strict=False) | |
| if skipped: | |
| log.warning("unmapped params dropped: %s", ", ".join(skipped)) | |
| if s["loras"]: | |
| comfy.set_loras(s["loras"], wf) | |
| seed = comfy.randomize_seed(wf) | |
| return seed, list(comfy.run(wf, on_progress=on_progress)) | |
| await context.bot.send_chat_action(msg.chat_id, ChatAction.UPLOAD_PHOTO) | |
| try: | |
| seed, images = await asyncio.to_thread(work) | |
| except ComfyError as exc: | |
| await status.edit_text(f"Failed:\n<code>{html.escape(str(exc))}</code>", | |
| parse_mode="HTML") | |
| return | |
| except Exception as exc: | |
| log.exception("generation failed") | |
| await status.edit_text(f"Error: {type(exc).__name__}: {exc}") | |
| return | |
| if not images: | |
| await status.edit_text("Finished but produced no images.") | |
| return | |
| await status.edit_text(f"Done β seed {seed}") | |
| for img in images: | |
| data = io.BytesIO(img.data) | |
| data.name = img.filename | |
| # As a document: Telegram won't recompress it, and sendPhoto caps at | |
| # 10MB while sendDocument allows 50MB. | |
| await msg.reply_document(InputFile(data, filename=img.filename), | |
| caption=f"seed {seed}") | |
| async def on_error(update: object, context: ContextTypes.DEFAULT_TYPE) -> None: | |
| """Without this, any unhandled exception only ever reaches the log and the | |
| user is left staring at a message that never updates.""" | |
| log.exception("handler failed", exc_info=context.error) | |
| chat = getattr(update, "effective_chat", None) | |
| if chat: | |
| try: | |
| await chat.send_message( | |
| f"Something broke: {type(context.error).__name__}: " | |
| f"{context.error}") | |
| except Exception: | |
| pass | |
| def main() -> None: | |
| app = Application.builder().token(TOKEN).build() | |
| app.add_error_handler(on_error) | |
| app.add_handler(CommandHandler("start", cmd_start)) | |
| app.add_handler(CommandHandler("help", cmd_start)) | |
| app.add_handler(CommandHandler("status", cmd_status)) | |
| app.add_handler(CommandHandler("settings", cmd_settings)) | |
| app.add_handler(CommandHandler("loras", cmd_loras)) | |
| app.add_handler(CommandHandler("strength", cmd_strength)) | |
| app.add_handler(CommandHandler("cancel", cmd_cancel)) | |
| app.add_handler(CommandHandler("diag", cmd_diag)) | |
| app.add_handler(CommandHandler("refresh", cmd_refresh)) | |
| app.add_handler(CommandHandler("reset", cmd_reset)) | |
| for c in NUMERICS: | |
| app.add_handler(CommandHandler(c, cmd_set)) | |
| app.add_handler(CommandHandler("numbers", cmd_numbers)) | |
| app.add_handler(CommandHandler("system", cmd_system)) | |
| app.add_handler(CommandHandler("cancelinput", cmd_cancelinput)) | |
| for p in PICKERS: | |
| app.add_handler(CommandHandler(p, cmd_pick)) | |
| app.add_handler(CallbackQueryHandler(on_button)) | |
| app.add_handler(MessageHandler( | |
| filters.Document.FileExtension("txt") | filters.Document.FileExtension("md"), | |
| on_text_file)) | |
| app.add_handler(MessageHandler(filters.PHOTO | filters.Document.IMAGE, | |
| on_image)) | |
| app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, on_prompt)) | |
| log.info("polling (allowed chats: %s)", ALLOWED or "ALL β set ALLOWED_CHAT_IDS") | |
| app.run_polling(drop_pending_updates=True) | |
| if __name__ == "__main__": | |
| main() | |