Luca448 commited on
Commit
3a1c0fc
·
1 Parent(s): 821f6b7

Savestate: Integrate Gradio Client to hit FLUX.1-Fill-dev Space directly for high-quality AI inpainting

Browse files
index.html CHANGED
@@ -74,7 +74,7 @@
74
  </head>
75
  <body class="dark-theme in-chat-view">
76
 
77
- <div id="live-version-badge" style="position: fixed; top: 50px; left: 50%; transform: translateX(-50%); font-size: 10px; color: var(--text-secondary); opacity: 0.6; z-index: 99999; pointer-events: none; font-weight: 500; font-family: monospace; letter-spacing: 1px; background: rgba(0,0,0,0.2); padding: 2px 8px; border-radius: 10px; border: 1px solid rgba(255,255,255,0.05);">BUILD 1.8.220</div>
78
 
79
  <!-- SVG Filters for Liquid Glass Refraction -->
80
  <svg width="0" height="0" style="position: absolute; pointer-events: none;">
 
74
  </head>
75
  <body class="dark-theme in-chat-view">
76
 
77
+ <div id="live-version-badge" style="position: fixed; top: 50px; left: 50%; transform: translateX(-50%); font-size: 10px; color: var(--text-secondary); opacity: 0.6; z-index: 99999; pointer-events: none; font-weight: 500; font-family: monospace; letter-spacing: 1px; background: rgba(0,0,0,0.2); padding: 2px 8px; border-radius: 10px; border: 1px solid rgba(255,255,255,0.05);">BUILD 1.8.221</div>
78
 
79
  <!-- SVG Filters for Liquid Glass Refraction -->
80
  <svg width="0" height="0" style="position: absolute; pointer-events: none;">
package-lock.json CHANGED
@@ -13,6 +13,7 @@
13
  "@capacitor/core": "^6.0.0",
14
  "@capacitor/filesystem": "^6.0.0",
15
  "@capacitor/preferences": "^6.0.0",
 
16
  "@huggingface/inference": "^4.13.23",
17
  "@supabase/supabase-js": "^2.110.0",
18
  "body-parser": "^2.3.0",
@@ -2376,6 +2377,18 @@
2376
  "node": ">=12"
2377
  }
2378
  },
 
 
 
 
 
 
 
 
 
 
 
 
2379
  "node_modules/@huggingface/inference": {
2380
  "version": "4.13.23",
2381
  "resolved": "https://registry.npmjs.org/@huggingface/inference/-/inference-4.13.23.tgz",
@@ -6090,6 +6103,12 @@
6090
  }
6091
  }
6092
  },
 
 
 
 
 
 
6093
  "node_modules/filelist": {
6094
  "version": "1.0.6",
6095
  "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.6.tgz",
 
13
  "@capacitor/core": "^6.0.0",
14
  "@capacitor/filesystem": "^6.0.0",
15
  "@capacitor/preferences": "^6.0.0",
16
+ "@gradio/client": "^2.3.1",
17
  "@huggingface/inference": "^4.13.23",
18
  "@supabase/supabase-js": "^2.110.0",
19
  "body-parser": "^2.3.0",
 
2377
  "node": ">=12"
2378
  }
2379
  },
2380
+ "node_modules/@gradio/client": {
2381
+ "version": "2.3.1",
2382
+ "resolved": "https://registry.npmjs.org/@gradio/client/-/client-2.3.1.tgz",
2383
+ "integrity": "sha512-Vznt4Ju/nPCajVMlwbJgfrHp0NGodSNCYxoxQEb9WfwPVF2fSNyobGmIiQ2/xbm7Mkn3afNGRqfmIyjJesjOxw==",
2384
+ "license": "ISC",
2385
+ "dependencies": {
2386
+ "fetch-event-stream": "^0.1.5"
2387
+ },
2388
+ "engines": {
2389
+ "node": ">=18.0.0"
2390
+ }
2391
+ },
2392
  "node_modules/@huggingface/inference": {
2393
  "version": "4.13.23",
2394
  "resolved": "https://registry.npmjs.org/@huggingface/inference/-/inference-4.13.23.tgz",
 
6103
  }
6104
  }
6105
  },
