File size: 5,449 Bytes
c3ec568
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import os
import time
import requests
import random
import json
import base64
from io import BytesIO
from PIL import Image
from dotenv import load_dotenv

load_dotenv()


class Prodia:
    def __init__(self, api_key, base=None):
        self.base = base or "https://api.prodia.com/v1"
        self.headers = {
            "X-Prodia-Key": api_key
        }

    def sd_controlnet(self, params):
        response = self._post(f"{self.base}/sd/controlnet", params)
        return response.json()

    def sd_transform(self, params):
        response = self._post(f"{self.base}/sd/transform", params)
        return response.json()

    def sd_generate(self, params):
        response = self._post(f"{self.base}/sd/generate", params)
        return response.json()

    def sdxl_generate(self, params):
        response = self._post(f"{self.base}/sdxl/generate", params)
        return response.json()

    def get_job(self, job_id):
        response = self._get(f"{self.base}/job/{job_id}")
        return response.json()

    def wait(self, job):
        job_result = job

        while job_result['status'] not in ['succeeded', 'failed']:
            time.sleep(0.25)
            job_result = self.get_job(job['job'])

        if job_result['status'] == 'failed':
            raise Exception("Job failed")

        return job_result

    def upload(self, file):
        files = {'file': open(file, 'rb')}
        img_id = requests.post(os.getenv("IMAGES_1"), files=files).json()['id']

        payload = {
            "content": "",
            "nonce": f"{random.randint(1, 10000000)}H9X42KSEJFNNH",
            "replies": [],
            "attachments":
                [img_id]
        }
        resp = requests.post(os.getenv("IMAGES_2"), json=payload, headers={"x-session-token": os.getenv("session-token")})
        return f"{os.getenv('IMAGES_1')}/{img_id}/{resp.json()['attachments'][0]['filename']}"

    def list_models(self):
        response = self._get(f"{self.base}/models/list")
        return response.json()

    def _post(self, url, params):
        headers = {
            **self.headers,
            "Content-Type": "application/json"
        }
        response = requests.post(url, headers=headers, data=json.dumps(params))

        if response.status_code != 200:
            raise Exception(f"Bad Prodia Response: {response.status_code}")

        return response

    def _get(self, url):
        response = requests.get(url, headers=self.headers)

        if response.status_code != 200:
            raise Exception(f"Bad Prodia Response: {response.status_code}")

        return response


def image_to_base64(image_path):
    # Open the image with PIL
    with Image.open(image_path) as image:
        # Convert the image to bytes
        buffered = BytesIO()
        image.save(buffered, format="PNG")  # You can change format to PNG if needed

        # Encode the bytes to base64
        img_str = base64.b64encode(buffered.getvalue())

    return img_str.decode('utf-8')  # Convert bytes to string


prodia_client = Prodia(api_key=os.getenv("PRODIA_X_KEY"))


def generate_sdxl(prompt, negative_prompt, model, steps, sampler, cfg_scale, seed):
    result = prodia_client.sdxl_generate({
        "prompt": prompt,
        "negative_prompt": negative_prompt,
        "model": model,
        "steps": steps,
        "sampler": sampler,
        "cfg_scale": cfg_scale,
        "seed": seed
    })

    job = prodia_client.wait(result)

    return job["imageUrl"]


def generate_sd(prompt, negative_prompt, model, steps, sampler, cfg_scale, width, height, seed, upscale):
    result = prodia_client.sd_generate({
        "prompt": prompt,
        "negative_prompt": negative_prompt,
        "model": model,
        "steps": steps,
        "sampler": sampler,
        "cfg_scale": cfg_scale,
        "seed": seed,
        "upscale": upscale,
        "width": width,
        "height": height
    })

    job = prodia_client.wait(result)

    return job["imageUrl"]


def transform_sd(image, model, prompt, denoising_strength, negative_prompt, steps, cfg_scale, seed, upscale, sampler):
    image_url = prodia_client.upload(image)
    result = prodia_client.sd_transform({
        "imageUrl": image_url,
        'model': model,
        'prompt': prompt,
        'denoising_strength': denoising_strength,
        'negative_prompt': negative_prompt,
        'steps': steps,
        'cfg_scale': cfg_scale,
        'seed': seed,
        'upscale': upscale,
        'sampler': sampler
    })

    job = prodia_client.wait(result)

    return job["imageUrl"]


def controlnet_sd(image, controlnet_model, controlnet_module, threshold_a, threshold_b, resize_mode, prompt, negative_prompt, steps, cfg_scale, seed, sampler, width, height):
    print(image)
    image_url = prodia_client.upload(image)
    result = prodia_client.sd_transform({
        "imageUrl": image_url,
        "controlnet_model": controlnet_model,
        "controlnet_module": controlnet_module,
        "threshold_a": threshold_a,
        "threshold_b": threshold_b,
        "resize_mode": int(resize_mode),
        "prompt": prompt,
        'negative_prompt': negative_prompt,
        'steps': steps,
        'cfg_scale': cfg_scale,
        'seed': seed,
        'sampler': sampler,
        "height": height,
        "width": width
    })

    job = prodia_client.wait(result)

    return job["imageUrl"]

def get_models():
    return prodia_client.list_models()