q6 commited on
Commit
3aca7f0
·
1 Parent(s): 4b2855a

Expand standalone upscale interface

Browse files
Files changed (5) hide show
  1. app.py +37 -11
  2. upscale-page.js +42 -11
  3. upscale.css +51 -7
  4. upscale.html +11 -3
  5. upscale.js +12 -3
app.py CHANGED
@@ -284,7 +284,6 @@ MATRIX_TYPES = (
284
  "sampler+scheduler",
285
  COMBINED_MATRIX_TYPE,
286
  )
287
- UPSCALE_MODEL_ID = 1
288
  UPSCALE_GPU_DURATION = 5
289
  MAX_UPSCALE_BYTES = 20 * MIB
290
  MAX_UPSCALE_PIXELS = 4 * 1024 * 1024
@@ -2694,6 +2693,20 @@ def api_generate(body, p=""):
2694
  def api_upscale(body, p=""):
2695
  if not valid_pass(p):
2696
  raise gr.Error("Invalid password")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2697
  if len(body) > (MAX_UPSCALE_BYTES + 2) // 3 * 4:
2698
  raise gr.Error("Image exceeds 20 MiB")
2699
  try:
@@ -2713,18 +2726,16 @@ def api_upscale(body, p=""):
2713
  ).unsqueeze(0)
2714
  with lock:
2715
  init_comfy()
2716
- prefix = f"{UPSCALE_MODEL_ID}_"
2717
- names = [
2718
- name for name in remote_models["upscale_models"]
2719
- if name.startswith(prefix)
2720
- ]
2721
- if len(names) != 1:
2722
- raise gr.Error(f"Expected one upscale model with prefix {prefix}")
2723
- model = load_upscale_model(names[0])
2724
  result = tensor_image(infer_upscale(pixels, model))
 
 
 
2725
  alpha = image.getchannel("A")
2726
  if alpha.getextrema() != (255, 255):
2727
- result.putalpha(alpha.resize(result.size, Image.Resampling.LANCZOS))
2728
  result.info.update(image.info)
2729
  return base64.b64encode(image_png_bytes(result)).decode()
2730
 
@@ -3488,19 +3499,34 @@ def upscale_asset(name: str):
3488
  return FileResponse(Path.cwd() / filename, media_type=media_type)
3489
 
3490
 
 
 
 
 
 
 
 
 
3491
  @api.post("/api/upscale", dependencies=[Depends(require_pass)])
3492
  def upscale_download(
3493
  body: bytes = Body(b"", media_type="application/octet-stream"),
3494
  path: str = Query(None),
 
 
3495
  ):
3496
  data = stored_bytes(stored_path(path)) if path is not None else body
3497
  if len(data) > MAX_UPSCALE_BYTES:
3498
  raise HTTPException(413, "Image exceeds 20 MiB")
3499
  if not data:
3500
  raise HTTPException(422, "An image is required")
 
 
 
 
 
3501
  try:
3502
  result = get_local_client().predict(
3503
- base64.b64encode(data).decode(),
3504
  PASSWORD,
3505
  api_name="/upscale",
3506
  )
 
284
  "sampler+scheduler",
285
  COMBINED_MATRIX_TYPE,
286
  )
 
287
  UPSCALE_GPU_DURATION = 5
288
  MAX_UPSCALE_BYTES = 20 * MIB
289
  MAX_UPSCALE_PIXELS = 4 * 1024 * 1024
 
2693
  def api_upscale(body, p=""):
2694
  if not valid_pass(p):
2695
  raise gr.Error("Invalid password")
2696
+ model_name = DEFAULT_UPSCALE_MODEL
2697
+ scale = 1
2698
+ try:
2699
+ payload = json.loads(body)
2700
+ if isinstance(payload, dict):
2701
+ body = payload["image"]
2702
+ model_name = payload.get("model", model_name)
2703
+ scale = float(payload.get("scale", scale))
2704
+ except json.JSONDecodeError:
2705
+ pass
2706
+ except (KeyError, TypeError, ValueError) as error:
2707
+ raise gr.Error("Invalid upscale request") from error
2708
+ if not 1 <= scale <= 4:
2709
+ raise gr.Error("Scale must be between 1 and 4")
2710
  if len(body) > (MAX_UPSCALE_BYTES + 2) // 3 * 4:
