DataWhale夏令营第四期魔搭- AIGC方向 task02笔记

一、AI生图

1、AIGC是通过人工智能技术自动生成内容的生产方式,很早就有专家指出,AIGC将是未来人工智能的重点方向,也将改造相关行业和领域生产内容的方式。

二、AI生图的发展:

2、最早的AI生图可追溯到20世纪70年代,当时由艺术家哈罗德·科恩发明AARON,可通过机械臂输出作画。

现在AI生图模型大多基于深度神经网络基础上的训练,最早追溯到2012年吴恩达训练出的能生成‘‘猫脸’’的模型;

2015年,谷歌推出了‘‘深梦’’图像生成工具,类似一个高级滤镜,可以基于给定的图片生成梦幻般图片;

2021年1月OpenAI推出DALL-E模型,能直接从文本提示‘‘按需创造’’风格多样的图形设计。

3、AI生图的缺点:

AI生图的天主教教皇身穿羽绒服的图片在网上疯传,以及特朗普被捕的图片,骗过了很多网友;

国际上颇有影响力的摄影奖项之一‘‘2023年索尼世界摄影奖’’的作品是由AI合成的,而获奖摄影师也拒接接受该奖项;

往前一年,AI生图还不会画手;不少文章中可以看到AI翻车的场面。

4、了解AI生图的意义:

对于普通人来说,可以避免被AI场景欺骗,并且简单使用AI绘图。

对于工作者来说:可以利用AI生图的工具完成自己所需的工作。

三、通义千问

(前面我们已经跑通了baseline,对baseline也有了基本了解,接下来我们将对baseline有一个更深入的了解然后我们会学习如何用AI来提升我们的自学能力,从而帮助大家在后面的学习工作中如何从容迎接各种挑战。)

下面是通义千问的自我介绍

下面是通义千问编程能力的介绍

四、精读baseline

(在task1中,我们跟着流程走,跑完baseline似乎并无大碍,但具体每一个代码是干什么的我们还是一脸懵,下面我们可以借助通义千问解读这些代码)

1、文生图的框架结构

2、baseline的实例代码

!pip install simple-aesthetics-predictor
 
!pip install -v -e data-juicer
 
!pip uninstall pytorch-lightning -y
!pip install peft lightning pandas torchvision
 
!pip install -e DiffSynth-Studio
 
from modelscope.msdatasets import MsDataset
 
ds = MsDataset.load(
    'AI-ModelScope/lowres_anime',
    subset_name='default',
    split='train',
    cache_dir="/mnt/workspace/kolors/data"
)
 
import json, os
from data_juicer.utils.mm_utils import SpecialTokens
from tqdm import tqdm
 
 
os.makedirs("./data/lora_dataset/train", exist_ok=True)
os.makedirs("./data/data-juicer/input", exist_ok=True)
with open("./data/data-juicer/input/metadata.jsonl", "w") as f:
    for data_id, data in enumerate(tqdm(ds)):
        image = data["image"].convert("RGB")
        image.save(f"/mnt/workspace/kolors/data/lora_dataset/train/{data_id}.jpg")
        metadata = {"text": "二次元", "image": [f"/mnt/workspace/kolors/data/lora_dataset/train/{data_id}.jpg"]}
        f.write(json.dumps(metadata))
        f.write("\n")
 
data_juicer_config = """
# global parameters
project_name: 'data-process'
dataset_path: './data/data-juicer/input/metadata.jsonl'  # path to your dataset directory or file
np: 4  # number of subprocess to process your dataset
text_keys: 'text'
image_key: 'image'
image_special_token: '<__dj__image>'
export_path: './data/data-juicer/output/result.jsonl'
# process schedule
# a list of several process operators with their arguments
process:
    - image_shape_filter:
        min_width: 1024
        min_height: 1024
        any_or_all: any
    - image_aspect_ratio_filter:
        min_ratio: 0.5
        max_ratio: 2.0
        any_or_all: any
"""
with open("data/data-juicer/data_juicer_config.yaml", "w") as file:
    file.write(data_juicer_config.strip())
 
!dj-process --config data/data-juicer/data_juicer_config.yaml
 
import pandas as pd
import os, json
from PIL import Image
from tqdm import tqdm
 
 
texts, file_names = [], []
os.makedirs("./data/data-juicer/output/images", exist_ok=True)
with open("./data/data-juicer/output/result.jsonl", "r") as f:
    for line in tqdm(f):
        metadata = json.loads(line)
        texts.append(metadata["text"])
        file_names.append(metadata["image"][0])
 
df = pd.DataFrame({"text": texts, "file_name": file_names})
df.to_csv("./data/data-juicer/output/result.csv", index=False)
 
df
 
from transformers import CLIPProcessor, CLIPModel
import torch
 
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
 
images = [Image.open(img_path) for img_path in df["file_name"]]
inputs = processor(text=df["text"].tolist(), images=images, return_tensors="pt", padding=True)
 
outputs = model(**inputs)
logits_per_image = outputs.logits_per_image  # this is the image-text similarity score
probs = logits_per_image.softmax(dim=1)  # we can take the softmax to get the probabilities
 
probs
 
from torch.utils.data import Dataset, DataLoader
 
class CustomDataset(Dataset):
    def __init__(self, df, processor):
        self.texts = df["text"].tolist()
        self.images = [Image.open(img_path) for img_path in df["file_name"]]
        self.processor = processor
 
    def __len__(self):
        return len(self.texts)
 
    def __getitem__(self, idx):
        inputs = self.processor(text=self.texts[idx], images=self.images[idx], return_tensors="pt", padding=True)
        return inputs
 
dataset = CustomDataset(df, processor)
dataloader = DataLoader(dataset, batch_size=8)
 
