Python 驱动的 AI 艺术批量创作: 免费的Bing 绘图代码解析

这篇文章将深入分析一段 Python 代码,该代码利用 Bing 的 AI 绘图功能,即 bing 的 images/create,根据用户提供的文本提示生成图像。我们将详细探讨其工作原理、代码结构、使用的库和技术,并提出潜在的改进方向。

代码概述: AI 艺术创作的幕后推手

首先说明一下,代码不是我写的,来自于 github,但又忘记了链接和作者,所以无法提示开源项目和作者。

这段代码的核心目标是使用户能够利用 Bing 的 AI 能力创作图像。它通过模拟用户在 Bing 图片创建页面上的操作,发送请求获取生成的图像链接。

代码

import random 
from typing import Dict, List
import requests
from bs4 import BeautifulSoup
import re
import time
import json


bing="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 类:封装核心功能:

  • Image_Gen 类是代码的核心,封装了生成图像的所有功能。
    • __init__ 方法初始化 requests.Session 对象,设置请求头,并加载 cookies。
    • Generate 方法接受用户提供的文本提示,将其编码后构建请求 URL 和参数,发送 POST 请求到 Bing 服务器,然后解析响应获取生成的图像链接。

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 艺术创作领域将扮演更重要的角色。

THE END