Datawhale X 魔搭 AI夏令营-AIGC文生图方向Task2笔记

打印 上一主题 下一主题

主题 1493|帖子 1493|积分 4494

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
目录

媒介
代码分析
​编辑
第一部分:安装和卸载依赖
第二部分:加载数据集
第三部分:数据预处理
第四部分:数据过滤
第五部分:数据整理
第六部分:模型评估
第七部分:创建PyTorch数据集
第八部分:图像生成
第九部分:组合生成的图像
代码修改 进阶提拔
1.修改图像尺寸——生成要求的尺寸
2.修改提示词(Prompt)——生成要求的画面
3.调解生成参数 ——调治图像精致度
5.设置随机种子——设置图像随机程度
6.修改图像的组合方式——改变排序、大小等


媒介

经过上一期task01的学习,我学习到了文生图的发展历程、文生图涉及到的干系知识点和重要名词、尝试通过baseline修改提示词并微调生成了属于自己的第一份图片。在第二阶段,我根据社区的资料进一步学习到了AI生图的前沿领域并且“从AI到AI”借助现在的大模型技能对baseline代码举行模块划分和明确,进一步对文生图的原理和并且呈现到该笔记中,同时尝试了scepter webui举行模型训练。
代码分析

下方展示的为baseline中的所有代码
  1. !pip install simple-aesthetics-predictor
  2. !pip install -v -e data-juicer
  3. !pip uninstall pytorch-lightning -y
  4. !pip install peft lightning pandas torchvision
  5. !pip install -e DiffSynth-Studio
  6. from modelscope.msdatasets import MsDataset
  7. ds = MsDataset.load(
  8.     'AI-ModelScope/lowres_anime',
  9.     subset_name='default',
  10.     split='train',
  11.     cache_dir="/mnt/workspace/kolors/data"
  12. )
  13. import json, os
  14. from data_juicer.utils.mm_utils import SpecialTokens
  15. from tqdm import tqdm
  16. os.makedirs("./data/lora_dataset/train", exist_ok=True)
  17. os.makedirs("./data/data-juicer/input", exist_ok=True)
  18. with open("./data/data-juicer/input/metadata.jsonl", "w") as f:
  19.     for data_id, data in enumerate(tqdm(ds)):
  20.         image = data["image"].convert("RGB")
  21.         image.save(f"/mnt/workspace/kolors/data/lora_dataset/train/{data_id}.jpg")
  22.         metadata = {"text": "二次元", "image": [f"/mnt/workspace/kolors/data/lora_dataset/train/{data_id}.jpg"]}
  23.         f.write(json.dumps(metadata))
  24.         f.write("\n")
  25. data_juicer_config = """
  26. # global parameters
  27. project_name: 'data-process'
  28. dataset_path: './data/data-juicer/input/metadata.jsonl'  # path to your dataset directory or file
  29. np: 4  # number of subprocess to process your dataset
  30. text_keys: 'text'
  31. image_key: 'image'
  32. image_special_token: '<__dj__image>'
  33. export_path: './data/data-juicer/output/result.jsonl'
  34. # process schedule
  35. # a list of several process operators with their arguments
  36. process:
  37.     - image_shape_filter:
  38.         min_width: 1024
  39.         min_height: 1024
  40.         any_or_all: any
  41.     - image_aspect_ratio_filter:
  42.         min_ratio: 0.5
  43.         max_ratio: 2.0
  44.         any_or_all: any
  45. """
  46. with open("data/data-juicer/data_juicer_config.yaml", "w") as file:
  47.     file.write(data_juicer_config.strip())
  48. !dj-process --config data/data-juicer/data_juicer_config.yaml
  49. import pandas as pd
  50. import os, json
  51. from PIL import Image
  52. from tqdm import tqdm
  53. texts, file_names = [], []
  54. os.makedirs("./data/data-juicer/output/images", exist_ok=True)
  55. with open("./data/data-juicer/output/result.jsonl", "r") as f:
  56.     for line in tqdm(f):
  57.         metadata = json.loads(line)
  58.         texts.append(metadata["text"])
  59.         file_names.append(metadata["image"][0])
  60. df = pd.DataFrame({"text": texts, "file_name": file_names})
  61. df.to_csv("./data/data-juicer/output/result.csv", index=False)
  62. df
  63. from transformers import CLIPProcessor, CLIPModel
  64. import torch
  65. model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
  66. processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
  67. images = [Image.open(img_path) for img_path in df["file_name"]]
  68. inputs = processor(text=df["text"].tolist(), images=images, return_tensors="pt", padding=True)
  69. outputs = model(**inputs)
  70. logits_per_image = outputs.logits_per_image  # this is the image-text similarity score
  71. probs = logits_per_image.softmax(dim=1)  # we can take the softmax to get the probabilities
  72. probs
  73. from torch.utils.data import Dataset, DataLoader
  74. class CustomDataset(Dataset):
  75.     def __init__(self, df, processor):
  76.         self.texts = df["text"].tolist()
  77.         self.images = [Image.open(img_path) for img_path in df["file_name"]]
  78.         self.processor = processor
  79.     def __len__(self):
  80.         return len(self.texts)
  81.     def __getitem__(self, idx):
  82.         inputs = self.processor(text=self.texts[idx], images=self.images[idx], return_tensors="pt", padding=True)
  83.         return inputs
  84. dataset = CustomDataset(df, processor)
  85. dataloader = DataLoader(dataset, batch_size=8)
  86. for batch in dataloader:
  87.     outputs = model(**batch)
  88.     logits_per_image = outputs.logits_per_image
  89.     probs = logits_per_image.softmax(dim=1)
  90.     print(probs)
  91. import torch
  92. from diffusers import StableDiffusionPipeline
  93. torch.manual_seed(1)
  94. pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v-1-4", torch_dtype=torch.float16)
  95. pipe = pipe.to("cuda")
  96. prompt = "二次元,一个紫色长发小女孩穿着粉色吊带漏肩连衣裙,在练习室练习唱歌,手持话筒"
  97. negative_prompt = "丑陋、变形、嘈杂、模糊、低对比度"
  98. guidance_scale = 4
  99. num_inference_steps = 50
  100. image = pipe(
  101.     prompt=prompt,
  102.     negative_prompt=negative_prompt,
  103.     guidance_scale=guidance_scale,
  104.     num_inference_steps=num_inference_steps,
  105.     height=1024,
  106.     width=1024,
  107. ).images[0]
  108. image.save("example_image.png")
  109. image
  110. from PIL import Image
  111. torch.manual_seed(1)
  112. image = pipe(
  113.     prompt="二次元,日系动漫,演唱会的观众席,人山人海,一个紫色短发小女孩穿着粉色吊带漏肩连衣裙坐在演唱会的观众席,舞台上衣着华丽的歌星们在唱歌",
  114.     negative_prompt="丑陋、变形、嘈杂、模糊、低对比度",
  115.     cfg_scale=4,
  116.     num_inference_steps=50, height=1024, width=1024,
  117. )
  118. image.save("1.jpg")
  119. torch.manual_seed(1)
  120. image = pipe(
  121.     prompt="二次元,一个紫色短发小女孩穿着粉色吊带漏肩连衣裙坐在演唱会的观众席,露出憧憬的神情",
  122.     negative_prompt="丑陋、变形、嘈杂、模糊、低对比度,色情擦边",
  123.     cfg_scale=4,
  124.     num_inference_steps=50, height=1024, width=1024,
  125. )
  126. image.save("2.jpg")
  127. torch.manual_seed(2)
  128. image = pipe(
  129.     prompt="二次元,一个紫色短发小女孩穿着粉色吊带漏肩连衣裙坐在演唱会的观众席,露出憧憬的神情",
  130.     negative_prompt="丑陋、变形、嘈杂、模糊、低对比度,色情擦边",
  131.     cfg_scale=4,
  132.     num_inference_steps=50, height=1024, width=1024,
  133. )
  134. image.save("3.jpg")
  135. torch.manual_seed(5)
  136. image = pipe(
  137.     prompt="二次元,一个紫色短发小女孩穿着粉色吊带漏肩连衣裙,对着流星许愿,闭着眼睛,十指交叉,侧面",
  138.     negative_prompt="丑陋、变形、嘈杂、模糊、低对比度,扭曲的手指,多余的手指",
  139.     cfg_scale=4,
  140.     num_inference_steps=50, height=1024, width=1024,
  141. )
  142. image.save("4.jpg")
  143. torch.manual_seed(0)
  144. image = pipe(
  145.     prompt="二次元,一个紫色中等长度头发小女孩穿着粉色吊带漏肩连衣裙,在练习室练习唱歌",
  146.     negative_prompt="丑陋、变形、嘈杂、模糊、低对比度",
  147.     cfg_scale=4,
  148.     num_inference_steps=50, height=1024, width=1024,
  149. )
  150. image.save("5.jpg")
  151. torch.manual_seed(1)
  152. image = pipe(
  153.     prompt="二次元,一个紫色长发小女孩穿着粉色吊带漏肩连衣裙,在练习室练习唱歌,手持话筒",
  154.     negative_prompt="丑陋、变形、嘈杂、模糊、低对比度",
  155.     cfg_scale=4,
  156.     num_inference_steps=50, height=1024, width=1024,
  157. )
  158. image.save("6.jpg")
  159. torch.manual_seed(7)
  160. image = pipe(
  161.     prompt="二次元,紫色长发少女,穿着黑色连衣裙,试衣间,心情忐忑",
  162.     negative_prompt="丑陋、变形、嘈杂、模糊、低对比度",
  163.     cfg_scale=4,
  164.     num_inference_steps=50, height=1024, width=1024,
  165. )
  166. image.save("7.jpg")
  167. torch.manual_seed(0)
  168. image = pipe(
  169.     prompt="二次元,紫色长发少女,穿着黑色礼服,连衣裙,在台上唱歌",
  170.     negative_prompt="丑陋、变形、嘈杂、模糊、低对比度",
  171.     cfg_scale=4,
  172.     num_inference_steps=50, height=1024, width=1024,
  173. )
  174. image.save("8.jpg")
  175. import numpy as np
  176. from PIL import Image
  177. images = [np.array(Image.open(f"{i}.jpg")) for i in range(1, 9)]
  178. image = np.concatenate([
  179.     np.concatenate(images[0:2], axis=1),
  180.     np.concatenate(images[2:4], axis=1),
  181.     np.concatenate(images[4:6], axis=1),
  182.     np.concatenate(images[6:8], axis=1),
  183. ], axis=0)
  184. image = Image.fromarray(image).resize((1024, 2048))
  185. image
