veltrixcode commited on
Commit
62c0892
·
verified ·
1 Parent(s): fcb1baf

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +234 -40
main.py CHANGED
@@ -1,78 +1,272 @@
1
- from fastapi import FastAPI, UploadFile, File, Form
2
  from fastapi.responses import HTMLResponse, FileResponse
3
  import subprocess, uuid, os, shutil, requests
4
 
5
  app = FastAPI()
6
-
7
  TMP = "/tmp/audio"
8
  os.makedirs(TMP, exist_ok=True)
9
 
 
 
 
 
 
 
 
 
 
 
10
  FILTER = (
11
- "asetrate=44100*0.85,"
12
- "atempo=1/0.85,"
13
- "aresample=44100,"
14
- "aecho=0.8:0.9:1200:0.4"
15
  )
16
 
17
- HTML = """
18
- <!DOCTYPE html>
19
- <html>
20
  <head>
 
 
21
  <title>Slowed + Reverb</title>
22
  <style>
23
- body { background:#111; color:#fff; font-family:sans-serif; text-align:center; padding:40px }
24
- input, button { padding:10px; margin:10px; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  </style>
26
  </head>
27
  <body>
28
- <h1>🎧 Slowed + Reverb</h1>
29
 
30
- <form action="/slowed-reverb" method="post" enctype="multipart/form-data">
31
- <h3>Upload file</h3>
32
- <input type="file" name="file">
33
- <button type="submit">Process</button>
34
- </form>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
- <h3>OR</h3>
37
 
38
- <form action="/slowed-reverb-url" method="post">
39
- <input type="text" name="url" placeholder="Direct audio URL" size="50">
40
- <button type="submit">Process</button>
41
- </form>
 
42
  </body>
43
- </html>
44
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
  @app.get("/", response_class=HTMLResponse)
47
  def home():
48
  return HTML
49
 
 
50
  @app.post("/slowed-reverb")
51
- async def slowed_reverb(file: UploadFile = File(...)):
52
- ext = os.path.splitext(file.filename)[1]
53
- inp = os.path.join(TMP, f"{uuid.uuid4()}{ext}")
54
- out = os.path.join(TMP, f"{uuid.uuid4()}_sr.mp3")
 
55
 
56
  with open(inp, "wb") as f:
57
  shutil.copyfileobj(file.file, f)
58
 
59
- cmd = ["ffmpeg", "-y", "-i", inp, "-af", FILTER, out]
60
- subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
 
 
61
 
62
- return FileResponse(out, media_type="audio/mpeg", filename="slowed_reverb.mp3")
63
 
64
  @app.post("/slowed-reverb-url")
65
- def slowed_reverb_url(url: str = Form(...)):
66
- ext = os.path.splitext(url)[1] or ".mp3"
67
- inp = os.path.join(TMP, f"{uuid.uuid4()}{ext}")
68
- out = os.path.join(TMP, f"{uuid.uuid4()}_sr.mp3")
 
 
 
 
 
 
 
69
 
70
- r = requests.get(url, stream=True, timeout=20)
71
  with open(inp, "wb") as f:
72
- for chunk in r.iter_content(1024):
73
  f.write(chunk)
74
 
75
- cmd = ["ffmpeg", "-y", "-i", inp, "-af", FILTER, out]
76
- subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
77
 
78
- return FileResponse(out, media_type="audio/mpeg", filename="slowed_reverb.mp3")
 
 
1
+ from fastapi import FastAPI, UploadFile, File, Form, HTTPException, BackgroundTasks
2
  from fastapi.responses import HTMLResponse, FileResponse
3
  import subprocess, uuid, os, shutil, requests
4
 
5
  app = FastAPI()
 
6
  TMP = "/tmp/audio"
7
  os.makedirs(TMP, exist_ok=True)
8
 
9
+ # ─── FILTER EXPLAINED ────────────────────────────────────────────────────────
10
+ # 1. asetrate=37485 → lowers sample rate to 85% of 44100, slowing + lowering pitch
11
+ # 2. atempo=1.0 → keep duration as-is (slowing came from asetrate)
12
+ # 3. aresample=44100 → resample back to standard 44100 Hz for playback
13
+ # 4. aecho (subtle) → short multi-tap reverb feel, NOT a slap echo:
14
+ # in_gain=0.8 → input level
15
+ # out_gain=0.88 → output level (keep it quieter than dry)
16
+ # delays=20|40|60 → very short early reflections in ms (room-like, not echo)
17
+ # decays=0.4|0.25|0.15 → each reflection fades quickly
18
+ # Result: dreamy, slowed, pitched-down with room reverb — no slapback echo
19
  FILTER = (
20
+ "asetrate=37485," # 44100 * 0.85 = 37485
21
+ "aresample=44100," # restore to standard rate (slows + lowers pitch)
22
+ "aecho=0.8:0.88:20|40|60:0.4|0.25|0.15" # subtle room reverb, not echo
 
23
  )
24
 
25
+ HTML = """<!DOCTYPE html>
26
+ <html lang="en">
 