6106
+ "node_modules/fetch-event-stream": {
6107
+ "version": "0.1.6",
6108
+ "resolved": "https://registry.npmjs.org/fetch-event-stream/-/fetch-event-stream-0.1.6.tgz",
6109
+ "integrity": "sha512-GREtJ5HNikdU2AXtZ6E/5bk+aslMU6ie5mPG6H9nvsdDkkHQ6m5lHwmmmDTOBexok9hApQ7EprsXCdmz9ZC68w==",
6110
+ "license": "MIT"
6111
+ },
6112
  "node_modules/filelist": {
6113
  "version": "1.0.6",
6114
  "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.6.tgz",
package.json CHANGED
@@ -15,6 +15,7 @@
15
  "@capacitor/core": "^6.0.0",
16
  "@capacitor/filesystem": "^6.0.0",
17
  "@capacitor/preferences": "^6.0.0",
 
18
  "@huggingface/inference": "^4.13.23",
19
  "@supabase/supabase-js": "^2.110.0",
20
  "body-parser": "^2.3.0",
 
15
  "@capacitor/core": "^6.0.0",
16
  "@capacitor/filesystem": "^6.0.0",
17
  "@capacitor/preferences": "^6.0.0",
18
+ "@gradio/client": "^2.3.1",
19
  "@huggingface/inference": "^4.13.23",
20
  "@supabase/supabase-js": "^2.110.0",
21
  "body-parser": "^2.3.0",
src/ai/flux-client.js CHANGED
@@ -1,78 +1,58 @@
 
 
1
  export class FluxClient {
2
  constructor() {
3
- this.huggingFaceUrl = "https://router.huggingface.co/hf-inference/models/diffusers/stable-diffusion-xl-1.0-inpainting-0.1";
4
  }
5
 
6
  async fillImage(prompt, originalBase64, maskBase64, apiKey) {
7
  if (!apiKey) throw new Error("Hugging Face API Token fehlt.");
8
 
9
- // Convert base64 to blobs for multipart/form-data
10
  const originalBlob = this.base64ToBlob(originalBase64, 'image/png');
11
  const maskBlob = this.base64ToBlob(maskBase64, 'image/png');
 
 
 
12
 
13
- const formData = new FormData();
14
- formData.append("inputs", prompt);
15
- formData.append("image", originalBlob, "image.png");
16
- formData.append("mask_image", maskBlob, "mask.png");
17
 
18
- const controller = new AbortController();
19
- const timeoutId = setTimeout(() => controller.abort(), 180000); // 3 Minuten Timeout
 
 
 
 
20
 
21
- let response;
22
- try {
23
- response = await fetch(this.huggingFaceUrl, {
24
- method: 'POST',
25
- headers: {
26
- 'Authorization': `Bearer ${apiKey}`
27
- },
28
- body: formData,
29
- signal: controller.signal
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  });
 
31
  } catch (e) {
32
- if (e.name === 'AbortError') {
33
- throw new Error("Timeout: Der Hugging Face Server hat nach 3 Minuten nicht geantwortet.");
34
- }
35
- if (e.message.includes('Failed to fetch') || e.message.includes('NetworkError')) {
36
- console.warn("Direct fetch failed (CORS/Network). Retrying via proxy...");
37
- // Retry with a CORS proxy
38
- try {
39
- const proxyUrl = "https://corsproxy.io/?" + encodeURIComponent(this.huggingFaceUrl);
40
- response = await fetch(proxyUrl, {
41
- method: 'POST',
42
- headers: {
43
- 'Authorization': `Bearer ${apiKey}`
44
- },
45
- body: formData,
46
- signal: controller.signal
47
- });
48
- } catch(proxyErr) {
49
- throw new Error("Netzwerkfehler (Failed to fetch). Hugging Face blockiert die Anfrage (CORS) oder das Modell ist überlastet. " + proxyErr.message);
50
- }
51
- } else {
52
- throw e;
53
- }
54
- } finally {
55
- clearTimeout(timeoutId);
56
- }
57
-
58
- if (!response.ok) {
59
- const errText = await response.text();
60
- let msg = errText;
61
- try {
62
- const json = JSON.parse(errText);
63
- if (json.error) msg = json.error;
64
- if (json.estimated_time) msg += ` (Geschätzte Wartezeit: ${Math.round(json.estimated_time)}s)`;
65
- } catch(e) {}
66
- throw new Error(`FLUX.1-Fill API Error ${response.status}: ${msg}`);
67
  }
68
-
69
- const blob = await response.blob();
70
- return new Promise((resolve, reject) => {
71
- const reader = new FileReader();
72
- reader.onloadend = () => resolve(reader.result); // Returns data:image/jpeg;base64,...
73
- reader.onerror = reject;
74
- reader.readAsDataURL(blob);
75
- });
76
  }
77
 
78
  base64ToBlob(base64, mimeType) {
@@ -87,7 +67,7 @@ export class FluxClient {
87
  const byteArray = new Uint8Array(byteNumbers);
88
  byteArrays.push(byteArray);
89
  }
90
- return new Blob(byteArrays, {type: mimeType});
91
  }
92
  }
93
 
 
1
+ import { Client } from "@gradio/client";
2
+
3
  export class FluxClient {
4
  constructor() {
5
+ this.spaceId = "black-forest-labs/FLUX.1-Fill-dev";
6
  }
7
 
8
  async fillImage(prompt, originalBase64, maskBase64, apiKey) {
9
  if (!apiKey) throw new Error("Hugging Face API Token fehlt.");
10
 
 
11
  const originalBlob = this.base64ToBlob(originalBase64, 'image/png');
12
  const maskBlob = this.base64ToBlob(maskBase64, 'image/png');
13
+
14
+ // Für optimale Ergebnisse maskBlob invertieren, da mask meist weiß für inpaint ist,
15
+ // aber das hängt vom Tool ab. Wir lassen es so, wie es von chat-view kommt.
16
 
17
+ try {
18
+ const app = await Client.connect(this.spaceId, { hf_token: apiKey });
 
 
19
 
20
+ // Gradio ImageEditor erwartet dieses Format für Inpainting
21
+ const editImage = {
22
+ background: originalBlob,
23
+ layers: [maskBlob],
24
+ composite: null
25
+ };
26
 
27
+ const result = await app.predict("/infer", [
28
+ editImage, // edit_images
29
+ prompt, // prompt
30
+ 0, // seed
31
+ true, // randomize_seed
32
+ 1024, // width
33
+ 1024, // height
34
+ 30, // guidance_scale
35
+ 28 // num_inference_steps
36
+ ]);
37
+
38
+ const outputData = result.data[0];
39
+ const outputUrl = outputData.url || outputData;
40
+
41
+ // Fetch the image and convert to base64
42
+ const response = await fetch(outputUrl);
43
+ const blob = await response.blob();
44
+
45
+ return new Promise((resolve, reject) => {
46
+ const reader = new FileReader();
47
+ reader.onloadend = () => resolve(reader.result);
48
+ reader.onerror = reject;
49
+ reader.readAsDataURL(blob);
50
  });
51
+
52
  } catch (e) {
53
+ console.error("Gradio API Error:", e);
54
+ throw new Error(`Fehler bei der Verbindung zum FLUX Space: ${e.message}`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  }
 
 
 
 
 
 
 
 
56
  }
57
 
58
  base64ToBlob(base64, mimeType) {
 
67
  const byteArray = new Uint8Array(byteNumbers);
68
  byteArrays.push(byteArray);
69
  }
70
+ return new Blob(byteArrays, { type: mimeType });
71
  }
72
  }
73
 
src/views/chat/chat-view.js CHANGED
@@ -4525,46 +4525,49 @@ body { margin: 0; padding: 0; background: #000; overflow: hidden; display: flex;
4525
  const width = sourceImage.width;
4526
  const height = sourceImage.height;
4527
 
4528
- // Lokales, sofortiges "Inpainting" per Canvas (100% präzise, 100% gratis)
4529
- const finalCanvas = document.createElement('canvas');
4530
- finalCanvas.width = width;
4531
- finalCanvas.height = height;
4532
- const fCtx = finalCanvas.getContext('2d');
 
 
 
 
4533
 
4534
- // Originalbild zeichnen
4535
- fCtx.drawImage(sourceImage, 0, 0);
 
4536
 
4537
- // Jede Lücke ausfüllen
4538
  jsonData.forEach(item => {
4539
  const x = (item.x / 1000) * width;
4540
  const y = (item.y / 1000) * height;
4541
  const w = (item.width / 1000) * width || 100;
4542
  const h = (item.height / 1000) * height || 30;
4543
-
4544
- // Originalen leeren Platz leicht aufhellen, falls Striche im Weg sind
4545
- fCtx.fillStyle = 'rgba(255, 255, 255, 0.6)';
4546
- fCtx.fillRect(x, y, w, h);
4547
-
4548
- // Blaue "Tinte" für Handschrift
4549
- fCtx.fillStyle = "#0f172a"; // Sehr dunkles Blau/Grau
4550
- fCtx.textAlign = "center";
4551
- fCtx.textBaseline = "middle";
4552
-
4553
- // Schriftgröße berechnen
4554
- let fontSize = Math.max(12, Math.min(22, h * 0.7));
4555
- // Versuche eine Handschrift-Schriftart, ansonsten kursiv
4556
- fCtx.font = `italic ${fontSize}px "Comic Sans MS", "Chalkboard SE", "Segoe UI", sans-serif`;
4557
-
4558
- fCtx.fillText(item.text, x + (w/2), y + (h/2));
4559
  });
4560
 
4561
- const resultBase64 = finalCanvas.toDataURL('image/jpeg', 0.95);
4562
- img.src = resultBase64;
4563
 
4564
- const loadingText = img.previousElementSibling;
4565
- if (loadingText) {
4566
- loadingText.innerHTML = "Arbeitsblatt erfolgreich ausgefüllt!";
4567
- setTimeout(() => { loadingText.style.display = 'none'; }, 2000);
 
 
 
 
 
 
 
 
 
 
 
 
 
4568
  }
4569
 
4570
  } catch (e) {
 
4525
  const width = sourceImage.width;
4526
  const height = sourceImage.height;
4527
 
4528
+ // Canvas für Maske erstellen
4529
+ const canvas = document.createElement('canvas');
4530
+ canvas.width = width;
4531
+ canvas.height = height;
4532
+ const ctx = canvas.getContext('2d');
4533
+
4534
+ // Schwarz füllen
4535
+ ctx.fillStyle = '#000000';
4536
+ ctx.fillRect(0, 0, width, height);
4537
 
4538
+ // Weiß für Lücken zeichnen
4539
+ ctx.fillStyle = '#FFFFFF';
4540
+ let promptText = "Schreibe folgende Texte sauber und handschriftlich an die markierten Stellen im Bild, achte exakt auf die Perspektive und die Form des Papiers: ";
4541
 
 
4542
  jsonData.forEach(item => {
4543
  const x = (item.x / 1000) * width;
4544
  const y = (item.y / 1000) * height;
4545
  const w = (item.width / 1000) * width || 100;
4546
  const h = (item.height / 1000) * height || 30;
4547
+ ctx.fillRect(x, y, w, h);
4548
+ promptText += `"${item.text}", `;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4549
  });
4550
 
4551
+ const maskDataUrl = canvas.toDataURL('image/png');
4552
+ const maskBase64 = maskDataUrl.split(',')[1];
4553
 
4554
+ // API Call
4555
+ if (hfKey) {
4556
+ try {
4557
+ const loadingText = img.previousElementSibling;
4558
+ const timerId = setTimeout(() => {
4559
+ if (loadingText) loadingText.innerHTML = loadingText.innerHTML.replace('FLUX.1 Inpainting aktiv...', 'FLUX.1 Server wacht auf (ca. 2 Min)...');
4560
+ }, 10000);
4561
+
4562
+ const resultBase64 = await fluxClient.fillImage(promptText, lastUserBase64, maskBase64, hfKey);
4563
+ clearTimeout(timerId);
4564
+ img.src = resultBase64;
4565
+ } catch(apiErr) {
4566
+ console.error("FLUX API Error:", apiErr);
4567
+ throw new Error(apiErr.message);
4568
+ }
4569
+ } else {
4570
+ throw new Error("Hugging Face API Key fehlt in den Einstellungen!");
4571
  }
4572
 
4573
  } catch (e) {