teknolis / app /Services /SvgImageService.php
OpenAI Codex
Fix storage symlink and adapt cron status for Spaces
1501522
Raw
History Blame Contribute Delete
15.2 kB
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use RuntimeException;
class SvgImageService
{
public function generate(string $prompt, string $aspect = 'landscape', int $count = 1): array
{
$apiKey = (string) config('services.openai.api_key');
$baseUrl = rtrim((string) config('services.openai.base_url', 'https://api.openai.com/v1'), '/');
$model = (string) config('services.openai.model', 'gpt-4o');
$timeout = max(20, (int) config('services.openai.timeout', 40));
$maxTokens = max(600, (int) config('services.openai.svg_max_tokens', 900));
if (trim($apiKey) === '') {
throw new RuntimeException('OPENAI_API_KEY belum diisi di file .env');
}
$count = in_array($count, [1, 2, 4, 6], true) ? $count : 1;
[$width, $height] = $this->sizeFromAspect($aspect);
$urls = [];
for ($i = 1; $i <= $count; $i++) {
$svg = $this->templateSvg($prompt, $width, $height, $i);
if ($svg === null) {
$messages = $this->messages($prompt, $width, $height, $aspect, $i, $count);
$response = Http::timeout($timeout)
->withToken($apiKey)
->acceptJson()
->post("{$baseUrl}/chat/completions", [
'model' => $model,
'messages' => $messages,
'max_tokens' => $maxTokens,
'temperature' => 0.8,
]);
if (! $response->successful()) {
$errorBody = trim((string) data_get($response->json(), 'error.message', $response->body()));
throw new RuntimeException('SVG image request gagal: '.$response->status().' - '.$errorBody);
}
$content = (string) data_get($response->json(), 'choices.0.message.content', '');
$svg = $this->sanitizeSvg($content, $prompt, $width, $height, $i);
}
$filename = 'svg_'.now()->format('Ymd_His').'_'.Str::lower(Str::random(8)).'.svg';
$path = 'images/'.$filename;
if (! Storage::disk('public')->put($path, $svg)) {
throw new RuntimeException('Gagal menyimpan file SVG ke storage publik.');
}
$urls[] = Storage::url($path);
}
return $urls;
}
private function messages(string $prompt, int $width, int $height, string $aspect, int $variant, int $count): array
{
return [
[
'role' => 'system',
'content' => 'You create polished SVG artwork. Return only raw <svg> markup. No markdown, no code fences, no explanations, no scripts, no foreignObject, no external assets, no remote fonts. The image must be literal and recognizable first, stylish second. Show one clear main subject matching the prompt, centered and large. Avoid abstract blobs unless the prompt explicitly asks for abstract art.',
],
[
'role' => 'user',
'content' => "Create a premium AI-style SVG illustration inspired by this prompt: {$prompt}\n".
"Aspect ratio: {$aspect}\n".
"Canvas: {$width}x{$height}\n".
"Variant {$variant} of {$count}\n".
"Requirements:\n".
"- valid standalone SVG\n".
"- include viewBox=\"0 0 {$width} {$height}\"\n".
"- no XML declaration\n".
"- use only SVG shapes, gradients, patterns, filters, and text\n".
"- keep it visually rich and suitable for a product mockup or concept poster\n".
"- make the main subject obvious at first glance\n".
"- if the prompt is an animal or object, draw the actual animal or object, not a symbolic orb or abstract icon\n".
"- avoid text unless the prompt explicitly asks for typography\n".
"- do not mention policies or limitations",
],
];
}
private function sanitizeSvg(string $raw, string $prompt, int $width, int $height, int $variant): string
{
$raw = trim($raw);
$raw = preg_replace('/^```(?:svg)?/i', '', $raw) ?? $raw;
$raw = preg_replace('/```$/', '', $raw) ?? $raw;
$start = stripos($raw, '<svg');
$end = strripos($raw, '</svg>');
if ($start === false || $end === false) {
return $this->templateSvg($prompt, $width, $height, $variant) ?? $this->fallbackSvg($prompt, $width, $height, $variant);
}
$svg = substr($raw, $start, $end - $start + 6);
$svg = preg_replace('/<script\b[^>]*>.*?<\/script>/is', '', $svg) ?? $svg;
$svg = preg_replace('/<foreignObject\b[^>]*>.*?<\/foreignObject>/is', '', $svg) ?? $svg;
if (! str_contains($svg, 'xmlns=')) {
$svg = preg_replace('/<svg\b/', '<svg xmlns="http://www.w3.org/2000/svg"', $svg, 1) ?? $svg;
}
if (! str_contains($svg, 'viewBox=')) {
$svg = preg_replace('/<svg\b/', '<svg viewBox="0 0 '.$width.' '.$height.'"', $svg, 1) ?? $svg;
}
return trim($svg);
}
private function templateSvg(string $prompt, int $width, int $height, int $variant): ?string
{
$normalized = Str::lower($prompt);
if (Str::contains($normalized, ['gajah', 'elephant'])) {
return $this->elephantSvg($prompt, $width, $height, $variant);
}
return null;
}
private function fallbackSvg(string $prompt, int $width, int $height, int $variant): string
{
$label = htmlspecialchars(Str::limit($prompt, 42, ''), ENT_QUOTES, 'UTF-8');
$accentA = ['#43d9bd', '#f5b96b', '#ff7a59', '#8de2ff'][$variant % 4];
$accentB = ['#13273b', '#101a2a', '#1d1730', '#0f2233'][$variant % 4];
$panelWidth = max(320, $width - 160);
$panelHeight = max(220, $height - 180);
$cx = (int) floor($width * 0.24);
$cy = (int) floor($height * 0.36);
$radius = (int) floor(min($width, $height) * 0.12);
$x = (int) floor($width * 0.36);
$y = (int) floor($height * 0.25);
$w = (int) floor($width * 0.42);
$h = (int) floor($height * 0.18);
$x2 = (int) floor($width * 0.36);
$y2 = (int) floor($height * 0.48);
$w2 = (int) floor($width * 0.32);
$h2 = (int) floor($height * 0.12);
$textY = max(120, $height - 120);
$textY2 = max(156, $height - 84);
return <<<SVG
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {$width} {$height}" fill="none">
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#07111a"/>
<stop offset="60%" stop-color="#101b2b"/>
<stop offset="100%" stop-color="{$accentB}"/>
</linearGradient>
<radialGradient id="orbA" cx="0.25" cy="0.2" r="0.65">
<stop offset="0%" stop-color="{$accentA}" stop-opacity="0.95"/>
<stop offset="100%" stop-color="{$accentA}" stop-opacity="0"/>
</radialGradient>
<radialGradient id="orbB" cx="0.78" cy="0.18" r="0.45">
<stop offset="0%" stop-color="#ffffff" stop-opacity="0.24"/>
<stop offset="100%" stop-color="#ffffff" stop-opacity="0"/>
</radialGradient>
<filter id="blur" x="-20%" y="-20%" width="140%" height="140%">
<feGaussianBlur stdDeviation="40"/>
</filter>
</defs>
<rect width="{$width}" height="{$height}" rx="32" fill="url(#bg)"/>
<circle cx="{$width}" cy="0" r="{$height}" fill="url(#orbA)" filter="url(#blur)"/>
<circle cx="{$width}" cy="{$height}" r="{$height}" fill="url(#orbB)" filter="url(#blur)"/>
<g opacity="0.86">
<rect x="80" y="90" width="{$panelWidth}" height="{$panelHeight}" rx="36" fill="rgba(255,255,255,0.05)" stroke="rgba(255,255,255,0.12)"/>
<circle cx="{$cx}" cy="{$cy}" r="{$radius}" fill="{$accentA}" fill-opacity="0.9"/>
<rect x="{$x}" y="{$y}" width="{$w}" height="{$h}" rx="28" fill="rgba(255,255,255,0.08)"/>
<rect x="{$x2}" y="{$y2}" width="{$w2}" height="{$h2}" rx="22" fill="rgba(255,255,255,0.06)"/>
</g>
<text x="80" y="{$textY}" fill="#f6fbff" font-family="Arial, sans-serif" font-size="28" font-weight="700" letter-spacing="1.2">{$label}</text>
<text x="80" y="{$textY2}" fill="rgba(232,238,247,0.72)" font-family="Arial, sans-serif" font-size="16" letter-spacing="3">SVG CONCEPT POSTER</text>
</svg>
SVG;
}
private function elephantSvg(string $prompt, int $width, int $height, int $variant): string
{
$accentA = ['#43d9bd', '#f5b96b', '#ff7a59', '#8de2ff'][$variant % 4];
$accentB = ['#13273b', '#101a2a', '#1d1730', '#0f2233'][$variant % 4];
$label = htmlspecialchars(Str::limit($prompt, 34, ''), ENT_QUOTES, 'UTF-8');
$shadowY = (int) floor($height * 0.78);
$bodyCx = (int) floor($width * 0.5);
$bodyCy = (int) floor($height * 0.5);
$bodyRx = (int) floor($width * 0.19);
$bodyRy = (int) floor($height * 0.2);
$headCx = (int) floor($width * 0.39);
$headCy = (int) floor($height * 0.42);
$headR = (int) floor(min($width, $height) * 0.12);
$earLeftCx = (int) floor($width * 0.29);
$earRightCx = (int) floor($width * 0.44);
$earCy = (int) floor($height * 0.4);
$earRx = (int) floor($width * 0.09);
$earRy = (int) floor($height * 0.12);
$legTop = (int) floor($height * 0.58);
$legHeight = (int) floor($height * 0.18);
$textY = max(90, $height - 90);
$leg1X = $bodyCx - 150;
$leg2X = $bodyCx - 90;
$leg3X = $bodyCx + 22;
$leg4X = $bodyCx + 82;
$trunkX1 = $headCx + 28;
$trunkY1 = $headCy + 18;
$trunkX2 = $headCx + 44;
$trunkY2 = $headCy + 66;
$trunkX3 = $headCx + 34;
$trunkY3 = $headCy + 116;
$trunkX4 = $headCx + 24;
$trunkY4 = $headCy + 162;
$trunkX5 = $headCx + 70;
$trunkY5 = $headCy + 172;
$trunkX6 = $headCx + 86;
$trunkY6 = $headCy + 128;
$trunkHlX1 = $headCx + 16;
$trunkHlY1 = $headCy + 42;
$trunkHlX2 = $headCx + 44;
$trunkHlY2 = $headCy + 72;
$trunkHlX3 = $headCx + 58;
$trunkHlY3 = $headCy + 120;
$trunkHlX4 = $headCx + 48;
$trunkHlY4 = $headCy + 154;
$tusk1X1 = $headCx + 12;
$tusk1Y1 = $headCy + 30;
$tusk1X2 = $headCx + 30;
$tusk1Y2 = $headCy + 42;
$tusk1X3 = $headCx + 44;
$tusk1Y3 = $headCy + 52;
$tusk1X4 = $headCx + 56;
$tusk1Y4 = $headCy + 54;
$tusk2X1 = $headCx + 2;
$tusk2Y1 = $headCy + 28;
$tusk2X2 = $headCx + 18;
$tusk2Y2 = $headCy + 42;
$tusk2X3 = $headCx + 28;
$tusk2Y3 = $headCy + 52;
$tusk2X4 = $headCx + 34;
$tusk2Y4 = $headCy + 58;
$eyeLeftX = $headCx - 18;
$eyeRightX = $headCx + 14;
$eyeY = $headCy - 10;
$eyeGlowLeftX = $headCx - 20;
$eyeGlowRightX = $headCx + 12;
$eyeGlowY = $headCy - 12;
$tailX1 = $bodyCx + 150;
$tailY1 = $bodyCy - 52;
$tailX2 = $bodyCx + 184;
$tailY2 = $bodyCy - 78;
$tailX3 = $bodyCx + 198;
$tailY3 = $bodyCy - 18;
$tailX4 = $bodyCx + 174;
$tailY4 = $bodyCy + 14;
return <<<SVG
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {$width} {$height}" fill="none">
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#08111b"/>
<stop offset="56%" stop-color="#121d2c"/>
<stop offset="100%" stop-color="{$accentB}"/>
</linearGradient>
<radialGradient id="glow" cx="0.5" cy="0.18" r="0.72">
<stop offset="0%" stop-color="#ffffff" stop-opacity="0.34"/>
<stop offset="55%" stop-color="{$accentA}" stop-opacity="0.12"/>
<stop offset="100%" stop-color="{$accentA}" stop-opacity="0"/>
</radialGradient>
<linearGradient id="eleBody" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#d9e1ea"/>
<stop offset="100%" stop-color="#9eabb8"/>
</linearGradient>
<linearGradient id="eleShade" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#c6d0da"/>
<stop offset="100%" stop-color="#8795a3"/>
</linearGradient>
<filter id="blur" x="-20%" y="-20%" width="140%" height="140%">
<feGaussianBlur stdDeviation="48"/>
</filter>
</defs>
<rect width="{$width}" height="{$height}" rx="36" fill="url(#bg)"/>
<circle cx="{$bodyCx}" cy="{$headCy}" r="{$height}" fill="url(#glow)" filter="url(#blur)"/>
<ellipse cx="{$bodyCx}" cy="{$shadowY}" rx="{$bodyRx}" ry="36" fill="#071019" opacity="0.48"/>
<ellipse cx="{$earLeftCx}" cy="{$earCy}" rx="{$earRx}" ry="{$earRy}" fill="#b9c5d1"/>
<ellipse cx="{$earRightCx}" cy="{$earCy}" rx="{$earRx}" ry="{$earRy}" fill="#c7d2dc"/>
<ellipse cx="{$bodyCx}" cy="{$bodyCy}" rx="{$bodyRx}" ry="{$bodyRy}" fill="url(#eleShade)"/>
<circle cx="{$headCx}" cy="{$headCy}" r="{$headR}" fill="url(#eleBody)"/>
<rect x="{$leg1X}" y="{$legTop}" width="42" height="{$legHeight}" rx="18" fill="#98a6b4"/>
<rect x="{$leg2X}" y="{$legTop}" width="42" height="{$legHeight}" rx="18" fill="#a6b3bf"/>
<rect x="{$leg3X}" y="{$legTop}" width="42" height="{$legHeight}" rx="18" fill="#9aa8b5"/>
<rect x="{$leg4X}" y="{$legTop}" width="42" height="{$legHeight}" rx="18" fill="#90a0ae"/>
<path d="M {$headCx} {$headCy} C {$trunkX1} {$trunkY1}, {$trunkX2} {$trunkY2}, {$trunkX3} {$trunkY3} C {$trunkX4} {$trunkY4}, {$trunkX5} {$trunkY5}, {$trunkX6} {$trunkY6}" stroke="#9eabb8" stroke-width="30" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M {$trunkHlX1} {$trunkHlY1} C {$trunkHlX2} {$trunkHlY2}, {$trunkHlX3} {$trunkHlY3}, {$trunkHlX4} {$trunkHlY4}" stroke="#cfd8e1" stroke-width="10" stroke-linecap="round" opacity="0.55"/>
<path d="M {$tusk1X1} {$tusk1Y1} C {$tusk1X2} {$tusk1Y2}, {$tusk1X3} {$tusk1Y3}, {$tusk1X4} {$tusk1Y4}" stroke="#f6f1e7" stroke-width="8" stroke-linecap="round"/>
<path d="M {$tusk2X1} {$tusk2Y1} C {$tusk2X2} {$tusk2Y2}, {$tusk2X3} {$tusk2Y3}, {$tusk2X4} {$tusk2Y4}" stroke="#f6f1e7" stroke-width="7" stroke-linecap="round"/>
<circle cx="{$eyeLeftX}" cy="{$eyeY}" r="7" fill="#11151c"/>
<circle cx="{$eyeRightX}" cy="{$eyeY}" r="7" fill="#11151c"/>
<circle cx="{$eyeGlowLeftX}" cy="{$eyeGlowY}" r="2.5" fill="#ffffff" opacity="0.9"/>
<circle cx="{$eyeGlowRightX}" cy="{$eyeGlowY}" r="2.5" fill="#ffffff" opacity="0.9"/>
<path d="M {$tailX1} {$tailY1} C {$tailX2} {$tailY2}, {$tailX3} {$tailY3}, {$tailX4} {$tailY4}" stroke="#919fad" stroke-width="10" stroke-linecap="round"/>
<text x="72" y="{$textY}" fill="#eef4fb" font-family="Arial, sans-serif" font-size="26" font-weight="700">{$label}</text>
</svg>
SVG;
}
private function sizeFromAspect(string $aspect): array
{
return match ($aspect) {
'portrait' => [1024, 1536],
'square' => [1024, 1024],
default => [1536, 1024],
};
}
}