-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
392 lines (329 loc) · 14.1 KB
/
app.py
File metadata and controls
392 lines (329 loc) · 14.1 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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
"""
app.py — Flask application: routes only.
All heavy logic lives in config.py, ffmpeg.py, vad.py, and jobs.py.
"""
import json
import platform
import queue
import subprocess
import sys
import threading
import uuid
import webbrowser
from pathlib import Path
from threading import Timer
from flask import Flask, Response, after_this_request, jsonify, render_template, request, send_file
from config import ALLOWED_EXTENSIONS, BUNDLE_DIR, DATA_DIR, MAX_UPLOAD_SIZE, TEMP_FOLDER
from ffmpeg import extract_audio, get_duration, get_fps
from jobs import (
compute_stats,
file_sessions,
job_logs,
jobs,
parse_params,
process_job,
purge_output,
)
from vad import detect_speech, DEVICE
# ── App setup ─────────────────────────────────────────────────────────────────
app = Flask(
__name__,
template_folder=str(BUNDLE_DIR / "static"),
static_folder=str(BUNDLE_DIR / "static"),
)
app.config["MAX_CONTENT_LENGTH"] = MAX_UPLOAD_SIZE
# One lock to serialise preview requests (VAD is memory-heavy)
_preview_lock = threading.Lock()
# ── Startup cleanup ───────────────────────────────────────────────────────────
def _cleanup_temp_folder():
"""Clear all files in temp folder on app launch."""
try:
if TEMP_FOLDER.exists():
for item in TEMP_FOLDER.iterdir():
if item.is_file():
try:
item.unlink()
except OSError:
pass
print(f"[startup] cleaned temp folder", flush=True)
except Exception as e:
print(f"[startup] temp cleanup error: {e}", flush=True)
_cleanup_temp_folder()
# ── Routes ────────────────────────────────────────────────────────────────────
@app.route("/")
def index():
return render_template("index.html")
@app.route("/api/browse")
def api_browse():
"""Open a native OS file-picker dialog and return the chosen path."""
exts_glob = " ".join(f"*{e}" for e in ALLOWED_EXTENSIONS)
script = (
"import tkinter as tk; from tkinter import filedialog; "
"root = tk.Tk(); root.withdraw(); root.wm_attributes('-topmost', 1); "
f"f = filedialog.askopenfilename(title='Select video', "
f"filetypes=[('Video files', '{exts_glob}'), ('All files', '*.*')]); "
"print(f, end='')"
)
try:
result = subprocess.run(
[sys.executable, "-c", script],
capture_output=True, text=True, timeout=120,
)
path = result.stdout.strip()
if not path:
return jsonify({"cancelled": True})
return jsonify({"path": path})
except subprocess.TimeoutExpired:
return jsonify({"cancelled": True})
except Exception as e:
print(f"[browse] error: {e}", flush=True)
return jsonify({"error": str(e)}), 500
@app.route("/api/register", methods=["POST"])
def api_register():
"""Register a local file by path — zero-copy, no upload."""
body = request.get_json(force=True)
file_path = body.get("path", "").strip().strip('"').strip("'")
print(f"[register] path={file_path}", flush=True)
if not file_path:
return jsonify({"error": "No path provided"}), 400
p = Path(file_path)
if not p.exists() or not p.is_file():
return jsonify({"error": f"File not found: {file_path}"}), 404
if p.suffix.lower() not in ALLOWED_EXTENSIONS:
return jsonify({"error": f"Unsupported format: {p.suffix}"}), 400
file_id = str(uuid.uuid4())[:8]
audio_path = str(DATA_DIR / "temp" / f"{file_id}.wav")
print(f"[register] file_id={file_id} audio_path={audio_path}", flush=True)
try:
print(f"[register] getting duration...", flush=True)
duration = get_duration(str(p))
fps = get_fps(str(p))
print(f"[register] duration={duration}, fps={fps}, extracting audio...", flush=True)
extract_audio(str(p), audio_path)
print(f"[register] audio extracted ok", flush=True)
except Exception as e:
import traceback
print(f"[register] ERROR: {e}", flush=True)
traceback.print_exc()
return jsonify({"error": str(e)}), 500
file_sessions[file_id] = {
"video_path": str(p),
"audio_path": audio_path,
"duration": duration,
"fps": fps,
"filename": p.name,
}
print(f"[register] ✓ registered file_id={file_id} ({p.name}) — total files in session: {len(file_sessions)}", flush=True)
return jsonify({
"file_id": file_id,
"duration": round(duration, 2),
"fps": round(fps, 2),
"filename": p.name,
"size": p.stat().st_size,
})
@app.route("/api/video/<file_id>")
def api_video(file_id: str):
"""Stream the registered video with range-request support for seeking."""
sess = file_sessions.get(file_id)
if not sess:
return jsonify({"error": "Unknown file_id"}), 404
video_path = Path(sess["video_path"])
if not video_path.exists():
return jsonify({"error": "File not found"}), 404
file_size = video_path.stat().st_size
mime_map = {
".mp4": "video/mp4", ".mkv": "video/x-matroska",
".mov": "video/quicktime", ".avi": "video/x-msvideo",
".webm": "video/webm", ".m4v": "video/mp4", ".flv": "video/x-flv",
}
mime = mime_map.get(video_path.suffix.lower(), "video/mp4")
def stream(start: int, end: int):
with open(video_path, "rb") as f:
f.seek(start)
remaining = end - start + 1
while remaining > 0:
chunk = f.read(min(65536, remaining))
if not chunk:
break
remaining -= len(chunk)
yield chunk
range_header = request.headers.get("Range")
if range_header:
start_str, _, end_str = range_header.strip().split("=")[1].partition("-")
start = int(start_str) if start_str else 0
end = int(end_str) if end_str else file_size - 1
end = min(end, file_size - 1)
return Response(
stream(start, end), status=206,
headers={
"Content-Range": f"bytes {start}-{end}/{file_size}",
"Accept-Ranges": "bytes",
"Content-Length": str(end - start + 1),
"Content-Type": mime,
},
)
return Response(
stream(0, file_size - 1), status=200,
headers={
"Content-Length": str(file_size),
"Accept-Ranges": "bytes",
"Content-Type": mime,
},
)
@app.route("/api/audio/<file_id>")
def api_audio(file_id: str):
"""Serve the extracted WAV for client-side waveform rendering."""
sess = file_sessions.get(file_id)
if not sess:
return jsonify({"error": "Unknown file_id"}), 404
audio_path = Path(sess["audio_path"])
if not audio_path.exists():
return jsonify({"error": "Audio file not found"}), 404
file_size = audio_path.stat().st_size
print(f"[audio] serving {audio_path.name} size={file_size}", flush=True)
def stream():
with open(audio_path, "rb") as f:
while True:
chunk = f.read(65536)
if not chunk:
break
yield chunk
return Response(
stream(),
status=200,
headers={
"Content-Type": "audio/wav",
"Content-Length": str(file_size),
"Cache-Control": "no-store",
"Accept-Ranges": "none",
},
)
@app.route("/api/preview", methods=["POST"])
def api_preview():
"""Run VAD preview (returns segment stats, no video encoding)."""
body = request.get_json(force=True)
file_id = body.get("file_id")
print(f"[preview] ========== PREVIEW REQUEST START ==========", flush=True)
print(f"[preview] request body: {body}", flush=True)
print(f"[preview] file_id={file_id}", flush=True)
print(f"[preview] registered file_ids: {list(file_sessions.keys())} (count={len(file_sessions)})", flush=True)
if not file_id or file_id not in file_sessions:
print(f"[preview] ERROR: unknown file_id or not in sessions", flush=True)
print(f"[preview] CRITICAL: file_id='{file_id}' not found in file_sessions", flush=True)
print(f"[preview] available file_ids: {list(file_sessions.keys())}", flush=True)
if file_sessions:
for fid in file_sessions:
print(f"[preview] - {fid}: {file_sessions[fid].get('filename')}", flush=True)
else:
print(f"[preview] file_sessions is EMPTY - no files registered!", flush=True)
return jsonify({"error": "Unknown file_id"}), 404
print(f"[preview] attempting to acquire lock (non-blocking)...", flush=True)
lock_acquired = _preview_lock.acquire(blocking=False)
print(f"[preview] lock acquisition result: {lock_acquired}", flush=True)
if not lock_acquired:
print(f"[preview] ERROR: lock already held (busy), returning 429", flush=True)
return jsonify({"error": "busy"}), 429
sess = file_sessions[file_id]
print(f"[preview] session data: {sess}", flush=True)
# Check if audio file exists
audio_file = Path(sess["audio_path"])
if not audio_file.exists():
print(f"[preview] ERROR: audio file missing at {audio_file}", flush=True)
_preview_lock.release()
return jsonify({"error": "Audio file not found"}), 500
print(f"[preview] audio file found: {audio_file.stat().st_size} bytes", flush=True)
try:
p = parse_params(body)
print(f"[preview] parsed params: {p}", flush=True)
vad_kw = {k: v for k, v in p.items() if k != "label"}
print(f"[preview] running VAD with params: {vad_kw}", flush=True)
segments = detect_speech(sess["audio_path"], **vad_kw)
print(f"[preview] VAD complete — {len(segments)} segments found", flush=True)
stats = compute_stats(segments, sess["duration"])
print(f"[preview] stats computed: {stats}", flush=True)
print(f"[preview] ========== PREVIEW SUCCESS ==========", flush=True)
return jsonify({"ok": True, "stats": stats})
except Exception as e:
import traceback
print(f"[preview] ERROR: {e}", flush=True)
traceback.print_exc()
print(f"[preview] ========== PREVIEW FAILED ==========", flush=True)
return jsonify({"error": str(e)}), 500
finally:
_preview_lock.release()
print(f"[preview] lock released", flush=True)
@app.route("/api/process", methods=["POST"])
def api_process():
"""Start a full encode job in a background thread."""
body = request.get_json(force=True)
file_id = body.get("file_id")
print(f"[process] request file_id={file_id}", flush=True)
if not file_id or file_id not in file_sessions:
return jsonify({"error": "Unknown file_id"}), 404
params = parse_params(body)
job_id = str(uuid.uuid4())[:8]
print(f"[process] created job_id={job_id} params={params}", flush=True)
jobs[job_id] = {"status": "queued", "progress": 0, "label": params["label"], "file_id": file_id}
job_logs[job_id] = queue.Queue()
threading.Thread(target=process_job, args=(job_id, file_id, params), daemon=True).start()
return jsonify({"job_id": job_id})
@app.route("/api/status/<job_id>")
def api_status(job_id: str):
job = jobs.get(job_id)
if not job:
return jsonify({"error": "Unknown job"}), 404
return jsonify(job)
@app.route("/api/logs/<job_id>")
def api_logs(job_id: str):
"""Server-Sent Events stream of job log messages."""
if job_id not in job_logs:
return jsonify({"error": "Unknown job"}), 404
def generate():
q = job_logs[job_id]
while True:
try:
item = q.get(timeout=30)
if item is None:
yield 'data: {"done":true}\n\n'
break
yield f"data: {json.dumps(item)}\n\n"
except queue.Empty:
yield ": heartbeat\n\n"
return Response(
generate(),
mimetype="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)
@app.route("/api/download/<job_id>")
def api_download(job_id: str):
job = jobs.get(job_id)
if not job or job.get("status") != "done":
return jsonify({"error": "Not ready"}), 404
output_path = DATA_DIR / "outputs" / job["output_filename"]
if not output_path.exists():
return jsonify({"error": "File missing"}), 404
sess = file_sessions.get(job.get("file_id", ""), {})
orig_stem = Path(sess.get("filename", "sliced.mp4")).stem
label = job.get("label", "sliced")
print(f"[download] job_id={job_id} file={output_path}", flush=True)
@after_this_request
def cleanup(response):
purge_output(output_path)
# Clean up session data from memory
file_sessions.pop(job.get("file_id", ""), None)
jobs.pop(job_id, None)
job_logs.pop(job_id, None)
return response
return send_file(str(output_path), as_attachment=True, download_name=f"{orig_stem}_{label}.mp4")
# ── Entry point ───────────────────────────────────────────────────────────────
PORT = 5001
if __name__ == "__main__":
print(f"\n Chaotics Slice ✂ http://127.0.0.1:{PORT} [{DEVICE.upper()}]\n")
def _open_browser():
if platform.system() in ("Windows", "Darwin"):
webbrowser.open(f"http://127.0.0.1:{PORT}")
else:
print(f" Open http://127.0.0.1:{PORT} in your browser")
Timer(1.5, _open_browser).start()
from waitress import serve
serve(app, host="127.0.0.1", port=PORT, threads=8, channel_timeout=300)