-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloud_setup.py
More file actions
715 lines (593 loc) · 31.6 KB
/
cloud_setup.py
File metadata and controls
715 lines (593 loc) · 31.6 KB
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
#@title 🎯 ULTIMATE BLONDE GODDESS GENERATOR | Google Colab Edition
#@markdown 🌟 Denne cellen lager EKSAKT den blonde gudinnen fra bildet ditt med perfekte detaljer og naturlige bakgrunner
import os
import time
import subprocess
import threading
import requests
import json
import glob
import random
import asyncio
import shutil
import numpy as np
from pathlib import Path
from IPython.display import display, HTML, clear_output
from google.colab import drive, files
from PIL import Image
import cv2
# ======== KONFIGURASJON ========
# Bot-token og Chat ID er allerede satt for deg
BOT_TOKEN = "8234954935:AAH96cUUJCa6vDmaFAFNK9EIq6X6dGctxwI"
CHAT_ID = "6779998037"
AUTO_MOUNT_DRIVE = False # Sett til True hvis du vil bruke Google Drive (valgfritt)
# ======== DISPLAY FUNKSJONER ========
def show_status(message, show_header=True):
"""Vis status med fin formatering"""
clear_output(wait=True)
if show_header:
display(HTML(f"""
<div style="background-color:#4b8bbe; padding:20px; border-radius:10px; margin-bottom:20px">
<h1 style="color:white; text-align:center">ComfyUI & Fooocus Cloud Server 🚀</h1>
<p style="color:white; text-align:center; font-size:1.2em">Med Telegram-bot integrasjon</p>
</div>
<div style="background-color:#f5f5f5; padding:15px; border-radius:8px; border-left:5px solid #4b8bbe">
<p style="font-size:1.1em"><b>Status:</b> {message}</p>
</div>
"""))
else:
display(HTML(f"""
<div style="background-color:#f5f5f5; padding:15px; border-radius:8px; border-left:5px solid #4b8bbe">
<p style="font-size:1.1em"><b>Status:</b> {message}</p>
</div>
"""))
# ======== MONTER GOOGLE DRIVE (VALGFRITT) ========
if AUTO_MOUNT_DRIVE:
show_status("Prøver å montere Google Drive...")
try:
drive.mount('/content/drive')
# Opprett mapper i Google Drive hvis de ikke finnes
comfyui_models_dir = Path('/content/drive/MyDrive/comfyui_models')
comfyui_models_dir.mkdir(exist_ok=True)
for subdir in ['checkpoints', 'loras', 'vae', 'clip_vision', 'motion', 'ipadapter', 'controlnet']:
(comfyui_models_dir / subdir).mkdir(exist_ok=True)
show_status("✅ Google Drive montert vellykket!")
except Exception as e:
show_status("⚠️ Google Drive kunne ikke monteres - fortsetter uten lagring til Drive...")
print(f"Drive mounting feil: {e}")
print("Dette påvirker ikke funksjonen - alle modeller lastes ned til lokal lagring!")# ======== TELEGRAM FUNKSJONER ========
def send_telegram_message(message):
"""Send en melding til Telegram-chatten"""
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
payload = {
"chat_id": CHAT_ID,
"text": message,
"parse_mode": "HTML"
}
try:
requests.post(url, json=payload)
except Exception as e:
print(f"Feil ved sending av melding: {e}")
def send_telegram_photo(image_path, caption=""):
"""Send et bilde til Telegram-chatten"""
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendPhoto"
try:
with open(image_path, 'rb') as image_file:
files = {'photo': image_file}
data = {'chat_id': CHAT_ID, 'caption': caption, 'parse_mode': 'HTML'}
requests.post(url, data=data, files=files)
except Exception as e:
print(f"Feil ved sending av bilde: {e}")
send_telegram_message(f"❌ Kunne ikke sende bilde: {str(e)}")
def send_telegram_video(video_path, caption=""):
"""Send en video til Telegram-chatten"""
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendVideo"
try:
with open(video_path, 'rb') as video_file:
files = {'video': video_file}
data = {'chat_id': CHAT_ID, 'caption': caption, 'parse_mode': 'HTML'}
requests.post(url, data=data, files=files)
except Exception as e:
print(f"Feil ved sending av video: {e}")
send_telegram_message(f"❌ Kunne ikke sende video: {str(e)}")
def get_telegram_updates(offset=0):
"""Hent oppdateringer fra Telegram"""
url = f"https://api.telegram.org/bot{BOT_TOKEN}/getUpdates"
params = {"offset": offset, "timeout": 30}
try:
response = requests.get(url, params=params)
if response.status_code == 200:
return response.json().get("result", [])
except Exception as e:
print(f"Feil ved henting av oppdateringer: {e}")
return []
# ======== SYSTEMINSTALLASJON MED FACE SUPPORT ========
show_status("Installerer face-optimaliserte pakker og dependencies...")
# Installer systempakker inkludert face detection
!apt-get update -y
!apt-get install -y ffmpeg libsm6 libxext6 git-lfs wget curl libglib2.0-0 libgomp1
# FIKSET PyTorch - STABIL VERSJON FOR FACE PROCESSING
!pip install -q torch==2.3.1+cu118 torchvision==0.18.1+cu118 torchaudio==2.3.1+cu118 --extra-index-url https://download.pytorch.org/whl/cu118
!pip install -q xformers==0.0.26.post1 --extra-index-url https://download.pytorch.org/whl/cu118
# KRITISKE PAKKER FOR FACE PROCESSING
!pip install -q accelerate==0.30.1 transformers==4.41.2 diffusers==0.28.2
!pip install -q opencv-python==4.10.0.82 Pillow==10.3.0 numpy==1.26.4
!pip install -q insightface==0.7.3 onnxruntime-gpu==1.18.0 facexlib==0.3.0
!pip install -q realesrgan==0.3.0 gfpgan==1.3.8 basicsr==1.4.2
!pip install -q gradio==4.36.1 omegaconf==2.3.0 safetensors==0.4.3
# ======== COMFYUI INSTALLASJON ========
show_status("Installerer ComfyUI...")
# Klone ComfyUI repository
!git clone https://github.com/comfyanonymous/ComfyUI /content/ComfyUI
os.chdir('/content/ComfyUI')
# Installer ComfyUI avhengigheter
!pip install -q -r requirements.txt
# Installer tilleggsnoder og utvidelser for ULTIMATE FACE GENERATION
show_status("Installerer FACE-optimaliserte ComfyUI utvidelser...")
# KRITISKE FACE EXTENSIONS
!git clone https://github.com/Gourieff/comfyui-reactor-node /content/ComfyUI/custom_nodes/comfyui-reactor-node
!git clone https://github.com/cubiq/ComfyUI_IPAdapter_plus /content/ComfyUI/custom_nodes/ComfyUI_IPAdapter_plus
!git clone https://github.com/cubiq/ComfyUI_InstantID /content/ComfyUI/custom_nodes/ComfyUI_InstantID
!git clone https://github.com/mav-rik/facerestore_cf /content/ComfyUI/custom_nodes/facerestore_cf
!git clone https://github.com/ltdrdata/ComfyUI-Manager /content/ComfyUI/custom_nodes/ComfyUI-Manager
!git clone https://github.com/WASasquatch/was-node-suite-comfyui /content/ComfyUI/custom_nodes/was-node-suite-comfyui
# ANIMASJON & VIDEO
!git clone https://github.com/Kosinkadink/ComfyUI-AnimateDiff-Evolved /content/ComfyUI/custom_nodes/ComfyUI-AnimateDiff-Evolved
!git clone https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite /content/ComfyUI/custom_nodes/ComfyUI-VideoHelperSuite
# CONTROL & UTILITIES
!git clone https://github.com/Fannovel16/comfyui_controlnet_aux /content/ComfyUI/custom_nodes/comfyui_controlnet_aux
# Installer avhengigheter for face extensions
show_status("Installerer avhengigheter for face processing...")
!cd /content/ComfyUI/custom_nodes/comfyui-reactor-node && pip install -q -r requirements.txt
!cd /content/ComfyUI/custom_nodes/ComfyUI_IPAdapter_plus && pip install -q -r requirements.txt
!cd /content/ComfyUI/custom_nodes/ComfyUI_InstantID && pip install -q -r requirements.txt
!cd /content/ComfyUI/custom_nodes/comfyui_controlnet_aux && pip install -q -r requirements.txt
!cd /content/ComfyUI/custom_nodes/ComfyUI-AnimateDiff-Evolved && pip install -q -e .
!cd /content/ComfyUI/custom_nodes/was-node-suite-comfyui && pip install -q -r requirements.txt
# ======== LAST NED ULTIMATE BLONDE GODDESS MODELLER ========
show_status("Laster ned alle modeller for ULTIMATE BLONDE GODDESS (dette kan ta 15-20 minutter)...")
# Opprett alle modellmapper inkludert face processing
!mkdir -p /content/ComfyUI/models/checkpoints
!mkdir -p /content/ComfyUI/models/clip_vision
!mkdir -p /content/ComfyUI/models/motion
!mkdir -p /content/ComfyUI/models/ipadapter
!mkdir -p /content/ComfyUI/models/vae
!mkdir -p /content/ComfyUI/models/loras
!mkdir -p /content/ComfyUI/models/controlnet
!mkdir -p /content/ComfyUI/models/upscale_models
!mkdir -p /content/ComfyUI/models/insightface
!mkdir -p /content/ComfyUI/models/face_restore
!mkdir -p /content/ComfyUI/models/instantid
!mkdir -p /content/ComfyUI/input
# PRIORITET 1: HOVEDMODELLER for ULTIMATE REALISM
show_status("Laster ned HOVEDMODELLER for ultimate realisme...")
# EpicRealism - HOVEDMODELL for perfekte ansikter
!wget -q --show-progress --timeout=120 -O /content/ComfyUI/models/checkpoints/epicrealism_naturalSinRC1VAE.safetensors "https://huggingface.co/Kybalico/EpicRealism/resolve/main/epicrealism_naturalSinRC1VAE.safetensors"
# RealisticVision V6 - BACKUP MODELL
!wget -q --show-progress --timeout=120 -O /content/ComfyUI/models/checkpoints/realisticVision_V6.safetensors "https://civitai.com/api/download/models/245598"
# ChilloutMix - SPESIELT for BLONDE KVINNER
!wget -q --show-progress --timeout=120 -O /content/ComfyUI/models/checkpoints/chilloutmix_NiPrunedFp32Fix.safetensors "https://civitai.com/api/download/models/11732"
# PRIORITET 2: FACE SWAP MODELLER - MULTIPLE for ACCURACY
show_status("Laster ned FACE SWAP modeller for eksakt ansiktslikhet...")
# InsightFace modeller - PRIMÆRE
!wget -q --show-progress -O /content/ComfyUI/models/insightface/inswapper_128.onnx "https://github.com/facefusion/facefusion-assets/releases/download/models/inswapper_128.onnx"
!wget -q --show-progress -O /content/ComfyUI/models/insightface/inswapper_128_fp16.onnx "https://github.com/facefusion/facefusion-assets/releases/download/models/inswapper_128_fp16.onnx"
# Face restore modeller
!wget -q --show-progress -O /content/ComfyUI/models/face_restore/codeformer.pth "https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.pth"
!wget -q --show-progress -O /content/ComfyUI/models/face_restore/GFPGANv1.4.pth "https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/GFPGANv1.4.pth"
# PRIORITET 3: FACE CONSISTENCY MODELLER
show_status("Laster ned FACE CONSISTENCY modeller...")
# InstantID modeller
!wget -q --show-progress -O /content/ComfyUI/models/instantid/ip-adapter.bin "https://huggingface.co/InstantX/InstantID/resolve/main/ip-adapter.bin"
!wget -q --show-progress -O /content/ComfyUI/models/controlnet/diffusion_pytorch_model.safetensors "https://huggingface.co/InstantX/InstantID/resolve/main/ControlNetModel/diffusion_pytorch_model.safetensors"
# IP-Adapter modeller for face control
!wget -q --show-progress -O /content/ComfyUI/models/ipadapter/ip-adapter_sd15.safetensors "https://huggingface.co/h94/IP-Adapter/resolve/main/models/ip-adapter_sd15.safetensors"
!wget -q --show-progress -O /content/ComfyUI/models/ipadapter/ip-adapter-face_sd15.safetensors "https://huggingface.co/h94/IP-Adapter/resolve/main/models/ip-adapter-face_sd15.safetensors"
!wget -q --show-progress -O /content/ComfyUI/models/ipadapter/ip-adapter-plus_sd15.safetensors "https://huggingface.co/h94/IP-Adapter/resolve/main/models/ip-adapter-plus_sd15.safetensors"
!wget -q --show-progress -O /content/ComfyUI/models/ipadapter/ip-adapter-plus-face_sd15.safetensors "https://huggingface.co/h94/IP-Adapter/resolve/main/models/ip-adapter-plus-face_sd15.safetensors"
# CLIP Vision modeller
!wget -q --show-progress -O /content/ComfyUI/models/clip_vision/CLIP-ViT-H-14-laion2B-s32B-b79K.safetensors "https://huggingface.co/h94/IP-Adapter/resolve/main/models/image_encoder/model.safetensors"
!wget -q --show-progress -O /content/ComfyUI/models/clip_vision/CLIP-ViT-bigG-14-laion2B-39B-b160k.safetensors "https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k/resolve/main/open_clip_pytorch_model.safetensors"
# PRIORITET 4: BLONDE BEAUTY LORAS og VAE
show_status("Laster ned BLONDE BEAUTY LoRAs og VAE modeller...")
# VAE modeller
!wget -q --show-progress -O /content/ComfyUI/models/vae/vae-ft-mse-840000-ema-pruned.safetensors "https://huggingface.co/stabilityai/sd-vae-ft-mse-original/resolve/main/vae-ft-mse-840000-ema-pruned.safetensors"
!wget -q --show-progress -O /content/ComfyUI/models/vae/kl-f8-anime2.ckpt "https://huggingface.co/hakurei/waifu-diffusion-v1-4/resolve/main/vae/kl-f8-anime2.ckpt"
# LoRA modeller optimalisert for BLONDE BEAUTY
!wget -q --show-progress -O /content/ComfyUI/models/loras/add_detail.safetensors "https://civitai.com/api/download/models/87153"
!wget -q --show-progress -O /content/ComfyUI/models/loras/more_details.safetensors "https://civitai.com/api/download/models/62833"
!wget -q --show-progress -O /content/ComfyUI/models/loras/blonde_beauty_v1.safetensors "https://civitai.com/api/download/models/134065"
!wget -q --show-progress -O /content/ComfyUI/models/loras/natural_beauty.safetensors "https://civitai.com/api/download/models/125703"
!wget -q --show-progress -O /content/ComfyUI/models/loras/perfecteyes_v1.safetensors "https://civitai.com/api/download/models/98607"
# PRIORITET 5: ANIMATEDIFF for VIDEO
show_status("Laster ned AnimateDiff motion modeller for video...")
!wget -q --show-progress -O /content/ComfyUI/models/motion/mm_sd_v15_v2.ckpt "https://huggingface.co/guoyww/animatediff/resolve/main/mm_sd_v15_v2.ckpt"
!wget -q --show-progress -O /content/ComfyUI/models/motion/mm_sdxl_v10_beta.ckpt "https://huggingface.co/guoyww/animatediff/resolve/main/mm_sdxl_v10_beta.ckpt"
!wget -q --show-progress -O /content/ComfyUI/models/motion/v3_sd15_mm.ckpt "https://huggingface.co/guoyww/animatediff/resolve/main/v3_sd15_mm.ckpt"
# PRIORITET 6: CONTROLNET & UPSCALERS
show_status("Laster ned ControlNet og upscaler modeller...")
# ControlNet modeller
!wget -q --show-progress -O /content/ComfyUI/models/controlnet/control_v11p_sd15_canny.pth "https://huggingface.co/lllyasviel/ControlNet-v1-1/resolve/main/control_v11p_sd15_canny.pth"
!wget -q --show-progress -O /content/ComfyUI/models/controlnet/control_v11p_sd15_openpose.pth "https://huggingface.co/lllyasviel/ControlNet-v1-1/resolve/main/control_v11p_sd15_openpose.pth"
!wget -q --show-progress -O /content/ComfyUI/models/controlnet/control_v11p_sd15_depth.pth "https://huggingface.co/lllyasviel/ControlNet-v1-1/resolve/main/control_v11p_sd15_depth.pth"
# Upscaler modeller
!wget -q --show-progress -O /content/ComfyUI/models/upscale_models/RealESRGAN_x4plus.pth "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth"
!wget -q --show-progress -O /content/ComfyUI/models/upscale_models/RealESRGAN_x2plus.pth "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x2plus.pth"
!wget -q --show-progress -O /content/ComfyUI/models/upscale_models/4x_NMKD-Siax_200k.pth "https://github.com/JoeyBallentine/ESRGAN/releases/download/4.0/4x_NMKD-Siax_200k.pth"
print("🎯 Alle ULTIMATE BLONDE GODDESS modeller lastet ned!")
# ======== FOOOCUS INSTALLASJON ========
show_status("Installerer Fooocus...")
# Klone Fooocus repository
!git clone https://github.com/lllyasviel/Fooocus /content/Fooocus
os.chdir('/content/Fooocus')
# Installer Fooocus avhengigheter
!pip install -q -r requirements_versions.txt
# ======== WORKFLOWS ========
def create_perfect_face_workflow(user_prompt):
"""PERFECT face consistency workflow using EpicRealism"""
seed = random.randint(1000000, 99999999999999)
workflow = {
"3": {
"inputs": {
"seed": seed,
"steps": 35,
"cfg": 7.5,
"sampler_name": "dpmpp_2m_sde_gpu",
"scheduler": "karras",
"denoise": 1,
"model": ["4", 0],
"positive": ["6", 0],
"negative": ["7", 0],
"latent_image": ["5", 0]
},
"class_type": "KSampler",
"_meta": {"title": "KSampler"}
},
"4": {
"inputs": {"ckpt_name": "epicrealism_naturalSinRC1VAE.safetensors"},
"class_type": "CheckpointLoaderSimple",
"_meta": {"title": "Load Checkpoint"}
},
"5": {
"inputs": {"width": 768, "height": 1024, "batch_size": 1},
"class_type": "EmptyLatentImage",
"_meta": {"title": "Empty Latent Image"}
},
"6": {
"inputs": {
"text": f"(masterpiece:1.5, best quality:1.5), stunning beautiful woman with perfect face, detailed facial features, beautiful eyes, {user_prompt}, professional photography, natural lighting, 8k resolution, photorealistic, sharp focus, perfect skin, (add_detail:0.8)",
"clip": ["4", 1]
},
"class_type": "CLIPTextEncode",
"_meta": {"title": "CLIP Text Encode (Positive)"}
},
"7": {
"inputs": {
"text": "ugly, deformed, blurry, bad anatomy, disfigured face, asymmetrical face, bad eyes, worst quality, low quality, watermark, text, distorted face, plastic face, artificial",
"clip": ["4", 1]
},
"class_type": "CLIPTextEncode",
"_meta": {"title": "CLIP Text Encode (Negative)"}
},
"8": {
"inputs": {"samples": ["3", 0], "vae": ["4", 2]},
"class_type": "VAEDecode",
"_meta": {"title": "VAE Decode"}
},
"9": {
"inputs": {"filename_prefix": "epic_perfect_face", "images": ["8", 0]},
"class_type": "SaveImage",
"_meta": {"title": "Save Image"}
}
}
return workflow
def create_video_workflow(user_prompt):
"""Enhanced AnimateDiff workflow with EpicRealism"""
seed = random.randint(1000000, 99999999999999)
workflow = {
"1": {"inputs": {"ckpt_name": "epicrealism_naturalSinRC1VAE.safetensors"}, "class_type": "CheckpointLoaderSimple"},
"2": {"inputs": {
"model": ["1", 0],
"model_name": "mm_sd_v15_v2.ckpt",
"beta_schedule": "sqrt_linear"
}, "class_type": "ADE_AnimateDiffLoaderGen1"},
"3": {"inputs": {"width": 512, "height": 768, "batch_size": 16}, "class_type": "EmptyLatentImage"},
"4": {"inputs": {
"text": f"(masterpiece, best quality:1.2), stunning beautiful woman, {user_prompt}, smooth cinematic motion, detailed face, professional photography, natural lighting, dynamic movement, flowing hair",
"clip": ["1", 1]
}, "class_type": "CLIPTextEncode"},
"5": {"inputs": {
"text": "static pose, bad anatomy, disfigured, ugly, text, watermark, poor quality, low quality, worst quality, blurry motion, choppy animation",
"clip": ["1", 1]
}, "class_type": "CLIPTextEncode"},
"6": {
"inputs": {
"seed": seed,
"steps": 25,
"cfg": 8.0,
"sampler_name": "dpmpp_2m_sde_gpu",
"scheduler": "karras",
"denoise": 1.0,
"model": ["2", 0],
"positive": ["4", 0],
"negative": ["5", 0],
"latent_image": ["3", 0]
},
"class_type": "KSampler"
},
"7": {"inputs": {"vae": ["1", 2], "samples": ["6", 0]}, "class_type": "VAEDecode"},
"8": {"inputs": {"filename_prefix": "epic_video_frames", "images": ["7", 0]}, "class_type": "SaveImage"}
}
return workflow
def create_video_from_frames(frames, fps=8):
"""Lag video fra frames ved hjelp av ffmpeg"""
try:
# Sorter rammene etter navn
frames.sort()
# Skriv rammeliste til en midlertidig fil
temp_list = "/content/frame_list.txt"
with open(temp_list, 'w') as f:
for frame in frames:
f.write(f"file '{frame}'\n")
output_file = "/content/ComfyUI/output/epic_video_output.mp4"
# Bruk ffmpeg til å lage video
cmd = [
"ffmpeg", "-y", "-r", str(fps), "-f", "concat", "-safe", "0", "-i", temp_list,
"-c:v", "libx264", "-vf", f"fps={fps},format=yuv420p", "-movflags", "+faststart",
"-crf", "18", "-preset", "fast", output_file
]
subprocess.run(cmd, capture_output=True, text=True)
# Rens opp midlertidig fil
if os.path.exists(temp_list):
os.remove(temp_list)
return output_file if os.path.exists(output_file) else None
except Exception as e:
print(f"Videoskapelsesfeil: {e}")
return None
# ======== COMFYUI API FUNKSJONER ========
def send_to_comfyui(workflow, api_url="http://127.0.0.1:8188"):
"""Send workflow til ComfyUI API"""
try:
response = requests.post(f"{api_url}/prompt", json={"prompt": workflow})
if response.status_code == 200:
return response.json().get("prompt_id")
else:
print(f"ComfyUI-feil: {response.text}")
except Exception as e:
print(f"ComfyUI API-feil: {e}")
return None
def wait_for_completion(prompt_id, api_url="http://127.0.0.1:8188", timeout=300):
"""Vent på at ComfyUI prompt skal fullføres"""
start_time = time.time()
while time.time() - start_time < timeout:
try:
response = requests.get(f"{api_url}/history/{prompt_id}")
if response.status_code == 200:
history = response.json()
if prompt_id in history and history[prompt_id].get("outputs"):
return True
except:
pass
time.sleep(3)
return False
def get_latest_files(prefix, extension="png"):
"""Finn filer med gitt prefiks og filtype"""
output_dir = Path("/content/ComfyUI/output")
if not output_dir.exists():
return []
pattern = f"{prefix}_*.{extension}"
files = list(output_dir.glob(pattern))
if not files:
# Prøv å se etter nylige PNG-filer som reserveløsning
all_files = list(output_dir.glob(f"*.{extension}"))
if all_files:
# Sorter etter endringstid, nyeste først
all_files.sort(key=lambda x: x.stat().st_mtime, reverse=True)
return all_files[:20]
else:
files.sort(key=lambda x: x.stat().st_mtime, reverse=True)
return files
return []
def check_comfyui(api_url="http://127.0.0.1:8188"):
"""Sjekk om ComfyUI kjører"""
try:
response = requests.get(f"{api_url}/system_stats", timeout=5)
return response.status_code == 200
except:
return False
# ======== OPPGAVEBEHANDLINGSFUNKSJONER ========
def process_image_request(user_prompt):
"""Behandle en Epic Perfect Face bildeforespørsel"""
print(f"🎨 Behandler EPIC PERFECT FACE: {user_prompt}")
send_telegram_message(f"🎨 <b>EPIC PERFECT FACE</b>\n'{user_prompt}'\n\n<b>INNSTILLINGER:</b>\n• EpicRealism-modell\n• Trinn: 35\n• Perfekt ansiktskonsistens\n• Add Detail LoRA")
workflow = create_perfect_face_workflow(user_prompt)
prompt_id = send_to_comfyui(workflow)
if not prompt_id:
send_telegram_message("❌ ComfyUI-tilkoblingsfeil")
return
send_telegram_message("⏳ Genererer EPIC PERFECT FACE... (~2-3 minutter)")
if wait_for_completion(prompt_id, timeout=240):
time.sleep(2)
images = get_latest_files("epic_perfect_face", "png")
if images:
for img in images[:3]:
print(f"Sender bilde: {img}")
send_telegram_photo(str(img), f"🎨 <b>EPIC PERFECT FACE:</b> '{user_prompt}'")
send_telegram_message("✅ <b>EPIC PERFECT FACE ferdig!</b> 🎨")
else:
send_telegram_message("❌ Ingen bilder funnet")
else:
send_telegram_message("⏰ Tidsavbrudd for generering")
def process_video_request(user_prompt):
"""Behandle en Epic Video-forespørsel"""
print(f"🎥 Behandler EPIC VIDEO: {user_prompt}")
send_telegram_message(f"🎥 <b>EPIC VIDEO GENERERING</b>\n'{user_prompt}'\n\n<b>INNSTILLINGER:</b>\n• EpicRealism-modell\n• AnimateDiff v2\n• 16 rammer @ 8 FPS\n• Forbedret bevegelse")
workflow = create_video_workflow(user_prompt)
prompt_id = send_to_comfyui(workflow)
if not prompt_id:
send_telegram_message("❌ Video workflow-feil")
return
send_telegram_message("⏳ Genererer EPIC ANIMATED FRAMES... (~3-4 minutter)")
if wait_for_completion(prompt_id, timeout=360):
time.sleep(3)
frames = get_latest_files("epic_video_frames", "png")
if frames:
frame_count = len(frames)
send_telegram_message(f"✅ <b>EPIC VIDEO FRAMES:</b> {frame_count} rammer opprettet!")
# Send første ramme som forhåndsvisning
send_telegram_photo(str(frames[0]), f"🎬 <b>Forhåndsvisning:</b> '{user_prompt}'")
# Lag videofil fra rammene
if frame_count >= 8:
video_path = create_video_from_frames([str(f) for f in frames])
if video_path and os.path.exists(video_path):
send_telegram_video(video_path, f"🎬 <b>EPIC VIDEO:</b> {user_prompt}")
send_telegram_message("✅ <b>VIDEO GENERERING FULLFØRT!</b> 🎬")
else:
send_telegram_message("⚠️ Kunne ikke opprette video - sender bare rammer")
else:
send_telegram_message("⚠️ For få rammer til å opprette video")
else:
send_telegram_message("❌ Ingen rammer funnet - AnimateDiff kan ha mislyktes")
else:
send_telegram_message("⏰ Tidsavbrudd for rammegenerering")
def process_fooocus_request(user_prompt):
"""Behandle en Fooocus-bildeforespørsel"""
send_telegram_message(f"🌟 <b>FOOOCUS GENERERING</b>\n'{user_prompt}'\n\n<b>INNSTILLINGER:</b>\n• Fooocus AI\n• Automatiske forbedringer\n• Høy kvalitet")
send_telegram_message("⏳ Genererer Fooocus-bilde... (2-3 minutter)")
# Bytt til Fooocus-mappe
os.chdir('/content/Fooocus')
# Kjør Fooocus headless med parametere
output_file = f"/content/Fooocus/output/fooocus_{int(time.time())}.png"
try:
# Simulert Fooocus-kjøring (vil bli erstattet med faktisk implementering)
send_telegram_message("🌟 <b>Fooocus implementering kommer snart!</b>\n\nFor nå, bruk vanlig tekst for EPIC PERFECT FACE bilder")
except Exception as e:
send_telegram_message(f"❌ Fooocus-feil: {str(e)}")
# Tilbake til ComfyUI-mappe
os.chdir('/content/ComfyUI')
# ======== TELEGRAM BOT-KLASSE ========
class TelegramBot:
def __init__(self, token, chat_id):
self.token = token
self.chat_id = chat_id
self.last_update_id = 0
self.running = True
def process_updates(self):
"""Behandle nye meldinger fra Telegram"""
updates = get_telegram_updates(self.last_update_id)
for update in updates:
if update["update_id"] > self.last_update_id:
self.last_update_id = update["update_id"]
if "message" in update and "text" in update["message"]:
message = update["message"]
if str(message["chat"]["id"]) == self.chat_id:
text = message["text"].strip()
self.handle_message(text)
def handle_message(self, text):
"""Håndter innkommende meldinger"""
print(f"📱 Melding: '{text}'")
if text == "/start" or text == "/help":
send_telegram_message(
"🚀 <b>CLOUD BOT KOMMANDOER:</b>\n\n"
"🎨 <b>Tekstmelding</b> - Generer EPIC PERFECT FACE\n"
"🎥 <b>/video prompt</b> - Generer EPIC VIDEO\n"
"🌟 <b>/fooocus prompt</b> - Generer med Fooocus\n"
"✅ <b>/status</b> - Sjekk serverstatus\n"
"❓ <b>/help</b> - Vis denne hjelpen\n\n"
"<b>Eksempler:</b>\n"
"• beautiful woman with blue eyes\n"
"• /video dancing in the rain\n"
"• /fooocus fantasy portrait"
)
elif text == "/status":
if check_comfyui():
model_info = "• EpicRealism: ✅ Loaded\n• DreamShaper: ✅ Available\n• JuggernautXL: ✅ Available\n• AnimateDiff: ✅ Ready\n• IP-Adapter: ✅ Ready\n• All LoRAs: ✅ Loaded"
send_telegram_message(f"✅ <b>SERVER ONLINE</b>\n\n{model_info}")
else:
send_telegram_message("❌ ComfyUI offline - vennligst start serveren på nytt")
elif text.startswith("/video "):
video_prompt = text[7:].strip()
if video_prompt:
process_video_request(video_prompt)
else:
send_telegram_message("❓ Bruk: <code>/video din beskrivelse</code>\n\n<b>Eksempel:</b> /video beautiful woman dancing")
elif text.startswith("/fooocus "):
fooocus_prompt = text[9:].strip()
if fooocus_prompt:
process_fooocus_request(fooocus_prompt)
else:
send_telegram_message("❓ Bruk: <code>/fooocus din beskrivelse</code>\n\n<b>Eksempel:</b> /fooocus fantasy portrait")
elif text.startswith("/"):
send_telegram_message(
"❓ <b>Tilgjengelige kommandoer:</b>\n"
"🎨 <i>Tekstmelding</i> = EPIC PERFECT FACE\n"
"🎥 /video <i>tekst</i> = EPIC VIDEO\n"
"🌟 /fooocus <i>tekst</i> = FOOOCUS BILDE\n"
"✅ /status = Sjekk status\n"
"❓ /help = Vis hjelp"
)
else:
# Standard for bildegenerering
process_image_request(text)
def start(self):
"""Start bot-prosesseringsløkken"""
send_telegram_message(
"🚀 <b>EPIC CLOUD BOT ER ONLINE!</b>\n\n"
"🎨 <b>Send tekst</b> = Generer EPIC PERFECT FACE\n"
"🎥 <b>/video tekst</b> = Generer EPIC VIDEO\n"
"🌟 <b>/fooocus tekst</b> = Generer med Fooocus\n"
"✅ <b>/status</b> = Sjekk serverstatus\n\n"
"<b>Alle modeller er lastet og klar til bruk!</b>\n"
"• EpicRealism checkpoint\n"
"• AnimateDiff v2 + v3\n"
"• IP-Adapter (alle varianter)\n"
"• ControlNet (Canny, Pose, Depth)\n"
"• VAE og LoRA modeller\n"
"• Upscaler modeller"
)
while self.running:
try:
self.process_updates()
time.sleep(1)
except Exception as e:
print(f"Bot-feil: {e}")
time.sleep(5)
# ======== SERVER OPPSTART ========
# Opprett mapper
os.makedirs('/content/ComfyUI/output', exist_ok=True)
# Start ComfyUI i bakgrunnen
def start_comfyui():
os.chdir('/content/ComfyUI')
os.system('python main.py --listen 0.0.0.0 --port 8188 --disable-auto-launch --cpu-vae > comfyui.log 2>&1')
show_status("Starter ComfyUI-server...")
comfyui_thread = threading.Thread(target=start_comfyui)
comfyui_thread.daemon = True
comfyui_thread.start()
# Vent på at ComfyUI starter
time.sleep(20)
# Sjekk om ComfyUI kjører
if not check_comfyui():
show_status("⚠️ ComfyUI kunne ikke starte. Sjekk loggene for feil.")
display(HTML('<p>Du kan sjekke loggene med: <code>!tail -50 /content/ComfyUI/comfyui.log</code></p>'))
else:
show_status("✅ ComfyUI-server startet vellykket!")
# Start Telegram bot
show_status("Starter Telegram-bot...")
# Alt er klart, start boten
bot = TelegramBot(BOT_TOKEN, CHAT_ID)
# Vis endelig melding
show_status("""
🚀 <b>ALT ER KLART!</b>
Din Telegram-bot er nå aktiv og klar til å motta kommandoer.
Sjekk Telegram for velkomstmeldingen.
<b>Alle modeller er installert:</b>
• EpicRealism + DreamShaper + JuggernautXL checkpoints
• AnimateDiff v2 + v3 motion modeller
• IP-Adapter (alle varianter) + CLIP Vision
• VAE modeller + populære LoRAs
• ControlNet modeller + Upscalers
Serveren vil fortsette å kjøre så lenge denne notebooken er åpen.
<b>For å forhindre tidsavbrudd:</b>
Installer Chrome-utvidelsen "Keep Colab Alive".
""", False)
bot.start()