File size: 1,759 Bytes
5f32fbd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | <?php
namespace App\Services;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Response;
class StableDiffusion
{
protected Client $client;
protected Response $response;
protected string $accept = 'application/json';
public function __construct(
private string $apiKey,
private ?string $organization = null,
private ?string $stabilityClientId = null,
private string $stabilityClientVersion = '1.2.1'
) {
$this->client = new Client([
'base_uri' => 'https://api.stability.ai/v1/',
'headers' => [
'Authorization' => 'Bearer ' . $this->apiKey,
'Accept' => $this->accept,
],
]);
}
public function generate(
string $text,
float $weight = 0.5,
?string $engine = null,
) {
// engine: stable-diffusion-v1-6
$response = $this->client->post('generation/stable-diffusion-v1-6/text-to-image', [
'json' => [
'text_prompts' => [[
'text' => $text,
'weight' => $weight,
]],
],
]);
$this->response = $response;
return match ($this->accept) {
'application/json' => json_decode($response->getBody()->getContents(), true),
'image/png' => $response->getBody()->getContents(),
};
}
public function image()
{
$this->accept = 'image/png';
return $this;
}
public function json()
{
return $this;
}
public function engines()
{
$response = $this->client->get('engines/list');
return json_decode($response->getBody()->getContents(), true);
}
}
|