File size: 7,548 Bytes
730c60f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba83473
 
 
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
from fastapi import FastAPI, HTTPException, Request
from fastapi.staticfiles import StaticFiles
from concurrent.futures import ThreadPoolExecutor
import asyncio
import aiohttp
import tempfile
import uuid
import os
import random
import traceback
import string

app = FastAPI()

def generate_hash(length=12):
    # Characters that can appear in the hash
    characters = string.ascii_lowercase + string.digits
    # Generate a random string of the specified length
    hash_string = ''.join(random.choice(characters) for _ in range(length))
    return hash_string

@app.get("/")
async def read_root():
    return {"message": "Saqib's API"}

# Create a directory to store MP3 files if it doesn't exist
AUDIO_DIR = "audio_files"
os.makedirs(AUDIO_DIR, exist_ok=True)

# Create a directory for storing output files
OUTPUT_DIR = "output"
os.makedirs(OUTPUT_DIR, exist_ok=True)

# Mount the audio directory
app.mount("/audio", StaticFiles(directory=AUDIO_DIR), name="audio")

# Mount the output directory
app.mount("/output", StaticFiles(directory=OUTPUT_DIR), name="output")

thread_pool = ThreadPoolExecutor(max_workers=2)

async def run_ffmpeg_async(ffmpeg_command):
    loop = asyncio.get_running_loop()
    await loop.run_in_executor(thread_pool, ffmpeg_command)

async def download_file(url: str, suffix: str):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            if response.status != 200:
                raise HTTPException(status_code=400, detail=f"Failed to download file from {url}")
            with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp_file:
                temp_file.write(await response.read())
                return temp_file.name


@app.post("/add_audio_to_image")
async def add_audio_to_image(request: Request):
    try:
        # Generate a unique filename
        output_filename = f"{uuid.uuid4()}.mp4"
        output_path = os.path.join(OUTPUT_DIR, output_filename)

        # Call the modal API with the request data and download the output file
        data = await request.json()
        async with aiohttp.ClientSession() as session:
            async with session.post(f"{MODAL_BASE_URL}/add_audio_to_image", json=data) as response:
                if response.status != 200:
                    raise HTTPException(status_code=500, detail="Failed to process request")
                output_data = await response.read()
                async with aiofiles.open(output_path, "wb") as f:
                    await f.write(output_data)

        # Return the URL path to the output file
        return f"https://sxqib-api.hf.space/output/{output_filename}"
    except Exception as e:
        print(f"An error occurred: {str(e)}")
        print(traceback.format_exc())
        raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {str(e)}")

@app.post("/add_audio_to_video")
async def add_audio_to_video(request: Request):
    try:
        # Generate a unique filename
        output_filename = f"{uuid.uuid4()}.mp4"
        output_path = os.path.join(OUTPUT_DIR, output_filename)

        # Call the modal API with the request data and download the output file
        data = await request.json()
        async with aiohttp.ClientSession() as session:
            async with session.post(f"{MODAL_BASE_URL}/add_audio_to_video", json=data) as response:
                if response.status != 200:
                    raise HTTPException(status_code=500, detail="Failed to process request")
                output_data = await response.read()
                async with aiofiles.open(output_path, "wb") as f:
                    await f.write(output_data)

        # Return the URL path to the output file
        return f"https://sxqib-api.hf.space/output/{output_filename}"
    except Exception as e:
        print(f"An error occurred: {str(e)}")
        print(traceback.format_exc())
        raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {str(e)}")

@app.post("/concatenate_videos")
async def concatenate_videos(request: Request):
    try:
        # Generate a unique filename for the output
        output_filename = f"{uuid.uuid4()}.mp4"
        output_path = os.path.join(OUTPUT_DIR, output_filename)

        # Call the modal API with the request data and download the output file
        data = await request.json()
        async with aiohttp.ClientSession() as session:
            async with session.post(f"{MODAL_BASE_URL}/concatenate_videos", json=data) as response:
                if response.status != 200:
                    raise HTTPException(status_code=500, detail="Failed to process request")
                output_data = await response.read()
                async with aiofiles.open(output_path, "wb") as f:
                    await f.write(output_data)

        # Return the URL path to the output file
        return f"https://sxqib-api.hf.space/output/{output_filename}"

    except Exception as e:
        print(f"An error occurred: {str(e)}")
        print(traceback.format_exc())
        raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {str(e)}")
    
@app.post("/concatenate_audio")
async def concatenate_audio(request: Request):
    try:
        # Generate a unique filename for the output
        output_filename = f"{uuid.uuid4()}.mp3"
        output_path = os.path.join(AUDIO_DIR, output_filename)

        # Call the modal API with the request data and download the output file
        data = await request.json()
        async with aiohttp.ClientSession() as session:
            async with session.post(f"{MODAL_BASE_URL}/concatenate_audio", json=data) as response:
                if response.status != 200:
                    raise HTTPException(status_code=500, detail="Failed to process request")
                output_data = await response.read()
                async with aiofiles.open(output_path, "wb") as f:
                    await f.write(output_data)

        # Return the URL path to the output file
        return f"https://sxqib-api.hf.space/audio_files/{output_filename}"

    except Exception as e:
        print(f"An error occurred: {str(e)}")
        print(traceback.format_exc())
        raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {str(e)}")

@app.post("/make_video")
async def make_video(request: Request):
    try:
        # Generate a unique filename for the output
        output_filename = f"{uuid.uuid4()}.mp4"
        output_path = os.path.join(OUTPUT_DIR, output_filename)

        # Call the modal API with the request data and download the output file
        data = await request.json()
        async with aiohttp.ClientSession() as session:
            async with session.post(f"{MODAL_BASE_URL}/make_video", json=data) as response:
                if response.status != 200:
                    raise HTTPException(status_code=500, detail="Failed to process request")
                output_data = await response.read()
                async with aiofiles.open(output_path, "wb") as f:
                    await f.write(output_data)

        # Return the URL path to the output file
        return f"https://sxqib-api.hf.space/output/{output_filename}"

    except Exception as e:
        print(f"An error occurred: {str(e)}")
        print(traceback.format_exc())
        raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {str(e)}")

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)