for batch in dataloader:
    outputs = model(**batch)
    logits_per_image = outputs.logits_per_image
    probs = logits_per_image.softmax(dim=1)
    print(probs)
 
import torch
from diffusers import StableDiffusionPipeline
 
torch.manual_seed(1)
pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v-1-4", torch_dtype=torch.float16)
pipe = pipe.to("cuda")
 
prompt = "二次元,一个紫色长发小女孩穿着粉色吊带漏肩连衣裙,在练习室练习唱歌,手持话筒"
negative_prompt = "丑陋、变形、嘈杂、模糊、低对比度"
guidance_scale = 4
num_inference_steps = 50
 
image = pipe(
    prompt=prompt,
    negative_prompt=negative_prompt,
    guidance_scale=guidance_scale,
    num_inference_steps=num_inference_steps,
    height=1024,
    width=1024,
).images[0]
 
image.save("example_image.png")
image
 
from PIL import Image
 
torch.manual_seed(1)
image = pipe(
    prompt="二次元,日系动漫,演唱会的观众席,人山人海,一个紫色短发小女孩穿着粉色吊带漏肩连衣裙坐在演唱会的观众席,舞台上衣着华丽的歌星们在唱歌",
    negative_prompt="丑陋、变形、嘈杂、模糊、低对比度",
    cfg_scale=4,
    num_inference_steps=50, height=1024, width=1024,
)
image.save("1.jpg")
 
torch.manual_seed(1)
image = pipe(
    prompt="二次元,一个紫色短发小女孩穿着粉色吊带漏肩连衣裙坐在演唱会的观众席,露出憧憬的神情",
    negative_prompt="丑陋、变形、嘈杂、模糊、低对比度,色情擦边",
    cfg_scale=4,
    num_inference_steps=50, height=1024, width=1024,
)
image.save("2.jpg")
 
torch.manual_seed(2)
image = pipe(
    prompt="二次元,一个紫色短发小女孩穿着粉色吊带漏肩连衣裙坐在演唱会的观众席,露出憧憬的神情",
    negative_prompt="丑陋、变形、嘈杂、模糊、低对比度,色情擦边",
    cfg_scale=4,
    num_inference_steps=50, height=1024, width=1024,
)
image.save("3.jpg")
 
torch.manual_seed(5)
image = pipe(
    prompt="二次元,一个紫色短发小女孩穿着粉色吊带漏肩连衣裙,对着流星许愿,闭着眼睛,十指交叉,侧面",
    negative_prompt="丑陋、变形、嘈杂、模糊、低对比度,扭曲的手指,多余的手指",
    cfg_scale=4,
    num_inference_steps=50, height=1024, width=1024,
)
image.save("4.jpg")
 
torch.manual_seed(0)
image = pipe(
    prompt="二次元,一个紫色中等长度头发小女孩穿着粉色吊带漏肩连衣裙,在练习室练习唱歌",
    negative_prompt="丑陋、变形、嘈杂、模糊、低对比度",
    cfg_scale=4,
    num_inference_steps=50, height=1024, width=1024,
)
image.save("5.jpg")
 
torch.manual_seed(1)
image = pipe(
    prompt="二次元,一个紫色长发小女孩穿着粉色吊带漏肩连衣裙,在练习室练习唱歌,手持话筒",
    negative_prompt="丑陋、变形、嘈杂、模糊、低对比度",
    cfg_scale=4,
    num_inference_steps=50, height=1024, width=1024,
)
image.save("6.jpg")
 
torch.manual_seed(7)
image = pipe(
    prompt="二次元,紫色长发少女,穿着黑色连衣裙,试衣间,心情忐忑",
    negative_prompt="丑陋、变形、嘈杂、模糊、低对比度",
    cfg_scale=4,
    num_inference_steps=50, height=1024, width=1024,
)
image.save("7.jpg")
 
torch.manual_seed(0)
image = pipe(
    prompt="二次元,紫色长发少女,穿着黑色礼服,连衣裙,在台上唱歌",
    negative_prompt="丑陋、变形、嘈杂、模糊、低对比度",
    cfg_scale=4,
    num_inference_steps=50, height=1024, width=1024,
)
image.save("8.jpg")
 
import numpy as np
from PIL import Image
 
 
images = [np.array(Image.open(f"{i}.jpg")) for i in range(1, 9)]
image = np.concatenate([
    np.concatenate(images[0:2], axis=1),
    np.concatenate(images[2:4], axis=1),
    np.concatenate(images[4:6], axis=1),
    np.concatenate(images[6:8], axis=1),
], axis=0)
image = Image.fromarray(image).resize((1024, 2048))
image

我们可以询问通义来解读

你是一个优秀的python开发工程师,现在我们需要你帮我们分析这个代码的主体框架,你需要把代码按照工作流分成几部分,用中文回答我的问题。{此处替换前面的代码}

我们还可以让通义逐行解析我们的代码

 

你是一个优秀的python开发工程师,现在我们需要你帮我们逐行分析这个代码,用中文回答我的问题。{此处替换前面的代码}

 

如果代码还有疑问,我们可以在逐行解析的页面后继续追问

 

我对其中{替换成你的问题}还是不太理解,给我再详细介绍一下(图片就先不展示了对)

五、实战演练--基于话剧的连环画制作

1、数据准备

2、话剧场景

3、执行task1的30分钟跑通baseline即可

4、提示词修改

双击进入baseline文件,找到生成图像的版块,依次替换8张图片的正向提示词和反向提示词即可

5、结果展图

(我就展示下自己跑的吧,教程图片大家应该都看过)

6、测试美学打分

task2到这了也结束了,大家task3再见了,学习难度在增加,希望大家一起加油哦!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值