这段代码的核心目标是利用户能够利用 Bing 的 AI 能力创作图像。它通过仿照用户在 Bing 图片创建页面上的操作,发送要求获取天生的图像链接。
代码import random from typing import Dict, Listimport requestsfrom bs4 import BeautifulSoupimport reimport timeimport jsonbing=34;https://www.bing.com"FORWARDED_IP = f"13.{random.randint(104, 107)}.{random.randint(0, 255)}.{random.randint(0, 255)}"HEADERS = { "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8,application/signed-exchange;v=b3;q=0.7", "accept-language": "en-US,en;q=0.9", "cache-control": "max-age=0", "content-type": "application/x-www-form-urlencoded", "referrer": "https://www.bing.com/images/create/", "origin": "https://www.bing.com", "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.63", "x-forwarded-for": FORWARDED_IP,}class Image_Gen: def __init__(self,all_cookies: List[Dict])-> None: self.session=requests.Session() self.session.headers=HEADERS for cookie in all_cookies: self.session.cookies.set(cookie["name"],cookie["value"]) self.quiet= False def Generate(self,prompt: str)-> list: url_encoded_prompt = requests.utils.quote(prompt) payload= "q="+url_encoded_prompt+"&qs=ds" urls=[f"{bing}/images/create?q={url_encoded_prompt}&rt={rt}&FORM=GENCRE" for rt in [4, 3]] for i in urls: response=self.session.post(i,allow_redirects=False, data=payload, timeout= 200) if response.status_code==302: break else: print("Error while generating. Error Code =" + str(response.status_code)) if "Location" in response.headers: id = response.headers["Location"].split("id=")[-1] else: print("Error: Location header not found in response.") return new_url=f"https://www.bing.com/images/create/async/results/{id}?q={url_encoded_prompt}" start_wait = time.time() while True: if int(time.time() - start_wait) > 200: print("timeout") response = self.session.get(new_url) if response.status_code != 200 or not response.text or response.text.find("errorMessage") != -1: time.sleep(1) continue else: break img_tags = BeautifulSoup(response.text, 'html.parser').find_all('img',{'class': 'mimg'}) links=[] for img in img_tags: l=img.get('src') l=re.sub(r'w=\d+&h=\d+&c=\d+&r=\d+&o=\d+&', '', l) links.append(l) return links if __name__ == "__main__": # 从 "cookies.json" 文件加载 cookies cookies = json.load(open(r"D:\wenjian\python\data\json\cookies.json")) image_gen = Image_Gen(cookies) # 调用Generate方法并传入prompt参数 prompt = "一只在用饭的猫" result = image_gen.Generate(prompt) # 打印结果 print(result)
代码解析: 步步深入理解事情机制
1. 初始化与环境设置:
代码首先导入必要的库:random, typing, requests, BeautifulSoup, re, time, json. random 用于天生随机 IP 地址; typing 用于类型提示,提高代码可读性和掩护性; requests 用于发送 HTTP 要求与 Bing 做事器交互; BeautifulSoup 用于解析 HTML 内容,提取图像链接; re 用于正则表达式操作,清理图像链接; time 用于计时,设置要求超时; json 用于加载 cookies 文件。代码定义了一些常量:bing (Bing 网站地址), FORWARDED_IP (假造的 IP 地址), HEADERS (HTTP 要求头). 假造 IP 地址和设置要求头是为了仿照真实用户访问,避免被 Bing 做事器识别为机器人。2. Image_Gen 类:封装核心功能:
3. 代码实行流程:
主程序首先从 "cookies.json" 文件加载 cookies。创建 Image_Gen 类的实例,并传入 cookies。调用 Generate 方法,传入文本提示 "一只在用饭的猫"。打印返回的图像链接列表。4. 代码亮点:
利用 BeautifulSoup 解析 HTML 内容,提取图像链接。利用正则表达式清理图像链接,去除冗余参数。设置要求超时,避免程序无限期等待。代码限定与改进建议: 优化与提升空间Cookies 依赖: 代码依赖于 "cookies.json" 文件中供应的 cookies,这可能会导致代码失落效,如果 Bing 变动了其网站构造或 cookies 机制。 建议:探索自动获取和更新 cookies 的方法,例如仿照登录过程或利用第三方库。缺点处理: 代码的缺点处理机制较为大略,只是大略地打印缺点信息。 建议:添加更完善的缺点处理机制,例如捕获特定类型的非常,并根据缺点类型采纳不同的处理方法。参数调度: 代码中一些参数,例如超时时间,可以根据实际情形进行调度。 建议: 许可用户自定义参数,例如超时时间、图像数量、图像尺寸等。功能扩展: 代码目前只能天生单张图像,可以扩展支持天生多张图像或不同风格的图像。 建议: 研究 Bing AI API,探索更多功能和参数,例如图像风格、图像尺寸、艺术家模拟等。总结: Python 驱动 AI 艺术创作的未来这段 Python 代码展示了利用编程措辞驱动 AI 艺术创作的可能性。通过深入理解代码的运作机制,我们可以更好地利用 Bing AI 绘图功能,创作出更具创意和个性化的作品。同时,代码的改进空间也预示着未来 Python 在 AI 艺术创作领域将扮演更主要的角色。