-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathapp.py
More file actions
1759 lines (1471 loc) · 60.8 KB
/
Copy pathapp.py
File metadata and controls
1759 lines (1471 loc) · 60.8 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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Upscale4K — AI-powered video upscaling server."""
import json
import os
import re
import secrets
import shutil
import sqlite3
import subprocess
import sys
import threading
import time
import uuid
from pathlib import Path
from urllib.parse import urlparse
from flask import Flask, Response, jsonify, render_template, request, send_file
import paths
VERSION = '1.2.0'
try:
import ai_engine
SERVER_AI = ai_engine.available()
except ImportError:
ai_engine = None
SERVER_AI = False
try:
import face_restore as _face_restore
FACE_RESTORE = SERVER_AI and _face_restore.available()
except Exception:
FACE_RESTORE = False
try:
import bg_remove
except Exception:
bg_remove = None
try:
import model_store
import restore_engine
except Exception as e:
print(f'[startup] restore tools unavailable: {e}', flush=True)
model_store = None
restore_engine = None
try:
import audio_engine
except Exception as e:
print(f'[startup] audio tools unavailable: {e}', flush=True)
audio_engine = None
try:
import video_tools
except Exception as e:
print(f'[startup] video tools unavailable: {e}', flush=True)
video_tools = None
def _find_bin(name):
"""Find a binary next to the packaged executable, in PATH, or in
common install locations."""
exe_name = name + '.exe' if sys.platform == 'win32' else name
if paths.EXE_DIR:
p = os.path.join(paths.EXE_DIR, exe_name)
if os.path.isfile(p):
return p
found = shutil.which(name)
if found:
return found
for d in ['/usr/local/bin', '/opt/homebrew/bin', '/opt/anaconda3/bin', '/usr/bin']:
p = os.path.join(d, name)
if os.path.isfile(p):
return p
return name
FFMPEG = _find_bin('ffmpeg')
FFPROBE = _find_bin('ffprobe')
def _bin_works(path):
try:
return subprocess.run([path, '-version'], capture_output=True,
timeout=8).returncode == 0
except Exception:
return False
FFMPEG_OK = _bin_works(FFMPEG)
if not FFMPEG_OK:
print(f'[startup] WARNING: ffmpeg not working at {FFMPEG} — '
'video and Quality-mode features will be unavailable', flush=True)
app = Flask(__name__,
template_folder=paths.resource('templates'),
static_folder=paths.resource('static'))
app.config['UPLOAD_FOLDER'] = paths.data('uploads')
app.config['OUTPUT_FOLDER'] = paths.data('outputs')
app.config['FRAMES_FOLDER'] = paths.data('frames')
app.config['MAX_CONTENT_LENGTH'] = 2 * 1024 * 1024 * 1024 # 2GB
tasks = {}
# Live subprocess handles per task, so cancel can kill them (not persisted)
_procs = {}
# Per-session token for file-writing endpoints. It is embedded in the page,
# so only same-origin scripts can read it, and it travels in a custom header,
# which forces a CORS preflight — a cross-origin page (e.g. a malicious
# website poking at localhost) can neither obtain nor send it.
API_TOKEN = secrets.token_hex(32)
class TaskCancelled(Exception):
pass
TASK_ID_RE = re.compile(r'^[a-z0-9_]{1,40}$')
DB_PATH = paths.data('tasks.db')
def _safe_task_id(task_id):
"""Validate task_id format to prevent path traversal in disk lookups."""
return bool(TASK_ID_RE.fullmatch(task_id))
# --- Task persistence (SQLite) ---
def _db():
conn = sqlite3.connect(DB_PATH)
conn.execute(
'CREATE TABLE IF NOT EXISTS tasks '
'(task_id TEXT PRIMARY KEY, data TEXT, updated REAL)'
)
return conn
def save_task(task_id):
"""Persist a task's JSON-serializable fields so it survives restarts."""
task = tasks.get(task_id)
if not task:
return
data = json.dumps({
k: v for k, v in task.items()
if isinstance(v, (str, int, float, bool, list, dict, type(None)))
})
try:
with _db() as conn:
conn.execute(
'INSERT OR REPLACE INTO tasks VALUES (?, ?, ?)',
(task_id, data, time.time()),
)
except Exception as e:
print(f'[db] save failed for {task_id}: {e}', flush=True)
def delete_task(task_id):
tasks.pop(task_id, None)
try:
with _db() as conn:
conn.execute('DELETE FROM tasks WHERE task_id = ?', (task_id,))
except Exception:
pass
def load_tasks():
try:
with _db() as conn:
for tid, data in conn.execute('SELECT task_id, data FROM tasks'):
try:
task = json.loads(data)
except ValueError:
continue
# Anything mid-flight when the server died can't resume
if task.get('status') in ('processing', 'pro_processing'):
task['status'] = 'error'
task['message'] = 'Interrupted by server restart'
tasks[tid] = task
print(f'[db] loaded {len(tasks)} task(s)', flush=True)
except Exception as e:
print(f'[db] load failed: {e}', flush=True)
# --- Auto-cleanup of old files ---
CLEANUP_HOURS = float(os.environ.get('CLEANUP_HOURS', 24))
def _cleanup_loop():
while True:
cutoff = time.time() - CLEANUP_HOURS * 3600
for folder in (app.config['UPLOAD_FOLDER'], app.config['OUTPUT_FOLDER'],
app.config['FRAMES_FOLDER']):
try:
for entry in os.scandir(folder):
if entry.stat().st_mtime < cutoff:
if entry.is_dir():
shutil.rmtree(entry.path, ignore_errors=True)
else:
os.remove(entry.path)
except OSError:
pass
try:
with _db() as conn:
old = [r[0] for r in conn.execute(
'SELECT task_id FROM tasks WHERE updated < ?', (cutoff,))]
for tid in old:
delete_task(tid)
except Exception:
pass
time.sleep(3600)
@app.route('/')
def index():
model_exists = paths.find_model('realesr-general-x4v3.onnx') is not None
return render_template('index.html', model_available=model_exists,
server_ai=SERVER_AI, face_restore=FACE_RESTORE,
api_token=API_TOKEN)
@app.route('/llms.txt')
def llms_txt():
path = paths.resource('llms.txt')
if os.path.exists(path):
return send_file(path, mimetype='text/plain')
return jsonify({'error': 'Not found'}), 404
@app.route('/api/capabilities')
def capabilities():
return jsonify({'server_ai': SERVER_AI, 'face_restore': FACE_RESTORE,
'ffmpeg': FFMPEG_OK, 'version': VERSION,
'bg_remove': bool(bg_remove and bg_remove.available())})
# Domains the About dialog may open in the system browser. The desktop
# webview can't open external links itself, so it asks the local server.
OPEN_ALLOWED = {'matily.org', 'www.matily.org', 'github.com'}
@app.route('/api/open', methods=['POST'])
def open_external():
import webbrowser
url = (request.json or {}).get('url', '')
parsed = urlparse(url)
if parsed.scheme != 'https' or parsed.hostname not in OPEN_ALLOWED:
return jsonify({'error': 'URL not allowed'}), 400
# Local connection + session token; remote LAN users have a real
# browser and don't need (or want) links opening on the server.
if not _write_authorized():
return jsonify({'error': 'Not authorized'}), 403
webbrowser.open(url)
return jsonify({'status': 'ok'})
def _local_only():
return request.remote_addr in ('127.0.0.1', '::1')
def _origin_ok(origin):
"""Accept only our own page (any localhost origin) or the Tauri webview."""
if origin in ('tauri://localhost', 'https://tauri.localhost',
'http://tauri.localhost'):
return True
parsed = urlparse(origin)
return parsed.scheme in ('http', 'https') and \
parsed.hostname in ('127.0.0.1', 'localhost', '::1')
def _write_authorized():
"""Guard for endpoints that write to user-chosen paths or open URLs:
local connection + the page's session token + a sane Origin. A localhost
connection alone is not proof the USER asked — a malicious website could
fire cross-origin requests at 127.0.0.1 (GitHub issue #2)."""
if not _local_only():
return False
if request.headers.get('X-NGU-Token') != API_TOKEN:
return False
origin = request.headers.get('Origin')
if origin and not _origin_ok(origin):
return False
return True
def _find_output(task_id):
"""Locate a finished task's output file, surviving server restarts."""
task = tasks.get(task_id)
if task and task.get('output') and os.path.exists(task['output']):
return task['output']
if _safe_task_id(task_id):
for suffix in ('_basic_4k.mp4', '_pro_4k.mp4', '_upscaled.png',
'_nobg.png', '_clean.png', '_restored.png',
'_erased.png', '.zip', '.wav', '_denoised.wav',
'.mp4', '.gif'):
p = os.path.join(app.config['OUTPUT_FOLDER'], task_id + suffix)
if os.path.exists(p):
return p
return None
@app.route('/api/save', methods=['POST'])
def save_to_path():
"""Copy a finished result to a user-chosen absolute path. Used by the
desktop app after its native Save dialog (the webview has no download
manager). Local requests with the session token only."""
if not _write_authorized():
return jsonify({'error': 'Not authorized'}), 403
data = request.json or {}
task_id = data.get('task_id', '')
dest = data.get('path', '')
src = _find_output(task_id)
if not src:
return jsonify({'error': 'Result not found'}), 404
if not os.path.isabs(dest) or not os.path.isdir(os.path.dirname(dest)):
return jsonify({'error': 'Invalid destination path'}), 400
try:
shutil.copyfile(src, dest)
return jsonify({'status': 'ok', 'path': dest})
except OSError as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/save-blob', methods=['POST'])
def save_blob():
"""Write posted bytes (browser-side results: Quick/Enhance images,
batch zips) to a user-chosen absolute path. Local requests with the
session token only."""
if not _write_authorized():
return jsonify({'error': 'Not authorized'}), 403
dest = request.args.get('path', '')
if not os.path.isabs(dest) or not os.path.isdir(os.path.dirname(dest)):
return jsonify({'error': 'Invalid destination path'}), 400
if not request.data:
return jsonify({'error': 'No data'}), 400
try:
with open(dest, 'wb') as f:
f.write(request.data)
return jsonify({'status': 'ok', 'path': dest})
except OSError as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/diag')
def diagnostics():
"""Environment report for bug triage."""
import platform as _pf
enc = _detect_encoder()
try:
ffv = subprocess.run([FFMPEG, '-version'], capture_output=True,
text=True, encoding='utf-8', errors='replace', timeout=8).stdout.splitlines()[0]
except Exception as e:
ffv = f'unavailable: {e}'
return jsonify({
'version': VERSION,
'platform': f'{_pf.system()} {_pf.release()} {_pf.machine()}',
'python': sys.version.split()[0],
'ffmpeg': ffv,
'encoder': enc,
'server_ai': SERVER_AI,
'face_restore': FACE_RESTORE,
'frozen': paths.FROZEN,
})
@app.route('/api/update-check')
def update_check():
"""Compare the running version against the newest GitHub release."""
import ssl
import urllib.request
try:
ctx = None
try:
import certifi
ctx = ssl.create_default_context(cafile=certifi.where())
except ImportError:
pass
req = urllib.request.Request(
'https://api.github.com/repos/riponcm/nextgenUp/releases/latest',
headers={'Accept': 'application/vnd.github+json',
'User-Agent': f'NextGenUp/{VERSION}'})
try:
with urllib.request.urlopen(req, timeout=6, context=ctx) as resp:
release = json.loads(resp.read())
except urllib.error.HTTPError as e:
if e.code == 404: # no releases published yet
return jsonify({'current': VERSION, 'latest': VERSION,
'update_available': False,
'url': 'https://github.com/riponcm/nextgenUp/releases'})
raise
latest = release.get('tag_name', '').lstrip('v')
if not latest:
return jsonify({'error': 'No release found'}), 502
def ver(v):
nums = re.findall(r'\d+', v)[:3]
return tuple(int(n) for n in nums) if nums else (0,)
return jsonify({
'current': VERSION,
'latest': latest,
'update_available': ver(latest) > ver(VERSION),
'url': release.get('html_url',
'https://github.com/riponcm/nextgenUp/releases/latest'),
})
except Exception:
return jsonify({'error': 'Could not reach GitHub'}), 502
@app.route('/api/upload', methods=['POST'])
def upload():
file = request.files.get('video')
if not file or not file.filename:
return jsonify({'error': 'No video file provided'}), 400
allowed = {'.mp4', '.mov', '.webm', '.mkv', '.avi'}
ext = Path(file.filename).suffix.lower()
if ext not in allowed:
return jsonify({'error': f'Unsupported format: {ext}'}), 400
task_id = uuid.uuid4().hex[:12]
safe_name = re.sub(r'[^\w.\-]', '_', file.filename)
filename = f"{task_id}_{safe_name}"
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
info = get_video_info(filepath)
if not info:
os.remove(filepath)
return jsonify({'error': 'Could not read video file'}), 400
tasks[task_id] = {
'status': 'uploaded',
'input': filepath,
'filename': file.filename,
'info': info,
'progress': 0,
'current_frame': 0,
'total_frames': int(info['duration'] * info['fps']),
'message': 'Ready',
}
save_task(task_id)
return jsonify({'task_id': task_id, 'info': info})
@app.route('/api/upscale/basic', methods=['POST'])
def upscale_basic():
data = request.json or {}
task_id = data.get('task_id')
scale = int(data.get('scale', 4))
task = tasks.get(task_id)
if not task:
return jsonify({'error': 'Task not found'}), 404
task['status'] = 'processing'
task['progress'] = 0
task['message'] = 'Starting FFmpeg...'
thread = threading.Thread(target=_run_basic_upscale, args=(task_id, scale), daemon=True)
thread.start()
return jsonify({'status': 'processing'})
@app.route('/api/progress/<task_id>')
def progress(task_id):
def generate():
while True:
task = tasks.get(task_id)
if not task:
yield f"data: {json.dumps({'status': 'error', 'message': 'Task not found'})}\n\n"
break
yield f"data: {json.dumps({k: task[k] for k in ('status', 'progress', 'message', 'current_frame', 'total_frames')})}\n\n"
if task['status'] in ('completed', 'error', 'cancelled'):
break
time.sleep(0.5)
return Response(generate(), mimetype='text/event-stream',
headers={'Cache-Control': 'no-cache', 'X-Accel-Buffering': 'no'})
@app.route('/api/cancel/<task_id>', methods=['POST'])
@app.route('/api/image/cancel/<task_id>', methods=['POST'])
def cancel_task(task_id):
task = tasks.get(task_id)
if not task:
return jsonify({'error': 'Task not found'}), 404
task['cancel_requested'] = True
proc = _procs.get(task_id)
if proc and proc.poll() is None:
proc.kill()
return jsonify({'status': 'cancelling'})
@app.route('/api/download/<task_id>')
def download(task_id):
task = tasks.get(task_id)
if task and task.get('status') == 'completed':
output_path = task.get('output')
if output_path and os.path.exists(output_path):
stem = Path(task['filename']).stem
download_name = f"{stem}_4K.mp4"
return send_file(output_path, as_attachment=True, download_name=download_name)
# Fallback: task lost after server restart — find the file on disk
if _safe_task_id(task_id):
for suffix in ('_basic_4k.mp4', '_pro_4k.mp4'):
path = os.path.join(app.config['OUTPUT_FOLDER'], task_id + suffix)
if os.path.exists(path):
return send_file(path, as_attachment=True, download_name=f"{task_id}_4K.mp4")
return jsonify({'error': 'Not ready'}), 404
# --- Pro mode: receive upscaled frames from browser WebGPU ---
@app.route('/api/pro/start', methods=['POST'])
def pro_start():
data = request.json or {}
task_id = data.get('task_id')
task = tasks.get(task_id)
if not task:
return jsonify({'error': 'Task not found'}), 404
frames_dir = os.path.join(app.config['FRAMES_FOLDER'], task_id)
os.makedirs(frames_dir, exist_ok=True)
task['status'] = 'pro_processing'
task['progress'] = 0
task['message'] = 'Receiving upscaled frames...'
task['frames_dir'] = frames_dir
task['frames_received'] = 0
return jsonify({'status': 'ready'})
@app.route('/api/pro/frame/<task_id>/<int:frame_num>', methods=['POST'])
def pro_frame(task_id, frame_num):
task = tasks.get(task_id)
if not task:
return jsonify({'error': 'Task not found'}), 404
frames_dir = task.get('frames_dir')
if not frames_dir:
return jsonify({'error': 'Pro processing not started'}), 400
frame_data = request.data
if not frame_data:
return jsonify({'error': 'No frame data'}), 400
frame_path = os.path.join(frames_dir, f"frame_{frame_num:05d}.jpg")
with open(frame_path, 'wb') as f:
f.write(frame_data)
task['frames_received'] = frame_num + 1
total = task['total_frames']
task['progress'] = min(95, int((frame_num + 1) / total * 95))
task['current_frame'] = frame_num + 1
task['message'] = f'Frame {frame_num + 1}/{total}'
return jsonify({'status': 'ok'})
@app.route('/api/pro/assemble', methods=['POST'])
def pro_assemble():
data = request.json or {}
task_id = data.get('task_id')
fps = data.get('fps', 24)
task = tasks.get(task_id)
if not task:
return jsonify({'error': 'Task not found'}), 404
task['message'] = 'Assembling final video...'
task['progress'] = 96
thread = threading.Thread(target=_run_pro_assemble, args=(task_id, fps), daemon=True)
thread.start()
return jsonify({'status': 'assembling'})
# --- Image upscale endpoints ---
@app.route('/api/image/upload', methods=['POST'])
def image_upload():
file = request.files.get('image')
if not file or not file.filename:
return jsonify({'error': 'No image file provided'}), 400
allowed = {'.png', '.jpg', '.jpeg', '.webp', '.bmp', '.tiff', '.tif'}
ext = Path(file.filename).suffix.lower()
if ext not in allowed:
return jsonify({'error': f'Unsupported format: {ext}'}), 400
task_id = 'img_' + uuid.uuid4().hex[:12]
safe_name = re.sub(r'[^\w.\-]', '_', file.filename)
filename = f"{task_id}_{safe_name}"
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
# Get image dimensions using ffprobe
info = get_image_info(filepath)
if not info:
os.remove(filepath)
return jsonify({'error': 'Could not read image file'}), 400
tasks[task_id] = {
'status': 'uploaded',
'type': 'image',
'input': filepath,
'filename': file.filename,
'info': info,
'progress': 0,
'message': 'Ready',
}
save_task(task_id)
return jsonify({'task_id': task_id, 'info': info})
@app.route('/api/image/upscale', methods=['POST'])
def image_upscale():
data = request.json or {}
task_id = data.get('task_id')
scale = int(data.get('scale', 4))
mode = data.get('mode', 'ffmpeg') # ffmpeg | ai | ai-enhance
task = tasks.get(task_id)
if not task:
return jsonify({'error': 'Task not found'}), 404
if mode in ('ai', 'ai-enhance') and not SERVER_AI:
return jsonify({'error': 'Server AI not available on this host'}), 400
task['status'] = 'processing'
task['progress'] = 10
task['message'] = 'Starting upscale...'
if mode in ('ai', 'ai-enhance'):
face = bool(data.get('face_restore')) and FACE_RESTORE
target = _run_image_upscale_ai
args = (task_id, scale, mode == 'ai-enhance', face)
else:
target = _run_image_upscale
args = (task_id, scale)
thread = threading.Thread(target=target, args=args, daemon=True)
thread.start()
return jsonify({'status': 'processing'})
@app.route('/api/image/status/<task_id>')
def image_status(task_id):
task = tasks.get(task_id)
if not task:
return jsonify({'error': 'Task not found'}), 404
result = {k: task.get(k) for k in ('status', 'progress', 'message')}
if task.get('output_width'):
result['output_width'] = task['output_width']
result['output_height'] = task['output_height']
return jsonify(result)
@app.route('/api/image/download/<task_id>')
def image_download(task_id):
task = tasks.get(task_id)
if task and task.get('status') == 'completed':
output_path = task.get('output')
if output_path and os.path.exists(output_path):
stem = Path(task['filename']).stem
download_name = f"{stem}{task.get('name_suffix', '_upscaled')}.png"
return send_file(output_path, as_attachment=True, download_name=download_name)
# Fallback: find file on disk after server restart
if _safe_task_id(task_id):
for suffix in ('_upscaled.png', '_nobg.png', '_clean.png',
'_restored.png', '_erased.png'):
path = os.path.join(app.config['OUTPUT_FOLDER'], task_id + suffix)
if os.path.exists(path):
return send_file(path, as_attachment=True, download_name=task_id + suffix)
return jsonify({'error': 'Not ready'}), 404
# --- Restore tools: model management + denoise/deblur, colorize, erase ---
@app.route('/api/models/<key>', methods=['GET', 'POST'])
def models_endpoint(key):
"""GET: availability / download progress. POST: start download."""
if not model_store or not model_store.valid(key):
return jsonify({'error': 'Unknown model'}), 404
if request.method == 'POST':
model_store.start_download(key)
return jsonify(model_store.status(key))
def _start_tool_thread(task_id, runner, *args):
task = tasks[task_id]
task['status'] = 'processing'
task['progress'] = 10
task['message'] = 'Starting...'
threading.Thread(target=runner, args=(task_id,) + args, daemon=True).start()
return jsonify({'status': 'processing'})
def _finish_tool_task(task_id, output_path, suffix, size):
task = tasks[task_id]
task['status'] = 'completed'
task['progress'] = 100
task['output'] = output_path
task['name_suffix'] = suffix
task['message'] = 'Done!'
task['output_width'], task['output_height'] = size
@app.route('/api/clean', methods=['POST'])
def clean_start():
data = request.json or {}
task_id = data.get('task_id')
mode = data.get('mode', 'denoise')
task = tasks.get(task_id)
if not task:
return jsonify({'error': 'Task not found'}), 404
if mode not in ('denoise', 'deblur'):
return jsonify({'error': 'Invalid mode'}), 400
if not (model_store and model_store.available(mode)):
return jsonify({'error': 'Model not installed'}), 400
return _start_tool_thread(task_id, _run_clean, mode)
def _run_clean(task_id, mode):
task = tasks[task_id]
output_path = os.path.join(app.config['OUTPUT_FOLDER'], f'{task_id}_clean.png')
verb = 'Denoising' if mode == 'denoise' else 'Deblurring'
def on_tile(done, total):
if task.get('cancel_requested'):
raise TaskCancelled()
task['progress'] = min(95, 10 + int(done / total * 85))
task['message'] = f'{verb} tile {done}/{total}'
try:
task['message'] = f'{verb} on server...'
size = restore_engine.clean_image(mode, task['input'], output_path,
progress_cb=on_tile)
_finish_tool_task(task_id, output_path, '_clean', size)
except TaskCancelled:
task['status'] = 'cancelled'
task['message'] = 'Cancelled'
except Exception as e:
print(f'[clean] error: {e}', flush=True)
task['status'] = 'error'
task['message'] = f'{verb} error: {str(e)[:200]}'
save_task(task_id)
@app.route('/api/restore', methods=['POST'])
def restore_start():
data = request.json or {}
task_id = data.get('task_id')
task = tasks.get(task_id)
if not task:
return jsonify({'error': 'Task not found'}), 404
colorize = bool(data.get('colorize'))
face = bool(data.get('face')) and FACE_RESTORE
enhance = bool(data.get('enhance')) and SERVER_AI
if colorize and not (model_store and model_store.available('colorize')):
return jsonify({'error': 'Colorization model not installed'}), 400
if not (colorize or face or enhance):
return jsonify({'error': 'Pick at least one restore option'}), 400
return _start_tool_thread(task_id, _run_restore, colorize, face, enhance)
def _run_restore(task_id, colorize, face, enhance):
task = tasks[task_id]
output_path = os.path.join(app.config['OUTPUT_FOLDER'], f'{task_id}_restored.png')
def check_cancel():
if task.get('cancel_requested'):
raise TaskCancelled()
def on_progress(pct, msg):
check_cancel()
task['progress'] = pct
task['message'] = msg
try:
working = task['input']
# Stage 1: detail enhancement (Real-ESRGAN at original size),
# with GFPGAN folded in when faces are requested
if enhance:
def on_tile(done, total):
check_cancel()
task['progress'] = min(60, 10 + int(done / total * 50))
task['message'] = f'Enhancing detail (tile {done}/{total})'
ai_engine.enhance_image(working, output_path,
progress_cb=on_tile, face_restore=face)
working = output_path
elif face:
on_progress(25, 'Restoring faces...')
import cv2
import face_restore as fr
bgr = cv2.imread(working)
cv2.imwrite(output_path, fr.restore_faces(bgr))
working = output_path
# Stage 2: colorization (last — works on the cleaned luminance)
if colorize:
def on_col(pct, msg):
check_cancel()
task['progress'] = 65 + int(pct * 0.3)
task['message'] = msg
size = restore_engine.colorize_image(working, output_path,
progress_cb=on_col)
else:
if working != output_path:
shutil.copyfile(working, output_path)
from PIL import Image as _Image
with _Image.open(output_path) as im:
size = im.size
check_cancel()
_finish_tool_task(task_id, output_path, '_restored', size)
except TaskCancelled:
task['status'] = 'cancelled'
task['message'] = 'Cancelled'
except Exception as e:
print(f'[restore] error: {e}', flush=True)
task['status'] = 'error'
task['message'] = f'Restore error: {str(e)[:200]}'
save_task(task_id)
@app.route('/api/erase', methods=['POST'])
def erase_start():
"""Object eraser: takes the current image and a white-on-black mask as
multipart files, returns a task to poll."""
if not (model_store and model_store.available('erase')):
return jsonify({'error': 'Eraser model not installed'}), 400
image = request.files.get('image')
mask = request.files.get('mask')
if not image or not mask:
return jsonify({'error': 'Image and mask required'}), 400
task_id = 'img_' + uuid.uuid4().hex[:12]
img_path = os.path.join(app.config['UPLOAD_FOLDER'], f'{task_id}_erase_src.png')
mask_path = os.path.join(app.config['UPLOAD_FOLDER'], f'{task_id}_mask.png')
image.save(img_path)
mask.save(mask_path)
tasks[task_id] = {
'status': 'uploaded', 'type': 'image', 'input': img_path,
'filename': image.filename or 'image.png',
'progress': 0, 'message': 'Ready',
}
_start_tool_thread(task_id, _run_erase, mask_path)
return jsonify({'task_id': task_id})
def _run_erase(task_id, mask_path):
task = tasks[task_id]
output_path = os.path.join(app.config['OUTPUT_FOLDER'], f'{task_id}_erased.png')
def on_progress(pct, msg):
if task.get('cancel_requested'):
raise TaskCancelled()
task['progress'] = pct
task['message'] = msg
try:
size = restore_engine.inpaint_image(task['input'], mask_path,
output_path, progress_cb=on_progress)
_finish_tool_task(task_id, output_path, '_erased', size)
except TaskCancelled:
task['status'] = 'cancelled'
task['message'] = 'Cancelled'
except Exception as e:
print(f'[erase] error: {e}', flush=True)
task['status'] = 'error'
task['message'] = f'Erase error: {str(e)[:200]}'
save_task(task_id)
# --- Background removal endpoints ---
@app.route('/api/bg/model', methods=['GET', 'POST'])
def bg_model():
"""GET: model availability / download progress. POST: start download."""
if not bg_remove:
return jsonify({'error': 'Background removal module missing'}), 500
if request.method == 'POST':
bg_remove.start_download()
return jsonify(bg_remove.download_status())
@app.route('/api/bg/remove', methods=['POST'])
def bg_remove_start():
data = request.json or {}
task_id = data.get('task_id')
background = data.get('background', 'transparent')
task = tasks.get(task_id)
if not task:
return jsonify({'error': 'Task not found'}), 404
if not (bg_remove and bg_remove.available()):
return jsonify({'error': 'Background removal model not installed'}), 400
if background != 'transparent' and not re.fullmatch(r'#[0-9a-fA-F]{6}', background):
return jsonify({'error': 'Invalid background color'}), 400
task['status'] = 'processing'
task['progress'] = 10
task['message'] = 'Starting background removal...'
thread = threading.Thread(target=_run_bg_remove,
args=(task_id, background), daemon=True)
thread.start()
return jsonify({'status': 'processing'})
def _run_bg_remove(task_id, background):
task = tasks[task_id]
output_path = os.path.join(app.config['OUTPUT_FOLDER'], f'{task_id}_nobg.png')
def on_progress(pct, msg):
if task.get('cancel_requested'):
raise TaskCancelled()
task['progress'] = pct
task['message'] = msg
# Inference is one opaque model call (~seconds to ~30s on old CPUs) —
# tick the bar forward so it doesn't look frozen mid-run.
done_evt = threading.Event()
def _tick():
while not done_evt.wait(1.0):
if task.get('status') == 'processing' and 30 <= task['progress'] < 80:
task['progress'] += 2
threading.Thread(target=_tick, daemon=True).start()
try:
out_w, out_h = bg_remove.remove_background(
task['input'], output_path, background=background,
progress_cb=on_progress)
if task.get('cancel_requested'):
raise TaskCancelled()
task['status'] = 'completed'
task['progress'] = 100
task['output'] = output_path
task['name_suffix'] = '_nobg'
task['message'] = 'Done!'
task['output_width'] = out_w
task['output_height'] = out_h
except TaskCancelled:
task['status'] = 'cancelled'
task['message'] = 'Cancelled'
except Exception as e:
print(f'[bg-remove] error: {e}', flush=True)
task['status'] = 'error'
task['message'] = f'Background removal error: {str(e)[:200]}'
finally:
done_evt.set()
save_task(task_id)
# --- Audio tools: vocal separation + noise removal ---
AUDIO_EXTS = {'.mp3', '.wav', '.flac', '.m4a', '.aac', '.ogg', '.opus',
'.wma', '.aiff', '.aif', '.mp4', '.webm'}
@app.route('/api/audio/upload', methods=['POST'])
def audio_upload():
if not audio_engine:
return jsonify({'error': 'Audio tools unavailable'}), 500
file = request.files.get('audio')
if not file or not file.filename:
return jsonify({'error': 'No audio file provided'}), 400
ext = Path(file.filename).suffix.lower()
if ext not in AUDIO_EXTS:
return jsonify({'error': f'Unsupported format: {ext}'}), 400
task_id = 'aud_' + uuid.uuid4().hex[:12]
safe_name = re.sub(r'[^\w.\-]', '_', file.filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], f'{task_id}_{safe_name}')
file.save(filepath)
duration = audio_engine.probe_duration(filepath)
if not duration:
os.remove(filepath)
return jsonify({'error': 'Could not read audio file'}), 400
tasks[task_id] = {
'status': 'uploaded', 'type': 'audio', 'input': filepath,