# Code Custodian File ID: 9F2C5A14-38D7-4A6B-91E2-81D23A0B59E1 import socket import json import urllib.request import struct import os import sys import time class ArtistlyBrowser: def __init__(self, port=9222): self.port = port self.sock = None self.cmd_id = 0 self.target = None self.connect() def connect(self): with urllib.request.urlopen(f"http://127.0.0.1:{self.port}/json", timeout=5) as resp: targets = json.loads(resp.read().decode("utf-8")) self.target = next((t for t in targets if t.get("type") == "page" and "artistly.ai" in t.get("url", "")), None) if not self.target: self.target = next((t for t in targets if t.get("type") == "page"), None) if not self.target: raise ValueError("No browser page target found.") page_id = self.target["id"] path = f"/devtools/page/{page_id}" self.sock = socket.create_connection(("127.0.0.1", self.port), timeout=20) key = "dGhlIHNhbXBsZSBub25jZQ==" req = ( f"GET {path} HTTP/1.1\r\n" f"Host: 127.0.0.1:{self.port}\r\n" f"Upgrade: websocket\r\n" f"Connection: Upgrade\r\n" f"Sec-WebSocket-Key: {key}\r\n" f"Sec-WebSocket-Version: 13\r\n\r\n" ) self.sock.sendall(req.encode("utf-8")) resp_header = b"" while b"\r\n\r\n" not in resp_header: chunk = self.sock.recv(1024) if not chunk: break resp_header += chunk if b"101" not in resp_header: raise ConnectionError("WebSocket upgrade failed.") def send(self, method, params=None): self.cmd_id += 1 cmd_dict = {"id": self.cmd_id, "method": method, "params": params or {}} payload_bytes = json.dumps(cmd_dict).encode("utf-8") length = len(payload_bytes) mask_key = os.urandom(4) masked_payload = bytearray(length) for i in range(length): masked_payload[i] = payload_bytes[i] ^ mask_key[i % 4] if length <= 125: header = struct.pack("!BB", 0x81, 0x80 | length) + mask_key elif length <= 65535: header = struct.pack("!BBH", 0x81, 0x80 | 126, length) + mask_key else: header = struct.pack("!BBQ", 0x81, 0x80 | 127, length) + mask_key self.sock.sendall(header + masked_payload) raw_resp = self.sock.recv(2) b1, b2 = struct.unpack("!BB", raw_resp) payload_len = b2 & 0x7F if payload_len == 126: ext = self.sock.recv(2) payload_len = struct.unpack("!H", ext)[0] elif payload_len == 127: ext = self.sock.recv(8) payload_len = struct.unpack("!Q", ext)[0] response_data = b"" while len(response_data) < payload_len: chunk = self.sock.recv(min(16384, payload_len - len(response_data))) if not chunk: break response_data += chunk return json.loads(response_data.decode("utf-8")) def evaluate(self, js_code): res = self.send("Runtime.evaluate", {"expression": js_code, "returnByValue": True}) return res.get("result", {}).get("result", {}).get("value") def dismiss_modals(self): for _ in range(3): self.send("Input.dispatchKeyEvent", {"type": "rawKeyDown", "windowsVirtualKeyCode": 27}) time.sleep(0.05) self.send("Input.dispatchKeyEvent", {"type": "keyUp", "windowsVirtualKeyCode": 27}) time.sleep(0.1) time.sleep(0.3) def navigate(self, url): self.send("Page.navigate", {"url": url}) time.sleep(4) self.dismiss_modals() def click_coordinate(self, x, y): self.send("Input.dispatchMouseEvent", {"type": "mouseMoved", "x": x, "y": y}) time.sleep(0.05) self.send("Input.dispatchMouseEvent", {"type": "mousePressed", "x": x, "y": y, "button": "left", "clickCount": 1}) time.sleep(0.05) self.send("Input.dispatchMouseEvent", {"type": "mouseReleased", "x": x, "y": y, "button": "left", "clickCount": 1}) time.sleep(0.3) def upload_file_to_slot(self, slot_idx, file_path): print(f"Uploading {file_path} to slot {slot_idx}...") res = self.send("Runtime.evaluate", { "expression": f"document.querySelectorAll('input.filepond--browser')[{slot_idx}]" }) obj_id = res.get("result", {}).get("result", {}).get("objectId") if not obj_id: raise ValueError(f"Could not find filepond input at slot {slot_idx}") self.send("DOM.setFileInputFiles", {"files": [file_path], "objectId": obj_id}) print("Waiting for filepond upload to complete...") for i in range(30): time.sleep(1) status = self.evaluate(f""" (() => {{ const pond = document.querySelectorAll('.filepond--root')[{slot_idx}]; if (!pond) return 'no_pond'; const text = pond.innerText || ''; const item = pond.querySelector('.filepond--item'); return {{ text: text.slice(0, 100), itemState: item ? item.getAttribute('data-filepond-item-state') : null }}; }})() """) if status and (status.get('itemState') in ['idle', 'processing-complete', 'complete'] or 'Upload complete' in status.get('text', '')): print("Upload confirmed complete!") return True return True def close(self): if self.sock: self.sock.close() def main(): anchor_path = "/Volumes/FACTORY_SSD/warezfactory/Art_Cannon/Characters/Arlo/arlo_dna_anchor.png" output_png = "/Volumes/FACTORY_SSD/warezfactory/Art_Cannon/Characters/Arlo/Poses/arlo_seated_anchor.png" output_meta = "/Volumes/FACTORY_SSD/warezfactory/Art_Cannon/Characters/Arlo/Poses/arlo_seated_anchor_metadata.json" os.makedirs(os.path.dirname(output_png), exist_ok=True) prompt = "Full body character cutout of cheerful boy giant panda Arlo sitting flat on the floor like a cuddly teddy bear. His short chubby panda legs are sticking forward showing the black padded soles of his feet. His hands are resting relaxed on his lap and belly with no peace signs. Wearing his rainbow spiral tie-dye beanie headband, retro tie-dye short-sleeve shirt, and classic blue denim overalls. Happy wide cheerful smile, chubby cheeks. Whimsical 3D Disney Pixar character art, soft fuzzy fur textures, vibrant boho hippie colors, clean isolated cutout on solid pure white background, master character design asset." browser = ArtistlyBrowser() print("Connected to Chrome.") # Step 0: Ensure we are on consistent characters and dismiss drawers browser.navigate("https://app.artistly.ai/ai/consistent-characters") browser.dismiss_modals() # Step 1: Select "3d & 2d Style Images" print("Selecting '3d & 2d Style Images' category card...") find_card_js = """ (() => { const all = Array.from(document.querySelectorAll('*')); const el = all.find(e => e.children.length === 0 && e.innerText && e.innerText.trim() === '3d & 2d Style Images'); if (!el) return null; const clickable = el.closest('.group') || el.closest('button, [role="button"], .cursor-pointer') || el; clickable.scrollIntoView({ behavior: 'instant', block: 'center' }); const rect = clickable.getBoundingClientRect(); return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }; })() """ coords = browser.evaluate(find_card_js) if not coords: raise ValueError("Could not find '3d & 2d Style Images' card.") print(f"Clicking category at ({coords['x']}, {coords['y']})...") browser.click_coordinate(int(coords["x"]), int(coords["y"])) time.sleep(3) browser.dismiss_modals() # Step 2: Upload Arlo's anchor browser.upload_file_to_slot(0, anchor_path) time.sleep(2) # Step 3: Aspect Ratio (1:1) print("Setting Aspect Ratio to 1:1...") set_aspect_js = """ (() => { const sel = document.querySelectorAll('select')[0]; if (!sel) return false; sel.value = '1:1'; sel.dispatchEvent(new Event('change', { bubbles: true })); return sel.value; })() """ val = browser.evaluate(set_aspect_js) print(f"Aspect ratio set to: {val}") # Step 4: Inject Prompt print("Injecting Prompt...") inject_prompt_js = f""" (() => {{ const textarea = document.querySelector('textarea'); if (!textarea) return false; textarea.focus(); const setter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value').set; setter.call(textarea, {json.dumps(prompt)}); textarea.dispatchEvent(new Event('input', {{ bubbles: true }})); textarea.dispatchEvent(new Event('change', {{ bubbles: true }})); return textarea.value; }})() """ p_val = browser.evaluate(inject_prompt_js) print(f"Prompt set ({len(p_val)} chars):\n{p_val}") # Step 5: Click Generate Image button print("Locating Generate button...") find_generate_btn_js = """ (() => { const buttons = Array.from(document.querySelectorAll('button')); const genBtn = buttons.find(b => (b.innerText || '').trim().toLowerCase().includes('generate')); if (!genBtn) return null; genBtn.scrollIntoView({ behavior: 'instant', block: 'center' }); const rect = genBtn.getBoundingClientRect(); return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2, text: genBtn.innerText.trim() }; })() """ gen_coords = browser.evaluate(find_generate_btn_js) if not gen_coords: raise ValueError("Generate button not found.") print(f"Clicking Generate button '{gen_coords['text']}' at ({gen_coords['x']}, {gen_coords['y']})...") browser.click_coordinate(int(gen_coords["x"]), int(gen_coords["y"])) print("Job submitted! Waiting 10s for generation pipeline...") time.sleep(10) # Step 6: Poll Personal Designs Gallery print("Navigating/Polling https://app.artistly.ai/personal-designs...") target_img_url = None initial_time = time.time() for attempt in range(1, 35): print(f"\n--- Polling attempt {attempt}/35 ({int(time.time() - initial_time)}s elapsed) ---") browser.navigate("https://app.artistly.ai/personal-designs") time.sleep(4) browser.dismiss_modals() # Query latest generated images in personal designs gallery get_latest_img_js = """ (() => { const imgs = Array.from(document.querySelectorAll('img')).map(img => img.src).filter(src => { return src && src.includes('cdn.artistly.ai/user-assets/'); }); return { images: imgs.slice(0, 10), currentUrl: window.location.href }; })() """ res = browser.evaluate(get_latest_img_js) imgs = res.get("images", []) print(f"Found {len(imgs)} user-asset images in gallery.") if imgs: print("Latest image in gallery:", imgs[0]) # Check if this image was generated just now or if it's the newest item target_img_url = imgs[0] break time.sleep(10) if not target_img_url: raise TimeoutError("Timed out waiting for generated asset in personal designs gallery.") # Strip query compression parameters clean_url = target_img_url.split("?")[0] print(f"\nHarvesting full-resolution master PNG from CDN:\n{clean_url}") req = urllib.request.Request( clean_url, headers={"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)"} ) with urllib.request.urlopen(req, timeout=30) as resp: img_bytes = resp.read() with open(output_png, "wb") as f: f.write(img_bytes) print(f"Master PNG successfully saved to {output_png} ({len(img_bytes)} bytes)") # Companion metadata JSON metadata = { "design_id": os.path.splitext(os.path.basename(clean_url))[0], "tool_used": "Consistent Characters (3D & 2D Style Images)", "prompt_recipe": prompt, "aspect_ratio": "1:1 (1024 X 1024) px", "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "character_anchors": [ { "name": "Arlo", "source_anchor": "Characters/Arlo/arlo_dna_anchor.png", "hash": "e7495800" } ], "cdn_source_url": clean_url, "raw_cdn_url": target_img_url } with open(output_meta, "w") as f: json.dump(metadata, f, indent=2) print(f"Metadata JSON written to {output_meta}") print("\nGeneration and harvesting completed successfully!") if __name__ == "__main__": main()