Spaces:
Running
Running
| import os | |
| import uuid | |
| import base64 | |
| import aiohttp | |
| from typing import Dict, Any, List | |
| VIDEO_DIR = "/tmp/generated_videos" | |
| async def save_video(video_data: Dict[str, Any]) -> List[str]: | |
| """ | |
| Saves all videos from a response object and returns a list of their local paths. | |
| """ | |
| os.makedirs(VIDEO_DIR, exist_ok=True) | |
| saved_paths = [] | |
| video_list = video_data.get("videos", []) | |
| if not video_list: | |
| raise Exception("No 'videos' array found in the response data.") | |
| for video_item in video_list: | |
| video_filename = f"{uuid.uuid4()}.mp4" | |
| video_path = os.path.join(VIDEO_DIR, video_filename) | |
| saved = False | |
| try: | |
| if "gcsUri" in video_item: | |
| gcs_uri = video_item["gcsUri"] | |
| async with aiohttp.ClientSession() as session: | |
| async with session.get(gcs_uri) as response: | |
| response.raise_for_status() | |
| with open(video_path, "wb") as f: | |
| f.write(await response.read()) | |
| saved_paths.append(video_path) | |
| saved = True | |
| elif "bytesBase64Encoded" in video_item: | |
| video_bytes = base64.b64decode(video_item["bytesBase64Encoded"]) | |
| with open(video_path, "wb") as f: | |
| f.write(video_bytes) | |
| saved_paths.append(video_path) | |
| saved = True | |
| except Exception as e: | |
| # Log the error but continue trying to process other videos | |
| print(f"Warning: Failed to save a video. Error: {e}") | |
| if not saved_paths: | |
| raise Exception("Failed to save any videos from the provided data.") | |
| return saved_paths |