From aa9075d922d2a378ccd7ba9054f460ad30316583 Mon Sep 17 00:00:00 2001 From: Torsten Dittmann Date: Sun, 6 Sep 2026 10:10:11 +0000 Subject: [PATCH 01/13] Add automatic image crop gravity --- app/config/variables.php | 10 +++ app/init/resources.php | 10 +++ docker-compose.yml | 9 +++ src/Appwrite/Autogravity/Client.php | 51 ++++++++++++ src/Appwrite/Autogravity/Detector.php | 39 +++++++++ src/Appwrite/Autogravity/Exception.php | 7 ++ src/Appwrite/Autogravity/Gravity.php | 61 ++++++++++++++ .../Http/Buckets/Files/Preview/Get.php | 53 +++++++++++- .../Storage/StorageCustomServerTest.php | 49 ++++++++++++ tests/unit/Autogravity/ClientTest.php | 80 +++++++++++++++++++ tests/unit/Autogravity/DetectorTest.php | 70 ++++++++++++++++ tests/unit/Autogravity/GravityTest.php | 47 +++++++++++ tests/unit/Docker/Compose/GeneratorTest.php | 2 + 13 files changed, 486 insertions(+), 2 deletions(-) create mode 100644 src/Appwrite/Autogravity/Client.php create mode 100644 src/Appwrite/Autogravity/Detector.php create mode 100644 src/Appwrite/Autogravity/Exception.php create mode 100644 src/Appwrite/Autogravity/Gravity.php create mode 100644 tests/unit/Autogravity/ClientTest.php create mode 100644 tests/unit/Autogravity/DetectorTest.php create mode 100644 tests/unit/Autogravity/GravityTest.php diff --git a/app/config/variables.php b/app/config/variables.php index aed2f57f54..e68f20dfa4 100644 --- a/app/config/variables.php +++ b/app/config/variables.php @@ -904,6 +904,16 @@ return [ 'question' => '', 'filter' => '' ], + [ + 'name' => '_APP_AUTOGRAVITY_HOST', + 'description' => 'The host used by Appwrite to determine automatic image crop gravity.', + 'introduction' => '2.0.0', + 'default' => 'http://appwrite-autogravity:8080', + 'required' => false, + 'overwrite' => true, + 'question' => '', + 'filter' => '' + ], [ 'name' => '_APP_STORAGE_ANTIVIRUS', 'description' => 'This variable allows you to disable the internal anti-virus scans. This value is set to \'disabled\' by default, to enable the scans set the value to \'enabled\'. Before enabling, you must add the ClamAV service and depend on it on main Appwrite service.', diff --git a/app/init/resources.php b/app/init/resources.php index 4897062b00..571ee64202 100644 --- a/app/init/resources.php +++ b/app/init/resources.php @@ -1,5 +1,7 @@ set('screenshots', function () { return new ScreenshotsClient($client); }, []); +$container->set('autogravity', function (Cache $cache) { + $client = (new Client((new SwooleClientAdapter())->withConnectionReuse())) + ->withBaseUri(System::getEnv('_APP_AUTOGRAVITY_HOST', 'http://appwrite-autogravity:8080')) + ->withTimeout(30); + + return new AutogravityDetector(new AutogravityClient($client), $cache); +}, ['cache']); + $container->set('telemetry', fn () => new NoTelemetry(), []); $container->set('authorization', fn () => new Authorization(), []); diff --git a/docker-compose.yml b/docker-compose.yml index f2894a5ee3..8daed5b8ae 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -76,6 +76,7 @@ services: - redis - ${_APP_DB_HOST:-postgresql} - appwrite-geo + - appwrite-autogravity environment: - _APP_ENV - _APP_USAGE_STATS @@ -163,6 +164,7 @@ services: - _APP_SMTP_PASSWORD - _APP_STORAGE_LIMIT - _APP_STORAGE_PREVIEW_LIMIT + - _APP_AUTOGRAVITY_HOST - _APP_STORAGE_ANTIVIRUS - _APP_STORAGE_ANTIVIRUS_HOST - _APP_STORAGE_ANTIVIRUS_PORT @@ -1578,6 +1580,13 @@ services: networks: - appwrite + appwrite-autogravity: + container_name: appwrite-autogravity + image: ghcr.io/appwrite/autogravity:0.0.2 + restart: unless-stopped + networks: + - appwrite + clickhouse: image: clickhouse/clickhouse-server:26.4.3-alpine restart: unless-stopped diff --git a/src/Appwrite/Autogravity/Client.php b/src/Appwrite/Autogravity/Client.php new file mode 100644 index 0000000000..03dea42189 --- /dev/null +++ b/src/Appwrite/Autogravity/Client.php @@ -0,0 +1,51 @@ +factory = new Factory(); + } + + /** + * Find the image's focal point. + * + * @throws Exception on an error response or malformed result + * @throws ClientExceptionInterface on transport failure + */ + public function analyze(string $image): Gravity + { + $request = $this->factory->body( + Method::POST, + 'analyze', + $image, + 'application/octet-stream' + ); + $response = $this->client->sendRequest($request); + $status = $response->getStatusCode(); + $body = (string) $response->getBody(); + $result = \json_decode($body, true); + + if ($status >= 400) { + $error = \is_array($result) ? ($result['error'] ?? null) : null; + throw new Exception(\is_string($error) ? $error : 'Autogravity failed with status ' . $status, $status); + } + + $x = \is_array($result) ? ($result['gravity']['x'] ?? null) : null; + $y = \is_array($result) ? ($result['gravity']['y'] ?? null) : null; + if (!\is_numeric($x) || !\is_numeric($y)) { + throw new Exception('Autogravity returned an invalid gravity', $status); + } + + return new Gravity((float) $x, (float) $y); + } +} diff --git a/src/Appwrite/Autogravity/Detector.php b/src/Appwrite/Autogravity/Detector.php new file mode 100644 index 0000000000..f3bf4bcce6 --- /dev/null +++ b/src/Appwrite/Autogravity/Detector.php @@ -0,0 +1,39 @@ +cache->load($key, self::CACHE_TTL); + if ( + \is_array($cached) + && isset($cached['x'], $cached['y']) + && \is_numeric($cached['x']) + && \is_numeric($cached['y']) + && $cached['x'] >= 0 + && $cached['x'] <= 1 + && $cached['y'] >= 0 + && $cached['y'] <= 1 + ) { + return new Gravity((float) $cached['x'], (float) $cached['y']); + } + + $gravity = $this->client->analyze($analysis ?? $source); + $this->cache->save($key, $gravity->getArrayCopy()); + + return $gravity; + } +} diff --git a/src/Appwrite/Autogravity/Exception.php b/src/Appwrite/Autogravity/Exception.php new file mode 100644 index 0000000000..a94252b7b5 --- /dev/null +++ b/src/Appwrite/Autogravity/Exception.php @@ -0,0 +1,7 @@ + 1 || $y < 0 || $y > 1) { + throw new Exception('Autogravity returned an invalid gravity'); + } + } + + public function getType(int $width, int $height, int $sourceWidth, int $sourceHeight): string + { + $sourceAspect = $sourceWidth / $sourceHeight; + $targetAspect = $width / $height; + if ($targetAspect > $sourceAspect) { + $resizeWidth = $width; + $resizeHeight = (int) \ceil($width / $sourceAspect); + } else { + $resizeWidth = (int) \ceil($height * $sourceAspect); + $resizeHeight = $height; + } + + $horizontal = match (true) { + $this->x * $resizeWidth < ($resizeWidth - $width) / 2 => 'left', + $this->x * $resizeWidth > ($resizeWidth + $width) / 2 => 'right', + default => '', + }; + $vertical = match (true) { + $this->y * $resizeHeight < ($resizeHeight - $height) / 2 => 'top', + $this->y * $resizeHeight > ($resizeHeight + $height) / 2 => 'bottom', + default => '', + }; + + return match ([$vertical, $horizontal]) { + ['', ''] => Image::GRAVITY_CENTER, + ['', 'left'] => Image::GRAVITY_LEFT, + ['', 'right'] => Image::GRAVITY_RIGHT, + ['top', ''] => Image::GRAVITY_TOP, + ['top', 'left'] => Image::GRAVITY_TOP_LEFT, + ['top', 'right'] => Image::GRAVITY_TOP_RIGHT, + ['bottom', ''] => Image::GRAVITY_BOTTOM, + ['bottom', 'left'] => Image::GRAVITY_BOTTOM_LEFT, + ['bottom', 'right'] => Image::GRAVITY_BOTTOM_RIGHT, + }; + } + + /** + * @return array{x: float, y: float} + */ + public function getArrayCopy(): array + { + return ['x' => $this->x, 'y' => $this->y]; + } +} diff --git a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php index 7c7eaacf71..8fd6b02bd4 100644 --- a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php +++ b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php @@ -2,6 +2,7 @@ namespace Appwrite\Platform\Modules\Storage\Http\Buckets\Files\Preview; +use Appwrite\Autogravity\Detector as AutogravityDetector; use Appwrite\Extend\Exception; use Appwrite\OpenSSL\OpenSSL; use Appwrite\Platform\Action; @@ -40,6 +41,10 @@ class Get extends Action { use HTTP; + private const AUTOGRAVITY_MAX_BYTES = 10 * 1024 * 1024; + + private const GRAVITY_AUTO = 'auto'; + public static function getName() { return 'getFilePreview'; @@ -79,7 +84,7 @@ class Get extends Action ->param('fileId', '', new UID(), 'File ID') ->param('width', 0, new Range(0, 4000), 'Resize preview image width, Pass an integer between 0 to 4000.', true) ->param('height', 0, new Range(0, 4000), 'Resize preview image height, Pass an integer between 0 to 4000.', true) - ->param('gravity', Image::GRAVITY_CENTER, new WhiteList(Image::getGravityTypes()), 'Image crop gravity. Can be one of ' . implode(",", Image::getGravityTypes()), true, enum: new Enum(name: 'ImageGravity')) + ->param('gravity', Image::GRAVITY_CENTER, new WhiteList([self::GRAVITY_AUTO, ...Image::getGravityTypes()]), 'Image crop gravity. Can be one of ' . implode(",", [self::GRAVITY_AUTO, ...Image::getGravityTypes()]), true, enum: new Enum(name: 'ImageGravity')) ->param('quality', -1, new Range(-1, 100), 'Preview image quality. Pass an integer between 0 to 100. Defaults to keep existing image quality.', true) ->param('borderWidth', 0, new Range(0, 100), 'Preview image border in pixels. Pass an integer between 0 to 100. Defaults to 0.', true) ->param('borderColor', '', new HexColor(), 'Preview image border color. Use a valid HEX color, no # is needed for prefix.', true) @@ -100,6 +105,7 @@ class Get extends Action ->inject('authorization') ->inject('user') ->inject('cacheControlForStorage') + ->inject('autogravity') ->callback($this->action(...)); } @@ -127,7 +133,8 @@ class Get extends Action Document $project, Authorization $authorization, User $user, - callable $cacheControlForStorage + callable $cacheControlForStorage, + AutogravityDetector $autogravity ) { if (!\extension_loaded('imagick')) { @@ -264,6 +271,19 @@ class Get extends Action throw new Exception(Exception::STORAGE_FILE_TYPE_UNSUPPORTED, $e->getMessage()); } + if ( + $gravity === self::GRAVITY_AUTO + && $width > 0 + && $height > 0 + && isset($sourceWidth, $sourceHeight) + && \abs($width / $height - $sourceWidth / $sourceHeight) > 0.000001 + ) { + $automaticGravity = $autogravity->get($source, $this->prepareForAutogravity($source, $type)); + $gravity = $automaticGravity->getType($width, $height, $sourceWidth, $sourceHeight); + } elseif ($gravity === self::GRAVITY_AUTO) { + $gravity = Image::GRAVITY_CENTER; + } + if ($width > 0 || $height > 0 || $gravity !== Image::GRAVITY_CENTER) { Span::add('storage.transform.crop.width', $width); Span::add('storage.transform.crop.height', $height); @@ -351,4 +371,33 @@ class Get extends Action unset($image); } + + private function prepareForAutogravity(string $source, string $type): string + { + if ( + \in_array($type, ['jpg', 'jpeg', 'png', 'webp'], true) + && \strlen($source) < self::AUTOGRAVITY_MAX_BYTES + ) { + return $source; + } + + $image = new \Imagick(); + $image->readImageBlob($source); + $image->setFirstIterator(); + $orientation = $image->getImageProperties()['exif:Orientation'] ?? null; + $rotation = match ($orientation) { + '3' => 180, + '6' => 90, + '8' => -90, + default => 0, + }; + if ($rotation !== 0) { + $image->rotateImage(new \ImagickPixel('transparent'), $rotation); + } + $image->resizeImage(320, 320, \Imagick::FILTER_LANCZOS, 1, false); + $image->setImageFormat('png'); + $image->stripImage(); + + return $image->getImageBlob(); + } } diff --git a/tests/e2e/Services/Storage/StorageCustomServerTest.php b/tests/e2e/Services/Storage/StorageCustomServerTest.php index 39a1b112d7..9172822610 100644 --- a/tests/e2e/Services/Storage/StorageCustomServerTest.php +++ b/tests/e2e/Services/Storage/StorageCustomServerTest.php @@ -55,6 +55,55 @@ final class StorageCustomServerTest extends Scope return self::$cachedBucket[$cacheKey]; } + public function testGetFilePreviewWithAutomaticGravity(): void + { + $bucketId = $this->setupBucket()['bucketId']; + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', array_merge([ + 'content-type' => 'multipart/form-data', + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'fileId' => ID::unique(), + 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'autogravity.png'), + ]); + + $this->assertEquals(201, $file['headers']['status-code']); + + $headers = array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()); + $params = [ + 'width' => 120, + 'height' => 320, + 'gravity' => 'auto', + 'output' => 'png', + ]; + $path = '/storage/buckets/' . $bucketId . '/files/' . $file['body']['$id'] . '/preview'; + + $preview = $this->client->call(Client::METHOD_GET, $path, $headers, $params); + + $this->assertEquals(200, $preview['headers']['status-code']); + $this->assertEquals('image/png', $preview['headers']['content-type']); + $this->assertEquals('miss', $preview['headers']['x-appwrite-cache']); + $this->assertNotEmpty($preview['body']); + + $image = new \Imagick(); + $image->readImageBlob($preview['body']); + $this->assertSame(120, $image->getImageWidth()); + $this->assertSame(320, $image->getImageHeight()); + + $cached = []; + $this->assertEventually(function () use (&$cached, $path, $headers, $params, $preview): void { + $cached = $this->client->call(Client::METHOD_GET, $path, $headers, $params); + + $this->assertSame('hit', $cached['headers']['x-appwrite-cache']); + $this->assertSame($preview['body'], $cached['body']); + }); + + $this->assertEquals(200, $cached['headers']['status-code']); + $this->assertEquals('image/png', $cached['headers']['content-type']); + } + public function testCreateBucket(): void { /** diff --git a/tests/unit/Autogravity/ClientTest.php b/tests/unit/Autogravity/ClientTest.php new file mode 100644 index 0000000000..fd05fbc963 --- /dev/null +++ b/tests/unit/Autogravity/ClientTest.php @@ -0,0 +1,80 @@ +test->setRequest($request); + return $this->response; + } + }); + } + + public function setRequest(RequestInterface $request): void + { + $this->request = $request; + } + + public function testAnalyze(): void + { + $response = (new Response(200, body: new Stream('{"gravity":{"x":0.7,"y":0.4},"confidence":0.9}'))) + ->withHeader('Content-Type', 'application/json'); + + $gravity = $this->client($response)->analyze('image-bytes'); + + $this->assertSame(0.7, $gravity->x); + $this->assertSame(0.4, $gravity->y); + $this->assertInstanceOf(RequestInterface::class, $this->request); + $this->assertSame('POST', $this->request->getMethod()); + $this->assertSame('analyze', (string) $this->request->getUri()); + $this->assertSame('application/octet-stream', $this->request->getHeaderLine('Content-Type')); + $this->assertSame('image-bytes', (string) $this->request->getBody()); + } + + public function testAnalyzeError(): void + { + $this->expectException(Exception::class); + $this->expectExceptionMessage('invalid image'); + $this->expectExceptionCode(400); + + $this->client(new Response(400, body: new Stream('{"error":"invalid image"}')))->analyze('invalid'); + } + + public function testAnalyzeInvalidResponse(): void + { + $this->expectException(Exception::class); + $this->expectExceptionMessage('Autogravity returned an invalid gravity'); + + $this->client(new Response(200, body: new Stream('{"gravity":{"x":2,"y":0.5}}')))->analyze('image'); + } + + public function testAnalyzeErrorWithoutBody(): void + { + $this->expectException(Exception::class); + $this->expectExceptionMessage('Autogravity failed with status 502'); + + $this->client(new Response(502, body: new Stream('')))->analyze('image'); + } +} diff --git a/tests/unit/Autogravity/DetectorTest.php b/tests/unit/Autogravity/DetectorTest.php new file mode 100644 index 0000000000..1890baee9d --- /dev/null +++ b/tests/unit/Autogravity/DetectorTest.php @@ -0,0 +1,70 @@ +get('source-image', 'first-analysis-image'); + $second = $detector->get('source-image', 'different-analysis-image'); + + $this->assertSame(0.7, $first->x); + $this->assertSame(0.4, $first->y); + $this->assertSame($first->getArrayCopy(), $second->getArrayCopy()); + $this->assertSame(1, $http->requests); + $this->assertSame('first-analysis-image', $http->lastBody); + } + + public function testDifferentSourcesAreDetectedSeparately(): void + { + $http = new CountingClient(new Response( + 200, + body: new Stream('{"gravity":{"x":0.5,"y":0.5},"confidence":0.9}') + )); + $detector = new Detector(new Client($http), new Cache(new Memory())); + + $detector->get('first-source'); + $detector->get('second-source'); + + $this->assertSame(2, $http->requests); + } +} + +final class CountingClient implements ClientInterface +{ + public int $requests = 0; + + public string $lastBody = ''; + + public function __construct(private readonly ResponseInterface $response) + { + } + + public function sendRequest(RequestInterface $request): ResponseInterface + { + $this->requests++; + $this->lastBody = (string) $request->getBody(); + + return $this->response; + } +} diff --git a/tests/unit/Autogravity/GravityTest.php b/tests/unit/Autogravity/GravityTest.php new file mode 100644 index 0000000000..116d924c96 --- /dev/null +++ b/tests/unit/Autogravity/GravityTest.php @@ -0,0 +1,47 @@ + + */ + public static function typeProvider(): array + { + return [ + 'landscape to portrait, subject right' => [0.7, 0.5, 180, 320, 1280, 720, Image::GRAVITY_RIGHT], + 'landscape to portrait, subject left' => [0.2, 0.5, 180, 320, 1280, 720, Image::GRAVITY_LEFT], + 'landscape to wide, subject remains visible' => [0.7, 0.5, 800, 600, 1280, 720, Image::GRAVITY_CENTER], + 'portrait to landscape, subject top' => [0.5, 0.1, 600, 300, 600, 900, Image::GRAVITY_TOP], + 'portrait to landscape, subject bottom' => [0.9, 0.9, 600, 300, 600, 900, Image::GRAVITY_BOTTOM], + ]; + } + + #[DataProvider('typeProvider')] + public function testGetType(float $x, float $y, int $width, int $height, int $sourceWidth, int $sourceHeight, string $expected): void + { + $this->assertSame($expected, (new Gravity($x, $y))->getType($width, $height, $sourceWidth, $sourceHeight)); + } + + public function testRejectsInvalidCoordinates(): void + { + $this->expectException(Exception::class); + $this->expectExceptionMessage('Autogravity returned an invalid gravity'); + + new Gravity(1.1, 0.5); + } + + public function testGetArrayCopy(): void + { + $this->assertSame(['x' => 0.2, 'y' => 0.8], (new Gravity(0.2, 0.8))->getArrayCopy()); + } +} diff --git a/tests/unit/Docker/Compose/GeneratorTest.php b/tests/unit/Docker/Compose/GeneratorTest.php index 7202fff215..345941a272 100644 --- a/tests/unit/Docker/Compose/GeneratorTest.php +++ b/tests/unit/Docker/Compose/GeneratorTest.php @@ -68,6 +68,8 @@ final class GeneratorTest extends TestCase $this->assertArrayHasKey('appwrite-task-scheduler', $compose['services']); $this->assertArrayHasKey('appwrite-task-interval', $compose['services']); $this->assertArrayHasKey('appwrite-embedding', $compose['services']); + $this->assertArrayHasKey('appwrite-autogravity', $compose['services']); + $this->assertSame('ghcr.io/appwrite/autogravity:0.0.2', $compose['services']['appwrite-autogravity']['image']); $this->assertArrayNotHasKey('profiles', $compose['services']['appwrite-worker']); $this->assertArrayNotHasKey('profiles', $compose['services']['appwrite-task-scheduler']); } From dc64b43b1b53ad080f45182651f09fb9e71c7ddf Mon Sep 17 00:00:00 2001 From: Torsten Dittmann Date: Sun, 6 Sep 2026 10:32:18 +0000 Subject: [PATCH 02/13] Fix automatic gravity orientation mapping --- src/Appwrite/Autogravity/Gravity.php | 11 ++++++++++ .../Http/Buckets/Files/Preview/Get.php | 14 +++++++++---- .../Storage/StorageCustomServerTest.php | 19 ++++++++++++++++- tests/unit/Autogravity/GravityTest.php | 21 +++++++++++++++++++ 4 files changed, 60 insertions(+), 5 deletions(-) diff --git a/src/Appwrite/Autogravity/Gravity.php b/src/Appwrite/Autogravity/Gravity.php index ca1b3d54ab..6b5580a9ac 100644 --- a/src/Appwrite/Autogravity/Gravity.php +++ b/src/Appwrite/Autogravity/Gravity.php @@ -51,6 +51,17 @@ class Gravity }; } + public function unrotate(int $rotation): self + { + return match (($rotation % 360 + 360) % 360) { + 0 => $this, + 90 => new self($this->y, 1 - $this->x), + 180 => new self(1 - $this->x, 1 - $this->y), + 270 => new self(1 - $this->y, $this->x), + default => throw new Exception('Autogravity cannot reverse an unsupported rotation'), + }; + } + /** * @return array{x: float, y: float} */ diff --git a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php index 8fd6b02bd4..99b8faddc4 100644 --- a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php +++ b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php @@ -278,7 +278,10 @@ class Get extends Action && isset($sourceWidth, $sourceHeight) && \abs($width / $height - $sourceWidth / $sourceHeight) > 0.000001 ) { - $automaticGravity = $autogravity->get($source, $this->prepareForAutogravity($source, $type)); + $prepared = $this->prepareForAutogravity($source, $type); + $automaticGravity = $autogravity + ->get($source, $prepared['source']) + ->unrotate($prepared['rotation']); $gravity = $automaticGravity->getType($width, $height, $sourceWidth, $sourceHeight); } elseif ($gravity === self::GRAVITY_AUTO) { $gravity = Image::GRAVITY_CENTER; @@ -372,13 +375,16 @@ class Get extends Action unset($image); } - private function prepareForAutogravity(string $source, string $type): string + /** + * @return array{source: string, rotation: int} + */ + private function prepareForAutogravity(string $source, string $type): array { if ( \in_array($type, ['jpg', 'jpeg', 'png', 'webp'], true) && \strlen($source) < self::AUTOGRAVITY_MAX_BYTES ) { - return $source; + return ['source' => $source, 'rotation' => 0]; } $image = new \Imagick(); @@ -398,6 +404,6 @@ class Get extends Action $image->setImageFormat('png'); $image->stripImage(); - return $image->getImageBlob(); + return ['source' => $image->getImageBlob(), 'rotation' => $rotation]; } } diff --git a/tests/e2e/Services/Storage/StorageCustomServerTest.php b/tests/e2e/Services/Storage/StorageCustomServerTest.php index 9172822610..d74091b26a 100644 --- a/tests/e2e/Services/Storage/StorageCustomServerTest.php +++ b/tests/e2e/Services/Storage/StorageCustomServerTest.php @@ -58,13 +58,25 @@ final class StorageCustomServerTest extends Scope public function testGetFilePreviewWithAutomaticGravity(): void { $bucketId = $this->setupBucket()['bucketId']; + $source = \tempnam(\sys_get_temp_dir(), 'appwrite-autogravity-'); + if ($source === false) { + $this->fail('Failed to create a temporary image'); + } + $subject = new \Imagick(__DIR__ . '/../../../resources/disk-a/kitten-1.jpg'); + $subject->resizeImage(900, 0, \Imagick::FILTER_LANCZOS, 1); + $canvas = new \Imagick(); + $canvas->newImage(2400, 1920, 'white', 'png'); + $canvas->compositeImage($subject, \Imagick::COMPOSITE_OVER, 1450, 0); + $canvas->writeImage($source); + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'autogravity.png'), + 'file' => new CURLFile($source, 'image/png', 'autogravity.png'), ]); + \unlink($source); $this->assertEquals(201, $file['headers']['status-code']); @@ -92,6 +104,11 @@ final class StorageCustomServerTest extends Scope $this->assertSame(120, $image->getImageWidth()); $this->assertSame(320, $image->getImageHeight()); + $right = $this->client->call(Client::METHOD_GET, $path, $headers, [...$params, 'gravity' => 'right']); + $center = $this->client->call(Client::METHOD_GET, $path, $headers, [...$params, 'gravity' => 'center']); + $this->assertSame($right['body'], $preview['body']); + $this->assertNotSame($center['body'], $preview['body']); + $cached = []; $this->assertEventually(function () use (&$cached, $path, $headers, $params, $preview): void { $cached = $this->client->call(Client::METHOD_GET, $path, $headers, $params); diff --git a/tests/unit/Autogravity/GravityTest.php b/tests/unit/Autogravity/GravityTest.php index 116d924c96..25f3d5d568 100644 --- a/tests/unit/Autogravity/GravityTest.php +++ b/tests/unit/Autogravity/GravityTest.php @@ -40,6 +40,27 @@ final class GravityTest extends TestCase new Gravity(1.1, 0.5); } + /** + * @return array + */ + public static function rotationProvider(): array + { + return [ + 'clockwise' => [90, 0.8, 0.75], + 'upside down' => [180, 0.75, 0.2], + 'counterclockwise' => [-90, 0.2, 0.25], + ]; + } + + #[DataProvider('rotationProvider')] + public function testUnrotate(int $rotation, float $expectedX, float $expectedY): void + { + $gravity = (new Gravity(0.25, 0.8))->unrotate($rotation); + + $this->assertEqualsWithDelta($expectedX, $gravity->x, 0.000001); + $this->assertEqualsWithDelta($expectedY, $gravity->y, 0.000001); + } + public function testGetArrayCopy(): void { $this->assertSame(['x' => 0.2, 'y' => 0.8], (new Gravity(0.2, 0.8))->getArrayCopy()); From 0737b917653743c1a00fd0aa8d065f8dd79ed4bf Mon Sep 17 00:00:00 2001 From: Torsten Dittmann Date: Sun, 6 Sep 2026 10:40:15 +0000 Subject: [PATCH 03/13] Require explicit Autogravity configuration --- .env | 1 + app/config/variables.php | 2 +- app/init/resources.php | 11 +++++++---- src/Appwrite/Autogravity/Detector.php | 11 ++++++++++- .../Storage/Http/Buckets/Files/Preview/Get.php | 14 ++++++++------ .../Services/Storage/StorageCustomServerTest.php | 12 ++++++++++++ tests/unit/Autogravity/DetectorTest.php | 14 ++++++++++++++ 7 files changed, 53 insertions(+), 12 deletions(-) diff --git a/.env b/.env index 905b9b5e84..2ab4f1005c 100644 --- a/.env +++ b/.env @@ -76,6 +76,7 @@ _APP_EMBEDDING_TIMEOUT=30000 _APP_STORAGE_DEVICE=Local _APP_STORAGE_LIMIT=30000000 _APP_STORAGE_PREVIEW_LIMIT=20000000 +_APP_AUTOGRAVITY_HOST=http://appwrite-autogravity:8080 _APP_STORAGE_ANTIVIRUS=disabled _APP_STORAGE_ANTIVIRUS_HOST=clamav _APP_STORAGE_ANTIVIRUS_PORT=3310 diff --git a/app/config/variables.php b/app/config/variables.php index e68f20dfa4..ef208047a6 100644 --- a/app/config/variables.php +++ b/app/config/variables.php @@ -908,7 +908,7 @@ return [ 'name' => '_APP_AUTOGRAVITY_HOST', 'description' => 'The host used by Appwrite to determine automatic image crop gravity.', 'introduction' => '2.0.0', - 'default' => 'http://appwrite-autogravity:8080', + 'default' => '', 'required' => false, 'overwrite' => true, 'question' => '', diff --git a/app/init/resources.php b/app/init/resources.php index 571ee64202..3ab02d29e4 100644 --- a/app/init/resources.php +++ b/app/init/resources.php @@ -105,11 +105,14 @@ $container->set('screenshots', function () { }, []); $container->set('autogravity', function (Cache $cache) { - $client = (new Client((new SwooleClientAdapter())->withConnectionReuse())) - ->withBaseUri(System::getEnv('_APP_AUTOGRAVITY_HOST', 'http://appwrite-autogravity:8080')) - ->withTimeout(30); + $host = System::getEnv('_APP_AUTOGRAVITY_HOST', ''); + $client = $host === '' + ? null + : (new Client((new SwooleClientAdapter())->withConnectionReuse())) + ->withBaseUri($host) + ->withTimeout(30); - return new AutogravityDetector(new AutogravityClient($client), $cache); + return new AutogravityDetector($client === null ? null : new AutogravityClient($client), $cache); }, ['cache']); $container->set('telemetry', fn () => new NoTelemetry(), []); diff --git a/src/Appwrite/Autogravity/Detector.php b/src/Appwrite/Autogravity/Detector.php index f3bf4bcce6..e759f4b019 100644 --- a/src/Appwrite/Autogravity/Detector.php +++ b/src/Appwrite/Autogravity/Detector.php @@ -9,13 +9,22 @@ class Detector private const CACHE_TTL = 15_552_000; public function __construct( - private readonly Client $client, + private readonly ?Client $client, private readonly Cache $cache ) { } + public function isEnabled(): bool + { + return $this->client !== null; + } + public function get(string $source, ?string $analysis = null): Gravity { + if ($this->client === null) { + throw new Exception('Autogravity needs to be configured with _APP_AUTOGRAVITY_HOST to use automatic gravity'); + } + $key = 'autogravity-' . \hash('sha256', $source); $cached = $this->cache->load($key, self::CACHE_TTL); if ( diff --git a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php index 99b8faddc4..f479cf66c5 100644 --- a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php +++ b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php @@ -41,8 +41,6 @@ class Get extends Action { use HTTP; - private const AUTOGRAVITY_MAX_BYTES = 10 * 1024 * 1024; - private const GRAVITY_AUTO = 'auto'; public static function getName() @@ -271,6 +269,13 @@ class Get extends Action throw new Exception(Exception::STORAGE_FILE_TYPE_UNSUPPORTED, $e->getMessage()); } + if ($gravity === self::GRAVITY_AUTO && !$autogravity->isEnabled()) { + throw new Exception( + Exception::GENERAL_ARGUMENT_INVALID, + 'Autogravity needs to be configured with _APP_AUTOGRAVITY_HOST to use automatic gravity' + ); + } + if ( $gravity === self::GRAVITY_AUTO && $width > 0 @@ -380,10 +385,7 @@ class Get extends Action */ private function prepareForAutogravity(string $source, string $type): array { - if ( - \in_array($type, ['jpg', 'jpeg', 'png', 'webp'], true) - && \strlen($source) < self::AUTOGRAVITY_MAX_BYTES - ) { + if (\in_array($type, ['jpg', 'jpeg', 'png', 'webp'], true)) { return ['source' => $source, 'rotation' => 0]; } diff --git a/tests/e2e/Services/Storage/StorageCustomServerTest.php b/tests/e2e/Services/Storage/StorageCustomServerTest.php index d74091b26a..64240c4654 100644 --- a/tests/e2e/Services/Storage/StorageCustomServerTest.php +++ b/tests/e2e/Services/Storage/StorageCustomServerTest.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Tests\E2E\Services\Storage; +use Appwrite\Extend\Exception; use CURLFile; use PHPUnit\Framework\Attributes\Group; use Tests\E2E\Client; @@ -94,6 +95,17 @@ final class StorageCustomServerTest extends Scope $preview = $this->client->call(Client::METHOD_GET, $path, $headers, $params); + if (System::getEnv('_APP_AUTOGRAVITY_HOST', '') === '') { + $this->assertEquals(400, $preview['headers']['status-code']); + $this->assertSame(Exception::GENERAL_ARGUMENT_INVALID, $preview['body']['type']); + $this->assertSame( + 'Autogravity needs to be configured with _APP_AUTOGRAVITY_HOST to use automatic gravity', + $preview['body']['message'] + ); + + return; + } + $this->assertEquals(200, $preview['headers']['status-code']); $this->assertEquals('image/png', $preview['headers']['content-type']); $this->assertEquals('miss', $preview['headers']['x-appwrite-cache']); diff --git a/tests/unit/Autogravity/DetectorTest.php b/tests/unit/Autogravity/DetectorTest.php index 1890baee9d..2a0301c921 100644 --- a/tests/unit/Autogravity/DetectorTest.php +++ b/tests/unit/Autogravity/DetectorTest.php @@ -6,6 +6,7 @@ namespace Tests\Unit\Autogravity; use Appwrite\Autogravity\Client; use Appwrite\Autogravity\Detector; +use Appwrite\Autogravity\Exception; use PHPUnit\Framework\TestCase; use Psr\Http\Client\ClientInterface; use Psr\Http\Message\RequestInterface; @@ -17,6 +18,17 @@ use Utopia\Psr7\Stream; final class DetectorTest extends TestCase { + public function testRejectsDetectionWhenDisabled(): void + { + $detector = new Detector(null, new Cache(new Memory())); + + $this->assertFalse($detector->isEnabled()); + $this->expectException(Exception::class); + $this->expectExceptionMessage('Autogravity needs to be configured with _APP_AUTOGRAVITY_HOST to use automatic gravity'); + + $detector->get('source-image'); + } + public function testCachesDetectionBySource(): void { $http = new CountingClient(new Response( @@ -25,6 +37,8 @@ final class DetectorTest extends TestCase )); $detector = new Detector(new Client($http), new Cache(new Memory())); + $this->assertTrue($detector->isEnabled()); + $first = $detector->get('source-image', 'first-analysis-image'); $second = $detector->get('source-image', 'different-analysis-image'); From 8039e554a376e653af16c9bcb2febaadad1f7937 Mon Sep 17 00:00:00 2001 From: Torsten Dittmann Date: Sun, 6 Sep 2026 10:45:16 +0000 Subject: [PATCH 04/13] Avoid duplicate Autogravity resizing --- .../Http/Buckets/Files/Preview/Get.php | 20 ++++++++++--------- .../Storage/StorageCustomServerTest.php | 8 ++++++-- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php index f479cf66c5..6d1ad6b60d 100644 --- a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php +++ b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php @@ -385,24 +385,26 @@ class Get extends Action */ private function prepareForAutogravity(string $source, string $type): array { - if (\in_array($type, ['jpg', 'jpeg', 'png', 'webp'], true)) { - return ['source' => $source, 'rotation' => 0]; - } - - $image = new \Imagick(); - $image->readImageBlob($source); - $image->setFirstIterator(); - $orientation = $image->getImageProperties()['exif:Orientation'] ?? null; + $metadata = new \Imagick(); + $metadata->pingImageBlob($source); + $orientation = $metadata->getImageProperties()['exif:Orientation'] ?? null; $rotation = match ($orientation) { '3' => 180, '6' => 90, '8' => -90, default => 0, }; + + if (\in_array($type, ['jpg', 'jpeg', 'png', 'webp'], true)) { + return ['source' => $source, 'rotation' => $rotation]; + } + + $image = new \Imagick(); + $image->readImageBlob($source); + $image->setFirstIterator(); if ($rotation !== 0) { $image->rotateImage(new \ImagickPixel('transparent'), $rotation); } - $image->resizeImage(320, 320, \Imagick::FILTER_LANCZOS, 1, false); $image->setImageFormat('png'); $image->stripImage(); diff --git a/tests/e2e/Services/Storage/StorageCustomServerTest.php b/tests/e2e/Services/Storage/StorageCustomServerTest.php index 64240c4654..3a76b98ed0 100644 --- a/tests/e2e/Services/Storage/StorageCustomServerTest.php +++ b/tests/e2e/Services/Storage/StorageCustomServerTest.php @@ -118,8 +118,12 @@ final class StorageCustomServerTest extends Scope $right = $this->client->call(Client::METHOD_GET, $path, $headers, [...$params, 'gravity' => 'right']); $center = $this->client->call(Client::METHOD_GET, $path, $headers, [...$params, 'gravity' => 'center']); - $this->assertSame($right['body'], $preview['body']); - $this->assertNotSame($center['body'], $preview['body']); + $rightImage = new \Imagick(); + $rightImage->readImageBlob($right['body']); + $centerImage = new \Imagick(); + $centerImage->readImageBlob($center['body']); + $this->assertSame($rightImage->getImageSignature(), $image->getImageSignature()); + $this->assertNotSame($centerImage->getImageSignature(), $image->getImageSignature()); $cached = []; $this->assertEventually(function () use (&$cached, $path, $headers, $params, $preview): void { From 0d06cff1ab52df31500a5d0ba51f05176bdd1e2e Mon Sep 17 00:00:00 2001 From: Torsten Dittmann Date: Sun, 6 Sep 2026 10:48:33 +0000 Subject: [PATCH 05/13] Delegate image preprocessing to Autogravity --- src/Appwrite/Autogravity/Detector.php | 4 +-- .../Http/Buckets/Files/Preview/Get.php | 28 ++++--------------- tests/unit/Autogravity/DetectorTest.php | 6 ++-- 3 files changed, 10 insertions(+), 28 deletions(-) diff --git a/src/Appwrite/Autogravity/Detector.php b/src/Appwrite/Autogravity/Detector.php index e759f4b019..187e99a69e 100644 --- a/src/Appwrite/Autogravity/Detector.php +++ b/src/Appwrite/Autogravity/Detector.php @@ -19,7 +19,7 @@ class Detector return $this->client !== null; } - public function get(string $source, ?string $analysis = null): Gravity + public function get(string $source): Gravity { if ($this->client === null) { throw new Exception('Autogravity needs to be configured with _APP_AUTOGRAVITY_HOST to use automatic gravity'); @@ -40,7 +40,7 @@ class Detector return new Gravity((float) $cached['x'], (float) $cached['y']); } - $gravity = $this->client->analyze($analysis ?? $source); + $gravity = $this->client->analyze($source); $this->cache->save($key, $gravity->getArrayCopy()); return $gravity; diff --git a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php index 6d1ad6b60d..fc4af4a84b 100644 --- a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php +++ b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php @@ -283,10 +283,9 @@ class Get extends Action && isset($sourceWidth, $sourceHeight) && \abs($width / $height - $sourceWidth / $sourceHeight) > 0.000001 ) { - $prepared = $this->prepareForAutogravity($source, $type); $automaticGravity = $autogravity - ->get($source, $prepared['source']) - ->unrotate($prepared['rotation']); + ->get($source) + ->unrotate($this->getAutogravityRotation($source)); $gravity = $automaticGravity->getType($width, $height, $sourceWidth, $sourceHeight); } elseif ($gravity === self::GRAVITY_AUTO) { $gravity = Image::GRAVITY_CENTER; @@ -380,34 +379,17 @@ class Get extends Action unset($image); } - /** - * @return array{source: string, rotation: int} - */ - private function prepareForAutogravity(string $source, string $type): array + private function getAutogravityRotation(string $source): int { $metadata = new \Imagick(); $metadata->pingImageBlob($source); $orientation = $metadata->getImageProperties()['exif:Orientation'] ?? null; - $rotation = match ($orientation) { + + return match ($orientation) { '3' => 180, '6' => 90, '8' => -90, default => 0, }; - - if (\in_array($type, ['jpg', 'jpeg', 'png', 'webp'], true)) { - return ['source' => $source, 'rotation' => $rotation]; - } - - $image = new \Imagick(); - $image->readImageBlob($source); - $image->setFirstIterator(); - if ($rotation !== 0) { - $image->rotateImage(new \ImagickPixel('transparent'), $rotation); - } - $image->setImageFormat('png'); - $image->stripImage(); - - return ['source' => $image->getImageBlob(), 'rotation' => $rotation]; } } diff --git a/tests/unit/Autogravity/DetectorTest.php b/tests/unit/Autogravity/DetectorTest.php index 2a0301c921..246e2145ca 100644 --- a/tests/unit/Autogravity/DetectorTest.php +++ b/tests/unit/Autogravity/DetectorTest.php @@ -39,14 +39,14 @@ final class DetectorTest extends TestCase $this->assertTrue($detector->isEnabled()); - $first = $detector->get('source-image', 'first-analysis-image'); - $second = $detector->get('source-image', 'different-analysis-image'); + $first = $detector->get('source-image'); + $second = $detector->get('source-image'); $this->assertSame(0.7, $first->x); $this->assertSame(0.4, $first->y); $this->assertSame($first->getArrayCopy(), $second->getArrayCopy()); $this->assertSame(1, $http->requests); - $this->assertSame('first-analysis-image', $http->lastBody); + $this->assertSame('source-image', $http->lastBody); } public function testDifferentSourcesAreDetectedSeparately(): void From c18b8098d4b5db5962d663191995a1bf3595c0f0 Mon Sep 17 00:00:00 2001 From: Torsten Dittmann Date: Sun, 6 Sep 2026 10:55:07 +0000 Subject: [PATCH 06/13] Apply Rector to Autogravity tests --- tests/unit/Autogravity/ClientTest.php | 4 ++-- tests/unit/Autogravity/DetectorTest.php | 4 ++-- tests/unit/Autogravity/GravityTest.php | 28 +++++++++++-------------- 3 files changed, 16 insertions(+), 20 deletions(-) diff --git a/tests/unit/Autogravity/ClientTest.php b/tests/unit/Autogravity/ClientTest.php index fd05fbc963..06220f8d7d 100644 --- a/tests/unit/Autogravity/ClientTest.php +++ b/tests/unit/Autogravity/ClientTest.php @@ -44,8 +44,8 @@ final class ClientTest extends TestCase $gravity = $this->client($response)->analyze('image-bytes'); - $this->assertSame(0.7, $gravity->x); - $this->assertSame(0.4, $gravity->y); + $this->assertEqualsWithDelta(0.7, $gravity->x, PHP_FLOAT_EPSILON); + $this->assertEqualsWithDelta(0.4, $gravity->y, PHP_FLOAT_EPSILON); $this->assertInstanceOf(RequestInterface::class, $this->request); $this->assertSame('POST', $this->request->getMethod()); $this->assertSame('analyze', (string) $this->request->getUri()); diff --git a/tests/unit/Autogravity/DetectorTest.php b/tests/unit/Autogravity/DetectorTest.php index 246e2145ca..0b60ab29bc 100644 --- a/tests/unit/Autogravity/DetectorTest.php +++ b/tests/unit/Autogravity/DetectorTest.php @@ -42,8 +42,8 @@ final class DetectorTest extends TestCase $first = $detector->get('source-image'); $second = $detector->get('source-image'); - $this->assertSame(0.7, $first->x); - $this->assertSame(0.4, $first->y); + $this->assertEqualsWithDelta(0.7, $first->x, PHP_FLOAT_EPSILON); + $this->assertEqualsWithDelta(0.4, $first->y, PHP_FLOAT_EPSILON); $this->assertSame($first->getArrayCopy(), $second->getArrayCopy()); $this->assertSame(1, $http->requests); $this->assertSame('source-image', $http->lastBody); diff --git a/tests/unit/Autogravity/GravityTest.php b/tests/unit/Autogravity/GravityTest.php index 25f3d5d568..773a556a3f 100644 --- a/tests/unit/Autogravity/GravityTest.php +++ b/tests/unit/Autogravity/GravityTest.php @@ -13,17 +13,15 @@ use Utopia\Image\Image; final class GravityTest extends TestCase { /** - * @return array + * @return \Iterator */ - public static function typeProvider(): array + public static function typeProvider(): \Iterator { - return [ - 'landscape to portrait, subject right' => [0.7, 0.5, 180, 320, 1280, 720, Image::GRAVITY_RIGHT], - 'landscape to portrait, subject left' => [0.2, 0.5, 180, 320, 1280, 720, Image::GRAVITY_LEFT], - 'landscape to wide, subject remains visible' => [0.7, 0.5, 800, 600, 1280, 720, Image::GRAVITY_CENTER], - 'portrait to landscape, subject top' => [0.5, 0.1, 600, 300, 600, 900, Image::GRAVITY_TOP], - 'portrait to landscape, subject bottom' => [0.9, 0.9, 600, 300, 600, 900, Image::GRAVITY_BOTTOM], - ]; + yield 'landscape to portrait, subject right' => [0.7, 0.5, 180, 320, 1280, 720, Image::GRAVITY_RIGHT]; + yield 'landscape to portrait, subject left' => [0.2, 0.5, 180, 320, 1280, 720, Image::GRAVITY_LEFT]; + yield 'landscape to wide, subject remains visible' => [0.7, 0.5, 800, 600, 1280, 720, Image::GRAVITY_CENTER]; + yield 'portrait to landscape, subject top' => [0.5, 0.1, 600, 300, 600, 900, Image::GRAVITY_TOP]; + yield 'portrait to landscape, subject bottom' => [0.9, 0.9, 600, 300, 600, 900, Image::GRAVITY_BOTTOM]; } #[DataProvider('typeProvider')] @@ -41,15 +39,13 @@ final class GravityTest extends TestCase } /** - * @return array + * @return \Iterator */ - public static function rotationProvider(): array + public static function rotationProvider(): \Iterator { - return [ - 'clockwise' => [90, 0.8, 0.75], - 'upside down' => [180, 0.75, 0.2], - 'counterclockwise' => [-90, 0.2, 0.25], - ]; + yield 'clockwise' => [90, 0.8, 0.75]; + yield 'upside down' => [180, 0.75, 0.2]; + yield 'counterclockwise' => [-90, 0.2, 0.25]; } #[DataProvider('rotationProvider')] From 895bfc7a55ca7b3d6e7e3dc8410247e109c29ec0 Mon Sep 17 00:00:00 2001 From: Torsten Dittmann Date: Sun, 6 Sep 2026 13:11:31 +0000 Subject: [PATCH 07/13] Fix automatic gravity cache assertion --- tests/e2e/Services/Storage/StorageCustomServerTest.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/e2e/Services/Storage/StorageCustomServerTest.php b/tests/e2e/Services/Storage/StorageCustomServerTest.php index 3a76b98ed0..0292790abb 100644 --- a/tests/e2e/Services/Storage/StorageCustomServerTest.php +++ b/tests/e2e/Services/Storage/StorageCustomServerTest.php @@ -126,11 +126,13 @@ final class StorageCustomServerTest extends Scope $this->assertNotSame($centerImage->getImageSignature(), $image->getImageSignature()); $cached = []; - $this->assertEventually(function () use (&$cached, $path, $headers, $params, $preview): void { + $this->assertEventually(function () use (&$cached, $path, $headers, $params, $image): void { $cached = $this->client->call(Client::METHOD_GET, $path, $headers, $params); $this->assertSame('hit', $cached['headers']['x-appwrite-cache']); - $this->assertSame($preview['body'], $cached['body']); + $cachedImage = new \Imagick(); + $cachedImage->readImageBlob($cached['body']); + $this->assertSame($image->getImageSignature(), $cachedImage->getImageSignature()); }); $this->assertEquals(200, $cached['headers']['status-code']); From dde07e7cc9320e1996a19043f21089147f5ed0ba Mon Sep 17 00:00:00 2001 From: Torsten Dittmann Date: Sun, 6 Sep 2026 13:38:02 +0000 Subject: [PATCH 08/13] Add Autogravity health check --- docker-compose.yml | 11 ++++++++++- tests/unit/Docker/Compose/GeneratorTest.php | 3 ++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 8daed5b8ae..9a21717cde 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1582,10 +1582,19 @@ services: appwrite-autogravity: container_name: appwrite-autogravity - image: ghcr.io/appwrite/autogravity:0.0.2 + image: ghcr.io/appwrite/autogravity:0.0.3 restart: unless-stopped networks: - appwrite + healthcheck: + test: + - CMD + - bash + - -c + - 'exec 3<>/dev/tcp/127.0.0.1/8080 && printf "GET /healthz HTTP/1.0\r\n\r\n" >&3 && grep -q "200 OK" <&3' + interval: 5s + timeout: 5s + retries: 3 clickhouse: image: clickhouse/clickhouse-server:26.4.3-alpine diff --git a/tests/unit/Docker/Compose/GeneratorTest.php b/tests/unit/Docker/Compose/GeneratorTest.php index 345941a272..8a1fd79705 100644 --- a/tests/unit/Docker/Compose/GeneratorTest.php +++ b/tests/unit/Docker/Compose/GeneratorTest.php @@ -69,7 +69,8 @@ final class GeneratorTest extends TestCase $this->assertArrayHasKey('appwrite-task-interval', $compose['services']); $this->assertArrayHasKey('appwrite-embedding', $compose['services']); $this->assertArrayHasKey('appwrite-autogravity', $compose['services']); - $this->assertSame('ghcr.io/appwrite/autogravity:0.0.2', $compose['services']['appwrite-autogravity']['image']); + $this->assertSame('ghcr.io/appwrite/autogravity:0.0.3', $compose['services']['appwrite-autogravity']['image']); + $this->assertStringContainsString('/healthz', $compose['services']['appwrite-autogravity']['healthcheck']['test'][3]); $this->assertArrayNotHasKey('profiles', $compose['services']['appwrite-worker']); $this->assertArrayNotHasKey('profiles', $compose['services']['appwrite-task-scheduler']); } From de9e32988966b81ceb0d5d7099b8c5da3fce71c5 Mon Sep 17 00:00:00 2001 From: Torsten Dittmann Date: Sun, 6 Sep 2026 14:01:20 +0000 Subject: [PATCH 09/13] Use Autogravity image health check --- docker-compose.yml | 11 +---------- tests/unit/Docker/Compose/GeneratorTest.php | 3 +-- 2 files changed, 2 insertions(+), 12 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 9a21717cde..590a072ef2 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1582,19 +1582,10 @@ services: appwrite-autogravity: container_name: appwrite-autogravity - image: ghcr.io/appwrite/autogravity:0.0.3 + image: ghcr.io/appwrite/autogravity:0.0.4 restart: unless-stopped networks: - appwrite - healthcheck: - test: - - CMD - - bash - - -c - - 'exec 3<>/dev/tcp/127.0.0.1/8080 && printf "GET /healthz HTTP/1.0\r\n\r\n" >&3 && grep -q "200 OK" <&3' - interval: 5s - timeout: 5s - retries: 3 clickhouse: image: clickhouse/clickhouse-server:26.4.3-alpine diff --git a/tests/unit/Docker/Compose/GeneratorTest.php b/tests/unit/Docker/Compose/GeneratorTest.php index 8a1fd79705..29ea68f1fe 100644 --- a/tests/unit/Docker/Compose/GeneratorTest.php +++ b/tests/unit/Docker/Compose/GeneratorTest.php @@ -69,8 +69,7 @@ final class GeneratorTest extends TestCase $this->assertArrayHasKey('appwrite-task-interval', $compose['services']); $this->assertArrayHasKey('appwrite-embedding', $compose['services']); $this->assertArrayHasKey('appwrite-autogravity', $compose['services']); - $this->assertSame('ghcr.io/appwrite/autogravity:0.0.3', $compose['services']['appwrite-autogravity']['image']); - $this->assertStringContainsString('/healthz', $compose['services']['appwrite-autogravity']['healthcheck']['test'][3]); + $this->assertSame('ghcr.io/appwrite/autogravity:0.0.4', $compose['services']['appwrite-autogravity']['image']); $this->assertArrayNotHasKey('profiles', $compose['services']['appwrite-worker']); $this->assertArrayNotHasKey('profiles', $compose['services']['appwrite-task-scheduler']); } From 28b008aa29a2d40f9fb5710988ac3b2c2a8231ce Mon Sep 17 00:00:00 2001 From: Torsten Dittmann Date: Sun, 6 Sep 2026 15:18:19 +0000 Subject: [PATCH 10/13] Update Autogravity to 0.0.5 --- docker-compose.yml | 2 +- tests/unit/Docker/Compose/GeneratorTest.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 590a072ef2..6a7b4cf2b6 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1582,7 +1582,7 @@ services: appwrite-autogravity: container_name: appwrite-autogravity - image: ghcr.io/appwrite/autogravity:0.0.4 + image: ghcr.io/appwrite/autogravity:0.0.5 restart: unless-stopped networks: - appwrite diff --git a/tests/unit/Docker/Compose/GeneratorTest.php b/tests/unit/Docker/Compose/GeneratorTest.php index 29ea68f1fe..92f89bf4ce 100644 --- a/tests/unit/Docker/Compose/GeneratorTest.php +++ b/tests/unit/Docker/Compose/GeneratorTest.php @@ -69,7 +69,7 @@ final class GeneratorTest extends TestCase $this->assertArrayHasKey('appwrite-task-interval', $compose['services']); $this->assertArrayHasKey('appwrite-embedding', $compose['services']); $this->assertArrayHasKey('appwrite-autogravity', $compose['services']); - $this->assertSame('ghcr.io/appwrite/autogravity:0.0.4', $compose['services']['appwrite-autogravity']['image']); + $this->assertSame('ghcr.io/appwrite/autogravity:0.0.5', $compose['services']['appwrite-autogravity']['image']); $this->assertArrayNotHasKey('profiles', $compose['services']['appwrite-worker']); $this->assertArrayNotHasKey('profiles', $compose['services']['appwrite-task-scheduler']); } From d4819b58edda02578ad871d2b32b447f1a25e066 Mon Sep 17 00:00:00 2001 From: Torsten Dittmann Date: Mon, 7 Sep 2026 10:07:47 +0000 Subject: [PATCH 11/13] Use focal point image cropping --- composer.lock | 12 +++--- src/Appwrite/Autogravity/Gravity.php | 38 ------------------- .../Http/Buckets/Files/Preview/Get.php | 7 ++-- .../Storage/StorageCustomServerTest.php | 4 -- tests/unit/Autogravity/GravityTest.php | 19 ---------- 5 files changed, 10 insertions(+), 70 deletions(-) diff --git a/composer.lock b/composer.lock index d029ff1eb8..6213a05d26 100644 --- a/composer.lock +++ b/composer.lock @@ -4108,16 +4108,16 @@ }, { "name": "utopia-php/image", - "version": "0.8.9", + "version": "0.8.12", "source": { "type": "git", "url": "https://github.com/utopia-php/image.git", - "reference": "6647714267e43bae25c8e8ae7021264eca4a1e84" + "reference": "cab2779faf1e02f3bed9bc5cddd6350a69056948" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/image/zipball/6647714267e43bae25c8e8ae7021264eca4a1e84", - "reference": "6647714267e43bae25c8e8ae7021264eca4a1e84", + "url": "https://api.github.com/repos/utopia-php/image/zipball/cab2779faf1e02f3bed9bc5cddd6350a69056948", + "reference": "cab2779faf1e02f3bed9bc5cddd6350a69056948", "shasum": "" }, "require": { @@ -4148,9 +4148,9 @@ ], "support": { "issues": "https://github.com/utopia-php/image/issues", - "source": "https://github.com/utopia-php/image/tree/0.8.9" + "source": "https://github.com/utopia-php/image/tree/0.8.12" }, - "time": "2026-07-20T18:04:09+00:00" + "time": "2026-09-07T10:00:40+00:00" }, { "name": "utopia-php/locale", diff --git a/src/Appwrite/Autogravity/Gravity.php b/src/Appwrite/Autogravity/Gravity.php index 6b5580a9ac..8c0aff5f06 100644 --- a/src/Appwrite/Autogravity/Gravity.php +++ b/src/Appwrite/Autogravity/Gravity.php @@ -2,8 +2,6 @@ namespace Appwrite\Autogravity; -use Utopia\Image\Image; - class Gravity { public function __construct( @@ -15,42 +13,6 @@ class Gravity } } - public function getType(int $width, int $height, int $sourceWidth, int $sourceHeight): string - { - $sourceAspect = $sourceWidth / $sourceHeight; - $targetAspect = $width / $height; - if ($targetAspect > $sourceAspect) { - $resizeWidth = $width; - $resizeHeight = (int) \ceil($width / $sourceAspect); - } else { - $resizeWidth = (int) \ceil($height * $sourceAspect); - $resizeHeight = $height; - } - - $horizontal = match (true) { - $this->x * $resizeWidth < ($resizeWidth - $width) / 2 => 'left', - $this->x * $resizeWidth > ($resizeWidth + $width) / 2 => 'right', - default => '', - }; - $vertical = match (true) { - $this->y * $resizeHeight < ($resizeHeight - $height) / 2 => 'top', - $this->y * $resizeHeight > ($resizeHeight + $height) / 2 => 'bottom', - default => '', - }; - - return match ([$vertical, $horizontal]) { - ['', ''] => Image::GRAVITY_CENTER, - ['', 'left'] => Image::GRAVITY_LEFT, - ['', 'right'] => Image::GRAVITY_RIGHT, - ['top', ''] => Image::GRAVITY_TOP, - ['top', 'left'] => Image::GRAVITY_TOP_LEFT, - ['top', 'right'] => Image::GRAVITY_TOP_RIGHT, - ['bottom', ''] => Image::GRAVITY_BOTTOM, - ['bottom', 'left'] => Image::GRAVITY_BOTTOM_LEFT, - ['bottom', 'right'] => Image::GRAVITY_BOTTOM_RIGHT, - }; - } - public function unrotate(int $rotation): self { return match (($rotation % 360 + 360) % 360) { diff --git a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php index fc4af4a84b..5a2b0718c3 100644 --- a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php +++ b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php @@ -276,6 +276,7 @@ class Get extends Action ); } + $focalPoint = null; if ( $gravity === self::GRAVITY_AUTO && $width > 0 @@ -283,10 +284,10 @@ class Get extends Action && isset($sourceWidth, $sourceHeight) && \abs($width / $height - $sourceWidth / $sourceHeight) > 0.000001 ) { - $automaticGravity = $autogravity + $focalPoint = $autogravity ->get($source) ->unrotate($this->getAutogravityRotation($source)); - $gravity = $automaticGravity->getType($width, $height, $sourceWidth, $sourceHeight); + $gravity = Image::GRAVITY_CENTER; } elseif ($gravity === self::GRAVITY_AUTO) { $gravity = Image::GRAVITY_CENTER; } @@ -295,7 +296,7 @@ class Get extends Action Span::add('storage.transform.crop.width', $width); Span::add('storage.transform.crop.height', $height); Span::add('storage.transform.crop.gravity', $gravity); - $image->crop($width, $height, $gravity); + $image->crop($width, $height, $gravity, x: $focalPoint?->x, y: $focalPoint?->y); } if ($opacity !== 1.0) { diff --git a/tests/e2e/Services/Storage/StorageCustomServerTest.php b/tests/e2e/Services/Storage/StorageCustomServerTest.php index 0292790abb..f514c6d595 100644 --- a/tests/e2e/Services/Storage/StorageCustomServerTest.php +++ b/tests/e2e/Services/Storage/StorageCustomServerTest.php @@ -116,13 +116,9 @@ final class StorageCustomServerTest extends Scope $this->assertSame(120, $image->getImageWidth()); $this->assertSame(320, $image->getImageHeight()); - $right = $this->client->call(Client::METHOD_GET, $path, $headers, [...$params, 'gravity' => 'right']); $center = $this->client->call(Client::METHOD_GET, $path, $headers, [...$params, 'gravity' => 'center']); - $rightImage = new \Imagick(); - $rightImage->readImageBlob($right['body']); $centerImage = new \Imagick(); $centerImage->readImageBlob($center['body']); - $this->assertSame($rightImage->getImageSignature(), $image->getImageSignature()); $this->assertNotSame($centerImage->getImageSignature(), $image->getImageSignature()); $cached = []; diff --git a/tests/unit/Autogravity/GravityTest.php b/tests/unit/Autogravity/GravityTest.php index 773a556a3f..3e06f332c7 100644 --- a/tests/unit/Autogravity/GravityTest.php +++ b/tests/unit/Autogravity/GravityTest.php @@ -8,28 +8,9 @@ use Appwrite\Autogravity\Exception; use Appwrite\Autogravity\Gravity; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; -use Utopia\Image\Image; final class GravityTest extends TestCase { - /** - * @return \Iterator - */ - public static function typeProvider(): \Iterator - { - yield 'landscape to portrait, subject right' => [0.7, 0.5, 180, 320, 1280, 720, Image::GRAVITY_RIGHT]; - yield 'landscape to portrait, subject left' => [0.2, 0.5, 180, 320, 1280, 720, Image::GRAVITY_LEFT]; - yield 'landscape to wide, subject remains visible' => [0.7, 0.5, 800, 600, 1280, 720, Image::GRAVITY_CENTER]; - yield 'portrait to landscape, subject top' => [0.5, 0.1, 600, 300, 600, 900, Image::GRAVITY_TOP]; - yield 'portrait to landscape, subject bottom' => [0.9, 0.9, 600, 300, 600, 900, Image::GRAVITY_BOTTOM]; - } - - #[DataProvider('typeProvider')] - public function testGetType(float $x, float $y, int $width, int $height, int $sourceWidth, int $sourceHeight, string $expected): void - { - $this->assertSame($expected, (new Gravity($x, $y))->getType($width, $height, $sourceWidth, $sourceHeight)); - } - public function testRejectsInvalidCoordinates(): void { $this->expectException(Exception::class); From b18d361e27f0319ec725bca77eb33bd3e2d80ba3 Mon Sep 17 00:00:00 2001 From: Torsten Dittmann Date: Mon, 7 Sep 2026 13:30:52 +0000 Subject: [PATCH 12/13] Update Autogravity to 0.0.6 --- docker-compose.yml | 2 +- tests/unit/Docker/Compose/GeneratorTest.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 6a7b4cf2b6..db402af49e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1582,7 +1582,7 @@ services: appwrite-autogravity: container_name: appwrite-autogravity - image: ghcr.io/appwrite/autogravity:0.0.5 + image: ghcr.io/appwrite/autogravity:0.0.6 restart: unless-stopped networks: - appwrite diff --git a/tests/unit/Docker/Compose/GeneratorTest.php b/tests/unit/Docker/Compose/GeneratorTest.php index 92f89bf4ce..e946d516fc 100644 --- a/tests/unit/Docker/Compose/GeneratorTest.php +++ b/tests/unit/Docker/Compose/GeneratorTest.php @@ -69,7 +69,7 @@ final class GeneratorTest extends TestCase $this->assertArrayHasKey('appwrite-task-interval', $compose['services']); $this->assertArrayHasKey('appwrite-embedding', $compose['services']); $this->assertArrayHasKey('appwrite-autogravity', $compose['services']); - $this->assertSame('ghcr.io/appwrite/autogravity:0.0.5', $compose['services']['appwrite-autogravity']['image']); + $this->assertSame('ghcr.io/appwrite/autogravity:0.0.6', $compose['services']['appwrite-autogravity']['image']); $this->assertArrayNotHasKey('profiles', $compose['services']['appwrite-worker']); $this->assertArrayNotHasKey('profiles', $compose['services']['appwrite-task-scheduler']); } From 9b62d4577b16b07d1ecf62a205ed0e8f84794f86 Mon Sep 17 00:00:00 2001 From: Torsten Dittmann Date: Mon, 7 Sep 2026 13:53:29 +0000 Subject: [PATCH 13/13] fix: avoid sharing Autogravity connections --- app/init/resources.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/init/resources.php b/app/init/resources.php index 3ab02d29e4..db4dffc854 100644 --- a/app/init/resources.php +++ b/app/init/resources.php @@ -108,7 +108,7 @@ $container->set('autogravity', function (Cache $cache) { $host = System::getEnv('_APP_AUTOGRAVITY_HOST', ''); $client = $host === '' ? null - : (new Client((new SwooleClientAdapter())->withConnectionReuse())) + : (new Client(new SwooleClientAdapter())) ->withBaseUri($host) ->withTimeout(30);