复制代码


第一部分:安装和卸载依赖

   使用!pip命令安装和卸载所需的Python包。
  第二部分:加载数据集

   使用ModelScope库加载名为lowres_anime的数据集,并将其保存到指定路径。
  第三部分:数据预处理

   将数据会合的图像转换为RGB格式,并将每张图像及对应的标签(文本形貌)写入到JSONL文件中,为后续的数据处理做预备。
  第四部分:数据过滤

   创建设置文件data_juicer_config.yaml,界说数据处理的参数和流程。
  使用data-juicer工具根据设置文件对数据举行过滤,比方筛选出特定尺寸和宽高比的图像。
  第五部分:数据整理

   读取经过过滤后的数据,将图像路径和对应的文本形貌存储到Pandas DataFrame中,并保存为CSV文件。
  第六部分:模型评估

   加载CLIP模型和处理器,并使用它们来计算图像和文本之间的相似性得分。
  第七部分:创建PyTorch数据集

   界说一个自界说的PyTorch数据集类CustomDataset,用于加载图像和文本数据。
  创建数据加载器DataLoader,以便在训练过程中高效地迭代数据集。
  第八部分:图像生成

   使用StableDiffusionPipeline从预训练模型生成图像。
  根据不同的提示(prompt)和负面提示(negative prompt),生成多张具有特定内容的二次元风格图像。
  第九部分:组合生成的图像

   将生成的图像合并成一张大图,并调解大小。
  代码修改 进阶提拔

