77
88use Codewithkyrian \Transformers \Utils \Image ;
99use Codewithkyrian \Transformers \Utils \Tensor ;
10+ use Exception ;
1011use Interop \Polite \Math \Matrix \NDArray ;
1112use function Codewithkyrian \Transformers \Utils \prepareImages ;
12- use function Codewithkyrian \Transformers \Utils \timeUsage ;
1313
1414/**
1515 * Image to Image pipeline using any `AutoModelForImageToImage`. This pipeline generates an image based on a previous image input.
1818 * ```php
1919 * $upscaler = pipeline('image-to-image', 'Xenova/swin2SR-classical-sr-x2-64');
2020 * $url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/butterfly.jpg';
21- * $output = $upscaler($url);
22- * // Image {
23- * // data: array(786432) [ 41, 31, 24, 43, ... ] ,
21+ * $output = $upscaler($url, saveTo: 'butterfly-super-resolution.jpg' );
22+ * // [
23+ * // path: 'butterfly-super-resolution.jpg' ,
2424 * // width: 512,
2525 * // height: 512,
2626 * // channels: 3
27- * // }
27+ * // ]
2828 * ```
2929 */
3030class ImageToImagePipeline extends Pipeline
@@ -34,10 +34,20 @@ class ImageToImagePipeline extends Pipeline
3434 * @param array|string $inputs
3535 * @param mixed ...$args
3636 * @return Image|Image[]
37- * @throws \ Exception
37+ * @throws Exception
3838 */
3939 public function __invoke (array |string $ inputs , ...$ args ): array |Image
4040 {
41+ $ saveTo = $ args [0 ] ?? $ args ['saveTo ' ] ?? null ;
42+
43+ if (!$ saveTo ) {
44+ throw new Exception ('You must provide a save path ' );
45+ }
46+
47+ if (!is_array ($ saveTo )) {
48+ $ saveTo = [$ saveTo ];
49+ }
50+
4151 $ preparedImages = prepareImages ($ inputs );
4252
4353 $ inputs = ($ this ->processor )($ preparedImages );
@@ -47,14 +57,23 @@ public function __invoke(array|string $inputs, ...$args): array|Image
4757 $ toReturn = [];
4858
4959 /** @var Tensor $batch */
50- foreach ($ outputs ['reconstruction ' ] as $ batch ) {
60+ foreach ($ outputs ['reconstruction ' ] as $ i => $ batch ) {
5161 $ output = $ batch ->squeeze ()
5262 ->clamp (0 , 1 )
5363 ->multiplyScalar (255 )
5464 ->round ()
5565 ->to (NDArray::uint8);
5666
57- $ toReturn [] = Image::fromTensor ($ output );
67+ $ image = Image::fromTensor ($ output );
68+
69+ $ image ->save ($ saveTo [$ i ]);
70+
71+ $ toReturn [] = [
72+ 'path ' => $ saveTo [$ i ],
73+ 'width ' => $ image ->width (),
74+ 'height ' => $ image ->height (),
75+ 'channels ' => $ image ->channels ,
76+ ];
5877 }
5978
6079 return count ($ toReturn ) > 1 ? $ toReturn : $ toReturn [0 ];
0 commit comments