rajux75 commited on
Commit
24dade7
·
verified ·
1 Parent(s): dc2099d

Create utils/helpers.py

Browse files
Files changed (1) hide show
  1. utils/helpers.py +49 -0
utils/helpers.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # utils/helpers.py
2
+ import base64
3
+ from io import BytesIO
4
+ from PIL import Image
5
+ import imageio
6
+ import numpy as np
7
+ from typing import List
8
+
9
+ def encode_image_base64(image: Image.Image, format="PNG") -> str:
10
+ """Encodes a PIL Image to a base64 string."""
11
+ buffered = BytesIO()
12
+ image.save(buffered, format=format)
13
+ img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
14
+ return img_str
15
+
16
+ def decode_base64_image(image_base64: str) -> Image.Image:
17
+ """Decodes a base64 string to a PIL Image."""
18
+ img_bytes = base64.b64decode(image_base64)
19
+ img = Image.open(BytesIO(img_bytes))
20
+ return img.convert("RGB") # Ensure RGB format
21
+
22
+ def encode_video_base64(video_frames: List[np.ndarray], fps: int, format="MP4") -> str:
23
+ """Encodes a list of numpy array frames (H, W, C) to a base64 video string."""
24
+ if not video_frames:
25
+ raise ValueError("Cannot encode empty video frames list.")
26
+
27
+ buffered = BytesIO()
28
+ # Ensure frames are uint8
29
+ frames_uint8 = [(frame * 255).astype(np.uint8) if frame.dtype != np.uint8 else frame for frame in video_frames]
30
+
31
+ if format.upper() == "MP4":
32
+ # imageio requires ffmpeg to be installed in the Space environment
33
+ # Add 'imageio[ffmpeg]' to requirements.txt if needed, or ensure ffmpeg is available
34
+ try:
35
+ imageio.mimwrite(buffered, frames_uint8, format='mp4', fps=fps, output_params=['-vf', 'pad=ceil(iw/2)*2:ceil(ih/2)*2']) # Ensure dimensions are even for some codecs
36
+ # quality=8 is a reasonable default, adjust if needed. Macro_block size needed for h264
37
+ except Exception as e:
38
+ print(f"WARNING: MP4 encoding failed ({e}). Check ffmpeg availability. Falling back to GIF.")
39
+ # Fallback to GIF if MP4 fails (e.g., ffmpeg not found)
40
+ imageio.mimwrite(buffered, frames_uint8, format='gif', duration=1000/fps) # duration is in ms
41
+ format = "GIF"
42
+
43
+ elif format.upper() == "GIF":
44
+ imageio.mimwrite(buffered, frames_uint8, format='gif', duration=1000/fps) # duration is in ms
45
+ else:
46
+ raise ValueError(f"Unsupported video format: {format}")
47
+
48
+ video_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
49
+ return video_str, format.upper() # Return actual format used (might differ on fallback)