国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

八十行代碼實現(xiàn)開源的 Midjourney、Stable Diffusion “咒語”作圖工具

這篇具有很好參考價值的文章主要介紹了八十行代碼實現(xiàn)開源的 Midjourney、Stable Diffusion “咒語”作圖工具。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

本篇文章聊聊如何通過 Docker 和八十行左右的 Python 代碼,實現(xiàn)一款類似 Midjourney 官方圖片解析功能 Describe 的 Prompt 工具。

讓你在玩 Midjourney、Stable Diffusion 這類模型時,不再為生成 Prompt 描述撓頭。

寫在前面

本文將提供兩個版本的工具,分別支持 CPU 和 GPU 推理使用,如果你有一張大于 8GB 顯存的顯卡,可以愉快的使用全部的功能,如果你只有 CPU,那么也可以使用 CPU 版本的應用來進行偷懶。

本篇文章的代碼已上傳至 GitHub soulteary/docker-prompt-generator,歡迎自取,以及“一鍵三連”

八十行代碼實現(xiàn)開源的 Midjourney、Stable Diffusion “咒語”作圖工具

昨晚在玩 Midjourney 的時候,在想 Prompt 的時候,想到撓頭。作為一個懶人,計上心頭:能不能讓模型幫我生成 Prompt 呢,輸入一些關鍵詞或者句子,然后讓程序幫助我完成完整的 Prompt 內容。(俗話:文生文)于是我開了個坑,創(chuàng)建了上面的這個開源項目,在簡單驗證可行性之后,就去補覺了。

