nimzuk commited on
Commit
6893801
·
verified ·
1 Parent(s): c982d64

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +143 -0
app.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, io, math, time, base64
2
+ from typing import Tuple
3
+ import gradio as gr
4
+ from PIL import Image, ImageFilter, ImageOps
5
+ import numpy as np
6
+ import torch
7
+
8
+ # ---- Модель по умолчанию (можно переопределить в Settings → Variables) ----
9
+ MODEL_ID = os.getenv("MODEL_ID", "Qwen/Qwen-Image-Edit")
10
+ HF_TOKEN = os.getenv("HF_TOKEN", "").strip() or None # если модель gated
11
+
12
+ # ---- Подгружаем подходящий пайплайн inpainting ----
13
+ # Многие редактирующие модели следуют API diffusers InpaintPipeline
14
+ # Попробуем сначала специализированный пайплайн, затем универсальный.
15
+ from diffusers import AutoPipelineForInpainting, StableDiffusionInpaintPipeline
16
+
17
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
18
+ dtype = torch.float16 if device.type == "cuda" else torch.float32
19
+
20
+ def _load_pipeline():
21
+ auth = {"token": HF_TOKEN} if HF_TOKEN else {}
22
+ try:
23
+ pipe = AutoPipelineForInpainting.from_pretrained(
24
+ MODEL_ID, torch_dtype=dtype, **auth
25
+ )
26
+ except Exception:
27
+ # fallback на классический SD inpaint, если у модели нет auto-конфига
28
+ pipe = StableDiffusionInpaintPipeline.from_pretrained(
29
+ MODEL_ID, torch_dtype=dtype, **auth
30
+ )
31
+ pipe = pipe.to(device)
32
+ if hasattr(pipe, "enable_attention_slicing"):
33
+ pipe.enable_attention_slicing()
34
+ return pipe
35
+
36
+ PIPE = None
37
+ LOAD_ERR = None
38
+ try:
39
+ PIPE = _load_pipeline()
40
+ except Exception as e:
41
+ LOAD_ERR = str(e)
42
+
43
+ # ----------------- Утилиты -----------------
44
+ def _pad_canvas(img: Image.Image, left: int, right: int, top: int, bottom: int,
45
+ fill=(127,127,127)) -> Tuple[Image.Image, Tuple[int,int,int,int]]:
46
+ """Создаёт расширенный холст и возвращает (canvas, bbox вставки исходника)."""
47
+ w, h = img.size
48
+ canvas = Image.new("RGB", (w + left + right, h + top + bottom), fill)
49
+ canvas.paste(img, (left, top))
50
+ return canvas, (left, top, left + w, top + h)
51
+
52
+ def _feather_mask(size: Tuple[int,int], bbox: Tuple[int,int,int,int], feather_px: int = 32) -> Image.Image:
53
+ """Маска: 255 = дорисовать, 0 = оставить исходник. По краю делаем плавный градиент."""
54
+ W, H = size
55
+ L, T, R, B = bbox
56
+ mask = Image.new("L", (W, H), 255)
57
+ base = Image.new("L", (W, H), 0)
58
+ base.paste(255, (L, T, R, B))
59
+ # invert: центральная область = 0 (не трогать), снаружи = 255
60
+ inv = ImageOps.invert(base)
61
+ if feather_px > 0:
62
+ inv = inv.filter(ImageFilter.GaussianBlur(radius=feather_px))
63
+ return inv
64
+
65
+ def expand_with_model(image: Image.Image, left: int, right: int, top: int, bottom: int,
66
+ prompt: str, neg: str, steps: int, guidance: float, seed: int | None):
67
+ if LOAD_ERR:
68
+ raise gr.Error(f"Не удалось загрузить модель '{MODEL_ID}'.\n{LOAD_ERR}")
69
+
70
+ for name, val in [("left",left),("right",right),("top",top),("bottom",bottom)]:
71
+ if val is None or val < 0 or val > 2048:
72
+ raise gr.Error(f"{name} должен быть в диапазоне 0..2048")
73
+
74
+ # 1) строим холст и маску
75
+ canvas, bbox = _pad_canvas(image.convert("RGB"), left, right, top, bottom)
76
+ mask = _feather_mask(canvas.size, bbox, feather_px=48)
77
+
78
+ # 2) аккуратный промпт для бесшовного расширения
79
+ clean_prompt = (prompt or "").strip()
80
+ if not clean_prompt:
81
+ clean_prompt = (
82
+ "Seamlessly continue the existing background so it looks like a natural, "
83
+ "wider version of the same image. Match colors, textures, lighting and perspective. "
84
+ "No frames, no collage, no new subjects."
85
+ )
86
+ negative_prompt = (neg or "frames, borders, phone mockup, collage tiles, UI elements, captions, watermark").strip()
87
+
88
+ generator = None
89
+ if isinstance(seed, int) and seed >= 0:
90
+ generator = torch.Generator(device=device).manual_seed(seed)
91
+
92
+ # 3) инференс
93
+ out = PIPE(
94
+ prompt=clean_prompt,
95
+ negative_prompt=negative_prompt,
96
+ image=canvas,
97
+ mask_image=mask,
98
+ num_inference_steps=int(steps),
99
+ guidance_scale=float(guidance),
100
+ generator=generator
101
+ ).images[0]
102
+
103
+ return out, clean_prompt, negative_prompt
104
+
105
+ # ----------------- Gradio UI -----------------
106
+ with gr.Blocks(title="Qwen Image — Seamless Expand") as demo:
107
+ gr.Markdown("## Qwen Image — Seamless Background Expand\n"
108
+ "Загрузи картинку, задай сколько пикселей дорисовать, при желании уточни промпт.")
109
+
110
+ if LOAD_ERR:
111
+ gr.Markdown(
112
+ f"**⚠️ Модель не загрузил��сь.** Проверь `MODEL_ID` в Settings → Variables. Текущая: `{MODEL_ID}` "
113
+ f"\nСообщение: `{LOAD_ERR}`"
114
+ )
115
+
116
+ with gr.Row():
117
+ with gr.Column(scale=1):
118
+ img_in = gr.Image(type="pil", label="Картинка")
119
+ prompt = gr.Textbox(label="Prompt (EN)", placeholder="Describe seamless continuation…")
120
+ neg = gr.Textbox(label="Negative prompt", value="frames, borders, phone mockup, collage tiles, UI elements, captions, watermark")
121
+ with gr.Row():
122
+ left = gr.Number(value=256, label="Left (px)", precision=0)
123
+ right = gr.Number(value=256, label="Right (px)", precision=0)
124
+ with gr.Row():
125
+ top = gr.Number(value=256, label="Top (px)", precision=0)
126
+ bottom = gr.Number(value=256, label="Bottom (px)", precision=0)
127
+ with gr.Row():
128
+ steps = gr.Slider(10, 60, value=30, step=1, label="Steps")
129
+ guidance = gr.Slider(0.5, 12.0, value=5.5, step=0.1, label="Guidance scale")
130
+ seed = gr.Number(value=-1, label="Seed (-1 = random)", precision=0)
131
+ btn = gr.Button("Expand", variant="primary")
132
+ with gr.Column(scale=1):
133
+ img_out = gr.Image(label="Результат")
134
+ used_prompt = gr.Textbox(label="Использованный prompt", interactive=False)
135
+ used_neg = gr.Textbox(label="Использованный negative", interactive=False)
136
+
137
+ btn.click(
138
+ expand_with_model,
139
+ inputs=[img_in, left, right, top, bottom, prompt, neg, steps, guidance, seed],
140
+ outputs=[img_out, used_prompt, used_neg]
141
+ )
142
+
143
+ demo.launch()