File size: 29,206 Bytes
e609fe4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
#!/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):
    @functools.wraps(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
@guard
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")


@guard
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}")


@guard
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())


@guard
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]}")


@guard
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


@guard
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())


@guard
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)")


@guard
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))


@guard
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}")


@guard
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))


@guard
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")


@guard
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")]]))


@guard
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))


@guard
async def cmd_cancel(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await asyncio.to_thread(comfy.interrupt)
    await update.message.reply_text("interrupt sent")


# --------------------------------------------------------------- callbacks
@guard
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
@guard
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
@guard
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")]]))


@guard
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))


@guard
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.")


@guard
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()