File size: 3,938 Bytes
910955f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"""Model-free adapter: readiness requires a real fixed-schedule warmup image."""
import hashlib, io, json, os, pathlib, runpy, sys, threading, time, urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
# The producer places reference_workflow.py beside this adapter. LPK injection
# evaluates that source first in this namespace, before executing this module.
STATE={'ready':False,'model':MODEL,'schedule':list(SIGMAS),'phase':'starting'}
PORT=int(os.environ.get('AIPOD_COMFY_PORT','8188'))
READY_PORT=int(os.environ.get('AIPOD_READY_PORT','8190'))
BASE='http://127.0.0.1:'+str(PORT)
def request(path,body=None):
    data=None if body is None else json.dumps(body).encode()
    req=urllib.request.Request(BASE+path,data=data,headers={'Content-Type':'application/json'})
    with urllib.request.urlopen(req,timeout=30) as response:return json.loads(response.read())
def warmup():
    deadline=time.monotonic()+1800
    try:
        while time.monotonic()<deadline:
            try:request('/system_stats');break
            except Exception:time.sleep(2)
        else:raise TimeoutError('Image service startup timed out')
        STATE['phase']='loading_weights'
        # No caller-supplied commands, downloads or mutable dependencies.
        result=request('/prompt',{'prompt':workflow('A red ceramic teapot on a white table, photograph.',width=256,height=256,seed=42,output_prefix='startup/warmup')})
        prompt_id=result['prompt_id']
        while time.monotonic()<deadline:
            row=request('/history/'+prompt_id).get(prompt_id)
            if row:
                if row.get('status',{}).get('status_str')=='error':raise RuntimeError('Warmup inference failed; see device service logs')
                saved=row.get('outputs',{}).get('8',{}).get('images',[])
                if saved:
                    from PIL import Image, ImageStat
                    dest=pathlib.Path('/cache/output')/saved[0].get('subfolder','')/saved[0]['filename']
                    with Image.open(dest) as image:
                        rgb=image.convert('RGB')
                        if image.size!=(256,256) or max(ImageStat.Stat(rgb).stddev)<1:raise RuntimeError('Warmup returned an invalid image')
                        STATE['warmupPixelSha256']=hashlib.sha256(rgb.tobytes()).hexdigest()
                    STATE.update(ready=True,phase='ready');return
            time.sleep(1)
        raise TimeoutError('Model warmup timed out')
    except Exception as exc:
        STATE.update(phase='failed',error=str(exc));print('Readiness warmup failed:',exc,flush=True)
class Health(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path!='/ready':self.send_error(404);return
        payload=json.dumps(STATE).encode();self.send_response(200 if STATE['ready'] else 503)
        self.send_header('Content-Type','application/json');self.send_header('Content-Length',str(len(payload)));self.end_headers();self.wfile.write(payload)
    def log_message(self,*args):pass
def main():
    for folder in ('input','output','temp','user','home','cache','torch'):pathlib.Path('/cache',folder).mkdir(parents=True,exist_ok=True)
    os.environ.update(HF_HUB_OFFLINE='1',TRANSFORMERS_OFFLINE='1',HF_DATASETS_OFFLINE='1',PYTHONDONTWRITEBYTECODE='1',HOME='/cache/home',XDG_CACHE_HOME='/cache/cache',TORCH_HOME='/cache/torch')
    server=ThreadingHTTPServer(('0.0.0.0',READY_PORT),Health)
    threading.Thread(target=server.serve_forever,daemon=True).start()
    threading.Thread(target=warmup,daemon=True).start()
    os.chdir('/opt/ComfyUI');sys.path.insert(0,'/opt/ComfyUI')
    sys.argv=['main.py','--listen','0.0.0.0','--port',str(PORT),'--disable-dynamic-vram','--output-directory','/cache/output','--input-directory','/cache/input','--temp-directory','/cache/temp','--user-directory','/cache/user']+sys.argv[1:]
    runpy.run_path('/opt/ComfyUI/main.py',run_name='__main__')
if __name__=='__main__':main()