Create main.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181from fastapi import FastAPI, HTTPException, Requestfrom fastapi.staticfiles import StaticFilesfrom concurrent.futures import ThreadPoolExecutorimport asyncioimport aiohttpimport tempfileimport uuidimport osimport randomimport tracebackimport 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 existAUDIO_DIR = "audio_files"os.makedirs(AUDIO_DIR, exist_ok=True)
# Create a directory for storing output filesOUTPUT_DIR = "output"os.makedirs(OUTPUT_DIR, exist_ok=True)
# Mount the audio directoryapp.mount("/audio", StaticFiles(directory=AUDIO_DIR), name="audio")
# Mount the output directoryapp.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=8000)main.pyAdded+181