File size: 5,613 Bytes
3aed964
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import time

import aiohttp

from .base import Backend
from PIL import Image
import asyncio
import json
import traceback
import math
import zipfile
import io
import os
import aiofiles
import base64

from pathlib import Path

class AIDRAW(Backend):

    def __init__(self, count, payload, **kwargs):
        super().__init__(count=count, payload=payload, **kwargs)

        self.model = f"MidJourney"
        self.model_hash = "c7352c5d2f"
        self.logger = self.setup_logger('[MidJourney]')

        self.backend_url = self.config.midjourney['backend_url'][self.count]
        self.backend_name = self.config.backend_name_list[10]
        self.workload_name = f"{self.backend_name}-{self.config.midjourney['name'][self.count]}"

    async def heart_beat(self, id_):
        task_url = f"{self.backend_url}/mj/task/{id_}/fetch"

        while True:
            try:
                resp = await self.http_request("GET", task_url, format=True)
                status = resp.get('status')
                content = ''

                if status == "SUCCESS":
                    content = resp['imageUrl']
                    self.img_url.append(resp['imageUrl'])
                    self.logger.img(f"任务{id_}成功完成,图片URL:{resp['imageUrl']}")
                    return content

                elif status == "FAILED":
                    content = resp.get('failReason') or '未知原因'
                    self.logger.error(f"任务处理失败,原因:{content}")

                    raise Exception(f"任务处理失败,原因:{content}")

                elif status == "NOT_START":
                    content = '任务未开始'

                elif status == "IN_PROGRESS":
                    content = '任务正在运行'
                    if resp.get('progress'):
                        content += f",进度:{resp['progress']}"

                elif status == "SUBMITTED":
                    content = '任务已提交处理'

                elif status == "FAILURE":
                    fail_reason = resp.get('failReason') or '未知原因'
                    self.logger.error(f"任务处理失败,原因:{fail_reason}")
                    if "Banned prompt detected" in fail_reason:
                        await self.return_build_image("NSFW Prompt Detected")
                        return
                    else:
                        raise Exception(f"任务处理失败,原因:{content}")

                else:
                    content = status

                self.logger.info(f"任务{id_}状态:{content}")

                await asyncio.sleep(5)

            except Exception as e:
                self.logger.error(f"任务{id_}心跳监控出错: {str(e)}")
                raise


    async def update_progress(self):
        # 覆写函数
        pass

    async def get_shape(self):

        gcd = math.gcd(self.width, self.height)

        simplified_width = self.width // gcd
        simplified_height = self.height // gcd

        ar = f"{simplified_width}:{simplified_height}"

        return ar

    async def check_backend_usability(self):
        pass

    async def split_image(self):
        img = Image.open(io.BytesIO(self.img_btyes[0]))
        width, height = img.size

        half_width = width // 2
        half_height = height // 2

        coordinates = [(0, 0, half_width, half_height),
                       (half_width, 0, width, half_height),
                       (0, half_height, half_width, height),
                       (half_width, half_height, width, height)]

        images = [img.crop(c) for c in coordinates]

        images_bytes = [io.BytesIO() for _ in range(4)]
        base64_images = []

        for i in range(4):
            images[i].save(images_bytes[i], format='PNG')

            images_bytes[i].seek(0)
            base64_image = base64.b64encode(images_bytes[i].getvalue()).decode('utf-8')

            base64_images.append(base64_image)

        self.img_btyes += images_bytes
        self.img += base64_images

    # async def formating_to_sd_style(self):
    #
    #     await self.download_img()
    #     await self.split_image()
    #
    #     self.format_api_respond()
    #     self.result = self.build_respond

    async def posting(self):

        accept_ratio = await self.get_shape()

        ntags = f"--no {self.ntags}" if self.ntags else ""

        build_prompt = f"{self.tags} --ar {accept_ratio} --seed {self.seed}" + ' ' + ntags + ' '

        payload = {
            "prompt": build_prompt
        }

        if self.config.midjourney['auth_toekn'][self.count]:
            self.headers.update({"mj-api-secret": self.config.midjourney['auth_toekn'][self.count]})

        resp = await self.http_request(
            "POST",
            f"{self.backend_url}/mj/submit/imagine",
            headers=self.headers,
            content=json.dumps(payload),
            format=True
        )

        if resp.get('code') == 24:
            await self.return_build_image(text="NSFW Prompt Detected")

        elif resp.get('code') == 1:
            task_id = resp.get('result')
            self.task_id = task_id
            self.logger.info(f"任务提交成功,任务id: {task_id}")

            await self.heart_beat(task_id)
            await self.download_img()
            await self.split_image()

        self.format_api_respond()
        self.result = self.build_respond