如何用Stable Diffusion让书中的人物更加真实

如何用Stable Diffusion让书中的人物更加真实

简介

Chroma是AI原生的开源嵌入数据库。Chroma通过为LLMs提供知识、事实和技能的插件,使建立LLM应用程序变得简单。

Cohere,是一个允许你只用几行代码就能建立人工智能驱动的应用程序的平台。Cohere的API允许你建立广泛的应用程序,包括聊天机器人、问题回答系统和总结工具。

Stable Diffusion,是一个新的生成模型,只需一次前向传递就能生成高分辨率的图像。

我们要做什么?

在本教程中,我将向你们展示如何使用Chroma DB和Cohere,来使用Stable Diffusion生成一个更加真实的角色。

为了使它更清晰易懂,让我把本教程分成两部分:

  • 第一部分–获得Stable Diffusion提示词。在这一部分,我们将通过Chroma DB和Cohere LLM。我们将加载文件,把它分成小块,用Cohere嵌入它们,然后我们将用Chroma查询数据库,得到提示词,在第二部分使用。
  • 第二部分–使用Stable Diffusion生成图像。在这一部分中,我们将通过Stable Diffusion SDK并实现代码,根据我们在第一部分中从Chroma DB得到的提示词生成图像。

学习成果

  • 如何使用谷歌Colab。
  • 熟悉Chroma、Cohere和Stable Diffusion。
  • 如何使用Cohere LLM来嵌入大文件。
  • 如何使用Cohere嵌入。
  • 如何使用Chroma来存储嵌入物。
  • 如何使用Chroma来查询数据库。
  • 如何使用Stable Diffusion SDK生成图像,并使书中的人物角色栩栩如生。

前提条件

要使用Cohere的嵌入,我们需要API密钥。进入Cohere,在右上角点击TRY NOW ,登录或创建一个账户。一旦你创建了一个账户,你将被转到仪表板。点击左侧边栏上的API Keys 。复制API密钥并将其保存在安全的地方。

Cohere Dashboard
Cohere仪表板
Cohere API Key
Cohere API密钥

要使用Stable Diffusion,我们需要API密钥。进入Dream Studio,注册一个账户,就可以得到你的API密钥。一旦你创建了一个账户,点击 “我 “就会被带到你的API Key。复制API密钥并将其保存在安全的地方。

Stable Diffusion API Key
Stable Diffusion API Key

不需要,需要有使用谷歌Colab的知识。我将指导你完成整个过程。

开始使用

创建一个新的项目

让我们从在Google Colab中创建新的笔记本开始。进入GoogleColab>File 并点击New notebook

Creating new Notebook in Google Colab
在Google Colab中创建新的笔记本

它将在一个新的标签中打开一个新的笔记本,通过点击Untitled0 ,给它起一个名字,并把它重命名为Chroma Stable Diffusion Tutorial 或任何你想要的东西。

很好,我们已经准备好开始CODING了!。

安装所需

添加新的code cell 。你可以通过点击+ Code 按钮或通过快捷方式CMD/CTRL + M B

安装必要的库,我们将在整个教程中使用这些库:

!pip install chromadb
!pip install langchain
!pip install pymupdf
!pip install cohere
!pip install stability-sdk

点击Run 按钮或CMD/CTRL + Enter ,它将运行活动的code cell 并花几分钟时间安装所有必要的库。请确保你有稳定的网络连接。

现在,如果一切都安装正确,我们可以进入下一步。

导入所需

添加新的code cell

这里我们将导入所有必要的库,copy/paste 以下几行代码:

from langchain.vectorstores import Chroma  # Chroma vector store
from langchain.embeddings import CohereEmbeddings  # Cohere embeddings
from langchain.text_splitter import RecursiveCharacterTextSplitter  # Recursive character text splitter
from langchain.llms import Cohere  # Cohere LLM
from langchain.chains import VectorDBQA  # VectorDBQA chain
from langchain.document_loaders import PyMuPDFLoader  # PyMuPDF document loaders. Read more: https://pymupdf.readthedocs.io/en/latest/
import os
import io
import warnings
from PIL import Image
from stability_sdk import client  # Stability SDK
import stability_sdk.interfaces.gooseai.generation.generation_pb2 as generation

