diff --git a/CanvasToolLone/data.json b/CanvasToolLone/data.json deleted file mode 100644 index 08dc500..0000000 --- a/CanvasToolLone/data.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "savedata": { - "crpdimsref": { - "left": 0, - "top": 186, - "right": 512, - "bottom": 698 - }, - "crpdims": { - "left": 0, - "top": 540, - "right": 512, - "bottom": 698 - }, - "additionaldims": { - "left": 0, - "top": 0, - "right": 0, - "bottom": 354 - }, - "boxsz": "512", - "ff": "30", - "pxlsarray": "" - } -} \ No newline at end of file diff --git a/CanvasToolLone/index.html b/CanvasToolLone/index.html deleted file mode 100644 index 529ba98..0000000 --- a/CanvasToolLone/index.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - ComfyUI - - - - - - - - - - -

Open Canvas

-

Open Canvas (last image)

- diff --git a/CanvasToolLone/index.py b/CanvasToolLone/index.py deleted file mode 100644 index 0d89375..0000000 --- a/CanvasToolLone/index.py +++ /dev/null @@ -1,417 +0,0 @@ -from flask import Flask, render_template,jsonify,request, send_from_directory -from urllib import parse -from urllib import request as rq -import webbrowser -import os,base64,io, time, random -from PIL import Image, ImageFilter, ImageOps -try: - from signal import SIGKILL -except: - from signal import SIGABRT -import json - -def stopprocess(): - pid = os.getpid() - print(pid) - try: - os.kill(int(pid), SIGKILL) - except: - os.kill(int(pid), SIGABRT) - return "none" - -import argparse -import numpy as np -parser = argparse.ArgumentParser() -parser.add_argument("-s","--same") -parser.add_argument("-p","--path") -args = parser.parse_args() - - -app = Flask(__name__) -data = { - "lastimage":"", - "done":"n" -} -json_object = json.dumps(data, indent=4) -with open("./lastimage.json", "w") as outfile: - outfile.write(json_object) -image = "" -if args.same == "yes": - with open("./lastimage.json","r") as filename: - image = Image.open(json.load(filename)["lastimage"]) - - w = str(int(float(image.size[0]))) - h = str(int(float(image.size[1]))) - -try: - with open("./data.json","r") as filename: - bs = str(json.load(filename)["savedata"]["boxsz"]) - pixels = json.load(filename)["savedata"]["pxlsarray"] - if pixels != "": - for i in range(0,len(pixels)): - for j in range(0,len(pixels[i])): - pixels[i][j] = tuple(pixels[i][j]) - - - array = np.array(pixels, dtype=np.uint8) - image = Image.fromarray(array) - new_image.save('erased.png') -except: - pass -bs = "256" -if args.same == "yes": - buf = io.BytesIO() - image.save(buf, format='PNG') - byte_im = buf.getvalue() - byte_im = base64.b64encode(byte_im).decode('utf-8') - byte_im = f"data:image/png;base64,{byte_im}" - -@app.route("/") -def index(): - if args.same == "yes": - return render_template('index.html',byte_im=byte_im,w=w,h=h,bs=bs) - else: - return render_template('index.html',byte_im="",w="",h="",bs=bs) - - -@app.route('/favicon.ico') -def favicon(): - return send_from_directory(os.path.join(app.root_path, 'static'), - 'favicon.ico', mimetype='image/vnd.microsoft.icon') - -@app.route("/grabwfsmodels",methods=['GET', 'POST','DELETE']) -def grabwfsmodels(): - models = [i for i in os.listdir('../../../models/diffusers') if os.path.isdir(f"../../../models/diffusers/{i}")] - wfs = os.listdir('./workflows') - return{"models":models,"wfs":wfs} - -@app.route("/prepare",methods=['GET', 'POST','DELETE']) -def prep(): - return{"exist":args.same} - -@app.route("/generate",methods=['GET', 'POST','DELETE']) -def generate(): - wf = request.json["wf"] - model = request.json["model"] - def queue_prompt(prompt_workflow): - p = {"prompt": prompt_workflow} - data = json.dumps(p).encode('utf-8') - req = rq.Request("http://127.0.0.1:8188/prompt", data=data) - rq.urlopen(req) - prompt_workflow = json.load(open(f'./workflows/{wf}')) - for i in prompt_workflow: - if "seed" in prompt_workflow[i]['inputs']: - print(i) - prompt_workflow[i]['inputs']['seed'] = random.randint(0,10000000000) - if "model_name" in prompt_workflow[i]['inputs']: - print(i) - prompt_workflow[i]['inputs']['model_name'] = model - - queue_prompt(prompt_workflow) - return{} - - -@app.route("/savedata",methods=['GET', 'POST','DELETE']) -def savedata(): - global image - print("trigerred") - taesd = request.json["taesd"] - savedata = request.json["savedata"] - if taesd == "false": - #print(savedata) - ff = int(savedata["ff"]) - selectorsize = request.json["selectorsize"] - pixels = savedata["pxlsarray"] - if pixels != "": - for i in range(0,len(pixels)): - for j in range(0,len(pixels[i])): - pixels[i][j] = tuple(pixels[i][j]) - - - array = np.array(pixels, dtype=np.uint8) - image = Image.fromarray(array) - image.save('erased.png') - image.save("out.png") - left = int(float(savedata["crpdims"]["left"])) - top = int(float(savedata["crpdims"]["top"])) - right = int(float(savedata["crpdims"]["right"])) - bottom = int(float(savedata["crpdims"]["bottom"])) - croped = image.crop((left,top,right,bottom)) - try: - left = int(float(savedata["crpdimsref"]["left"])) - top = int(float(savedata["crpdimsref"]["top"])) - right = int(float(savedata["crpdimsref"]["right"])) - bottom = int(float(savedata["crpdimsref"]["bottom"])) - ref = image.crop((left,top,right,bottom)) - except: - ref = image - ref.save("reference.png") - croped2 = croped.copy() - px = croped2.load() - for i in range(0,croped2.size[0]): - for j in range(0,croped2.size[1]): - try: - if px[i,j][3] <255: - px[i,j] = (255,255,255,255) - else: - px[i,j] = (0,0,0,255) - except: - px[i,j] = (0,0,0) - selectorsize = int(selectorsize) - bg = Image.new("RGB",(selectorsize,selectorsize),(0,0,0)) - bg2 = Image.new("RGB",(selectorsize,selectorsize),(255,255,255)) - add = (int(float(savedata["additionaldims"]["left"])),int(float(savedata["additionaldims"]["top"])),int(float(selectorsize-savedata["additionaldims"]["right"])),int(float(selectorsize-savedata["additionaldims"]["bottom"]))) - bg.paste(croped,(add)) - bg2.paste(croped2,(add)) - - - - ########################### - toparr = [] - leftarr = [] - rightarr = [] - bottomarr = [] - - topleftarr = [] - toprightarr = [] - bottomleftarr = [] - bottomrightarr = [] - whitepix = 0 - px = bg2.load() - for i in range(0,bg2.size[0]): - for j in range(0,bg2.size[1]): - if px[i,j][0] == 255: - whitepix+=1 - try: - if px[i,j][0] == 255 and 00: - lft = int(savedata["additionaldims"]["left"]) - - if savedata["additionaldims"]["top"]>0: - tp = int(savedata["additionaldims"]["top"]) - new.paste(bg,(lft,tp)) - lft = int(savedata["crpdims"]["left"]) - tp = int(savedata["crpdims"]["top"]) - new.paste(image,(lft,tp)) - image = new - taesds = "no" - except: - image = Image.open("out.png") - taesds = "yes" - try: - width = image.size[0] - height = image.size[1] - buf = io.BytesIO() - image.save(buf, format='PNG') - byte_im = buf.getvalue() - byte_im = base64.b64encode(byte_im).decode('utf-8') - byte_im = f"data:image/png;base64,{byte_im}" - except: - byte_im = "" - width = "" - height = "" - #time.sleep(0.1) - return {"img":byte_im,"width":width,"height":height,"data":savedata,"flag":str(realflag),"taesd":taesds} - -@app.route("/refresh",methods=['GET', 'POST','DELETE']) -def refresh(): - flag = False - with open("./lastimage.json","r") as filename: - status = json.load(filename)["done"] - if status == "y": - flag = True - print("done!!!") - else: - print("reading....") - if flag: - with open("./lastimage.json","r") as filename: - image = Image.open(json.load(filename)["lastimage"]) - data = { - "lastimage":"", - "done":"n" - } - json_object = json.dumps(data, indent=4) - with open("./lastimage.json", "w") as outfile: - outfile.write(json_object) - try: - os.remove("./taesd.png") - except: - pass - else: - try: - image = Image.open("./taesd.png") - except: - image = "" - try: - width = image.size[0] - height = image.size[1] - buf = io.BytesIO() - image.save(buf, format='PNG') - byte_im = buf.getvalue() - byte_im = base64.b64encode(byte_im).decode('utf-8') - byte_im = f"data:image/png;base64,{byte_im}" - except: - byte_im = "" - width = "" - height = "" - time.sleep(0.1) - return {"img":byte_im,"width":width,"height":height,"data":savedata,"flag":str(flag)} - -if __name__ == "__main__": - webbrowser.open("http://localhost:5000") - app.run(debug=False) diff --git a/CanvasToolLone/lastimage.json b/CanvasToolLone/lastimage.json deleted file mode 100644 index 15c015a..0000000 --- a/CanvasToolLone/lastimage.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "lastimage": "", - "done": "n" -} \ No newline at end of file diff --git a/CanvasToolLone/server.py b/CanvasToolLone/server.py deleted file mode 100644 index c84c640..0000000 --- a/CanvasToolLone/server.py +++ /dev/null @@ -1,653 +0,0 @@ -import os -import sys -import asyncio -import traceback - -import nodes -import folder_paths -import execution -import uuid -import urllib -import json -import glob -import struct -from PIL import Image, ImageOps -from PIL.PngImagePlugin import PngInfo -from io import BytesIO - -try: - import aiohttp - from aiohttp import web -except ImportError: - print("Module 'aiohttp' not installed. Please install it via:") - print("pip install aiohttp") - print("or") - print("pip install -r requirements.txt") - sys.exit() - -import mimetypes -from comfy.cli_args import args -import comfy.utils -import comfy.model_management -import subprocess - - -class BinaryEventTypes: - PREVIEW_IMAGE = 1 - UNENCODED_PREVIEW_IMAGE = 2 - -async def send_socket_catch_exception(function, message): - try: - await function(message) - except (aiohttp.ClientError, aiohttp.ClientPayloadError, ConnectionResetError) as err: - print("send error:", err) - -@web.middleware -async def cache_control(request: web.Request, handler): - response: web.Response = await handler(request) - if request.path.endswith('.js') or request.path.endswith('.css'): - response.headers.setdefault('Cache-Control', 'no-cache') - return response - -def create_cors_middleware(allowed_origin: str): - @web.middleware - async def cors_middleware(request: web.Request, handler): - if request.method == "OPTIONS": - # Pre-flight request. Reply successfully: - response = web.Response() - else: - response = await handler(request) - - response.headers['Access-Control-Allow-Origin'] = allowed_origin - response.headers['Access-Control-Allow-Methods'] = 'POST, GET, DELETE, PUT, OPTIONS' - response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization' - response.headers['Access-Control-Allow-Credentials'] = 'true' - return response - - return cors_middleware - -class PromptServer(): - def __init__(self, loop): - PromptServer.instance = self - - mimetypes.init() - mimetypes.types_map['.js'] = 'application/javascript; charset=utf-8' - - self.supports = ["custom_nodes_from_web"] - self.prompt_queue = None - self.loop = loop - self.messages = asyncio.Queue() - self.number = 0 - - middlewares = [cache_control] - if args.enable_cors_header: - middlewares.append(create_cors_middleware(args.enable_cors_header)) - - self.app = web.Application(client_max_size=104857600, middlewares=middlewares) - self.sockets = dict() - self.web_root = os.path.join(os.path.dirname( - os.path.realpath(__file__)), "web") - routes = web.RouteTableDef() - self.routes = routes - self.last_node_id = None - self.client_id = None - - self.on_prompt_handlers = [] - - @routes.get('/ws') - async def websocket_handler(request): - ws = web.WebSocketResponse() - await ws.prepare(request) - sid = request.rel_url.query.get('clientId', '') - if sid: - # Reusing existing session, remove old - self.sockets.pop(sid, None) - else: - sid = uuid.uuid4().hex - - self.sockets[sid] = ws - - try: - # Send initial state to the new client - await self.send("status", { "status": self.get_queue_info(), 'sid': sid }, sid) - # On reconnect if we are the currently executing client send the current node - if self.client_id == sid and self.last_node_id is not None: - await self.send("executing", { "node": self.last_node_id }, sid) - - async for msg in ws: - if msg.type == aiohttp.WSMsgType.ERROR: - print('ws connection closed with exception %s' % ws.exception()) - finally: - self.sockets.pop(sid, None) - return ws - - @routes.get("/") - async def get_root(request): - return web.FileResponse(os.path.join(self.web_root, "index.html")) - - - @routes.post("/canvas") - async def get_canvas(request): - try: - subprocess.run(["python", "index.py","--same","no","--path",folder_paths.get_folder_paths("custom_nodes")[0]+'/LCM_Inpaint-Outpaint_Comfy/CanvasTool'], cwd=folder_paths.get_folder_paths("custom_nodes")[0]+'/LCM_Inpaint-Outpaint_Comfy/CanvasTool') - except: - subprocess.run(["python", "index.py","--same","no","--path",folder_paths.get_folder_paths("custom_nodes")[0]+'\LCM_Inpaint-Outpaint_Comfy\CanvasTool'], cwd=folder_paths.get_folder_paths("custom_nodes")[0]+'\LCM_Inpaint-Outpaint_Comfy\CanvasTool',shell=true) - return web.FileResponse(os.path.join(self.web_root, "index.html")) - - @routes.post("/canvassame") - async def get_canvas_same(request): - try: - subprocess.run(["python", "index.py","--same","yes","--path",folder_paths.get_folder_paths("custom_nodes")[0]+'/LCM_Inpaint-Outpaint_Comfy/CanvasTool'], cwd=folder_paths.get_folder_paths("custom_nodes")[0]+'/LCM_Inpaint-Outpaint_Comfy/CanvasTool') - except: - subprocess.run(["python", "index.py","--same","yes","--path",folder_paths.get_folder_paths("custom_nodes")[0]+'\LCM_Inpaint-Outpaint_Comfy\CanvasTool'], cwd=folder_paths.get_folder_paths("custom_nodes")[0]+'\LCM_Inpaint-Outpaint_Comfy\CanvasTool',shell=true) - return web.FileResponse(os.path.join(self.web_root, "index.html")) - - - @routes.get("/embeddings") - def get_embeddings(self): - embeddings = folder_paths.get_filename_list("embeddings") - return web.json_response(list(map(lambda a: os.path.splitext(a)[0], embeddings))) - - @routes.get("/extensions") - async def get_extensions(request): - files = glob.glob(os.path.join( - glob.escape(self.web_root), 'extensions/**/*.js'), recursive=True) - - extensions = list(map(lambda f: "/" + os.path.relpath(f, self.web_root).replace("\\", "/"), files)) - - for name, dir in nodes.EXTENSION_WEB_DIRS.items(): - files = glob.glob(os.path.join(glob.escape(dir), '**/*.js'), recursive=True) - extensions.extend(list(map(lambda f: "/extensions/" + urllib.parse.quote( - name) + "/" + os.path.relpath(f, dir).replace("\\", "/"), files))) - - return web.json_response(extensions) - - def get_dir_by_type(dir_type): - if dir_type is None: - dir_type = "input" - - if dir_type == "input": - type_dir = folder_paths.get_input_directory() - elif dir_type == "temp": - type_dir = folder_paths.get_temp_directory() - elif dir_type == "output": - type_dir = folder_paths.get_output_directory() - - return type_dir, dir_type - - def image_upload(post, image_save_function=None): - image = post.get("image") - overwrite = post.get("overwrite") - - image_upload_type = post.get("type") - upload_dir, image_upload_type = get_dir_by_type(image_upload_type) - - if image and image.file: - filename = image.filename - if not filename: - return web.Response(status=400) - - subfolder = post.get("subfolder", "") - full_output_folder = os.path.join(upload_dir, os.path.normpath(subfolder)) - filepath = os.path.abspath(os.path.join(full_output_folder, filename)) - - if os.path.commonpath((upload_dir, filepath)) != upload_dir: - return web.Response(status=400) - - if not os.path.exists(full_output_folder): - os.makedirs(full_output_folder) - - split = os.path.splitext(filename) - - if overwrite is not None and (overwrite == "true" or overwrite == "1"): - pass - else: - i = 1 - while os.path.exists(filepath): - filename = f"{split[0]} ({i}){split[1]}" - filepath = os.path.join(full_output_folder, filename) - i += 1 - - if image_save_function is not None: - image_save_function(image, post, filepath) - else: - with open(filepath, "wb") as f: - f.write(image.file.read()) - - return web.json_response({"name" : filename, "subfolder": subfolder, "type": image_upload_type}) - else: - return web.Response(status=400) - - @routes.post("/upload/image") - async def upload_image(request): - post = await request.post() - return image_upload(post) - - - @routes.post("/upload/mask") - async def upload_mask(request): - post = await request.post() - - def image_save_function(image, post, filepath): - original_ref = json.loads(post.get("original_ref")) - filename, output_dir = folder_paths.annotated_filepath(original_ref['filename']) - - # validation for security: prevent accessing arbitrary path - if filename[0] == '/' or '..' in filename: - return web.Response(status=400) - - if output_dir is None: - type = original_ref.get("type", "output") - output_dir = folder_paths.get_directory_by_type(type) - - if output_dir is None: - return web.Response(status=400) - - if original_ref.get("subfolder", "") != "": - full_output_dir = os.path.join(output_dir, original_ref["subfolder"]) - if os.path.commonpath((os.path.abspath(full_output_dir), output_dir)) != output_dir: - return web.Response(status=403) - output_dir = full_output_dir - - file = os.path.join(output_dir, filename) - - if os.path.isfile(file): - with Image.open(file) as original_pil: - metadata = PngInfo() - if hasattr(original_pil,'text'): - for key in original_pil.text: - metadata.add_text(key, original_pil.text[key]) - original_pil = original_pil.convert('RGBA') - mask_pil = Image.open(image.file).convert('RGBA') - - # alpha copy - new_alpha = mask_pil.getchannel('A') - original_pil.putalpha(new_alpha) - original_pil.save(filepath, compress_level=4, pnginfo=metadata) - - return image_upload(post, image_save_function) - - @routes.get("/view") - async def view_image(request): - if "filename" in request.rel_url.query: - filename = request.rel_url.query["filename"] - filename,output_dir = folder_paths.annotated_filepath(filename) - - # validation for security: prevent accessing arbitrary path - if filename[0] == '/' or '..' in filename: - return web.Response(status=400) - - if output_dir is None: - type = request.rel_url.query.get("type", "output") - output_dir = folder_paths.get_directory_by_type(type) - - if output_dir is None: - return web.Response(status=400) - - if "subfolder" in request.rel_url.query: - full_output_dir = os.path.join(output_dir, request.rel_url.query["subfolder"]) - if os.path.commonpath((os.path.abspath(full_output_dir), output_dir)) != output_dir: - return web.Response(status=403) - output_dir = full_output_dir - - filename = os.path.basename(filename) - file = os.path.join(output_dir, filename) - - if os.path.isfile(file): - if 'preview' in request.rel_url.query: - with Image.open(file) as img: - preview_info = request.rel_url.query['preview'].split(';') - image_format = preview_info[0] - if image_format not in ['webp', 'jpeg'] or 'a' in request.rel_url.query.get('channel', ''): - image_format = 'webp' - - quality = 90 - if preview_info[-1].isdigit(): - quality = int(preview_info[-1]) - - buffer = BytesIO() - if image_format in ['jpeg'] or request.rel_url.query.get('channel', '') == 'rgb': - img = img.convert("RGB") - img.save(buffer, format=image_format, quality=quality) - buffer.seek(0) - - return web.Response(body=buffer.read(), content_type=f'image/{image_format}', - headers={"Content-Disposition": f"filename=\"{filename}\""}) - - if 'channel' not in request.rel_url.query: - channel = 'rgba' - else: - channel = request.rel_url.query["channel"] - - if channel == 'rgb': - with Image.open(file) as img: - if img.mode == "RGBA": - r, g, b, a = img.split() - new_img = Image.merge('RGB', (r, g, b)) - else: - new_img = img.convert("RGB") - - buffer = BytesIO() - new_img.save(buffer, format='PNG') - buffer.seek(0) - - return web.Response(body=buffer.read(), content_type='image/png', - headers={"Content-Disposition": f"filename=\"{filename}\""}) - - elif channel == 'a': - with Image.open(file) as img: - if img.mode == "RGBA": - _, _, _, a = img.split() - else: - a = Image.new('L', img.size, 255) - - # alpha img - alpha_img = Image.new('RGBA', img.size) - alpha_img.putalpha(a) - alpha_buffer = BytesIO() - alpha_img.save(alpha_buffer, format='PNG') - alpha_buffer.seek(0) - - return web.Response(body=alpha_buffer.read(), content_type='image/png', - headers={"Content-Disposition": f"filename=\"{filename}\""}) - else: - return web.FileResponse(file, headers={"Content-Disposition": f"filename=\"{filename}\""}) - - return web.Response(status=404) - - @routes.get("/view_metadata/{folder_name}") - async def view_metadata(request): - folder_name = request.match_info.get("folder_name", None) - if folder_name is None: - return web.Response(status=404) - if not "filename" in request.rel_url.query: - return web.Response(status=404) - - filename = request.rel_url.query["filename"] - if not filename.endswith(".safetensors"): - return web.Response(status=404) - - safetensors_path = folder_paths.get_full_path(folder_name, filename) - if safetensors_path is None: - return web.Response(status=404) - out = comfy.utils.safetensors_header(safetensors_path, max_size=1024*1024) - if out is None: - return web.Response(status=404) - dt = json.loads(out) - if not "__metadata__" in dt: - return web.Response(status=404) - return web.json_response(dt["__metadata__"]) - - @routes.get("/system_stats") - async def get_queue(request): - device = comfy.model_management.get_torch_device() - device_name = comfy.model_management.get_torch_device_name(device) - vram_total, torch_vram_total = comfy.model_management.get_total_memory(device, torch_total_too=True) - vram_free, torch_vram_free = comfy.model_management.get_free_memory(device, torch_free_too=True) - system_stats = { - "system": { - "os": os.name, - "python_version": sys.version, - "embedded_python": os.path.split(os.path.split(sys.executable)[0])[1] == "python_embeded" - }, - "devices": [ - { - "name": device_name, - "type": device.type, - "index": device.index, - "vram_total": vram_total, - "vram_free": vram_free, - "torch_vram_total": torch_vram_total, - "torch_vram_free": torch_vram_free, - } - ] - } - return web.json_response(system_stats) - - @routes.get("/prompt") - async def get_prompt(request): - return web.json_response(self.get_queue_info()) - - def node_info(node_class): - obj_class = nodes.NODE_CLASS_MAPPINGS[node_class] - info = {} - info['input'] = obj_class.INPUT_TYPES() - info['output'] = obj_class.RETURN_TYPES - info['output_is_list'] = obj_class.OUTPUT_IS_LIST if hasattr(obj_class, 'OUTPUT_IS_LIST') else [False] * len(obj_class.RETURN_TYPES) - info['output_name'] = obj_class.RETURN_NAMES if hasattr(obj_class, 'RETURN_NAMES') else info['output'] - info['name'] = node_class - info['display_name'] = nodes.NODE_DISPLAY_NAME_MAPPINGS[node_class] if node_class in nodes.NODE_DISPLAY_NAME_MAPPINGS.keys() else node_class - info['description'] = obj_class.DESCRIPTION if hasattr(obj_class,'DESCRIPTION') else '' - info['category'] = 'sd' - if hasattr(obj_class, 'OUTPUT_NODE') and obj_class.OUTPUT_NODE == True: - info['output_node'] = True - else: - info['output_node'] = False - - if hasattr(obj_class, 'CATEGORY'): - info['category'] = obj_class.CATEGORY - return info - - @routes.get("/object_info") - async def get_object_info(request): - out = {} - for x in nodes.NODE_CLASS_MAPPINGS: - try: - out[x] = node_info(x) - except Exception as e: - print(f"[ERROR] An error occurred while retrieving information for the '{x}' node.", file=sys.stderr) - traceback.print_exc() - return web.json_response(out) - - @routes.get("/object_info/{node_class}") - async def get_object_info_node(request): - node_class = request.match_info.get("node_class", None) - out = {} - if (node_class is not None) and (node_class in nodes.NODE_CLASS_MAPPINGS): - out[node_class] = node_info(node_class) - return web.json_response(out) - - @routes.get("/history") - async def get_history(request): - return web.json_response(self.prompt_queue.get_history()) - - @routes.get("/history/{prompt_id}") - async def get_history(request): - prompt_id = request.match_info.get("prompt_id", None) - return web.json_response(self.prompt_queue.get_history(prompt_id=prompt_id)) - - @routes.get("/queue") - async def get_queue(request): - queue_info = {} - current_queue = self.prompt_queue.get_current_queue() - queue_info['queue_running'] = current_queue[0] - queue_info['queue_pending'] = current_queue[1] - return web.json_response(queue_info) - - @routes.post("/prompt") - async def post_prompt(request): - print("got prompt") - resp_code = 200 - out_string = "" - json_data = await request.json() - json_data = self.trigger_on_prompt(json_data) - - if "number" in json_data: - number = float(json_data['number']) - else: - number = self.number - if "front" in json_data: - if json_data['front']: - number = -number - - self.number += 1 - - if "prompt" in json_data: - prompt = json_data["prompt"] - valid = execution.validate_prompt(prompt) - extra_data = {} - if "extra_data" in json_data: - extra_data = json_data["extra_data"] - - if "client_id" in json_data: - extra_data["client_id"] = json_data["client_id"] - if valid[0]: - prompt_id = str(uuid.uuid4()) - outputs_to_execute = valid[2] - self.prompt_queue.put((number, prompt_id, prompt, extra_data, outputs_to_execute)) - response = {"prompt_id": prompt_id, "number": number, "node_errors": valid[3]} - return web.json_response(response) - else: - print("invalid prompt:", valid[1]) - return web.json_response({"error": valid[1], "node_errors": valid[3]}, status=400) - else: - return web.json_response({"error": "no prompt", "node_errors": []}, status=400) - - @routes.post("/queue") - async def post_queue(request): - json_data = await request.json() - if "clear" in json_data: - if json_data["clear"]: - self.prompt_queue.wipe_queue() - if "delete" in json_data: - to_delete = json_data['delete'] - for id_to_delete in to_delete: - delete_func = lambda a: a[1] == id_to_delete - self.prompt_queue.delete_queue_item(delete_func) - - return web.Response(status=200) - - @routes.post("/interrupt") - async def post_interrupt(request): - nodes.interrupt_processing() - return web.Response(status=200) - - @routes.post("/history") - async def post_history(request): - json_data = await request.json() - if "clear" in json_data: - if json_data["clear"]: - self.prompt_queue.wipe_history() - if "delete" in json_data: - to_delete = json_data['delete'] - for id_to_delete in to_delete: - self.prompt_queue.delete_history_item(id_to_delete) - - return web.Response(status=200) - - def add_routes(self): - self.app.add_routes(self.routes) - - for name, dir in nodes.EXTENSION_WEB_DIRS.items(): - self.app.add_routes([ - web.static('/extensions/' + urllib.parse.quote(name), dir, follow_symlinks=True), - ]) - - self.app.add_routes([ - web.static('/', self.web_root, follow_symlinks=True), - ]) - - def get_queue_info(self): - prompt_info = {} - exec_info = {} - exec_info['queue_remaining'] = self.prompt_queue.get_tasks_remaining() - prompt_info['exec_info'] = exec_info - return prompt_info - - async def send(self, event, data, sid=None): - if event == BinaryEventTypes.UNENCODED_PREVIEW_IMAGE: - await self.send_image(data, sid=sid) - elif isinstance(data, (bytes, bytearray)): - await self.send_bytes(event, data, sid) - else: - await self.send_json(event, data, sid) - - def encode_bytes(self, event, data): - if not isinstance(event, int): - raise RuntimeError(f"Binary event types must be integers, got {event}") - - packed = struct.pack(">I", event) - message = bytearray(packed) - message.extend(data) - return message - - async def send_image(self, image_data, sid=None): - image_type = image_data[0] - image = image_data[1] - max_size = image_data[2] - if max_size is not None: - if hasattr(Image, 'Resampling'): - resampling = Image.Resampling.BILINEAR - else: - resampling = Image.ANTIALIAS - - image = ImageOps.contain(image, (max_size, max_size), resampling) - type_num = 1 - if image_type == "JPEG": - type_num = 1 - elif image_type == "PNG": - type_num = 2 - - bytesIO = BytesIO() - header = struct.pack(">I", type_num) - bytesIO.write(header) - image.save(bytesIO, format=image_type, quality=95, compress_level=4) - preview_bytes = bytesIO.getvalue() - await self.send_bytes(BinaryEventTypes.PREVIEW_IMAGE, preview_bytes, sid=sid) - - async def send_bytes(self, event, data, sid=None): - message = self.encode_bytes(event, data) - - if sid is None: - for ws in self.sockets.values(): - await send_socket_catch_exception(ws.send_bytes, message) - elif sid in self.sockets: - await send_socket_catch_exception(self.sockets[sid].send_bytes, message) - - async def send_json(self, event, data, sid=None): - message = {"type": event, "data": data} - - if sid is None: - for ws in self.sockets.values(): - await send_socket_catch_exception(ws.send_json, message) - elif sid in self.sockets: - await send_socket_catch_exception(self.sockets[sid].send_json, message) - - def send_sync(self, event, data, sid=None): - self.loop.call_soon_threadsafe( - self.messages.put_nowait, (event, data, sid)) - - def queue_updated(self): - self.send_sync("status", { "status": self.get_queue_info() }) - - async def publish_loop(self): - while True: - msg = await self.messages.get() - await self.send(*msg) - - async def start(self, address, port, verbose=True, call_on_start=None): - runner = web.AppRunner(self.app, access_log=None) - await runner.setup() - site = web.TCPSite(runner, address, port) - await site.start() - - if address == '': - address = '0.0.0.0' - if verbose: - print("Starting server\n") - print("To see the GUI go to: http://{}:{}".format(address, port)) - if call_on_start is not None: - call_on_start(address, port) - - def add_on_prompt_handler(self, handler): - self.on_prompt_handlers.append(handler) - - def trigger_on_prompt(self, json_data): - for handler in self.on_prompt_handlers: - try: - json_data = handler(json_data) - except Exception as e: - print(f"[ERROR] An error occurred during the on_prompt_handler processing") - traceback.print_exc() - - return json_data diff --git a/CanvasToolLone/setup.py b/CanvasToolLone/setup.py deleted file mode 100644 index eeedfe7..0000000 --- a/CanvasToolLone/setup.py +++ /dev/null @@ -1,4 +0,0 @@ -import shutil - -shutil.copyfile('server.py', '../../../server.py') -shutil.copyfile('index.html', '../../../web/index.html') \ No newline at end of file diff --git a/CanvasToolLone/static/faviicon.ico b/CanvasToolLone/static/faviicon.ico deleted file mode 100644 index 38f871f..0000000 Binary files a/CanvasToolLone/static/faviicon.ico and /dev/null differ diff --git a/CanvasToolLone/static/index.css b/CanvasToolLone/static/index.css deleted file mode 100644 index d8f72f1..0000000 --- a/CanvasToolLone/static/index.css +++ /dev/null @@ -1,409 +0,0 @@ -html{ - background: linear-gradient(to top,rgb(29, 29, 29) 80%, rgb(5, 5, 5)); - background-attachment: fixed; - background-repeat: no-repeat; -} - -#settings,#settings2{ - width: 100%; - height: 10%; - background: linear-gradient(to bottom,rgb(44, 44, 44) 80%, rgb(36, 36, 36),transparent); - position: absolute; - top: 0%; - left: 0%; -} -#moveimg{ - position: absolute; - top: 30%; - left: 5%; - width: 10%; - height: 50%; - background-color: gray; - transform: translate(-50%,-50%); - font-weight: bolder; - font-family: Verdana, Geneva, Tahoma, sans-serif; - text-align: center; - cursor: pointer; -} -#setref,#undo{ - position: absolute; - top: 65%; - left: 5%; - width: 10%; - height: 50%; - background-color: gray; - transform: translate(-50%,-50%); - font-weight: bolder; - font-family: Verdana, Geneva, Tahoma, sans-serif; - text-align: center; - cursor: pointer; -} -#undo{ - left: 14%; -} -#resetimg{ - position: absolute; - top: 50%; - left: 83%; - width: 10%; - height: 50%; - background-color: gray; - transform: translate(-50%,-50%); - font-weight: bolder; - font-family: Verdana, Geneva, Tahoma, sans-serif; - text-align: center; - cursor: pointer; -} -#eraseon{ - position: absolute; - top: 30%; - left: 14%; - width: 10%; - height: 50%; - background-color: gray; - transform: translate(-50%,-50%); - font-weight: bolder; - font-family: Verdana, Geneva, Tahoma, sans-serif; - text-align: center; - cursor: pointer; -} -#drawon{ - position: absolute; - top: 30%; - left: 23%; - width: 10%; - height: 50%; - background-color: gray; - transform: translate(-50%,-50%); - font-weight: bolder; - font-family: Verdana, Geneva, Tahoma, sans-serif; - text-align: center; - cursor: pointer; -} - -#selectorsize{ - position: absolute; - left: 39%; - top: 45%; -} - -body{ - color: white; -} -.txt{ - width: 100%; - position: absolute; - top: 25%; - left: 50%; - transform: translate(-50%,-50%); -} -#container{ - width: 100%; - height: 100%; -} -#saveexit{ - position: absolute; - top: 50%; - left: 92%; - width: 10%; - height: 50%; - background-color: gray; - transform: translate(-50%,-50%); - font-weight: bolder; - font-family: Verdana, Geneva, Tahoma, sans-serif; - text-align: center; - visibility: hidden; - cursor: pointer; -} -#msg{ - position: absolute; - width: 90%; - height: 90%; - top: 50%; - left: 50%; - transform: translate(-50%,-50%); - visibility: hidden; - font-size: 50px; - background-color: gray; -} - -#saveexit:hover{ - background-color: rgb(20, 20, 20); -} - - -#moveimg:hover{ - background-color: rgb(20, 20, 20); -} -#eraseon:hover{ - background-color: rgb(20, 20, 20); -} -#drawon:hover{ - background-color: rgb(20, 20, 20); -} - -input{ - background-color: rgb(20, 20, 20); - border-radius: 5%; - outline: none; - caret-color: transparent; - color: white; - font-family: Verdana, Geneva, Tahoma, sans-serif; - border: 1px solid transparent; - text-align: center; -} -p{ - font-family: Verdana, Geneva, Tahoma, sans-serif; -} -#erasersize{ - position: absolute; - left: 61%; - top: 45%; -} -#ff{ - position: absolute; - left: 49%; - top: 45%; -} -#clr{ - position: absolute; - left: 30%; - top: 40%; -} -#inprange{ - position: absolute; - left: 30%; - top: 73%; - color: grey; -} -#source,#sourceunder{ - position: fixed; - left: 0px; - top: 0px; - -} - -#selector{ - width: 256px; - height: 256px; - background-color: transparent; - left: 0px; - top: 0px; - position: fixed; - border: 2px solid green; - transform: translate(-50%,-50%); -} -label{ - position: fixed; - top: 0%; - left: 0%; - width: 100%; - height: 100%; - - -} -#openimg{ - position: fixed; - top: 0%; - left: 0%; - width: 100%; - height: 100%; - opacity: 0; -} -label p{ - width: 100%; - height: 100%; - position: absolute; - top: 50%; - transform: translateY(-15%); - font-size: 500%; - text-align: center; - - -} - -#uploadcontainer{ - width: 100%; - height: 100%; - position: fixed; - top: 0%; - opacity: 0; - background: linear-gradient(to bottom,black,rgb(20,20,20),black); - left: 0%; - -} -#sourceimg{ - display: none; -} - -#lockbox{ - position: absolute; - top: 61%; - left: 73.1%; - width: 10%; - height: 28%; - background-color: gray; - transform: translate(-50%,-50%); - font-weight: bolder; - font-family: Verdana, Geneva, Tahoma, sans-serif; - text-align: center; - cursor: pointer; -} -#lockbox p{ - font-size: 15px; - top: 0%; -} - -#lockbox:hover{ - background-color: rgb(20, 20, 20); -} -#locktop, #lockleft, #lockright, #lockbottom{ - position: absolute; - top: 40%; - width: 2.5%; - height: 30%; - background-color: gray; - transform: translate(-50%,-50%); - font-weight: bolder; - font-family: Verdana, Geneva, Tahoma, sans-serif; - text-align: center; - cursor: pointer; - font-size: 10px; - text-align: center; -} -#locktop{ - left: 69.35%; -} -#lockleft{ - left: 71.85% -} -#lockright{ - left: 74.33%; -} -#lockbottom{ - left: 76.8%; -} -#moveimg2{ - position: absolute; - top: 50%; - left: 15%; - width: 10%; - height: 50%; - background-color: gray; - transform: translate(-50%,-50%); - font-weight: bolder; - font-family: Verdana, Geneva, Tahoma, sans-serif; - text-align: center; - cursor: pointer; -} -#moveimg2:hover{ - background-color: rgb(20, 20, 20); -} -#openimgadd{ - position: fixed; - top: 50%; - left: 90%; -} -#settings2{ - visibility: hidden; -} -.moveimgclass,#done,#moveimg1{ - position: absolute; - top: 50%; - width: 10%; - height: 50%; - background-color: gray; - transform: translate(-50%,-50%); - font-weight: bolder; - font-family: Verdana, Geneva, Tahoma, sans-serif; - text-align: center; - cursor: pointer; - z-index: 1; -} -.moveimgclass:hover{ - background-color: rgb(20, 20, 20); -} -#done{ - left: 95%; -} -#moveimg1{ - left: 5%; -} -#uploadanotherimg,#openimgadd{ - position: absolute; - width: 2%; - height: 40%; - top: 30%; - left: 65%; - -} -#uploadanotherimg{ - background-color: rgb(20, 20, 20); -} -#openimgadd{ - opacity: 0; -} -.icontxt{ - position: absolute; - top: -140%; - font-size: 50px; -} - - -.dropbtn { - background-color: transparent; - color: white; - padding: 16px; - font-size: 16px; - border: none; - cursor: pointer; - text-align: center; -} - -/* The container
- needed to position the dropdown content */ -.dropdown { - position: relative; - display: inline-block; - transform: translate(-50%,-30%); -} - -/* Dropdown Content (Hidden by Default) */ -.dropdown-content { - display: none; - position: absolute; - background-color: rgb(20,20,20); - min-width: 160px; - box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); - z-index: 3; - cursor: pointer; -} - -/* Links inside the dropdown */ -.dropdown-content a { - color: white; - padding: 12px 16px; - text-decoration: none; - display: block; -} - -/* Change color of dropdown links on hover */ -.dropdown-content a:hover {background-color: rgb(44, 44, 44)} - -/* Show the dropdown menu on hover */ -.dropdown:hover .dropdown-content { - display: block; -} - -/* Change the background color of the dropdown button when the dropdown content is shown */ -.dropdown:hover .dropbtn { - background-color: transparent; -} - -#wfsdropdown{ - left: 34%; - top: 5%; -} -#modelsdropdown{ - left: 38%; - top: 5%; -} \ No newline at end of file diff --git a/CanvasToolLone/static/index.js b/CanvasToolLone/static/index.js deleted file mode 100644 index e3741db..0000000 --- a/CanvasToolLone/static/index.js +++ /dev/null @@ -1,1283 +0,0 @@ -var mousex = 0; -var selmod = ""; -var selwf = ""; -var genflag = false; -var canvasflag = true; -var taesd = "false"; -var backup = { - "img":"", - "left":"", - "top":"", - "width":"", - "height":"" -} -var mousey = 0; -var lockflag = false; -var prevmousex = 0; -var prevmousey = 0; -var clickflag = false; -var moveimgenableflag = false; -var selectorsize = 256; -var crplft = 0; -var crptp = 0; -var crprght = 0; -var crpbtm = 0; -var eraseflag = false; -var drawenableflag = false; -var eraseenableflag = false; -var drawflag = false; -var ll = false; -var lr = false; -var lt = false; -var lb = false; -var setref = false; -var comporder = []; -var imagetomove = ""; -var savedata = { - "crpdimsref": { - "left":0, - "top": 0, - "right":0, - "bottom":0 - }, - "crpdims": { - "left":0, - "top": 0, - "right":0, - "bottom":0 - }, - "additionaldims": { - "left":0, - "top": 0, - "right":0, - "bottom":0 - }, - "boxsz":512, - "ff":10, - "pxlsarray":"" - - -}; - -var imagedims = { - "width":128, - "height":128 -}; - -function undoimg(){ - document.getElementById("sourceimg").width = backup["width"]; - document.getElementById("sourceimg").height =backup["height"]; - document.getElementById("source").width = backup["width"]; - document.getElementById("source").height = backup["height"]; - document.getElementById("source").style.left = backup["left"]; - document.getElementById("source").style.top = backup["top"]; - document.getElementById("sourceimg").src = backup["img"]; - img = new Image(); - img.onload = function() { - var canvas = document.getElementById("source"); - var ctx = canvas.getContext("2d"); - ctx.clearRect(0, 0, canvas.width, canvas.height); - var img = document.getElementById("sourceimg"); - ctx.drawImage(img, 0, 0); - imgData = ctx.getImageData(0, 0, canvas.width,canvas.height); - data = imgData.data; - pxls = []; - for (let i = 0; i < data.length; i += 4) { - var pixel = []; - pixel.push(data[i]); - pixel.push(data[i+1]); - pixel.push(data[i+2]); - pixel.push(data[i+3]); - pxls.push(pixel); - } - var pxlsarray = [[]]; - for(i = 0;icanvas.width-10){ - pxlsarray.push([]); - } - } - - } - savedata["pxlsarray"] = pxlsarray; - ctx.clearRect(0, 0, canvas.width, canvas.height); - ctx.drawImage(img, 0, 0); - } - img.src = backup["img"]; - savedata["crpdims"] = { - "left":0, - "top": 0, - "right":0, - "bottom":0 - }; - savedata["additionaldims"] = { - "left":0, - "top": 0, - "right":0, - "bottom":0 - }; - -} - - -window.onload = function(){ - document.getElementById("erasersize").value = 10; - document.getElementById("ff").value = 10; - document.getElementById("selectorsize").value = 256; - prepare(); - //copied from https://jsfiddle.net/4N6D9/1/ - document.getElementById("openimg").onchange =function(e) { - var file, img; - - - if ((file = this.files[0])) { - img = new Image(); - img.onload = function() { - document.getElementById("sourceimg").width = this.width; - document.getElementById("sourceimg").height = this.height; - document.getElementById("source").width = this.width; - document.getElementById("source").height = this.height; - var canvas = document.getElementById("source"); - var ctx = canvas.getContext("2d"); - ctx.clearRect(0, 0, canvas.width, canvas.height); - var img = document.getElementById("sourceimg"); - ctx.drawImage(img, 0, 0); - imgData = ctx.getImageData(0, 0, canvas.width,canvas.height); - data = imgData.data; - pxls = []; - for (let i = 0; i < data.length; i += 4) { - var pixel = []; - pixel.push(data[i]); - pixel.push(data[i+1]); - pixel.push(data[i+2]); - pixel.push(data[i+3]); - pxls.push(pixel); - } - var pxlsarray = [[]]; - for(i = 0;icanvas.width-10){ - pxlsarray.push([]); - } - } - - } - savedata["pxlsarray"] = pxlsarray; - console.log(savedata["pxlsarray"]); - }; - img.src = URL.createObjectURL(file); - document.getElementById("sourceimg").src = URL.createObjectURL(file); - document.getElementById("uploadcontainer").remove(); - - - - } - - - } - - document.getElementById("openimgadd").onchange =function(e) { - var file, img; - if ((file = this.files[0])) { - comporder = []; - document.getElementById("selector").style.visibility = "hidden"; - var num = (document.getElementById("canvascontainer").children.length /2)+1; - num = String(num); - document.getElementById("settings2").style.visibility = "visible"; - document.getElementById("openimgadd").remove(); - var newel = document.createElement("input"); - newel.id = "openimgadd"; - newel.type = "file"; - newel.onchange =function(e) { - var file, img; - if ((file = this.files[0])) { - comporder = []; - document.getElementById("selector").style.visibility = "hidden"; - var num = (document.getElementById("canvascontainer").children.length /2)+1; - num = String(num); - document.getElementById("settings2").style.visibility = "visible"; - var newel = document.createElement("div"); - newel.id = "moveimg"+num; - newel.addEventListener("click",moveimgenable); - newel.className = "moveimgclass txt"; - newel.style.left = 5+(num-1)*10+"%"; - var newelpar = document.createElement("p"); - newelpar.innerHTML = "Move Image "+num; - newelpar.className = "txt"; - newel.append(newelpar); - document.getElementById("settings2").append(newel); - newel = document.createElement("img"); - newel.id = "sourceimg"+num; - newel.style.display = "none"; - document.getElementById("canvascontainer").append(newel); - newel = document.createElement("canvas"); - newel.id = "source"+num; - newel.style.position = "fixed"; - document.getElementById("canvascontainer").append(newel); - img = new Image(); - img.onload = function() { - document.getElementById("sourceimg"+num).width = this.width; - document.getElementById("sourceimg"+num).height = this.height; - document.getElementById("source"+num).width = this.width; - document.getElementById("source"+num).height = this.height; - var canvas = document.getElementById("source"+num); - var ctx = canvas.getContext("2d"); - ctx.clearRect(0, 0, canvas.width, canvas.height); - var img = document.getElementById("sourceimg"+num); - ctx.drawImage(img, 0, 0); - imgData = ctx.getImageData(0, 0, canvas.width,canvas.height); - data = imgData.data; - pxls = []; - for (let i = 0; i < data.length; i += 4) { - var pixel = []; - pixel.push(data[i]); - pixel.push(data[i+1]); - pixel.push(data[i+2]); - pixel.push(data[i+3]); - pxls.push(pixel); - } - var pxlsarray = [[]]; - for(i = 0;icanvas.width-10){ - pxlsarray.push([]); - } - } - - } - }; - img.src = URL.createObjectURL(file); - document.getElementById("sourceimg"+num).src = URL.createObjectURL(file); - } - - } - document.getElementById("settings2").append(newel); - var newel = document.createElement("div"); - newel.id = "moveimg"+num; - newel.addEventListener("click",moveimgenable); - newel.className = "moveimgclass txt"; - newel.style.left = 5+(num-1)*10+"%"; - var newelpar = document.createElement("p"); - newelpar.innerHTML = "Move Image "+num; - newelpar.className = "txt"; - newel.append(newelpar); - document.getElementById("settings2").append(newel); - newel = document.createElement("img"); - newel.id = "sourceimg"+num; - newel.style.display = "none"; - document.getElementById("canvascontainer").append(newel); - newel = document.createElement("canvas"); - newel.id = "source"+num; - newel.style.position = "fixed"; - document.getElementById("canvascontainer").append(newel); - img = new Image(); - img.onload = function() { - document.getElementById("sourceimg"+num).width = this.width; - document.getElementById("sourceimg"+num).height = this.height; - document.getElementById("source"+num).width = this.width; - document.getElementById("source"+num).height = this.height; - var canvas = document.getElementById("source"+num); - var ctx = canvas.getContext("2d"); - ctx.clearRect(0, 0, canvas.width, canvas.height); - var img = document.getElementById("sourceimg"+num); - ctx.drawImage(img, 0, 0); - imgData = ctx.getImageData(0, 0, canvas.width,canvas.height); - data = imgData.data; - pxls = []; - for (let i = 0; i < data.length; i += 4) { - var pixel = []; - pixel.push(data[i]); - pixel.push(data[i+1]); - pixel.push(data[i+2]); - pixel.push(data[i+3]); - pxls.push(pixel); - } - var pxlsarray = [[]]; - for(i = 0;icanvas.width-10){ - pxlsarray.push([]); - } - } - - } - }; - img.src = URL.createObjectURL(file); - document.getElementById("sourceimg"+num).src = URL.createObjectURL(file); - } - - } - grabwfsmodels(); - -} - -function prepare(){ - fetch('http://localhost:5000/prepare' - ).then(function (response) { - responseClone = response.clone(); // 2 - return response.json(); - }) - .then(data => { - if(data["exist"]!="yes"){ - document.getElementById("sourceimg").src = ""; - document.getElementById("uploadcontainer").style.height = "100%"; - document.getElementById("uploadcontainer").style.visibility = "visible"; - document.getElementById("uploadcontainer").style.opacity = 1; - } - else{ - document.getElementById("uploadcontainer").style.visibility = "hidden"; - resetimg(); - } - }); -} - -function setreftoggle(){ - setref = !setref; - if(setref){ - document.getElementById("selector").style.border = "2px solid red"; - document.getElementById("setref").style.backgroundColor = "rgb(20,20,20)"; - document.getElementById("saveexit").style.visibility = "hidden"; - ll = true; - lr = true; - lt = true; - lb = true; - document.getElementById("lockleft").style.backgroundColor = "gray"; - document.getElementById("lockright").style.backgroundColor = "gray"; - document.getElementById("locktop").style.backgroundColor = "gray"; - document.getElementById("lockbottom").style.backgroundColor = "gray"; - document.getElementById("lockbox").style.backgroundColor = "rgb(20, 20, 20)"; - } - else{ - document.getElementById("selector").style.border = "2px solid green"; - document.getElementById("setref").style.backgroundColor = "gray"; - } -} -function resetimg(){ - var canvas = document.getElementById("source"); - var ctx = canvas.getContext("2d"); - ctx.clearRect(0, 0, canvas.width, canvas.height); - var img = document.getElementById("sourceimg"); - ctx.drawImage(img, 0, 0); -} - -function ffupdate(){ - savedata["ff"] = document.getElementById("ff").value; -} -function draw(){ - var c = document.getElementById("source"); - var ctx = c.getContext("2d"); - var erasersize = 30 - try{ - erasersize = parseInt(document.getElementById("erasersize").value); - } - catch(err){ - console.log(err); - } - if(eraseenableflag){ - - var imgData = ctx.getImageData(Math.floor(mousex)-parseInt(document.getElementById('source').getBoundingClientRect()["left"]), Math.floor(mousey)-parseInt(document.getElementById('source').getBoundingClientRect()["top"]), erasersize,erasersize); - var data = imgData.data; - var pxls = []; - for (let i = 0; i < data.length; i += 4) { - const avg = (data[i] + data[i + 1] + data[i + 2]) / 3; - data[i] = avg; // red - data[i + 1] = avg; // green - data[i + 2] = avg; // blue - data[i + 3] = 0; // alpha - } - ctx.putImageData(imgData, (Math.floor(mousex)-parseInt(document.getElementById('source').getBoundingClientRect()["left"]))-(erasersize/2), (Math.floor(mousey)-parseInt(document.getElementById('source').getBoundingClientRect()["top"]))-(erasersize/2)); - } - else if(drawenableflag){ - ctx.fillStyle = document.getElementById("clr").value+parseInt(document.getElementById("inprange").value).toString(16); - ctx.fillRect((Math.floor(mousex)-parseInt(document.getElementById('source').getBoundingClientRect()["left"]))-(erasersize/2), (Math.floor(mousey)-parseInt(document.getElementById('source').getBoundingClientRect()["top"]))-(erasersize/2),erasersize/2,erasersize/2); - - } - else{ - imgData = ctx.getImageData(0, 0, c.width,c.height); - data = imgData.data; - pxls = []; - for (let i = 0; i < data.length; i += 4) { - var pixel = []; - pixel.push(data[i]); - pixel.push(data[i+1]); - pixel.push(data[i+2]); - pixel.push(data[i+3]); - pxls.push(pixel); - } - var pxlsarray = [[]]; - for(i = 0;ic.width-10){ - pxlsarray.push([]); - } - } - - } - savedata["pxlsarray"] = pxlsarray; - } - - -} -function drawenable(){ - if(drawflag){ - drawenableflag = !drawenableflag; - } - else{ - eraseenableflag = !eraseenableflag; - } -} - - -function changesize(e){ - if(drawflag || eraseflag){ - if(e.deltaY < 0){ - document.getElementById("erasersize").value = parseInt(document.getElementById("erasersize").value) + 1; - } - else{ - if(parseInt(document.getElementById("erasersize").value)-1>0){ - document.getElementById("erasersize").value = parseInt(document.getElementById("erasersize").value) - 1; - } - } - } - else if(!moveimgenableflag){ - if(e.deltaY < 0){ - if(!lockflag){ - document.getElementById("selectorsize").value = parseInt(document.getElementById("selectorsize").value) + 64; - changeselectorsize(); - } - else if(lockflag && parseInt(document.getElementById("selectorsize").value)+64<= parseInt(document.getElementById("source").width) && parseInt(document.getElementById("selectorsize").value)+64<= parseInt(document.getElementById("source").height)){ - document.getElementById("selector").style.left = parseFloat(document.getElementById("source").style.left) + Math.floor(selectorsize/2)+"px"; - document.getElementById("selector").style.top = parseFloat(document.getElementById("source").style.top) + Math.floor(selectorsize/2)+"px"; - document.getElementById("selectorsize").value = parseInt(document.getElementById("selectorsize").value) + 64; - changeselectorsize(); - - } - } - else{ - if(parseInt(document.getElementById("selectorsize").value)-64>0){ - document.getElementById("selectorsize").value = parseInt(document.getElementById("selectorsize").value) - 64; - changeselectorsize(); - } - } - } -} - -function erasemodeon(){ - if(eraseflag){ - document.getElementById("selector").style.visibility = "visible"; - document.getElementById("moveimglistner").style.visibility = "visible"; - document.getElementById("eraseon").style.backgroundColor = "gray"; - eraseflag = !eraseflag - } - else{ - if(drawflag==false && moveimgenableflag==false){ - document.getElementById("selector").style.visibility = "hidden"; - document.getElementById("moveimglistner").style.visibility = "hidden"; - document.getElementById("eraseon").style.backgroundColor = "rgb(20, 20, 20)"; - eraseflag = !eraseflag - } - } -} - -function drawmodeon(){ - if(drawflag){ - document.getElementById("selector").style.visibility = "visible"; - document.getElementById("moveimglistner").style.visibility = "visible"; - document.getElementById("drawon").style.backgroundColor = "gray"; - drawflag = !drawflag - } - else{ - if(eraseflag==false && moveimgenableflag==false){ - document.getElementById("selector").style.visibility = "hidden"; - document.getElementById("moveimglistner").style.visibility = "hidden"; - document.getElementById("drawon").style.backgroundColor = "rgb(20, 20, 20)"; - drawflag = !drawflag - } - } -} - -function refresh(savedata){ - var responseClone; // 1 - fetch('http://localhost:5000/refresh', { - method: 'POST', - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({"savedata":savedata,"selectorsize":selectorsize}) - }) - .then(function (response) { - responseClone = response.clone(); // 2 - return response.json(); - }) - .then(data => { - document.getElementById("sourceimg").width = data["width"]; - document.getElementById("sourceimg").height =data["height"]; - document.getElementById("source").width = data["width"]; - document.getElementById("source").height = data["height"]; - document.getElementById("sourceimg").src = data["img"]; - img = new Image(); - img.onload = function() { - - var canvas = document.getElementById("source"); - var ctx = canvas.getContext("2d"); - ctx.clearRect(0, 0, canvas.width, canvas.height); - var img = document.getElementById("sourceimg"); - ctx.drawImage(img, 0, 0); - imgData = ctx.getImageData(0, 0, canvas.width,canvas.height); - data = imgData.data; - pxls = []; - for (let i = 0; i < data.length; i += 4) { - var pixel = []; - pixel.push(data[i]); - pixel.push(data[i+1]); - pixel.push(data[i+2]); - pixel.push(data[i+3]); - pxls.push(pixel); - } - var pxlsarray = [[]]; - for(i = 0;icanvas.width-10){ - pxlsarray.push([]); - } - } - - } - savedata["pxlsarray"] = pxlsarray; - ctx.clearRect(0, 0, canvas.width, canvas.height); - ctx.drawImage(img, 0, 0); - } - img.src = data["img"]; - savedata["crpdims"] = { - "left":0, - "top": 0, - "right":0, - "bottom":0 - }; - /*savedata["crpdimsref"] = { - "left":0, - "top": 0, - "right":0, - "bottom":0 - };*/ - savedata["additionaldims"] = { - "left":0, - "top": 0, - "right":0, - "bottom":0 - }; - if(data["flag"]=="True"){ - refresh(savedata); - } - - - }, function (rejectionReason) { // 3 - console.log('Error parsing JSON from response:', rejectionReason, responseClone); // 4 - responseClone.text() // 5 - .then(function (bodyText) { - console.log('Received the following instead of valid JSON:', bodyText); // 6 - }); - }); - - //document.getElementById("msg").style.visibility = "visible"; - //document.getElementById("container").remove(); - -} - -function grabwfsmodels(){ - fetch('http://localhost:5000/grabwfsmodels') - .then(function (response){ - return response.json(); - }) - .then(data=>{ - console.log(data); - for(let i =0;i{ - }); -} - -function saved(savedata){ - var responseClone; // 1 - fetch('http://localhost:5000/savedata', { - method: 'POST', - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({"savedata":savedata,"selectorsize":selectorsize,"taesd":taesd}) - }) - .then(function (response) { - responseClone = response.clone(); // 2 - return response.json(); - }) - .then(data => { - document.getElementById("settings").style.visibility = "hidden"; - document.getElementById("selector").style.visibility = "hidden"; - document.getElementById("saveexit").style.visibility = "hidden"; - if(genflag==false){ - generate(); - genflag = true; - } - if(data["taesd"]=="no"){ - if(canvasflag){ - backup["width"] = document.getElementById("source").width; - backup["height"] = document.getElementById("source").height; - backup["left"] = document.getElementById("source").style.left; - backup["top"] = document.getElementById("source").style.top; - backup["img"] = document.getElementById("sourceimg").src; - - document.getElementById("sourceimg").width = data["width"]; - document.getElementById("sourceimg").height =data["height"]; - document.getElementById("source").width = data["width"]; - document.getElementById("source").height = data["height"]; - /*document.getElementById("sourceunder").width = data["width"]; - document.getElementById("sourceunder").height = data["height"];*/ - if(parseInt(data["data"]["additionaldims"]["left"])!=0){ - document.getElementById("source").style.left = parseFloat(document.getElementById("source").style.left) - parseInt(data["data"]["additionaldims"]["left"]) +"px"; - } - if(parseInt(data["data"]["additionaldims"]["top"])!=0){ - document.getElementById("source").style.top = parseFloat(document.getElementById("source").style.top) - parseInt(data["data"]["additionaldims"]["top"]) +"px"; - } - } - canvasflag = false; - - //document.getElementById("sourceunder").style.visibility = "visible"; - - - /*document.getElementById("sourceunder").style.left = "0px"; - document.getElementById("sourceunder").style.top = document.getElementById("source").style.top;*/ - - - - document.getElementById("sourceimg").src = data["img"]; - img = new Image(); - img.onload = function() { - var canvas = document.getElementById("source"); - var ctx = canvas.getContext("2d"); - ctx.clearRect(0, 0, canvas.width, canvas.height); - var img = document.getElementById("sourceimg"); - ctx.drawImage(img, 0, 0); - imgData = ctx.getImageData(0, 0, canvas.width,canvas.height); - data = imgData.data; - pxls = []; - for (let i = 0; i < data.length; i += 4) { - var pixel = []; - pixel.push(data[i]); - pixel.push(data[i+1]); - pixel.push(data[i+2]); - pixel.push(data[i+3]); - pxls.push(pixel); - } - var pxlsarray = [[]]; - for(i = 0;icanvas.width-10){ - pxlsarray.push([]); - } - } - - } - savedata["pxlsarray"] = pxlsarray; - ctx.clearRect(0, 0, canvas.width, canvas.height); - ctx.drawImage(img, 0, 0); - } - img.src = data["img"]; - savedata["crpdims"] = { - "left":0, - "top": 0, - "right":0, - "bottom":0 - }; - savedata["additionaldims"] = { - "left":0, - "top": 0, - "right":0, - "bottom":0 - }; - } - /*setTimeout(() => { - var canvasunder = document.getElementById("sourceunder"); - var ctxunder = canvasunder.getContext("2d"); - ctxunder.clearRect(0, 0, canvasunder.width, canvasunder.height); - ctxunder.drawImage(img, 0, 0); - }, 100);*/ - - if(data["flag"]=="False"){ - taesd = "true"; - setTimeout(() => { - saved(savedata); - }, 100); - } - else{ - document.getElementById("settings").style.visibility = "visible"; - document.getElementById("selector").style.visibility = "visible"; - document.getElementById("saveexit").style.visibility = "visible"; - taesd = "false"; - canvasflag = true; - genflag = false; - //document.getElementById("sourceunder").style.visibility = "hidden"; - } - //refresh(savedata); - - - }, function (rejectionReason) { // 3 - console.log('Error parsing JSON from response:', rejectionReason, responseClone); // 4 - responseClone.text() // 5 - .then(function (bodyText) { - console.log('Received the following instead of valid JSON:', bodyText); // 6 - }); - }); - - //document.getElementById("msg").style.visibility = "visible"; - //document.getElementById("container").remove(); - -} -function mousecoordinates(event){ - prevmousex = mousex; - prevmousey =mousey; - mousex = event.clientX; - mousey = event.clientY; - - -} -function selector(){ - var selec = document.getElementById("selector"); - selec.style.left = Math.floor(mousex)+"px"; - selec.style.top = Math.floor(mousey)+"px"; - if(lockflag==false){ - if((parseFloat(document.getElementById("selector").style.left)-(selectorsize/2))<0){ - selec.style.left = Math.floor(selectorsize/2)+"px"; - } - if((parseFloat(document.getElementById('selector').getBoundingClientRect()["right"])-(selectorsize/2))>parseInt(screen.availWidth)){ - selec.style.left = parseInt(screen.availWidth)-selectorsize+"px"; - } - if((parseFloat(document.getElementById("selector").style.top)-(selectorsize/2))<0){ - selec.style.top = Math.floor(selectorsize/2)+"px"; - } - if((parseFloat(document.getElementById('selector').getBoundingClientRect()["bottom"])-(selectorsize/2))>parseInt(screen.availHeight)){ - selec.style.bottom = parseInt(screen.availHeight)-selectorsize+"px"; - } - } - - if(ll){ - if((parseFloat(document.getElementById("selector").style.left)-(selectorsize/2))parseFloat(document.getElementById('source').getBoundingClientRect()["right"])){ - selec.style.left = parseFloat(document.getElementById("source").style.left)+parseFloat(document.getElementById("source").width) - Math.floor(selectorsize/2) +"px"; - } - } - if(lt){ - if((parseFloat(document.getElementById("selector").style.top)-(selectorsize/2))parseFloat(document.getElementById('source').getBoundingClientRect()["bottom"])){ - selec.style.top = parseFloat(document.getElementById("source").style.top)+parseFloat(document.getElementById("source").height) - Math.floor(selectorsize/2)+"px"; - } - } - - - -} - - -function imgmover(){ - var selec = document.getElementById("source"+imagetomove); - console.log(selec.id); - if(mousex>prevmousex){ - selec.style.left = parseInt(selec.getBoundingClientRect()["left"])+10+"px"; - } - else if(mousexprevmousey){ - selec.style.top = parseInt(selec.getBoundingClientRect()["top"])+10+"px"; - } - else if(mousey=document.getElementById('source').getBoundingClientRect()["left"]){ - if(((parseFloat(document.getElementById("selector").style.left)-(parseFloat(selectorsize)/2))-document.getElementById('source').getBoundingClientRect()["left"])+parseFloat(selectorsize)>imagedims["width"]){ - let lft = (parseFloat(document.getElementById("selector").style.left)-(parseFloat(selectorsize)/2))-document.getElementById('source').getBoundingClientRect()["left"]; - savedata["additionaldims"]["right"] = parseFloat(selectorsize) - (imagedims["width"]-lft); - savedata["additionaldims"]["left"] = 0; - savedata["crpdims"]["left"] = lft; - savedata["crpdims"]["right"] = imagedims["width"]; - console.log(savedata["crpdims"]["right"]); - } - else{ - - savedata["crpdims"]["left"] = (parseFloat(document.getElementById("selector").style.left)-(parseFloat(selectorsize)/2))-document.getElementById('source').getBoundingClientRect()["left"]; - savedata["crpdims"]["right"] = parseFloat(selectorsize) + ((parseFloat(document.getElementById("selector").style.left)-(parseFloat(selectorsize)/2))-parseFloat(document.getElementById('source').getBoundingClientRect()["left"])); - console.log(savedata["crpdims"]["right"]); - } - } - - if((parseFloat(document.getElementById("selector").style.top)-(parseFloat(selectorsize)/2))=document.getElementById('source').getBoundingClientRect()["top"]){ - if(((parseFloat(document.getElementById("selector").style.top)-(parseFloat(selectorsize)/2))-document.getElementById('source').getBoundingClientRect()["top"])+parseFloat(selectorsize)>imagedims["height"]){ - let tp = (parseFloat(document.getElementById("selector").style.top)-(parseFloat(selectorsize)/2))-document.getElementById('source').getBoundingClientRect()["top"]; - savedata["additionaldims"]["bottom"] = parseFloat(selectorsize) - (imagedims["height"]-tp); - savedata["additionaldims"]["top"] = 0; - savedata["crpdims"]["top"] = tp; - savedata["crpdims"]["bottom"] = imagedims["height"]; - } - else{ - savedata["crpdims"]["top"] = (parseFloat(document.getElementById("selector").style.top)-(parseFloat(selectorsize)/2))-document.getElementById('source').getBoundingClientRect()["top"]; - savedata["crpdims"]["bottom"] = (((parseFloat(document.getElementById("selector").style.top)-(parseFloat(selectorsize)/2))-document.getElementById('source').getBoundingClientRect()["top"])+parseFloat(selectorsize)); - } - } - } - else{ - savedata["crpdimsref"] = { - "left":0, - "top": 0, - "right":0, - "bottom":0 - }; - if((parseFloat(document.getElementById("selector").style.left)-(parseFloat(selectorsize)/2))=document.getElementById('source').getBoundingClientRect()["left"]){ - if(((parseFloat(document.getElementById("selector").style.left)-(parseFloat(selectorsize)/2))-document.getElementById('source').getBoundingClientRect()["left"])+parseFloat(selectorsize)>imagedims["width"]){ - let lft = (parseFloat(document.getElementById("selector").style.left)-(parseFloat(selectorsize)/2))-document.getElementById('source').getBoundingClientRect()["left"]; - savedata["crpdimsref"]["left"] = lft; - savedata["crpdimsref"]["right"] = imagedims["width"]; - console.log(savedata["crpdimsref"]["right"]); - } - else{ - - savedata["crpdimsref"]["left"] = (parseFloat(document.getElementById("selector").style.left)-(parseFloat(selectorsize)/2))-document.getElementById('source').getBoundingClientRect()["left"]; - savedata["crpdimsref"]["right"] = parseFloat(selectorsize) + ((parseFloat(document.getElementById("selector").style.left)-(parseFloat(selectorsize)/2))-parseFloat(document.getElementById('source').getBoundingClientRect()["left"])); - console.log(savedata["crpdimsref"]["right"]); - } - } - - if((parseFloat(document.getElementById("selector").style.top)-(parseFloat(selectorsize)/2))=document.getElementById('source').getBoundingClientRect()["top"]){ - if(((parseFloat(document.getElementById("selector").style.top)-(parseFloat(selectorsize)/2))-document.getElementById('source').getBoundingClientRect()["top"])+parseFloat(selectorsize)>imagedims["height"]){ - let tp = (parseFloat(document.getElementById("selector").style.top)-(parseFloat(selectorsize)/2))-document.getElementById('source').getBoundingClientRect()["top"]; - - savedata["crpdimsref"]["top"] = tp; - savedata["crpdimsref"]["bottom"] = imagedims["height"]; - } - else{ - savedata["crpdimsref"]["top"] = (parseFloat(document.getElementById("selector").style.top)-(parseFloat(selectorsize)/2))-document.getElementById('source').getBoundingClientRect()["top"]; - savedata["crpdimsref"]["bottom"] = (((parseFloat(document.getElementById("selector").style.top)-(parseFloat(selectorsize)/2))-document.getElementById('source').getBoundingClientRect()["top"])+parseFloat(selectorsize)); - } - } - } - -} - -function lockleft(){ - if(ll){ - document.getElementById("lockleft").style.backgroundColor = "gray"; - } - else{ - document.getElementById("lockleft").style.backgroundColor = "rgb(20,20,20)"; - } - if(!lockflag){ - ll = !ll; - } -} -function lockright(){ - if(lr){ - document.getElementById("lockright").style.backgroundColor = "gray"; - } - else{ - document.getElementById("lockright").style.backgroundColor = "rgb(20,20,20)"; - } - if(!lockflag){ - lr = !lr; - } - -} -function locktop(){ - if(lt){ - document.getElementById("locktop").style.backgroundColor = "gray"; - } - else{ - document.getElementById("locktop").style.backgroundColor = "rgb(20,20,20)"; - } - if(!lockflag){ - lt = !lt; - } - -} -function lockbottom(){ - if(lb){ - document.getElementById("lockbottom").style.backgroundColor = "gray"; - } - else{ - document.getElementById("lockbottom").style.backgroundColor = "rgb(20,20,20)"; - } - if(!lockflag){ - lb = !lb; - } - - -} -function lockbox(){ - if(!lockflag){ - ll = true; - lr = true; - lt = true; - lb = true; - document.getElementById("lockleft").style.backgroundColor = "gray"; - document.getElementById("lockright").style.backgroundColor = "gray"; - document.getElementById("locktop").style.backgroundColor = "gray"; - document.getElementById("lockbottom").style.backgroundColor = "gray"; - document.getElementById("lockbox").style.backgroundColor = "rgb(20, 20, 20)"; - } - else{ - document.getElementById("lockbox").style.backgroundColor = "gray"; - ll = false; - lr = false; - lt = false; - lb = false; - } - lockflag = !lockflag; -} - -function grabselector(){ - if(lockflag==false){ - document.getElementById("selector").style.left = Math.floor(mousex)+"px"; - document.getElementById("selector").style.top = Math.floor(mousey)+"px"; - } - - -} - -function moveimgenablefirst(){ - if(moveimgenableflag){ - document.getElementById("selector").style.visibility = "visible"; - document.getElementById("moveimg").style.backgroundColor = "gray"; - moveimgenableflag = !moveimgenableflag - imagetomove = ""; - } - else{ - if(drawflag==false && eraseflag==false){ - document.getElementById("selector").style.visibility = "hidden"; - document.getElementById("moveimg").style.backgroundColor = "rgb(20,20,20)"; - moveimgenableflag = !moveimgenableflag; - imagetomove = ""; - } - } -} -function moveimgenable(t){ - if(moveimgenableflag){ - try{ - document.getElementById(t.currentTarget.id).style.backgroundColor = "gray"; - } - catch(error){ - document.getElementById("moveimg1").style.backgroundColor = "gray"; - } - moveimgenableflag = !moveimgenableflag - imagetomove = ""; - } - else{ - if(drawflag==false && eraseflag==false){ - try{ - document.getElementById(t.currentTarget.id).style.backgroundColor = "rgb(20,20,20)"; - document.getElementById("canvascontainer").appendChild(document.getElementById("source"+t.currentTarget.id.match(/\d+/)[0])); - } - catch(error){ - document.getElementById("moveimg1").style.backgroundColor = "rgb(20,20,20)"; - document.getElementById("canvascontainer").appendChild(document.getElementById("source")); - } - - moveimgenableflag = !moveimgenableflag; - try{ - imagetomove = String(t.currentTarget.id.match(/\d+/)[0]); - comporder.push(t.currentTarget.id.match(/\d+/)[0]); - } - catch(error){ - imagetomove = ""; - comporder.push(""); - } - } - } -} - -function compimage(){ - var order = [""]; - var coordinates = [[parseInt(document.getElementById('source').getBoundingClientRect()["left"]),parseInt(document.getElementById('source').getBoundingClientRect()["top"])]]; - var num = document.getElementById("settings2").children.length - 3; - document.getElementById("openimgadd").remove(); - var newel = document.createElement("input"); - newel.id = "openimgadd"; - newel.type = "file"; - newel.onchange =function(e) { - var file, img; - if ((file = this.files[0])) { - comporder = []; - document.getElementById("selector").style.visibility = "hidden"; - var num = (document.getElementById("canvascontainer").children.length /2)+1; - num = String(num); - document.getElementById("settings2").style.visibility = "visible"; - var newel = document.createElement("div"); - newel.id = "moveimg"+num; - newel.addEventListener("click",moveimgenable); - newel.className = "moveimgclass txt"; - newel.style.left = 5+(num-1)*10+"%"; - var newelpar = document.createElement("p"); - newelpar.innerHTML = "Move Image "+num; - newelpar.className = "txt"; - newel.append(newelpar); - document.getElementById("settings2").append(newel); - newel = document.createElement("img"); - newel.id = "sourceimg"+num; - newel.style.display = "none"; - document.getElementById("canvascontainer").append(newel); - newel = document.createElement("canvas"); - newel.id = "source"+num; - newel.style.position = "fixed"; - document.getElementById("canvascontainer").append(newel); - img = new Image(); - img.onload = function() { - document.getElementById("sourceimg"+num).width = this.width; - document.getElementById("sourceimg"+num).height = this.height; - document.getElementById("source"+num).width = this.width; - document.getElementById("source"+num).height = this.height; - var canvas = document.getElementById("source"+num); - var ctx = canvas.getContext("2d"); - ctx.clearRect(0, 0, canvas.width, canvas.height); - var img = document.getElementById("sourceimg"+num); - ctx.drawImage(img, 0, 0); - imgData = ctx.getImageData(0, 0, canvas.width,canvas.height); - data = imgData.data; - pxls = []; - for (let i = 0; i < data.length; i += 4) { - var pixel = []; - pixel.push(data[i]); - pixel.push(data[i+1]); - pixel.push(data[i+2]); - pixel.push(data[i+3]); - pxls.push(pixel); - } - var pxlsarray = [[]]; - for(i = 0;icanvas.width-10){ - pxlsarray.push([]); - } - } - - } - }; - img.src = URL.createObjectURL(file); - document.getElementById("sourceimg"+num).src = URL.createObjectURL(file); - } - - } - document.getElementById("settings").append(newel); - for(let i=1;i0){ - comporder.reverse(); - order.reverse(); - for(let i=0;irightest){ - rightest = parseInt(document.getElementById('source'+i).getBoundingClientRect()["right"]) - } - if(parseInt(document.getElementById('source'+i).getBoundingClientRect()["bottom"])>bottomest){ - bottomest = parseInt(document.getElementById('source'+i).getBoundingClientRect()["bottom"]) - } - } - console.log(coordinates); - console.log(order); - var canvas = document.getElementById("source"); - var ctx = canvas.getContext("2d"); - canvas.width = rightest-leftest; - canvas.height = bottomest-topest; - ctx.clearRect(0, 0, canvas.width, canvas.height); - order.reverse(); - for(let i = 0;icanvas.width-10){ - pxlsarray.push([]); - } - } - - } - savedata["pxlsarray"] = pxlsarray; - document.getElementById("settings2").style.visibility="hidden"; - document.getElementById("selector").style.visibility = "visible"; - -} -function moveimg(){ - if(clickflag && moveimgenableflag){ - document.getElementById("moveimglistner").removeEventListener("mousemove", imgmover); - clickflag = !clickflag - } - else{ - document.getElementById("moveimglistner").addEventListener("mousemove", imgmover); - clickflag = !clickflag - } -} -function changeselectorsize(){ - var elem = document.getElementById("selectorsize"); - selectorsize = elem.value; - savedata["boxsz"] = selectorsize; - document.getElementById("selector").style.width = selectorsize+"px"; - document.getElementById("selector").style.height = selectorsize+"px"; -} - -function savejson(){ - saved(savedata); - -} - -function reset(){ - var selec = document.getElementById("selector"); - selec.style.left = mousex+"px"; - selec.style.top = mousey+"px"; -} diff --git a/CanvasToolLone/templates/index.html b/CanvasToolLone/templates/index.html deleted file mode 100644 index 98cf4cb..0000000 --- a/CanvasToolLone/templates/index.html +++ /dev/null @@ -1,67 +0,0 @@ - - - - - - - - -
-
- - -
-
-
-
-

