Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,3 @@
|
|
| 1 |
-
from base64 import b64decode
|
| 2 |
-
from base64 import b85decode
|
| 3 |
import base64
|
| 4 |
import io
|
| 5 |
import json
|
|
@@ -9,181 +7,532 @@ import threading
|
|
| 9 |
import time
|
| 10 |
import traceback
|
| 11 |
import uuid
|
| 12 |
-
from concurrent.futures import ThreadPoolExecutor,as_completed
|
| 13 |
-
from datetime import datetime,timezone
|
|
|
|
| 14 |
import gradio as gr
|
| 15 |
import requests
|
| 16 |
from PIL import Image
|
|
|
|
| 17 |
try:
|
| 18 |
-
|
| 19 |
except ImportError:
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import base64
|
| 2 |
import io
|
| 3 |
import json
|
|
|
|
| 7 |
import time
|
| 8 |
import traceback
|
| 9 |
import uuid
|
| 10 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 11 |
+
from datetime import datetime, timezone
|
| 12 |
+
|
| 13 |
import gradio as gr
|
| 14 |
import requests
|
| 15 |
from PIL import Image
|
| 16 |
+
|
| 17 |
try:
|
| 18 |
+
from huggingface_hub import batch_bucket_files
|
| 19 |
except ImportError:
|
| 20 |
+
batch_bucket_files = None
|
| 21 |
+
|
| 22 |
+
# --- Config (secrets only, never hardcoded) ----------------------------------
|
| 23 |
+
HF_TOKEN = os.environ.get("HF_TOKEN", "").strip()
|
| 24 |
+
BUCKET_ID = os.environ.get("BUCKET_ID", "").strip()
|
| 25 |
+
OPENROUTER_API_KEY = os.environ.get("OPENROUTER_API_KEY", "").strip()
|
| 26 |
+
|
| 27 |
+
OPENROUTER_IMAGES_URL = "https://openrouter.ai/api/v1/images"
|
| 28 |
+
EDIT_MODEL = "black-forest-labs/flux.2-klein-4b"
|
| 29 |
+
GUARD_MODEL = "hfmlsoc/ncii-light-guard-v01"
|
| 30 |
+
NCII_THRESHOLD = 0.70
|
| 31 |
+
|
| 32 |
+
MODEL_CHOICES = ["Auto-Routing", "FLUX + LoRA", "Qwen Edit", "Lance", "Krea2", "SenseNova"]
|
| 33 |
+
# Every choice currently routes to FLUX.2 Klein; swap slugs here to wire real backends.
|
| 34 |
+
MODEL_ROUTES = {choice: EDIT_MODEL for choice in MODEL_CHOICES}
|
| 35 |
+
|
| 36 |
+
REQUEST_TIMEOUT = 180
|
| 37 |
+
MAX_SIDE = 2048 # downscale reference images before upload
|
| 38 |
+
|
| 39 |
+
logging_enabled = bool(HF_TOKEN and BUCKET_ID and batch_bucket_files)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# --- Prompt guard -------------------------------------------------------------
|
| 43 |
+
_guard = None
|
| 44 |
+
_guard_lock = threading.Lock()
|
| 45 |
+
_guard_failed = False
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _load_guard():
|
| 49 |
+
"""Load the classifier once; safe to call from several threads."""
|
| 50 |
+
global _guard, _guard_failed
|
| 51 |
+
if _guard is not None:
|
| 52 |
+
return _guard
|
| 53 |
+
with _guard_lock:
|
| 54 |
+
if _guard is None and not _guard_failed:
|
| 55 |
+
try:
|
| 56 |
+
from transformers import pipeline
|
| 57 |
+
_guard = pipeline("text-classification", model=GUARD_MODEL)
|
| 58 |
+
except Exception:
|
| 59 |
+
_guard_failed = True
|
| 60 |
+
print(f"[DEBUG] guard load failed:\n{traceback.format_exc()}", file=sys.stderr)
|
| 61 |
+
return _guard
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def ncii_score(prompt: str) -> float:
|
| 65 |
+
"""Return the ncii probability for a prompt. Fails closed on any error."""
|
| 66 |
+
clf = _load_guard()
|
| 67 |
+
if clf is None:
|
| 68 |
+
# Safety system unavailable -> refuse to generate rather than bypass it.
|
| 69 |
+
raise RuntimeError("guard unavailable (still loading or failed to load)")
|
| 70 |
+
try:
|
| 71 |
+
result = clf(prompt[:2048])[0]
|
| 72 |
+
label = str(result.get("label", "")).strip().lower()
|
| 73 |
+
score = float(result.get("score", 1.0))
|
| 74 |
+
except Exception as err:
|
| 75 |
+
raise RuntimeError(f"guard inference failed: {err}")
|
| 76 |
+
return score if label == "ncii" else 1.0 - score
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# Warm the model in the background so the first user doesn't pay the load time.
|
| 80 |
+
threading.Thread(target=_load_guard, daemon=True).start()
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
# --- Image encoding / OpenRouter ----------------------------------------------
|
| 84 |
+
def _to_data_url(image: Image.Image) -> str:
|
| 85 |
+
img = image.convert("RGB")
|
| 86 |
+
if max(img.size) > MAX_SIDE:
|
| 87 |
+
ratio = MAX_SIDE / max(img.size)
|
| 88 |
+
img = img.resize((round(img.width * ratio), round(img.height * ratio)), Image.LANCZOS)
|
| 89 |
+
buf = io.BytesIO()
|
| 90 |
+
img.save(buf, format="PNG")
|
| 91 |
+
return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _decode_result(item: dict) -> Image.Image:
|
| 95 |
+
if item.get("b64_json"):
|
| 96 |
+
return Image.open(io.BytesIO(base64.b64decode(item["b64_json"])))
|
| 97 |
+
url = item.get("url") or (item.get("image_url") or {}).get("url", "")
|
| 98 |
+
if url.startswith("data:"):
|
| 99 |
+
return Image.open(io.BytesIO(base64.b64decode(url.split(",", 1)[1])))
|
| 100 |
+
if url:
|
| 101 |
+
resp = requests.get(url, timeout=60)
|
| 102 |
+
resp.raise_for_status()
|
| 103 |
+
return Image.open(io.BytesIO(resp.content))
|
| 104 |
+
raise ValueError(f"No image payload in response item: {list(item.keys())}")
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def _generate_one(data_url: str, prompt: str, model: str = EDIT_MODEL,
|
| 108 |
+
attempts: int = 2) -> Image.Image:
|
| 109 |
+
payload = {
|
| 110 |
+
"model": model,
|
| 111 |
+
"prompt": prompt,
|
| 112 |
+
"input_references": [{"type": "image_url", "image_url": {"url": data_url}}],
|
| 113 |
+
}
|
| 114 |
+
headers = {
|
| 115 |
+
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
|
| 116 |
+
"Content-Type": "application/json",
|
| 117 |
+
}
|
| 118 |
+
last_err = None
|
| 119 |
+
for attempt in range(attempts):
|
| 120 |
+
try:
|
| 121 |
+
resp = requests.post(
|
| 122 |
+
OPENROUTER_IMAGES_URL, json=payload, headers=headers, timeout=REQUEST_TIMEOUT
|
| 123 |
+
)
|
| 124 |
+
if resp.status_code != 200:
|
| 125 |
+
snippet = resp.text[:300]
|
| 126 |
+
raise RuntimeError(f"OpenRouter {resp.status_code}: {snippet}")
|
| 127 |
+
data = resp.json().get("data") or []
|
| 128 |
+
if not data:
|
| 129 |
+
raise RuntimeError("OpenRouter returned an empty result.")
|
| 130 |
+
return _decode_result(data[0])
|
| 131 |
+
except Exception as err:
|
| 132 |
+
last_err = err
|
| 133 |
+
if attempt < attempts - 1:
|
| 134 |
+
time.sleep(1.5 * (attempt + 1))
|
| 135 |
+
raise last_err
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def generate_variants(data_url: str, prompt: str, n: int, model: str = EDIT_MODEL) -> list:
|
| 139 |
+
"""n independent requests in parallel — guarantees n distinct variants
|
| 140 |
+
regardless of provider support for the `n` parameter."""
|
| 141 |
+
images, errors = [], []
|
| 142 |
+
with ThreadPoolExecutor(max_workers=n) as pool:
|
| 143 |
+
futures = [pool.submit(_generate_one, data_url, prompt, model) for _ in range(n)]
|
| 144 |
+
for future in as_completed(futures):
|
| 145 |
+
try:
|
| 146 |
+
images.append(future.result())
|
| 147 |
+
except Exception as err:
|
| 148 |
+
errors.append(err)
|
| 149 |
+
print(f"[DEBUG] variant failed: {err}", file=sys.stderr)
|
| 150 |
+
if not images:
|
| 151 |
+
# Surface the raw provider errors to the caller so they reach the logs.
|
| 152 |
+
raise RuntimeError(" | ".join(str(e) for e in errors) or "no image returned")
|
| 153 |
+
return images
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
# --- Logging -------------------------------------------------------------------
|
| 157 |
+
def _png_bytes(image: Image.Image) -> bytes:
|
| 158 |
+
buf = io.BytesIO()
|
| 159 |
+
image.convert("RGB").save(buf, format="PNG")
|
| 160 |
+
return buf.getvalue()
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def _log_async(files: list):
|
| 164 |
+
"""Fire-and-forget upload of [(bytes, path), ...] to the bucket."""
|
| 165 |
+
if not logging_enabled or not files:
|
| 166 |
+
return
|
| 167 |
+
|
| 168 |
+
def _worker():
|
| 169 |
+
try:
|
| 170 |
+
batch_bucket_files(BUCKET_ID, add=files, token=HF_TOKEN)
|
| 171 |
+
except Exception:
|
| 172 |
+
# logging must never take the app down — degrade to no logging
|
| 173 |
+
print(f"[DEBUG] bucket upload failed:\n{traceback.format_exc()}", file=sys.stderr)
|
| 174 |
+
|
| 175 |
+
threading.Thread(target=_worker, daemon=True).start()
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def log_submission(session_id: str, image: Image.Image, prompt: str,
|
| 179 |
+
status: str, error: str = None, outputs: list = ()):
|
| 180 |
+
"""Export the full outcome of one submission: input image, prompt, date,
|
| 181 |
+
session_id, status (blocked / generated / error), the raw error detail
|
| 182 |
+
when something failed, and the output image when one was generated."""
|
| 183 |
+
sample_id = uuid.uuid4().hex[:10]
|
| 184 |
+
date = datetime.now(timezone.utc).isoformat()
|
| 185 |
+
base = f"sessions/{session_id}/{date[:19].replace(':', '-')}_{sample_id}"
|
| 186 |
+
record = {
|
| 187 |
+
"session_id": session_id,
|
| 188 |
+
"prompt": prompt,
|
| 189 |
+
"date": date,
|
| 190 |
+
"status": status,
|
| 191 |
+
}
|
| 192 |
+
if error:
|
| 193 |
+
record["error"] = error[:4000]
|
| 194 |
+
files = [
|
| 195 |
+
(_png_bytes(image), f"{base}_input.png"),
|
| 196 |
+
(json.dumps(record).encode(), f"{base}.json"),
|
| 197 |
+
]
|
| 198 |
+
files += [
|
| 199 |
+
(_png_bytes(img), f"{base}_output{'' if len(outputs) == 1 else f'_{i}'}.png")
|
| 200 |
+
for i, img in enumerate(outputs)
|
| 201 |
+
]
|
| 202 |
+
_log_async(files)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
# --- Main pipeline ---------------------------------------------------------------
|
| 206 |
+
BLOCKED_MSG = "🚫 Prompt forbidden"
|
| 207 |
+
FAILED_MSG = "⚠️ Generation failed — please try again."
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def edit_image(image, prompt, model_choice, request: gr.Request,
|
| 211 |
+
progress=gr.Progress()):
|
| 212 |
+
if image is None:
|
| 213 |
+
raise gr.Error("Please upload an image first.")
|
| 214 |
+
if not prompt or not prompt.strip():
|
| 215 |
+
raise gr.Error("Please describe the change you would like to make.")
|
| 216 |
+
prompt = prompt.strip()
|
| 217 |
+
|
| 218 |
+
# One id per browser session: every prompt sent from the same tab —
|
| 219 |
+
# including blocked ones and retries — is linked together.
|
| 220 |
+
session_id = getattr(request, "session_hash", None) or uuid.uuid4().hex
|
| 221 |
+
|
| 222 |
+
status, error_detail, images = "error", None, []
|
| 223 |
+
try:
|
| 224 |
+
progress(0.1, desc="Checking prompt…")
|
| 225 |
+
if ncii_score(prompt) > NCII_THRESHOLD:
|
| 226 |
+
status = "blocked"
|
| 227 |
+
raise gr.Error(BLOCKED_MSG)
|
| 228 |
+
|
| 229 |
+
if not OPENROUTER_API_KEY:
|
| 230 |
+
error_detail = "OPENROUTER_API_KEY not configured"
|
| 231 |
+
raise gr.Error(BLOCKED_MSG)
|
| 232 |
+
|
| 233 |
+
model = MODEL_ROUTES.get(model_choice, EDIT_MODEL)
|
| 234 |
+
progress(0.3, desc="Generating…")
|
| 235 |
+
images = generate_variants(_to_data_url(image), prompt, 1, model)
|
| 236 |
+
status = "generated"
|
| 237 |
+
return images, gr.update(visible=True)
|
| 238 |
+
except gr.Error:
|
| 239 |
+
raise
|
| 240 |
+
except Exception as err:
|
| 241 |
+
# Full detail goes to the logs; the user always sees the same message.
|
| 242 |
+
error_detail = str(err)
|
| 243 |
+
print(f"[DEBUG] generation error: {error_detail}", file=sys.stderr)
|
| 244 |
+
raise gr.Error(BLOCKED_MSG)
|
| 245 |
+
finally:
|
| 246 |
+
log_submission(session_id, image, prompt, status, error_detail, images)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
# --- Styling: editorial brief — cream paper, grid, ink & orange -----------------
|
| 250 |
+
LAB_CSS = """
|
| 251 |
+
@import url('https://fonts.googleapis.com/css2?family=Archivo+Black&family=JetBrains+Mono:wght@400;500;700&display=swap');
|
| 252 |
+
|
| 253 |
+
:root {
|
| 254 |
+
--paper: #f4f0e6;
|
| 255 |
+
--panel: #fbf9f2;
|
| 256 |
+
--ink: #16130e;
|
| 257 |
+
--muted: #8f8a7d;
|
| 258 |
+
--accent: #ee4f1e;
|
| 259 |
+
--grid: rgba(22, 19, 14, 0.06);
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
body, .app, gradio-app {
|
| 263 |
+
background: var(--paper) !important;
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
.gradio-container {
|
| 267 |
+
background-color: var(--paper) !important;
|
| 268 |
+
background-image:
|
| 269 |
+
linear-gradient(var(--grid) 1px, transparent 1px),
|
| 270 |
+
linear-gradient(90deg, var(--grid) 1px, transparent 1px);
|
| 271 |
+
background-size: 44px 44px;
|
| 272 |
+
font-family: 'JetBrains Mono', monospace !important;
|
| 273 |
+
color: var(--ink) !important;
|
| 274 |
+
width: min(1680px, 96vw) !important;
|
| 275 |
+
max-width: min(1680px, 96vw) !important;
|
| 276 |
+
margin: 0 auto !important;
|
| 277 |
+
}
|
| 278 |
+
.gradio-container .main, .gradio-container .fillable {
|
| 279 |
+
max-width: none !important;
|
| 280 |
+
width: 100% !important;
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
/* ---------- header frame ---------- */
|
| 284 |
+
#brief-frame {
|
| 285 |
+
position: relative;
|
| 286 |
+
border: 2px solid var(--ink);
|
| 287 |
+
background: var(--paper);
|
| 288 |
+
padding: 1.1rem 1.6rem 0.4rem;
|
| 289 |
+
margin: 1.6rem 0 1.8rem;
|
| 290 |
+
}
|
| 291 |
+
#brief-frame .tick {
|
| 292 |
+
position: absolute;
|
| 293 |
+
background: var(--ink);
|
| 294 |
+
}
|
| 295 |
+
#brief-frame .tick.t1 { top: -12px; left: 18%; width: 2px; height: 24px; }
|
| 296 |
+
#brief-frame .tick.t2 { top: -12px; right: 8%; width: 2px; height: 24px; }
|
| 297 |
+
#brief-frame .tick.t3 { bottom: -12px; left: 40%; width: 2px; height: 24px; }
|
| 298 |
+
#brief-frame .tick.t4 { top: 30%; left: -12px; width: 24px; height: 2px; }
|
| 299 |
+
#brief-frame .tick.t5 { top: 62%; right: -12px; width: 24px; height: 2px; }
|
| 300 |
+
|
| 301 |
+
.brief-kicker {
|
| 302 |
+
display: flex;
|
| 303 |
+
justify-content: space-between;
|
| 304 |
+
gap: 1rem;
|
| 305 |
+
color: var(--ink);
|
| 306 |
+
font-size: 0.72rem;
|
| 307 |
+
font-weight: 700;
|
| 308 |
+
letter-spacing: 4px;
|
| 309 |
+
text-transform: uppercase;
|
| 310 |
+
padding-bottom: 0.9rem;
|
| 311 |
+
}
|
| 312 |
+
.brief-kicker span { color: var(--ink) !important; }
|
| 313 |
+
.brief-kicker span.dim { color: var(--muted) !important; font-weight: 500; }
|
| 314 |
+
|
| 315 |
+
.brief-headline {
|
| 316 |
+
font-family: 'Archivo Black', 'JetBrains Mono', sans-serif;
|
| 317 |
+
font-size: clamp(2.1rem, 5.2vw, 3.6rem);
|
| 318 |
+
line-height: 1.04;
|
| 319 |
+
letter-spacing: 1px;
|
| 320 |
+
text-transform: uppercase;
|
| 321 |
+
margin: 1.4rem 0 1rem;
|
| 322 |
+
color: var(--ink);
|
| 323 |
+
}
|
| 324 |
+
.brief-headline .accent { color: var(--accent); }
|
| 325 |
+
|
| 326 |
+
.brief-sub {
|
| 327 |
+
font-size: 0.8rem;
|
| 328 |
+
letter-spacing: 3.5px;
|
| 329 |
+
text-transform: uppercase;
|
| 330 |
+
color: var(--muted);
|
| 331 |
+
margin: 0 0 1.6rem;
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
/* floating component labels (e.g. on the image inputs) */
|
| 335 |
+
.block label.float, .block .label {
|
| 336 |
+
background: var(--ink) !important;
|
| 337 |
+
color: var(--paper) !important;
|
| 338 |
+
border-radius: 0 !important;
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
/* ---------- panels & fields ---------- */
|
| 342 |
+
.gr-panel, .block, .form {
|
| 343 |
+
background: var(--panel) !important;
|
| 344 |
+
border: 2px solid var(--ink) !important;
|
| 345 |
+
border-radius: 0 !important;
|
| 346 |
+
box-shadow: none !important;
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
textarea, input, select {
|
| 350 |
+
background: var(--panel) !important;
|
| 351 |
+
color: var(--ink) !important;
|
| 352 |
+
font-family: 'JetBrains Mono', monospace !important;
|
| 353 |
+
border: 2px solid var(--ink) !important;
|
| 354 |
+
border-radius: 0 !important;
|
| 355 |
+
}
|
| 356 |
+
textarea:focus, input:focus { border-color: var(--accent) !important; }
|
| 357 |
+
|
| 358 |
+
label, label span, .gr-check-radio span, span[data-testid="block-info"] {
|
| 359 |
+
color: var(--ink) !important;
|
| 360 |
+
font-family: 'JetBrains Mono', monospace !important;
|
| 361 |
+
font-size: 0.72rem !important;
|
| 362 |
+
font-weight: 700 !important;
|
| 363 |
+
text-transform: uppercase;
|
| 364 |
+
letter-spacing: 2px;
|
| 365 |
+
}
|
| 366 |
+
|
| 367 |
+
button {
|
| 368 |
+
font-family: 'JetBrains Mono', monospace !important;
|
| 369 |
+
font-weight: 700 !important;
|
| 370 |
+
text-transform: uppercase;
|
| 371 |
+
letter-spacing: 2.5px;
|
| 372 |
+
border-radius: 0 !important;
|
| 373 |
+
transition: all 0.15s ease-in-out;
|
| 374 |
+
}
|
| 375 |
+
|
| 376 |
+
#submit-btn {
|
| 377 |
+
background: var(--ink) !important;
|
| 378 |
+
color: var(--paper) !important;
|
| 379 |
+
border: 2px solid var(--ink) !important;
|
| 380 |
+
padding: 0.9rem !important;
|
| 381 |
+
font-size: 0.9rem !important;
|
| 382 |
+
}
|
| 383 |
+
#submit-btn:hover {
|
| 384 |
+
background: var(--accent) !important;
|
| 385 |
+
border-color: var(--accent) !important;
|
| 386 |
+
color: #fff !important;
|
| 387 |
+
}
|
| 388 |
+
|
| 389 |
+
/* ---------- like callout ---------- */
|
| 390 |
+
#like-callout {
|
| 391 |
+
border: 2px solid var(--accent) !important;
|
| 392 |
+
background: var(--panel) !important;
|
| 393 |
+
text-align: center;
|
| 394 |
+
padding: 0.8rem;
|
| 395 |
+
font-size: 0.78rem;
|
| 396 |
+
letter-spacing: 2.5px;
|
| 397 |
+
text-transform: uppercase;
|
| 398 |
+
color: var(--ink);
|
| 399 |
+
}
|
| 400 |
+
#like-callout .accent { color: var(--accent); font-weight: 700; }
|
| 401 |
+
|
| 402 |
+
footer { visibility: hidden; }
|
| 403 |
+
|
| 404 |
+
/* ---------- privacy ---------- */
|
| 405 |
+
#privacy-footer {
|
| 406 |
+
text-align: center;
|
| 407 |
+
font-size: 0.7rem;
|
| 408 |
+
color: var(--muted);
|
| 409 |
+
margin-top: 2rem;
|
| 410 |
+
letter-spacing: 1.5px;
|
| 411 |
+
text-transform: uppercase;
|
| 412 |
+
}
|
| 413 |
+
#privacy-footer a { color: var(--muted); text-decoration: underline; cursor: pointer; }
|
| 414 |
+
|
| 415 |
+
#privacy-modal {
|
| 416 |
+
display: none;
|
| 417 |
+
position: fixed;
|
| 418 |
+
top: 0; left: 0; width: 100%; height: 100%;
|
| 419 |
+
background: rgba(22, 19, 14, 0.6);
|
| 420 |
+
z-index: 9999;
|
| 421 |
+
align-items: center;
|
| 422 |
+
justify-content: center;
|
| 423 |
+
}
|
| 424 |
+
#privacy-modal.open { display: flex; }
|
| 425 |
+
#privacy-modal-box {
|
| 426 |
+
background: var(--paper);
|
| 427 |
+
border: 2px solid var(--ink);
|
| 428 |
+
padding: 2rem;
|
| 429 |
+
max-width: 480px;
|
| 430 |
+
font-family: 'JetBrains Mono', monospace;
|
| 431 |
+
font-size: 0.8rem;
|
| 432 |
+
line-height: 1.55;
|
| 433 |
+
}
|
| 434 |
+
#privacy-modal-box button {
|
| 435 |
+
margin-top: 1rem;
|
| 436 |
+
background: var(--ink);
|
| 437 |
+
color: var(--paper);
|
| 438 |
+
border: 2px solid var(--ink);
|
| 439 |
+
padding: 0.5rem 1.4rem;
|
| 440 |
+
}
|
| 441 |
+
"""
|
| 442 |
+
|
| 443 |
+
HEADER_HTML = """
|
| 444 |
+
<div id="brief-frame">
|
| 445 |
+
<span class="tick t1"></span><span class="tick t2"></span><span class="tick t3"></span>
|
| 446 |
+
<span class="tick t4"></span><span class="tick t5"></span>
|
| 447 |
+
<div class="brief-kicker">
|
| 448 |
+
<span>WanGen · Image Editing Studio</span>
|
| 449 |
+
<span class="dim">Open Models · Free For All</span>
|
| 450 |
+
</div>
|
| 451 |
+
<h1 class="brief-headline">Describe It. <span class="accent">Done.</span></h1>
|
| 452 |
+
<p class="brief-sub">Multi-model editing — for the beauty of open source.</p>
|
| 453 |
+
</div>
|
| 454 |
+
"""
|
| 455 |
+
|
| 456 |
+
PRIVACY_HTML = """
|
| 457 |
+
<p id='privacy-footer'>
|
| 458 |
+
<a onclick="document.getElementById('privacy-modal').classList.add('open')">Privacy Policy</a>
|
| 459 |
+
</p>
|
| 460 |
+
|
| 461 |
+
<div id='privacy-modal'>
|
| 462 |
+
<div id='privacy-modal-box'>
|
| 463 |
+
<strong>Privacy Policy</strong><br><br>
|
| 464 |
+
Please do not upload personal information, or images you do not have the right to use.<br><br>
|
| 465 |
+
No personal data beyond what you explicitly submitted is collected. Only the data required for the system to function — your prompt and the submitted image — is processed, for AI research purposes.<br><br>
|
| 466 |
+
<button onclick="document.getElementById('privacy-modal').classList.remove('open')">Close</button>
|
| 467 |
+
</div>
|
| 468 |
+
</div>
|
| 469 |
+
"""
|
| 470 |
+
|
| 471 |
+
# Pin the light theme — the design is paper-based and must not invert.
|
| 472 |
+
FORCE_LIGHT_HEAD = """
|
| 473 |
+
<script>
|
| 474 |
+
(function () {
|
| 475 |
+
const url = new URL(window.location);
|
| 476 |
+
if (url.searchParams.get('__theme') !== 'light') {
|
| 477 |
+
url.searchParams.set('__theme', 'light');
|
| 478 |
+
window.location.replace(url.href);
|
| 479 |
+
}
|
| 480 |
+
})();
|
| 481 |
+
</script>
|
| 482 |
+
"""
|
| 483 |
+
|
| 484 |
+
# Gradio 6 moved css/head from the Blocks constructor to launch().
|
| 485 |
+
GRADIO_MAJOR = int(gr.__version__.split(".")[0])
|
| 486 |
+
_style_kwargs = {"css": LAB_CSS, "head": FORCE_LIGHT_HEAD}
|
| 487 |
+
_blocks_kwargs = {} if GRADIO_MAJOR >= 6 else dict(_style_kwargs)
|
| 488 |
+
_launch_kwargs = dict(_style_kwargs) if GRADIO_MAJOR >= 6 else {}
|
| 489 |
+
|
| 490 |
+
with gr.Blocks(title="Describe It. Done.", fill_width=True, **_blocks_kwargs) as demo:
|
| 491 |
+
gr.HTML(HEADER_HTML)
|
| 492 |
+
|
| 493 |
+
with gr.Row(equal_height=False):
|
| 494 |
+
with gr.Column(scale=5):
|
| 495 |
+
image_in = gr.Image(
|
| 496 |
+
type="pil",
|
| 497 |
+
label="Input Image — drop, paste or upload",
|
| 498 |
+
sources=["upload", "clipboard"],
|
| 499 |
+
height=320,
|
| 500 |
+
)
|
| 501 |
+
prompt_in = gr.Textbox(
|
| 502 |
+
label="What changes would you like to make ?",
|
| 503 |
+
placeholder="e.g. change the background to a forest at dusk",
|
| 504 |
+
lines=3,
|
| 505 |
+
)
|
| 506 |
+
model_in = gr.Dropdown(
|
| 507 |
+
choices=MODEL_CHOICES,
|
| 508 |
+
value="Auto-Routing",
|
| 509 |
+
label="Model",
|
| 510 |
+
)
|
| 511 |
+
submit_btn = gr.Button("Submit", elem_id="submit-btn")
|
| 512 |
+
|
| 513 |
+
with gr.Column(scale=5):
|
| 514 |
+
gallery_out = gr.Gallery(
|
| 515 |
+
label="Output",
|
| 516 |
+
columns=1,
|
| 517 |
+
height=460,
|
| 518 |
+
object_fit="contain",
|
| 519 |
+
)
|
| 520 |
+
like_callout = gr.HTML(
|
| 521 |
+
"<div id='like-callout'>Enjoying the results ? "
|
| 522 |
+
"<span class='accent'>♥ Like this Space</span> 🙂</div>",
|
| 523 |
+
visible=False,
|
| 524 |
+
)
|
| 525 |
+
|
| 526 |
+
submit_btn.click(
|
| 527 |
+
fn=edit_image,
|
| 528 |
+
inputs=[image_in, prompt_in, model_in],
|
| 529 |
+
outputs=[gallery_out, like_callout],
|
| 530 |
+
show_progress="full",
|
| 531 |
+
)
|
| 532 |
+
|
| 533 |
+
gr.HTML(PRIVACY_HTML)
|
| 534 |
+
|
| 535 |
+
demo.queue(max_size=20, default_concurrency_limit=4)
|
| 536 |
+
|
| 537 |
+
if __name__ == "__main__":
|
| 538 |
+
demo.launch(share=False, **_launch_kwargs)
|