Datawhale X 魔搭 AI夏令营 第四期--AIGC文生图 task2笔记

先上图看连环画成果

 一直有个篮球总冠军,根据通义千问的文生图对话式生成8个连贯的文生图故事。通过生成的故事内容生成了下面的图片

  1. 男主正在练习打篮球 动漫风,连环画,一个黑色高个子帅气男生,穿着红色篮球服,正在篮球训练场上,练习投篮,专注地重复着动作,力求每个动作都达到标准,全身画面。

  2. 开始在休息室休息了 动漫风,连环画,男生坐在休息室的长椅上,手握水瓶,汗水从额头上滑落,眼神疲惫但充满坚毅,上半身特写,背景是休息室的墙壁和队友们的储物柜。

  3. 进入梦乡,梦到自己站在NBA球场上作为主力比赛 动漫风,连环画,男生闭眼躺在休息室,旁边是逐渐淡化的现实环境;梦境中,他穿着NBA球队的球衣,站在灯火辉煌的球场中央,观众席上人山人海,全身画面,正准备接球。

  4. 詹姆斯和库里等明星跟你一起并肩作战 动漫风,连环画,男生与勒布朗·詹姆斯和斯蒂芬·库里站在一起,三人并肩,眼神坚定,身穿各自球队的球衣,背景是紧张的比赛现场,全身画面,准备发起进攻。

  5. 大家合作非常默契,把对手打的找不到南北 动漫风,连环画,男生与队友们形成完美的配合,传球、跑位、防守,动作流畅,背景是对方队伍显得混乱,全场观众的欢呼声,全身画面,展示团队协作的力量。

  6. 最终赢得了比赛,得到了总冠军 动漫风,连环画,男生高举总冠军奖杯,队友们围绕在他周围,跳跃、拥抱庆祝胜利,背景是烟花绽放的夜空,全身画面,展现胜利的喜悦。

  7. 铃声响了,梦醒了 动漫风,连环画,男生突然坐起,眼神从迷茫变为清醒,手中还紧握着篮球,背景是安静的休息室,上半身特写,表现出从梦境回到现实的过程。

  8. 又回到了练习篮球的训练中 动漫风,连环画,男生重新出现在篮球场上,汗水再次浸湿了他的球衣,专注地练习着每一个动作,全身画面,背景是篮球架和球场,展现他的不懈努力。


    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
    
  • 1. 环境与依赖安装
    使用!pip命令安装一系列Python包,包括simple-aesthetics-predictor, data-juicer, peft, lightning, pandas, torchvision, 和DiffSynth-Studio。
    卸载并重新安装pytorch-lightning。
    2. 数据集加载与预处理
    从ModelScope加载名为lowres_anime的数据集,并将其保存到指定目录。
    遍历数据集,将图像转换为RGB格式并保存,同时构建包含图像路径和描述性文本的元数据,写入metadata.jsonl文件。
    3. 数据过滤与处理配置
    创建data_juicer配置文件,定义数据处理规则,如图像尺寸和长宽比过滤。
    使用dj-process命令行工具执行数据处理。
    4. 处理后数据导出与分析
    将处理后的数据读取到DataFrame中,保存为CSV文件。
    使用CLIP模型计算图像与文本的相似度得分。
    5. 自定义数据集与数据加载
    定义一个CustomDataset类,用于封装DataFrame中的图像和文本数据,以供模型使用。
    创建数据集实例和数据加载器。
    6. 模型预测
    使用CLIP模型对数据集进行预测,输出图像与文本的匹配概率。
    7. 图像生成
    使用StableDiffusionPipeline生成基于不同提示(prompt)的二次元图像。
    设置随机种子确保生成结果的可重复性,调整生成参数,保存生成的图像。
    8. 图像拼接展示
    加载之前生成的所有图像,将其拼接成一张大图,并调整大小以便展示。
    整个流程涵盖了从环境搭建、数据集加载与预处理、数据质量控制、模型预测到图像生成的一系列操作,旨在处理二次元风格的图像数据,实现图像分析和基于文本的图像生成。

    如针对某一部分觉得解释太粗,可通过上下文继续对话方式让通义千问继续对疑问部分更详细的介绍。

  • 浅尝scepter webui 

     网址为魔搭社区

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值