ChatGPT中API的试用
最近ChatGPT智能AI很火,可以写代码,DEBUG,写简历等等
上去查看了一下,是可以调用API的,本着学习的态度就是用这个款AI辅助我写了一个demo(本人原来对flask只懂一点点)
目录
- 0x01主页
- 0x02图片API
- 0x03上传图片
- 0x04调用的API自动保存
- 0x05上传视频
- 0x06日志功能
- 0x07目录结构
- 0x08APP.py
- 0x09Key.py
- 0x0A结语
先看效果:
0x01主页
主要功能是验证API,可以用默认的(考虑到多人使用,所以用自己的更好)
0x02图片API
主要功能就是自带的API,创建图片、变体图片、编辑图片
0x03上传图片
作为一个网站怎么能没有上传口 =。=
0x04调用的API自动保存
主要是第二部调用的api创建的图片等进行自动保存
0x05上传视频
上传视频,AI写的,真牛啊
0x06日志功能
AI还写了自动后台记录日志功能
0x07目录结构
0x08APP.py
@app.route('/')
def index():key = {"api":-1}if k != "":key["key"]=1else:key["key"]=0logger.info(f"[{request.remote_addr}]::[{request.method}]::{request.url}::{request.args}::<{key}>")return render_template('index.html', key=key)@app.route('/submit', methods=['POST'])
def submit():key = {"api":-1}if k != "":key["key"] = 1else:key["key"] = 0logger.info(f"[{request.remote_addr}]::[{request.method}]::{request.url}::{request.args}::<{key}>")return render_template('index.html', key=key)@app.route('/image')
def image1():key = {"key":0}logger.info(f"[{request.remote_addr}]::[{request.method}]::{request.url}::{request.args}::<{key}>")return render_template('image.html',key=key,key2=key,key3=key)@app.route('/text')
def text():key = -1filenames = os.listdir("static\\text\\")# 打印文件名items_gx = []for filename in filenames:items_gx.append(f"text/{filename}")logger.info(f"[{request.remote_addr}]::[{request.method}]::{request.url}::{request.args}::<{key}>")return render_template('text.html',key=key,items_gx=items_gx)@app.route('/test_api',methods=['POST'])
def test_api():key = {"key":1}timestamp = time.time()try:org = request.form['org']api = request.form['api_key']f = open("temp", "w", encoding="utf-8")f.write(api)f.close()openai.organization = orgopenai.api_key_path = "temp"api_dict[org] = apitry:k = openai.Model.list()key["api"]=1f = open("share-api/org", "a+", encoding="utf-8")f.write(f"[{timestamp}]{org}\n")f.close()f = open("share-api/api", "a+", encoding="utf-8")f.write(f"[{timestamp}]{api}\n")f.close()except:key["api"]=0openai.organization = "org-tuPuSBX5NRzKaE06CVvU2dHD"openai.api_key_path = "api_key.txt"logger.debug(f"[{request.remote_addr}]::[{request.method}]::{request.url}::{request.args}::<[{api_dict}>")return render_template('index.html', key=key)except Exception as e:logger.debug(f"[{request.remote_addr}]::[{request.method}]::{request.url}::{request.args}::<[{e}>")return e@app.route('/img_sub1',methods=['POST'])
def img_sub1():key ={"key":1}keyn = {"key": 0}items = []try:prompt = request.form['prompt']size = request.form['size']num = int(request.form['num'])if int(num) >10:for i in range(0,num,10):sleep(31)ret = openai.Image.create(prompt=prompt, n=10, size=size)for i in ret['data']:items.append(i['url'])else:ret = openai.Image.create(prompt=prompt, n=num, size=size)for i in ret['data']:items.append(i['url'])for i in items:md5_name = md5(i)response = requests.get(i)# 打开图片img = Image.open(BytesIO(response.content))img.save(f"{save_cimg}{md5_name}.png", optimize=True, quality=50)# urllib.request.urlretrieve(i, f"{save_cimg}{md5_name}.png")logger.info(f"[{request.remote_addr}]::[{request.method}]::{request.url}::{request.args}::<{key}>::<{keyn}>::<{items}>")return render_template('image.html', key=key,key2=keyn,key3=keyn, items=items)except openai.error.OpenAIError as e:stat = f"[{e.http_status}]{e.error}"logger.debug(f"[{request.remote_addr}]::[{request.method}]::{request.url}::{request.args}::<[{e.http_status}]{e.error}>")return stat@app.route('/img_sub2',methods=['POST'])
def img_sub2():key ={"key":1}keyn = {"key": 0}items = []file_src1 = ""file_src2 =""try:image = request.form['main']mask = request.form['mask']if image=="" or mask =="":image = file_src1mask = file_src2prompt = request.form['prompt']size = request.form['size']num = int(request.form['num'])if int(num) > 10:for i in range(0, num, 10):sleep(31)ret = openai.Image.create_edit(image=image,mask=mask,prompt=prompt, n=int(num), size=size)for i in ret['data']:items.append(i['url'])else:ret = openai.Image.create_edit(image=image,mask=mask,prompt=prompt, n=int(num), size=size)for i in ret['data']:items.append(i['url'])for i in items:md5_name = md5(i)response = requests.get(i)# 打开图片img = Image.open(BytesIO(response.content))img.save(f"{save_cimg}{md5_name}.png", optimize=True, quality=50)# urllib.request.urlretrieve(i, f"{save_cimg}{md5_name}.png")logger.info(f"[{request.remote_addr}]::[{request.method}]::{request.url}::{request.args}::<{key}>::<{keyn}>::<{items}>")return render_template('image.html',key=keyn, key2=key,key3=keyn,items2=items)except openai.error.OpenAIError as e:stat = f"[{e.http_status}]{e.error}"logger.debug(f"[{request.remote_addr}]::[{request.method}]::{request.url}::{request.args}::<[{e.http_status}]{e.error}>")return stat@app.route('/img_sub3',methods=['POST'])
def img_sub3():key ={"key":1}keyn = {"key": 0}items = []file_src3 = ""try:image = request.form['main']if image=="":image = file_src3size = request.form['size']num = int(request.form['num'])if int(num) > 10:for i in range(0, num, 10):sleep(31)ret = openai.Image.create_variation(image=image, n=int(num), size=size)for i in ret['data']:items.append(i['url'])else:ret = openai.Image.create_variation(image=image, n=int(num), size=size)for i in ret['data']:items.append(i['url'])for i in items:md5_name = md5(i)response = requests.get(i)# 打开图片img = Image.open(BytesIO(response.content))img.save(f"{save_cimg}{md5_name}.png", optimize=True, quality=50)# urllib.request.urlretrieve(i, f"{save_cimg}{md5_name}.png")logger.info(f"[{request.remote_addr}]::[{request.method}]::{request.url}::{request.args}::<{key}>::<{keyn}>::<{items}>")return render_template('image.html',key=keyn, key2=keyn, key3=key, items3=items)except openai.error.OpenAIError as e:stat = f"[{e.http_status}]{e.error}"logger.debug(f"[{request.remote_addr}]::[{request.method}]::{request.url}::{request.args}::<[{e.http_status}]{e.error}>")return stat@app.route('/upload_edit1', methods=['POST'])
def upload1():# 获取客户端上传的图片image = request.files['image']# 获取图片的名称image_name = image.filenamedirok= mkdir_date("img\\")if dirok != 0:# 保存图片到本地file_src1 = f"img\\{dirok}\\{image_name}"image.save(file_src1)logger.info(f"[{request.remote_addr}]::[{request.method}]::{request.url}::{request.args}::<{file_src1}>")return "上传成功!"return "上传失败!"@app.route('/upload_edit2', methods=['POST'])
def upload2():# 获取客户端上传的图片image = request.files['image']# 获取图片的名称image_name = image.filenamedirok= mkdir_date("img\\")if dirok != 0:# 保存图片到本地file_src2 = f"img\\{dirok}\\{image_name}"image.save(file_src2)logger.info(f"[{request.remote_addr}]::[{request.method}]::{request.url}::{request.args}::<{file_src2}>")return "上传成功!"return "上传失败!"@app.route('/upload_edit3', methods=['POST'])
def upload3():# 获取客户端上传的图片image = request.files['image']# 获取图片的名称image_name = image.filenamedirok= mkdir_date("img\\")if dirok != 0:# 保存图片到本地file_src3 = f"img\\{dirok}\\{image_name}"image.save(file_src3)logger.info(f"[{request.remote_addr}]::[{request.method}]::{request.url}::{request.args}::<{file_src3}>")return "上传成功!"return "上传失败!"@app.route('/gx_upload', methods=['POST'])
def gx_upload():key = 1filenames = os.listdir("static\\text\\")# 打印文件名items_gx = []for filename in filenames:items_gx.append(f"text/{filename}")try:# 获取客户端上传的图片image = request.files['image']# 获取图片的名称image_name = image.filenamefilename = md5(str(image_name))file_src_gx = f"static\\text\\{filename}.{image_name.split('.')[-1]}"image.save(file_src_gx)logger.info(f"[{request.remote_addr}]::[{request.method}]::{request.url}::{request.args}::<{key}::{file_src_gx}>")return render_template('text.html', key=key, items_gx=items_gx)except Exception as e:print(e)return render_template('text.html',key=0,items_gx=items_gx)if __name__ == '__main__':app.run(host="0.0.0.0", port=5001)
0x09Key.py
import os
from datetime import datetime
import hashlib
import openai
openai.organization = "org-xxxx"
openai.api_key_path = "api_key.txt"def mkdir_date(dir):nows = datetime.now()date_str = nows.strftime('%Y-%m-%d')try:# 创建文件夹os.mkdir(dir+date_str)return date_strexcept Exception as e:return date_strdef md5(str1):m = hashlib.md5()m.update(str1.encode('utf-8'))return str(m.hexdigest())
0x0A结语
对于一个只会一点点代码水平的人来说,这个AI也是够了,解决能力大于某度,过于强大
源码整合包:传送门
Demo地址:传送门(请勿攻击)