- 
                Notifications
    You must be signed in to change notification settings 
- Fork 6.5k
          Add remote_decode to remote_utils
          #10898
        
          New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Merged
      
      
    
  
     Merged
                    Changes from 6 commits
      Commits
    
    
            Show all changes
          
          
            40 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      47498fb
              
                Add `remote_decode` to `remote_utils`
              
              
                hlky 5fb50f1
              
                test dependency
              
              
                hlky 76f79b3
              
                test dependency
              
              
                hlky 303e920
              
                dependency
              
              
                hlky 8c405d5
              
                dependency
              
              
                hlky 19414df
              
                dependency
              
              
                hlky 2a2157e
              
                docstrings
              
              
                hlky f80ef6d
              
                changes
              
              
                hlky 2c572f7
              
                make style
              
              
                hlky 1978a8a
              
                apply
              
              
                sayakpaul e55139b
              
                revert, add new options
              
              
                hlky 4773420
              
                Apply style fixes
              
              
                github-actions[bot] 54280dd
              
                Merge branch 'main' into remote-utils
              
              
                hlky 2af1995
              
                deprecate base64, headers not needed
              
              
                hlky d80d66c
              
                address comments
              
              
                hlky 05b39ab
              
                add license header
              
              
                hlky c2a2daf
              
                init test_remote_decode
              
              
                hlky 1c4fdea
              
                more
              
              
                hlky f03a105
              
                more test
              
              
                hlky 7e7af59
              
                more test
              
              
                hlky d16c855
              
                skeleton for xl, flux
              
              
                hlky 485d99e
              
                more test
              
              
                hlky 2937eb2
              
                flux test
              
              
                hlky 86c2236
              
                flux packed
              
              
                hlky b10ea13
              
                no scaling
              
              
                hlky 7df21f2
              
                -save
              
              
                hlky 562a4c0
              
                hunyuanvideo test
              
              
                hlky 9a39e35
              
                Apply style fixes
              
              
                github-actions[bot] 217e161
              
                Merge branch 'main' into remote-utils
              
              
                hlky 3712dc3
              
                init docs
              
              
                hlky 5302645
              
                Update src/diffusers/utils/remote_utils.py
              
              
                hlky 3f69f92
              
                comments
              
              
                hlky 08ffc8f
              
                Apply style fixes
              
              
                github-actions[bot] 6c2f123
              
                comments
              
              
                hlky 82aa5cd
              
                hybrid_inference/vae_decode
              
              
                hlky 7151510
              
                fix
              
              
                hlky 9f6d91f
              
                tip?
              
              
                hlky 4c24111
              
                tip
              
              
                hlky 9c39564
              
                api reference autodoc
              
              
                hlky ca53835
              
                install tip
              
              
                hlky File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,127 @@ | ||
| import base64 | ||
| import io | ||
| import json | ||
| from typing import List, Literal, Optional, Union, cast | ||
|  | ||
| import requests | ||
|  | ||
| from .import_utils import is_safetensors_available, is_torch_available | ||
|  | ||
|  | ||
| if is_torch_available(): | ||
| import torch | ||
|  | ||
| from ..image_processor import VaeImageProcessor | ||
| from ..video_processor import VideoProcessor | ||
|  | ||
| if is_safetensors_available(): | ||
| import safetensors | ||
|  | ||
| DTYPE_MAP = { | ||
| "float16": torch.float16, | ||
| "float32": torch.float32, | ||
| "bfloat16": torch.bfloat16, | ||
| "uint8": torch.uint8, | ||
| } | ||
|  | ||
|  | ||
| from PIL import Image | ||
|  | ||
|  | ||
| def remote_decode( | ||
| endpoint: str, | ||
| tensor: "torch.Tensor", | ||
| processor: Optional[Union["VaeImageProcessor", "VideoProcessor"]] = None, | ||
| do_scaling: bool = True, | ||
| output_type: Literal["mp4", "pil", "pt"] = "pil", | ||
| image_format: Literal["png", "jpg"] = "jpg", | ||
| partial_postprocess: bool = False, | ||
| input_tensor_type: Literal["base64", "binary"] = "base64", | ||
| output_tensor_type: Literal["base64", "binary"] = "base64", | ||
|         
                  hlky marked this conversation as resolved.
              Outdated
          
            Show resolved
            Hide resolved | ||
| height: Optional[int] = None, | ||
| width: Optional[int] = None, | ||
| ) -> Union[Image.Image, List[Image.Image], bytes, "torch.Tensor"]: | ||
| if tensor.ndim == 3 and height is None and width is None: | ||
| raise ValueError("`height` and `width` required for packed latents.") | ||
| if output_type == "pt" and partial_postprocess is False and processor is None: | ||
| raise ValueError("`processor` is required with `output_type='pt' and `partial_postprocess=False`.") | ||
| headers = {} | ||
| parameters = { | ||
| "do_scaling": do_scaling, | ||
| "output_type": output_type, | ||
| "partial_postprocess": partial_postprocess, | ||
| "shape": list(tensor.shape), | ||
| "dtype": str(tensor.dtype).split(".")[-1], | ||
| } | ||
| if height is not None and width is not None: | ||
|         
                  sayakpaul marked this conversation as resolved.
              Outdated
          
            Show resolved
            Hide resolved | ||
