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

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +88 -93
main.py CHANGED
@@ -6,20 +6,56 @@ 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>
@@ -30,22 +66,10 @@ HTML = """<!DOCTYPE html>
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;
@@ -57,46 +81,41 @@ HTML = """<!DOCTYPE html>
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;
@@ -105,47 +124,36 @@ HTML = """<!DOCTYPE html>
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;
@@ -154,37 +162,35 @@ HTML = """<!DOCTYPE html>
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">
@@ -193,34 +199,30 @@ HTML = """<!DOCTYPE html>
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)
@@ -239,34 +241,27 @@ async def slowed_reverb(background_tasks: BackgroundTasks, file: UploadFile = Fi
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")
 
6
  TMP = "/tmp/audio"
7
  os.makedirs(TMP, exist_ok=True)
8
 
9
+ # ─── LOFI FILTER CHAIN ───────────────────────────────────────────────────────
10
+ #
11
+ # 1. asetrate=37485
12
+ # Lowers sample rate to 85% of 44100. This simultaneously slows playback
13
+ # AND lowers pitch — exactly how slowed+reverb tracks are made.
14
+ # (No atempo — that would undo the slowdown.)
15
+ #
16
+ # 2. aresample=44100
17
+ # Resample back to standard 44100 Hz so players read it correctly.
18
+ # The audio remains slow+pitched-down; this just fixes the clock rate.
19
+ #
20
+ # 3. lowpass=f=3500
21
+ # Hard low-pass at 3.5 kHz. Cuts harsh digital highs, cymbals become
22
+ # soft, vocals get that "playing through a wall" warmth. Core lofi sound.
23
+ #
24
+ # 4. equalizer=f=80:width_type=o:width=2:g=3
25
+ # +3 dB boost at 80 Hz (sub-bass warmth). Makes the track feel heavy
26
+ # and warm without booming. width=2 octaves = wide, musical boost.
27
+ #
28
+ # 5. equalizer=f=250:width_type=o:width=1.5:g=-1.5
29
+ # -1.5 dB cut at 250 Hz. Removes boxiness/muddiness that builds up
30
+ # after slowing + bass boost. Keeps the mix clear.
31
+ #
32
+ # 6. equalizer=f=6000:width_type=o:width=2:g=-6
33
+ # -6 dB shelf cut around 6 kHz. Tames presence/brightness further for
34
+ # that cassette-tape dull warmth lofi is known for.
35
+ #
36
+ # 7. aecho=0.7:0.8:18|36|54|72:0.5|0.35|0.2|0.1
37
+ # Multi-tap room reverb simulation:
38
+ # delays = 18|36|54|72 ms → early reflections (NOT echo — way too short)
39
+ # decays = 0.5|0.35|0.2|0.1 → each tap fades steeply = short reverb tail
40
+ # in=0.7, out=0.8 → keep it behind the dry signal
41
+ # This gives a small room / bathroom reverb feel, not a slapback echo.
42
+ #
43
+ # 8. volume=1.5
44
+ # All the cuts + reverb mix reduce level. Bring it back up so output
45
+ # isn't quieter than the input.
46
+ #
47
+ # Output: AAC 256 kbps M4A — transparent quality, 2x faster than MP3 encode
48
+ # ─────────────────────────────────────────────────────────────────────────────
49
+
50
  FILTER = (
51
+ "asetrate=37485,"
52
+ "aresample=44100,"
53
+ "lowpass=f=3500,"
54
+ "equalizer=f=80:width_type=o:width=2:g=3,"
55
+ "equalizer=f=250:width_type=o:width=1.5:g=-1.5,"
56
+ "equalizer=f=6000:width_type=o:width=2:g=-6,"
57
+ "aecho=0.7:0.8:18|36|54|72:0.5|0.35|0.2|0.1,"
58
+ "volume=1.5"
59
  )
60
 
61
  HTML = """<!DOCTYPE html>
 
