Pepguy commited on
Commit
a8336db
·
verified ·
1 Parent(s): 24d52af

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +133 -16
app.py CHANGED
@@ -1,28 +1,145 @@
1
- from fastapi import FastAPI
 
2
  import subprocess
 
 
 
 
 
3
 
4
  app = FastAPI()
5
 
6
- @app.get("/")
7
- def greet_json():
8
- return {"Hello": "World!"}
 
 
 
 
 
9
 
10
- @app.get("/ffmpeg-version")
11
- def get_ffmpeg_version():
12
- try:
13
- result = subprocess.run(["ffmpeg", "-version"], capture_output=True, text=True)
14
- return {"ffmpeg_version": result.stdout.splitlines()[0]} # Return only the first line
15
- except FileNotFoundError:
16
- return {"error": "FFmpeg is not installed or not found in PATH"}
 
 
 
 
 
 
 
 
 
 
17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
 
 
 
 
 
19
 
 
 
20
 
 
 
 
 
 
21
 
22
- # from fastapi import FastAPI
 
23
 
24
- # app = FastAPI()
 
 
 
 
25
 
26
- # @app.get("/")
27
- # def greet_json():
28
- # return {"Hello": "World!"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import uuid
3
  import subprocess
4
+ import requests
5
+ import base64
6
+ from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Request
7
+ from fastapi.responses import HTMLResponse, JSONResponse
8
+ from fastapi.middleware.cors import CORSMiddleware
9
 
10
  app = FastAPI()
11
 
12
+ # Allow CORS for testing
13
+ app.add_middleware(
14
+ CORSMiddleware,
15
+ allow_origins=["*"],
16
+ allow_credentials=True,
17
+ allow_methods=["*"],
18
+ allow_headers=["*"],
19
+ )
20
 
21
+ # Base directory to store task files
22
+ BASE_DIR = "tasks"
23
+ os.makedirs(BASE_DIR, exist_ok=True)
24
+
25
+ @app.post("/process")
26
+ async def process_audio(
27
+ request: Request,
28
+ file: UploadFile = File(None),
29
+ url: str = Form(None)
30
+ ):
31
+ if not file and not url:
32
+ raise HTTPException(status_code=400, detail="Provide either a file or a URL.")
33
+
34
+ # Generate unique task ID and create folder for this task
35
+ task_id = str(uuid.uuid4())
36
+ task_dir = os.path.join(BASE_DIR, task_id)
37
+ os.makedirs(task_dir, exist_ok=True)
38
 
39
+ # Download or read the file
40
+ if file:
41
+ filename = file.filename
42
+ input_path = os.path.join(task_dir, filename)
43
+ with open(input_path, "wb") as f:
44
+ content = await file.read()
45
+ f.write(content)
46
+ else:
47
+ # Download file from provided URL
48
+ resp = requests.get(url)
49
+ if resp.status_code != 200:
50
+ raise HTTPException(status_code=400, detail="Failed to download file from URL.")
51
+ ext = os.path.splitext(url)[1] or ".mp3"
52
+ filename = f"input{ext}"
53
+ input_path = os.path.join(task_dir, filename)
54
+ with open(input_path, "wb") as f:
55
+ f.write(resp.content)
56
+
57
+ # Run Spleeter to separate into 2 stems (vocals and accompaniment)
58
+ # Spleeter will create a subfolder named after the input file (without extension)
59
+ cmd = [
60
+ "spleeter", "separate",
61
+ "-i", input_path,
62
+ "-p", "spleeter:2stems",
63
+ "-o", task_dir
64
+ ]
65
+ try:
66
+ subprocess.run(cmd, check=True)
67
+ except subprocess.CalledProcessError as e:
68
+ raise HTTPException(status_code=500, detail=f"Spleeter processing failed: {e}")
69
 
70
+ # Determine output folder name and expected files
71
+ base_name = os.path.splitext(filename)[0]
72
+ output_dir = os.path.join(task_dir, base_name)
73
+ vocals_path = os.path.join(output_dir, "vocals.wav")
74
+ accomp_path = os.path.join(output_dir, "accompaniment.wav")
75
 
76
+ if not (os.path.exists(vocals_path) and os.path.exists(accomp_path)):
77
+ raise HTTPException(status_code=500, detail="Output files not found after processing.")
78
 
79
+ # Read output files and encode in base64
80
+ with open(vocals_path, "rb") as f:
81
+ vocals_data = f.read()
82
+ with open(accomp_path, "rb") as f:
83
+ accomp_data = f.read()
84
 
85
+ vocals_b64 = base64.b64encode(vocals_data).decode("utf-8")
86
+ accomp_b64 = base64.b64encode(accomp_data).decode("utf-8")
87
 
88
+ return JSONResponse(content={
89
+ "task_id": task_id,
90
+ "vocals": vocals_b64,
91
+ "accompaniment": accomp_b64
92
+ })
93
 
94
+ @app.get("/", response_class=HTMLResponse)
95
+ def index():
96
+ html_content = """
97
+ <!DOCTYPE html>
98
+ <html>
99
+ <head>
100
+ <title>Spleeter API Test</title>
101
+ </head>
102
+ <body>
103
+ <h1>Spleeter API Test</h1>
104
+ <form id="spleeterForm" enctype="multipart/form-data">
105
+ <div>
106
+ <label>Upload File:</label>
107
+ <input type="file" name="file">
108
+ </div>
109
+ <div>
110
+ <label>Or Enter URL:</label>
111
+ <input type="text" name="url" size="50">
112
+ </div>
113
+ <button type="submit">Process Audio</button>
114
+ </form>
115
+ <div id="result"></div>
116
+ <script>
117
+ const form = document.getElementById('spleeterForm');
118
+ form.onsubmit = async (e) => {
119
+ e.preventDefault();
120
+ const formData = new FormData(form);
121
+ const response = await fetch('/process', {
122
+ method: 'POST',
123
+ body: formData
124
+ });
125
+ const data = await response.json();
126
+ if (response.ok) {
127
+ const vocalsSrc = "data:audio/wav;base64," + data.vocals;
128
+ const accompSrc = "data:audio/wav;base64," + data.accompaniment;
129
+
130
+ document.getElementById('result').innerHTML = `
131
+ <h3>Vocals</h3>
132
+ <audio controls src="${vocalsSrc}"></audio>
133
+ <h3>Accompaniment</h3>
134
+ <audio controls src="${accompSrc}"></audio>
135
+ `;
136
+ } else {
137
+ document.getElementById('result').innerHTML = `<p>Error: ${data.detail}</p>`;
138
+ }
139
+ };
140
+ </script>
141
+ </body>
142
+ </html>
143
+ """
144
+ return HTMLResponse(content=html_content)
145
+