-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.py
More file actions
317 lines (262 loc) · 9.91 KB
/
server.py
File metadata and controls
317 lines (262 loc) · 9.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
"""
Web server for Kyle's Optical Decoder.
Run: python server.py
Then open http://localhost:8000 in your browser.
This file is part of Kyle's Optical Decoder.
Copyright (C) 2026 Kyle Mikolajczyk
Kyle's Optical Decoder is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Kyle's Optical Decoder is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Kyle's Optical Decoder; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
import json
import os
import pathlib
import threading
import time
from fastapi import FastAPI, HTTPException, Query
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, Response, StreamingResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
import KylesOpticalDecoder as decoder
app = FastAPI(title="Kyle's Optical Decoder")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# ---------------------------------------------------------------------------
# State — currently loaded project
# ---------------------------------------------------------------------------
_state = {
"source": None,
}
# Extraction job state
_extract_job = {
"running": False,
"current": 0,
"total": 0,
"phase": "",
"done": False,
"error": None,
"wav_bytes": None,
}
# ---------------------------------------------------------------------------
# API routes
# ---------------------------------------------------------------------------
class LoadProjectRequest(BaseModel):
input_dir: str
class LoadProjectResponse(BaseModel):
num_frames: int
frame_width: int
frame_height: int
fps: float | None = None
@app.post("/api/load", response_model=LoadProjectResponse)
def load_project(req: LoadProjectRequest):
"""Point the server at a directory of frame images or a video file."""
try:
source = decoder.open_source(req.input_dir)
except ValueError as e:
raise HTTPException(400, str(e))
except RuntimeError as e:
raise HTTPException(500, str(e))
_state["source"] = source
return LoadProjectResponse(
num_frames=source.num_frames,
frame_width=source.frame_width,
frame_height=source.frame_height,
fps=source.fps,
)
@app.get("/api/frame/{index}/raw")
def get_raw_frame(index: int, rotate: int = Query(0)):
"""Return the raw (uncropped) frame as a JPEG for preview."""
_check_loaded()
source = _state["source"]
if index < 0 or index >= source.num_frames:
raise HTTPException(404, f"Frame index {index} out of range (0–{source.num_frames - 1})")
img = source.load_frame(index)
if img is None:
raise HTTPException(500, f"Could not read frame {index}")
img = decoder.rotate_image(img, rotate)
return Response(content=decoder.frame_to_jpeg(img), media_type="image/jpeg")
@app.get("/api/frame/{index}/corrected")
def get_corrected_frame(
index: int,
rotate: int = Query(0),
negative: bool = Query(False),
lift: float = Query(0.0),
gamma: float = Query(1.0),
gain: float = Query(1.0),
threshold: float = Query(0.0),
):
"""Return full frame with corrections applied (no crop), rotated, as JPEG."""
_check_loaded()
source = _state["source"]
if index < 0 or index >= source.num_frames:
raise HTTPException(404, f"Frame index {index} out of range (0–{source.num_frames - 1})")
img = source.load_frame(index)
if img is None:
raise HTTPException(500, f"Could not read frame {index}")
corrected = decoder.correct_full_frame(img, negative, lift, gamma, gain, threshold)
corrected = decoder.rotate_image(corrected, rotate)
return Response(content=decoder.corrected_to_jpeg(corrected), media_type="image/jpeg")
@app.get("/api/frame/{index}/preview")
def get_preview_frame(
index: int,
top: int = Query(0),
bottom: int = Query(0),
left: int = Query(0),
right: int = Query(0),
rotate: int = Query(0),
negative: bool = Query(False),
lift: float = Query(0.0),
gamma: float = Query(1.0),
gain: float = Query(1.0),
threshold: float = Query(0.0),
):
"""Return a cropped+corrected frame as JPEG (for live preview)."""
_check_loaded()
source = _state["source"]
if index < 0 or index >= source.num_frames:
raise HTTPException(404, f"Frame index {index} out of range (0–{source.num_frames - 1})")
img = source.load_frame(index)
if img is None:
raise HTTPException(500, f"Could not read frame {index}")
corrected = decoder.crop_and_correct(
img, top, bottom, left, right, rotate,
negative, lift, gamma, gain, threshold,
)
return Response(content=decoder.corrected_to_jpeg(corrected), media_type="image/jpeg")
class ExtractRequest(BaseModel):
top: int
bottom: int
left: int
right: int
rotate: int = 0
negative: bool = False
lift: float = 0.0
gamma: float = 1.0
gain: float = 1.0
threshold: float = 0.0
fps: float = 24.0
sample_rate: int = 48000
hpf: float = 40.0
lpf: float = 13500.0
overlap: float = 0.25
reverse: bool = False
stereo: bool = False
start_frame: int = 0
end_frame: int | None = None
@app.post("/api/extract")
def extract(req: ExtractRequest):
"""Start the extraction pipeline in a background thread."""
_check_loaded()
if _extract_job["running"]:
raise HTTPException(409, "Extraction already in progress")
source = _state["source"]
start = max(0, req.start_frame)
end = req.end_frame if req.end_frame is not None else source.num_frames - 1
end = min(end, source.num_frames - 1)
frame_count = end - start + 1
_extract_job["running"] = True
_extract_job["current"] = 0
_extract_job["total"] = frame_count
_extract_job["phase"] = "Processing frames"
_extract_job["done"] = False
_extract_job["error"] = None
_extract_job["wav_bytes"] = None
def _run():
try:
def progress_cb(current, total):
_extract_job["current"] = current
_extract_job["total"] = total
def phase_cb(phase):
_extract_job["phase"] = phase
wav_bytes = decoder.extract_audio_to_wav_bytes(
source,
top=req.top, bottom=req.bottom, left=req.left, right=req.right,
rotate=req.rotate, negative=req.negative, lift=req.lift,
gamma=req.gamma, gain=req.gain, threshold=req.threshold,
fps=req.fps, sample_rate=req.sample_rate,
hpf=req.hpf, lpf=req.lpf, overlap=req.overlap,
stereo=req.stereo, reverse=req.reverse,
start_frame=req.start_frame, end_frame=req.end_frame,
progress_callback=progress_cb,
phase_callback=phase_cb,
)
_extract_job["wav_bytes"] = wav_bytes
_extract_job["phase"] = "Complete"
except Exception as e:
_extract_job["error"] = str(e)
_extract_job["phase"] = "Error"
finally:
_extract_job["done"] = True
_extract_job["running"] = False
threading.Thread(target=_run, daemon=True).start()
return {"status": "started", "total": frame_count}
@app.get("/api/extract/progress")
def extract_progress():
"""SSE stream of extraction progress."""
def event_stream():
while True:
data = {
"current": _extract_job["current"],
"total": _extract_job["total"],
"phase": _extract_job["phase"],
"done": _extract_job["done"],
"error": _extract_job["error"],
}
yield f"data: {json.dumps(data)}\n\n"
if _extract_job["done"]:
break
time.sleep(0.3)
return StreamingResponse(
event_stream(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"X-Accel-Buffering": "no",
},
)
@app.get("/api/extract/result")
def extract_result():
"""Download the completed WAV file."""
if _extract_job["running"]:
raise HTTPException(409, "Extraction still in progress")
if _extract_job["error"]:
raise HTTPException(500, _extract_job["error"])
if _extract_job["wav_bytes"] is None:
raise HTTPException(404, "No extraction result available")
wav_bytes = _extract_job["wav_bytes"]
_extract_job["wav_bytes"] = None # free memory
return Response(
content=wav_bytes,
media_type="audio/wav",
headers={"Content-Disposition": "attachment; filename=output.wav"},
)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _check_loaded():
if _state["source"] is None:
raise HTTPException(400, "No project loaded. POST /api/load first.")
# ---------------------------------------------------------------------------
# Serve the React build (production) or just the API (development)
# ---------------------------------------------------------------------------
_frontend_dist = pathlib.Path(__file__).parent / "frontend" / "dist"
if _frontend_dist.is_dir():
# Serve React build artifacts
app.mount("/", StaticFiles(directory=str(_frontend_dist), html=True), name="frontend")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)