点击RunCMD/CTRL + Enter

当你运行该单元时,你可能会看到一个warning message/messages 。不要担心它。我们可以忽略它。

注意:在运行code cell ,你不需要每次都保存笔记本,Google Colab会自动为你保存它。但是,如果你想手动保存它,你可以通过点击File >Save 或者通过快捷键CMD/CTRL + S

导出环境变量:

添加新的code cell

os.environ["COHERE_API_KEY"] = "key-goes-here"

os.environ['STABILITY_HOST'] = 'grpc.stability.ai:443'  # Host URL should not be prepended with "https" nor should it have a trailing slash.
os.environ["STABILITY_KEY"] = "key-goes-here"

点击RunCMD/CTRL + Enter

第一部分 – 获取Stable Diffusion提示词

首先,让我们快速将书上传到Google Colab。在本教程中,我们将使用Harry Potter and the Sorcerer's Stone 。。

之后,下载回到Google Colab,进入屏幕左侧的Files 标签,点击Upload to session storage ,上传文件。等到书被上传,然后copy 路径。

Path to uploaded document
上传文件的路径

现在,我们可以加载该文件。

添加新的code cell

loader = PyMuPDFLoader('/content/harry-potter-book-1.pdf')  # Replace with your file path
documents = loader.load()

点击RunCMD/CTRL + Enter

让我们把文件分成小块。

为什么?我们应该确保LLM能够处理这个文件。如果文件太长,LLM将无法处理它。

添加新的code cell

text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
texts = text_splitter.split_documents(documents)

点击RunCMD/CTRL + Enter

接下来,我们将创建一个矢量存储。

添加新的code cell

embeddings = CohereEmbeddings(cohere_api_key=os.environ["COHERE_API_KEY"])  # Create Cohere embeddings
vectordb = Chroma.from_documents(texts, embeddings)  # Create Chroma vector store

点击RunCMD/CTRL + Enter

现在,我们应该创建链。

添加新的code cell

qa = VectorDBQA.from_chain_type(llm=Cohere(cohere_api_key=os.environ["COHERE_API_KEY"]), chain_type="stuff", vectorstore=vectordb)  # Create QA chain

点击RunCMD/CTRL + Enter

完美!我们已经完成了链的创建!我们已经完成了链。现在,我们可以根据处理后的书进行查询。让我们试着询问一下关于Harry Potter

添加新的code cellcopy/paste 以下的代码行:

query = "Can you tell me more about Harry Potter's style, behaviour and character"  # Feel free to change the query to your own
qa.run(query)

点击RunCMD/CTRL + Enter

你应该看到如下图所示的东西,但如果你看到的东西不一样,也不用担心。

About Harry Potter
关于哈利波特

第二部分–使用Stable Diffusion生成图像

现在,我们将使用Stable Diffusion生成一个图像。我们将使用Stability SDK 来生成一个图像。让我们创建一个Stability SDK 客户端。

添加新的code cell

# Set up our connection to the API.
stability_api = client.StabilityInference(
    key=os.environ['STABILITY_KEY'], # API Key reference.
    verbose=True, # Print debug messages.
    engine="stable-diffusion-xl-beta-v2-2-2", # Set the engine to use for generation.
    # Available engines: stable-diffusion-v1 stable-diffusion-v1-5 stable-diffusion-512-v2-0 stable-diffusion-768-v2-0
    # stable-diffusion-512-v2-1 stable-diffusion-768-v2-1 stable-diffusion-xl-beta-v2-2-2 stable-inpainting-v1-0 stable-inpainting-512-v2-0
)

点击RunCMD/CTRL + Enter

接下来,粘贴你在第一部分中从Chroma 链得到的提示。

添加新的code cell

