AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

StoreLogos.php 9.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. <?php
  2. namespace App\Storefront\Logos;
  3. use App\Ai\AiException;
  4. use App\Ai\AiManager;
  5. use App\Models\Store;
  6. use App\StorePlan\Ai\JsonAnswer;
  7. use App\StorePlan\PlanSchema;
  8. use GdImage;
  9. use Illuminate\Http\UploadedFile;
  10. use Illuminate\Support\Facades\DB;
  11. use Illuminate\Support\Facades\Storage;
  12. use Illuminate\Support\Str;
  13. use RuntimeException;
  14. /**
  15. * A store's logo: one the merchant uploads, one of our ready designs, or one Claude draws.
  16. *
  17. * The logo belongs to the store, not to the design, so it shows on the live store right away.
  18. * Ready designs are drawn by the storefront from the store's name, fonts and colours, so they follow
  19. * the store's look when it changes. Claude's drawings are cleaned by LogoSvg before they are kept.
  20. */
  21. class StoreLogos
  22. {
  23. /** Keep in step with LOGO_DESIGNS in resources/js/storefront/logo.tsx. */
  24. public const array DESIGNS = ['wordmark', 'spaced', 'monogram-circle', 'monogram-square', 'two-tone', 'underline', 'badge', 'dot'];
  25. /** Uploaded logos are made smaller than this on their longest side. */
  26. public const int MAX_SIDE = 800;
  27. public const int MIN_SIDE = 64;
  28. /** How many logos one "Draw with AI" try asks for. */
  29. public const int PER_TRY = 3;
  30. /** Claude's drawings kept per store, newest first. */
  31. private const int MAX_DRAFTS = 12;
  32. public function __construct(private readonly AiManager $ai) {}
  33. /**
  34. * Lifetime "Draw with AI" tries per store.
  35. */
  36. public function tryLimit(): int
  37. {
  38. return (int) config('ai.logo.lifetime_tries', 3);
  39. }
  40. public function triesLeft(Store $store): int
  41. {
  42. return max(0, $this->tryLimit() - $store->ai_logo_tries);
  43. }
  44. /**
  45. * The name the logo shows: the store header's words, or the store name.
  46. */
  47. public function name(Store $store): string
  48. {
  49. $plan = $store->published_plan ?? $store->plan ?? [];
  50. $header = $plan['header'] ?? collect($plan['sections'] ?? [])->firstWhere('type', 'header');
  51. $text = trim((string) ($header['content']['logoText'] ?? ''));
  52. return $text !== '' ? $text : $store->name;
  53. }
  54. /**
  55. * What the storefront needs to draw the logo, or null when the store has none.
  56. *
  57. * @return array{type: string, url?: string, width?: int, height?: int, key?: string, svg?: string}|null
  58. */
  59. public function present(Store $store): ?array
  60. {
  61. $logo = $store->logo;
  62. return match ($logo['type'] ?? null) {
  63. 'upload' => ['type' => 'upload', 'url' => Storage::disk('public')->url($logo['path']), 'width' => (int) $logo['width'], 'height' => (int) $logo['height']],
  64. 'design' => in_array($logo['key'] ?? null, self::DESIGNS, true) ? ['type' => 'design', 'key' => $logo['key']] : null,
  65. 'drawn' => is_string($logo['svg'] ?? null) ? ['type' => 'drawn', 'svg' => $logo['svg']] : null,
  66. default => null,
  67. };
  68. }
  69. /**
  70. * Save an uploaded logo, made smaller when large and saved as WebP, keeping a see-through background.
  71. * Saving it again also drops hidden details in the file. Replaces the old logo.
  72. *
  73. * @throws RuntimeException When the picture cannot be read.
  74. */
  75. public function upload(Store $store, UploadedFile $file): void
  76. {
  77. $image = @imagecreatefromstring((string) file_get_contents($file->getRealPath()));
  78. if (! $image instanceof GdImage) {
  79. throw new RuntimeException('The picture could not be read.');
  80. }
  81. $width = imagesx($image);
  82. $height = imagesy($image);
  83. $scale = min(1, self::MAX_SIDE / max($width, $height));
  84. $newWidth = max(1, (int) round($width * $scale));
  85. $newHeight = max(1, (int) round($height * $scale));
  86. $canvas = imagecreatetruecolor($newWidth, $newHeight);
  87. imagealphablending($canvas, false);
  88. imagesavealpha($canvas, true);
  89. imagefill($canvas, 0, 0, imagecolorallocatealpha($canvas, 0, 0, 0, 127));
  90. imagecopyresampled($canvas, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  91. $path = 'logos/'.$store->id.'-'.Str::random(12).'.webp';
  92. ob_start();
  93. imagewebp($canvas, null, 90);
  94. Storage::disk('public')->put($path, (string) ob_get_clean());
  95. $this->replace($store, ['type' => 'upload', 'path' => $path, 'width' => $newWidth, 'height' => $newHeight]);
  96. }
  97. public function useDesign(Store $store, string $key): void
  98. {
  99. $this->replace($store, ['type' => 'design', 'key' => $key]);
  100. }
  101. /**
  102. * Use one of the drawings Claude made for this store.
  103. */
  104. public function useDrawn(Store $store, int $index): bool
  105. {
  106. $svg = $store->logo_drafts[$index] ?? null;
  107. if (! is_string($svg)) {
  108. return false;
  109. }
  110. $this->replace($store, ['type' => 'drawn', 'svg' => $svg]);
  111. return true;
  112. }
  113. public function remove(Store $store): void
  114. {
  115. $this->replace($store, null);
  116. }
  117. /**
  118. * Ask Claude for new logos. A try counts only when at least one usable logo comes back.
  119. * Returns how many new logos were added, or null when the store has no tries left.
  120. *
  121. * @throws AiException
  122. */
  123. public function draw(Store $store): ?int
  124. {
  125. // Take a try first, in one step, so two quick clicks can never pass the limit.
  126. $taken = DB::table('stores')->where('id', $store->id)->where('ai_logo_tries', '<', $this->tryLimit())->increment('ai_logo_tries');
  127. if ($taken === 0) {
  128. return null;
  129. }
  130. try {
  131. $answer = $this->ai->ask('logo', $this->system(), $this->prompt($store));
  132. $logos = JsonAnswer::decode($answer->text)['logos'] ?? null;
  133. $clean = is_array($logos)
  134. ? array_values(array_filter(array_map(fn ($logo) => is_array($logo) && is_string($logo['svg'] ?? null) ? LogoSvg::clean($logo['svg']) : null, $logos)))
  135. : [];
  136. if ($clean === []) {
  137. throw new AiException('The AI did not draw a usable logo.', AiException::INVALID_RESULT);
  138. }
  139. } catch (AiException $e) {
  140. // Nothing usable: give the try back.
  141. DB::table('stores')->where('id', $store->id)->where('ai_logo_tries', '>', 0)->decrement('ai_logo_tries');
  142. $store->refresh();
  143. throw $e;
  144. }
  145. $store->refresh();
  146. $store->logo_drafts = array_slice([...array_slice($clean, 0, self::PER_TRY), ...($store->logo_drafts ?? [])], 0, self::MAX_DRAFTS);
  147. $store->save();
  148. return min(count($clean), self::PER_TRY);
  149. }
  150. /**
  151. * @param array<string, mixed>|null $logo
  152. */
  153. private function replace(Store $store, ?array $logo): void
  154. {
  155. $old = $store->logo;
  156. $store->logo = $logo;
  157. $store->save();
  158. if (($old['type'] ?? null) === 'upload' && ($old['path'] ?? null) !== ($logo['path'] ?? null)) {
  159. Storage::disk('public')->delete($old['path']);
  160. }
  161. }
  162. private function system(): string
  163. {
  164. return <<<'TEXT'
  165. You design simple, professional logos for small online shops in Malaysia. You draw them as SVG.
  166. Answer with JSON only, in this shape: {"logos": [{"svg": "<svg ...>...</svg>"}, ...]} with exactly 3 logos.
  167. Rules for every logo:
  168. - A wide logo for a website header: viewBox about "0 0 400 100" (width 240 to 600, height 80 to 140). No width or height on the svg element.
  169. - Show the store name exactly as given, spelled exactly, as a <text> element. Do not set font-family: the store's own font is applied. Pick a font-size and positions so the whole name fits inside the viewBox: each letter is about 0.6 times the font-size wide.
  170. - You may add a simple mark or icon on the left made from basic shapes (circle, rect, path, polygon). Keep it simple and clear at small sizes.
  171. - Use only the store's colours given below (as hex values), plus white or none. A linear or radial gradient between them is allowed.
  172. - Allowed elements only: svg, g, path, circle, ellipse, rect, line, polyline, polygon, text, tspan, defs, linearGradient, radialGradient, stop. No images, links, scripts, styles, filters, masks, clip paths, animation or embedded fonts.
  173. - Make the 3 logos clearly different ideas, for example: an icon beside the name, a monogram badge with the name, and a stylish wordmark.
  174. - Fit the brand: what it sells and its mood. Avoid clichés like a generic shopping cart.
  175. TEXT;
  176. }
  177. private function prompt(Store $store): string
  178. {
  179. $plan = $store->published_plan ?? $store->plan ?? [];
  180. $colors = $plan['theme']['colors'] ?? [];
  181. $font = PlanSchema::FONTS[$plan['theme']['fonts']['heading'] ?? ''] ?? 'a clean sans-serif';
  182. $palette = collect(['primary', 'accent', 'foreground', 'surface', 'background'])
  183. ->filter(fn (string $key) => is_string($colors[$key] ?? null))
  184. ->map(fn (string $key) => "- {$key}: {$colors[$key]}")
  185. ->implode("\n");
  186. return implode("\n", [
  187. 'Store name: '.$this->name($store),
  188. 'What it sells: '.$store->category->value,
  189. 'About the brand: '.Str::limit((string) $store->description, 600),
  190. "The store's heading font (applied for you): ".$font,
  191. "The store's colours:",
  192. $palette !== '' ? $palette : '- primary: #1F1F1F',
  193. ]);
  194. }
  195. }