-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
1241 lines (1058 loc) · 50.2 KB
/
api.py
File metadata and controls
1241 lines (1058 loc) · 50.2 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
"""
=== MIGRATION SUPABASE ===
À exécuter manuellement dans Supabase SQL Editor :
-- Migration : Focus Track Indices (Pistes favorites pour DJs/Sélecteurs)
ALTER TABLE albums
ADD COLUMN IF NOT EXISTS focus_track_indices INTEGER[] DEFAULT '{}';
Cette colonne permet de stocker les indices des pistes marquées comme "Favorites" ou "Pépites".
Exemple : [0, 2] signifie que la piste 1 (index 0) et la piste 3 (index 2) sont marquées.
"""
import sys
import io
# Configuration de l'encodage UTF-8 pour Windows
if sys.platform == 'win32':
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')
from fastapi import FastAPI, HTTPException, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Optional, List, Dict, Tuple
import difflib
import shutil
import os
import tempfile
import unicodedata
import uuid
import requests
import colorgram
from pathlib import Path
from dotenv import load_dotenv
# Charger .env depuis le répertoire du projet (évite les soucis de CWD au démarrage)
load_dotenv(dotenv_path=Path(__file__).resolve().parent / ".env")
from main import KissaCore
from supabase import create_client, Client
# --- CONFIGURATION SUPABASE ---
url: str = os.environ.get("SUPABASE_URL")
key: str = os.environ.get("SUPABASE_KEY")
if not url or not key:
print("⚠️ ATTENTION : SUPABASE_URL ou SUPABASE_KEY manquant dans le .env")
# Initialisation du client Supabase
supabase: Client = create_client(url, key)
# Création de l'application
app = FastAPI()
# --- BLOC SÉCURITÉ (CORS) ---
# Doit être placé IMMÉDIATEMENT après app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# -----------------------------
kissa = KissaCore()
# Modèles de données
class SearchRequest(BaseModel):
query: str
class AddByIdRequest(BaseModel):
discogs_id: int
class CandidateRequest(BaseModel):
query: str
class PurchaseDataUpdate(BaseModel):
"""Modèle pour mettre à jour les données d'achat (mémoire personnelle), localisation physique et notes personnelles"""
date: Optional[str] = None
location: Optional[str] = None
price: Optional[float] = None
condition: Optional[str] = None
storage_location: Optional[str] = None
mood_colors: Optional[List[str]] = None
personal_notes: Optional[str] = None
class GenerateNotesResponse(BaseModel):
"""Réponse de génération de notes éditoriales"""
editorial_notes: str
album_id: str
class SettingsUpdate(BaseModel):
"""Modèle pour mettre à jour les settings (configuration des Moods)"""
mood_config: Optional[Dict[str, str]] = None
# --- Discogs Bridge ---
DISCOGS_SPOTIFY_ARTIST_THRESHOLD = 60 # score 0-100 on artist only; below = reject Spotify match
def _normalize_for_match(s: str) -> str:
"""Normalise une chaîne pour la comparaison fuzzy (minuscules, strip, NFD)."""
if not s:
return ""
s = (s or "").strip().lower()
s = unicodedata.normalize("NFD", s)
s = "".join(c for c in s if unicodedata.category(c) != "Mn")
return s
def _similarity_score(a: str, b: str) -> float:
"""Score de similarité 0-100 entre deux chaînes (difflib)."""
na, nb = _normalize_for_match(a), _normalize_for_match(b)
if not na and not nb:
return 100.0
if not na or not nb:
return 0.0
return difflib.SequenceMatcher(None, na, nb).ratio() * 100
def get_dominant_color(image_url: str) -> Optional[str]:
"""
Returns dominant color as hex (#RRGGBB) from an image URL, or None on error.
Used by import-batch for dominant_color column.
"""
if not image_url or not str(image_url).strip():
return None
hex_str, _ = _extract_dominant_color(image_url, is_url=True)
return hex_str
def _extract_dominant_color(source: str, is_url: bool) -> Tuple[Optional[str], Optional[float]]:
"""
Extract dominant color (hex) and hue (0-360) from an image.
source: local file path or URL. is_url: True if source is a URL.
Returns (hex_str, hue_float) or (None, None) on error.
"""
path: Optional[str] = None
try:
if is_url:
if not source or not source.strip():
return (None, None)
# Headers pour éviter les erreurs 403 (Discogs bloque les requêtes sans User-Agent)
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
resp = requests.get(source, timeout=10, headers=headers)
resp.raise_for_status()
content = resp.content
if not content:
return (None, None)
tmp = tempfile.NamedTemporaryFile(suffix=".jpg", delete=False)
path = tmp.name
try:
tmp.write(content)
tmp.close()
except Exception:
try:
tmp.close()
except Exception:
pass
try:
os.unlink(path)
except OSError:
pass
return (None, None)
else:
if not source or not os.path.isfile(source):
return (None, None)
path = source
colors = colorgram.extract(path, 1)
if not colors:
return (None, None)
c = colors[0]
# Gérer les deux formats possibles de c.rgb (objet avec attributs ou tuple)
if isinstance(c.rgb, tuple):
r, g, b = c.rgb[0], c.rgb[1], c.rgb[2]
else:
r, g, b = c.rgb.r, c.rgb.g, c.rgb.b
hex_str = "#%02x%02x%02x" % (r, g, b)
# colorgram hsl: h,s,l in 0-255; convert h to 0-360
# Gérer aussi le cas où hsl pourrait être un tuple
if hasattr(c.hsl, 'h'):
h_raw = c.hsl.h
elif isinstance(c.hsl, tuple):
h_raw = c.hsl[0] if len(c.hsl) > 0 else None
else:
h_raw = None
hue_float = (h_raw / 255.0) * 360.0 if h_raw is not None else None
return (hex_str, hue_float)
except Exception as e:
print(f"Dominant color extraction failed: {e}")
return (None, None)
finally:
if is_url and path and os.path.isfile(path):
try:
os.unlink(path)
except OSError:
pass
class DiscogsCollectionItem(BaseModel):
"""Un album simplifié renvoyé par GET /discogs/collection/{username}"""
discogs_id: int
artist: str
title: str
year: Optional[str] = None
thumb: Optional[str] = None
resource_url: Optional[str] = None
cover_image: Optional[str] = None
class DiscogsImportBatchRequest(BaseModel):
"""Body de POST /discogs/import-batch : liste d'albums au format simplifié"""
albums: List[DiscogsCollectionItem]
class DiscogsImportBatchResponse(BaseModel):
"""Résumé de l'import par lots"""
processed: int
success: int
failed: int
@app.get("/")
def read_root():
return {"message": "API Kissa connectée à Supabase. Prête ! 🚀"}
@app.get("/health")
def health():
"""État des services (ex. openai_configured pour Generate Story)."""
return {"openai_configured": kissa.openai_client is not None}
@app.get("/debug/recalc-colors")
def recalc_colors():
"""
Recalcule dominant_color et dominant_hue pour les albums (ceux sans couleur ou tous).
Télécharge cover_image, extrait via colorgram, met à jour Supabase.
Retourne le nombre d'albums mis à jour.
"""
try:
response = supabase.table("albums").select("id, cover_image").execute()
rows = response.data or []
updated = 0
for row in rows:
album_id = row.get("id")
cover_image = row.get("cover_image")
if not album_id or not cover_image or not str(cover_image).strip():
continue
hex_color, hue_float = _extract_dominant_color(cover_image, is_url=True)
if hex_color is None:
continue
payload = {"dominant_color": hex_color}
if hue_float is not None:
payload["dominant_hue"] = hue_float
supabase.table("albums").update(payload).eq("id", album_id).execute()
updated += 1
return {"updated": updated}
except Exception as e:
print(f"Recalc colors failed: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.get("/library")
def get_library():
try:
response = supabase.table("albums").select("*").order("created_at", desc=True).execute()
data = response.data
print(f"Library fetch: {len(data)} items found")
return data
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.delete("/album/{album_id}")
def delete_album(album_id: str):
try:
# Note: Assure-toi que ta méthode delete existe dans main.py ou utilise supabase directement ici
# Si tu utilises supabase direct dans api.py, assure-toi d'avoir importé supabase
# Sinon, pour faire simple, on suppose que kissa a une méthode delete ou on l'ajoute
# Voici la version simple directe si tu as supabase ici, sinon via kissa:
response = supabase.table("albums").delete().eq("id", album_id).execute()
return {"message": "Album supprimé"}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/scan")
async def scan_vinyl(file: UploadFile = File(...)):
"""
1. Reçoit l'image
2. Analyse avec Kissa (Google/Discogs/Spotify)
3. Sauvegarde le résultat dans Supabase
4. Renvoie le résultat au frontend
"""
file_location = f"temp_{uuid.uuid4()}.jpg"
try:
# A. Vérification fichier vide AVANT de lancer les processus lourds
print(f"📥 Réception : {file.filename}")
contents = await file.read()
if len(contents) == 0:
raise HTTPException(status_code=400, detail="Fichier vide.")
with open(file_location, "wb") as f:
f.write(contents)
# B. Analyse Kissa
result = kissa.process(file_location)
# C. Couleur dominante (avant suppression du fichier)
dominant_color, dominant_hue = _extract_dominant_color(file_location, is_url=False)
# D. Nettoyage image après analyse
if os.path.exists(file_location):
os.remove(file_location)
# E. Vérification erreur
if result.get("status") == "error":
raise HTTPException(status_code=400, detail=result["message"])
# F. Sauvegarde dans Supabase
new_album = {
"artist": result['display']['artist'],
"title": result['display']['title'],
"cover_image": result['display']['cover_image'],
"year": result['details']['year'],
"label": result['details']['label'],
"genre": result['details']['genre'],
"spotify_url": result['links']['spotify_url'],
"discogs_url": result['links']['discogs_url'],
"tracklist": result['details']['tracklist']
}
if dominant_color is not None:
new_album["dominant_color"] = dominant_color
if dominant_hue is not None:
new_album["dominant_hue"] = dominant_hue
print("💾 Sauvegarde en base de données...")
supabase.table("albums").insert(new_album).execute()
return result
except HTTPException as he:
# Erreurs "prévues" (400/404) : on les laisse passer telles quelles
if os.path.exists(file_location):
os.remove(file_location)
raise he
except Exception as e:
# Crashs imprévus : deviennent 500
print(f"Erreur API: {e}")
if os.path.exists(file_location):
os.remove(file_location)
raise HTTPException(status_code=500, detail=str(e))
@app.post("/search-candidates")
async def get_candidates(request: CandidateRequest):
return kissa.search_candidates(request.query)
@app.post("/add-by-id")
async def add_vinyl_by_id(request: AddByIdRequest):
"""Ajoute le vinyle spécifique choisi par l'utilisateur"""
try:
result = kissa.process_by_id(request.discogs_id)
if result.get("status") == "error":
raise HTTPException(status_code=404, detail=result["message"])
cover_image_url = result.get("display", {}).get("cover_image")
dominant_color, dominant_hue = _extract_dominant_color(cover_image_url or "", is_url=True)
# Sauvegarde dans Supabase
new_album = {
"artist": result['display']['artist'],
"title": result['display']['title'],
"cover_image": result['display']['cover_image'],
"year": result['details']['year'],
"label": result['details']['label'],
"genre": result['details']['genre'],
"spotify_url": result['links']['spotify_url'],
"discogs_url": result['links']['discogs_url'],
"tracklist": result['details']['tracklist']
}
if dominant_color is not None:
new_album["dominant_color"] = dominant_color
if dominant_hue is not None:
new_album["dominant_hue"] = dominant_hue
supabase.table("albums").insert(new_album).execute()
return result
except HTTPException as he:
# Erreurs "prévues" (404) : on les laisse passer telles quelles
raise he
except Exception as e:
# Crashs imprévus : deviennent 500
raise HTTPException(status_code=500, detail=str(e))
# --- Discogs Bridge : récupération collection ---
DISCOGS_COLLECTION_MAX_ITEMS = 500
DISCOGS_PER_PAGE = 100
DISCOGS_USER_AGENT = "KissaApp/1.0 +https://github.com/kissa"
@app.get("/discogs/collection/{username}", response_model=List[DiscogsCollectionItem])
def get_discogs_collection(username: str):
"""
Récupère la collection Discogs d'un utilisateur (folder 0) et la renvoie
en liste simplifiée. Pagination gérée en interne, plafonnée à 500 items (v1).
"""
token = os.environ.get("DISCOGS_TOKEN")
if not token:
raise HTTPException(
status_code=503,
detail="DISCOGS_TOKEN manquant. Configurez-le dans .env pour accéder à la collection.",
)
headers = {
"User-Agent": DISCOGS_USER_AGENT,
"Authorization": f"Discogs token={token}",
}
all_items: List[DiscogsCollectionItem] = []
page = 1
while len(all_items) < DISCOGS_COLLECTION_MAX_ITEMS:
url = (
f"https://api.discogs.com/users/{username}/collection/folders/0/releases"
f"?page={page}&per_page={DISCOGS_PER_PAGE}"
)
try:
resp = requests.get(url, headers=headers, timeout=30)
except requests.RequestException as e:
print(f"Discogs request error: {e}")
raise HTTPException(status_code=502, detail="Discogs API indisponible.")
if resp.status_code == 401:
raise HTTPException(
status_code=401,
detail="Token Discogs invalide ou expiré.",
)
if resp.status_code == 403:
raise HTTPException(
status_code=403,
detail="Accès refusé à la collection Discogs.",
)
if resp.status_code == 404:
raise HTTPException(
status_code=404,
detail=f"Utilisateur Discogs '{username}' introuvable ou collection vide.",
)
if resp.status_code != 200:
raise HTTPException(
status_code=502,
detail=f"Discogs API a renvoyé {resp.status_code}.",
)
data = resp.json()
releases = data.get("releases") or []
pagination = data.get("pagination") or {}
for item in releases:
if len(all_items) >= DISCOGS_COLLECTION_MAX_ITEMS:
break
info = item.get("basic_information") or item
# Release ID: prefer basic_information.id (release), fallback to item.id
release_id = info.get("id") or item.get("id")
if release_id is None:
continue
artists = info.get("artists") or []
artist = "Unknown"
if artists:
names = [a.get("name") for a in artists if a.get("name")]
artist = ", ".join(names) if names else "Unknown"
title = (info.get("title") or "").strip() or "Unknown"
year_val = info.get("year")
year = str(year_val) if year_val is not None else None
thumb = info.get("thumb")
resource_url = info.get("resource_url")
cover_image = info.get("cover_image")
all_items.append(
DiscogsCollectionItem(
discogs_id=int(release_id),
artist=artist,
title=title,
year=year,
thumb=thumb,
resource_url=resource_url,
cover_image=cover_image,
)
)
pages = pagination.get("pages", 1)
if page >= pages or not releases:
break
page += 1
return all_items
def _is_empty(val, kind="str"):
"""Valeur considérée vide pour l'upsert (ne pas écraser si déjà renseigné)."""
if val is None:
return True
if kind == "str":
return (val or "").strip() == ""
if kind == "list":
return not (val if isinstance(val, list) else [])
return False
@app.post("/discogs/import-batch", response_model=DiscogsImportBatchResponse)
async def discogs_import_batch(request: DiscogsImportBatchRequest):
"""
Importe par lots des albums au format simplifié (ex. issus de GET /discogs/collection/{username}).
Upsert par discogs_id : si l'album existe, met à jour uniquement les champs vides (jamais écraser spotify_url).
Enrichissement : tracklist/label/year/genre via Spotify puis fallback Discogs ; dominant_color depuis la cover.
"""
processed = len(request.albums)
success = 0
failed = 0
for album in request.albums:
try:
# 1. Existant par discogs_id (champs nécessaires pour upsert)
select_cols = "id, discogs_id, spotify_url, tracklist, label, year, genre, cover_image, dominant_color, dominant_hue"
existing_res = (
supabase.table("albums")
.select(select_cols)
.eq("discogs_id", album.discogs_id)
.execute()
)
existing_row = existing_res.data[0] if existing_res.data and len(existing_res.data) > 0 else None
existing_id = existing_row["id"] if existing_row else None
# 1b. Fallback : si rien par discogs_id, chercher par artist + title (import manuel antérieur)
if existing_row is None:
fallback_res = (
supabase.table("albums")
.select(select_cols)
.eq("artist", album.artist)
.eq("title", album.title)
.execute()
)
if fallback_res.data and len(fallback_res.data) > 0:
existing_row = fallback_res.data[0]
existing_id = existing_row["id"]
# 2. Spotify (priorité) : tracklist + year, label, genres
spotify_url = None
cover_image = album.cover_image or album.thumb
tracklist = []
year = album.year or ""
label = ""
genre = []
try:
if kissa.sp and (album.artist or "").strip():
search_query = f"album:{album.title} artist:{album.artist}"
spotify_data = kissa.step_3_spotify(album.artist, album.title, search_query=search_query)
if spotify_data:
spotify_artist = spotify_data.get("spotify_artist") or ""
score_artist = _similarity_score(album.artist, spotify_artist)
if score_artist >= DISCOGS_SPOTIFY_ARTIST_THRESHOLD:
spotify_url = spotify_data.get("spotify_link")
if spotify_data.get("cover_hd"):
cover_image = spotify_data["cover_hd"]
tracklist = spotify_data.get("tracks") or []
year = spotify_data.get("year") or year
label = spotify_data.get("label") or ""
genre = spotify_data.get("genres") or []
except Exception as e:
print(f"Spotify lookup failed for {album.artist} - {album.title}: {e}")
# 3. Discogs fallback : si tracklist ou métadonnées manquants
if (not tracklist or _is_empty(label, "str") or _is_empty(year, "str") or _is_empty(genre, "list")):
discogs_details = kissa.get_discogs_release_details(album.discogs_id)
if discogs_details:
if not tracklist and discogs_details.get("tracklist"):
tracklist = discogs_details["tracklist"]
if _is_empty(label, "str") and discogs_details.get("label"):
label = discogs_details["label"]
if _is_empty(year, "str") and discogs_details.get("year"):
year = discogs_details["year"]
if _is_empty(genre, "list") and discogs_details.get("genre"):
genre = discogs_details["genre"]
# 4. Couleur dominante (cover_image = URL)
dominant_color, dominant_hue = (None, None)
if cover_image:
dominant_color, dominant_hue = _extract_dominant_color(cover_image, is_url=True)
discogs_url = album.resource_url or (
f"https://www.discogs.com/release/{album.discogs_id}"
)
if existing_row:
# Upsert : ne mettre à jour que les champs vides (jamais écraser spotify_url renseigné)
payload = {}
if existing_row.get("discogs_id") is None and album.discogs_id:
payload["discogs_id"] = album.discogs_id
if _is_empty(existing_row.get("spotify_url"), "str") and spotify_url:
payload["spotify_url"] = spotify_url
if _is_empty(existing_row.get("tracklist"), "list") and tracklist:
payload["tracklist"] = tracklist
if _is_empty(existing_row.get("label"), "str") and label:
payload["label"] = label
if _is_empty(existing_row.get("year"), "str") and year:
payload["year"] = year
if _is_empty(existing_row.get("genre"), "list") and genre:
payload["genre"] = genre
if _is_empty(existing_row.get("cover_image"), "str") and cover_image:
payload["cover_image"] = cover_image
if existing_row.get("dominant_color") is None and dominant_color is not None:
payload["dominant_color"] = dominant_color
if existing_row.get("dominant_hue") is None and dominant_hue is not None:
payload["dominant_hue"] = dominant_hue
if payload:
supabase.table("albums").update(payload).eq("id", existing_id).execute()
success += 1
else:
# Insert nouveau
new_album = {
"artist": album.artist,
"title": album.title,
"cover_image": cover_image,
"year": year,
"label": label,
"genre": genre,
"spotify_url": spotify_url,
"discogs_url": discogs_url,
"tracklist": tracklist,
"discogs_id": album.discogs_id,
"tags": ["Imported"],
}
if dominant_color is not None:
new_album["dominant_color"] = dominant_color
if dominant_hue is not None:
new_album["dominant_hue"] = dominant_hue
supabase.table("albums").insert(new_album).execute()
success += 1
except Exception as e:
print(f"Import failed for {album.artist} - {album.title}: {e}")
failed += 1
return DiscogsImportBatchResponse(
processed=processed,
success=success,
failed=failed,
)
@app.post("/albums/{album_id}/generate-notes")
async def generate_editorial_notes(album_id: str):
"""
Génère du contenu éditorial via GPT-4o sur l'album.
Style critique musical expert (Rolling Stone / Pitchfork mais concis).
"""
try:
# 0. Log de la requête reçue
print(f"📥 Requête reçue pour génération de story - Album ID: {album_id}")
# 1. Vérifier que le client OpenAI est disponible
if not kissa.openai_client:
print("❌ OpenAI client non disponible")
raise HTTPException(
status_code=500,
detail="OpenAI client non disponible. Vérifiez OPENAI_API_KEY dans le .env"
)
# 2. Récupérer l'album depuis Supabase (avec year)
response = supabase.table("albums").select("id, artist, title, year").eq("id", album_id).execute()
if not response.data or len(response.data) == 0:
print(f"❌ Album avec l'ID {album_id} introuvable")
raise HTTPException(status_code=404, detail=f"Album avec l'ID {album_id} introuvable")
album = response.data[0]
artist = album.get("artist", "Artiste inconnu")
title = album.get("title", "Titre inconnu")
year = album.get("year", "")
# 3. Validation des données
if not artist or artist.strip() == "" or not title or title.strip() == "":
print(f"❌ Données invalides - Artist: '{artist}', Title: '{title}'")
raise HTTPException(
status_code=400,
detail="L'album doit avoir un artiste et un titre valides pour générer une story"
)
# 4. Construire le prompt pour GPT-4o (formaté correctement)
year_info = f" ({year})" if year else ""
system_prompt = f"""Tu es le propriétaire d'un 'Jazz Kissa' (bar audiophile) à Tokyo. Tu es un expert musical passionné, poétique et précis.
Ta mission est d'écrire une courte note de pochette (Liner Note) pour l'album : {artist} - {title}{year_info}.
Règles de style :
1. **Ton :** Intime, atmosphérique, narratif. Utilise le présent de narration. Ne sois pas scolaire.
2. **Structure :**
* Commence par une phrase d'accroche sensorielle (ambiance, son, contexte).
* Raconte une anecdote spécifique sur l'enregistrement ou l'artiste (pas de biographie générale).
* Termine par une phrase sur pourquoi cet album est essentiel dans une collection.
3. **Format :** Markdown léger. Mets les mots importants en gras.
4. **Longueur :** 150 mots maximum.
5. **Langue :** Français élégant.
Exemple de ton attendu : 'Dès les premières mesures de Space is Only Noise, on entend le craquement du bois et la poussière. Nicolas Jaar ne fait pas de la techno, il sculpte le silence...'"""
user_prompt = f"Écris un texte éditorial sur l'album '{title}' de {artist}."
# 5. Appeler GPT-4o
print(f"🤖 Génération de notes éditoriales pour {artist} - {title}{year_info}...")
openai_response = kissa.openai_client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}
],
temperature=0.7,
max_tokens=300 # Limite pour garantir ~150 mots
)
editorial_notes = openai_response.choices[0].message.content.strip()
# 6. Sauvegarder dans Supabase
supabase.table("albums").update({"editorial_notes": editorial_notes}).eq("id", album_id).execute()
print(f"✅ Notes éditoriales générées et sauvegardées pour {album_id} ({artist} - {title}{year_info})")
# 7. Retourner le résultat
return GenerateNotesResponse(
editorial_notes=editorial_notes,
album_id=album_id
)
except HTTPException as he:
raise he
except Exception as e:
err = str(e).lower()
if "429" in str(e) or ("rate" in err and "limit" in err):
raise HTTPException(status_code=503, detail="AI busy, try again")
print(f"❌ Erreur lors de la génération de notes : {e}")
raise HTTPException(status_code=500, detail=f"Erreur lors de la génération de notes : {str(e)}")
@app.patch("/albums/{album_id}/context")
async def update_purchase_context(album_id: str, purchase_data: PurchaseDataUpdate):
"""
Met à jour le champ purchase_data (mémoire personnelle), storage_location et/ou mood_colors d'un album.
Permet de stocker : date, location, price, condition, storage_location, mood_colors.
"""
try:
# 1. Vérifier que l'album existe
check_response = supabase.table("albums").select("id").eq("id", album_id).execute()
if not check_response.data or len(check_response.data) == 0:
raise HTTPException(status_code=404, detail=f"Album avec l'ID {album_id} introuvable")
# 2. Construire l'objet purchase_data (seulement les champs fournis)
purchase_dict = {}
if purchase_data.date is not None:
purchase_dict["date"] = purchase_data.date
if purchase_data.location is not None:
purchase_dict["location"] = purchase_data.location
if purchase_data.price is not None:
purchase_dict["price"] = purchase_data.price
if purchase_data.condition is not None:
purchase_dict["condition"] = purchase_data.condition
has_storage = purchase_data.storage_location is not None
has_mood_colors = purchase_data.mood_colors is not None
has_personal_notes = purchase_data.personal_notes is not None
# Au moins un champ requis (purchase, storage_location, mood_colors ou personal_notes)
if not purchase_dict and not has_storage and not has_mood_colors and not has_personal_notes:
raise HTTPException(
status_code=400,
detail="Au moins un champ doit être fourni (date, location, price, condition, storage_location, mood_colors, personal_notes)"
)
update_payload = {}
if purchase_dict:
existing_response = supabase.table("albums").select("purchase_data").eq("id", album_id).execute()
existing_purchase_data = existing_response.data[0].get("purchase_data") or {}
update_payload["purchase_data"] = {**existing_purchase_data, **purchase_dict}
if has_storage:
update_payload["storage_location"] = purchase_data.storage_location
if has_mood_colors:
update_payload["mood_colors"] = purchase_data.mood_colors
if has_personal_notes:
update_payload["personal_notes"] = purchase_data.personal_notes
update_response = supabase.table("albums").update(update_payload).eq("id", album_id).execute()
if not update_response.data:
raise HTTPException(status_code=500, detail="Erreur lors de la mise à jour")
print(f"✅ Contexte d'achat mis à jour pour l'album {album_id}")
return update_response.data[0]
except HTTPException as he:
raise he
except Exception as e:
print(f"❌ Erreur lors de la mise à jour du contexte : {e}")
raise HTTPException(status_code=500, detail=f"Erreur lors de la mise à jour : {str(e)}")
@app.patch("/albums/{album_id}/toggle-track/{track_index}")
async def toggle_focus_track(album_id: str, track_index: int):
"""
Toggle le statut "Focus Track" d'une piste spécifique d'un album.
Si la piste est déjà marquée, elle est retirée. Sinon, elle est ajoutée.
"""
try:
# 1. Vérifier que l'album existe
response = supabase.table("albums").select("id, focus_track_indices, tracklist").eq("id", album_id).execute()
if not response.data or len(response.data) == 0:
raise HTTPException(status_code=404, detail=f"Album avec l'ID {album_id} introuvable")
album = response.data[0]
# 2. Valider track_index
if track_index < 0:
raise HTTPException(status_code=400, detail="track_index doit être un entier positif ou nul")
# Optionnel : vérifier que l'index correspond à une piste existante
tracklist = album.get("tracklist") or []
if tracklist and track_index >= len(tracklist):
raise HTTPException(
status_code=400,
detail=f"track_index {track_index} est hors limites (album contient {len(tracklist)} piste(s))"
)
# 3. Récupérer la liste actuelle des indices focus
current_indices = album.get("focus_track_indices") or []
# 4. Toggle : si présent, retirer ; sinon, ajouter
if track_index in current_indices:
updated_indices = [i for i in current_indices if i != track_index]
else:
updated_indices = sorted(current_indices + [track_index])
# 5. Sauvegarder dans Supabase
update_response = supabase.table("albums").update(
{"focus_track_indices": updated_indices}
).eq("id", album_id).execute()
if not update_response.data:
raise HTTPException(status_code=500, detail="Erreur lors de la mise à jour")
print(f"✅ Focus track togglé pour l'album {album_id}, piste {track_index}. Indices: {updated_indices}")
# 6. Retourner l'album mis à jour
return update_response.data[0]
except HTTPException as he:
raise he
except Exception as e:
print(f"❌ Erreur lors du toggle focus track : {e}")
raise HTTPException(status_code=500, detail=f"Erreur lors du toggle : {str(e)}")
@app.patch("/albums/{album_id}/favorite")
async def toggle_favorite(album_id: str):
"""
Toggle le statut favori (is_favorite) d'un album.
Inverse la valeur actuelle (coalesce false pour anciennes lignes).
"""
try:
response = supabase.table("albums").select("id, is_favorite").eq("id", album_id).execute()
if not response.data or len(response.data) == 0:
raise HTTPException(status_code=404, detail=f"Album avec l'ID {album_id} introuvable")
album = response.data[0]
current = album.get("is_favorite")
new_value = not (current is True)
update_response = supabase.table("albums").update(
{"is_favorite": new_value}
).eq("id", album_id).execute()
if not update_response.data:
raise HTTPException(status_code=500, detail="Erreur lors de la mise à jour")
print(f"✅ Favori togglé pour l'album {album_id}: is_favorite={new_value}")
return update_response.data[0]
except HTTPException as he:
raise he
except Exception as e:
print(f"❌ Erreur lors du toggle favori : {e}")
raise HTTPException(status_code=500, detail=f"Erreur lors du toggle : {str(e)}")
@app.post("/admin/refetch-tracks")
async def refetch_tracks():
"""
Endpoint admin pour récupérer les tracklists manquantes depuis Spotify.
Parcourt tous les albums avec tracklist vide/null et met à jour depuis Spotify.
"""
try:
# 1. Récupérer tous les albums avec tracklist vide ou null
response = supabase.table("albums").select("id, artist, title, spotify_url, tracklist").execute()
if not response.data:
return {
"processed": 0,
"updated": 0,
"failed": 0,
"details": []
}
# Filtrer les albums sans tracklist ou avec tracklist vide
albums_to_update = [
album for album in response.data
if not album.get('tracklist') or len(album.get('tracklist', [])) == 0
]
if not albums_to_update:
return {
"processed": 0,
"updated": 0,
"failed": 0,
"message": "Aucun album sans tracklist trouvé",
"details": []
}
print(f"🔄 Début du refetch pour {len(albums_to_update)} album(s)...")
updated = 0
failed = 0
details = []
# 2. Pour chaque album, récupérer la tracklist depuis Spotify
for album in albums_to_update:
album_id = album.get('id')
artist = album.get('artist', 'Unknown')
title = album.get('title', 'Unknown')
spotify_url = album.get('spotify_url')
try:
# Vérifier si spotify_url existe
if not spotify_url:
details.append({
"album_id": album_id,
"artist": artist,
"title": title,
"status": "skipped",
"reason": "Pas de spotify_url"
})
continue
# Extraire l'album_id Spotify depuis l'URL
# Format: https://open.spotify.com/album/{album_id}
try:
spotify_album_id = spotify_url.split('/album/')[1].split('?')[0].split('/')[0]
except (IndexError, AttributeError):
details.append({
"album_id": album_id,
"artist": artist,
"title": title,
"status": "failed",
"reason": "Impossible d'extraire l'ID Spotify de l'URL"
})
failed += 1
continue
# Récupérer les tracks depuis Spotify
if not kissa.sp:
details.append({
"album_id": album_id,
"artist": artist,
"title": title,
"status": "failed",
"reason": "Client Spotify non disponible"
})
failed += 1
continue
tracks = kissa._fetch_spotify_tracks(spotify_album_id)
if tracks and len(tracks) > 0:
# Mettre à jour la BDD
supabase.table("albums").update({
"tracklist": tracks
}).eq("id", album_id).execute()
updated += 1
details.append({
"album_id": album_id,
"artist": artist,
"title": title,
"status": "updated",
"tracks_count": len(tracks)
})
print(f" ✅ {artist} - {title} : {len(tracks)} pistes récupérées")
else:
details.append({
"album_id": album_id,