File size: 2,113 Bytes
1a79cb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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}"

@app.post("/process_video_audio")
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)