FlightSimulator101 commited on
Commit
0881b1b
·
verified ·
1 Parent(s): a6e8b1f

Update server.py

Browse files
Files changed (1) hide show
  1. server.py +167 -18
server.py CHANGED
@@ -1,34 +1,183 @@
1
  from fastapi import FastAPI, UploadFile, File
2
  from fastapi.responses import JSONResponse
 
 
 
 
3
 
4
  app = FastAPI()
5
 
 
 
 
 
 
6
 
7
  @app.api_route("/ping", methods=["GET", "HEAD"])
8
  async def ping():
9
  """
10
- Health check for uptime monitors.
11
- Accepts GET and HEAD so services like UptimeRobot don't get 405.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  """
13
- return {"status": "alive", "backend": "minimal"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
 
16
  @app.post("/analyze_piano")
17
  async def analyze_piano(audio: UploadFile = File(...)):
18
  """
19
- TEMP VERSION: accepts an audio file but does not do real AI yet.
20
- This is just so the Android app & networking work end-to-end.
21
-
22
- Later we will plug in piano-only AI logic here.
23
  """
24
- # Read the uploaded audio (we ignore it for now)
25
- _ = await audio.read()
26
-
27
- # Dummy result just so your app sees something real
28
- return JSONResponse({
29
- "has_piano": True,
30
- "chord_root": "C",
31
- "chord_quality": "major", # or "minor"
32
- "nashville": "I",
33
- "key": "C"
34
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from fastapi import FastAPI, UploadFile, File
2
  from fastapi.responses import JSONResponse
3
+ import tempfile
4
+ import os
5
+ import numpy as np
6
+ import librosa
7
 
8
  app = FastAPI()
9
 
10
+ NOTE_NAMES = [
11
+ "C", "C#", "D", "D#", "E", "F",
12
+ "F#", "G", "G#", "A", "A#", "B"
13
+ ]
14
+
15
 
16
  @app.api_route("/ping", methods=["GET", "HEAD"])
17
  async def ping():
18
  """
19
+ Health check for uptime monitors and the app.
20
+ """
21
+ return {"status": "alive", "backend": "librosa-analyzer"}
22
+
23
+
24
+ def freq_to_pc(freq: float):
25
+ """Convert freq (Hz) to pitch class 0..11 (C..B)."""
26
+ if freq <= 0:
27
+ return None
28
+ midi = 69 + 12 * np.log2(freq / 440.0)
29
+ mround = int(np.round(midi))
30
+ # A0..C8 (piano range)
31
+ if mround < 21 or mround > 108:
32
+ return None
33
+ return mround % 12
34
+
35
+
36
+ def interval_to_nashville(interval: int, quality: str) -> str:
37
+ if interval == 0:
38
+ return "i" if quality == "minor" else "I"
39
+ elif interval == 2:
40
+ return "ii" if quality == "minor" else "II"
41
+ elif interval == 4:
42
+ return "iii" if quality == "minor" else "III"
43
+ elif interval == 5:
44
+ return "iv" if quality == "minor" else "IV"
45
+ elif interval == 7:
46
+ return "v" if quality == "minor" else "V"
47
+ elif interval == 9:
48
+ return "vi" if quality == "minor" else "VI"
49
+ elif interval == 11:
50
+ return "vii°" if quality == "minor" else "VII°"
51
+ else:
52
+ return "?"
53
+
54
+
55
+ def detect_chord_and_key_from_pcs(pitch_classes):
56
+ """
57
+ Given list of pitch classes (0..11), guess chord (major/minor) and key.
58
  """
59
+ if len(pitch_classes) == 0:
60
+ return None, None, None, None
61
+
62
+ # Histogram of pitch classes
63
+ hist = np.zeros(12, dtype=int)
64
+ for pc in pitch_classes:
65
+ hist[pc % 12] += 1
66
+
67
+ # Simple major-key profile: I, ii, iii, IV, V, vi, vii°
68
+ major_degrees = np.array([0, 2, 4, 5, 7, 9, 11])
69
+ best_key = -1
70
+ best_score = -1
71
+ for root in range(12):
72
+ score = hist[(root + major_degrees) % 12].sum()
73
+ if score > best_score:
74
+ best_score = score
75
+ best_key = root
76
+
77
+ if best_score <= 0:
78
+ # Fallback: just use last pitch class
79
+ best_key = pitch_classes[-1]
80
+
81
+ key_pc = best_key % 12
82
+ key_name = NOTE_NAMES[key_pc]
83
+
84
+ # Chord detection
85
+ unique_pcs = sorted(list(set(pitch_classes)))
86
+ if len(unique_pcs) < 2:
87
+ root_pc = unique_pcs[-1]
88
+ return root_pc, "major", "I", key_name
89
+
90
+ chosen_root = None
91
+ chosen_quality = None
92
+ for root in unique_pcs:
93
+ intervals = sorted([(pc - root) % 12 for pc in unique_pcs])
94
+ is_major = (4 in intervals) and (7 in intervals)
95
+ is_minor = (3 in intervals) and (7 in intervals)
96
+ if is_major:
97
+ chosen_root = root
98
+ chosen_quality = "major"
99
+ break
100
+ if is_minor:
101
+ chosen_root = root
102
+ chosen_quality = "minor"
103
+ break
104
+
105
+ if chosen_root is None:
106
+ # fallback: treat as major on last PC
107
+ chosen_root = unique_pcs[-1]
108
+ chosen_quality = "major"
109
+
110
+ interval = (chosen_root - key_pc) % 12
111
+ nashville = interval_to_nashville(interval, chosen_quality)
112
+
113
+ return chosen_root, chosen_quality, nashville, key_name
114
 
115
 
116
  @app.post("/analyze_piano")
117
  async def analyze_piano(audio: UploadFile = File(...)):
118
  """
119
+ Accepts a short audio snippet (0.5–2s), estimates pitches using librosa,
120
+ and returns a rough chord + key guess.
 
 
121
  """
122
+ # Save uploaded file to a temp WAV
123
+ with tempfile.TemporaryDirectory() as tmpdir:
124
+ in_path = os.path.join(tmpdir, "input.wav")
125
+
126
+ with open(in_path, "wb") as f:
127
+ f.write(await audio.read())
128
+
129
+ # Load audio, mono, 16k
130
+ try:
131
+ y, sr = librosa.load(in_path, sr=16000, mono=True)
132
+ except Exception as e:
133
+ return JSONResponse({
134
+ "has_piano": False,
135
+ "reason": f"Error loading audio: {e}"
136
+ })
137
+
138
+ # If too short, bail
139
+ if len(y) < 1600:
140
+ return JSONResponse({
141
+ "has_piano": False,
142
+ "reason": "Audio too short"
143
+ })
144
+
145
+ # Limit to ~2 seconds for speed
146
+ max_len = sr * 2
147
+ if len(y) > max_len:
148
+ y = y[:max_len]
149
+
150
+ # Pitch estimation using librosa.yin
151
+ f0 = librosa.yin(
152
+ y,
153
+ fmin=60.0,
154
+ fmax=1000.0,
155
+ sr=sr,
156
+ frame_length=1024,
157
+ hop_length=256
158
+ )
159
+
160
+ pcs = []
161
+ for freq in f0:
162
+ if np.isnan(freq) or freq <= 0:
163
+ continue
164
+ pc = freq_to_pc(float(freq))
165
+ if pc is not None:
166
+ pcs.append(pc)
167
+
168
+ if len(pcs) == 0:
169
+ return JSONResponse({
170
+ "has_piano": False,
171
+ "reason": "No stable pitches found"
172
+ })
173
+
174
+ root_pc, quality, nashville, key_name = detect_chord_and_key_from_pcs(pcs)
175
+ chord_root_name = NOTE_NAMES[root_pc] if root_pc is not None else None
176
+
177
+ return JSONResponse({
178
+ "has_piano": True,
179
+ "chord_root": chord_root_name,
180
+ "chord_quality": quality,
181
+ "nashville": nashville,
182
+ "key": key_name
183
+ })