#!/usr/bin/env python3 """WI Local Image Studio. Python standard library, no incoming ports or dependencies. ComfyUI must be running on http://127.0.0.1:8188 and have model checkpoints. Set WI_IMAGE_URL, WI_IMAGE_WORKER_KEY on your PC before running. """ import os,sys,time,json,base64,urllib.request,urllib.parse WI=os.environ.get("WI_IMAGE_URL","").rstrip("/") TOKEN=os.environ.get("WI_IMAGE_WORKER_KEY","") COMFY=os.environ.get("COMFY_URL","http://127.0.0.1:8188").rstrip("/") MODEL={"sdxl":os.environ.get("COMFY_SDXL_CHECKPOINT","sd_xl_base_1.0.safetensors"), "sd15":os.environ.get("COMFY_SD15_CHECKPOINT","v1-5-pruned-emaonly.safetensors")} def call(origin,endpoint,method="GET",obj=None,token="",timeout=90): data=json.dumps(obj).encode() if obj is not None else None head={"Accept":"application/json"} if data is not None:head["Content-Type"]="application/json" if token:head["Authorization"]="Bearer "+token with urllib.request.urlopen(urllib.request.Request(origin+endpoint,data=data,headers=head,method=method),timeout=timeout) as r: return json.load(r) def graph(job): if job["model"] not in MODEL: raise ValueError("FLUX Schnell requires a validated official API workflow; use SDXL or SD1.5 until added") return { "4":{"class_type":"CheckpointLoaderSimple","inputs":{"ckpt_name":MODEL[job["model"]]}}, "6":{"class_type":"CLIPTextEncode","inputs":{"text":job["prompt"],"clip":["4",1]}}, "7":{"class_type":"CLIPTextEncode","inputs":{"text":job.get("negative",""),"clip":["4",1]}}, "5":{"class_type":"EmptyLatentImage","inputs":{"width":job["width"],"height":job["height"],"batch_size":1}}, "3":{"class_type":"KSampler","inputs":{"seed":job["seed"],"steps":job["steps"],"cfg":7,"sampler_name":"euler","scheduler":"normal","denoise":1,"model":["4",0],"positive":["6",0],"negative":["7",0],"latent_image":["5",0]}}, "8":{"class_type":"VAEDecode","inputs":{"samples":["3",0],"vae":["4",2]}}, "9":{"class_type":"SaveImage","inputs":{"filename_prefix":"WI-Local","images":["8",0]}} } def generate(job): queued=call(COMFY,"/prompt","POST",{"prompt":graph(job),"client_id":"wi-local-worker"}) pid=queued.get("prompt_id") if not pid:raise RuntimeError("ComfyUI workflow rejected: "+str(queued)[:200]) deadline=time.monotonic()+1500 while time.monotonic()8000000 or mime not in ("image/png","image/jpeg"):raise RuntimeError("Unexpected image format / over 8MB") return {"mime":mime,"image_base64":base64.b64encode(payload).decode("ascii")} raise RuntimeError("ComfyUI generation timed out (25 min)") def main(): if "--check" in sys.argv: print("ComfyUI reachable; API nodes:",len(call(COMFY,"/object_info"))) return if not WI.startswith("https://"):raise SystemExit("WI_IMAGE_URL must be the deployed HTTPS staging site origin") if len(TOKEN)<32:raise SystemExit("WI_IMAGE_WORKER_KEY missing; use the private Railway worker token") print("Local image worker polling",WI,flush=True) while True: try: job=call(WI,"/api/image-jobs/v1/worker/next","POST",{},TOKEN).get("job") if not job:time.sleep(10);continue print("Processing",job["id"],job["model"],flush=True) try: result=generate(job) call(WI,"/api/image-jobs/v1/worker/"+job["id"]+"/complete","POST",result,TOKEN,180) print("Completed",job["id"],flush=True) except Exception as e: print("Generation failure:",str(e),file=sys.stderr,flush=True) call(WI,"/api/image-jobs/v1/worker/"+job["id"]+"/fail","POST",{"error":str(e)[:280]},TOKEN) except KeyboardInterrupt:return except Exception as e: print("Connection issue:",str(e),file=sys.stderr,flush=True);time.sleep(20) if __name__=="__main__":main()