| parameters["height"] = height | ||
| parameters["width"] = width | ||
| tensor_data = safetensors.torch._tobytes(tensor, "tensor") | ||
| if input_tensor_type == "base64": | ||
| headers["Content-Type"] = "tensor/base64" | ||
| elif input_tensor_type == "binary": | ||
| headers["Content-Type"] = "tensor/binary" | ||
| if output_type == "pil" and image_format == "jpg" and processor is None: | ||
| headers["Accept"] = "image/jpeg" | ||
| elif output_type == "pil" and image_format == "png" and processor is None: | ||
| headers["Accept"] = "image/png" | ||
| elif (output_tensor_type == "base64" and output_type == "pt") or ( | ||
| output_tensor_type == "base64" and output_type == "pil" and processor is not None | ||
| ): | ||
| headers["Accept"] = "tensor/base64" | ||
| elif (output_tensor_type == "binary" and output_type == "pt") or ( | ||
| output_tensor_type == "binary" and output_type == "pil" and processor is not None | ||
| ): | ||
| headers["Accept"] = "tensor/binary" | ||
| elif output_type == "mp4": | ||
| headers["Accept"] = "text/plain" | ||
| if input_tensor_type == "base64": | ||
| kwargs = {"json": {"inputs": base64.b64encode(tensor_data).decode("utf-8")}} | ||
| elif input_tensor_type == "binary": | ||
| kwargs = {"data": tensor_data} | ||
| response = requests.post(endpoint, params=parameters, **kwargs, headers=headers) | ||
| if not response.ok: | ||
| raise RuntimeError(response.json()) | ||
| if output_type == "pt" or (output_type == "pil" and processor is not None): | ||
| if output_tensor_type == "base64": | ||
| content = response.json() | ||
| output_tensor = base64.b64decode(content["inputs"]) | ||
| parameters = content["parameters"] | ||
| shape = parameters["shape"] | ||
| dtype = parameters["dtype"] | ||
| elif output_tensor_type == "binary": | ||
| output_tensor = response.content | ||
| parameters = response.headers | ||
| shape = json.loads(parameters["shape"]) | ||
| dtype = parameters["dtype"] | ||
| torch_dtype = DTYPE_MAP[dtype] | ||
| output_tensor = torch.frombuffer(bytearray(output_tensor), dtype=torch_dtype).reshape(shape) | ||
| if output_type == "pt": | ||
| if partial_postprocess: | ||
| output = [Image.fromarray(image.numpy()) for image in output_tensor] | ||
| if len(output) == 1: | ||
| output = output[0] | ||
| else: | ||
| if processor is None: | ||
| output = output_tensor | ||
| else: | ||
| if isinstance(processor, VideoProcessor): | ||
| output = cast( | ||
| List[Image.Image], | ||
| processor.postprocess_video(output_tensor, output_type="pil")[0], | ||
| ) | ||
| else: | ||
| output = cast( | ||
| Image.Image, | ||
| processor.postprocess(output_tensor, output_type="pil")[0], | ||
| ) | ||
| elif output_type == "pil" and processor is None: | ||
| output = Image.open(io.BytesIO(response.content)).convert("RGB") | ||
| elif output_type == "pil" and processor is not None: | ||
| output = [ | ||
| Image.fromarray(image) | ||
| for image in (output_tensor.permute(0, 2, 3, 1).float().numpy() * 255).round().astype("uint8") | ||
| ] | ||
| elif output_type == "mp4": | ||
| output = response.content | ||
| return output | ||
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.