florinnichifiriuc / stable-diffusion-php-client
Stable Diffusion API 的 PHP 客户端库
Requires
- guzzlehttp/guzzle: ^7.0
Requires (Dev)
- phpunit/phpunit: ^9.0
This package is auto-updated.
Last update: 2024-10-02 20:47:28 UTC
README
一个用于与 Stable Diffusion API 交互的 PHP 客户端库。此库允许您将 Stable Diffusion 的文本到图像生成功能集成到您的 PHP 应用程序中,包括 Laravel 项目。
目录
特性
- 使用 PHP 与 Stable Diffusion API 交互。
- 从文本提示生成图像(
txt2img
)。 - 检索和切换可用模型。
- 灵活的参数配置。
- 易于与 Laravel 应用程序集成。
- PSR-4 自动加载兼容。
要求
- PHP 7.4 或更高。
- Composer。
- Guzzle HTTP 客户端(通过 Composer 自动安装)。
- 本地运行带有 API 启用的 Stable Diffusion 实例(使用 Automatic1111 的 Web UI)。
安装
1. 通过 Composer 安装
在您项目根目录中运行以下命令
composer require florinnichifiriuc/stable-diffusion-php-client
将 florinnichifiriuc/stable-diffusion-php-client
替换为 Packagist 上发布的实际包名。
2. 设置 Stable Diffusion API
确保您的 Stable Diffusion 实例已启动并启用了 API。
步骤
-
如果尚未安装,请安装 Stable Diffusion 与 Automatic1111 Web UI。请按照 GitHub 存储库 中的说明进行操作。
-
通过使用
--api
标志启动 Web UI 来启用 APIpython launch.py --api
- 或者,修改您的启动脚本或批处理文件以包括
--api
标志。 - 默认情况下,API 在
http://127.0.0.1:7860
上运行。
- 或者,修改您的启动脚本或批处理文件以包括
配置
环境变量
在您项目的 .env
文件(或等效配置)中添加以下行
STABLE_DIFFUSION_API_URL=http://127.0.0.1:7860
根据您的 Stable Diffusion API 在不同主机或端口上运行,调整 URL。
Laravel 配置(可选)
如果您正在使用 Laravel,创建一个配置文件来管理 Stable Diffusion 设置。
文件: config/stable_diffusion.php
<?php return [ 'api_url' => env('STABLE_DIFFUSION_API_URL', 'http://127.0.0.1:7860'), ];
用法
基本示例
<?php require 'vendor/autoload.php'; use Florinnichifiriuc\StableDiffusionPhpClient\StableDiffusionClient; $sdClient = new StableDiffusionClient(); // Define parameters $params = [ 'prompt' => 'A fantasy landscape with mountains and a river', 'negative_prompt' => 'low quality, blurry', 'steps' => 50, 'cfg_scale' => 7.5, ]; // Generate image $images = $sdClient->txt2img($params); if ($images) { // Decode the base64 image $decodedImage = base64_decode($images[0]); // Save the image to a file file_put_contents('generated_image.png', $decodedImage); echo "Image generated successfully: generated_image.png"; } else { echo "Failed to generate image."; }
使用模型
您可以检索可用模型并设置用于图像生成的特定模型。
获取可用模型
$sdClient = new StableDiffusionClient(); try { $models = $sdClient->getModels(); if ($models) { echo "Available Models:\n"; foreach ($models as $model) { echo "- " . $model['title'] . "\n"; } } else { echo "No models found."; } } catch (\Exception $e) { echo 'Error: ' . $e->getMessage(); }
设置模型
try { $desiredModelTitle = 'v1-5-pruned-emaonly'; // Replace with your desired model title $sdClient->setModel($desiredModelTitle); } catch (\InvalidArgumentException $e) { echo 'Model Error: ' . $e->getMessage(); }
使用所选模型生成图像
$params = [ 'prompt' => 'A beautiful sunset over the mountains', 'negative_prompt' => 'low quality, blurry', 'steps' => 30, 'cfg_scale' => 7.5, ]; $images = $sdClient->txt2img($params);
Laravel 集成
控制器示例
文件: app/Http/Controllers/ImageGenerationController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Florinnichifiriuc\StableDiffusionPhpClient\StableDiffusionClient; use Illuminate\Support\Facades\Storage; class ImageGenerationController extends Controller { public function showForm() { return view('generate_image'); } public function generateImage(Request $request) { $request->validate([ 'prompt' => 'required|string|max:1000', 'negative_prompt' => 'nullable|string|max:1000', 'steps' => 'nullable|integer|min:1|max:150', 'cfg_scale' => 'nullable|numeric|min:1|max:30', 'seed' => 'nullable|integer', 'model' => 'nullable|string', ]); $params = [ 'prompt' => $request->input('prompt'), 'negative_prompt' => $request->input('negative_prompt', ''), 'steps' => $request->input('steps', 20), 'cfg_scale' => $request->input('cfg_scale', 7.5), 'seed' => $request->input('seed'), ]; $sdClient = new StableDiffusionClient(); try { // Set model if provided if ($request->filled('model')) { $sdClient->setModel($request->input('model')); } $images = $sdClient->txt2img($params); if ($images) { $decodedImage = base64_decode($images[0]); // Save the image to storage (e.g., public disk) $filename = 'generated_' . time() . '.png'; Storage::disk('public')->put($filename, $decodedImage); return view('image_result', [ 'image_url' => Storage::url($filename), ]); } else { return back()->withErrors(['message' => 'Failed to generate image']); } } catch (\InvalidArgumentException $e) { return back()->withErrors(['message' => 'Model Error: ' . $e->getMessage()]); } catch (\Exception $e) { return back()->withErrors(['message' => 'Error: ' . $e->getMessage()]); } } }
Blade 模板
a. 图像生成表单
文件: resources/views/generate_image.blade.php
<!DOCTYPE html> <html> <head> <title>Generate Image</title> </head> <body> <h1>Generate Image</h1> @if ($errors->any()) <div style="color:red;"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <form action="{{ url('/generate-image') }}" method="POST"> @csrf <label for="prompt">Prompt:</label><br> <textarea id="prompt" name="prompt" required rows="4" cols="50">{{ old('prompt') }}</textarea><br><br> <label for="negative_prompt">Negative Prompt:</label><br> <textarea id="negative_prompt" name="negative_prompt" rows="2" cols="50">{{ old('negative_prompt') }}</textarea><br><br> <label for="steps">Steps (1-150):</label><br> <input type="number" id="steps" name="steps" value="{{ old('steps', 20) }}" min="1" max="150"><br><br> <label for="cfg_scale">CFG Scale (1-30):</label><br> <input type="number" id="cfg_scale" name="cfg_scale" step="0.5" value="{{ old('cfg_scale', 7.5) }}" min="1" max="30"><br><br> <label for="seed">Seed (Optional):</label><br> <input type="number" id="seed" name="seed" value="{{ old('seed') }}"><br><br> <label for="model">Model (Optional):</label><br> <input type="text" id="model" name="model" value="{{ old('model') }}"><br><br> <input type="submit" value="Generate Image"> </form> </body> </html>
b. 图像结果页面
文件: resources/views/image_result.blade.php
<!DOCTYPE html> <html> <head> <title>Generated Image</title> </head> <body> <h1>Generated Image</h1> <img src="{{ asset($image_url) }}" alt="Generated Image"><br><br> <a href="{{ url('/generate-image') }}">Generate Another Image</a> </body> </html>
路由
文件: routes/web.php
<?php use App\Http\Controllers\ImageGenerationController; use Illuminate\Support\Facades\Route; Route::get('/generate-image', [ImageGenerationController::class, 'showForm']); Route::post('/generate-image', [ImageGenerationController::class, 'generateImage']);
存储设置
确保您的应用程序从 public/storage
到 storage/app/public
有一个符号链接
php artisan storage:link
高级用法
可用方法
txt2img(array $params)
从文本提示生成图像。
- 如果您已使用
setModel()
设置了模型,则该模型将作为'sd_model_checkpoint'
添加到$params
数组中,但前提是它尚未在$params
中设置。 - 如果
'sd_model_checkpoint'
已在$params
中设置,则它不会被通过setModel()
设置的模型覆盖。
getModels()
从本地实例检索所有可用的Stable Diffusion模型列表。
使用示例
$models = $sdClient->getModels();
响应格式
getModels()
方法返回一个模型数组,其中每个模型都是一个包含模型信息的关联数组。
示例响应
[ [ 'title' => 'v1-5-pruned-emaonly', 'model_name' => 'v1-5-pruned-emaonly.ckpt', 'hash' => 'abc123', 'sha256' => '...', 'filename' => '/path/to/v1-5-pruned-emaonly.ckpt', 'config' => '/path/to/v1-5-pruned-emaonly.yaml', ], // Additional models... ]
setModel($modelTitle)
设置用于图像生成的模型。
- 验证模型是否存在。
- 将模型存储在私有属性中,用于后续API调用。
- 如果
$params
中已设置'sd_model_checkpoint'
,则不会覆盖它。
使用示例
$sdClient->setModel('v1-5-pruned-emaonly');
重要提示
- 在
txt2img
API调用中将'sd_model_checkpoint'
作为顶级参数包括在内,可能取决于您的Stable Diffusion API的具体实现。 - 在标准Automatic1111 API中,通常通过
'override_settings'
参数来进行模型覆盖。 - 请验证您的API是否支持将
'sd_model_checkpoint'
作为顶级参数。
自定义参数
txt2img
方法接受一个与Stable Diffusion API选项对应的关联数组参数。
常见参数
prompt
(字符串):图像生成的文本提示。negative_prompt
(字符串):从图像中排除的文本提示。steps
(整数):推理步骤数(默认为20)。cfg_scale
(浮点数):无分类器指导尺度(默认为7.5)。seed
(整数):随机数生成的种子(可选)。width
(整数):生成图像的宽度。height
(整数):生成图像的高度。sampler_index
(字符串):用于图像生成的采样器。
带额外参数的示例
$params = [ 'prompt' => 'A futuristic cityscape at night', 'negative_prompt' => 'low resolution, blurry', 'steps' => 50, 'cfg_scale' => 9.0, 'width' => 512, 'height' => 512, 'sampler_index' => 'Euler', ];
有关所有可用参数的完整列表,请参阅Stable Diffusion API文档。
错误处理
库在以下情况下抛出异常
- 指定的模型不存在(
InvalidArgumentException
)。 - HTTP请求失败或API返回错误。
您应该将API调用包裹在try-catch块中,以优雅地处理异常。
示例
try { $sdClient->setModel('non-existent-model'); } catch (\InvalidArgumentException $e) { echo 'Model Error: ' . $e->getMessage(); } catch (\Exception $e) { echo 'Error: ' . $e->getMessage(); }
贡献
欢迎贡献!如果您遇到错误或有功能请求,请在GitHub上打开问题或提交pull请求。
开发设置
-
克隆仓库
git clone https://github.com/florinnichifiriuc/stable-diffusion-php-client.git
-
安装依赖项
composer install
-
运行测试
composer test
许可
本项目采用MIT许可证。有关详细信息,请参阅LICENSE文件。