Should mostly work and send to openoutpaint button

Signed-off-by: Victor Seiji Hariki <victorseijih@gmail.com>
pull/5/head
Victor Seiji Hariki 2022-12-19 13:14:16 -03:00
parent 77f73696bf
commit d81f7476a7
4 changed files with 190 additions and 6 deletions

19
.prettierrc.json Normal file
View File

@ -0,0 +1,19 @@
{
"arrowParens": "always",
"bracketSameLine": true,
"bracketSpacing": false,
"embeddedLanguageFormatting": "auto",
"htmlWhitespaceSensitivity": "ignore",
"insertPragma": false,
"jsxSingleQuote": false,
"printWidth": 80,
"proseWrap": "preserve",
"quoteProps": "as-needed",
"requirePragma": false,
"semi": true,
"singleQuote": false,
"tabWidth": 2,
"trailingComma": "es5",
"useTabs": true,
"vueIndentScriptAndStyle": false
}

View File

@ -0,0 +1,107 @@
// Txt2Img Send to Resource
const openoutpaint = {
frame: null,
key: null,
};
async function openoutpaint_get_image_from_gallery() {
return new Promise(function (resolve, reject) {
var buttons = gradioApp().querySelectorAll(
'[style="display: block;"].tabitem div[id$=_gallery] .gallery-item'
);
var button = gradioApp().querySelector(
'[style="display: block;"].tabitem div[id$=_gallery] .gallery-item.\\!ring-2'
);
if (!button) button = buttons[0];
if (!button)
reject(new Error("[openoutpaint] No image selected in the gallery"));
const canvas = document.createElement("canvas");
const image = document.createElement("img");
image.onload = () => {
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext("2d").drawImage(image, 0, 0);
resolve(canvas.toDataURL());
};
image.src = button.querySelector("img").src;
});
}
function openoutpaint_send_gallery() {
openoutpaint_get_image_from_gallery()
.then((dataURL) => {
// Send to openOutpaint
openoutpaint.frame.contentWindow.postMessage({
key: openoutpaint.key,
type: "openoutpaint/add-resource",
image: {
dataURL,
resourceName: "Embed Resource",
},
});
})
.catch((error) => {
console.warn("[openoutpaint] No image selected to send to openOutpaint");
});
// Change Tab
Array.from(
gradioApp().querySelectorAll("#tabs > div:first-child button")
).forEach((button) => {
if (button.textContent.trim() === "openOutpaint") {
button.click();
}
});
}
const openoutpaintjs = async () => {
const frame = gradioApp().getElementById("openoutpaint-iframe");
const key = gradioApp().getElementById("openoutpaint-key").value;
openoutpaint.frame = frame;
openoutpaint.key = key;
// Listens for messages from the frame
console.info("[embed] Add message listener");
window.addEventListener("message", ({data, origin, source}) => {
if (source === frame.contentWindow) {
switch (data.type) {
case "ack":
if (data.message.type === "openoutpaint/init") {
console.info("[embed] Received init ack");
clearTimeout(initLoop);
initLoop = null;
}
break;
}
}
});
// Initializes communication channel
let initLoop = null;
const sendInit = () => {
console.info("[embed] Sending init message");
frame.contentWindow.postMessage({
type: "openoutpaint/init",
key,
});
initLoop = setTimeout(sendInit, 1000);
};
sendInit();
};
document.addEventListener("DOMContentLoaded", () => {
const onload = () => {
if (gradioApp().getElementById("openoutpaint-iframe")) {
openoutpaintjs();
} else {
setTimeout(onload, 10);
}
};
onload();
});

33
scripts/interface.py Normal file
View File

@ -0,0 +1,33 @@
import gradio as gr
from modules import script_callbacks, shared, scripts
elements = {}
class Script(scripts.Script):
img2img = None
txt2img = None
def title(self):
return "OpenOutpaint"
def show(self, is_img2img):
return scripts.AlwaysVisible
def after_component(self, component, **kwargs):
global elements, share_image
if kwargs.get('elem_id') is not None:
if kwargs.get('elem_id').find('txt2img_gallery') != -1:
self.txt2img = component
elif kwargs.get('elem_id').find('img2img_gallery') != -1:
self.img2img = component
if kwargs.get("value") == "Send to extras":
elements["openoutpaint_button"] = gr.Button(
"Send to openOutpaint", elem_id=f"openoutpaint_button")
elements["openoutpaint_button"].click(None, [], None,
_js="() => openoutpaint_send_gallery()")
def ui(self, is_img2img):
if elements.get("openoutpaint_button"):
pass
return []

View File

@ -7,22 +7,47 @@ import sys
import platform
from launch import run
import string
import random as rd
key_characters = (string.ascii_letters + string.digits)
def random_string(length=20):
return ''.join([rd.choice(key_characters) for _ in range(length)])
key = random_string()
def add_tab():
with gr.Blocks(analytics_enabled=False) as ui:
#refresh = gr.Button(value="refresh", variant="primary")
canvas = gr.HTML(f"<iframe src=\"file/" + usefulDirs[0] + "/" + usefulDirs[1] + "/app/index.html\" style=\"height:1024px;width:100%;\"></iframe>")
canvas = gr.HTML(
f"<iframe id=\"openoutpaint-iframe\" src=\"file/{usefulDirs[0]}/{usefulDirs[1]}/app/index.html\" style=\"height:1024px;width:100%;\"></iframe>")
keyinput = gr.HTML(
f"<input id=\"openoutpaint-key\" type=\"hidden\" value=\"{key}\">")
# refresh.click(
# )
# )
return [(ui, "openOutpaint", "openOutpaint")]
usefulDirs = scripts.basedir().split(os.sep)[-2:]
print("openOutpaint init")
print(scripts.basedir())
usefulDirs = scripts.basedir().split(os.sep)[-2:]
print(usefulDirs)
git = os.environ.get('GIT', "git")
print(git)
print(run(f'"{git}" -C ' + scripts.basedir() + ' submodule update --init --recursive --remote'))
script_callbacks.on_ui_tabs(add_tab)
print(run(f'"{git}" -C ' + scripts.basedir() +
' submodule update --init --recursive --remote'))
with open(f"{scripts.basedir()}/app/key.json", "w") as keyfile:
keyfile.write('{\n')
keyfile.write(f" \"key\": \"{key}\"\n")
keyfile.write('}\n')
keyfile.close()
script_callbacks.on_ui_tabs(add_tab)