随着现在大模型技能的飞速发展,各种制品AI生图工具变得越来越遍及和强盛。但是自界说代码提仍然具有一些无法取代的长处,首先就是我们通过阅读和逐步实行代码的过程中可以增加我们对AI生图底层原理的相识并举行实验和创新,而不受限于预设软件的功能和限制,并且我们可以根据自己的需求正确调解数据处理流程、模型参数和生成设置,从而实现更精细的控制和优化。这种灵活性和可扩展性使得代码在我哦们的研究和开发阶段尤为宝贵,可以或许满意更专业和个性化的需求。
因此接下来我们先容代码中可以简朴举行进一步修改的部分,从而生成更加符合自己要求的优质图像
1.修改图像尺寸——生成要求的尺寸

在生成图像的部分,我们可以设置height和width参数来改变输出图像的尺寸。
  1. # 修改高度和宽度
  2. image = pipe(
  3.     prompt=prompt,
  4.     negative_prompt=negative_prompt,
  5.     guidance_scale=guidance_scale,
  6.     num_inference_steps=num_inference_steps,
  7.     height=1024,  # 设置高度
  8.     width=1024,   # 设置宽度
  9. ).images[0]
复制代码
2.修改提示词(Prompt)——生成要求的画面

该部分即task1中提到的我们可以通过更改prompt变量的内容,你控制生成图像的主题和风格比方,更改形貌人物的细节大概配景情况等,从而生成符合自己要求的图片。
  1. # 更改prompt
  2. prompt = "二次元,一个紫色长发小女孩穿着粉色吊带漏肩连衣裙,在练习室练习唱歌,手持话筒"