2711
  raise gr.Error("Image exceeds 20 MiB")
2712
  try:
 
2726
  ).unsqueeze(0)
2727
  with lock:
2728
  init_comfy()
2729
+ if model_name not in model_options("upscale_models", []):
2730
+ raise gr.Error(f"Unknown upscale model: {model_name}")
2731
+ model = load_upscale_model(model_name)
 
 
 
 
 
2732
  result = tensor_image(infer_upscale(pixels, model))
2733
+ size = round(image.width * scale), round(image.height * scale)
2734
+ if result.size != size:
2735
+ result = result.resize(size, Image.Resampling.LANCZOS)
2736
  alpha = image.getchannel("A")
2737
  if alpha.getextrema() != (255, 255):
2738
+ result.putalpha(alpha.resize(size, Image.Resampling.LANCZOS))
2739
  result.info.update(image.info)
2740
  return base64.b64encode(image_png_bytes(result)).decode()
2741
 
 
3499
  return FileResponse(Path.cwd() / filename, media_type=media_type)
3500
 
3501
 
3502
+ @api.get("/api/upscale/options", dependencies=[Depends(require_pass)])
3503
+ def upscale_options():
3504
+ return {
3505
+ "models": model_options("upscale_models", []),
3506
+ "default": DEFAULT_UPSCALE_MODEL,
3507
+ }
3508
+
3509
+
3510
  @api.post("/api/upscale", dependencies=[Depends(require_pass)])
3511
  def upscale_download(
3512
  body: bytes = Body(b"", media_type="application/octet-stream"),
3513
  path: str = Query(None),
3514
+ model: str = Query(DEFAULT_UPSCALE_MODEL),
3515
+ scale: float = Query(1, ge=1, le=4),
3516
  ):
3517
  data = stored_bytes(stored_path(path)) if path is not None else body
3518
  if len(data) > MAX_UPSCALE_BYTES:
3519
  raise HTTPException(413, "Image exceeds 20 MiB")
3520
  if not data:
3521
  raise HTTPException(422, "An image is required")
3522
+ request = json.dumps({
3523
+ "image": base64.b64encode(data).decode(),
3524
+ "model": model,
3525
+ "scale": scale,
3526
+ })
3527
  try:
3528
  result = get_local_client().predict(
3529
+ request,
3530
  PASSWORD,
3531
  api_name="/upscale",
3532
  )
upscale-page.js CHANGED
@@ -1,25 +1,56 @@
1
- import { downloadUpscale } from "/upscale/image.js"
2
 
3
  const $ = selector => document.querySelector(selector)
 
 
 
4
  const upload = $("#upload")
5
- const preview = $("#preview")
 
 
6
  const status = $(".status")
 
 
7
 
8
- upload.addEventListener("change", async () => {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  const file = upload.files[0]
10
  if (!file) return
11
- if (preview.hasAttribute("src")) URL.revokeObjectURL(preview.src)
12
- preview.src = URL.createObjectURL(file)
13
- preview.hidden = false
14
- upload.disabled = true
15
  status.textContent = "Upscaling…"
16
  try {
17
- await downloadUpscale({ file, name: file.name })
18
- status.textContent = "Downloaded"
 
 
 
 
 
 
 
 
19
  } catch (error) {
20
  status.textContent = error.message
21
  } finally {
22
- upload.disabled = false
23
- upload.value = ""
24
  }
25
  })
 
1
+ import { upscaleImage } from "/upscale/image.js"
2
 
3
  const $ = selector => document.querySelector(selector)