一覺起來,看到有著相同興趣愛好的同事轉發(fā)了一篇文章:Midjourney 發(fā)布了新功能,“describe”,支持解析圖片為幾段不同的 Prompt 文本,并支持繼續(xù)進行圖片生成。(俗話:圖生文,然后文生圖

八十行代碼實現(xiàn)開源的 Midjourney、Stable Diffusion “咒語”作圖工具

這個功能相比昨晚折騰的小東西,顯然更能體現(xiàn)先進的生產效率嘛(作為懶人體驗非常好)。

可惜網上掃了一圈,發(fā)現(xiàn)官方功能并不開源,那么,我來實現(xiàn)一個吧。

“作圖咒語生成器” 的使用

為了更快的上手和使用到這個工具,我們需要先完成環(huán)境的配置。

應用和 Docker 環(huán)境準備

在過去的幾篇文章里,我提到過了我個人習慣和推薦的開發(fā)環(huán)境,基于 Docker 和 Nvidia 官方基礎容器的深度學習環(huán)境,所以就不再贅述相關知識點,感興趣可以自行翻閱,比如這篇《基于 Docker 的深度學習環(huán)境:入門篇》。相信老讀者應該已經很熟悉啦。

當然,因為本文包含純 CPU 也能玩的部分,你也可以參考幾個月前的《在搭載 M1 及 M2 芯片 MacBook設備上玩 Stable Diffusion 模型》,來配置你的環(huán)境。

在準備好 Docker 環(huán)境的配置之后,我們就可以繼續(xù)玩啦。

我們隨便找一個合適的目錄,使用 git clone 或者下載 Zip 壓縮包的方式,先把“Docker Prompt Generator(Docker 作圖咒語生成器)”項目的代碼下載到本地。

git clone https://github.com/soulteary/docker-prompt-generator.git
# or
curl -sL -o docker-prompt-generator.zip https://github.com/soulteary/docker-prompt-generator/archive/refs/heads/main.zip

接著,進入項目目錄,使用 Nvidia 原廠的 PyTorch Docker 基礎鏡像來完成基礎環(huán)境的構建,相比于我們直接從 DockerHub 拉制作好的鏡像,自行構建將能節(jié)約大量時間。

我們在項目目錄中執(zhí)行下面的命令,就能夠完成應用模型應用的構建啦:

# 構建基礎鏡像
docker build -t soulteary/prompt-generator:base . -f docker/Dockerfile.base

# 構建 CPU 應用
docker build -t soulteary/prompt-generator:cpu . -f docker/Dockerfile.cpu

# 構建 GPU 應用
docker build -t soulteary/prompt-generator:gpu . -f docker/Dockerfile.gpu

然后,根據(jù)你的硬件環(huán)境,選擇性執(zhí)行下面的命令,就能夠啟動一個帶有 Web UI 界面的模型應用啦。

# 運行 CPU 鏡像
docker run --gpus all --ipc=host --ulimit memlock=-1 --ulimit stack=67108864 --rm -it -p 7860:7860 soulteary/prompt-generator:cpu

# 運行 GPU 鏡像
docker run --gpus all --ipc=host --ulimit memlock=-1 --ulimit stack=67108864 --rm -it -p 7860:7860 soulteary/prompt-generator:gpu

我們在瀏覽器中輸入運行容器的宿主機的 IP 地址,就能夠開始使用工具啦。

使用工具

工具的使用,非常簡單,分別有使用“圖片生成描述”和使用“文本生成描述”兩種。

我找了一張之前模型生成的圖片,然后將這張圖片喂給這個程序,點擊按鈕,就能獲得圖片的描述文本啦。

八十行代碼實現(xiàn)開源的 Midjourney、Stable Diffusion “咒語”作圖工具

我們可以在 Midjourney 或者 Stable Diffusion 中,直接使用這段文本來繼續(xù)生成圖片,或者使用“從文本中生成”,來擴展內容,讓內容更適合 Midjourney 這類應用。

為了體現(xiàn)工具的中文翻譯和續(xù)寫能力,我們單獨寫一段簡單的中文描述:“一只小鳥立梢頭,一輪明月當空照,一片黃葉鋪枝頭”。

八十行代碼實現(xiàn)開源的 Midjourney、Stable Diffusion “咒語”作圖工具

可以看到,基于我們的輸入內容,生成了非常多不同的文本。

想要驗證文本內容是否符合原意,我們可以將內容粘貼到 Midjourney 中進行測試。

八十行代碼實現(xiàn)開源的 Midjourney、Stable Diffusion “咒語”作圖工具

因為模型存在隨機性,如果想要得到更好的結果,還需要對描述進行更多的調整優(yōu)化,不過,看起來工具解析圖片,生成的描述,其實是能夠做到開箱即用的,而根據(jù)我們的三言兩語生成的文本,也生成出了符合要求的圖片。

八十行代碼實現(xiàn)開源的 Midjourney、Stable Diffusion “咒語”作圖工具

好啦,工具的基礎使用,我們介紹完啦。

模型應用功能實現(xiàn)

下面是工具的實現(xiàn)流程和思考,如果你想學習或快速使用開源模型項目來構建你的 AI 容器應用,可以繼續(xù)瀏覽。

應用功能設計

在“動手”前,我們需要先明確功能設計,以及考慮使用什么樣的技術來做具體功能的技術支撐。

在我日常使用 Stable Diffusion、Midjourney 的過程中,時常有三個場景撓頭:

  1. 我只有一些關鍵詞,需要發(fā)揮想象力把關鍵詞串起來,然后喂給模型應用。如果描述內容不夠好,或者關鍵詞之間的關聯(lián)比較遠,那么圖片的生成效果就不會特別好。
  2. 我有一張圖片,想讓模型圍繞圖片中的內容,比如:構圖、某些元素、情感等進行二次創(chuàng)作,而不是簡單的做圖片中的元素替換。
  3. 我更習慣使用中文做描述,而不是英文,但是目前模型生成圖片,想要好的效果,需要使用英文,總是借助翻譯工具,切換程序界面或者網頁,還是挺麻煩的。

解決第一個問題,我們可以使用最近火爆出圈的 GPT-4 的前輩的前輩:GPT-2 其實就能夠滿足需求,將內容(一句話、幾個關鍵詞)進行快速續(xù)寫。相比較使用 GPT-3 / GPT-4,無需聯(lián)網,也無需付費,模型文件更是“便宜大碗”,用 CPU 就能跑起來。

解決第二個問題,我們可以使用 OpenAI 在一年前推出的 CLIP 神經網絡模型,以及 Salesforce 推出的 BLIP ,能夠從圖片中抽取出最合適的描述文本,讓我們用在新的 AIGC 圖片生成任務中。稍作優(yōu)化調整,我們只需要大概使用 6~8GB 顯存就能將這部分功能的模型跑起來。

解決第三個問題,我們可以使用赫爾辛基大學開源的 OPUS MT 模型,實現(xiàn)將中文翻譯為英文,進一步偷懶,以及解決上面兩類原始模型不支持中文輸入的問題。

因為前兩個場景問題中的模型不支持中文,而我又是一個懶人,不想輸入英文來玩圖,所以我們先來解決第三個問題,讓整個應用實現(xiàn)流程更絲滑。

中文 Prompt 翻譯為英文 Prompt 功能

想要實現(xiàn)第一個懶人功能,從用戶輸入的中文內容中,自動生成英文,我們需要使用中英雙語的翻譯模型。赫爾辛基大學的開源組織將預訓練模型開放在了 HuggingFace 社區(qū),Helsinki-NLP/opus-mt-zh-en。

我們可以通過寫十五行簡單的 Python 代碼,來完成模型文件的下載,以及實現(xiàn)將中文自動轉換為合適的英文內容的功能。比如下面的例子中,程序運行完畢,將輸出《火影忍者》中的金句“青春不能回頭,所以青春沒有終點”的譯文。

from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
import torch

model = AutoModelForSeq2SeqLM.from_pretrained("Helsinki-NLP/opus-mt-zh-en").eval()
tokenizer = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-zh-en")

def translate(text):
    with torch.no_grad():
        encoded = tokenizer([text], return_tensors="pt")
        sequences = model.generate(**encoded)
        return tokenizer.batch_decode(sequences, skip_special_tokens=True)[0]

input = "青春不能回頭,所以青春沒有終點。 ——《火影忍者》"
print(input, translate(input))

將上面的代碼保存為 translate.py,然后執(zhí)行 python translate.py,等待模型下載完畢,我們將得到類似下面的結果:

青春不能回頭,所以青春沒有終點。 Youth can't turn back, so there's no end to youth.

是不是看起來還不錯?這部分代碼保存在了項目中的 soulteary/docker-prompt-generator/app/translate.py。

接下來,我們來實現(xiàn) Prompt “免費續(xù)杯”(有邏輯續(xù)寫)功能。

實現(xiàn) MidJourney Prompt 續(xù)寫功能

基于一些內容,進行繼續(xù)的內容生成,是生成類模型的看家本領,比如大家已經熟悉的不能再熟悉的 ChatGPT 背后的 GPT 模型系列。

作為一個懶人,我在網上尋覓了一番,找到了一個 Google 離職創(chuàng)業(yè)的“國外大姐” 基于 GPT-2 使用 25 萬條 MidJourney 數(shù)據(jù) fine-tune 好的 GPT2 模型:succinctly/text2image-prompt-generator,簡單試了試了試效果還不錯,那么我們就用它來實現(xiàn)這部分功能吧。(其實,用前幾篇文章里的 LLaMA 也行,可以自行替換。)

和上面一樣,我們實現(xiàn)一個不到 30 行的簡單的程序,就能夠實現(xiàn)模型自動下載,以及調用模型根據(jù)我們的輸入內容(上文中熱血臺詞的翻譯)生成一些符合 Midjourney 或 Stable Diffusion 的新的 Prompt 內容:

from transformers import pipeline, set_seed
import random
import re

text_pipe = pipeline('text-generation', model='succinctly/text2image-prompt-generator')

def text_generate(input):
    seed = random.randint(100, 1000000)
    set_seed(seed)

    for count in range(6):    
        sequences = text_pipe(input, max_length=random.randint(60, 90), num_return_sequences=8)
        list = []
        for sequence in sequences:
            line = sequence['generated_text'].strip()
            if line != input and len(line) > (len(input) + 4) and line.endswith((":", "-", "—")) is False:
                list.append(line)

        result = "\n".join(list)
        result = re.sub('[^ ]+\.[^ ]+','', result)
        result = result.replace("<", "").replace(">", "")
        if result != "":
            return result
        if count == 5:
            return result

input = "Youth can't turn back, so there's no end to youth."
print(input, text_generate(input))

我們將上面的代碼保存為 text-generation.py,然后執(zhí)行 python text-generation.py,稍等片刻我們將得到類似下面的內容:

# Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation.
Youth can't turn back, so there's no end to youth. Youth can't turn back, so there's no end to youth. Young, handsome, confident, lonely boy sitting on his  can't turn back, so there's no end to youth. Where old yang waits, young man on the streets of Bangkok::10 film poster::10 photorealism, postprocessing, low angle::10 Trending on artstation::8 —ar 47:82
Youth can't turn back, so there's no end to youth. By Karel Thole and Mike Mignola --ar 2:3
Youth can't turn back, so there's no end to youth. And there is a bright hope about a future where there will be time.

內容看起來好像還不錯,我們直接在 Midjourney 中輸入測試,將得到類似下面的結果。

八十行代碼實現(xiàn)開源的 Midjourney、Stable Diffusion “咒語”作圖工具

看起來算是及格了,這部分代碼保存在項目的 soulteary/docker-prompt-generator/app/text-generation.py中,有需要可以自取。

完成了兩個功能之后,我們來實現(xiàn)根據(jù)圖片內容生成 Prompt 描述的應用功能。

實現(xiàn)根據(jù)圖片生成 Prompt 描述功能

相比較上面兩個功能,使用 CPU 就能搞定,內容生成效率也非常高。

但是想要快速的根據(jù)圖片生成 Prompt 則需要顯卡的支持。不過根據(jù)我的試驗,運行起來只需要 6~8GB 左右的顯存,還是比較省錢的。(沒有顯卡可以使用云服務器代替,買個按量的,玩罷銷毀即可。)

這里,我們依舊是實現(xiàn)一段簡單的,不到 30 行的 Python 代碼,完成模型下載、應用加載、圖片下載,以及將圖片轉換為 Prompt 的功能:

from clip_interrogator import Config, Interrogator
import torch
config = Config()
config.device = 'cuda' if torch.cuda.is_available() else 'cpu'
config.blip_offload = False if torch.cuda.is_available() else True
config.chunk_size = 2048
config.flavor_intermediate_count = 512
config.blip_num_beams = 64
config.clip_model_name = "ViT-H-14/laion2b_s32b_b79k"
ci = Interrogator(config)

def get_prompt_from_image(image):
    return ci.interrogate(image.convert('RGB'))

import requests
import shutil
r = requests.get("https://pic1.zhimg.com/v2-6e056c49362bff9af1eb39ce530ac0c6_1440w.jpg?source=d16d100b", stream=True)
if r.status_code == 200:
    with open('./image.jpg', 'wb') as f:
        r.raw.decode_content = True
        shutil.copyfileobj(r.raw, f) 

from PIL import Image
print(get_prompt_from_image(Image.open('./image.jpg')))

代碼中的圖片,使用了我專欄中上一篇文章的題圖(同樣使用 Midjourney 生成)。將上面的內容保存為 clip.py,然后執(zhí)行 python clip.py,稍等片刻,我們將得到類似下面的結果:

# WARNING:root:Pytorch pre-release version 1.14.0a0+410ce96 - assuming intent to test it
Loading BLIP model...
load checkpoint from https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_large_caption.pth
Loading CLIP model...
Loaded CLIP model and data in 8.29 seconds.
100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 55/55 [00:00<00:00, 316.23it/s]
Flavor chain:  38%|███████████████████████████████████████████████████████▏                                                                                           | 12/32 [00:04<00:07,  2.74it/s]
100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 55/55 [00:00<00:00, 441.49it/s]
100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 6/6 [00:00<00:00, 346.74it/s]
100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 50/50 [00:00<00:00, 457.84it/s]

a robot with a speech bubble on a blue background, highly detailed hyper real retro, artificial intelligence!!, toy photography, by Emma Andijewska, markings on robot, computer generated, blueish, delete, small gadget, animated, blue body, in retro colors

從結果中看,描述還是比較準確的。這部分代碼我保存在了項目的 soulteary/docker-midjourney-prompt-generator/app/clip.py。

好啦,到目前為止,三個主要功能,我們就都實現(xiàn)完畢了。接下來,我們借助 Docker 和 Gradio 來完成 Web UI 和一鍵運行的模型容器應用。

使用 Docker 構建 AI 應用容器

接下來,我們來完成 AI 應用的容器構建和相關代碼編寫。

前文中提到,我們將實現(xiàn)兩個版本的應用,分別支持 CPU 和 GPU 來完成快速的 AI 模型推理功能。因為后者可以向下兼容前者,所以我們先來實現(xiàn)一個包含前兩個應用功能,CPU 就能跑的模型基礎鏡像。

完成只需要 CPU 運行的應用容器鏡像

結合上文中的代碼,Dockerfile 文件不難編寫:

FROM nvcr.io/nvidia/pytorch:22.12-py3
LABEL org.opencontainers.image.authors="soulteary@gmail.com"

RUN pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple && \
    pip install transformers sentencepiece sacremoses && \
    pip install gradio

WORKDIR /app

RUN cat > /get-models.py <<EOF
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
AutoModelForSeq2SeqLM.from_pretrained('Helsinki-NLP/opus-mt-zh-en')
AutoTokenizer.from_pretrained('Helsinki-NLP/opus-mt-zh-en')
pipeline('text-generation', model='succinctly/text2image-prompt-generator')
EOF

RUN python /get-models.py && \
    rm -rf /get-models.py

將上面的內容保存為 Dockerfile.base,然后使用 docker build -t soulteary/prompt-generator:base . -f Dockerfile.base ,稍等片刻,包含了模型文件的基礎應用模型就搞定啦。

[+] Building 189.5s (7/8)                                                                                                                                                                             
 => [internal] load .dockerignore                                                                                                                                                                0.0s
 => => transferring context: 2B                                                                                                                                                                  0.0s
 => [internal] load build definition from Dockerfile.base                                                                                                                                        0.0s
 => => transferring dockerfile: 692B                                                                                                                                                             0.0s
 => [internal] load metadata for nvcr.io/nvidia/pytorch:22.12-py3                                                                                                                                0.0s
 => [1/5] FROM nvcr.io/nvidia/pytorch:22.12-py3                                                                                                                                                  0.0s
 => CACHED [2/5] RUN pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple &&     pip install transformers sentencepiece sacremoses &&     pip install gradio                 0.0s
 => CACHED [3/5] WORKDIR /app                                                                                                                                                                    0.0s
 => CACHED [4/5] RUN cat > /get-models.py <<EOF                                                                                                                                                  0.0s
 => [5/5] RUN python /get-models.py &&     rm -rf /get-models.py                                                                                                                               189.4s
 => => # Downloading (…)olve/main/source.spm: 100%|██████████| 805k/805k [00:06<00:00, 130kB/s]                                                                                                      
 => => # Downloading (…)olve/main/target.spm: 100%|██████████| 807k/807k [00:01<00:00, 440kB/s]                                                                                                      
 => => # Downloading (…)olve/main/vocab.json: 100%|██████████| 1.62M/1.62M [00:01<00:00, 1.21MB/s]                                                                                                   
 => => # Downloading (…)lve/main/config.json: 100%|██████████| 907/907 [00:00<00:00, 499kB/s]                                                                                                        
 => => # Downloading pytorch_model.bin: 100%|██████████| 665M/665M [00:11<00:00, 57.2MB/s]                                                                                                           
 => => # Downloading (…)okenizer_config.json: 100%|██████████| 255/255 [00:00<00:00, 81.9kB/s]

實現(xiàn)過程中,我這邊的構建時間大概要 5 分鐘左右,可以從椅子上起來,動一動,聽首歌放松一會。

鏡像構建完畢,可以使用下面的命令,進入包含模型和 PyTorch 環(huán)境的 Docker 鏡像。在這個鏡像中,我們可以自由的使用前兩個功能相關的模型:

docker run --gpus all --ipc=host --ulimit memlock=-1 --ulimit stack=67108864 --rm -it -p 7680:7680 soulteary/prompt-generator:base bash

有了環(huán)境之后,我們來繼續(xù)實現(xiàn)一個簡單的 Web UI,實現(xiàn)上文中的懶人功能:讓模型根據(jù)我們輸入的中文內容,生成可以繪制高質量圖片的 Prompt:

from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
import torch

model = AutoModelForSeq2SeqLM.from_pretrained('Helsinki-NLP/opus-mt-zh-en').eval()
tokenizer = AutoTokenizer.from_pretrained('Helsinki-NLP/opus-mt-zh-en')

def translate(text):
    with torch.no_grad():
        encoded = tokenizer([text], return_tensors='pt')
        sequences = model.generate(**encoded)
        return tokenizer.batch_decode(sequences, skip_special_tokens=True)[0]

from transformers import pipeline, set_seed
import random
import re

text_pipe = pipeline('text-generation', model='succinctly/text2image-prompt-generator')

def text_generate(input):
    seed = random.randint(100, 1000000)
    set_seed(seed)
    text_in_english = translate(input)
    for count in range(6):    
        sequences = text_pipe(text_in_english, max_length=random.randint(60, 90), num_return_sequences=8)
        list = []
        for sequence in sequences:
            line = sequence['generated_text'].strip()
            if line != text_in_english and len(line) > (len(text_in_english) + 4) and line.endswith((':', '-', '—')) is False:
                list.append(line)

        result = "\n".join(list)
        result = re.sub('[^ ]+\.[^ ]+','', result)
        result = result.replace('<', '').replace('>', '')
        if result != '':
            return result
        if count == 5:
            return result

import gradio as gr

with gr.Blocks() as block:
    with gr.Column():
        with gr.Tab('文本生成'):
            input = gr.Textbox(lines=6, label='你的想法', placeholder='在此輸入內容...')
            output = gr.Textbox(lines=6, label='生成的 Prompt')
            submit_btn = gr.Button('快給我編')

    submit_btn.click(
        fn=text_generate,
        inputs=input,
        outputs=output
    )

block.queue(max_size=64).launch(show_api=False, enable_queue=True, debug=True, share=False, server_name='0.0.0.0')

在容器環(huán)境中創(chuàng)建一個名為 webui.cpu.py 的文件,然后使用 python webui.cpu.py,將看到類似下面的日志輸出:

Running on local URL:  http://0.0.0.0:7860

To create a public link, set `share=True` in `launch()`.

然后我們在瀏覽器中打開容器所在設備的 IP (如果在本機運行,可以訪問 http://127.0.0.1:7860 ,就能訪問 Web 服務啦。

八十行代碼實現(xiàn)開源的 Midjourney、Stable Diffusion “咒語”作圖工具

我們在上面的輸入框里輸入一些內容,然后點擊“快給我編”按鈕,就能夠得到一堆模型編出來的 Prompt 內容啦。

實現(xiàn)完“文生文”功能之后,我們來實現(xiàn)“圖生文”相關功能。

完成需要 GPU 運行的應用容器鏡像

結合上文,完成 GPU 相關功能需要的容器環(huán)境也不難:

FROM soulteary/prompt-generator:base
LABEL org.opencontainers.image.authors="soulteary@gmail.com"

RUN pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple && \
    pip install clip_interrogator git+https://github.com/pharmapsychotic/BLIP.git@lib#egg=blip

RUN cat > /get-models.py <<EOF
from clip_interrogator import Config, Interrogator
import torch
config = Config()
config.device = 'cuda' if torch.cuda.is_available() else 'cpu'
config.blip_offload = False if torch.cuda.is_available() else True
config.chunk_size = 2048
config.flavor_intermediate_count = 512
config.blip_num_beams = 64
config.clip_model_name = "ViT-H-14/laion2b_s32b_b79k"
ci = Interrogator(config)
EOF

RUN python /get-models.py && \
    rm -rf /get-models.py

將上面的內容保存為 Dockerfile.gpu 文件,然后使用 docker build -t soulteary/prompt-generator:gpu . -f Dockerfile.gpu 完成鏡像的構建。

耐心等待鏡像構建完畢,使用下面的命令,能夠進入包含三種模型和 PyTorch 環(huán)境的 Docker 鏡像:

docker run --gpus all --ipc=host --ulimit memlock=-1 --ulimit stack=67108864 --rm -it -p 7680:7680 soulteary/prompt-generator:gpu bash

接著,來編寫能夠調用三種模型能力的 Python 程序:

from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
import torch

model = AutoModelForSeq2SeqLM.from_pretrained('Helsinki-NLP/opus-mt-zh-en').eval()
tokenizer = AutoTokenizer.from_pretrained('Helsinki-NLP/opus-mt-zh-en')

def translate(text):
    with torch.no_grad():
        encoded = tokenizer([text], return_tensors='pt')
        sequences = model.generate(**encoded)
        return tokenizer.batch_decode(sequences, skip_special_tokens=True)[0]

from transformers import pipeline, set_seed
import random
import re

text_pipe = pipeline('text-generation', model='succinctly/text2image-prompt-generator')

def text_generate(input):
    seed = random.randint(100, 1000000)
    set_seed(seed)
    text_in_english = translate(input)
    for count in range(6):    
        sequences = text_pipe(text_in_english, max_length=random.randint(60, 90), num_return_sequences=8)
        list = []
        for sequence in sequences:
            line = sequence['generated_text'].strip()
            if line != text_in_english and len(line) > (len(text_in_english) + 4) and line.endswith((':', '-', '—')) is False:
                list.append(line)

        result = "\n".join(list)
        result = re.sub('[^ ]+\.[^ ]+','', result)
        result = result.replace('<', '').replace('>', '')
        if result != '':
            return result
        if count == 5:
            return result

from clip_interrogator import Config, Interrogator
import torch
import gradio as gr

config = Config()
config.device = 'cuda' if torch.cuda.is_available() else 'cpu'
config.blip_offload = False if torch.cuda.is_available() else True
config.chunk_size = 2048
config.flavor_intermediate_count = 512
config.blip_num_beams = 64
config.clip_model_name = "ViT-H-14/laion2b_s32b_b79k"

ci = Interrogator(config)

def get_prompt_from_image(image, mode):
    image = image.convert('RGB')
    if mode == 'best':
        prompt = ci.interrogate(image)
    elif mode == 'classic':
        prompt = ci.interrogate_classic(image)
    elif mode == 'fast':
        prompt = ci.interrogate_fast(image)
    elif mode == 'negative':
        prompt = ci.interrogate_negative(image)
    return prompt

with gr.Blocks() as block:
    with gr.Column():
        gr.HTML('<h1>MidJourney / SD2 懶人工具</h1>')
        with gr.Tab('從圖片中生成'):
            with gr.Row():
                input_image = gr.Image(type='pil')
                with gr.Column():
                    input_mode = gr.Radio(['best', 'fast', 'classic', 'negative'], value='best', label='Mode')
            img_btn = gr.Button('這圖里有啥')
            output_image = gr.Textbox(lines=6, label='生成的 Prompt')

        with gr.Tab('從文本中生成'):
            input_text = gr.Textbox(lines=6, label='你的想法', placeholder='在此輸入內容...')
            output_text = gr.Textbox(lines=6, label='生成的 Prompt')
            text_btn = gr.Button('快給我編')

    img_btn.click(fn=get_prompt_from_image, inputs=[input_image, input_mode], outputs=output_image)
    text_btn.click(fn=text_generate, inputs=input_text, outputs=output_text)

block.queue(max_size=64).launch(show_api=False, enable_queue=True, debug=True, share=False, server_name='0.0.0.0')

我們將上面的程序保存為 webui.gpu.py,然后使用 python webui.gpu.py 運行程序,將得到類似下面的日志:

██████████████████████████████████████████████████████████████████████████████████████████████████████████████| 44.0/44.0 [00:00<00:00, 31.5kB/s]
Downloading: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 786k/786k [00:01<00:00, 772kB/s]
Downloading: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 788k/788k [00:00<00:00, 863kB/s]
Downloading: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1.54M/1.54M [00:01<00:00, 1.29MB/s]
Downloading: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 907/907 [00:00<00:00, 618kB/s]
Downloading: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 634M/634M [00:27<00:00, 23.8MB/s]
Downloading: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 255/255 [00:00<00:00, 172kB/s]
Downloading: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 779k/779k [00:01<00:00, 757kB/s]
Downloading: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 446k/446k [00:00<00:00, 556kB/s]
Downloading: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 2.01M/2.01M [00:01<00:00, 1.60MB/s]
Downloading: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 99.0/99.0 [00:00<00:00, 69.2kB/s]
I0405 12:50:42.798199 140240289830720 instantiator.py:21] Created a temporary directory at /tmp/tmpuvpi8s9q
I0405 12:50:42.798363 140240289830720 instantiator.py:76] Writing /tmp/tmpuvpi8s9q/_remote_module_non_scriptable.py
W0405 12:50:42.878760 140240289830720 version.py:27] Pytorch pre-release version 1.14.0a0+410ce96 - assuming intent to test it
I0405 12:50:43.373221 140240289830720 font_manager.py:1633] generated new fontManager
Loading BLIP model...
load checkpoint from https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_large_caption.pth
Loading CLIP model...
I0405 12:51:00.455630 140240289830720 factory.py:158] Loaded ViT-H-14 model config.
I0405 12:51:06.642275 140240289830720 factory.py:206] Loading pretrained ViT-H-14 weights (laion2b_s32b_b79k).
Loaded CLIP model and data in 8.22 seconds.
Running on local URL:  http://0.0.0.0:7860

