File size: 8,571 Bytes
6632cd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "059cca54-7257-44be-991f-85d83572666e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# keys管理\n",
    "\n",
    "keys = {\"pst-HldliYUSKyTUF4lmAPnMXd4PuK6Ff6nBxnf5QnHz4w5rw96jAqwFqDsK68vpGjxH\"}\n",
    "\n",
    "def get(key): # 读取key\n",
    "    global keys\n",
    "    return keys[key]\n",
    "\n",
    "def set(key, status): # 存在key 则设置\n",
    "    global keys\n",
    "    if status in [True,False]:\n",
    "        if key in keys:\n",
    "            keys[key] = status\n",
    "\n",
    "def add(key): # 添加key\n",
    "    global keys\n",
    "    if key not in keys:\n",
    "        keys[key] = True\n",
    "    save()\n",
    "\n",
    "def delete(key): # 删除key\n",
    "    global keys\n",
    "    del keys[key]\n",
    "    save()\n",
    "\n",
    "def save():\n",
    "    global keys\n",
    "    with open('keys.txt','w') as f:\n",
    "        f.write('\\n'.join(list(keys.keys())))\n",
    "\n",
    "def load():\n",
    "    global keys\n",
    "    with open('keys.txt','r') as f:\n",
    "        keys = {i:True for i in f.read().split('\\n') if i}\n",
    "\n",
    "load()\n",
    "\n",
    "# nai3绘画\n",
    "\n",
    "import requests, zipfile, os, random, time, shutil, urllib3, json\n",
    "urllib3.disable_warnings()\n",
    "\n",
    "IMAGE_URL = 'https://image.novelai.net/'#'https://image.goutou.cc/'#\n",
    "\n",
    "# 适配ai3参数\n",
    "def check_data(dict): \n",
    "    inp = {\n",
    "        \"model\": \"nai-diffusion-3\",\n",
    "        \"prompt\": \"\",\n",
    "        'img':'',\n",
    "        \"size\": \"832x1216\",\n",
    "        \"n_prompt\": \"lowres, {bad}, error, fewer, extra, missing, worst quality, jpeg artifacts, bad quality, watermark, unfinished, displeasing, chromatic aberration, signature, extra digits, artistic error, username, scan, [abstract]\",\n",
    "        \"steps\": \"28\",\n",
    "        \"scale\": \"5\",\n",
    "        \"auto\": False,\n",
    "        \"cfg_scale\": \"0\",\n",
    "        \"seed\": \"-1\",\n",
    "        \"sampler\": \"k_euler\",\n",
    "        \"SMEA\": False,\n",
    "        \"DYN\": False,\n",
    "        \"noise\": \"native\"\n",
    "    }\n",
    "\n",
    "    inp |= {k: v for k, v in dict.items() if k in ['model', 'prompt','img', 'size', 'n_prompt', 'steps', 'scale', 'auto', 'cfg_scale', 'seed', 'sampler', 'SMEA', 'DYN', 'noise']}\n",
    "\n",
    "    if int(inp['seed']) == -1:\n",
    "        inp['seed'] = random.randint(0,21474836)\n",
    "\n",
    "    data = {\n",
    "        \"input\":inp['prompt'], # 提示词\n",
    "        \"model\":inp['model'], # 模型\n",
    "        \"action\":\"generate\",\n",
    "        \"parameters\":{\n",
    "            \"params_version\":1,\n",
    "            \"width\":int(inp['size'].split('x')[0]), # 宽度\n",
    "            \"height\":int(inp['size'].split('x')[1]), # 高度\n",
    "            \"scale\":float(inp['scale']),# 提示词引导值\n",
    "            \"sampler\":inp['sampler'], # 采样器\n",
    "            \"steps\": int(inp['steps']), # 步数\n",
    "            \"seed\": int(inp['seed']),  # 种子\n",
    "            \"sm\":bool(inp['SMEA']), # SMEA\n",
    "            \"sm_dyn\":bool(inp['DYN']), # DYN\n",
    "            \"cfg_rescale\":float(inp['cfg_scale']), # 缩放提示词引导式\n",
    "            \"noise_schedule\":inp['noise'], # 噪声计划表\n",
    "            \"negative_prompt\":inp['n_prompt'], # 反向提示词\n",
    "        }\n",
    "    }\n",
    "\n",
    "    # 图生图\n",
    "    if inp['img'] != 'data:,' and inp['img'] != '':\n",
    "        data[\"action\"] = \"img2img\"\n",
    "        data[\"parameters\"][\"image\"] = inp['img'].split(',')[1] if ',' in inp['img'] else inp['img']\n",
    "        data[\"parameters\"][\"noise\"] = 0\n",
    "        data[\"parameters\"][\"strength\"] = 0.7\n",
    "        data[\"parameters\"][\"extra_noise_seed\"] = 3263049076\n",
    "        \n",
    "    return data\n",
    "\n",
    "# 提交任务\n",
    "def draw(prompt,apikey,savepath):\n",
    "    global IMAGE_URL\n",
    "    \n",
    "    # 开始计时\n",
    "    start_time = time.time()\n",
    "\n",
    "    print('API /nai3> 开始绘图')\n",
    "\n",
    "    try:\n",
    "        draw_data = check_data(prompt)\n",
    "    except Exception as e:\n",
    "        print('API /nai3> 参数错误',e)\n",
    "        return {'status': 'error', 'msg':'参数错误'}\n",
    "    \n",
    "    try:\n",
    "        response = requests.post(IMAGE_URL+'ai/generate-image', json=draw_data, headers={\n",
    "            \"Authorization\": \"Bearer \" + apikey,\n",
    "            \"Content-type\": \"application/json\",\n",
    "            \"Referer\": \"https://novelai.net/\",\n",
    "            \"User-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.6045.160 Safari/537.36\",\n",
    "        })\n",
    "    except:\n",
    "        print('API /nai3> 连接绘图服务器失败')\n",
    "        return {'status': 'error', 'msg':'连接绘图服务器失败'}\n",
    "\n",
    "    # 判断是否成功\n",
    "    try:\n",
    "        data = response.json()\n",
    "\n",
    "        # 绘图失败\n",
    "        if 'statusCode' in data and 'message' in data:\n",
    "            wrong = f'{data[\"statusCode\"]}: {data[\"message\"]}'\n",
    "\n",
    "            print(f'API /nai3> 绘图失败 {wrong}')\n",
    "            return {'status': 'error', 'msg': wrong}\n",
    "        else:\n",
    "            # 无法获取错误信息\n",
    "            wrong = '无法得到正确响应,请检查地址'\n",
    "\n",
    "            print(f'API /nai3> 绘图失败 {wrong}')\n",
    "            return {'status': 'error', 'msg': wrong}\n",
    "        \n",
    "    except:\n",
    "\n",
    "        # 绘画成功\n",
    "        print('API /nai3> 绘图成功')\n",
    "        try:\n",
    "            down_img(response.content,savepath)\n",
    "            tools.save_img(savepath,draw_data)\n",
    "            return {\n",
    "                'status' : 'ok',\n",
    "                'time' : str(time.time() - start_time)\n",
    "            }\n",
    "        except:\n",
    "            print('API /nai3> 图片转码失败')\n",
    "            return {'status': 'error', 'msg':'图片转码失败'}\n",
    "\n",
    "# 处理图片\n",
    "def down_img(content,savepath:str):\n",
    "\n",
    "    # 清理文件\n",
    "    if os.path.exists(savepath):\n",
    "        os.remove(savepath)\n",
    "    if os.path.exists(f'{savepath}.zip'):\n",
    "        os.remove(f'{savepath}.zip')\n",
    "    if os.path.exists(f'{savepath}-f'):\n",
    "        shutil.rmtree(f'{savepath}-f')\n",
    "\n",
    "    # 如果文件夹不存在,则创建\n",
    "    if not os.path.exists(savepath.replace(savepath.split('/')[-1],'')):\n",
    "        os.makedirs(savepath.replace(savepath.split('/')[-1],''))\n",
    "\n",
    "    try:\n",
    "        # 转得图片文件夹\n",
    "        with open(f'{savepath}.zip', 'wb') as f:\n",
    "            f.write(content)\n",
    "\n",
    "        with zipfile.ZipFile(f'{savepath}.zip', 'r') as zip_ref:\n",
    "            zip_ref.extractall(f'{savepath}-f')\n",
    "        os.remove(f'{savepath}.zip')\n",
    "        \n",
    "        print('API /nai3> 下载解压图片成功')\n",
    "    except:\n",
    "        print('API /nai3> 下载解压图片失败')\n",
    "        return {'status': 'error', 'msg':'下载解压图片失败'}\n",
    "\n",
    "    # 提取图片\n",
    "    os.rename(f'{savepath}-f/image_0.png', savepath)\n",
    "\n",
    "    shutil.rmtree(f'{savepath}-f')\n",
    "\n",
    "    print('API /nai3> 提取图片成功')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ef4ee159-3ca1-4b21-abda-f586dff8943d",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}