Spaces:
Sleeping
Sleeping
File size: 48,929 Bytes
d8c9e3e 1ef6525 e2e353c f2b4e57 3eb3bc8 a7879e7 a2fba2c 24821f5 8fc0cc9 505e47d 07c87c2 048ec00 eda9678 048ec00 eda9678 07c87c2 a16d1ad 71c7c64 b6c1631 07c87c2 4ef6a50 0959b59 609963f 17ba4f0 8fc0cc9 4ef6a50 609963f 14aa6e2 f2b4e57 4a4441a f2b4e57 a2fba2c 630bca6 a2fba2c f2b4e57 a2fba2c fd344f9 a2fba2c f2b4e57 a2fba2c f2b4e57 a2fba2c fd344f9 26a123d 1ef6525 f2b4e57 1ef6525 f2b4e57 1ef6525 04b9bad 1ef6525 a2fba2c 4ef6a50 4bbb1b6 f637917 609963f f637917 4bbb1b6 f637917 4ef6a50 6f3bea7 4ef6a50 7fa98fe 4ef6a50 4bbb1b6 609963f f637917 2ee469f 71a70a2 695a675 71a70a2 f2b4e57 6f3bea7 71a70a2 04b9bad 71a70a2 7fa98fe d9cf50f 1a7921e a5b0b8b 1a7921e 168d77e 1a7921e 7fa98fe f637917 a5b0b8b f637917 f2b4e57 0841cb6 47c3727 6ec1fba ef10ef6 47c3727 fb0bc57 6ec1fba 2e71401 0841cb6 2f0e9d4 d57291a 2f0e9d4 6ec1fba d57291a 2f0e9d4 954055a 0841cb6 954055a fb0bc57 6ec1fba 0841cb6 f2b4e57 bfa8eb4 f2b4e57 bfa8eb4 f2b4e57 bfa8eb4 f2b4e57 bfa8eb4 67f27ea bfa8eb4 14aa6e2 7bf5dcb 14aa6e2 7bf5dcb bfa8eb4 7bf5dcb bfa8eb4 7bf5dcb bfa8eb4 f2b4e57 e5ba18f 6e96983 3eb3bc8 38acc2c e09e179 3eb3bc8 24821f5 8fc0cc9 24821f5 fb0bc57 e5ba18f f637917 3eb3bc8 07c87c2 a2fba2c 04b9bad ecfe07b 0841cb6 47c3727 4ef6a50 24821f5 07c87c2 4ef6a50 db28d8b 7fa98fe 47c3727 f2b4e57 4ef6a50 14f7722 3eb3bc8 04b9bad 8fc0cc9 3933cd9 8fc0cc9 f893fde 04b9bad f893fde 3933cd9 609963f e5ba18f f637917 bd52ae5 04b9bad 17ba4f0 a5b0b8b a3ab6f6 fb0bc57 e5ba18f f637917 7fa98fe a5b0b8b f2b4e57 4a97fe5 51bcfeb a2fba2c 04b9bad a5b0b8b fd344f9 a2fba2c 5716100 2f0e9d4 d7e835a f637917 fe4203b f637917 f2b4e57 86c9f8a 3a21356 86c9f8a 47c3727 f2b4e57 f637917 0841cb6 f637917 04b9bad f637917 a2fba2c 67f27ea 4f8c4d0 f637917 f893fde 04b9bad f893fde f637917 f2b4e57 b1ec392 f2b4e57 67f27ea b1ec392 4a4441a 67f27ea b1ec392 4a4441a b1ec392 4a4441a 98e4d76 f21d88d 233e224 f2b4e57 67f27ea f2b4e57 f9c6fb6 e7fd276 164b01d 233e224 f21d88d 8ef3ac8 f3c61a0 df1051e 8ef3ac8 14aa6e2 8ef3ac8 f3c61a0 8ef3ac8 c8ef1d3 8ef3ac8 f3c61a0 8ef3ac8 c8ef1d3 8ef3ac8 0e596dd 8ef3ac8 f38baa8 8ef3ac8 14aa6e2 f38baa8 8617fef 501dbc3 b61afdf f0759da b61afdf f0759da 501dbc3 f38baa8 8ef3ac8 c8ef1d3 8ef3ac8 4caed39 9053184 feff4e7 35223bc 9053184 4345d16 35223bc f4c4a43 8ef3ac8 e7fd276 f637917 e7fd276 f21d88d e7fd276 f21d88d f2b4e57 f21d88d f2b4e57 14aa6e2 f2b4e57 f21d88d f2b4e57 f21d88d f2b4e57 f21d88d 48b9be3 f2b4e57 f21d88d 48b9be3 f2b4e57 f21d88d 04b9bad f21d88d c3d1d7f 9d25f87 881b48e c3d1d7f 8d024f8 ab5067b c3d1d7f 14aa6e2 f2b4e57 c3d1d7f b1ec392 4c64e7b 76a3370 b1ec392 88051b8 7b9a254 b1ec392 76a3370 b1ec392 c3d1d7f f2b4e57 98e4d76 b1ec392 4a4441a b1ec392 4a4441a b1ec392 4a4441a b1ec392 4a4441a f2b4e57 f21d88d f2b4e57 f21d88d 7fa98fe f2b4e57 f91b000 74554e3 f91b000 74554e3 f2b4e57 f91b000 f21d88d f2b4e57 14aa6e2 f21d88d 6f7c7a1 b0bfded f21d88d 6f7c7a1 f2b4e57 6f7c7a1 f2b4e57 f91b000 f21d88d 54ea5b2 f21d88d f2b4e57 f21d88d bfa8eb4 f2b4e57 bfa8eb4 f2b4e57 bfa8eb4 f2b4e57 bfa8eb4 f2b4e57 6f7c7a1 f2b4e57 6f7c7a1 f2b4e57 6f7c7a1 f2b4e57 6f7c7a1 f2b4e57 6f7c7a1 f2b4e57 6f7c7a1 7e3aff9 6f7c7a1 7e3aff9 67f27ea 04b9bad f21d88d c3ced4e b0bfded f21d88d 98e4d76 f91b000 4c64e7b f91b000 f2b4e57 98e4d76 f91b000 4a4441a f91b000 4a4441a f91b000 4a4441a f91b000 4a4441a f91b000 4a4441a f2b4e57 67f27ea f2b4e57 67f27ea f2b4e57 67f27ea f21d88d 9bb097e f21d88d 7fa98fe f2b4e57 f91b000 f2b4e57 f21d88d 164b01d 14aa6e2 f2b4e57 c4901e6 f21d88d f637917 8a5dd6b f21d88d 81ca76c f21d88d a535883 6f3bea7 b428d2b 954055a |
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 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 |
import gradio as gr
from diffusers import StableDiffusionPipeline, StableDiffusionImg2ImgPipeline
from diffusers import StableDiffusionInpaintPipeline
import torch
from PIL import Image, ImageDraw, ImageFont
import time
import os
import tempfile
import random
import re # Für reguläre Ausdrücke zur Gewichtserkennung
#Der Code ist perfekt für 512x512. Keine Verarbeitung großer Bilder, keine variablen Slider!
# === AUTOMATISCHE NEGATIVE PROMPT GENERIERUNG ===
def auto_negative_prompt(positive_prompt):
"""Generiert automatisch negative Prompts basierend auf dem positiven Prompt"""
p = positive_prompt.lower()
negatives = []
# Personen / Portraits
if any(w in p for w in [
"person", "man", "woman", "face", "portrait", "team", "employee",
"people", "crowd", "character", "figure", "human", "child", "baby",
"girl", "boy", "lady", "gentleman", "fairy", "elf", "dwarf", "santa claus",
"mermaid", "angel", "demon", "witch", "wizard", "creature", "being",
"model", "actor", "actress", "celebrity", "avatar"]):
negatives.append(
"blurry face, lowres face, deformed pupils, bad anatomy, malformed hands, extra fingers, uneven eyes, distorted face, "
"unrealistic skin, mutated, deformed, ugly, disfigured, poorly drawn face, "
"missing limbs, extra limbs, fused fingers, too many fingers, bad teeth, "
"mutated hands, long neck, extra wings, multiple wings, grainy face, noisy face, "
"compression artifacts, rendering artifacts, digital artifacts, overprocessed face, oversmoothed face "
)
# Business / Corporate
if any(w in p for w in ["office", "business", "team", "meeting", "corporate", "company", "workplace"]):
negatives.append(
"overexposed, oversaturated, harsh lighting, watermark, text, logo, amateur photo, lens flare, chromatic aberration, brand"
)
# Produkt / CGI
if any(w in p for w in ["product", "packshot", "mockup", "render", "3d", "cgi", "packaging"]):
negatives.append(
"plastic texture, noisy, overly reflective surfaces, watermark, text, render artifacts, unrealistic shadows, 3d model artifacts, low poly"
)
# Landschaft / Umgebung
if any(w in p for w in ["landscape", "nature", "mountain", "forest", "outdoor", "beach", "sky"]):
negatives.append(
"blurry, oversaturated, unnatural colors, distorted horizon, repeating patterns, plastic grass, unrealistic water, floating objects"
)
# Logos / Symbole
if any(w in p for w in ["logo", "symbol", "icon", "typography", "badge", "emblem"]):
negatives.append(
"watermark, signature, username, text, writing, scribble, pixelated, distorted shapes, misaligned elements, messy"
)
# Architektur / Gebäude
if any(w in p for w in ["building", "architecture", "house", "interior", "room", "facade"]):
negatives.append(
"deformed, distorted perspective, floating objects, unrealistic materials, leaning building, warped surfaces, collapsing structure"
)
# Kunst / Stil (NEUE KATEGORIE)
if any(w in p for w in ["art", "painting", "drawing", "illustration", "sketch", "artwork", "creative", "style"]):
negatives.append(
"3d render, cgi, cartoon, anime, painting, drawing, sketch, plastic look, digital painting, unrealistic"
)
# Basis negative Prompts für alle Fälle
base_negatives = "low quality, worst quality, blurry, jpeg artifacts, ugly, deformed"
if negatives:
result = base_negatives + ", " + ", ".join(negatives)
else:
result = base_negatives
print(f"🔍 Automatischer Negativ-Prompt generiert: {result[:100]}...")
return result
# === OPTIMIERTE EINSTELLUNGEN ===
device = "cuda" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16 if device == "cuda" else torch.float32
IMG_SIZE = 512
print(f"Running on: {device}")
# === AUDIO-URL ===
AUDIO_URL = "https://dn721801.ca.archive.org/0/items/emotional-soft-piano-music-413513-2/emotional-soft-piano-music-413513%202.mp3"
# === TEXT INTEGRATION IMPORT ===
from text_integration import (
add_text_to_image,
create_text_integration_section_t2i,
create_text_integration_section_i2i,
capture_click,
update_text_preview_i2i,
update_text_preview_t2i
)
# === GESICHTSMASKEN-FUNKTIONEN ===
def create_face_mask(image, bbox_coords, face_preserve):
"""Erzeugt eine Gesichtsmaske - WEIßE Bereiche werden VERÄNDERT, SCHWARZE BLEIBEN"""
mask = Image.new("L", image.size, 0)
if bbox_coords and all(coord is not None for coord in bbox_coords):
x1, y1, x2, y2 = bbox_coords
draw = ImageDraw.Draw(mask)
if face_preserve:
draw.rectangle([0, 0, image.size[0], image.size[1]], fill=255)
draw.rectangle([x1, y1, x2, y2], fill=0)
print("Gesicht wird GESCHÜTZT - Umgebung wird verändert")
else:
draw.rectangle([x1, y1, x2, y2], fill=255)
print("Nur Gesicht wird verändert - Umgebung bleibt erhalten")
return mask
def auto_detect_face_area(image):
"""Optimierten Vorschlag für Gesichtsbereich ohne externe Bibliotheken"""
width, height = image.size
face_size = min(width, height) * 0.4
x1 = (width - face_size) / 2
y1 = (height - face_size) / 4
x2 = x1 + face_size
y2 = y1 + face_size * 1.2
x1, y1 = max(0, int(x1)), max(0, int(y1))
x2, y2 = min(width, int(x2)), min(height, int(y2))
print(f"Geschätzte Gesichtskoordinaten: [{x1}, {y1}, {x2}, {y2}]")
return [x1, y1, x2, y2]
# === PIPELINES ===
pipe_txt2img = None
pipe_img2img = None
def load_txt2img():
global pipe_txt2img
if pipe_txt2img is None:
print("Loading Text-to-Image model...")
pipe_txt2img = StableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5",
torch_dtype=torch_dtype,
use_safetensors=True,
safety_checker=None,
requires_safety_checker=False,
).to(device)
from diffusers import DPMSolverMultistepScheduler
pipe_txt2img.scheduler = DPMSolverMultistepScheduler.from_config(pipe_txt2img.scheduler.config)
pipe_txt2img.enable_attention_slicing()
return pipe_txt2img
def load_img2img():
global pipe_img2img
if pipe_img2img is None:
print("Loading Inpainting model...")
try:
pipe_img2img = StableDiffusionInpaintPipeline.from_pretrained(
"runwayml/stable-diffusion-inpainting",
torch_dtype=torch_dtype,
allow_pickle=False,
safety_checker=None,
).to(device)
except Exception as e:
print(f"Fehler beim Laden des Modells: {e}")
raise
from diffusers import DPMSolverMultistepScheduler
pipe_img2img.scheduler = DPMSolverMultistepScheduler.from_config(
pipe_img2img.scheduler.config,
algorithm_type="sde-dpmsolver++",
use_karras_sigmas=True,
timestep_spacing="trailing"
)
pipe_img2img.enable_attention_slicing()
pipe_img2img.enable_vae_tiling()
pipe_img2img.vae_slicing = True
return pipe_img2img
# === CALLBACK-FUNKTIONEN ===
class TextToImageProgressCallback:
def __init__(self, progress, total_steps):
self.progress = progress
self.total_steps = total_steps
self.current_step = 0
def __call__(self, pipe, step, timestep, callback_kwargs):
self.current_step = step + 1
progress_percent = (step / self.total_steps) * 100
self.progress(progress_percent / 100, desc="Generierung läuft - CPU benötigt bis zu 10 Minuten!")
return callback_kwargs
class ImageToImageProgressCallback:
def __init__(self, progress, total_steps, strength):
self.progress = progress
self.total_steps = total_steps
self.current_step = 0
self.strength = strength
self.actual_total_steps = None
def __call__(self, pipe, step, timestep, callback_kwargs):
self.current_step = step + 1
if self.actual_total_steps is None:
if self.strength < 1.0:
self.actual_total_steps = int(self.total_steps * self.strength)
else:
self.actual_total_steps = self.total_steps
print(f"🎯 INTERNE STEP-AUSGABE: Strength {self.strength} → {self.actual_total_steps} tatsächliche Denoising-Schritte")
progress_percent = (step / self.actual_total_steps) * 100
self.progress(progress_percent / 100, desc="Generierung läuft - CPU benötigt bis zu 10 Minuten!")
return callback_kwargs
# === VORSCHAU-FUNKTIONEN ===
def create_preview_image(image, bbox_coords, face_preserve, mode_color):
"""Erstellt eine Vorschau mit farbigem Rahmen basierend auf dem Modus"""
if image is None:
return None
preview = image.copy()
draw = ImageDraw.Draw(preview)
if mode_color == "red":
border_color = (255, 0, 0, 180)
mode_text = "NUR BILDELEMENT VERÄNDERN"
else:
border_color = (0, 255, 0, 180)
mode_text = "BILDELEMENT BEIBEHALTEN"
border_width = 8
draw.rectangle([0, 0, preview.width-1, preview.height-1],
outline=border_color, width=border_width)
if bbox_coords and all(coord is not None for coord in bbox_coords):
x1, y1, x2, y2 = bbox_coords
box_color = (255, 255, 0, 200)
draw.rectangle([x1, y1, x2, y2], outline=box_color, width=3)
text_color = (255, 255, 255)
bg_color = (0, 0, 0, 160)
text_bbox = draw.textbbox((x1, y1 - 25), mode_text)
draw.rectangle([text_bbox[0]-5, text_bbox[1]-2, text_bbox[2]+5, text_bbox[3]+2],
fill=bg_color)
draw.text((x1, y1 - 25), mode_text, fill=text_color)
return preview
def update_live_preview(image, bbox_x1, bbox_y1, bbox_x2, bbox_y2, face_preserve):
"""Aktualisiert die Live-Vorschau bei Koordinaten-Änderungen"""
if image is None:
return None
bbox_coords = [bbox_x1, bbox_y1, bbox_x2, bbox_y2]
mode_color = "green" if face_preserve else "red"
return create_preview_image(image, bbox_coords, face_preserve, mode_color)
# === AUDIO-FUNKTION ===
def play_audio_on_image_click():
"""Startet die Musikwiedergabe bei Klick auf das Bild"""
print("🎵 Musikwiedergabe wird gestartet...")
return gr.Audio(AUDIO_URL, autoplay=True, visible=True, label="Hintergrundmusik")
# === NEUE FUNKTION: STOP AUDIO BEIM TAB-WECHSEL ===
def stop_audio_on_tab_change():
"""Stoppt die Musik beim Tab-Wechsel"""
print("🔇 Musik wird beim Tab-Wechsel gestoppt")
return None
def process_image_upload(image):
"""Verarbeitet Bild-Upload und gibt Bild + Koordinaten zurück"""
if image is None:
return None, None, None, None, None
width, height = image.size
if width > 512 or height > 512:
# Große Bilder: Keine bbox benötigt, nur Vorschau
preview = create_preview_image(image, None, True, "green") #create_preview_image Funktion erstellt nur die visuelle Vorschau
return preview, None, None, None, None
else:
# Kleine Bilder: bbox wie gehabt berechnen
bbox = auto_detect_face_area(image)
bbox_x1, bbox_y1, bbox_x2, bbox_y2 = bbox
preview = create_preview_image(image, bbox, True, "green")
return preview, bbox_x1, bbox_y1, bbox_x2, bbox_y2
# === HAUPTPROZESSE ===
def text_to_image(prompt, steps, guidance_scale, progress=gr.Progress()):
try:
if not prompt or not prompt.strip():
return None, None
print(f"Starting generation for: {prompt}")
start_time = time.time()
# Liste von Qualitätswörtern/Gewichten, die auf Benutzereingaben prüfen
quality_keywords = ['masterpiece', 'best quality', 'high quality', 'highly detailed',
'exquisite', 'detailed', 'ultra detailed', 'professional',
'perfect', 'excellent', 'amazing', 'stunning', 'beautiful']
# Prüfe, ob der Benutzer bereits Qualitätswörter/Gewichte verwendet hat
user_has_quality_words = False
# Konvertiere Prompt zu Kleinbuchstaben für die Prüfung
prompt_lower = prompt.lower()
# Prüfe auf einfache Qualitätswörter
for keyword in quality_keywords:
if keyword in prompt_lower:
user_has_quality_words = True
print(f"✓ Benutzer verwendet bereits Qualitätswort: {keyword}")
break
# Prüfe auf Gewichte (z.B. (word:1.5), [word], etc.)
weight_patterns = [r'\([^)]+:\d+(\.\d+)?\)', r'\[[^\]]+\]']
for pattern in weight_patterns:
if re.search(pattern, prompt):
user_has_quality_words = True
print("✓ Benutzer verwendet bereits Gewichte im Prompt")
break
# Prompt basierend auf Prüfung anpassen
if not user_has_quality_words:
enhanced_prompt = f"masterpiece, raw, best quality, highly detailed, {prompt}"
print(f"🔄 Verbesserter Prompt: {enhanced_prompt}")
else:
enhanced_prompt = prompt
print("✓ Benutzerprompt wird unverändert verwendet")
print(f"Finaler Prompt für Generation: {enhanced_prompt}")
progress(0, desc="Generierung läuft - CPU benötigt bis zu 10 Minuten!")
pipe = load_txt2img()
# Automatischen Negativ-Prompt generieren
neg_prompt = auto_negative_prompt(prompt)
print(f"🔍 Verwendeter Negativ-Prompt: {neg_prompt}")
seed = random.randint(0, 2**32 - 1)
generator = torch.Generator(device=device).manual_seed(seed)
print(f"Using seed: {seed}")
callback = TextToImageProgressCallback(progress, steps)
image = pipe(
prompt=enhanced_prompt,
negative_prompt=neg_prompt, # Automatischen Negativ-Prompt verwenden
height=IMG_SIZE,
width=IMG_SIZE,
num_inference_steps=int(steps),
guidance_scale=guidance_scale,
generator=generator,
callback_on_step_end=callback,
callback_on_step_end_tensor_inputs=[],
).images[0]
end_time = time.time()
print(f"Bild generiert in {end_time - start_time:.2f} Sekunden")
return image, image
except Exception as e:
print(f"Fehler: {e}")
import traceback
traceback.print_exc()
return None, None
def img_to_image(image, prompt, neg_prompt, strength, steps, guidance_scale, face_preserve, bbox_x1, bbox_y1, bbox_x2, bbox_y2, progress=gr.Progress()):
try:
if image is None:
return None
print(f"Img2Img Start → Strength: {strength}, Steps: {steps}, Guidance: {guidance_scale}")
start_time = time.time()
# ===== NEU: AUTOMATISCHEN NEGATIV-PROMPT GENERIEREN =====
auto_negatives = auto_negative_prompt(prompt)
print(f"🤖 Automatisch generierter Negativ-Prompt: {auto_negatives}")
# ===== NEU: KOMBINIERE MANUELLEN UND AUTOMATISCHEN PROMPT =====
combined_negative_prompt = ""
if neg_prompt and neg_prompt.strip():
# Benutzer hat einen Negativ-Prompt eingegeben
user_neg = neg_prompt.strip()
print(f"👤 Benutzer Negativ-Prompt: {user_neg}")
# Entferne Duplikate zwischen automatischen und manuellen Prompts
# Konvertiere beide in Sets für einfachen Duplikatvergleich
user_words = [word.strip().lower() for word in user_neg.split(",")]
auto_words = [word.strip().lower() for word in auto_negatives.split(",")]
# Starte mit dem Benutzer-Prompt
combined_words = user_words.copy()
# Füge automatische Wörter hinzu, die nicht bereits vorhanden sind
for auto_word in auto_words:
if auto_word and auto_word not in user_words:
combined_words.append(auto_word)
# Zusammenfügen und Duplikate entfernen (für den Fall von Duplikaten innerhalb des gleichen Prompts)
unique_words = []
seen_words = set()
for word in combined_words:
if word and word not in seen_words:
unique_words.append(word)
seen_words.add(word)
combined_negative_prompt = ", ".join(unique_words)
else:
# Kein Benutzer-Prompt, verwende nur den automatischen
combined_negative_prompt = auto_negatives
print(f"ℹ️ Kein manueller Negativ-Prompt, verwende nur automatischen: {combined_negative_prompt}")
print(f"✅ Finaler kombinierter Negativ-Prompt: {combined_negative_prompt}")
# ===== ENDE DER NEUEN LOGIK =====
progress(0, desc="Generierung läuft - CPU benötigt bis zu 10 Minuten!")
pipe = load_img2img()
img_resized = image.convert("RGB").resize((IMG_SIZE, IMG_SIZE))
adj_strength = min(0.85, strength * 1.3)
adj_guidance = min(guidance_scale, 12.0)
seed = random.randint(0, 2**32 - 1)
generator = torch.Generator(device=device).manual_seed(seed)
print(f"Using seed: {seed}")
mask = None
bbox_coords = None
if bbox_x1 is not None and bbox_y1 is not None and bbox_x2 is not None and bbox_y2 is not None:
orig_width, orig_height = image.size
scale_x = IMG_SIZE / orig_width
scale_y = IMG_SIZE / orig_height
scaled_coords = [
int(bbox_x1 * scale_x),
int(bbox_y1 * scale_y),
int(bbox_x2 * scale_x),
int(bbox_y2 * scale_y)
]
bbox_coords = scaled_coords
if bbox_coords:
mask = create_face_mask(img_resized, bbox_coords, face_preserve)
callback = ImageToImageProgressCallback(progress, int(steps), adj_strength)
result = pipe(
prompt=prompt,
negative_prompt=combined_negative_prompt,
image=img_resized,
mask_image=mask,
strength=adj_strength,
num_inference_steps=int(steps),
guidance_scale=adj_guidance,
generator=generator,
callback_on_step_end=callback,
callback_on_step_end_tensor_inputs=[],
)
end_time = time.time()
print(f"Bild transformiert in {end_time - start_time:.2f} Sekunden")
generated_image = result.images[0]
return generated_image
except Exception as e:
print(f"Fehler: {e}")
import traceback
traceback.print_exc()
return None
# === TEXT INTEGRATION HANDLER ===
def handle_text_integration_i2i(original_image, generated_image, text, text_x, text_y, font_size, font_family, font_color, target_selector):
"""Verwaltet Text-Integration für Bild-zu-Bild basierend auf Auswahl"""
if target_selector == "Originalbild":
target_image = original_image
else: # "Generiertes Bild"
target_image = generated_image
result = add_text_to_image(target_image, text, text_x, text_y, font_size, font_family, font_color)
# Rückgabe: Original bleibt unverändert, Text-Bild kommt in Download-Bereich
return original_image, result
def handle_text_integration_t2i(generated_image, text, text_x, text_y, font_size, font_family, font_color):
"""Verwaltet Text-Integration für Text-zu-Bild"""
result = add_text_to_image(generated_image, text, text_x, text_y, font_size, font_family, font_color)
return result
def main_ui():
with gr.Blocks(
title="AI Image Generator",
theme=gr.themes.Base(),
css="""
.info-box {
background-color: #f8f4f0;
padding: 15px;
border-radius: 8px;
border-left: 4px solid #8B7355;
margin: 20px 0;
}
.text-integration-section {
background: #e8f5e8;
padding: 15px;
border-radius: 8px;
margin: 15px 0;
border-left: 4px solid #4caf50;
}
.clickable-file {
color: #8B7355;
text-decoration: underline;
font-weight: bold;
}
.clickable-file:hover {
color: #6b5a45;
}
/* === CSS SCROLL-LÖSUNG === */
.tab-nav {
scroll-margin-top: 0 !important;
}
[data-testid="tab-text-zu-bild"] {
scroll-margin-top: 0 !important;
}
.tab-button {
scroll-margin-top: 0 !important;
}
.gr-tab-item {
scroll-margin-top: 0 !important;
}
.gr-block {
scroll-margin-top: 0 !important;
}
.gr-column {
scroll-margin-top: 0 !important;
scroll-padding-top: 0 !important;
}
"""
) as demo:
# --- Info-Bereich (Startseite) ---
gr.Markdown(
"""
# Demo-Projekt: Stable Diffusion Text-to-Image / Image-to-Image
<br>
<div class="info-box" style="border-left: 4px solid #4F46E5; background: linear-gradient(135deg, #f8faff 0%, #ffffff 100%);">
<div style="font-size: 1.2em; font-weight: bold; color: #4F46E5; margin-bottom: 15px;"><strong>🎯 Projekt & Kompetenzen</strong></div>
Dieses 4-Wochen-Projekt ist ein kleines <strong>Demo</strong> um meine zentralen Kompetenzen als <strong>AI-Engineer</strong> – sowohl in der technischen Umsetzung <br>
als auch in der strukturierten Entwicklung komplexer Workflows zu präsentieren. Es bildet <strong>grundlegende Stable-Diffusion-Prozesse</strong> ab, während ich in anderen <br>
GPU-basierten Umgebungen <strong>erweitered Text-to-Image und Image-to-Image-Pipelines mit präzisem Inpainting über ControlNet</strong> realisiere. Durch den Einsatz von <br>
<strong>multi-modalen Modellen mit höherer Parameteranzahl</strong> wird eine deutlich detailliertere und kontrolliertere Bildgenerierung ermöglicht.
</div>
<br>
<div class="info-box" style="border-left: 4px solid #10B981; background: linear-gradient(135deg, #f0fdf4 0%, #ffffff 100%);">
<div style="font-size: 1.2em; font-weight: bold; color: #10B981; margin-bottom: 15px;"><strong>📊 Professionelle-Architektur & Roadmap</strong></div>
Zudem führt der Link
<a class="clickable-file" href="https://huggingface.co/spaces/Astridkraft/Dokumentation" target="_blank">Roadmap</a>
zu einer <strong>durchdachten, skalierbaren, professionellen Code-Architektur</strong> für Text-to-Image- und Image-to-Image-Entwicklung <br>
die die <strong>gesamte Komplexität einer professionellen Umsetzung</strong> verdeutlicht.<br><br>
Die hiermit gezeigten Fähigkeiten meinerseits sind <strong>sicherlich auf andere Projekte übertragbar</strong>.
</div>
<br>
<div class="info-box" style="border-left: 4px solid #F59E0B; background: linear-gradient(135deg, #fffbeb 0%, #ffffff 100%);">
<div style="font-size: 1.2em; font-weight: bold; color: #F59E0B; margin-bottom: 15px;"><strong>⚠️ Wichtiger Hinweis</strong></div>
Die Anwendung läuft derzeit auf <strong>CPU</strong> ist jedoch <strong>vollständig GPU-fähig </strong>.
Deshalb muss bei jeder Generierung eine <strong>längere Wartezeit</strong> eingeplant werden.<br>
Bei <strong>Verbindungsabbrüchen</strong> -insbesondere bei CPU-Nutzung- wird die aktuelle Generierung zunächst serverseitig vollständig abgeschlossen, <br>
bevor neue Anfragen bearbeitet werden. Das generierte Bild wird in diesem Fall <strong>nicht angezeigt</strong>.
Die Meldung <strong>Connection re-established</strong> signalisiert, dass <br>
die Verbindung wiederhergestellt wurde, die laufende Verarbeitung jedoch priorisiert wird. In der Konsequenz werden neue <br>
Generierungsanfragen in eine Warteschlange gestellt und erst nach vollständigem Abschluss der aktuellen serverseitigen Berechnung verarbeitet.
</div>
<br>
<div class="info-box" style="border-left: 4px solid #EF4444; background: linear-gradient(135deg, #fef2f2 0%, #ffffff 100%);">
<div style="font-size: 1.2em; font-weight: bold; color: #EF4444; margin-bottom: 15px;"><strong>🔧 Technischer Hintergrund</strong></div>
Die Anwendung nutzt <strong>Gradio auf Hugging Face Spaces</strong> - eine Technologie, die <strong>keine temporäre Speicherung</strong>
generierter Bilder vorsieht. Jede Verbindung <br> wird als <strong>unabhängige Sitzung</strong> behandelt.
Dies wird <strong>besonders bei CPU-Nutzung relevant</strong>, da längere Transformationszeiten die Wahrscheinlichkeit
für <br> Timeouts und Seiten-Neuladungen erhöhen. Obwohl die Bildgenerierung serverseitig vollständig abgeschlossen wird,
kann das Ergebnis bei <br> Verbindungsunterbrechungen <strong>nicht an die neu geladene Seite übermittelt</strong> werden.<br><br>
</div>
<br>
<div class="info-box" style="border-left: 4px solid #8B5CF6; background: linear-gradient(135deg, #faf5ff 0%, #ffffff 100%);">
<div style="font-size: 1.2em; font-weight: bold; color: #8B5CF6; margin-bottom: 15px;"><strong>🔄 Anwendungsbereich & Workflow</strong></div>
Die Bild-zu-Bild-Transformation ermöglicht die <strong>gezielte Modifikation bestehender Bildelemente</strong> -
beispielsweise die Umwandlung einer Laterne <br> in eine Fackel, einer Katze in einen Hund, oder die Versetzung einer Person
vom Büro an einen tropischen Strand bei Beibehaltung des Gesichts.<br>
Es können <strong>keine neuen Objekte generiert</strong>, sondern ausschließlich <strong>vorhandene Elemente transformiert</strong> werden.<br><br>
Die Funktion unterstützt zwei operative Modi:<br>
• <strong>Umgebungstransformation:</strong> Veränderung der Umgebung bei Beibehaltung eines markierten Bildbereichs (z.B. Gesicht)<br>
• <strong>Fokustransformation:</strong> Veränderung eines markierten Bereichs (z.B. Objekt) bei Beibehaltung der Umgebung<br><br>
<strong>Optimale Workflow-Empfehlung:</strong><br>
Zur Gewährleistung optimaler Ergebnisse werden Bilder im Format <strong>512×512 Pixel</strong> verarbeitet.
Ein effizienter Workflow umfasst:<br>
1. Generierung von Basis-Bildern über <strong>Text-zu-Bild</strong><br>
2. Gezielte Transformation über <strong>Bild-zu-Bild</strong><br>
3. Optionale Textintegration auf generierten oder originalen Basis-Bildern<br>
<strong>Audio-Unterstützung:</strong><br>
Im Arbeitsbereich Text-zu-Bild steht eine <strong>Hintergrundmusik-Funktion</strong> zur Verfügung, die die Generierungszeit überbrückt. Der integrierte Audio-Player <br>
wird beim Tab-Wechsel unterbrochen.<br>
<strong>Die Textintegration </strong> ist verfügbar für generierte Bilder in beiden Arbeitsbereichen sowie für externe Bildquellen im Arbeitsbereich Bild zu Bild.<br>
Es werden alle gängigen Bildformate (JPG, PNG, WEBP, BMP, TIFF) unterstützt. Die maximale Dateigröße beträgt 15 MB.<br><br>
<strong>📱💻🖥️ Plattformübergreifende Kompatibilität:</strong><br>
Die Anwendung ist vollständig optimiert für <strong>Desktop, Tablet und Smartphone</strong> - nutzbar mit Maus, Touchscreen oder kombinierter Bedienung.<br>
<strong>📱 Mobile Nutzung</strong>
<strong>Hinweis zur Anzeige:</strong> Beim Wechsel von der Startseite zur Anwendung kann es auf einigen Mobilgeräten vorkommen, dass der Inhalt zunächst im<br>
unteren Bereich angezeigt wird. Bitte <strong>scrollen Sie gegebenenfalls nach oben</strong>, um die vollständige Oberfläche zu sehen. Dies ist eine <br>
technische Einschränkung der Hugging Face Plattform.
</div>
<br><br>
<div class="info-box" style="border-left: 4px solid #EC4899; background: linear-gradient(135deg, #fdf2f8 0%, #ffffff 100%);">
<div style="font-size: 1.2em; font-weight: bold; color: #EC4899; margin-bottom: 15px;"><strong>💡 Empfehlungen & Best Practices</strong></div>
Für eine präzise Abstimmung der zentralen Parameter – Prompt, Negativ-Prompt, Veränderungsstärke (Strength), Inferenz-Schritte (Steps) <br>
und Prompt-Stärke (Guidance) – liefern leistungsfähige Sprachmodelle wie GPT, Grok oder DeepSeek hochqualitative, kontextbezogene Vorschläge.<br>
Prompt und Negativ-Prompt sollten auf <strong>Englisch</strong> eingegeben werden, da "Stable Diffusion" mit Bild-Text-Paaren auf Englisch trainiert <br>
wurde und CLIP einen Tokenizer für ein englisches Vokabular nutzt. Der CLIP-Tokenizer hat außerdem ein <strong>Limit von 77 Token</strong>, wodurch längere <br>
Prompteingaben automatisch abgeschnitten werden. Deutsche Wörter werden zwar übersetzt, führen aber zu Verzerrungen.
</div>
<br><br>
<div class="info-box" style="border-left:4px solid #EA580C; background: linear-gradient(135deg, #FFF7ED 0%, #FFFFFF 100%); padding: 16px; border-radius: 8px; margin-bottom: 24px;display: block; width: 100%;">
<div style="font-size: 1.2em; font-weight: bold; color: #EA580C; margin-bottom: 15px;"><strong>⏳ Hinweis zur ersten Nutzung</strong></div>
Beim <strong>allerersten Aufruf</strong> der Anwendung (oder nach längerer Inaktivität) kann das Laden der Stable-Diffusion-Modelle und aller benötigten Komponenten in den <br>
Arbeitsspeicher <strong>30–90 Sekunden</strong> dauern.
Dies geschieht nur einmal pro Session bzw. nach Neustart des Spaces – danach sind alle Generierungen deutlich schneller.<br>
<div style="text-align: center; font-weight: 600; color: #C2410C; margin-top: 10px; padding: 10px 0;">
Vielen Dank für Ihre Geduld – es lohnt sich! ✨
</div>
</div>
<br><br>
"""
)
# --- Button zentriert im unteren Drittel, Taupe-Farbe ---
with gr.Row():
with gr.Column(scale=1): # Linker Leerraum
pass
with gr.Column(scale=1, min_width=300): # Mittig, feste Mindestbreite
start_btn = gr.Button(
"Weiter zur Anwendung",
variant="primary",
size="lg",
elem_id="start-button"
)
with gr.Column(scale=1): # Rechter Leerraum
pass
# --- Hauptanwendungsbereich ---
with gr.Column(visible=False) as content_area:
# === TAB: TEXT ZU BILD ===
with gr.Tab("Text zu Bild") as tab_text_to_image:
gr.Markdown("**Beschreibe dein gewünschtes Bild:**")
with gr.Row():
txt_input = gr.Textbox(
placeholder="z.B. ultra realistic mountain landscape at sunrise...",
lines=2,
label="Prompt (Englisch)"
)
with gr.Row():
with gr.Column():
txt_steps = gr.Slider(
minimum=10, maximum=40, value=30, step=1,
label="Inferenz-Schritte"
)
with gr.Column():
txt_guidance = gr.Slider(
minimum=1.0, maximum=12.0, value=7.5, step=0.5,
label="Prompt-Stärke"
)
generate_btn = gr.Button("Bild generieren", variant="primary")
# NEUE ANORDNUNG: Bilder nebeneinander
with gr.Row():
with gr.Column():
txt_output = gr.Image(
label="Generiertes Bild",
show_download_button=True,
type="pil",
height=400,
sources=[] #damit verschwinden die Upload-Symbole, nicht gut für Desktop!
)
with gr.Column():
preview_t2i = gr.Image(
label="Vorschau für Textposition (Klicken/Tippen um Position zu wählen)",
interactive=True,
type="pil",
height=400,
sources=[] #Button verschwinden, download trotzdem möglich! Gradio-Problem
)
# SICHTBARER AUDIO-PLAYER FÜR TEXT-ZU-BILD
hidden_audio_t2i = gr.Audio(
visible=True,
label="🎵 Hintergrundmusik zur Überbrückung der Wartezeit",
autoplay=True # WICHTIG: Hier autoplay setzen
)
# Klickbarer Bereich um das Bild
with gr.Row():
music_btn = gr.Button(
"🎵 Musik abspielen",
variant="secondary",
size="sm"
)
# Klick-Event für den Button
music_btn.click(
fn=play_audio_on_image_click,
outputs=hidden_audio_t2i
)
# TEXT INTEGRATION UNTERHALB DER BILDER
with gr.Row():
gr.Markdown("### 📝 Text auf Bild integrieren")
with gr.Row():
text_input_t2i = gr.Textbox(
label="Text eingeben",
placeholder="Dein Text hier...",
max_lines=2,
scale=3
)
# NEUE TEXT-FORMATIERUNGSOPTIONEN
with gr.Row():
with gr.Column():
font_size_t2i = gr.Dropdown(
choices=["60px", "50px", "40px", "30px", "20px"],
value="40px",
label="Schriftgröße"
)
with gr.Column():
font_family_t2i = gr.Dropdown(
choices=["Standard", "Einfache Handschrift", "Verschnörkelte Handschrift"],
value="Standard",
label="Schriftart"
)
with gr.Column():
font_color_t2i = gr.Dropdown(
choices=["Weiß", "Schwarz", "Rot"],
value="Weiß",
label="Schriftfarbe"
)
with gr.Row():
text_x_t2i = gr.Number(value=None, visible=False)
text_y_t2i = gr.Number(value=None, visible=False)
with gr.Row():
text_btn_t2i = gr.Button("📝 Text auf generiertes Bild", variant="secondary")
# CLICK HANDLER FÜR TEXT-zu-BILD
preview_t2i.select(
fn=capture_click,
outputs=[text_x_t2i, text_y_t2i]
)
# LIVE-TEXT-VORSCHAU FÜR TEXT-ZU-BILD MIT FORMATIERUNG
text_inputs_t2i = [txt_output, text_input_t2i, text_x_t2i, text_y_t2i, font_size_t2i, font_family_t2i, font_color_t2i]
text_input_t2i.change(
fn=update_text_preview_t2i,
inputs=text_inputs_t2i,
outputs=preview_t2i
)
text_x_t2i.change(
fn=update_text_preview_t2i,
inputs=text_inputs_t2i,
outputs=preview_t2i
)
text_y_t2i.change(
fn=update_text_preview_t2i,
inputs=text_inputs_t2i,
outputs=preview_t2i
)
font_size_t2i.change(
fn=update_text_preview_t2i,
inputs=text_inputs_t2i,
outputs=preview_t2i
)
font_family_t2i.change(
fn=update_text_preview_t2i,
inputs=text_inputs_t2i,
outputs=preview_t2i
)
font_color_t2i.change(
fn=update_text_preview_t2i,
inputs=text_inputs_t2i,
outputs=preview_t2i
)
# EVENT-HANDLER TEXT-zu-BILD
generate_btn.click(
fn=text_to_image,
inputs=[txt_input, txt_steps, txt_guidance],
outputs=[txt_output, preview_t2i],
concurrency_limit=1
)
text_btn_t2i.click(
fn=handle_text_integration_t2i,
inputs=[
txt_output,
text_input_t2i,
text_x_t2i,
text_y_t2i,
font_size_t2i,
font_family_t2i,
font_color_t2i
],
outputs=txt_output
)
# === TAB: BILD ZU BILD ===
with gr.Tab("Bild zu Bild") as tab_image_to_image:
gr.Markdown("**Lade ein Bild hoch und beschreibe die gewünschte Veränderung:**")
with gr.Row():
with gr.Column():
img_input = gr.Image(
type="pil",
label="Eingabebild",
height=300,
#sources=["upload"]
)
with gr.Column():
preview_output = gr.Image(
label="Live-Vorschau mit Maske (Klicken/Tippen für Textposition)",
height=300,
interactive=True,
show_download_button=False,
sources=[]
)
with gr.Row():
face_preserve = gr.Checkbox(
label="Schutz",
value=True,
info="🟢 AN: Umgebung verändern | 🔴 AUS: Objekt verändern"
)
with gr.Row():
with gr.Column():
bbox_x1 = gr.Slider(label="Links (x1)", minimum=0, maximum=512, value=100, step=1)
with gr.Column():
bbox_y1 = gr.Slider(label="Oben (y1)", minimum=0, maximum=512, value=100, step=1)
with gr.Row():
with gr.Column():
bbox_x2 = gr.Slider(label="Rechts (x2)", minimum=0, maximum=512, value=300, step=1)
with gr.Column():
bbox_y2 = gr.Slider(label="Unten (y2)", minimum=0, maximum=512, value=300, step=1)
with gr.Row():
with gr.Column():
img_prompt = gr.Textbox(
placeholder="change background to beach with palm trees...",
lines=2,
label="Transformations-Prompt"
)
with gr.Column():
img_neg_prompt = gr.Textbox(
placeholder="blurry, deformed, ugly...",
lines=2,
label="Negativ-Prompt"
)
with gr.Row():
with gr.Column():
strength_slider = gr.Slider(minimum=0.1, maximum=0.9, value=0.4, step=0.05, label="Veränderungs-Stärke")
with gr.Column():
img_steps = gr.Slider(minimum=10, maximum=35, value=30, step=1, label="Inferenz-Schritte")
with gr.Column():
img_guidance = gr.Slider(minimum=1.0, maximum=11.0, value=7.5, step=0.5, label="Prompt-Stärke")
transform_btn = gr.Button("Bild transformieren", variant="primary")
with gr.Row():
img_output = gr.Image(
label="Transformiertes Bild",
show_download_button=True,
type="pil",
sources=[]
)
# TEXT INTEGRATION FÜR BILD-zu-BILD mit Pulldown-Menüs
with gr.Row():
gr.Markdown("### 📝 Text auf Bild integrieren")
with gr.Row():
text_input_i2i = gr.Textbox(
label="Text eingeben",
placeholder="Dein Text hier...",
max_lines=2,
scale=3
)
# NEUE PULLDOWN-MENÜS FÜR BILD-ZU-BILD
with gr.Row():
with gr.Column():
font_size_i2i = gr.Dropdown(
choices=["180px", "160px", "140px", "120px", "80px", "60px", "50px", "40px", "30px", "20px"],
value="60px",
label="Schriftgröße"
)
with gr.Column():
font_family_i2i = gr.Dropdown(
choices=["Standard", "Einfache Handschrift", "Verschnörkelte Handschrift"],
value="Standard",
label="Schriftart"
)
with gr.Column():
font_color_i2i = gr.Dropdown(
choices=["Weiß", "Schwarz", "Rot"],
value="Weiß",
label="Schriftfarbe"
)
with gr.Row():
text_x_i2i = gr.Number(value=None, visible=False)
text_y_i2i = gr.Number(value=None, visible=False)
with gr.Row():
target_selector = gr.Radio(
choices=["Originalbild", "Generiertes Bild"],
value="Generiertes Bild",
label="Text auf welchem Bild?",
scale=2
)
with gr.Row():
text_btn_i2i = gr.Button("📝 Text integrieren", variant="secondary")
# CLICK HANDLER FÜR BILD-zu-BILD
preview_output.select(
fn=capture_click,
outputs=[text_x_i2i, text_y_i2i]
)
# LIVE-TEXT-VORSCHAU FÜR BILD-ZU-BILD MIT FORMATIERUNG
text_inputs_i2i = [img_input, img_output, text_input_i2i, text_x_i2i, text_y_i2i, font_size_i2i, font_family_i2i, font_color_i2i, target_selector]
text_input_i2i.change(
fn=update_text_preview_i2i,
inputs=text_inputs_i2i,
outputs=preview_output
)
text_x_i2i.change(
fn=update_text_preview_i2i,
inputs=text_inputs_i2i,
outputs=preview_output
)
text_y_i2i.change(
fn=update_text_preview_i2i,
inputs=text_inputs_i2i,
outputs=preview_output
)
font_size_i2i.change(
fn=update_text_preview_i2i,
inputs=text_inputs_i2i,
outputs=preview_output
)
font_family_i2i.change(
fn=update_text_preview_i2i,
inputs=text_inputs_i2i,
outputs=preview_output
)
font_color_i2i.change(
fn=update_text_preview_i2i,
inputs=text_inputs_i2i,
outputs=preview_output
)
target_selector.change(
fn=update_text_preview_i2i,
inputs=text_inputs_i2i,
outputs=preview_output
)
# EVENT-HANDLER BILD-zu-BILD
img_input.change(
fn=process_image_upload,
inputs=[img_input],
outputs=[preview_output, bbox_x1, bbox_y1, bbox_x2, bbox_y2]
)
coordinate_inputs = [img_input, bbox_x1, bbox_y1, bbox_x2, bbox_y2, face_preserve]
for coord in [bbox_x1, bbox_y1, bbox_x2, bbox_y2]:
coord.change(
fn=update_live_preview,
inputs=coordinate_inputs,
outputs=preview_output
)
face_preserve.change(
fn=update_live_preview,
inputs=coordinate_inputs,
outputs=preview_output
)
transform_btn.click(
fn=img_to_image,
inputs=[
img_input, img_prompt, img_neg_prompt,
strength_slider, img_steps, img_guidance,
face_preserve, bbox_x1, bbox_y1, bbox_x2, bbox_y2
],
outputs=img_output,
concurrency_limit=1
)
text_btn_i2i.click(
fn=handle_text_integration_i2i,
inputs=[
img_input,
img_output,
text_input_i2i,
text_x_i2i,
text_y_i2i,
font_size_i2i,
font_family_i2i,
font_color_i2i,
target_selector
],
outputs=[img_input, img_output]
)
# === EVENT-HANDLER: STOP AUDIO BEIM TAB-WECHSEL ===
tab_image_to_image.select(
fn=stop_audio_on_tab_change,
outputs=hidden_audio_t2i
)
# === START-BUTTON HANDLER ===
info_components = [child for child in demo.children if child != content_area]
start_btn.click(
fn=lambda: gr.update(visible=True),
outputs=content_area
).then(
fn=lambda: [gr.update(visible=False) for _ in info_components],
outputs=info_components
)
return demo
if __name__ == "__main__":
demo = main_ui()
demo.queue()
demo.launch(
server_name="0.0.0.0",
server_port=7860,
max_file_size="15MB",
show_error=True,
share=False
) |