Spaces:
Runtime error
Runtime error
Saqib commited on
Update modules/app.py
Browse files1 unmodified line2345678910111229 unmodified lines42434445464715 unmodified lines63646566676869707172737417 unmodified lines92939495969798991001011021031041051061071083 unmodified lines11211311411511611714 unmodified lines13213313413513613713813914014114214314414514614714827 unmodified lines1761771781791801811821 unmodified linefrom fastapi.staticfiles import StaticFilesfrom pytubefix import YouTubefrom pytubefix.exceptions import PytubeFixErrorfrom concurrent.futures import ThreadPoolExecutorimport ffmpegfrom pydantic import BaseModel, HttpUrlfrom typing import Listimport asyncioimport requestsimport tempfileimport time29 unmodified linesasync 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)15 unmodified linesclass VideosInput(BaseModel):video_urls: List[HttpUrl]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:17 unmodified lines# Use ffmpeg to combine image and audio into a videoinput_image = ffmpeg.input(temp_image_path, loop=1, t=5) # 5 seconds durationinput_audio = ffmpeg.input(temp_audio_path)ffmpeg_command = ffmpeg.concat(input_image, input_audio, v=1, a=1).output(output_path, vcodec='libx264', acodec='aac')# Run ffmpeg asynchronouslyawait run_ffmpeg_async(ffmpeg_command.run)# Clean up temporary filesos.unlink(temp_image_path)os.unlink(temp_audio_path)# Return the URL path to the output filereturn f"https://sxqib-api.hf.space/output/{output_filename}"except Exception as e:print(f"An error occurred: {str(e)}")print(traceback.format_exc())3 unmodified linesasync def concatenate_videos(input_data: VideosInput):try:temp_video_paths = []# Download videos to temporary filesfor video_url in input_data.video_urls:temp_video_paths.append(await download_file(str(video_url), ".mp4"))14 unmodified linesjoined = ffmpeg.concat(*video_and_audio_streams, v=1, a=1).node# Merge video and audioffmpeg_command = ffmpeg.output(joined[0], joined[1], output_path, vcodec='libx264', acodec='aac')# Run ffmpeg asynchronouslyawait run_ffmpeg_async(ffmpeg_command.run)# Clean up temporary filesfor path in temp_video_paths:os.remove(path)# Return the URL path to the output filereturn f"https://sxqib-api.hf.space/output/{output_filename}"except Exception as e:print(f"An error occurred: {str(e)}")print(traceback.format_exc())27 unmodified linesif file_stats.st_size <= 30000000:# Construct the URL for the MP3 filemp3_url = f"https://sxqib-api.hf.space/audio/{unique_filename}"return mp3_urlelse:os.remove(out_file)1 unmodified line234567891029 unmodified lines40414243444546474815 unmodified lines64656667686917 unmodified lines878889909192939495969798991003 unmodified lines10410510610710810911014 unmodified lines12512612712812913013113213313413513613713827 unmodified lines1661671681691701711721 unmodified linefrom fastapi.staticfiles import StaticFilesfrom pytubefix import YouTubefrom pytubefix.exceptions import PytubeFixErrorimport ffmpegfrom pydantic import BaseModel, HttpUrlfrom typing import Listimport requestsimport tempfileimport time29 unmodified linesasync def read_root():return {"message": "Saqib's API"}# API URLAPI_URL = "https://sxqib-api.hf.space"# Create a directory to store MP3 files if it doesn't existAUDIO_DIR = "audio_files"os.makedirs(AUDIO_DIR, exist_ok=True)15 unmodified linesclass VideosInput(BaseModel):video_urls: List[HttpUrl]async def download_file(url: str, suffix: str):async with aiohttp.ClientSession() as session:async with session.get(url) as response:17 unmodified lines# Use ffmpeg to combine image and audio into a videoinput_image = ffmpeg.input(temp_image_path, loop=1, t=5) # 5 seconds durationinput_audio = ffmpeg.input(temp_audio_path)ffmpeg.concat(input_image, input_audio, v=1, a=1).output(output_path, vcodec='libx264', acodec='aac').run_async()# Clean up temporary filesos.unlink(temp_image_path)os.unlink(temp_audio_path)# Return the URL path to the output filereturn f"{API_URL}/output/{output_filename}"except Exception as e:print(f"An error occurred: {str(e)}")print(traceback.format_exc())3 unmodified linesasync def concatenate_videos(input_data: VideosInput):try:temp_video_paths = []# Download videos to temporary filesfor video_url in input_data.video_urls:temp_video_paths.append(await download_file(str(video_url), ".mp4"))14 unmodified linesjoined = ffmpeg.concat(*video_and_audio_streams, v=1, a=1).node# Merge video and audioffmpeg.output(joined[0], joined[1], output_path, vcodec='libx264', acodec='aac').run_async()# Clean up temporary filesfor path in temp_video_paths:os.remove(path)# Return the URL path to the output filereturn f"{API_URL}/output/{output_filename}"except Exception as e:print(f"An error occurred: {str(e)}")print(traceback.format_exc())27 unmodified linesif file_stats.st_size <= 30000000:# Construct the URL for the MP3 filemp3_url = f"{API_URL}/audio/{unique_filename}"return mp3_urlelse:os.remove(out_file)
modules/app.py+9-19