首頁 後端開發 Python教學 如何運行 FLUXor Free:逐步指南

如何運行 FLUXor Free:逐步指南

Sep 10, 2024 am 06:33 AM

Flux.1 是市場上最新的文本到圖像模型,由 Black Forest Labs 為我們帶來。它是一種最先進的模型,可以從文字描述生成高品質圖像,處理複雜的描述並產生具有精細細節的高品質圖像。

Flux.1 背後是誰?

Flux.1 由 Black Forest Labs 開發,該公司由 Stability AI 的一群前員工創建。

它是如何運作的?

與其他擴散模型(例如從隨機起點逐漸消除雜訊來創建影像的穩定擴散)不同,Flux.1 使用一種稱為「流匹配」的技術來產生影像,該技術採用更直接的方法,學習所需的精確變換將雜訊轉換為真實的影像。與常見的擴散模型相比,這可以更快地產生高品質影像,並且步驟更少。

此外,透過這種不同的方法,Flux.1 可以處理其中包含文字的圖像,如下所示:

How to Run FLUXor Free: A Step-by-Step Guide

現代時尚筆記型電腦的逼真圖像,開啟的網頁以乾淨、簡約的設計顯示文字「codestackme」。筆記型電腦應放置在光線柔和的白色桌子上,突出螢幕的光芒和金屬外殼上的微妙反射。整體氛圍應該專業、吸引人,傳達出創新和科技進步的感覺。

如何為 Flux.1 寫一個好的提示?

Flux.1 的突出特點之一是其用戶友好的提示機制。 CLIP(來自 OpenAI)和 T5(來自 GoogleAI)文字編碼器的整合使模型能夠解釋具有高度細微差別的描述。 CLIP 擅長將文字與視覺內容對齊,而 T5 則增強了模型處理結構化文字輸入的能力。它們共同使 Flux.1 能夠產生與使用者提供的詳細提示非常匹配的圖像。

Flux.1 有哪些類型的模型?

Flux.1 有三個不同的版本:Schnell、Dev 和 Pro。

  • Schnell 是最快的模型,針對速度和效率進行了最佳化。它是在 Apache 2.0 許可證下發布的,因此可以用於商業用途。
  • Dev 提供了一個更靈活和實驗性的框架,它專注於想要微調或自訂模型某些功能的開發人員和研究人員。它以非商業許可證發布。
  • Pro 是最先進且資源密集的版本。它提供更高解析度的輸出,並可以產生更複雜的圖像,但它只能透過 Black Forest Labs API 使用。

如何免費使用Flux.1?

對於有興趣探索 Flux.1 功能而無需財務承諾的人來說,使用 modal.com 作為資源提供者是一個可行的選擇。 Modal.com 每月提供 30 美元的計算能力津貼,可以支援每月生成大量圖像。您可以在 Modal.com 定價上了解有關其定價和產品的更多資訊。

此推薦未經平台贊助或認可。

首先,您需要使用 GitHub 憑證登錄,在 modal.com 上建立帳戶。

接下來,您需要安裝 Modal CLI。確保您的電腦上安裝了 Python。 Python 設定完成後,開啟終端機並執行指令 pip install modal。安裝完成後,執行 modal setup 將 CLI 與您的 Modal 帳戶連結。

繼續將此 GitHub 儲存庫複製到您的電腦並導航到複製的目錄。

為了安全起見,請在模態儀表板中使用名為 API_KEY 的環境變數建立一個名為 Flux.1-secret 的金鑰,並為其指派一個隨機字串。

最後,透過在終端機中執行 modal deploy app.py --name Flux1 來部署服務。成功部署後,modal 將提供用於存取 Web 服務的 URL:

✓ Created objects.
├── ? Created mount PythonPackage:app
├── ? Created function Model.build.
├── ? Created function Model.*.
├── ? Created function Model._inference.
└── ? Created web function Model.web_inference => <PUBLIC_URL>
✓ App deployed in 3.206s! ?
登入後複製