复制代码
  1. # 更改negative_prompt
  2. negative_prompt = "丑陋、变形、嘈杂、模糊、低对比度"
复制代码
须要注意的是在我们实际使用提示词时要只管做到详细明确(使用简朴直白的语言,AI可能不完全明确某些复杂的语言布局或文化隐喻),逻辑连贯,思量上下文,思量生成模型的能力。在生成图片后不断测试和调解,根据反馈不断修改提示词,最终得到自己满意的图片。
3.调解生成参数 ——调治图像精致度

  1. # 调整生成参数
  2. guidance_scale = 4
  3. num_inference_steps = 50
复制代码
注:guidance_scale为引导比例,较高的值会使生成的图像更符合提示。
num_inference_steps为推理步数,更多的步数通常会产生更精细的结果,但也会增加生成时间。
5.设置随机种子——设置图像随机程度

假如使生成结果可重复,可以设置固定的随机种子。这样每次运行雷同的代码都会得到雷同的结果。
  1. # 设置随机种子
  2. torch.manual_seed(1)
复制代码
  在编程中,"随机种子"(random seed)是用来初始化伪随机数生成器的一个初始值。设置随机种子可以让所谓的“随机”过程可重复。当你使用雷同的种子值初始化随机数生成器时,无论何时运行程序,它都会产生雷同的随机数序列。
  在PyTorch等机器学习框架中,设置随机种子是非常重要的,特别是在开发和调试过程中。这可以确保实验的可重复性,即每次运行雷同的代码片断时,模型初始化的权重、数据集的划分以及任何其他依赖随机性的部分都将保持一致。
  6.修改图像的组合方式——改变排序、大小等

  1. # 修改图像组合方式
  2. images = [np.array(Image.open(f"{i}.jpg")) for i in range(1, 9)]
  3. image = np.concatenate([
  4.     np.concatenate(images[0:2], axis=1),
  5.     np.concatenate(images[2:4], axis=1),
  6.     np.concatenate(images[4:6], axis=1),
  7.     np.concatenate(images[6:8], axis=1),
  8. ], axis=0)
  9. image = Image.fromarray(image).resize((1024, 2048))
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

大连全瓷种植牙齿制作中心

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表