4
+ const p = new URLSearchParams(location.search).get("p")
5
+ const model = $("#model")
6
+ const scale = $("#scale")
7
  const upload = $("#upload")
8
+ const button = $("#upscale")
9
+ const input = $("#input")
10
+ const output = $("#output")
11
  const status = $(".status")
12
+ let inputUrl
13
+ let outputUrl
14
 
15
+ const optionsResponse = await fetch(`/api/upscale/options?${new URLSearchParams({ p })}`)
16
+ if (optionsResponse.ok) {
17
+ const options = await optionsResponse.json()
18
+ for (const name of options.models) model.add(new Option(name, name))
19
+ model.value = options.default
20
+ } else {
21
+ status.textContent = "Unable to load upscale models"
22
+ }
23
+
24
+ upload.addEventListener("change", () => {
25
+ const file = upload.files[0]
26
+ if (!file) return
27
+ if (inputUrl) URL.revokeObjectURL(inputUrl)
28
+ inputUrl = URL.createObjectURL(file)
29
+ input.src = inputUrl
30
+ input.hidden = false
31
+ button.disabled = !model.value
32
+ status.textContent = ""
33
+ })
34
+
35
+ button.addEventListener("click", async () => {
36
  const file = upload.files[0]
37
  if (!file) return
38
+ button.disabled = true
 
 
 
39
  status.textContent = "Upscaling…"
40
  try {
41
+ const blob = await upscaleImage({
42
+ file,
43
+ model: model.value,
44
+ scale: scale.value,
45
+ })
46
+ if (outputUrl) URL.revokeObjectURL(outputUrl)
47
+ outputUrl = URL.createObjectURL(blob)
48
+ output.src = outputUrl
49
+ output.hidden = false
50
+ status.textContent = "Complete"
51
  } catch (error) {
52
  status.textContent = error.message
53
  } finally {
54
+ button.disabled = false
 
55
  }
56
  })
upscale.css CHANGED
@@ -1,29 +1,73 @@
 
 
 
 
1
  .upscale-page {
2
- color: var(--muted);
3
  display: grid;
4
- gap: var(--gap);
 
5
  margin: 2rem auto;
6
  width: var(--width);
7
  }
8
 
9
- #upload {
10
- font: inherit;
11
- max-width: 100%;
 
 
12
  }
13
 
14
- #upload::file-selector-button {
 
 
 
 
 
 
 
 
 
 
 
15
  background: var(--panel);
16
  border: 1px solid var(--border);
17
  border-radius: 0;
18
  color: var(--text);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  cursor: pointer;
20
  font: inherit;
21
  margin-right: var(--gap);
22
  padding: .65rem .8rem;
23
  }
24
 
25
- #preview {
 
 
 
 
 
26
  max-height: 80vh;
27
  object-fit: contain;
28
  width: 100%;
29
  }
 
 
 
 
 
 
 
 
1
+ :root {
2
+ --control-width: 22rem;
3
+ }
4
+
5
  .upscale-page {
 
6
  display: grid;
7
+ gap: 2rem;
8
+ grid-template-columns: minmax(16rem, var(--control-width)) 1fr;
9
  margin: 2rem auto;
10
  width: var(--width);
11
  }
12
 
13
+ .controls,
14
+ .images,
15
+ label {
16
+ display: grid;
17
+ gap: var(--gap);
18
  }
19
 
20
+ .controls {
21
+ align-content: start;
22
+ }
23
+
24
+ label {
25
+ color: var(--muted);
26
+ gap: .4rem;
27
+ }
28
+
29
+ select,
30
+ input,
31
+ #upscale {
32
  background: var(--panel);
33
  border: 1px solid var(--border);
34
  border-radius: 0;
35
  color: var(--text);
36
+ font: inherit;
37
+ min-width: 0;
38
+ padding: .65rem .8rem;
39
+ width: 100%;
40
+ }
41
+
42
+ #upload {
43
+ padding: 0;
44
+ }
45
+
46
+ #upload::file-selector-button {
47
+ background: var(--panel);
48
+ border: 0;
49
+ border-right: 1px solid var(--border);
50
+ color: var(--text);
51
  cursor: pointer;
