Spaces:
Runtime error
Runtime error
File size: 4,967 Bytes
359c2e8 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 |
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 |