Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
1560 lines (1385 loc) · 62.3 KB
/
Copy pathapp.py
File metadata and controls
1560 lines (1385 loc) · 62.3 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
# AudioMuse-AI - https://github.com/NeptuneHub/AudioMuse-AI
# Copyright (C) 2025 NeptuneHub
# SPDX-License-Identifier: AGPL-3.0-only
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License v3.0. See the LICENSE file
# in the project root or <https://github.com/NeptuneHub/AudioMuse-AI/blob/main/LICENSE>
"""Main Flask application: root routes, task control, and blueprint wiring.
Owns the shared Flask instance (imported from `flask_app`), installs the
`before_request` auth barrier from `app_auth`, mounts Swagger, and registers
every feature blueprint (`app_*`). Sibling `app_*` modules provide the feature
routes; this module provides the app-wide plumbing they all hang off.
Main Features:
* Core routes: health, `/analysis` landing page, generic task status/cancel/
cancel-all, last-task and active-tasks polling, `/api/config`, `/api/playlists`.
* Registers all feature blueprints and, on the Flask server only (never queue
workers), loads similarity indexes/caches and starts the background listener.
* Counts every request for the idle heap trim; timer-driven status polls and
health probes count as in flight but never push the trim back.
"""
import os
from psycopg2.extras import DictCursor
from flask import jsonify, request, render_template, g
from werkzeug.exceptions import HTTPException
import logging
import threading
import time
import config
from sanitization import sanitize_for_log
from tasks.setup_manager import setup_manager
# Swagger imports
from flasgger import Swagger
# Import configuration
from config import TEMP_DIR, APP_VERSION, ENABLE_PROXY_FIX, JWT_SECRET
if ENABLE_PROXY_FIX:
# Werkzeug import for reverse proxy support
from werkzeug.middleware.proxy_fix import ProxyFix
from proxy_prefix import StripDuplicatedScriptName
# --- Flask App Setup ---
# The Flask instance lives in `flask_app` so task modules can import it
# without creating a circular import back into this file.
from flask_app import app
# Import helper functions
import app_server_context
from app_helper import max_bound as _max_bound_filter
from app_helper import min_bound as _min_bound_filter
from app_helper import (
SEARCH_MIN_QUERY_LENGTH,
SEARCH_PAGE_SIZE,
revoke_inline_task_row,
cancel_job_and_children_recursive,
sanitize_task_details,
)
from database import init_db, get_db, close_db, get_task_info_from_db, coerce_db_details, disable_legacy_ai_chat_role
from taskqueue.sql import CONTROL_TASK_TYPE
from tasks.provider_migration_tasks import MIGRATION_PLANNER_TASK_TYPE
import task_types
from config import (
TASK_STATUS_PENDING,
TASK_STATUS_STARTED,
TASK_STATUS_PROGRESS,
TASK_STATUS_REVOKED,
)
from app_auth import (
init_app as init_auth,
check_setup_needed,
seed_admin_from_env,
resolve_jwt_secret,
)
from error.error_manager import AudioMuseError
from error.error_dictionary import (
ERR_INVALID_REQUEST,
ERR_NOT_FOUND,
ERR_TASK_CANCEL_FAILED,
UNKNOWN_ERROR_CODE,
)
from error.responses import json_error, json_exception, json_http_exception, wants_json_error
# NOTE: Annoy Manager import is moved to be local where used to prevent circular imports.
# Queue rows the user never started. Both spellings come from the module that
# WRITES them, because a rename that moved only one side left these filters
# matching nothing: the handshake reappeared as a phantom dashboard task, and a
# pending restart 409-blocked the next analysis or cleaning start.
# A side job (the setup wizard title preview) is left out of the last-task recap
# but still shows as the running task: it refuses every batch start, so the
# dashboard must show it and let its Stop end it.
HIDDEN_ACTIVE_TASK_TYPES = (CONTROL_TASK_TYPE, MIGRATION_PLANNER_TASK_TYPE)
NON_USER_TASK_TYPES = (
HIDDEN_ACTIVE_TASK_TYPES + task_types.SIDE_JOB_TASK_TYPES
)
_CANCEL_UNCONFIRMED_MESSAGE = (
"Cancellation could not be fully applied or confirmed; recovery tasks may remain active."
)
logger = logging.getLogger(__name__)
@app.errorhandler(AudioMuseError)
def handle_audiomuse_error(err):
app.logger.error(
"[%s] %s: %s", err.code, err.error_class, err.error_message, exc_info=err.cause or err
)
return json_exception(err, err.code)
@app.errorhandler(Exception)
def handle_unexpected_error(err):
if isinstance(err, HTTPException):
if wants_json_error(request.path):
return json_http_exception(err)
return err
app.logger.exception("Unhandled exception during request")
return json_exception(err, UNKNOWN_ERROR_CODE)
from app_logging import configure_logging
configure_logging()
if ENABLE_PROXY_FIX:
# StripDuplicatedScriptName runs after ProxyFix (inner app) to undo a doubled
# subpath prefix from a proxy that forwards the full path while also sending
# X-Forwarded-Prefix, which otherwise loops redirects to /<prefix>/setup (#668).
app.wsgi_app = ProxyFix(
StripDuplicatedScriptName(app.wsgi_app), x_for=1, x_proto=1, x_host=1, x_prefix=1
)
# Log the application version on startup
app.logger.info(f"Starting AudioMuse-AI Backend version {APP_VERSION}")
# --- Authentication Setup ---
# All auth logic (user accounts, password hashing, JWT, /login /auth /logout
# /api/users routes, and the setup/auth/admin barrier) lives in app_auth.
# The JWT secret is resolved after DB init (see below) so every gunicorn
# worker ends up sharing the same value.
_jwt_secret = JWT_SECRET
def _get_jwt_secret():
return _jwt_secret
app.add_template_filter(_min_bound_filter, 'min_bound')
app.add_template_filter(_max_bound_filter, 'max_bound')
@app.context_processor
def inject_globals():
from config import CLAP_ENABLED, LYRICS_ENABLED, NEURAL_FINGERPRINT_ENABLED
# auth_role defaults to 'admin' (set by check_auth_needed), so when
# AUTH_ENABLED is false or the barrier has not run yet (e.g. error
# pages), is_admin will be True and the full UI is shown.
auth_role = getattr(g, 'auth_role', 'admin')
current_user = getattr(g, 'auth_user', None)
# Resolve each plugin menu link here (inside a request context) with per-item
# isolation so a plugin whose endpoint does not build can never 500 the layout
# that every authenticated page renders.
plugin_menu_items = []
try:
from flask import url_for
from plugin.manager import plugin_manager
for item in plugin_manager.menu_items():
if item.get('admin_only') and auth_role != 'admin':
continue
try:
item_url = url_for(item['endpoint'])
except Exception:
continue
plugin_menu_items.append({**item, 'url': item_url})
except Exception:
plugin_menu_items = []
# Sidebar server picker, rendered server-side so it paints with the page
# instead of popping in at DOMContentLoaded. Credentials are never included.
nav_music_servers = None
try:
payload = app_server_context.servers_for_ui()
nav_music_servers = {
'multi_server_enabled': bool(payload.get('multi_server_enabled')),
'default_id': payload.get('default_id'),
'servers': [
{'server_id': s['server_id'], 'name': s['name'], 'is_default': s['is_default']}
for s in payload.get('servers', [])
],
}
except Exception:
logger.exception("Could not build the sidebar server picker data")
nav_music_servers = None
return dict(
app_version=APP_VERSION,
clap_enabled=CLAP_ENABLED,
lyrics_enabled=LYRICS_ENABLED,
neural_enabled=NEURAL_FINGERPRINT_ENABLED,
auth_enabled=config.AUTH_ENABLED,
setup_saved=not check_setup_needed(),
is_admin=(auth_role == 'admin'),
current_user=current_user,
plugin_menu_items=plugin_menu_items,
nav_music_servers=nav_music_servers,
search_page_size=SEARCH_PAGE_SIZE,
search_min_chars=SEARCH_MIN_QUERY_LENGTH,
)
# Register the auth barrier + auth routes (/login, /auth, /logout, /api/users).
init_auth(app, setup_manager, _get_jwt_secret)
@app.before_request
def log_api_request():
if request.path.startswith('/api/') and not request.path.startswith('/static/'):
app.logger.info('API request: %s %s', request.method, request.path)
@app.before_request
def reject_non_object_json_body():
if request.method not in ('POST', 'PUT', 'PATCH', 'DELETE') or not request.is_json:
return None
if not wants_json_error(request.path):
return None
body = request.get_json(silent=True)
if body is None or isinstance(body, dict):
return None
return json_error(ERR_INVALID_REQUEST, "The request body must be a JSON object.")
# Timer-driven UI polls (dashboard every 30 s, task pages every 3 s) and health
# probes: they count as in flight but do not push the idle heap trim back, or any
# open AudioMuse page would keep the web process "busy" and the trim never fires.
_STATUS_POLL_PATHS = frozenset({
'/api/dashboard/summary',
'/api/active_tasks',
'/api/last_task',
'/api/health',
})
_STATUS_POLL_PREFIXES = ('/api/status/',)
def _is_status_poll():
if request.method != 'GET':
return False
path = request.path
return path in _STATUS_POLL_PATHS or path.startswith(_STATUS_POLL_PREFIXES)
@app.before_request
def note_request_start():
if _is_worker:
return
try:
from tasks.memory_utils import note_request_started
arm = not _is_status_poll()
g._heap_trim_counted = True
g._heap_trim_arms = arm
note_request_started(arm=arm)
except Exception:
app.logger.exception("Could not note the request start for the idle heap trim")
@app.teardown_request
def note_request_end(exc=None):
if _is_worker:
return
if not g.pop('_heap_trim_counted', False):
return
try:
from tasks.memory_utils import note_request_finished
note_request_finished(arm=g.pop('_heap_trim_arms', True))
except Exception:
app.logger.exception("Could not note the request finish for the idle heap trim")
@app.route('/api/health')
def health_check():
"""
Liveness probe.
---
tags:
- Health
summary: Lightweight health check.
responses:
200:
description: Service is up.
content:
application/json:
schema:
type: object
properties:
status:
type: string
example: ok
"""
return jsonify(
{
'status': 'ok',
}
)
@app.route('/api/version', methods=['GET'])
def version_api():
"""
Return the running application version to authenticated clients.
---
tags:
- Config
summary: Application version, separate from model metadata.
responses:
200:
description: Actual runtime APP_VERSION, preserving release suffixes.
content:
application/json:
schema:
type: object
required: [app_version]
properties:
app_version:
type: string
401:
description: Authentication required under the existing policy.
403:
description: Initial setup required under the existing policy.
"""
response = jsonify({'app_version': config.APP_VERSION})
response.headers['Cache-Control'] = 'no-store'
return response
# --- Swagger Setup ---
app.config['SWAGGER'] = {'title': 'AudioMuse-AI API', 'uiversion': 3, 'openapi': '3.0.0'}
swagger = Swagger(app)
@app.teardown_appcontext
def teardown_db(e=None):
close_db(e)
try:
from tasks.paged_ivf import end_all_requests
end_all_requests()
except Exception:
pass
# Initialize the database schema when the application module is loaded.
# This is safe because it doesn't import other application modules.
# queue workers import app.py too, but they should not perform schema bootstrapping.
_is_worker = (os.environ.get('AUDIOMUSE_ROLE') or '').lower() == 'worker'
if not _is_worker:
with app.app_context():
init_db()
# Keep app_config aligned with the parameters that config.py still
# accepts. Valid rows are never rewritten; only retired keys are
# removed, then every parameter that has no row yet is written with
# the value this process runs with (environment or config.py default,
# SETUP_BOOTSTRAP_EXCLUDED_KEYS stay env-only). From the next start on
# the database is the only source of those values, so a changed
# default never flips a setting an installation already has.
setup_manager.prune_obsolete_config_values(config)
setup_manager.persist_missing_config_values(config)
# One-time legacy cleanup: the retired AI chat role is set NOLOGIN when
# it still carries its shipped default password. Never creates a role.
try:
if disable_legacy_ai_chat_role():
app.logger.warning(
"Legacy AI chat database role 'ai_user' still had its default "
"password; its login was disabled."
)
except Exception:
app.logger.exception(
"Legacy AI chat database role check failed (will retry next boot)"
)
# Bootstrap / reconcile the first admin account:
# - If audiomuse_users already has an admin, purge any legacy
# AUDIOMUSE_USER / AUDIOMUSE_PASSWORD rows from app_config.
# - Else if app_config contains legacy admin values, import them into
# audiomuse_users and remove the legacy config.
# - Else if env vars contain legacy admin values, import them into
# audiomuse_users.
# See app_auth.seed_admin_from_env for full precedence.
try:
seed_admin_from_env()
except Exception as _seed_exc:
app.logger.warning("seed_admin_from_env failed at startup: %s", _seed_exc)
# Media-server settings live only in the music_servers registry: config
# globals are projected from its default row at import (config module),
# init_db migrates legacy app_config rows into it and deletes them, so
# no config<->registry sync is needed here anymore.
# One-time legacy catalogue migration, Flask startup ONLY: relabel any
# provider-keyed (or retired-scheme) rows to the canonical signature id.
# Pure DB work from stored embeddings; an instant no-op on every later
# boot. A relabel renames tracks without moving a single vector, so the
# migration repoints the existing indexes at the new ids rather than
# rebuilding them, and similarity keeps working across it.
_relabel = {}
try:
from tasks.fingerprint_canonicalize import canonicalize_fingerprinted_ids
_relabel = canonicalize_fingerprinted_ids()
if _relabel.get('relabelled'):
app.logger.info(
"Startup migration relabelled %s catalogue ids; the similarity "
"indexes were repointed at them, no rebuild needed.",
_relabel['relabelled'],
)
except Exception as _migrate_exc:
app.logger.warning(
"Startup catalogue-id migration failed (will retry next boot): %s",
_migrate_exc,
)
# One-time duplicate verification for installs merged by an early 3.0
# build (fp_ ids, but merged before track length was considered): each
# catalogue id mapping multiple files whose survivor has no duration yet
# is re-checked with the duration rule; false duplicates are unmapped so
# the next analysis re-analyzes them under their own ids. It is
# table-derived (score.duration), so it is an instant no-op after the
# legacy migration and after its own first pass - no stored flag that a
# config cleanup could wipe, no second duration fetch on a legacy upgrade.
_repair = {}
try:
from tasks.duplicate_repair import repair_duplicate_track_maps
# Reuse the whole-server listing the legacy migration just did so a
# mixed upgrade (provider ids plus leftover older-scheme rows) does not
# list the same server twice on one boot - its only slow step.
_repair = repair_duplicate_track_maps(
prefetched_durations=_relabel.get('server_durations'),
) or {}
except Exception as _repair_exc:
# A thrown repair proves nothing ran to completion: mark it skipped so
# the migration-gated steps below (same-folder split, orphan purge) do
# not act on a catalogue whose migration state is unknown.
_repair = {'skipped': 'error'}
app.logger.warning(
"Startup catalogue duplicate check failed (will retry next boot): %s",
_repair_exc,
)
# Split any merge that grouped two distinct files from the SAME folder (an
# album never holds one recording twice). The migration paths already reject
# same-folder pairs as they resolve; this group-level pass catches the few
# transitive leftovers. It is GATED on a scheme migration having actually run
# this boot (older-scheme rows existed) - so once everything is on the current
# scheme it never runs and never scans track_server_map on a steady-state boot.
_migration_happened = bool(_relabel.get('relabelled')) or 'skipped' not in _repair
if _migration_happened:
try:
from tasks.duplicate_repair import split_same_folder_merges
split_same_folder_merges()
except Exception as _folder_exc:
app.logger.warning(
"Startup same-folder cleanup failed (will retry next boot): %s",
_folder_exc,
)
# Leave a clean catalogue after a migration: delete every row a false
# split (or a prior run) left bound to no server, so re-analysis re-creates
# it under its own id rather than stranding an orphan.
try:
from tasks.duplicate_repair import purge_orphan_catalogue_rows
purge_orphan_catalogue_rows()
except Exception as _purge_exc:
app.logger.warning(
"Startup migration orphan purge failed (will retry next boot): %s",
_purge_exc,
)
# Finalize JWT_SECRET - must happen after DB init so the value can be
# persisted and shared across all gunicorn workers.
_jwt_secret = resolve_jwt_secret(setup_manager)
else:
app.logger.info("Worker mode: skipping startup database schema bootstrap.")
import app_setup # noqa: F401
# --- API Endpoints ---
@app.route('/analysis')
def index():
"""
Serve the Analysis & Clustering page (legacy home).
The application landing page is now the dashboard ('/').
---
tags:
- UI
responses:
200:
description: HTML content of the main page.
content:
text/html:
schema:
type: string
"""
return render_template('index.html', title='AudioMuse-AI - Home Page', active='index')
@app.route('/api/status/<task_id>', methods=['GET'])
def get_task_status_endpoint(task_id):
"""
Get the status of a specific task.
Retrieves status information from the database.
---
tags:
- Status
parameters:
- name: task_id
in: path
required: true
description: The ID of the task.
schema:
type: string
responses:
200:
description: Status information for the task.
content:
application/json:
schema:
type: object
properties:
task_id:
type: string
state:
type: string
description: Current state of the task (e.g., PENDING, STARTED, PROGRESS, SUCCESS, FAILURE, REVOKED, queued, finished, failed, canceled).
status_message:
type: string
description: A human-readable status message.
progress:
type: integer
description: Task progress percentage (0-100).
running_time_seconds:
type: number
description: The total running time of the task in seconds. Updates live for running tasks.
details:
type: object
description: Detailed information about the task. Structure varies by task type and state.
additionalProperties: true
example: {"log": ["Log message 1"], "current_album": "Album X"}
task_type_from_db:
type: string
nullable: true
description: The type of the task as recorded in the database (e.g., main_analysis, album_analysis, main_clustering, clustering_batch).
404:
description: Task ID not found in the database.
content:
application/json:
schema:
type: object
properties:
task_id:
type: string
state:
type: string
example: UNKNOWN
status_message:
type: string
example: Task ID not found in the database.
"""
# One read. There is no second system holding a second opinion about this
# task, so there is nothing to merge and no rule needed for whose answer wins.
response = {
'task_id': task_id,
'state': 'UNKNOWN',
'status_message': 'Task ID not found.',
'progress': 0,
'details': {},
'task_type_from_db': None,
'running_time_seconds': 0,
}
db_task_info = get_task_info_from_db(task_id)
if not db_task_info:
return json_error(ERR_NOT_FOUND, response['status_message'], **response)
details = coerce_db_details(db_task_info.get('details')) or {}
response['state'] = db_task_info.get('status') or 'UNKNOWN'
response['task_type_from_db'] = db_task_info.get('task_type')
response['running_time_seconds'] = db_task_info.get('running_time_seconds', 0)
response['progress'] = db_task_info.get('progress', 0)
response['details'] = details
response['status_message'] = (
details.get('status_message') or details.get('message') or response['state']
)
if response['state'] == TASK_STATUS_REVOKED:
response['status_message'] = details.get('message') or 'Task revoked.'
response['progress'] = 100
response['details'] = sanitize_task_details(
response.get('details'), response.get('state'), response.get('task_type_from_db')
)
# Clean up the final response to remove confusing raw time columns
response.pop('timestamp', None)
response.pop('start_time', None)
response.pop('end_time', None)
return jsonify(response)
@app.route('/api/cancel/<task_id>', methods=['POST'])
def cancel_task_endpoint(task_id):
"""
Cancel a specific task and its children.
Marks the task and its descendants as REVOKED in the database and notifies
the queue workers to stop the process running it.
---
tags:
- Control
parameters:
- name: task_id
in: path
required: true
description: The ID of the task.
schema:
type: string
responses:
200:
description: Cancellation initiated for the task and its children.
content:
application/json:
schema:
type: object
properties:
message:
type: string
task_id:
type: string
cancelled_jobs_count:
type: integer
400:
description: Task could not be cancelled (e.g., already completed or not in an active state).
404:
description: Task ID not found in the database.
"""
# An in-process task has no queue job to stop, and the global cancel below is
# destructive by design, so it gets a surgical revoke of its own row instead.
inline_message = revoke_inline_task_row(task_id)
if inline_message:
return jsonify(
{"message": inline_message, "task_id": task_id, "cancelled_jobs_count": 0}
), 200
# Always perform cancel when the endpoint is invoked. No early returns.
try:
cancelled_count = cancel_job_and_children_recursive(
task_id, reason=f"Cancellation requested for task {task_id} via API."
)
except Exception:
logger.exception(
"Cancellation of task %s could not be fully confirmed",
sanitize_for_log(task_id),
)
return json_error(
ERR_TASK_CANCEL_FAILED, _CANCEL_UNCONFIRMED_MESSAGE, task_id=task_id, details=None,
)
return jsonify(
{
"message": f"Task {task_id} cancellation requested. {cancelled_count} cancellation actions attempted.",
"task_id": task_id,
"cancelled_jobs_count": cancelled_count,
}
), 200
@app.route('/api/cancel_all/<task_type_prefix>', methods=['POST'])
def cancel_all_tasks_by_type_endpoint(task_type_prefix):
"""
Cancel all active tasks of a specific type (e.g., main_analysis, main_clustering) and their children.
---
tags:
- Control
parameters:
- name: task_type_prefix
in: path
required: true
description: The type of main tasks to cancel (e.g., "main_analysis", "main_clustering").
schema:
type: string
responses:
200:
description: Cancellation initiated for all matching active tasks and their children.
content:
application/json:
schema:
type: object
properties:
message:
type: string
cancelled_main_tasks:
type: array
items:
type: string
404:
description: No active tasks of the specified type found to cancel.
"""
db = get_db()
cur = db.cursor(cursor_factory=DictCursor)
cur.execute(
"SELECT task_id, task_type FROM task_status WHERE task_type = %s "
"AND status NOT IN %s",
(task_type_prefix, config.TASK_STATUS_TERMINAL),
)
tasks_to_cancel = cur.fetchall()
cur.close()
# Decide 404 BEFORE any destructive call: the cancel empties the whole table
# and revokes every row, so running it first and then reporting "nothing
# found" would be a lie about a wipe that already happened.
if not tasks_to_cancel:
nothing_to_cancel = f"No active tasks of type '{task_type_prefix}' found to cancel."
return json_error(ERR_NOT_FOUND, nothing_to_cancel, message=nothing_to_cancel)
cancelled_main_task_ids = [r['task_id'] for r in tasks_to_cancel]
# cancel_job_and_children_recursive re-raises when the tombstone commit fails.
# Without this the generic handler answered UNKNOWN 500 with no
# cancelled_main_tasks, so the caller could not tell a partially applied
# cancel from an unknown failure. The sibling /api/cancel/<task_id> answers 503.
try:
total_cancelled_jobs = cancel_job_and_children_recursive(
cancelled_main_task_ids[0],
reason=f"Bulk cancellation for task type '{task_type_prefix}' via API.",
)
except Exception:
logger.exception(
"Bulk cancellation for %s could not be fully confirmed",
sanitize_for_log(task_type_prefix),
)
return json_error(
ERR_TASK_CANCEL_FAILED, _CANCEL_UNCONFIRMED_MESSAGE,
cancelled_main_tasks=cancelled_main_task_ids, details=None,
)
return jsonify(
{
"message": (
f"Cancellation initiated for {len(cancelled_main_task_ids)} main tasks "
f"of type '{task_type_prefix}' and their children. "
f"Total jobs affected: {total_cancelled_jobs}."
),
"cancelled_main_tasks": cancelled_main_task_ids,
}
), 200
@app.route('/api/last_task', methods=['GET'])
def get_last_overall_task_status_endpoint():
"""
Get the most recent overall main task.
---
tags:
- Tasks
summary: Status of the latest top-level main task (analysis, clustering, cleaning, etc.).
description: |
Returns the most recent row in `task_status` whose `parent_task_id` is
NULL. Long log lists are truncated to the last 10 entries with a
"... earlier entries truncated" placeholder.
responses:
200:
description: Task summary or a sentinel object when no main task has ever run.
content:
application/json:
schema:
type: object
properties:
task_id:
type: string
nullable: true
task_type:
type: string
nullable: true
status:
type: string
progress:
type: number
details:
type: object
running_time_seconds:
type: number
format: float
"""
db = get_db()
cur = db.cursor(cursor_factory=DictCursor)
# Control-plane handshakes and migration planner runs are queue rows now, but
# they are not user tasks: showing one here made every task-polling page
# believe a restart request was "the last task".
cur.execute(
"""
SELECT task_id, task_type, status, progress, details, start_time, end_time
FROM task_status
WHERE parent_task_id IS NULL
AND task_type NOT IN %s
ORDER BY timestamp DESC
LIMIT 1
""",
(NON_USER_TASK_TYPES,),
)
last_task_row = cur.fetchone()
cur.close()
if last_task_row:
last_task_data = dict(last_task_row)
if last_task_data.get('details'):
last_task_data['details'] = coerce_db_details(last_task_data['details'])
# Calculate running time in Python
start_time = last_task_data.get('start_time')
end_time = last_task_data.get('end_time')
if start_time:
effective_end_time = end_time if end_time is not None else time.time()
last_task_data['running_time_seconds'] = max(0, effective_end_time - start_time)
else:
last_task_data['running_time_seconds'] = 0.0
last_task_data['details'] = sanitize_task_details(
last_task_data.get('details'),
last_task_data.get('status'),
last_task_data.get('task_type'),
)
# Clean up raw time columns before sending response
last_task_data.pop('start_time', None)
last_task_data.pop('end_time', None)
last_task_data.pop('timestamp', None)
return jsonify(last_task_data), 200
return jsonify(
{
"task_id": None,
"task_type": None,
"status": "NO_PREVIOUS_MAIN_TASK",
"details": {"log": ["No previous main task found."]},
}
), 200
@app.route('/api/active_tasks', methods=['GET'])
def get_active_tasks_endpoint():
"""
Get the currently active main task.
---
tags:
- Tasks
summary: Return the in-flight top-level main task (PENDING/STARTED/PROGRESS), if any.
description: |
Returns `{}` when no main task is active. Strips heavyweight internal
keys (`clustering_run_job_ids`, `checked_album_ids`, initial centroids)
from the response payload.
responses:
200:
description: Active task or empty object.
content:
application/json:
schema:
type: object
"""
db = get_db()
cur = db.cursor(cursor_factory=DictCursor)
non_terminal_statuses = (TASK_STATUS_PENDING, TASK_STATUS_STARTED, TASK_STATUS_PROGRESS)
# worker_control handshakes and migration planner runs are queue rows, not
# user tasks: without this filter a slow worker restart greyed out every
# Start button until the stale sweep failed the request row 30 minutes on.
cur.execute(
"""
SELECT task_id, parent_task_id, task_type, sub_type_identifier, status, progress, details, start_time, end_time
FROM task_status
WHERE parent_task_id IS NULL AND status IN %s
AND task_type NOT IN %s
ORDER BY timestamp DESC
LIMIT 1
""",
(non_terminal_statuses, HIDDEN_ACTIVE_TASK_TYPES),
)
active_main_task_row = cur.fetchone()
cur.close()
if active_main_task_row:
task_item = dict(active_main_task_row)
# Calculate running time in Python
start_time = task_item.get('start_time')
if start_time:
task_item['running_time_seconds'] = max(0, time.time() - start_time)
else:
task_item['running_time_seconds'] = 0.0
if task_item.get('details'):
details = coerce_db_details(task_item['details'])
# Prune specific large or internal keys from details
if isinstance(details, dict):
details.pop('clustering_run_job_ids', None)
details.pop('checked_album_ids', None)
cmc = (
details.get('best_params', {}).get('clustering_method_config', {})
if isinstance(details.get('best_params'), dict)
else {}
)
if isinstance(cmc, dict) and isinstance(cmc.get('params'), dict):
cmc['params'].pop('initial_centroids', None)
task_item['details'] = sanitize_task_details(
details, task_item.get('status'), task_item.get('task_type')
)
# Clean up raw time columns before sending response
task_item.pop('start_time', None)
task_item.pop('end_time', None)
task_item.pop('timestamp', None)
task_item['side_job'] = task_item.get('task_type') in task_types.SIDE_JOB_TASK_TYPES
return jsonify(task_item), 200
return jsonify({}), 200 # Return empty object if no active main task
@app.route('/api/config', methods=['GET'])
def get_config_endpoint():
"""
Public configuration snapshot.
---
tags:
- Config
summary: Return the user-relevant subset of `config.*` (clustering ranges, AI provider, alchemy defaults, etc.).
description: |
Reads attributes from the `config` module at request time rather than
using names imported at app.py module load, so wizard changes are
visible without a Flask restart.
responses:
200:
description: Configuration values currently in effect.
content:
application/json:
schema:
type: object
additionalProperties: true
"""
return jsonify(
{
"num_recent_albums": config.NUM_RECENT_ALBUMS,
"max_distance": config.MAX_DISTANCE,
"max_songs_per_cluster": config.MAX_SONGS_PER_CLUSTER,
"max_songs_per_artist": config.MAX_SONGS_PER_ARTIST,
"cluster_algorithm": config.CLUSTER_ALGORITHM,
"clustering_auto_calibration": config.CLUSTERING_AUTO_CALIBRATION,
"num_clusters_min": config.NUM_CLUSTERS_MIN,
"num_clusters_max": config.NUM_CLUSTERS_MAX,
"dbscan_eps_min": config.DBSCAN_EPS_MIN,
"dbscan_eps_max": config.DBSCAN_EPS_MAX,
"gmm_covariance_type": config.GMM_COVARIANCE_TYPE,
"dbscan_min_samples_min": config.DBSCAN_MIN_SAMPLES_MIN,
"dbscan_min_samples_max": config.DBSCAN_MIN_SAMPLES_MAX,
"gmm_n_components_min": config.GMM_N_COMPONENTS_MIN,
"gmm_n_components_max": config.GMM_N_COMPONENTS_MAX,
"spectral_n_clusters_min": config.SPECTRAL_N_CLUSTERS_MIN,
"spectral_n_clusters_max": config.SPECTRAL_N_CLUSTERS_MAX,
"pca_components_min": config.PCA_COMPONENTS_MIN,
"pca_components_max": config.PCA_COMPONENTS_MAX,
"min_songs_per_genre_for_stratification": config.MIN_SONGS_PER_GENRE_FOR_STRATIFICATION,
"stratified_sampling_target_percentile": config.STRATIFIED_SAMPLING_TARGET_PERCENTILE,
"ai_model_provider": config.AI_MODEL_PROVIDER,
"ollama_server_url": config.OLLAMA_SERVER_URL,
"ollama_model_name": config.OLLAMA_MODEL_NAME,
"openai_server_url": config.OPENAI_SERVER_URL,
"openai_model_name": config.OPENAI_MODEL_NAME,
"gemini_model_name": config.GEMINI_MODEL_NAME,
"mistral_model_name": config.MISTRAL_MODEL_NAME,
"top_n_moods": config.TOP_N_MOODS,
"mood_labels": config.MOOD_LABELS,
"clustering_runs": config.CLUSTERING_RUNS,
"top_n_clustering_playlist": config.TOP_N_CLUSTERING_PLAYLIST,
"enable_clustering_embeddings": config.ENABLE_CLUSTERING_EMBEDDINGS,
"score_weight_diversity": config.SCORE_WEIGHT_DIVERSITY,
"score_weight_silhouette": config.SCORE_WEIGHT_SILHOUETTE,
"score_weight_davies_bouldin": config.SCORE_WEIGHT_DAVIES_BOULDIN,
"score_weight_calinski_harabasz": config.SCORE_WEIGHT_CALINSKI_HARABASZ,
"score_weight_purity": config.SCORE_WEIGHT_PURITY,
"score_weight_other_feature_diversity": config.SCORE_WEIGHT_OTHER_FEATURE_DIVERSITY,
"score_weight_other_feature_purity": config.SCORE_WEIGHT_OTHER_FEATURE_PURITY,
"path_distance_metric": config.PATH_DISTANCE_METRIC,
"alchemy_default_n_results": config.ALCHEMY_DEFAULT_N_RESULTS,
"alchemy_max_n_results": config.ALCHEMY_MAX_N_RESULTS,
"alchemy_temperature": config.ALCHEMY_TEMPERATURE,
"alchemy_subtract_distance_angular": config.ALCHEMY_SUBTRACT_DISTANCE_ANGULAR,
"alchemy_subtract_distance_euclid": config.ALCHEMY_SUBTRACT_DISTANCE_EUCLIDEAN,
}
)