66
  <title>Slowed + Reverb</title>
67
  <style>
68
  @import url('https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&display=swap');
 
69
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
 
 
 
 
 
 
 
 
 
 
 
70
  body {
71
+ background: #0a0a0f;
72
+ color: #e8e8f0;
73
  font-family: 'Space Mono', monospace;
74
  min-height: 100vh;
75
  display: flex;
 
81
  radial-gradient(ellipse 80% 50% at 50% -10%, rgba(124,109,250,0.15) 0%, transparent 60%),
82
  radial-gradient(ellipse 60% 40% at 80% 100%, rgba(250,109,196,0.08) 0%, transparent 60%);
83
  }
 
84
  h1 {
85
  font-size: clamp(1.6rem, 5vw, 2.4rem);
86
  font-weight: 700;
87
  letter-spacing: -0.02em;
88
  margin-bottom: 8px;
89
+ background: linear-gradient(135deg, #7c6dfa, #fa6dc4);
90
  -webkit-background-clip: text;
91
  -webkit-text-fill-color: transparent;
92
  background-clip: text;
93
  }
 
94
  .subtitle {
95
+ font-size: 0.7rem;
96
  color: #555570;
97
+ letter-spacing: 0.14em;
98
  text-transform: uppercase;
99
  margin-bottom: 48px;
100
  }
 
101
  .card {
102
+ background: #13131a;
103
+ border: 1px solid #2a2a3a;
104
  border-radius: 16px;
105
  padding: 32px;
106
  width: 100%;
107
  max-width: 480px;
108
  margin-bottom: 16px;
109
  }
 
110
  .card-label {
111
+ font-size: 0.62rem;
112
  letter-spacing: 0.15em;
113
  text-transform: uppercase;
114
  color: #555570;
115
  margin-bottom: 20px;
116
  }
 
117
  .file-drop {
118
+ border: 2px dashed #2a2a3a;
119
  border-radius: 10px;
120
  padding: 28px 20px;
121
  text-align: center;
 
124
  margin-bottom: 16px;
125
  position: relative;
126
  }
127
+ .file-drop:hover { border-color: #7c6dfa; background: rgba(124,109,250,0.04); }
128
  .file-drop input[type=file] {
129
  position: absolute; inset: 0; opacity: 0; cursor: pointer; width: 100%; height: 100%;
130
  }
131
  .file-drop .icon { font-size: 2rem; margin-bottom: 8px; }
132
+ .file-drop .hint { font-size: 0.72rem; color: #555570; }
133
+ .file-drop .filename { font-size: 0.78rem; color: #7c6dfa; margin-top: 6px; min-height: 18px; }
 
 
 
 
 
 
 
 
 
 
134
  input[type=text] {
135
  width: 100%;
136
  background: #0d0d14;
137
+ border: 1px solid #2a2a3a;
138
  border-radius: 8px;
139
+ color: #e8e8f0;
140
  font-family: inherit;
141
+ font-size: 0.78rem;
142
  padding: 12px 14px;
143
  outline: none;
144
  transition: border-color 0.2s;
145
  margin-bottom: 16px;
146
  }
147
+ input[type=text]:focus { border-color: #7c6dfa; }
148
  input[type=text]::placeholder { color: #33334a; }
 
149
  button[type=submit] {
150
  width: 100%;
151
+ background: linear-gradient(135deg, #7c6dfa, #fa6dc4);
152
  border: none;
153
  border-radius: 8px;
154
  color: #fff;
155
  font-family: inherit;
156
+ font-size: 0.78rem;
157
  font-weight: 700;
158
  letter-spacing: 0.08em;
159
  padding: 13px;
 
162
  }
163
  button[type=submit]:hover { opacity: 0.88; }
164
  button[type=submit]:active { transform: scale(0.98); }
 
165
  .info {
166
+ font-size: 0.62rem;
167
  color: #33334a;
168
  text-align: center;
169
+ margin-top: 20px;
170
  letter-spacing: 0.08em;
171
+ line-height: 2;
172
  }
173
+ .info span { color: #7c6dfa; }
174
  </style>
175
  </head>
176
  <body>
 
177
  <h1>⟁ SLOWED + REVERB</h1>
178
+ <p class="subtitle">lofi · pitched down · warm reverb · 256k aac</p>
179
 
 
180
  <div class="card">
181
  <div class="card-label">// Upload audio file</div>
182
  <form action="/slowed-reverb" method="post" enctype="multipart/form-data">
183
+ <div class="file-drop">
184
+ <input type="file" name="file" accept="audio/*"
185
+ onchange="this.parentElement.querySelector('.filename').textContent=this.files[0]?.name||''">
186
  <div class="icon">🎵</div>
187
+ <div class="hint">mp3 · wav · flac · ogg · m4a</div>
188
+ <div class="filename"></div>
189
  </div>
190
  <button type="submit">Process File →</button>
191
  </form>
192
  </div>
193
 
 
194
  <div class="card">
195
  <div class="card-label">// Or paste direct audio URL</div>
196
  <form action="/slowed-reverb-url" method="post">
 
199
  </form>
200
  </div>
201
 
202
+ <p class="info">
203
+ <span>85% speed</span> · lowpass 3.5kHz · lofi EQ · room reverb<br>
204
+ output: <span>AAC 256kbps M4A</span> · instant streaming
205
+ </p>
 
 
 
206
  </body>
207
  </html>"""
208
 
209
 
210
  def run_ffmpeg(inp: str, out: str):
 
211
  cmd = [
212
  "ffmpeg", "-y", "-i", inp,
213
  "-af", FILTER,
214
+ "-c:a", "aac",
215
+ "-b:a", "256k",
216
+ "-ar", "44100",
217
+ "-movflags", "+faststart",
218
  out
219
  ]
220
  result = subprocess.run(cmd, capture_output=True, text=True)
221
  if result.returncode != 0:
222
+ raise HTTPException(status_code=500, detail=f"ffmpeg error:\n{result.stderr[-3000:]}")
223
 
224
 
225
  def cleanup(*paths: str):
 
226
  for p in paths:
227
  try:
228
  os.remove(p)
 
241
  uid = uuid.uuid4()
242
  inp = os.path.join(TMP, f"{uid}_in{ext}")
243
  out = os.path.join(TMP, f"{uid}_out.m4a")
 
244
  with open(inp, "wb") as f:
245
  shutil.copyfileobj(file.file, f)
 
246
  run_ffmpeg(inp, out)
 
247
  background_tasks.add_task(cleanup, inp, out)
248
  return FileResponse(out, media_type="audio/mp4", filename="slowed_reverb.m4a")
249
 
250
 
251
  @app.post("/slowed-reverb-url")
252
  def slowed_reverb_url(background_tasks: BackgroundTasks, url: str = Form(...)):
253
+ ext = os.path.splitext(url.split("?")[0])[1] or ".mp3"
254
  uid = uuid.uuid4()
255
  inp = os.path.join(TMP, f"{uid}_in{ext}")
256
  out = os.path.join(TMP, f"{uid}_out.m4a")
 
257
  try:
258
  r = requests.get(url, stream=True, timeout=30)
259
  r.raise_for_status()
260
  except requests.RequestException as e:
261
  raise HTTPException(status_code=400, detail=f"Failed to fetch URL: {e}")
 
262
  with open(inp, "wb") as f:
263
+ for chunk in r.iter_content(chunk_size=65536):
264
  f.write(chunk)
 
265
  run_ffmpeg(inp, out)
 
266
  background_tasks.add_task(cleanup, inp, out)
267
  return FileResponse(out, media_type="audio/mp4", filename="slowed_reverb.m4a")