light-hub-65 / utils.py
ItsMpilo's picture
Deploy Gradio app with multiple files
359c2e8 verified
import os
import tempfile
from pathlib import Path
import base64
from PIL import Image
import io
import shutil
def save_uploaded_file(file_obj, extension=".jpg"):
"""
Save uploaded file to temporary location
Args:
file_obj: File object or PIL Image
extension (str): File extension
Returns:
str: Path to saved file
"""
try:
temp_dir = tempfile.mkdtemp()
if isinstance(file_obj, Image.Image):
# PIL Image
temp_path = os.path.join(temp_dir, f"upload{extension}")
file_obj.save(temp_path)
elif hasattr(file_obj, 'name'):
# File-like object
temp_path = os.path.join(temp_dir, f"upload{extension}")
shutil.copy2(file_obj.name, temp_path)
else:
# Assume it's a base64 string or bytes
temp_path = os.path.join(temp_dir, f"upload{extension}")
if isinstance(file_obj, str):
# Base64 string
if ',' in file_obj:
file_data = base64.b64decode(file_obj.split(',')[1])
else:
file_data = base64.b64decode(file_obj)
with open(temp_path, 'wb') as f:
f.write(file_data)
elif isinstance(file_obj, bytes):
with open(temp_path, 'wb') as f:
f.write(file_obj)
return temp_path
except Exception as e:
print(f"Error saving file: {e}")
return None
def cleanup_temp_files(file_paths):
"""
Clean up temporary files
Args:
file_paths (list): List of file paths to clean up
"""
for file_path in file_paths:
try:
if os.path.exists(file_path):
if os.path.isfile(file_path):
os.remove(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print(f"Error cleaning up {file_path}: {e}")
def image_to_base64(image, format='JPEG', quality=85):
"""
Convert PIL Image to base64 string
Args:
image (PIL.Image): Input image
format (str): Output format
quality (int): Compression quality
Returns:
str: Base64 encoded image string
"""
buffer = io.BytesIO()
image.save(buffer, format=format, quality=quality)
image_data = buffer.getvalue()
return base64.b64encode(image_data).decode()
def base64_to_image(base64_string):
"""
Convert base64 string to PIL Image
Args:
base64_string (str): Base64 encoded image string
Returns:
PIL.Image: Decoded image
"""
try:
if ',' in base64_string:
base64_string = base64_string.split(',')[1]
image_data = base64.b64decode(base64_string)
image = Image.open(io.BytesIO(image_data))
return image
except Exception as e:
print(f"Error decoding base64 image: {e}")
return None
def create_video_preview(video_path, num_frames=4):
"""
Create preview frames from video
Args:
video_path (str): Path to video file
num_frames (int): Number of preview frames
Returns:
list: List of PIL Images
"""
try:
import cv2
cap = cv2.VideoCapture(video_path)
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
fps = cap.get(cv2.CAP_PROP_FPS)
if total_frames == 0:
return []
# Select frames evenly distributed across the video
frame_indices = np.linspace(0, total_frames-1, num_frames, dtype=int)
frames = []
for frame_idx in frame_indices:
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)
ret, frame = cap.read()
if ret:
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frames.append(Image.fromarray(frame_rgb))
cap.release()
return frames
except Exception as e:
print(f"Error creating video preview: {e}")
return []
def validate_video_file(file_path):
"""
Validate that the file is a valid video
Args:
file_path (str): Path to video file
Returns:
bool: True if valid video file
"""
try:
import cv2
cap = cv2.VideoCapture(file_path)
ret = cap.isOpened()
cap.release()
return ret
except:
return False
def validate_image_file(file_path):
"""
Validate that the file is a valid image
Args:
file_path (str): Path to image file
Returns:
bool: True if valid image file
"""
try:
from PIL import Image
with Image.open(file_path) as img:
img.verify()
return True
except:
return False