Update main.py
Browse files
main.py
CHANGED
@@ -3,12 +3,13 @@ from fastapi.staticfiles import StaticFiles
|
|
3 |
from pydantic import BaseModel, HttpUrl
|
4 |
from typing import List
|
5 |
import os
|
6 |
-
import
|
7 |
import uuid
|
8 |
-
import
|
9 |
import re
|
10 |
from urllib.parse import urlparse
|
11 |
import shutil
|
|
|
12 |
|
13 |
# Create FastAPI app
|
14 |
app = FastAPI()
|
@@ -29,8 +30,8 @@ def extract_google_drive_id(url):
|
|
29 |
match = re.search(pattern, str(url))
|
30 |
return match.group(1) if match else None
|
31 |
|
32 |
-
def download_file(url, local_path):
|
33 |
-
"""Download a file from URL to local path"""
|
34 |
try:
|
35 |
# Handle Google Drive URLs
|
36 |
if "drive.google.com" in str(url):
|
@@ -38,30 +39,34 @@ def download_file(url, local_path):
|
|
38 |
if file_id:
|
39 |
url = f"https://drive.google.com/uc?export=download&id={file_id}"
|
40 |
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
|
|
|
|
|
|
|
|
47 |
return True
|
48 |
except Exception as e:
|
49 |
print(f"Error downloading {url}: {str(e)}")
|
50 |
return False
|
51 |
|
52 |
-
def create_slideshow(image_paths, audio_path, output_path, duration):
|
53 |
-
"""Generate slideshow from images and audio using ffmpeg"""
|
54 |
# Create temporary file list for ffmpeg concat
|
55 |
concat_file = "temp_concat.txt"
|
56 |
|
57 |
-
with open(concat_file, "w") as f:
|
58 |
for img in image_paths:
|
59 |
-
f.write(f"file '{img}'\n")
|
60 |
-
f.write(f"duration {duration}\n")
|
61 |
|
62 |
# Add the last image again without duration (required by ffmpeg)
|
63 |
if image_paths:
|
64 |
-
f.write(f"file '{image_paths[-1]}'\n")
|
65 |
|
66 |
# Run ffmpeg command to create slideshow with audio
|
67 |
cmd = [
|
@@ -79,11 +84,22 @@ def create_slideshow(image_paths, audio_path, output_path, duration):
|
|
79 |
]
|
80 |
|
81 |
try:
|
82 |
-
|
83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
84 |
return True
|
85 |
-
except
|
86 |
-
print(f"FFmpeg error: {e
|
87 |
if os.path.exists(concat_file):
|
88 |
os.remove(concat_file)
|
89 |
return False
|
@@ -102,23 +118,32 @@ async def make_slideshow(request: SlideshowRequest):
|
|
102 |
try:
|
103 |
# Download images
|
104 |
image_paths = []
|
|
|
|
|
105 |
for i, url in enumerate(request.image_urls):
|
106 |
image_path = os.path.join(request_dir, f"image_{i:03d}.png")
|
107 |
-
|
108 |
-
|
109 |
-
else:
|
110 |
-
raise HTTPException(status_code=400, detail=f"Failed to download image: {url}")
|
111 |
|
112 |
# Download audio
|
113 |
audio_path = os.path.join(request_dir, "audio.mp3")
|
114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
115 |
raise HTTPException(status_code=400, detail=f"Failed to download audio: {request.audio_url}")
|
116 |
|
117 |
# Output video path
|
118 |
output_path = os.path.join(request_dir, "slideshow.mp4")
|
119 |
|
120 |
# Generate slideshow
|
121 |
-
if not create_slideshow(image_paths, audio_path, output_path, request.duration):
|
122 |
raise HTTPException(status_code=500, detail="Failed to create slideshow")
|
123 |
|
124 |
# Return URL to the video
|
|
|
3 |
from pydantic import BaseModel, HttpUrl
|
4 |
from typing import List
|
5 |
import os
|
6 |
+
import asyncio
|
7 |
import uuid
|
8 |
+
import aiohttp
|
9 |
import re
|
10 |
from urllib.parse import urlparse
|
11 |
import shutil
|
12 |
+
import aiofiles
|
13 |
|
14 |
# Create FastAPI app
|
15 |
app = FastAPI()
|
|
|
30 |
match = re.search(pattern, str(url))
|
31 |
return match.group(1) if match else None
|
32 |
|
33 |
+
async def download_file(url, local_path):
|
34 |
+
"""Download a file from URL to local path asynchronously"""
|
35 |
try:
|
36 |
# Handle Google Drive URLs
|
37 |
if "drive.google.com" in str(url):
|
|
|
39 |
if file_id:
|
40 |
url = f"https://drive.google.com/uc?export=download&id={file_id}"
|
41 |
|
42 |
+
async with aiohttp.ClientSession() as session:
|
43 |
+
async with session.get(str(url)) as response:
|
44 |
+
response.raise_for_status()
|
45 |
+
|
46 |
+
async with aiofiles.open(local_path, 'wb') as f:
|
47 |
+
while True:
|
48 |
+
chunk = await response.content.read(8192)
|
49 |
+
if not chunk:
|
50 |
+
break
|
51 |
+
await f.write(chunk)
|
52 |
return True
|
53 |
except Exception as e:
|
54 |
print(f"Error downloading {url}: {str(e)}")
|
55 |
return False
|
56 |
|
57 |
+
async def create_slideshow(image_paths, audio_path, output_path, duration):
|
58 |
+
"""Generate slideshow from images and audio using ffmpeg asynchronously"""
|
59 |
# Create temporary file list for ffmpeg concat
|
60 |
concat_file = "temp_concat.txt"
|
61 |
|
62 |
+
async with aiofiles.open(concat_file, "w") as f:
|
63 |
for img in image_paths:
|
64 |
+
await f.write(f"file '{img}'\n")
|
65 |
+
await f.write(f"duration {duration}\n")
|
66 |
|
67 |
# Add the last image again without duration (required by ffmpeg)
|
68 |
if image_paths:
|
69 |
+
await f.write(f"file '{image_paths[-1]}'\n")
|
70 |
|
71 |
# Run ffmpeg command to create slideshow with audio
|
72 |
cmd = [
|
|
|
84 |
]
|
85 |
|
86 |
try:
|
87 |
+
process = await asyncio.create_subprocess_exec(
|
88 |
+
*cmd,
|
89 |
+
stdout=asyncio.subprocess.PIPE,
|
90 |
+
stderr=asyncio.subprocess.PIPE
|
91 |
+
)
|
92 |
+
stdout, stderr = await process.communicate()
|
93 |
+
|
94 |
+
if os.path.exists(concat_file):
|
95 |
+
os.remove(concat_file)
|
96 |
+
|
97 |
+
if process.returncode != 0:
|
98 |
+
print(f"FFmpeg error: {stderr.decode()}")
|
99 |
+
return False
|
100 |
return True
|
101 |
+
except Exception as e:
|
102 |
+
print(f"FFmpeg error: {str(e)}")
|
103 |
if os.path.exists(concat_file):
|
104 |
os.remove(concat_file)
|
105 |
return False
|
|
|
118 |
try:
|
119 |
# Download images
|
120 |
image_paths = []
|
121 |
+
download_tasks = []
|
122 |
+
|
123 |
for i, url in enumerate(request.image_urls):
|
124 |
image_path = os.path.join(request_dir, f"image_{i:03d}.png")
|
125 |
+
image_paths.append(image_path)
|
126 |
+
download_tasks.append(download_file(url, image_path))
|
|
|
|
|
127 |
|
128 |
# Download audio
|
129 |
audio_path = os.path.join(request_dir, "audio.mp3")
|
130 |
+
download_tasks.append(download_file(request.audio_url, audio_path))
|
131 |
+
|
132 |
+
# Wait for all downloads to complete
|
133 |
+
results = await asyncio.gather(*download_tasks)
|
134 |
+
|
135 |
+
# Check if all downloads were successful
|
136 |
+
if not all(results[:-1]): # All image downloads
|
137 |
+
raise HTTPException(status_code=400, detail="Failed to download one or more images")
|
138 |
+
|
139 |
+
if not results[-1]: # Audio download
|
140 |
raise HTTPException(status_code=400, detail=f"Failed to download audio: {request.audio_url}")
|
141 |
|
142 |
# Output video path
|
143 |
output_path = os.path.join(request_dir, "slideshow.mp4")
|
144 |
|
145 |
# Generate slideshow
|
146 |
+
if not await create_slideshow(image_paths, audio_path, output_path, request.duration):
|
147 |
raise HTTPException(status_code=500, detail="Failed to create slideshow")
|
148 |
|
149 |
# Return URL to the video
|