Set Reference

-

UNDO

-

Move Image

-

Box Size:

- -

Generate

-

Erase

-

Draw

-

Fade Factor:

- -

Eraser/Pencil Size:

- - - -

Lock Box To Image

-

Left

-

Right

-

Bottom

-

Top

-

Reset Image

- - - - - -
-
-

Move Image

-

Done

- -
-
- - -
- - -
-

Close the tab if not auto-closed

- - \ No newline at end of file diff --git a/CanvasToolLone/workflows/img2img_workflow.json b/CanvasToolLone/workflows/img2img_workflow.json deleted file mode 100644 index 9cf6c7e..0000000 --- a/CanvasToolLone/workflows/img2img_workflow.json +++ /dev/null @@ -1,146 +0,0 @@ -{ - "16": { - "inputs": { - "seed": 25670445128187 - }, - "class_type": "OutpaintCanvasTool" - }, - "17": { - "inputs": { - "mode": "resize", - "supersample": "true", - "resampling": "bilinear", - "rescale_factor": 2, - "resize_width": [ - "18", - 0 - ], - "resize_height": [ - "18", - 1 - ], - "image": [ - "16", - 2 - ] - }, - "class_type": "Image Resize" - }, - "18": { - "inputs": { - "image": [ - "16", - 0 - ] - }, - "class_type": "Get Image Size" - }, - "19": { - "inputs": { - "images": [ - "16", - 0 - ] - }, - "class_type": "PreviewImage" - }, - "20": { - "inputs": { - "images": [ - "16", - 1 - ] - }, - "class_type": "PreviewImage" - }, - "21": { - "inputs": { - "images": [ - "16", - 2 - ] - }, - "class_type": "PreviewImage" - }, - "22": { - "inputs": { - "image": [ - "23", - 0 - ] - }, - "class_type": "stitch" - }, - "23": { - "inputs": { - "image": [ - "28", - 0 - ] - }, - "class_type": "ImageOutputToComfyNodes" - }, - "26": { - "inputs": { - "device": "GPU", - "tomesd_value": 0.6, - "ip_adapter": "enable", - "reference_only": "disable", - "ip_adapter_model": "ip-adapter_sd15.bin", - "model_name": "Juggernaut", - "controlnet_model": "cn_inpaint" - }, - "class_type": "LCMLoraLoader_inpaint" - }, - "28": { - "inputs": { - "seed": 834173561198935, - "text": "", - "steps": 4, - "width": [ - "18", - 0 - ], - "height": [ - "18", - 1 - ], - "cfg": 1.5, - "reference_style_fidelity": 0.1, - "batch": 1, - "strength": 0.45, - "prompt_weighting": "disable", - "controlnet_weight": 1, - "reference_only": "disable", - "ip_adapter": "enable", - "ipadapter_scale": 0.25, - "mask": [ - "16", - 1 - ], - "image": [ - "16", - 0 - ], - "reference_image": [ - "17", - 0 - ], - "pipe": [ - "26", - 0 - ] - }, - "class_type": "LCMLora_inpaint" - }, - "29": { - "inputs": { - "filename_prefix": "ComfyUI", - "images": [ - "22", - 0 - ] - }, - "class_type": "SaveImage_Canvas" - } -} \ No newline at end of file diff --git a/CanvasToolLone/workflows/img2img_workflow_ref.json b/CanvasToolLone/workflows/img2img_workflow_ref.json deleted file mode 100644 index 08fb679..0000000 --- a/CanvasToolLone/workflows/img2img_workflow_ref.json +++ /dev/null @@ -1,146 +0,0 @@ -{ - "16": { - "inputs": { - "seed": 25670445128187 - }, - "class_type": "OutpaintCanvasTool" - }, - "17": { - "inputs": { - "mode": "resize", - "supersample": "true", - "resampling": "bilinear", - "rescale_factor": 2, - "resize_width": [ - "18", - 0 - ], - "resize_height": [ - "18", - 1 - ], - "image": [ - "16", - 2 - ] - }, - "class_type": "Image Resize" - }, - "18": { - "inputs": { - "image": [ - "16", - 0 - ] - }, - "class_type": "Get Image Size" - }, - "19": { - "inputs": { - "images": [ - "16", - 0 - ] - }, - "class_type": "PreviewImage" - }, - "20": { - "inputs": { - "images": [ - "16", - 1 - ] - }, - "class_type": "PreviewImage" - }, - "21": { - "inputs": { - "images": [ - "16", - 2 - ] - }, - "class_type": "PreviewImage" - }, - "22": { - "inputs": { - "image": [ - "23", - 0 - ] - }, - "class_type": "stitch" - }, - "23": { - "inputs": { - "image": [ - "28", - 0 - ] - }, - "class_type": "ImageOutputToComfyNodes" - }, - "26": { - "inputs": { - "device": "GPU", - "tomesd_value": 0.6, - "ip_adapter": "disable", - "reference_only": "enable", - "ip_adapter_model": "ip-adapter_sd15.bin", - "model_name": "Juggernaut", - "controlnet_model": "cn_inpaint" - }, - "class_type": "LCMLoraLoader_inpaint" - }, - "28": { - "inputs": { - "seed": 834173561198935, - "text": "", - "steps": 8, - "width": [ - "18", - 0 - ], - "height": [ - "18", - 1 - ], - "cfg": 1.5, - "reference_style_fidelity": 0.3, - "batch": 1, - "strength": 0.45, - "prompt_weighting": "disable", - "controlnet_weight": 1, - "reference_only": "enable", - "ip_adapter": "disable", - "ipadapter_scale": 0.25, - "mask": [ - "16", - 1 - ], - "image": [ - "16", - 0 - ], - "reference_image": [ - "17", - 0 - ], - "pipe": [ - "26", - 0 - ] - }, - "class_type": "LCMLora_inpaint" - }, - "29": { - "inputs": { - "filename_prefix": "ComfyUI", - "images": [ - "22", - 0 - ] - }, - "class_type": "SaveImage_Canvas" - } -} \ No newline at end of file diff --git a/CanvasToolLone/workflows/ipadapter_workflow.json b/CanvasToolLone/workflows/ipadapter_workflow.json deleted file mode 100644 index a6aeab6..0000000 --- a/CanvasToolLone/workflows/ipadapter_workflow.json +++ /dev/null @@ -1,146 +0,0 @@ -{ - "16": { - "inputs": { - "seed": 25670445128187 - }, - "class_type": "OutpaintCanvasTool" - }, - "17": { - "inputs": { - "mode": "resize", - "supersample": "true", - "resampling": "bilinear", - "rescale_factor": 2, - "resize_width": [ - "18", - 0 - ], - "resize_height": [ - "18", - 1 - ], - "image": [ - "16", - 2 - ] - }, - "class_type": "Image Resize" - }, - "18": { - "inputs": { - "image": [ - "16", - 0 - ] - }, - "class_type": "Get Image Size" - }, - "19": { - "inputs": { - "images": [ - "16", - 0 - ] - }, - "class_type": "PreviewImage" - }, - "20": { - "inputs": { - "images": [ - "16", - 1 - ] - }, - "class_type": "PreviewImage" - }, - "21": { - "inputs": { - "images": [ - "16", - 2 - ] - }, - "class_type": "PreviewImage" - }, - "22": { - "inputs": { - "image": [ - "23", - 0 - ] - }, - "class_type": "stitch" - }, - "23": { - "inputs": { - "image": [ - "28", - 0 - ] - }, - "class_type": "ImageOutputToComfyNodes" - }, - "26": { - "inputs": { - "device": "GPU", - "tomesd_value": 0.6, - "ip_adapter": "enable", - "reference_only": "disable", - "ip_adapter_model": "ip-adapter_sd15.bin", - "model_name": "Juggernaut", - "controlnet_model": "cn_inpaint" - }, - "class_type": "LCMLoraLoader_inpaint" - }, - "28": { - "inputs": { - "seed": 834173561198935, - "text": "", - "steps": 4, - "width": [ - "18", - 0 - ], - "height": [ - "18", - 1 - ], - "cfg": 1.5, - "reference_style_fidelity": 0.1, - "batch": 1, - "strength": 1, - "prompt_weighting": "disable", - "controlnet_weight": 1, - "reference_only": "disable", - "ip_adapter": "enable", - "ipadapter_scale": 0.25, - "mask": [ - "16", - 1 - ], - "image": [ - "16", - 0 - ], - "reference_image": [ - "17", - 0 - ], - "pipe": [ - "26", - 0 - ] - }, - "class_type": "LCMLora_inpaint" - }, - "29": { - "inputs": { - "filename_prefix": "ComfyUI", - "images": [ - "22", - 0 - ] - }, - "class_type": "SaveImage_Canvas" - } -} \ No newline at end of file diff --git a/CanvasToolLone/workflows/ref_ipadapter_workflow.json b/CanvasToolLone/workflows/ref_ipadapter_workflow.json deleted file mode 100644 index 2d6fba1..0000000 --- a/CanvasToolLone/workflows/ref_ipadapter_workflow.json +++ /dev/null @@ -1,146 +0,0 @@ -{ - "16": { - "inputs": { - "seed": 25670445128187 - }, - "class_type": "OutpaintCanvasTool" - }, - "17": { - "inputs": { - "mode": "resize", - "supersample": "true", - "resampling": "bilinear", - "rescale_factor": 2, - "resize_width": [ - "18", - 0 - ], - "resize_height": [ - "18", - 1 - ], - "image": [ - "16", - 2 - ] - }, - "class_type": "Image Resize" - }, - "18": { - "inputs": { - "image": [ - "16", - 0 - ] - }, - "class_type": "Get Image Size" - }, - "19": { - "inputs": { - "images": [ - "16", - 0 - ] - }, - "class_type": "PreviewImage" - }, - "20": { - "inputs": { - "images": [ - "16", - 1 - ] - }, - "class_type": "PreviewImage" - }, - "21": { - "inputs": { - "images": [ - "16", - 2 - ] - }, - "class_type": "PreviewImage" - }, - "22": { - "inputs": { - "image": [ - "23", - 0 - ] - }, - "class_type": "stitch" - }, - "23": { - "inputs": { - "image": [ - "28", - 0 - ] - }, - "class_type": "ImageOutputToComfyNodes" - }, - "26": { - "inputs": { - "device": "GPU", - "tomesd_value": 0.6, - "ip_adapter": "enable", - "reference_only": "enable", - "ip_adapter_model": "ip-adapter_sd15.bin", - "model_name": "Juggernaut", - "controlnet_model": "cn_inpaint" - }, - "class_type": "LCMLoraLoader_inpaint" - }, - "28": { - "inputs": { - "seed": 834173561198935, - "text": "", - "steps": 4, - "width": [ - "18", - 0 - ], - "height": [ - "18", - 1 - ], - "cfg": 1.5, - "reference_style_fidelity": 0.1, - "batch": 1, - "strength": 1, - "prompt_weighting": "disable", - "controlnet_weight": 1, - "reference_only": "enable", - "ip_adapter": "enable", - "ipadapter_scale": 0.25, - "mask": [ - "16", - 1 - ], - "image": [ - "16", - 0 - ], - "reference_image": [ - "17", - 0 - ], - "pipe": [ - "26", - 0 - ] - }, - "class_type": "LCMLora_inpaint" - }, - "29": { - "inputs": { - "filename_prefix": "ComfyUI", - "images": [ - "22", - 0 - ] - }, - "class_type": "SaveImage_Canvas" - } -} \ No newline at end of file diff --git a/CanvasToolLone/workflows/ref_workflow.json b/CanvasToolLone/workflows/ref_workflow.json deleted file mode 100644 index 68bf5bd..0000000 --- a/CanvasToolLone/workflows/ref_workflow.json +++ /dev/null @@ -1,146 +0,0 @@ -{ - "16": { - "inputs": { - "seed": 25670445128187 - }, - "class_type": "OutpaintCanvasTool" - }, - "17": { - "inputs": { - "mode": "resize", - "supersample": "true", - "resampling": "bilinear", - "rescale_factor": 2, - "resize_width": [ - "18", - 0 - ], - "resize_height": [ - "18", - 1 - ], - "image": [ - "16", - 2 - ] - }, - "class_type": "Image Resize" - }, - "18": { - "inputs": { - "image": [ - "16", - 0 - ] - }, - "class_type": "Get Image Size" - }, - "19": { - "inputs": { - "images": [ - "16", - 0 - ] - }, - "class_type": "PreviewImage" - }, - "20": { - "inputs": { - "images": [ - "16", - 1 - ] - }, - "class_type": "PreviewImage" - }, - "21": { - "inputs": { - "images": [ - "16", - 2 - ] - }, - "class_type": "PreviewImage" - }, - "22": { - "inputs": { - "image": [ - "23", - 0 - ] - }, - "class_type": "stitch" - }, - "23": { - "inputs": { - "image": [ - "28", - 0 - ] - }, - "class_type": "ImageOutputToComfyNodes" - }, - "26": { - "inputs": { - "device": "GPU", - "tomesd_value": 0.6, - "ip_adapter": "disable", - "reference_only": "enable", - "ip_adapter_model": "ip-adapter_sd15.bin", - "model_name": "Juggernaut", - "controlnet_model": "cn_inpaint" - }, - "class_type": "LCMLoraLoader_inpaint" - }, - "28": { - "inputs": { - "seed": 834173561198935, - "text": "", - "steps": 4, - "width": [ - "18", - 0 - ], - "height": [ - "18", - 1 - ], - "cfg": 1.5, - "reference_style_fidelity": 0.1, - "batch": 1, - "strength": 1, - "prompt_weighting": "disable", - "controlnet_weight": 1, - "reference_only": "enable", - "ip_adapter": "disable", - "ipadapter_scale": 0.2, - "mask": [ - "16", - 1 - ], - "image": [ - "16", - 0 - ], - "reference_image": [ - "17", - 0 - ], - "pipe": [ - "26", - 0 - ] - }, - "class_type": "LCMLora_inpaint" - }, - "29": { - "inputs": { - "filename_prefix": "ComfyUI", - "images": [ - "22", - 0 - ] - }, - "class_type": "SaveImage_Canvas" - } -} \ No newline at end of file diff --git a/CanvasToolLone/workflows/workflow_api.json b/CanvasToolLone/workflows/workflow_api.json deleted file mode 100644 index 68bf5bd..0000000 --- a/CanvasToolLone/workflows/workflow_api.json +++ /dev/null @@ -1,146 +0,0 @@ -{ - "16": { - "inputs": { - "seed": 25670445128187 - }, - "class_type": "OutpaintCanvasTool" - }, - "17": { - "inputs": { - "mode": "resize", - "supersample": "true", - "resampling": "bilinear", - "rescale_factor": 2, - "resize_width": [ - "18", - 0 - ], - "resize_height": [ - "18", - 1 - ], - "image": [ - "16", - 2 - ] - }, - "class_type": "Image Resize" - }, - "18": { - "inputs": { - "image": [ - "16", - 0 - ] - }, - "class_type": "Get Image Size" - }, - "19": { - "inputs": { - "images": [ - "16", - 0 - ] - }, - "class_type": "PreviewImage" - }, - "20": { - "inputs": { - "images": [ - "16", - 1 - ] - }, - "class_type": "PreviewImage" - }, - "21": { - "inputs": { - "images": [ - "16", - 2 - ] - }, - "class_type": "PreviewImage" - }, - "22": { - "inputs": { - "image": [ - "23", - 0 - ] - }, - "class_type": "stitch" - }, - "23": { - "inputs": { - "image": [ - "28", - 0 - ] - }, - "class_type": "ImageOutputToComfyNodes" - }, - "26": { - "inputs": { - "device": "GPU", - "tomesd_value": 0.6, - "ip_adapter": "disable", - "reference_only": "enable", - "ip_adapter_model": "ip-adapter_sd15.bin", - "model_name": "Juggernaut", - "controlnet_model": "cn_inpaint" - }, - "class_type": "LCMLoraLoader_inpaint" - }, - "28": { - "inputs": { - "seed": 834173561198935, - "text": "", - "steps": 4, - "width": [ - "18", - 0 - ], - "height": [ - "18", - 1 - ], - "cfg": 1.5, - "reference_style_fidelity": 0.1, - "batch": 1, - "strength": 1, - "prompt_weighting": "disable", - "controlnet_weight": 1, - "reference_only": "enable", - "ip_adapter": "disable", - "ipadapter_scale": 0.2, - "mask": [ - "16", - 1 - ], - "image": [ - "16", - 0 - ], - "reference_image": [ - "17", - 0 - ], - "pipe": [ - "26", - 0 - ] - }, - "class_type": "LCMLora_inpaint" - }, - "29": { - "inputs": { - "filename_prefix": "ComfyUI", - "images": [ - "22", - 0 - ] - }, - "class_type": "SaveImage_Canvas" - } -} \ No newline at end of file