To create a public link, set `share=True` in `launch()`.

當看到 Running on local URL: http://0.0.0.0:7860 的日志的時候,我們就可以在瀏覽器中訪問程序啦。

八十行代碼實現(xiàn)開源的 Midjourney、Stable Diffusion “咒語”作圖工具

將上文中的圖片投喂給它,然后點下“這圖里有啥”按鈕,稍等片刻,我們將得到一些比較合理的 Prompts 內容,你可以用這些內容去生成圖片。

八十行代碼實現(xiàn)開源的 Midjourney、Stable Diffusion “咒語”作圖工具

當然,你也可以將生成的文本內容再投喂給它,來獲得更多的 Prompt 內容,讓圖片的變化更豐富一些。

其他:顯存資源消耗

在模型識別圖片的過程中,我簡單記錄了應用的顯存消耗,峰值大概在 8GB 左右。

Wed Apr  5 21:00:09 2023
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 525.89.02    Driver Version: 525.89.02    CUDA Version: 12.0     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  NVIDIA GeForce ...  Off  | 00000000:01:00.0 Off |                  Off |
| 31%   35C    P8    23W / 450W |   8111MiB / 24564MiB |      0%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                                  |
|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
|        ID   ID                                                   Usage      |
|=============================================================================|
|    0   N/A  N/A      1286      G   /usr/lib/xorg/Xorg                  9MiB |
|    0   N/A  N/A      1504      G   /usr/bin/gnome-shell               10MiB |
|    0   N/A  N/A    115252      C   python                           8086MiB |
+-----------------------------------------------------------------------------+