27
  <head>
28
+ <meta charset="UTF-8">
29
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
30
  <title>Slowed + Reverb</title>
31
  <style>
32
+ @import url('https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&display=swap');
33
+
34
+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
35
+
36
+ :root {
37
+ --bg: #0a0a0f;
38
+ --surface: #13131a;
39
+ --border: #2a2a3a;
40
+ --accent: #7c6dfa;
41
+ --accent2: #fa6dc4;
42
+ --text: #e8e8f0;
43
+ --muted: #6060808;
44
+ }
45
+
46
+ body {
47
+ background: var(--bg);
48
+ color: var(--text);
49
+ font-family: 'Space Mono', monospace;
50
+ min-height: 100vh;
51
+ display: flex;
52
+ flex-direction: column;
53
+ align-items: center;
54
+ justify-content: center;
55
+ padding: 40px 20px;
56
+ background-image:
57
+ radial-gradient(ellipse 80% 50% at 50% -10%, rgba(124,109,250,0.15) 0%, transparent 60%),
58
+ radial-gradient(ellipse 60% 40% at 80% 100%, rgba(250,109,196,0.08) 0%, transparent 60%);
59
+ }
60
+
61
+ h1 {
62
+ font-size: clamp(1.6rem, 5vw, 2.4rem);
63
+ font-weight: 700;
64
+ letter-spacing: -0.02em;
65
+ margin-bottom: 8px;
66
+ background: linear-gradient(135deg, var(--accent), var(--accent2));
67
+ -webkit-background-clip: text;
68
+ -webkit-text-fill-color: transparent;
69
+ background-clip: text;
70
+ }
71
+
72
+ .subtitle {
73
+ font-size: 0.75rem;
74
+ color: #555570;
75
+ letter-spacing: 0.12em;
76
+ text-transform: uppercase;
77
+ margin-bottom: 48px;
78
+ }
79
+
80
+ .card {
81
+ background: var(--surface);
82
+ border: 1px solid var(--border);
83
+ border-radius: 16px;
84
+ padding: 32px;
85
+ width: 100%;
86
+ max-width: 480px;
87
+ margin-bottom: 16px;
88
+ }
89
+
90
+ .card-label {
91
+ font-size: 0.65rem;
92
+ letter-spacing: 0.15em;
93
+ text-transform: uppercase;
94
+ color: #555570;
95
+ margin-bottom: 20px;
96
+ }
97
+
98
+ .file-drop {
99
+ border: 2px dashed var(--border);
100
+ border-radius: 10px;
101
+ padding: 28px 20px;
102
+ text-align: center;
103
+ cursor: pointer;
104
+ transition: border-color 0.2s, background 0.2s;
105
+ margin-bottom: 16px;
106
+ position: relative;
107
+ }
108
+ .file-drop:hover { border-color: var(--accent); background: rgba(124,109,250,0.04); }
109
+ .file-drop input[type=file] {
110
+ position: absolute; inset: 0; opacity: 0; cursor: pointer; width: 100%; height: 100%;
111
+ }
112
+ .file-drop .icon { font-size: 2rem; margin-bottom: 8px; }
113
+ .file-drop .hint { font-size: 0.75rem; color: #555570; }
114
+ .file-drop .filename { font-size: 0.8rem; color: var(--accent); margin-top: 6px; min-height: 18px; }
115
+
116
+ .divider {
117
+ display: flex; align-items: center; gap: 12px;
118
+ margin: 8px 0 24px;
119
+ color: #333350; font-size: 0.7rem; letter-spacing: 0.1em;
120
+ }
121
+ .divider::before, .divider::after {
122
+ content: ''; flex: 1; height: 1px; background: var(--border);
123
+ }
124
+
125
+ input[type=text] {
126
+ width: 100%;
127
+ background: #0d0d14;
128
+ border: 1px solid var(--border);
129
+ border-radius: 8px;
130
+ color: var(--text);
131
+ font-family: inherit;
132
+ font-size: 0.8rem;
133
+ padding: 12px 14px;
134
+ outline: none;
135
+ transition: border-color 0.2s;
136
+ margin-bottom: 16px;
137
+ }
138
+ input[type=text]:focus { border-color: var(--accent); }
139
+ input[type=text]::placeholder { color: #33334a; }
140
+
141
+ button[type=submit] {
142
+ width: 100%;
143
+ background: linear-gradient(135deg, var(--accent), var(--accent2));
144
+ border: none;
145
+ border-radius: 8px;
146
+ color: #fff;
147
+ font-family: inherit;
148
+ font-size: 0.8rem;
149
+ font-weight: 700;
150
+ letter-spacing: 0.08em;
151
+ padding: 13px;
152
+ cursor: pointer;
153
+ transition: opacity 0.2s, transform 0.1s;
154
+ }
155
+ button[type=submit]:hover { opacity: 0.88; }
156
+ button[type=submit]:active { transform: scale(0.98); }
157
+
158
+ .info {
159
+ font-size: 0.65rem;
160
+ color: #33334a;
161
+ text-align: center;
162
+ margin-top: 24px;
163
+ letter-spacing: 0.08em;
164
+ }
165
+ .info span { color: #555570; }
166
  </style>
167
  </head>
168
  <body>
 
169
 
170
+ <h1>⟁ SLOWED + REVERB</h1>
171
+ <p class="subtitle">pitch down · room reverb · m4a output</p>
172
+
173
+ <!-- Upload form -->
174
+ <div class="card">
175
+ <div class="card-label">// Upload audio file</div>
176
+ <form action="/slowed-reverb" method="post" enctype="multipart/form-data">
177
+ <div class="file-drop" id="dropZone">
178
+ <input type="file" name="file" accept="audio/*" id="fileInput" onchange="showName(this)">
179
+ <div class="icon">🎵</div>
180
+ <div class="hint">click to select · mp3, wav, flac, ogg, m4a</div>
181
+ <div class="filename" id="fname"></div>
182
+ </div>
183
+ <button type="submit">Process File →</button>
184
+ </form>
185
+ </div>
186
+
187
+ <!-- URL form -->
188
+ <div class="card">
189
+ <div class="card-label">// Or paste direct audio URL</div>
190
+ <form action="/slowed-reverb-url" method="post">
191
+ <input type="text" name="url" placeholder="https://example.com/track.mp3">
192
+ <button type="submit">Process URL →</button>
193
+ </form>
194
+ </div>
195
 
196
+ <p class="info">output: <span>AAC/M4A</span> · fastest encode · best quality/size ratio</p>
197
 
198
+ <script>
199
+ function showName(input) {
200
+ document.getElementById('fname').textContent = input.files[0]?.name || '';
201
+ }
202
+ </script>
203
  </body>
204
+ </html>"""
205
+
206
+
207
+ def run_ffmpeg(inp: str, out: str):
208
+ """Run ffmpeg with the slowed+reverb filter. Raises HTTPException on failure."""
209
+ cmd = [
210
+ "ffmpeg", "-y", "-i", inp,
211
+ "-af", FILTER,
212
+ "-c:a", "aac", # AAC codec — faster than libmp3lame, better quality/size
213
+ "-b:a", "192k", # 192kbps AAC ≈ 320kbps MP3 quality
214
+ "-movflags", "+faststart", # web-optimised: moov atom at front
215
+ out
216
+ ]
217
+ result = subprocess.run(cmd, capture_output=True, text=True)
218
+ if result.returncode != 0:
219
+ raise HTTPException(status_code=500, detail=f"ffmpeg error:\n{result.stderr}")
220
+
221
+
222
+ def cleanup(*paths: str):
223
+ """Delete temp files after response is sent."""
224
+ for p in paths:
225
+ try:
226
+ os.remove(p)
227
+ except FileNotFoundError:
228
+ pass
229
+
230
 
231
  @app.get("/", response_class=HTMLResponse)
232
  def home():
233
  return HTML
234
 
235
+
236
  @app.post("/slowed-reverb")
237
+ async def slowed_reverb(background_tasks: BackgroundTasks, file: UploadFile = File(...)):
238
+ ext = os.path.splitext(file.filename)[1] or ".mp3"
239
+ uid = uuid.uuid4()
240
+ inp = os.path.join(TMP, f"{uid}_in{ext}")
241
+ out = os.path.join(TMP, f"{uid}_out.m4a")
242
 
243
  with open(inp, "wb") as f:
244
  shutil.copyfileobj(file.file, f)
245
 
246
+ run_ffmpeg(inp, out)
247
+
248
+ background_tasks.add_task(cleanup, inp, out)
249
+ return FileResponse(out, media_type="audio/mp4", filename="slowed_reverb.m4a")
250
 
 
251
 
252
  @app.post("/slowed-reverb-url")
253
+ def slowed_reverb_url(background_tasks: BackgroundTasks, url: str = Form(...)):
254
+ ext = os.path.splitext(url.split("?")[0])[1] or ".mp3" # strip query params before ext check
255
+ uid = uuid.uuid4()
256
+ inp = os.path.join(TMP, f"{uid}_in{ext}")
257
+ out = os.path.join(TMP, f"{uid}_out.m4a")
258
+
259
+ try:
260
+ r = requests.get(url, stream=True, timeout=30)
261
+ r.raise_for_status()
262
+ except requests.RequestException as e:
263
+ raise HTTPException(status_code=400, detail=f"Failed to fetch URL: {e}")
264
 
 
265
  with open(inp, "wb") as f:
266
+ for chunk in r.iter_content(chunk_size=65536): # 64KB chunks — faster download
267
  f.write(chunk)
268
 
269
+ run_ffmpeg(inp, out)
 
270
 
271
+ background_tasks.add_task(cleanup, inp, out)
272
+ return FileResponse(out, media_type="audio/mp4", filename="slowed_reverb.m4a")