hlky HF staff commited on
Commit
9b00d20
·
verified ·
1 Parent(s): ef06ce9

Update handler.py

Browse files
Files changed (1) hide show
  1. handler.py +33 -39
handler.py CHANGED
@@ -1,64 +1,58 @@
1
- from typing import Dict, List, Any
 
2
  import torch
3
- from base64 import b64decode, b64encode
4
  from diffusers import AutoencoderKLHunyuanVideo
5
  from diffusers.video_processor import VideoProcessor
6
  from diffusers.utils import export_to_video
7
 
8
-
9
  class EndpointHandler:
10
  def __init__(self, path=""):
11
  self.device = "cuda"
12
  self.dtype = torch.float16
13
- self.vae = (
14
- AutoencoderKLHunyuanVideo.from_pretrained(
15
- path, subfolder="vae", torch_dtype=self.dtype
16
- )
17
- .to(self.device, self.dtype)
18
- .eval()
19
- )
20
 
21
- self.vae_scale_factor_spatial = self.vae.spatial_compression_ratio
22
  self.video_processor = VideoProcessor(
23
  vae_scale_factor=self.vae_scale_factor_spatial
24
  )
25
 
26
  @torch.no_grad()
27
- def __call__(self, data: Any) -> List[List[Dict[str, float]]]:
28
  """
29
  Args:
30
  data (:obj:):
31
  includes the input data and the parameters for the inference.
32
  """
33
- tensor = data["inputs"]
34
- tensor = b64decode(tensor.encode("utf-8"))
35
- parameters = data.get("parameters", {})
36
- if "shape" not in parameters:
37
- raise ValueError("Expected `shape` in parameters.")
38
- if "dtype" not in parameters:
39
- raise ValueError("Expected `dtype` in parameters.")
40
-
41
- DTYPE_MAP = {
42
- "float16": torch.float16,
43
- "float32": torch.float32,
44
- "bfloat16": torch.bfloat16,
45
- }
46
-
47
- shape = parameters.get("shape")
48
- dtype = DTYPE_MAP.get(parameters.get("dtype"))
49
- tensor = torch.frombuffer(bytearray(tensor), dtype=dtype).reshape(shape)
50
 
51
  tensor = tensor.to(self.device, self.dtype)
52
 
53
- tensor = tensor / self.vae.config.scaling_factor
 
54
 
55
  with torch.no_grad():
56
- frames = self.vae.decode(tensor, return_dict=False)[0]
57
-
58
- frames = self.video_processor.postprocess_video(frames, output_type="pil")[0]
59
-
60
- path = export_to_video(frames, fps=15)
61
- with open(path, "rb") as f:
62
- video = f.read()
63
-
64
- return {'bytes': b64encode(video).decode("utf-8")}
 
 
 
 
 
 
 
 
 
 
1
+ from typing import cast, Union
2
+
3
  import torch
4
+
5
  from diffusers import AutoencoderKLHunyuanVideo
6
  from diffusers.video_processor import VideoProcessor
7
  from diffusers.utils import export_to_video
8
 
 
9
  class EndpointHandler:
10
  def __init__(self, path=""):
11
  self.device = "cuda"
12
  self.dtype = torch.float16
13
+ self.vae = cast(AutoencoderKLHunyuanVideo, AutoencoderKLHunyuanVideo.from_pretrained(path, torch_dtype=self.dtype).to(self.device, self.dtype).eval())
 
 
 
 
 
 
14
 
15
+ self.vae_scale_factor = self.vae_scale_factor_spatial = self.vae.spatial_compression_ratio
16
  self.video_processor = VideoProcessor(
17
  vae_scale_factor=self.vae_scale_factor_spatial
18
  )
19
 
20
  @torch.no_grad()
21
+ def __call__(self, data) -> Union[torch.Tensor, bytes]:
22
  """
23
  Args:
24
  data (:obj:):
25
  includes the input data and the parameters for the inference.
26
  """
27
+ tensor = cast(torch.Tensor, data["inputs"])
28
+ parameters = cast(dict, data.get("parameters", {}))
29
+ do_scaling = cast(bool, parameters.get("do_scaling", True))
30
+ output_type = cast(str, parameters.get("output_type", "pil"))
31
+ partial_postprocess = cast(bool, parameters.get("partial_postprocess", False))
32
+ if partial_postprocess and output_type != "pt":
33
+ output_type = "pt"
 
 
 
 
 
 
 
 
 
 
34
 
35
  tensor = tensor.to(self.device, self.dtype)
36
 
37
+ if do_scaling:
38
+ tensor = tensor / self.vae.config.scaling_factor
39
 
40
  with torch.no_grad():
41
+ frames = cast(torch.Tensor, self.vae.decode(tensor, return_dict=False)[0])
42
+
43
+ if partial_postprocess:
44
+ frames = frames[0].permute(1, 0, 2, 3)
45
+ frames = torch.stack([(frame * 0.5 + 0.5).clamp(0, 1) for frame in frames])
46
+ frames = frames.permute(0, 2, 3, 1).contiguous().float()
47
+ frames = (frames * 255).round().to(torch.uint8)
48
+ elif output_type == "pil":
49
+ frames = cast(torch.Tensor, self.video_processor.postprocess_video(frames, output_type="pt")[0])
50
+ elif output_type == "mp4":
51
+ frames = cast(torch.Tensor, self.video_processor.postprocess_video(frames, output_type="pil")[0])
52
+ path = export_to_video(frames, fps=15)
53
+ with open(path, "rb") as f:
54
+ frames = f.read()
55
+ elif output_type == "pt":
56
+ frames = frames
57
+
58
+ return frames