From 33e53f5bca6213f34c89d310b04314fbac33946d Mon Sep 17 00:00:00 2001 From: Paulo Castellano Date: Thu, 21 May 2026 19:52:12 -0300 Subject: [PATCH] feat(posts): add regenerate_image option for background image handling - Introduced a new `regenerate_image` boolean parameter in the PostImageRegenerator schema to control background image regeneration. - Updated relevant methods in RegeneratePostMediaImage and TemplateImageGenerator to utilize the new parameter for reusing existing backgrounds when appropriate. - Enhanced documentation and comments to clarify the usage of the `regenerate_image` option. - Added tests to ensure correct behavior when reusing background images. --- app/Ai/Agents/PostImageRegenerator.php | 3 + app/Jobs/Ai/RegeneratePostMediaImage.php | 33 ++++++++- app/Services/Image/TemplateImageGenerator.php | 74 +++++++++++++------ .../prompts/post_image/regenerator.blade.php | 3 + .../Image/TemplateImageGeneratorTest.php | 26 ++++++- 5 files changed, 112 insertions(+), 27 deletions(-) diff --git a/app/Ai/Agents/PostImageRegenerator.php b/app/Ai/Agents/PostImageRegenerator.php index 8e3b94b4..0e3b9179 100644 --- a/app/Ai/Agents/PostImageRegenerator.php +++ b/app/Ai/Agents/PostImageRegenerator.php @@ -41,6 +41,9 @@ public function schema(JsonSchema $schema): array ->items($schema->string()) ->description('3-10 short keywords for image generation context.') ->required(), + 'regenerate_image' => $schema->boolean() + ->description('Whether the background image should be regenerated. Use false when only text/typo changes are needed and visual should stay the same.') + ->required(), ]; } diff --git a/app/Jobs/Ai/RegeneratePostMediaImage.php b/app/Jobs/Ai/RegeneratePostMediaImage.php index 397f1cac..ac3ecba7 100644 --- a/app/Jobs/Ai/RegeneratePostMediaImage.php +++ b/app/Jobs/Ai/RegeneratePostMediaImage.php @@ -116,11 +116,12 @@ private function resolveAiMediaTarget(Post $post): array * title: string, * body: string, * keywords: array, + * background_path: string, * language: string, * width: int, * height: int * } $baseContext - * @return array{title: string, body: string, keywords: array} + * @return array{title: string, body: string, keywords: array, regenerate_image: bool} */ private function regenerateSlideCopy(Workspace $workspace, Post $post, array $baseContext): array { @@ -154,12 +155,13 @@ private function regenerateSlideCopy(Workspace $workspace, Post $post, array $ba * title: string, * body: string, * keywords: array, + * background_path: string, * language: string, * width: int, * height: int * } $baseContext * @param array $structured - * @return array{title: string, body: string, keywords: array} + * @return array{title: string, body: string, keywords: array, regenerate_image: bool} */ private function mergeStructuredCopy(array $baseContext, array $structured): array { @@ -169,11 +171,12 @@ private function mergeStructuredCopy(array $baseContext, array $structured): arr 'title' => trim((string) data_get($structured, 'title', $baseContext['title'])), 'body' => trim((string) data_get($structured, 'body', $baseContext['body'])), 'keywords' => $keywords !== [] ? $keywords : $baseContext['keywords'], + 'regenerate_image' => (bool) data_get($structured, 'regenerate_image', true), ]; } /** - * @param array{title: string, body: string, keywords: array} $copy + * @param array{title: string, body: string, keywords: array, regenerate_image: bool} $copy * @param array{ * title: string, * body: string, @@ -196,6 +199,14 @@ private function renderRegeneratedImage( throw new RuntimeException('No social account available for image footer rendering.'); } + $reusedBackgroundPath = null; + if (! $copy['regenerate_image']) { + $reusedBackgroundPath = (string) data_get($baseContext, 'background_path', ''); + if ($reusedBackgroundPath === '') { + $reusedBackgroundPath = null; + } + } + $rendered = app(TemplateImageGenerator::class)->render( workspace: $workspace, socialAccount: $socialAccount, @@ -204,6 +215,7 @@ private function renderRegeneratedImage( imageKeywords: $copy['keywords'], width: $baseContext['width'], height: $baseContext['height'], + backgroundPath: $reusedBackgroundPath, ); if (! $rendered) { @@ -225,9 +237,11 @@ private function replaceMediaOnPost( array $rendered, ): array { $renderedPath = $rendered['path']; + $newBackgroundPath = (string) data_get($rendered, 'source_meta.background_path', ''); + $oldBackgroundPath = (string) data_get($target, 'source_meta.background_path', ''); try { - return DB::transaction(function () use ($post, $rendered, $target, $workspace) { + $newMediaItem = DB::transaction(function () use ($post, $rendered, $target, $workspace) { $newMediaItem = $this->buildAiMediaItem($workspace, $rendered); $fresh = Post::query()->whereKey($post->id)->lockForUpdate()->firstOrFail(); @@ -245,8 +259,17 @@ private function replaceMediaOnPost( return $newMediaItem; }); + + if ($oldBackgroundPath !== '' && $oldBackgroundPath !== $newBackgroundPath && Storage::exists($oldBackgroundPath)) { + Storage::delete($oldBackgroundPath); + } + + return $newMediaItem; } catch (Throwable $exception) { $this->discardRenderedFile($renderedPath); + if ($newBackgroundPath !== '' && $newBackgroundPath !== $oldBackgroundPath && Storage::exists($newBackgroundPath)) { + Storage::delete($newBackgroundPath); + } throw $exception; } @@ -265,6 +288,7 @@ private function discardRenderedFile(string $path): void * title: string, * body: string, * keywords: array, + * background_path: string, * language: string, * width: int, * height: int @@ -296,6 +320,7 @@ private function buildSourceContext(array $sourceMeta, Post $post, Workspace $wo 'title' => $title, 'body' => $body, 'keywords' => $keywords, + 'background_path' => (string) data_get($sourceMeta, 'background_path', ''), 'language' => (string) data_get($sourceMeta, 'language', $workspace->content_language), 'width' => (int) data_get($sourceMeta, 'width', TemplateImageGenerator::DEFAULT_WIDTH), 'height' => (int) data_get($sourceMeta, 'height', TemplateImageGenerator::DEFAULT_HEIGHT), diff --git a/app/Services/Image/TemplateImageGenerator.php b/app/Services/Image/TemplateImageGenerator.php index 756eb8fd..a33a424e 100644 --- a/app/Services/Image/TemplateImageGenerator.php +++ b/app/Services/Image/TemplateImageGenerator.php @@ -50,6 +50,7 @@ public function render( array $imageKeywords, int $width = self::DEFAULT_WIDTH, int $height = self::DEFAULT_HEIGHT, + ?string $backgroundPath = null, ): ?array { $this->width = $width; $this->height = $height; @@ -63,18 +64,33 @@ public function render( }; $language = $workspace->content_language; - $imageData = $this->aiImage->generate( - keywords: $imageKeywords, - style: $imageStyle, - orientation: $orientation, - language: $language, - brandColor: $workspace->brand_color, - backgroundColor: $workspace->background_color, - textColor: $workspace->text_color, - brandDescription: $workspace->brand_description, - ); - if ($imageData === null) { - return null; + $generatedNewBackground = false; + $resolvedBackgroundPath = null; + $imageData = null; + + if (is_string($backgroundPath) && trim($backgroundPath) !== '' && Storage::exists($backgroundPath)) { + $resolvedBackgroundPath = $backgroundPath; + $imageData = Storage::get($backgroundPath); + } + + if (! is_string($imageData) || $imageData === '') { + $imageData = $this->aiImage->generate( + keywords: $imageKeywords, + style: $imageStyle, + orientation: $orientation, + language: $language, + brandColor: $workspace->brand_color, + backgroundColor: $workspace->background_color, + textColor: $workspace->text_color, + brandDescription: $workspace->brand_description, + ); + + if ($imageData === null) { + return null; + } + + $generatedNewBackground = true; + $resolvedBackgroundPath = $this->storeBackgroundImage($imageData); } $manager = new ImageManager(Driver::class); @@ -85,16 +101,18 @@ public function render( $filename = 'ai-images/'.uniqid('slide_', true).'.webp'; Storage::put($filename, (string) $canvas->encode(new WebpEncoder(quality: 85))); - RecordAiUsage::recordImage( - workspace: $workspace, - provider: 'openai', - model: AiImageClient::MODEL, - metadata: [ - 'image_style' => $imageStyle->value, - 'width' => $this->width, - 'height' => $this->height, - ], - ); + if ($generatedNewBackground) { + RecordAiUsage::recordImage( + workspace: $workspace, + provider: 'openai', + model: AiImageClient::MODEL, + metadata: [ + 'image_style' => $imageStyle->value, + 'width' => $this->width, + 'height' => $this->height, + ], + ); + } RecordAiUsage::recordTemplate( workspace: $workspace, @@ -119,10 +137,22 @@ public function render( 'brand_color' => $workspace->brand_color, 'background_color' => $workspace->background_color, 'text_color' => $workspace->text_color, + 'background_path' => $resolvedBackgroundPath, ], ]; } + private function storeBackgroundImage(string $imageData): string + { + $manager = new ImageManager(Driver::class); + $background = $manager->decodeBinary($imageData)->cover($this->width, $this->height); + $backgroundPath = 'ai-images/'.uniqid('bg_', true).'.webp'; + + Storage::put($backgroundPath, (string) $background->encode(new WebpEncoder(quality: 85))); + + return $backgroundPath; + } + /** * Pick the closest aspect ratio for the active canvas so the AI image * generator returns a photo that doesn't need heavy cropping. diff --git a/resources/views/prompts/post_image/regenerator.blade.php b/resources/views/prompts/post_image/regenerator.blade.php index 1a4af529..372bfbd9 100644 --- a/resources/views/prompts/post_image/regenerator.blade.php +++ b/resources/views/prompts/post_image/regenerator.blade.php @@ -6,6 +6,9 @@ - Fix spelling and grammar when needed. - Keep output concise and suitable for image overlays. - Preserve intent and topic; only change what is needed. +- Set `regenerate_image` to: + - `false` when changes are text-only (typos, wording, capitalization, punctuation, CTA wording) and the visual background should stay the same. + - `true` when the user asks to change visual style, scene, objects, mood, colors, composition, or anything that requires a new background image. Return JSON only, following the schema. diff --git a/tests/Unit/Services/Image/TemplateImageGeneratorTest.php b/tests/Unit/Services/Image/TemplateImageGeneratorTest.php index 2abfa5e0..7c3f806c 100644 --- a/tests/Unit/Services/Image/TemplateImageGeneratorTest.php +++ b/tests/Unit/Services/Image/TemplateImageGeneratorTest.php @@ -81,10 +81,34 @@ ->toHaveKey('title', 'Hello World') ->toHaveKey('brand_color', '#0000ff') ->toHaveKey('background_color', '#ffffff') - ->toHaveKey('text_color', '#000000'); + ->toHaveKey('text_color', '#000000') + ->toHaveKey('background_path'); } Image::assertGenerated(fn ($prompt) => $prompt->contains('kitchen') && $prompt->contains('BRAND COLOR PALETTE') && $prompt->contains('blue')); })->skip(fn () => ! extension_loaded('gd'), 'GD extension required'); + +test('reuses existing background path when provided', function () use ($minimalPng) { + if (! file_exists(base_path('resources/fonts/Inter-Bold.ttf'))) { + $this->markTestSkipped('Inter fonts not available — skipping render-dependent test.'); + } + + $backgroundPath = 'ai-images/reuse-bg.webp'; + Storage::put($backgroundPath, $minimalPng()); + + $service = new TemplateImageGenerator(new BrandColorMapper, new AiImageClient); + $result = $service->render( + workspace: Workspace::factory()->make(), + socialAccount: SocialAccount::factory()->make(['username' => 'testuser', 'display_name' => 'Test User']), + title: 'Updated title', + body: 'Updated body', + imageKeywords: [], + backgroundPath: $backgroundPath, + ); + + expect($result)->not->toBeNull(); + expect(data_get($result, 'source_meta.background_path'))->toBe($backgroundPath); + Image::assertNothingGenerated(); +})->skip(fn () => ! extension_loaded('gd'), 'GD extension required');