Spaces:
Runtime error
Runtime error
| import os | |
| import shutil | |
| import subprocess | |
| import tempfile | |
| import urllib.request | |
| from typing import Tuple, Optional | |
| import asyncio | |
| from fastapi import FastAPI, File, UploadFile, HTTPException | |
| from fastapi.responses import FileResponse | |
| from pydantic import BaseModel, HttpUrl | |
| app = FastAPI() | |
| class VideoAudioRequest(BaseModel): | |
| face_url: HttpUrl | |
| audio_url: HttpUrl | |
| def download_file(url: str, destination: str) -> None: | |
| try: | |
| with urllib.request.urlopen(str(url)) as response, open(destination, 'wb') as out_file: | |
| shutil.copyfileobj(response, out_file) | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=f"Failed to download file from {url}: {e}") | |
| async def process_video_and_audio(face_url: str, audio_url: str) -> Tuple[str, Optional[str]]: | |
| print("process started") | |
| temp_dir = tempfile.mkdtemp(prefix="fastapi_processing_") | |
| face_path = os.path.join(temp_dir, "face.mp4") | |
| audio_path = os.path.join(temp_dir, "audio.mp3") | |
| try: | |
| download_file(face_url, face_path) | |
| download_file(audio_url, audio_path) | |
| print(face_path,audio_path) | |
| except HTTPException as e: | |
| return "", str(e) | |
| outfile_path = os.path.join(temp_dir, "result.mp4") | |
| command = f"python3 inference.py --face {face_path} --audio {audio_path} --outfile {outfile_path}" | |
| try: | |
| process = await asyncio.create_subprocess_shell(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) | |
| _, error = await process.communicate() | |
| if process.returncode == 0: | |
| return outfile_path, None | |
| else: | |
| return "", f"Error occurred during processing: {error.decode()}" | |
| except Exception as e: | |
| return "", f"Error occurred during processing: {e}" | |
| async def process_video_audio(request_data: VideoAudioRequest): | |
| result, error = await process_video_and_audio(request_data.face_url, request_data.audio_url) | |
| if result: | |
| return FileResponse(result, media_type="video/mp4") | |
| else: | |
| raise HTTPException(status_code=500, detail=error) | |