Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,16 +1,133 @@
|
|
| 1 |
-
|
| 2 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
app = FastAPI()
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import uuid
|
| 3 |
+
import requests
|
| 4 |
+
import ffmpeg
|
| 5 |
+
import shutil
|
| 6 |
+
from fastapi import FastAPI, HTTPException, Form
|
| 7 |
+
from fastapi.responses import HTMLResponse, FileResponse
|
| 8 |
+
from pydantic import BaseModel
|
| 9 |
+
from typing import List
|
| 10 |
+
import aiofiles
|
| 11 |
|
| 12 |
app = FastAPI()
|
| 13 |
|
| 14 |
+
# Storage paths
|
| 15 |
+
TEMP_DIR = "temp"
|
| 16 |
+
os.makedirs(TEMP_DIR, exist_ok=True)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class SplitRequest(BaseModel):
|
| 20 |
+
audio_url: str
|
| 21 |
+
segments: List[dict] # Example: [{"start": 10, "end": 15}, {"start": 30, "end": 40}]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class MergeRequest(BaseModel):
|
| 25 |
+
chunks: List[str] # List of file paths to merge
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
async def download_file(url: str, save_path: str):
|
| 29 |
+
"""Downloads an audio file from a URL."""
|
| 30 |
+
response = requests.get(url, stream=True)
|
| 31 |
+
if response.status_code != 200:
|
| 32 |
+
raise HTTPException(status_code=400, detail="Failed to download audio file")
|
| 33 |
+
|
| 34 |
+
async with aiofiles.open(save_path, 'wb') as f:
|
| 35 |
+
async for chunk in response.iter_content(chunk_size=8192):
|
| 36 |
+
await f.write(chunk)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def split_audio(file_path: str, segments: List[dict], output_dir: str):
|
| 40 |
+
"""Splits audio and saves chunks."""
|
| 41 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 42 |
+
base_name = os.path.splitext(os.path.basename(file_path))[0]
|
| 43 |
+
output_files = []
|
| 44 |
+
|
| 45 |
+
for i, seg in enumerate(segments):
|
| 46 |
+
output_file = os.path.join(output_dir, f"{base_name}_chunk{i}.mp3")
|
| 47 |
+
(
|
| 48 |
+
ffmpeg.input(file_path, ss=seg["start"], to=seg["end"])
|
| 49 |
+
.output(output_file, format="mp3")
|
| 50 |
+
.run(overwrite_output=True, quiet=True)
|
| 51 |
+
)
|
| 52 |
+
output_files.append(output_file)
|
| 53 |
+
|
| 54 |
+
return output_files
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def merge_audio(chunks: List[str], output_file: str):
|
| 58 |
+
"""Merges multiple audio chunks into one."""
|
| 59 |
+
inputs = [ffmpeg.input(chunk) for chunk in chunks]
|
| 60 |
+
concat = ffmpeg.concat(*inputs, v=0, a=1).output(output_file)
|
| 61 |
+
concat.run(overwrite_output=True, quiet=True)
|
| 62 |
+
return output_file
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@app.get("/", response_class=HTMLResponse)
|
| 66 |
+
def index():
|
| 67 |
+
"""Serve a simple HTML test page."""
|
| 68 |
+
return """
|
| 69 |
+
<html>
|
| 70 |
+
<head>
|
| 71 |
+
<title>Audio Processing Server</title>
|
| 72 |
+
</head>
|
| 73 |
+
<body>
|
| 74 |
+
<h2>Test Audio Split</h2>
|
| 75 |
+
<form action="/test_split" method="post">
|
| 76 |
+
<label>Audio URL:</label>
|
| 77 |
+
<input type="text" name="audio_url" required>
|
| 78 |
+
<label>Start Time (seconds):</label>
|
| 79 |
+
<input type="number" name="start_time" required>
|
| 80 |
+
<label>End Time (seconds):</label>
|
| 81 |
+
<input type="number" name="end_time" required>
|
| 82 |
+
<button type="submit">Split Audio</button>
|
| 83 |
+
</form>
|
| 84 |
+
</body>
|
| 85 |
+
</html>
|
| 86 |
+
"""
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@app.post("/test_split")
|
| 90 |
+
async def test_split(audio_url: str = Form(...), start_time: int = Form(...), end_time: int = Form(...)):
|
| 91 |
+
"""Test the split endpoint from the HTML form."""
|
| 92 |
+
file_id = str(uuid.uuid4())
|
| 93 |
+
input_file = os.path.join(TEMP_DIR, f"{file_id}.mp3")
|
| 94 |
+
output_dir = os.path.join(TEMP_DIR, f"{file_id}_chunks")
|
| 95 |
+
|
| 96 |
+
await download_file(audio_url, input_file)
|
| 97 |
+
chunk_files = split_audio(input_file, [{"start": start_time, "end": end_time}], output_dir)
|
| 98 |
+
|
| 99 |
+
if chunk_files:
|
| 100 |
+
return FileResponse(chunk_files[0], media_type="audio/mpeg", filename=os.path.basename(chunk_files[0]))
|
| 101 |
+
else:
|
| 102 |
+
raise HTTPException(status_code=500, detail="Error processing audio split")
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
@app.post("/split")
|
| 106 |
+
async def split_audio_endpoint(request: SplitRequest):
|
| 107 |
+
"""Splits audio into specified segments."""
|
| 108 |
+
file_id = str(uuid.uuid4())
|
| 109 |
+
input_file = os.path.join(TEMP_DIR, f"{file_id}.mp3")
|
| 110 |
+
output_dir = os.path.join(TEMP_DIR, f"{file_id}_chunks")
|
| 111 |
+
|
| 112 |
+
await download_file(request.audio_url, input_file)
|
| 113 |
+
chunk_files = split_audio(input_file, request.segments, output_dir)
|
| 114 |
+
|
| 115 |
+
return {"chunks": chunk_files}
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
@app.post("/merge")
|
| 119 |
+
def merge_audio_endpoint(request: MergeRequest):
|
| 120 |
+
"""Merges provided audio chunks into one."""
|
| 121 |
+
if not request.chunks:
|
| 122 |
+
raise HTTPException(status_code=400, detail="No chunks provided")
|
| 123 |
+
|
| 124 |
+
output_file = os.path.join(TEMP_DIR, f"merged_{uuid.uuid4()}.mp3")
|
| 125 |
+
merged_file = merge_audio(request.chunks, output_file)
|
| 126 |
+
|
| 127 |
+
return {"merged_audio": merged_file}
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
if __name__ == "__main__":
|
| 131 |
+
import uvicorn
|
| 132 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
| 133 |
+
|