prompt = """

Harry Potter is a boy wizard in training who has to learn how to
perform magic spells, and his character is that of a polite, kind and determined
individual.  Harry is described as being tall and thin, with large glasses and
long, thin, unkempt hair.  He is an extremely polite and friendly person, and
is always willing to help out other people.  Harry is also described as being
determined, and will not give up easily when faced with a challenge.  As he
learns how to perform magic spells, he becomes more confident in his abilities
and his character develops into a more confident and mature person.  Harry is
said to have a kind and caring personality, and is always willing to help out
other people.  Harry is also described as being a brave and determined individual
who will not give up easily when faced with a challenge.  He is described as
being a very intelligent and witty individual who is always willing to help
out other people

"""  # You may replace with your prompt or use the one provided here.

点击RunCMD/CTRL + Enter

现在,我们可以根据提示生成一个图像。

添加新的code cell

# Set up our initial generation parameters.
answers = stability_api.generate(
    prompt=prompt, # The prompt to generate from.
    seed=992446758, # If a seed is provided, the resulting generated image will be deterministic.
                    # What this means is that as long as all generation parameters remain the same, you can always recall the same image simply by generating it again.
                    # Note: This isn't quite the case for CLIP Guided generations, which we tackle in the CLIP Guidance documentation.
    steps=30, # Amount of inference steps performed on image generation. Defaults to 30.
    cfg_scale=8.0, # Influences how strongly your generation is guided to match your prompt.
                # Setting this value higher increases the strength in which it tries to match your prompt.
                # Defaults to 7.0 if not specified.
    width=512, # Generation width, defaults to 512 if not included.
    height=512, # Generation height, defaults to 512 if not included.
    samples=1, # Number of images to generate, defaults to 1 if not included.
    sampler=generation.SAMPLER_K_DPMPP_2M # Choose which sampler we want to denoise our generation with.
                                                # Defaults to k_dpmpp_2m if not specified. Clip Guidance only supports ancestral samplers.
                                                # (Available Samplers: ddim, plms, k_euler, k_euler_ancestral, k_heun, k_dpm_2, k_dpm_2_ancestral, k_dpmpp_2s_ancestral, k_lms, k_dpmpp_2m, k_dpmpp_sde)
)

点击RunCMD/CTRL + Enter

这将需要一段时间来生成一个图像。一旦完成,我们可以保存图像。

添加新的code cellcopy/paste 以下几行代码:

它将把以seed number 为文件名的图像保存在与本笔记本相同的目录中。

# Set up our warning to print to the console if the adult content classifier is tripped.
# If adult content classifier is not tripped, save generated images.
for resp in answers:
    for artifact in resp.artifacts:
        if artifact.finish_reason == generation.FILTER:
            warnings.warn(
                "Your request activated the API's safety filters and could not be processed."
                "Please modify the prompt and try again.")                  
        if artifact.type == generation.ARTIFACT_IMAGE:
            img = Image.open(io.BytesIO(artifact.binary))
            img_path = img.save(str(artifact.seed)+ ".png") # Save our generated images with their seed number as the filename.

点击RunCMD/CTRL + Enter

现在,你可以下载图片并立即看到图片。

Harry Potter generated art by Stable Diffusion
Stable Diffusion生成的哈利波特作品

添加新的code cell

# Display the image
img.show()

点击RunCMD/CTRL + Enter

Harry Potter generated art by Stable Diffusion
Stable Diffusion生成的哈利波特作品

祝贺你!你已经成功地用Stable Diffusion法将Chroma基于Cohere嵌入所产生的提示活用为角色。

总结

在整个教程中,我们使用了各种工具和库,包括ChromaCohere嵌入、PyMuPDFLoader、Stability SDK,以及用于图像处理的PIL库。我们还讨论了先决条件,其中包括获得Cohere和Stable Diffusion的API密钥。

通过学习本教程,你现在应该对如何利用Chroma DB和Cohere嵌入来生成使用Stable Diffusion的图像有了更好的了解。

记得参考Chroma、Cohere和Stable Diffusion各自的文档,以获得更深入的信息和高级用法。你可以在上面的介绍中找到它们。

(0)
上一篇 2023年6月5日 18:09
下一篇 2023年6月14日 22:45

相关推荐

分享本页
返回顶部