File size: 3,640 Bytes
6b796b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# This is an example that uses the websockets api to know when a prompt execution is done
# Once the prompt execution is done it downloads the images using the /history endpoint

import websocket  # NOTE: websocket-client (https://github.com/websocket-client/websocket-client)
import uuid
import json
import urllib.request
import urllib.parse
import requests
from typing import Union
from fastapi import FastAPI

app = FastAPI()

server_address = "http://127.0.0.1:8188"
client_id = str(uuid.uuid4())
session = requests.Session()


def queue_prompt(prompt):
    data = {"prompt": prompt, "client_id": client_id}
    # data = json.dumps(p).encode('utf-8')
    response = session.post("http://{}/prompt".format(server_address), json=data, headers={'User-Agent': 'Mozilla/5.0'})

    return json.loads(response.content)


def get_image(filename, subfolder, folder_type):
    data = {"filename": filename, "subfolder": subfolder, "type": folder_type}
    url_values = urllib.parse.urlencode(data)
    response = session.get("http://{}/view?{}".format(server_address, url_values),
                           headers={'User-Agent': 'Mozilla/5.0'})

    return response.content


def get_history(prompt_id):
    response = session.get("http://{}/history/{}".format(server_address, prompt_id),
                           headers={'User-Agent': 'Mozilla/5.0'})

    return json.loads(response.content)


def get_images(ws, prompt):
    global images_output
    prompt_id = queue_prompt(prompt)['prompt_id']
    output_images = {}
    while True:
        out = ws.recv()
        if isinstance(out, str):
            message = json.loads(out)
            if message['type'] == 'executing':
                data = message['data']
                if data['node'] is None and data['prompt_id'] == prompt_id:
                    break  # Execution is done
        else:
            continue  # previews are binary data

    history = get_history(prompt_id)[prompt_id]
    for o in history['outputs']:
        for node_id in history['outputs']:
            node_output = history['outputs'][node_id]
            if 'images' in node_output:
                images_output = []
                for image in node_output['images']:
                    image_data = get_image(image['filename'], image['subfolder'], image['type'])
                    images_output.append(image_data)
            output_images[node_id] = images_output

    return output_images


# load workflow from file
with open("ChangeBackground_v1_Compact_api (1).json", "r", encoding="utf-8") as f:
    prompt_texts = f.read()

prompt = json.loads(prompt_texts)
# set the text prompt for our positive CLIPTextEncode
# prompt["6"]["inputs"]["text"] = "masterpiece best quality man"

# set the seed for our KSampler node
# prompt["3"]["inputs"]["seed"] = 5

ws = websocket.WebSocket()
ws.connect("ws://{}/ws?clientId={}".format(server_address, client_id))


@app.get("/items")
def read_item(params: Union[str, None] = None):
    params = json.loads(params)
    for key in params:
        value = params[key]
        if key in prompt:
            if "prompt" in prompt[key]["inputs"]:
                prompt[key]["inputs"]["prompt"] = value
            elif "text" in prompt[key]["inputs"]:
                prompt[key]["inputs"]["text"] = value
            elif "image" in prompt[key]["inputs"]:
                prompt[key]["inputs"]["image"] = value

    images = get_images(ws, prompt)
    for node_id in images:
        for image_data in images[node_id]:
            from PIL import Image
            import io
            image = Image.open(io.BytesIO(image_data))
            image.show()