要使用該服務,請向提供的 PUBLIC URL 發出 GET 請求。在標頭中包含您先前設定的 x-api-key,並在查詢參數中對提示進行編碼。您也可以透過查詢參數指定所需的圖像尺寸。以下是如何建構請求的範例:

curl -H "x-api-key: <API_KEY>" <PUBLIC_URL>?width=<WIDTH>&height=<HEIGHT>&prompt=<PROMPT>
登入後複製

理解程式碼

讓我們剖析一下 app.py 文件,這對於使用 modal 平台運行 Flux.1 影像生成服務至關重要。以下是設定和功能的詳細說明:

import modal

image = modal.Image.debian_slim(python_version="3.10").apt_install(
    "libglib2.0-0", 
    "libsm6", 
    "libxrender1", 
    "libxext6", 
    "ffmpeg", 
    "libgl1",
    "git"
).pip_install(
    "git+https://github.com/huggingface/diffusers.git",
    "invisible_watermark",
    "transformers",
    "accelerate",
    "safetensors",
    "sentencepiece",
)
登入後複製

此區塊定義了我們的應用程式的 Docker 映像,指定了作業系統、必要的程式庫和 Python 套件。此環境支援 Flux.1 模型和相關實用程式的執行。

app = modal.App('flux1')

with image.imports():
    import os
    import io
    import torch
    from diffusers import FluxPipeline
    from fastapi import Response, Header
登入後複製

Here, we initialize our app and import necessary Python libraries within the context of our previously defined Docker image. These imports are essential for image processing and handling web requests.

@app.cls(gpu=modal.gpu.A100(), container_idle_timeout=15, image=image, timeout=120, secrets=[modal.Secret.from_name("flux.1-secret")])
class Model:
    @modal.build()
    def build(self):
        from huggingface_hub import snapshot_download

        snapshot_download("black-forest-labs/FLUX.1-schnell")

    @modal.enter()
    def enter(self):
        print("Loading model...")
        self.pipeline = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16).to('cuda')
        print("Model loaded!")

    def inference(self, prompt: str, width: int = 1440, height: int = 1440):
        print("Generating image...")
        image = self.pipeline(
            prompt, 
            output_type='pil', 
            width=width, 
            height=height, 
            num_inference_steps=8,
            generator=torch.Generator("cpu").manual_seed(
                torch.randint(0, 1000000, (1,)).item()
            )
        ).images[0]

        print("Image generated!")

        byte_stream = io.BytesIO()
        image.save(byte_stream, format="PNG")

        return byte_stream.getvalue()

    @modal.web_endpoint(docs=True)
    def web_inference(self, prompt: str, width: int = 1440, height: int = 1440, x_api_key: str = Header(None)):
        api_key = os.getenv("API_KEY")
        if x_api_key != api_key:
            return Response(content="Unauthorized", status_code=401)

        image = self.inference(prompt, width, height)
        return Response(content=image, media_type="image/png")
登入後複製

This section defines the main functionality of our service:

  • @modal.build(): Downloads the model when the application builds.
  • @modal.enter(): Loads the model into GPU memory the first time the service is invoked.
  • @modal.web_endpoint(): Serves as the web endpoint for our service using FastAPI.

If you just want to run it as a local service, you can add @modal.method() and define it as following inside the class.

        @modal.method()
    def _inference(self, prompt: str, width: int = 1440, height: int = 1440):
        return self.inference(prompt, width, height)
登入後複製

And outside it, define a local entry point

@app.local_entrypoint()
def main(prompt: str = "A beautiful sunset over the mountains"):
    image_bytes = Model()._inference.remote(prompt)

    with open("output.png", "wb") as f:
        f.write(image_bytes)
登入後複製

Local entry point will run locally on your machine calling the _inference method remotely, so you still using the modal’s service, without exposing it to the internet.

Conclusion

