-
-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy pathapp_helper.py
More file actions
1792 lines (1605 loc) · 81.3 KB
/
Copy pathapp_helper.py
File metadata and controls
1792 lines (1605 loc) · 81.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
# app_helper.py
import ipaddress
import json
import logging
import socket
import sys
import time
from urllib.parse import urlparse
import psycopg2
from psycopg2.extras import DictCursor
import numpy as np
from flask import g
from database import get_db, close_db
from taskqueue import (
redis_conn,
rq_queue_high,
rq_queue_default,
Job,
NoSuchJobError,
send_stop_job_command,
)
from config import STRATIFIED_GENRES
from tz_helper import UTC_NOW_SQL
logger = logging.getLogger(__name__)
# Import app object after it's defined to break circular dependency
# Avoid importing the Flask `app` object here to prevent circular imports.
# Use the module-level `logger` defined above for logging instead of `app.logger`.
# In-memory cache for the precomputed 2D map projection (optional)
MAP_PROJECTION_CACHE = None
def validate_outbound_url(url):
"""SSRF guard for user-supplied outbound HTTP(S) URLs.
Returns ``(True, None)`` when the URL is safe to fetch, else
``(False, reason)``.
Self-hosted media servers and APIs (e.g. a private Lyrics API) legitimately
live on the LAN (RFC1918) or the same host (loopback), so those are allowed.
Only what is never a real user service and is a classic SSRF target is
rejected: non-HTTP(S) schemes and link-local / multicast / reserved /
unspecified addresses (notably 169.254.169.254 cloud metadata).
"""
if not url:
return False, 'URL is required'
try:
parsed = urlparse(str(url))
except Exception:
return False, 'Invalid URL'
if parsed.scheme not in ('http', 'https'):
return False, 'Only http and https URLs are supported'
host = parsed.hostname
if not host:
return False, 'URL host is required'
try:
addrinfo = socket.getaddrinfo(
host, parsed.port or (443 if parsed.scheme == 'https' else 80),
type=socket.SOCK_STREAM,
)
except Exception:
return False, 'Could not resolve host'
for entry in addrinfo:
try:
ip_obj = ipaddress.ip_address(entry[4][0])
except ValueError:
return False, 'Resolved host to invalid IP'
if (
ip_obj.is_link_local
or ip_obj.is_multicast
or ip_obj.is_reserved
or ip_obj.is_unspecified
):
return False, 'Target host resolves to a disallowed IP address'
return True, None
# In-memory cache for the precomputed 2D artist component projections
ARTIST_PROJECTION_CACHE = None
# --- Constants ---
MAX_LOG_ENTRIES_STORED = 10 # Max number of recent log entries to store in the database per task
def init_db():
db = get_db()
with db.cursor() as cur:
# Serialize concurrent init_db() runs across gunicorn workers/containers.
# Multiple workers racing on CREATE EXTENSION / CREATE OR REPLACE FUNCTION
# causes Postgres "tuple concurrently updated" errors on pg_proc/pg_extension.
# A session-level advisory lock forces other workers to wait here.
# The key is an arbitrary stable bigint specific to this app's init.
# Safety: session-level advisory locks are auto-released by Postgres
# when the connection ends (normal close, crash, kill, or network drop),
# so this lock can NEVER leak permanently even if init_db() raises.
cur.execute("SELECT pg_advisory_lock(726354821)")
try:
# Enable extensions to fix and assist in searches
if sys.platform == 'win32':
for ext in ('unaccent', 'pg_trgm'):
cur.execute("SAVEPOINT ext_create")
try:
cur.execute(f'CREATE EXTENSION IF NOT EXISTS {ext}')
cur.execute("RELEASE SAVEPOINT ext_create")
except Exception:
logger.warning("Extension %s not available -- skipping", ext)
cur.execute("ROLLBACK TO SAVEPOINT ext_create")
else:
cur.execute('CREATE EXTENSION IF NOT EXISTS unaccent')
cur.execute('CREATE EXTENSION IF NOT EXISTS pg_trgm')
# Create 'score' table
cur.execute("CREATE TABLE IF NOT EXISTS score (item_id TEXT PRIMARY KEY, title TEXT, author TEXT, album TEXT, album_artist TEXT, tempo REAL, key TEXT, scale TEXT, mood_vector TEXT)")
# Add 'energy' column if not exists
cur.execute("SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'score' AND column_name = 'energy')")
if not cur.fetchone()[0]:
logger.info("Adding 'energy' column to 'score' table.")
cur.execute("ALTER TABLE score ADD COLUMN energy REAL")
# Add 'other_features' column if not exists
cur.execute("SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'score' AND column_name = 'other_features')")
if not cur.fetchone()[0]:
logger.info("Adding 'other_features' column to 'score' table.")
cur.execute("ALTER TABLE score ADD COLUMN other_features TEXT")
# Add 'album' column if not exists
cur.execute("SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'score' AND column_name = 'album')")
if not cur.fetchone()[0]:
logger.info("Adding 'album' column to 'score' table.")
cur.execute("ALTER TABLE score ADD COLUMN album TEXT")
# Add 'album_artist' column if not exists
cur.execute("SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'score' AND column_name = 'album_artist')")
if not cur.fetchone()[0]:
logger.info("Adding 'album_artist' column to 'score' table.")
cur.execute("ALTER TABLE score ADD COLUMN album_artist TEXT")
# Add 'year' column if not exists
cur.execute("SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'score' AND column_name = 'year')")
if not cur.fetchone()[0]:
logger.info("Adding 'year' column to 'score' table.")
cur.execute("ALTER TABLE score ADD COLUMN year INTEGER")
# Add 'rating' column if not exists
cur.execute("SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'score' AND column_name = 'rating')")
if not cur.fetchone()[0]:
logger.info("Adding 'rating' column to 'score' table.")
cur.execute("ALTER TABLE score ADD COLUMN rating INTEGER")
# Add 'file_path' column if not exists
cur.execute("SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'score' AND column_name = 'file_path')")
if not cur.fetchone()[0]:
logger.info("Adding 'file_path' column to 'score' table.")
cur.execute("ALTER TABLE score ADD COLUMN file_path TEXT")
# Ensure we have a searchable, accent-stripped `search_u` column.
# Postgres does not allow generated columns to call `unaccent()` (it's not marked immutable),
# so we store the value in a normal column and keep it in sync via trigger.
cur.execute("SELECT is_generated FROM information_schema.columns WHERE table_name = 'score' AND column_name = 'search_u'")
row = cur.fetchone()
search_u_generated = (row and row[0] == 'ALWAYS')
if search_u_generated:
logger.info("Dropping legacy generated 'search_u' column to replace it with a trigger-updated column.")
cur.execute("ALTER TABLE score DROP COLUMN IF EXISTS search_u")
row = None
# Create plain `search_u` column if missing
if not row:
logger.info("Adding 'search_u' column to 'score' table.")
cur.execute("ALTER TABLE score ADD COLUMN search_u TEXT")
# Create helper function for accent stripping (safe to run multiple times)
if sys.platform == 'win32':
cur.execute("SAVEPOINT search_setup")
try:
cur.execute("CREATE OR REPLACE FUNCTION immutable_unaccent(text) RETURNS text LANGUAGE sql IMMUTABLE AS $$ SELECT public.unaccent($1) $$;")
cur.execute("""
CREATE OR REPLACE FUNCTION score_search_u_sync() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
NEW.search_u := lower(immutable_unaccent(concat_ws(' ', NEW.title, NEW.author, NEW.album)));
RETURN NEW;
END;
$$;
""")
cur.execute("DROP TRIGGER IF EXISTS score_search_u_sync_trigger ON score")
cur.execute("""
CREATE TRIGGER score_search_u_sync_trigger
BEFORE INSERT OR UPDATE ON score
FOR EACH ROW
EXECUTE FUNCTION score_search_u_sync();
""")
cur.execute("UPDATE score SET search_u = lower(immutable_unaccent(concat_ws(' ', title, author, album))) WHERE search_u IS NULL")
cur.execute("CREATE INDEX IF NOT EXISTS score_search_u_trgm ON score USING gin (search_u gin_trgm_ops)")
cur.execute("RELEASE SAVEPOINT search_setup")
except Exception:
logger.warning("unaccent/pg_trgm extensions not available -- accent-insensitive search disabled")
cur.execute("ROLLBACK TO SAVEPOINT search_setup")
else:
cur.execute("CREATE OR REPLACE FUNCTION immutable_unaccent(text) RETURNS text LANGUAGE sql IMMUTABLE AS $$ SELECT public.unaccent($1) $$;")
cur.execute("""
CREATE OR REPLACE FUNCTION score_search_u_sync() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
NEW.search_u := lower(immutable_unaccent(concat_ws(' ', NEW.title, NEW.author, NEW.album)));
RETURN NEW;
END;
$$;
""")
cur.execute("DROP TRIGGER IF EXISTS score_search_u_sync_trigger ON score")
cur.execute("""
CREATE TRIGGER score_search_u_sync_trigger
BEFORE INSERT OR UPDATE ON score
FOR EACH ROW
EXECUTE FUNCTION score_search_u_sync();
""")
cur.execute("UPDATE score SET search_u = lower(immutable_unaccent(concat_ws(' ', title, author, album))) WHERE search_u IS NULL")
cur.execute("CREATE INDEX IF NOT EXISTS score_search_u_trgm ON score USING gin (search_u gin_trgm_ops)")
# Create 'playlist' table
cur.execute("CREATE TABLE IF NOT EXISTS playlist (id SERIAL PRIMARY KEY, playlist_name TEXT, item_id TEXT, title TEXT, author TEXT, UNIQUE (playlist_name, item_id))")
# Create 'task_status' table
cur.execute("CREATE TABLE IF NOT EXISTS task_status (id SERIAL PRIMARY KEY, task_id TEXT UNIQUE NOT NULL, parent_task_id TEXT, task_type TEXT NOT NULL, sub_type_identifier TEXT, status TEXT, progress INTEGER DEFAULT 0, details TEXT, timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP)")
# Migrate 'start_time' and 'end_time' columns
for col_name in ['start_time', 'end_time']:
cur.execute("SELECT data_type FROM information_schema.columns WHERE table_name = 'task_status' AND column_name = %s", (col_name,))
if not cur.fetchone(): cur.execute(f"ALTER TABLE task_status ADD COLUMN {col_name} DOUBLE PRECISION")
# Create 'task_history' table — a small, persistent log of the last
# completed/cancelled MAIN tasks. Survives the global Cancel button
# which wipes `task_status`. Capped to the most recent 10 rows.
cur.execute("""
CREATE TABLE IF NOT EXISTS task_history (
id SERIAL PRIMARY KEY,
recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
task_id TEXT,
task_type TEXT,
status TEXT,
duration_seconds DOUBLE PRECISION,
note TEXT
)
""")
# Create 'embedding' table
cur.execute("CREATE TABLE IF NOT EXISTS embedding (item_id TEXT PRIMARY KEY, FOREIGN KEY (item_id) REFERENCES score (item_id) ON DELETE CASCADE)")
cur.execute("SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'embedding' AND column_name = 'embedding')")
if not cur.fetchone()[0]: cur.execute("ALTER TABLE embedding ADD COLUMN embedding BYTEA")
# Create 'lyrics_embedding' table for lyrics similarity and axis scores
cur.execute("CREATE TABLE IF NOT EXISTS lyrics_embedding (item_id TEXT PRIMARY KEY, FOREIGN KEY (item_id) REFERENCES score (item_id) ON DELETE CASCADE)")
cur.execute("SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'lyrics_embedding' AND column_name = 'embedding')")
if not cur.fetchone()[0]: cur.execute("ALTER TABLE lyrics_embedding ADD COLUMN embedding BYTEA")
# axis_vector: float32 BYTEA, fixed-order flattened over MUSIC_ANALYSIS_AXES.
cur.execute("SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'lyrics_embedding' AND column_name = 'axis_vector')")
if not cur.fetchone()[0]: cur.execute("ALTER TABLE lyrics_embedding ADD COLUMN axis_vector BYTEA")
cur.execute("SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'lyrics_embedding' AND column_name = 'updated_at')")
if not cur.fetchone()[0]: cur.execute("ALTER TABLE lyrics_embedding ADD COLUMN updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
# Create 'clap_embedding' table for CLAP text search embeddings
cur.execute("CREATE TABLE IF NOT EXISTS clap_embedding (item_id TEXT PRIMARY KEY, FOREIGN KEY (item_id) REFERENCES score (item_id) ON DELETE CASCADE)")
cur.execute("SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'clap_embedding' AND column_name = 'embedding')")
if not cur.fetchone()[0]: cur.execute("ALTER TABLE clap_embedding ADD COLUMN embedding BYTEA")
# Create 'voyager_index_data' table
cur.execute("CREATE TABLE IF NOT EXISTS voyager_index_data (index_name VARCHAR(255) PRIMARY KEY, index_data BYTEA NOT NULL, id_map_json TEXT NOT NULL, embedding_dimension INTEGER NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)")
# Create 'clap_index_data' table for stored CLAP text search indexes
cur.execute("CREATE TABLE IF NOT EXISTS clap_index_data (index_name VARCHAR(255) PRIMARY KEY, index_data BYTEA NOT NULL, id_map_json TEXT NOT NULL, embedding_dimension INTEGER NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)")
# Create 'lyrics_index_data' table for stored Lyrics voyager indexes (mirrors clap_index_data; supports chunked storage).
cur.execute("CREATE TABLE IF NOT EXISTS lyrics_index_data (index_name VARCHAR(255) PRIMARY KEY, index_data BYTEA NOT NULL, id_map_json TEXT NOT NULL, embedding_dimension INTEGER NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)")
# Create 'lyrics_axes_index_data' table for the axis-vector voyager index (one binary-friendly vector per song over MUSIC_ANALYSIS_AXES labels).
cur.execute("CREATE TABLE IF NOT EXISTS lyrics_axes_index_data (index_name VARCHAR(255) PRIMARY KEY, index_data BYTEA NOT NULL, id_map_json TEXT NOT NULL, embedding_dimension INTEGER NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)")
# Create 'artist_index_data' table for artist GMM-based HNSW index
cur.execute("CREATE TABLE IF NOT EXISTS artist_index_data (index_name VARCHAR(255) PRIMARY KEY, index_data BYTEA NOT NULL, artist_map_json TEXT NOT NULL, gmm_params_json TEXT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)")
# Create 'artist_metadata_data' table for the per-artist auxiliary
# metadata blob (artist_map + GMM params). Decoupled from the Voyager
# index binary and segmented independently so a single column value
# never crosses PG's 1 GB MaxAllocSize cap, regardless of library size.
cur.execute("CREATE TABLE IF NOT EXISTS artist_metadata_data (name VARCHAR(255) PRIMARY KEY, blob_data BYTEA NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)")
# Create 'map_projection_data' table for precomputed 2D map projections
cur.execute("CREATE TABLE IF NOT EXISTS map_projection_data (index_name VARCHAR(255) PRIMARY KEY, projection_data BYTEA NOT NULL, id_map_json TEXT NOT NULL, embedding_dimension INTEGER NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)")
# Create 'artist_component_projection' table for precomputed 2D artist component projections
cur.execute("CREATE TABLE IF NOT EXISTS artist_component_projection (index_name VARCHAR(255) PRIMARY KEY, projection_data BYTEA NOT NULL, artist_component_map_json TEXT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)")
# Create 'cron' table to hold scheduled jobs (very small and simple)
cur.execute("CREATE TABLE IF NOT EXISTS cron (id SERIAL PRIMARY KEY, name TEXT, task_type TEXT NOT NULL, cron_expr TEXT NOT NULL, enabled BOOLEAN DEFAULT FALSE, last_run DOUBLE PRECISION, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)")
# Create 'audiomuse_users' table. Every account (including the
# install-time admin) lives here. 'role' is 'admin' or 'user'.
cur.execute("CREATE TABLE IF NOT EXISTS audiomuse_users (id SERIAL PRIMARY KEY, username TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL, role TEXT NOT NULL DEFAULT 'user', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)")
# Lightweight migration for installs that already have the table without a role column.
cur.execute("ALTER TABLE audiomuse_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user'")
# Create 'dashboard_stats' singleton table (id fixed to 1) that holds
# precomputed content/library aggregates and index counts. Refreshed
# at app startup and hourly by a background job so the dashboard
# does not have to scan the whole `score` table on every poll.
cur.execute(
"CREATE TABLE IF NOT EXISTS dashboard_stats ("
"id INTEGER PRIMARY KEY, "
"updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, "
"content JSONB NOT NULL DEFAULT '{}'::jsonb, "
"indexes JSONB NOT NULL DEFAULT '[]'::jsonb, "
"CONSTRAINT dashboard_stats_singleton CHECK (id = 1))"
)
# Ensure older restored DBs still have the primary key constraint.
cur.execute(
"SELECT COUNT(*) FROM information_schema.table_constraints "
"WHERE table_name = 'dashboard_stats' AND constraint_type = 'PRIMARY KEY'"
)
row = cur.fetchone()
if row and row[0] == 0:
logger.info("Cleaning dashboard_stats and adding missing primary key constraint to dashboard_stats.id")
cur.execute("DELETE FROM dashboard_stats")
cur.execute("ALTER TABLE dashboard_stats ADD CONSTRAINT dashboard_stats_pkey PRIMARY KEY (id)")
# Create 'artist_mapping' table to map artist names to media server artist IDs
cur.execute("CREATE TABLE IF NOT EXISTS artist_mapping (artist_name TEXT PRIMARY KEY, artist_id TEXT)")
# Create application configuration table to persist setup values.
cur.execute(
"SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'app_config')"
)
if not cur.fetchone()[0]:
cur.execute(
"CREATE TABLE app_config ("
"key TEXT PRIMARY KEY, value TEXT NOT NULL, "
"updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)"
)
# Create 'alchemy_anchors' table to persist named user anchors for reuse
cur.execute("CREATE TABLE IF NOT EXISTS alchemy_anchors (id SERIAL PRIMARY KEY, name TEXT UNIQUE NOT NULL, centroid JSONB NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)")
cur.execute("CREATE TABLE IF NOT EXISTS alchemy_radios (id SERIAL PRIMARY KEY, anchor_id INTEGER UNIQUE NOT NULL REFERENCES alchemy_anchors(id) ON DELETE CASCADE, temperature DOUBLE PRECISION NOT NULL, n_results INTEGER NOT NULL, enabled BOOLEAN NOT NULL DEFAULT TRUE, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)")
# Provider migration tool: wizard session state (one row per migration attempt)
cur.execute("""
CREATE TABLE IF NOT EXISTS migration_session (
id SERIAL PRIMARY KEY,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
completed_at TIMESTAMP,
status TEXT NOT NULL DEFAULT 'in_progress',
source_type TEXT NOT NULL,
target_type TEXT NOT NULL,
target_creds TEXT NOT NULL,
state JSONB NOT NULL DEFAULT '{}'
)
""")
# Create 'text_search_queries' table for precomputed CLAP text search queries
cur.execute("""
CREATE TABLE IF NOT EXISTS text_search_queries (
id SERIAL PRIMARY KEY,
query_text TEXT NOT NULL,
score REAL NOT NULL,
rank INTEGER NOT NULL,
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE(rank)
)
""")
cur.execute("CREATE INDEX IF NOT EXISTS idx_text_search_queries_rank ON text_search_queries(rank)")
# Insert default queries if table is empty
cur.execute("SELECT COUNT(*) FROM text_search_queries")
count = cur.fetchone()[0]
if count == 0:
default_queries = [
"female vocal romantic trap",
"synth indie pop raspy",
"sad hard rock male vocal",
"funk falsetto energetic",
"groovy sax blues",
"classical relaxed piano",
"belting jazz happy",
"tabla afrobeat fast-paced",
"harmonized vocals slow-paced electronica",
"autotuned gospel excited",
"breathy aggressive house",
"smooth folk mid-tempo",
"deep voice r&b dark",
"punk guitar angry",
"metal choir dreamy",
"chant reggae trumpet",
"high-pitched brass hip-hop",
"disco whispered drum machine",
"happy whispered indie pop",
"synth energetic raspy",
"rock slow-paced cello",
"falsetto jazz excited",
"r&b male vocal romantic",
"harmonized vocals dark trap",
"smooth blues sax",
"high-pitched fast-paced soul",
"female vocal sad hip-hop",
"congas aggressive soul",
"mid-tempo afrobeat autotuned",
"belting funk groovy",
"angry alternative breathy",
"gospel choir steelpan",
"viola relaxed folk",
"dreamy rhodes metal",
"acoustic guitar country chant",
"deep voice orchestra reggae",
"fast-paced synth progressive rock",
"hard rock raspy romantic",
"fast-paced electric guitar progressive rock",
"hard rock aggressive breathy",
"rock high-pitched energetic",
"autotuned energetic hip-hop",
"raspy fast-paced blues",
"belting electronica energetic",
"whispered indie pop aggressive",
"harmonized vocals aggressive synth",
"orchestra whispered romantic",
"belting mid-tempo progressive rock",
"autotuned pop mid-tempo",
"pop energetic synthesizer"
]
for rank, query in enumerate(default_queries, start=1):
cur.execute("""
INSERT INTO text_search_queries (query_text, score, rank, created_at)
VALUES (%s, %s, %s, NOW())
""", (query, 1.0, rank))
logger.info(f"Inserted {len(default_queries)} default DCLAP search queries")
db.commit()
# Release the advisory lock acquired at the top of init_db().
finally:
cur.execute("SELECT pg_advisory_unlock(726354821)")
# --- Status Constants ---
TASK_STATUS_PENDING = "PENDING"
TASK_STATUS_STARTED = "STARTED"
TASK_STATUS_PROGRESS = "PROGRESS"
TASK_STATUS_SUCCESS = "SUCCESS"
TASK_STATUS_FAILURE = "FAILURE"
TASK_STATUS_REVOKED = "REVOKED"
# --- DB Cleanup Utility ---
def clean_up_previous_main_tasks():
"""
Cleans up all previous main tasks before a new one starts.
- Archives tasks in SUCCESS state.
- Archives stale tasks stuck in PENDING, STARTED, or PROGRESS states.
- DELETES all child tasks associated with archived parent tasks to prevent DB bloat.
A main task is identified by having a NULL parent_task_id.
"""
db = get_db() # This now calls the function within this file
cur = db.cursor(cursor_factory=DictCursor)
logger.info("Starting cleanup of all previous main tasks.")
non_terminal_statuses = (TASK_STATUS_PENDING, TASK_STATUS_STARTED, TASK_STATUS_PROGRESS, TASK_STATUS_SUCCESS)
try:
cur.execute("SELECT task_id, status, details, task_type, start_time, end_time FROM task_status WHERE status IN %s AND parent_task_id IS NULL", (non_terminal_statuses,))
tasks_to_archive = cur.fetchall()
archived_count = 0
deleted_children_count = 0
for task_row in tasks_to_archive:
task_id = task_row['task_id']
original_status = task_row['status']
original_details_json = task_row['details']
original_status_message = f"Task was in '{original_status}' state."
original_details_dict = None
if original_details_json:
try:
original_details_dict = json.loads(original_details_json)
original_status_message = original_details_dict.get("status_message", original_status_message)
except (json.JSONDecodeError, TypeError):
logger.warning(f"Could not parse original details for task {task_id} during archival.")
# Record into persistent history BEFORE deleting children — the
# note builder needs to query subtasks (e.g. tracks_analyzed).
try:
duration_s = None
if task_row['start_time'] is not None:
end = task_row['end_time'] if task_row['end_time'] is not None else time.time()
duration_s = max(0.0, float(end) - float(task_row['start_time']))
final_status = TASK_STATUS_SUCCESS if original_status == TASK_STATUS_SUCCESS else TASK_STATUS_REVOKED
record_task_history(
task_id, task_row['task_type'], final_status,
duration_s, details=original_details_dict,
)
except Exception as e_hist:
logger.debug(f"history record skipped during archive of {task_id}: {e_hist}")
if original_status == TASK_STATUS_SUCCESS:
archival_reason = "New main task started, old successful task archived."
else:
archival_reason = f"New main task started, stale task (status: {original_status}) has been archived."
archived_details = {
"log": [f"[Archived] {archival_reason}. Original summary: {original_status_message}"],
"original_status_before_archival": original_status,
"archival_reason": archival_reason
}
archived_details_json = json.dumps(archived_details)
with db.cursor() as update_cur:
# First, delete all child tasks to prevent DB bloat and avoid counting old tasks
update_cur.execute(
"DELETE FROM task_status WHERE parent_task_id = %s",
(task_id,)
)
children_deleted = update_cur.rowcount
deleted_children_count += children_deleted
if children_deleted > 0:
logger.info(f"Deleted {children_deleted} child tasks for parent task {task_id}")
# Then archive the parent task
update_cur.execute(
"UPDATE task_status SET status = %s, details = %s, progress = 100, timestamp = NOW() WHERE task_id = %s AND status = %s",
(TASK_STATUS_REVOKED, archived_details_json, task_id, original_status)
)
archived_count += 1
if archived_count > 0:
db.commit()
logger.info(f"Archived {archived_count} previous main tasks and deleted {deleted_children_count} child tasks.")
else:
logger.info("No previous main tasks found to clean up.")
except Exception as e_main_clean:
db.rollback()
logger.error(f"Error during the main task cleanup process: {e_main_clean}")
finally:
cur.close()
# ---------------------------------------------------------------------------
# Task history (separate from task_status — survives the global Cancel button)
# ---------------------------------------------------------------------------
TASK_HISTORY_MAX_ROWS = 10
def _build_task_note(task_type, details_obj, db):
"""Build a short, human-readable note for a finished task.
Looks at the ``details`` JSON we stored on the main task and, when needed,
queries subtasks to compute a meaningful number (e.g. total songs analyzed
across all album_analysis subtasks)."""
if not isinstance(details_obj, dict):
details_obj = {}
t = (task_type or '').lower()
try:
if 'analysis' in t:
# Prefer summing tracks_analyzed from album_analysis subtasks.
try:
with db.cursor() as cur:
cur.execute(
"SELECT details FROM task_status WHERE parent_task_id = %s AND status = 'SUCCESS'",
(details_obj.get('_task_id') or '',),
)
rows = cur.fetchall()
except Exception:
rows = []
songs = 0
for (d,) in rows or []:
if not d:
continue
try:
obj = json.loads(d)
if isinstance(obj, dict):
v = obj.get('tracks_analyzed')
if isinstance(v, (int, float)):
songs += int(v)
except Exception:
continue
if songs > 0:
return f"Songs analyzed: {songs}"
# Fallback to album-level info from the main task details.
albums = details_obj.get('albums_completed') or details_obj.get('total_albums_processed')
if albums:
return f"Albums analyzed: {albums}"
return ''
if 'clean' in t:
for k in ('tracks_deleted', 'orphans_removed', 'songs_cleaned',
'tracks_removed', 'deleted_count', 'cleaned_tracks'):
v = details_obj.get(k)
if isinstance(v, (int, float)):
return f"Songs cleaned: {int(v)}"
return ''
if 'cluster' in t:
sampled = (details_obj.get('best_params') or {}).get('initial_subset_size') \
if isinstance(details_obj.get('best_params'), dict) else None
if sampled is None:
sampled = details_obj.get('sampled_songs') or details_obj.get('num_sampled_songs')
n_clusters = details_obj.get('num_playlists_created') or details_obj.get('num_clusters')
parts = []
if sampled:
parts.append(f"sampled: {int(sampled)}")
if n_clusters:
parts.append(f"clusters: {int(n_clusters)}")
return ' • '.join(parts)
except Exception as e:
logger.debug(f"task note builder failed for type={task_type}: {e}")
return ''
def record_task_history(task_id, task_type, status, duration_seconds=None, note=None, details=None):
"""Insert a row into ``task_history`` and trim the table to the most
recent ``TASK_HISTORY_MAX_ROWS`` entries.
Safe to call from anywhere; never raises. ``details`` (dict or None) is
used to build a default ``note`` when one is not provided explicitly.
If a short note cannot be inferred, fall back to the task's final
status_message or message text when available.
The history table is treated as immutable per task_id: once a task has
been recorded, we do not insert a second history row for the same task.
"""
if not task_id:
return
try:
db = get_db()
# If no note was supplied, try to infer one from details.
if note is None:
details_obj = details if isinstance(details, dict) else {}
# Pass task_id through so the analysis branch can query subtasks.
details_obj = dict(details_obj)
details_obj['_task_id'] = task_id
note = _build_task_note(task_type, details_obj, db) or ''
if not note:
note = details_obj.get('status_message') or details_obj.get('message') or ''
with db.cursor() as cur:
cur.execute(
"SELECT 1 FROM task_history WHERE task_id = %s LIMIT 1",
(task_id,)
)
if cur.fetchone():
return
cur.execute(
f"""
INSERT INTO task_history (task_id, task_type, status, duration_seconds, note, recorded_at)
VALUES (%s, %s, %s, %s, %s, {UTC_NOW_SQL})
""",
(task_id, task_type, status, duration_seconds, note),
)
# Trim — keep only the most recent rows.
cur.execute(
"""
DELETE FROM task_history
WHERE id NOT IN (
SELECT id FROM task_history ORDER BY recorded_at DESC, id DESC LIMIT %s
)
""",
(TASK_HISTORY_MAX_ROWS,),
)
db.commit()
except Exception as e:
logger.warning(f"record_task_history failed for {task_id}: {e}")
try:
db.rollback()
except Exception:
pass
def get_active_main_task(task_type=None):
"""Return the currently active main task.
If task_type is provided, only return an active task of that type.
If task_type is None, return any active main task.
"""
db = get_db()
cur = db.cursor(cursor_factory=DictCursor)
non_terminal_statuses = (TASK_STATUS_PENDING, TASK_STATUS_STARTED, TASK_STATUS_PROGRESS)
if task_type:
cur.execute("""
SELECT task_id, task_type, status, details
FROM task_status
WHERE task_type = %s AND status IN %s AND parent_task_id IS NULL
ORDER BY timestamp DESC
LIMIT 1
""", (task_type, non_terminal_statuses))
else:
cur.execute("""
SELECT task_id, task_type, status, details
FROM task_status
WHERE status IN %s AND parent_task_id IS NULL
ORDER BY timestamp DESC
LIMIT 1
""", (non_terminal_statuses,))
active_task = cur.fetchone()
cur.close()
return dict(active_task) if active_task else None
# --- DB Utility Functions (used by tasks.py and API) ---
def save_task_status(task_id, task_type, status=TASK_STATUS_PENDING, parent_task_id=None, sub_type_identifier=None, progress=0, details=None):
"""
Saves or updates a task's status in the database, using Unix timestamps for start and end times.
"""
db = get_db() # This now calls the function within this file
cur = db.cursor()
current_unix_time = time.time()
if details is not None and isinstance(details, dict):
# Log truncation logic remains the same
if status != TASK_STATUS_SUCCESS and 'log' in details and isinstance(details['log'], list):
log_list = details['log']
if len(log_list) > MAX_LOG_ENTRIES_STORED:
original_log_length = len(log_list)
details['log'] = log_list[-MAX_LOG_ENTRIES_STORED:]
details['log_storage_info'] = f"Log in DB truncated to last {MAX_LOG_ENTRIES_STORED} entries. Original length: {original_log_length}."
else:
details.pop('log_storage_info', None)
elif status == TASK_STATUS_SUCCESS:
details.pop('log_storage_info', None)
if 'log' not in details or not isinstance(details.get('log'), list) or not details.get('log'):
details['log'] = ["Task completed successfully."]
details_json = json.dumps(details) if details is not None else None
try:
# This query now handles start_time and end_time using Unix timestamps
cur.execute("""
INSERT INTO task_status (task_id, parent_task_id, task_type, sub_type_identifier, status, progress, details, timestamp, start_time, end_time)
VALUES (%s, %s, %s, %s, %s, %s, %s, NOW(), %s, CASE WHEN %s IN ('SUCCESS', 'FAILURE', 'REVOKED') THEN %s ELSE NULL END)
ON CONFLICT (task_id) DO UPDATE SET
status = EXCLUDED.status,
parent_task_id = EXCLUDED.parent_task_id,
sub_type_identifier = EXCLUDED.sub_type_identifier,
progress = EXCLUDED.progress,
details = EXCLUDED.details,
timestamp = NOW(),
start_time = COALESCE(task_status.start_time, %s),
end_time = CASE
WHEN EXCLUDED.status IN ('SUCCESS', 'FAILURE', 'REVOKED') AND task_status.end_time IS NULL
THEN %s
ELSE task_status.end_time
END
""", (task_id, parent_task_id, task_type, sub_type_identifier, status, progress, details_json, current_unix_time, status, current_unix_time, current_unix_time, current_unix_time))
db.commit()
except psycopg2.Error as e:
logger.error(f"DB Error saving task status for {task_id}: {e}")
try:
db.rollback()
logger.info(f"DB transaction rolled back for task status update of {task_id}.")
except psycopg2.Error as rb_e:
logger.error(f"DB Error during rollback for task status {task_id}: {rb_e}")
finally:
cur.close()
# Record persistent history for MAIN tasks that just reached a terminal state.
# Skip the synthetic 'unknown' placeholder inserted by the global cancel
# path (app_helper.cancel_all_jobs) — it has no real type and would show
# up as an 'unknown' row in the dashboard's recent activity table.
try:
if (
parent_task_id is None
and status in (TASK_STATUS_SUCCESS, TASK_STATUS_FAILURE, TASK_STATUS_REVOKED)
and task_type and task_type != 'unknown'
):
duration_s = None
try:
hist_cur = db.cursor()
hist_cur.execute(
"SELECT start_time, end_time FROM task_status WHERE task_id = %s",
(task_id,),
)
row = hist_cur.fetchone()
hist_cur.close()
if row and row[0] is not None:
end = row[1] if row[1] is not None else current_unix_time
duration_s = max(0.0, float(end) - float(row[0]))
except Exception:
pass
record_task_history(task_id, task_type, status, duration_s, details=details)
except Exception as e_hist:
logger.debug(f"history record skipped for {task_id}: {e_hist}")
def get_task_info_from_db(task_id):
"""Fetches task info from DB and calculates running time in Python."""
db = get_db() # This now calls the function within this file
cur = db.cursor(cursor_factory=DictCursor)
# Fetch raw columns including the Unix timestamps
cur.execute("""
SELECT
task_id, parent_task_id, task_type, sub_type_identifier, status, progress, details, timestamp, start_time, end_time
FROM task_status
WHERE task_id = %s
""", (task_id,))
row = cur.fetchone()
cur.close()
if not row:
return None
row_dict = dict(row)
current_unix_time = time.time()
start_time = row_dict.get('start_time')
end_time = row_dict.get('end_time')
# If start_time is null (old record or pre-start), duration is 0.
if start_time is None:
row_dict['running_time_seconds'] = 0.0
else:
# If end_time is null, task is running. Use current time.
effective_end_time = end_time if end_time is not None else current_unix_time
row_dict['running_time_seconds'] = max(0, effective_end_time - start_time)
return row_dict
def get_child_tasks_from_db(parent_task_id):
"""Fetches all child tasks for a given parent_task_id from the database."""
conn = get_db() # This now calls the function within this file
cur = conn.cursor(cursor_factory=DictCursor)
# MODIFIED: Select the 'details' column as well for the final check.
cur.execute("SELECT task_id, status, sub_type_identifier, details FROM task_status WHERE parent_task_id = %s", (parent_task_id,))
tasks = cur.fetchall()
cur.close()
# DictCursor returns a list of dictionary-like objects, convert to plain dicts
return [dict(row) for row in tasks]
def save_track_analysis_and_embedding(item_id, title, author, tempo, key, scale, moods, embedding_vector, energy=None, other_features=None, album=None, album_artist=None, year=None, rating=None, file_path=None):
"""Saves track analysis and embedding in a single transaction."""
def _sanitize_string(s, max_length=1000, field_name="field"):
"""Sanitize string for PostgreSQL insertion."""
if s is None:
return None
# Ensure it's a string
if not isinstance(s, str):
try:
s = str(s)
except Exception:
logger.warning(f"Could not convert {field_name} to string, using empty string")
return ""
# Remove problematic characters
# NUL byte (0x00) - PostgreSQL cannot store
s = s.replace('\x00', '')
# Remove other control characters that could cause issues
# Keep only printable ASCII, space, tab, newline, and common Unicode
s = ''.join(char for char in s if char.isprintable() or char in '\n\t ')
# Truncate to max length to prevent overly long strings
if len(s) > max_length:
logger.warning(f"{field_name} truncated from {len(s)} to {max_length} characters")
s = s[:max_length]
# Strip leading/trailing whitespace
s = s.strip()
return s
# Sanitize all string inputs with field-specific limits
title = _sanitize_string(title, max_length=500, field_name="title")
author = _sanitize_string(author, max_length=200, field_name="author")
album = _sanitize_string(album, max_length=200, field_name="album")
album_artist = _sanitize_string(album_artist, max_length=200, field_name="album_artist")
key = _sanitize_string(key, max_length=10, field_name="key")
scale = _sanitize_string(scale, max_length=10, field_name="scale")
other_features = _sanitize_string(other_features, max_length=2000, field_name="other_features")
# year: parse from various date formats and validate
def _parse_year_from_date(year_value):
"""
Parse year from various date formats.
Supports: YYYY, YYYY-MM-DD, MM-DD-YYYY, DD-MM-YYYY (with - or / separators)
"""
if year_value is None:
return None
year_str = str(year_value).strip()
if not year_str:
return None
# Try parsing as pure integer first (YYYY)
try:
year = int(year_str)
if 1000 <= year <= 2100:
return year
except (ValueError, TypeError):
pass
# Normalize separators
normalized = year_str.replace('/', '-')
parts = normalized.split('-')
if len(parts) == 3:
try:
# YYYY-MM-DD format
if len(parts[0]) == 4:
year = int(parts[0])
if 1000 <= year <= 2100:
return year
# MM-DD-YYYY or DD-MM-YYYY format
if len(parts[2]) == 4:
year = int(parts[2])
if 1000 <= year <= 2100:
return year
# 2-digit year (MM-DD-YY)
if len(parts[2]) == 2:
year = int(parts[2])
year += 2000 if year < 30 else 1900
if 1000 <= year <= 2100:
return year
except (ValueError, TypeError, IndexError):
pass
return None
year = _parse_year_from_date(year)
# rating: validate as integer 0-5 (5-star rating system)
if rating is not None:
try:
rating = int(rating)
if rating < 0 or rating > 5:
rating = None
except (ValueError, TypeError):
rating = None
file_path = _sanitize_string(file_path, max_length=1000, field_name="file_path")
mood_str = ','.join(f"{k}:{v:.3f}" for k, v in moods.items())
conn = get_db() # This now calls the function within this file
cur = conn.cursor()
try:
# Save analysis to score table
cur.execute("""
INSERT INTO score (item_id, title, author, tempo, key, scale, mood_vector, energy, other_features, album, album_artist, year, rating, file_path)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (item_id) DO UPDATE SET
title = EXCLUDED.title,
author = EXCLUDED.author,
tempo = EXCLUDED.tempo,
key = EXCLUDED.key,
scale = EXCLUDED.scale,
mood_vector = EXCLUDED.mood_vector,
energy = EXCLUDED.energy,
other_features = EXCLUDED.other_features,
album = EXCLUDED.album,
album_artist = EXCLUDED.album_artist,
year = EXCLUDED.year,
rating = EXCLUDED.rating,
file_path = EXCLUDED.file_path
""", (item_id, title, author, tempo, key, scale, mood_str, energy, other_features, album, album_artist, year, rating, file_path))
# Save embedding
if isinstance(embedding_vector, np.ndarray) and embedding_vector.size > 0:
embedding_blob = embedding_vector.astype(np.float32).tobytes()
cur.execute("""
INSERT INTO embedding (item_id, embedding) VALUES (%s, %s)
ON CONFLICT (item_id) DO UPDATE SET embedding = EXCLUDED.embedding
""", (item_id, psycopg2.Binary(embedding_blob)))
conn.commit()
except Exception as e:
conn.rollback()
logger.error("Error saving track analysis and embedding for %s: %s", item_id, e)
raise
finally:
cur.close()
def save_clap_embedding(item_id, clap_embedding_vector):
"""Saves CLAP embedding for a track."""
if clap_embedding_vector is None or (isinstance(clap_embedding_vector, np.ndarray) and clap_embedding_vector.size == 0):
return
conn = get_db()
cur = conn.cursor()
try:
embedding_blob = clap_embedding_vector.astype(np.float32).tobytes()
cur.execute("""
INSERT INTO clap_embedding (item_id, embedding) VALUES (%s, %s)
ON CONFLICT (item_id) DO UPDATE SET embedding = EXCLUDED.embedding
""", (item_id, psycopg2.Binary(embedding_blob)))
conn.commit()
except Exception as e:
conn.rollback()
logger.error(f"Error saving CLAP embedding for {item_id}: {e}")
raise
finally:
cur.close()
def get_clap_embedding(item_id):
"""Load CLAP embedding for a track from the database.
Returns:
numpy array (512-dim float32) or None if not found
"""
conn = get_db()
cur = conn.cursor()
try:
cur.execute("SELECT embedding FROM clap_embedding WHERE item_id = %s", (item_id,))
row = cur.fetchone()
if row and row[0]:
return np.frombuffer(row[0], dtype=np.float32)
return None
except Exception as e:
logger.error(f"Error loading CLAP embedding for {item_id}: {e}")
return None