最后

好了,這篇文章就先聊到這里啦。

下一篇文章,或許該揭示之前 fine-tune 的大模型的效果啦,最近一直很忙,直到今天才有空折騰模型。

–EOF


我們有一個小小的折騰群,里面聚集了一些喜歡折騰的小伙伴。

在不發(fā)廣告的情況下,我們在里面會一起聊聊軟硬件、HomeLab、編程上的一些問題,也會在群里不定期的分享一些技術資料。

喜歡折騰的小伙伴,歡迎閱讀下面的內容,掃碼添加好友。

關于“交友”的一些建議和看法

添加好友時,請備注實名和公司或學校、注明來源和目的,否則不會通過審核。

關于折騰群入群的那些事


本文使用「署名 4.0 國際 (CC BY 4.0)」許可協(xié)議,歡迎轉載、或重新修改使用,但需要注明來源。 署名 4.0 國際 (CC BY 4.0)

本文作者: 蘇洋

創(chuàng)建時間: 2023年04月05日
統(tǒng)計字數(shù): 10422字
閱讀時間: 21分鐘閱讀
本文鏈接: https://soulteary.com/2023/04/05/eighty-lines-of-code-to-implement-the-open-source-midjourney-and-stable-diffusion-spell-drawing-tool.html文章來源地址http://www.zghlxwxcb.cn/news/detail-413162.html