Flux.1 is not just another tech breakthrough - it's a game-changer for anyone who's ever dreamed of bringing their ideas to life visually. Imagine being able to describe a scene in words and watch as it materializes into a stunning, detailed image right before your eyes. That's the magic of Flux.1. It's like having a super-talented artist at your fingertips, ready to paint your thoughts with incredible precision. Whether you're an artist looking to speed up your creative process, a designer in need of quick visual concepts, or just someone who loves playing with new tech, Flux.1 opens up a world of possibilities. It's not about replacing human creativity - it's about enhancing it, making the journey from imagination to reality smoother and more exciting than ever before.

以上是如何運行 FLUXor Free:逐步指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1655
14
CakePHP 教程
1414
52
Laravel 教程
1307
25
PHP教程
1254
29
C# 教程
1228
24
Python vs.C:申請和用例 Python vs.C:申請和用例 Apr 12, 2025 am 12:01 AM

Python适合数据科学、Web开发和自动化任务,而C 适用于系统编程、游戏开发和嵌入式系统。Python以简洁和强大的生态系统著称,C 则以高性能和底层控制能力闻名。

您可以在2小時內學到多少python? 您可以在2小時內學到多少python? Apr 09, 2025 pm 04:33 PM

兩小時內可以學到Python的基礎知識。 1.學習變量和數據類型,2.掌握控制結構如if語句和循環,3.了解函數的定義和使用。這些將幫助你開始編寫簡單的Python程序。

Python:遊戲,Guis等 Python:遊戲,Guis等 Apr 13, 2025 am 12:14 AM

Python在遊戲和GUI開發中表現出色。 1)遊戲開發使用Pygame,提供繪圖、音頻等功能,適合創建2D遊戲。 2)GUI開發可選擇Tkinter或PyQt,Tkinter簡單易用,PyQt功能豐富,適合專業開發。

2小時的Python計劃:一種現實的方法 2小時的Python計劃:一種現實的方法 Apr 11, 2025 am 12:04 AM

2小時內可以學會Python的基本編程概念和技能。 1.學習變量和數據類型,2.掌握控制流(條件語句和循環),3.理解函數的定義和使用,4.通過簡單示例和代碼片段快速上手Python編程。

Python與C:學習曲線和易用性 Python與C:學習曲線和易用性 Apr 19, 2025 am 12:20 AM

Python更易學且易用,C 則更強大但複雜。 1.Python語法簡潔,適合初學者,動態類型和自動內存管理使其易用,但可能導致運行時錯誤。 2.C 提供低級控制和高級特性,適合高性能應用,但學習門檻高,需手動管理內存和類型安全。

Python和時間:充分利用您的學習時間 Python和時間:充分利用您的學習時間 Apr 14, 2025 am 12:02 AM

要在有限的時間內最大化學習Python的效率,可以使用Python的datetime、time和schedule模塊。 1.datetime模塊用於記錄和規劃學習時間。 2.time模塊幫助設置學習和休息時間。 3.schedule模塊自動化安排每週學習任務。

Python:探索其主要應用程序 Python:探索其主要應用程序 Apr 10, 2025 am 09:41 AM

Python在web開發、數據科學、機器學習、自動化和腳本編寫等領域有廣泛應用。 1)在web開發中,Django和Flask框架簡化了開發過程。 2)數據科學和機器學習領域,NumPy、Pandas、Scikit-learn和TensorFlow庫提供了強大支持。 3)自動化和腳本編寫方面,Python適用於自動化測試和系統管理等任務。

Python:自動化,腳本和任務管理 Python:自動化,腳本和任務管理 Apr 16, 2025 am 12:14 AM

Python在自動化、腳本編寫和任務管理中表現出色。 1)自動化:通過標準庫如os、shutil實現文件備份。 2)腳本編寫:使用psutil庫監控系統資源。 3)任務管理:利用schedule庫調度任務。 Python的易用性和豐富庫支持使其在這些領域中成為首選工具。

See all articles