52
  font: inherit;
53
  margin-right: var(--gap);
54
  padding: .65rem .8rem;
55
  }
56
 
57
+ .images {
58
+ grid-template-columns: repeat(2, minmax(0, 1fr));
59
+ }
60
+
61
+ .images img {
62
+ background: var(--panel);
63
  max-height: 80vh;
64
  object-fit: contain;
65
  width: 100%;
66
  }
67
+
68
+ @media (max-width: 800px) {
69
+ .upscale-page,
70
+ .images {
71
+ grid-template-columns: 1fr;
72
+ }
73
+ }
upscale.html CHANGED
@@ -11,9 +11,17 @@
11
  </head>
12
  <body>
13
  <main class="upscale-page">
14
- <input id="upload" type="file" accept="image/*" aria-label="Upload image">
15
- <div class="status" role="status" aria-live="polite"></div>
16
- <img id="preview" alt="Original image" hidden>
 
 
 
 
 
 
 
 
17
  </main>
18
  </body>
19
  </html>
 
11
  </head>
12
  <body>
13
  <main class="upscale-page">
14
+ <section class="controls">
15
+ <label>Upscale model<select id="model"></select></label>
16
+ <label>Upscale scale<input id="scale" type="number" min="1" max="4" step=".1" value="1"></label>
17
+ <label>Input image<input id="upload" type="file" accept="image/*"></label>
18
+ <button id="upscale" class="primary" type="button" disabled>Upscale</button>
19
+ <div class="status" role="status" aria-live="polite"></div>
20
+ </section>
21
+ <section class="images">
22
+ <img id="input" alt="Input image" hidden>
23
+ <img id="output" alt="Output image" hidden>
24
+ </section>
25
  </main>
26
  </body>
27
  </html>
upscale.js CHANGED
@@ -1,8 +1,12 @@
1
  const DOWNLOAD_LIFETIME = 30000
2
 
3
- export async function downloadUpscale({ file, path, name }) {
4
- const query = new URLSearchParams({ p: new URLSearchParams(location.search).get("p") })
 
 
 
5
  if (path !== undefined) query.set("path", path)
 
6
  const response = await fetch(`/api/upscale?${query}`, {
7
  method: "POST",
8
  headers: { "Content-Type": "application/octet-stream" },
@@ -15,7 +19,12 @@ export async function downloadUpscale({ file, path, name }) {
15
  }
16
  throw new Error(`Upscale failed (${response.status})`)
17
  }
18
- const url = URL.createObjectURL(await response.blob())
 
 
 
 
 
19
  const link = document.createElement("a")
20
  link.href = url
21
  link.download = `${name.replace(/\.[^.]+$/, "")}-upscaled.png`
 
1
  const DOWNLOAD_LIFETIME = 30000
2
 
3
+ export async function upscaleImage({ file, path, model, scale = 1 }) {
4
+ const query = new URLSearchParams({
5
+ p: new URLSearchParams(location.search).get("p"),
6
+ scale,
7
+ })
8
  if (path !== undefined) query.set("path", path)
9
+ if (model !== undefined) query.set("model", model)
10
  const response = await fetch(`/api/upscale?${query}`, {
11
  method: "POST",
12
  headers: { "Content-Type": "application/octet-stream" },
 
19
  }
20
  throw new Error(`Upscale failed (${response.status})`)
21
  }
22
+ return response.blob()
23
+ }
24
+
25
+ export async function downloadUpscale({ file, path, name, model, scale }) {
26
+ const blob = await upscaleImage({ file, path, model, scale })
27
+ const url = URL.createObjectURL(blob)
28
  const link = document.createElement("a")
29
  link.href = url
30
  link.download = `${name.replace(/\.[^.]+$/, "")}-upscaled.png`