到了這里,關于八十行代碼實現(xiàn)開源的 Midjourney、Stable Diffusion “咒語”作圖工具的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!

本文來自互聯(lián)網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如若轉載,請注明出處: 如若內容造成侵權/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

  • 【必看】AI繪畫/stable diffusion:超簡單高效的畫畫技巧 附咒語/提示詞

    【必看】AI繪畫/stable diffusion:超簡單高效的畫畫技巧 附咒語/提示詞

    用AI畫一幅符合自己預期的好畫,模型、提示詞和方法都很重要。本文是我通過數(shù)十個小時不斷探索總結出來的AI繪畫經驗,相信你看后一定有所收獲! 先看看我用AI畫出來的小姐姐(●\\\'?\\\'●) ?(其實是隨便畫的)(好像把自己的xp暴露在外了)(本人確實沒什么審美)(哇靠

    2024年02月16日
    瀏覽(28)
  • AI 繪畫咒語入門 - Stable Diffusion Prompt 語法指南 【成為初級魔導士吧!】

    AI 繪畫咒語入門 - Stable Diffusion Prompt 語法指南 【成為初級魔導士吧!】

    要用好 Stable Diffusion,最最重要的就是掌握 Prompt(提示詞)。由于提示詞對于生成圖的影響甚大,所以被稱為魔法,用得好驚天動地,用不好魂飛魄散 ??。 因此本篇整理下提示詞的語法(魔法咒語)、如何使用(如何吟唱)、以及一些需要注意的細節(jié)問題(避免翻車)。

    2024年02月08日
    瀏覽(29)
  • AI繪圖設計師Stable Diffusion提示詞/咒語/詞綴/關鍵詞使用指南(Prompt)

    AI繪圖設計師Stable Diffusion提示詞/咒語/詞綴/關鍵詞使用指南(Prompt)

    基本知識 : 安裝及其問題解決參考:《Windows安裝Stable Diffusion WebUI及問題解決記錄》; 運行使用時問題《Windows使用Stable Diffusion時遇到的各種問題整理》; 模型運用及參數(shù)《Stable Diffusion 個人推薦的各種模型及設置參數(shù)、擴展應用等合集》; 提示詞生圖咒語《AI繪圖提示詞

    2023年04月22日
    瀏覽(47)
  • AI繪圖設計師Stable Diffusion 關鍵詞/咒語/提示詞詞綴使用指南(Prompt)

    AI繪圖設計師Stable Diffusion 關鍵詞/咒語/提示詞詞綴使用指南(Prompt)

    基本知識 : 安裝及其問題解決參考:《Windows安裝Stable Diffusion WebUI及問題解決記錄》; 運行使用時問題《Windows使用Stable Diffusion時遇到的各種問題整理》; 模型運用及參數(shù)《Stable Diffusion 個人推薦的各種模型及設置參數(shù)、擴展應用等合集》; 提示詞生圖咒語《AI繪圖提示詞

    2023年04月20日
    瀏覽(66)
  • AI繪圖提示詞/咒語/詞綴/關鍵詞使用指南(Stable Diffusion Prompt 設計師操作手冊)

    AI繪圖提示詞/咒語/詞綴/關鍵詞使用指南(Stable Diffusion Prompt 設計師操作手冊)

    基本知識 : 安裝及其問題解決參考:《Windows安裝Stable Diffusion WebUI及問題解決記錄》; 運行使用時問題《Windows使用Stable Diffusion時遇到的各種問題整理》; 模型運用及參數(shù)《Stable Diffusion 個人推薦的各種模型及設置參數(shù)、擴展應用等合集》; 提示詞生圖咒語《AI繪圖提示詞

    2024年02月01日
    瀏覽(41)
  • 十行python代碼實現(xiàn)文件去重,去除重復文件的腳本

    path1/path2:待比較的兩個文件路徑。 shallow :默認為True,即只比較os.stat()獲取的元數(shù)據(jù)(創(chuàng)建時間,大小等信息)是否相同, 設置為False的話,在對比文件的時候還要比較文件內容。

    2024年02月02日
    瀏覽(22)
  • Stable Diffusion原理詳解(附代碼實現(xiàn))

    Stable Diffusion原理詳解(附代碼實現(xiàn))

    回顧AI繪畫的歷史,GAN(Generative Adversarial Nets)是比較出眾的一個。GAN的出現(xiàn)讓AI繪畫成為可能,當時GAN給AI繪畫提供了一種新的思路,現(xiàn)在回顧當時的繪畫可以算是相當粗糙。 gan-results.jpg 初代GAN出現(xiàn)后,出現(xiàn)了大量GAN的變種,比如StyleGAN、CycleGAN、DCGAN等。而StyleGAN已經可以生

    2024年02月20日
    瀏覽(21)
  • stable diffusion和midjourney哪個好

    stable diffusion和midjourney哪個好

    midjourney和stable diffusion哪個好?midjourney和stable diffusion的區(qū)別?那么今天就從這2款軟件入手,來探索一下他們的功能的各項區(qū)別吧,讓你選擇更適合你的一款ai軟件。 截至目前,我們目睹了生成式人工智能工具的在各行各業(yè)的爆發(fā)。沒有什么地方比圖像生成器領域更能體現(xiàn)這

    2024年02月06日
    瀏覽(18)
  • Stable diffusion 和 Midjourney 怎么選?

    Stable diffusion 和 Midjourney 怎么選?

    通過這段時間的摸索,我將和你探討,對普通人來說,Stable diffusion 和 Midjourney 怎么選?最重要的是,學好影視后期制作對 AI 繪畫創(chuàng)作有哪些幫助?反過來,AI 繪畫對影視后期又有哪些幫助? 先說第一個問題的結論:普通人請直接選擇 Midjourney。 對于咱們普通的小伙伴來說,

    2024年02月15日
    瀏覽(24)
  • Stable diffusion和Midjourney之間的抉擇

    Stable diffusion和Midjourney之間的抉擇

    首先,這兩個工具的差異體現(xiàn)在成本和出圖方面。就成本而言,Stable diffusion是一個免費使用且開源的工具,可以進行本地部署但需要較高的電腦配置。雖然其繪制圖像的速度還算快捷,但是必須使用穩(wěn)定的網絡連接才能正常運行。 與之相比,Midjourney同樣要求用戶擁有穩(wěn)定的

    2024年02月12日
    瀏覽(20)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包