-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathembedding_generator.py
More file actions
2503 lines (2174 loc) · 120 KB
/
embedding_generator.py
File metadata and controls
2503 lines (2174 loc) · 120 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
"""
Embedding Generator - Generazione embedding per ricerca semantica e similarita
Modelli: CLIP (semantica), DINOv2 (visiva), Aesthetic, MUSIQ (qualità tecnica), BioCLIP (natura)
LLM: Qwen2-VL via Ollama per descrizioni e tag AI
"""
import logging
import numpy as np
from pathlib import Path
from typing import Dict, List, Optional
import warnings
import os
from utils.paths import get_app_dir
from utils.tag_utils import normalize_tags
warnings.filterwarnings('ignore')
os.environ['TRANSFORMERS_VERBOSITY'] = 'error'
logger = logging.getLogger(__name__)
class EmbeddingGenerator:
"""Generatore embedding multipli con supporto LLM Vision e BioCLIP"""
def __init__(self, config, initialization_mode='full'):
self.config = config
self.embedding_config = config.get('embedding', {})
self.enabled = self.embedding_config.get('enabled', False)
# Modelli - inizializza tutti a None
self.clip_model = None
self.clip_processor = None
self.dinov2_model = None
self.dinov2_processor = None
self.aesthetic_model = None
self.aesthetic_head = None
self.aesthetic_processor = None
self.musiq_model = None
self.musiq_available = False
self.musiq_device = 'cpu' # MUSIQ gira su CPU di default (leggero, 0.28s/foto)
self.bioclip_classifier = None
self.bioclip_on_cpu = False
# Cache immagine LLM: evita estrazione/base64 ripetute per la stessa immagine
self._llm_image_cache = {'source': None, 'base64': None, 'temp_path': None}
# Contatore foto elaborate senza GPS (GeoSpecies non attivo)
self.geospecies_skipped_no_gps = 0
# Buffer messaggi di avvio — accumulati durante __init__ prima che la tab esista.
# La tab li scarica nell'area log al momento della sua creazione.
self.startup_log: list[tuple[str, str]] = [] # lista di (messaggio, livello)
# Device per-modello (allocazione da config o auto-detect)
from device_allocator import detect_hardware, resolve_device, MODEL_VRAM_ESTIMATES
self._hardware = detect_hardware()
self._hw_backend = self._hardware['backend']
self._model_devices = {} # cache device risolti per modello
# Avviso VRAM: controlla se la somma dei modelli configurati su GPU
# supera la VRAM disponibile (solo CUDA/DirectML — MPS è unified memory).
if self._hw_backend in ('cuda', 'directml'):
vram_total = self._hardware.get('vram_total_gb') or 0.0
if vram_total > 0:
models_cfg = self.embedding_config.get('models', {})
gpu_vram_requested = sum(
MODEL_VRAM_ESTIMATES.get(key, 0)
for key, cfg in models_cfg.items()
if isinstance(cfg, dict) and cfg.get('device', 'gpu') == 'gpu'
and key in MODEL_VRAM_ESTIMATES
)
if gpu_vram_requested > vram_total * 0.90:
msg = (
f"⚠️ VRAM: i modelli configurati su GPU richiedono ~{gpu_vram_requested:.1f} GB "
f"ma la GPU ha {vram_total:.1f} GB (soglia 90% = {vram_total*0.90:.1f} GB). "
f"Alcuni modelli potrebbero fallire o scalare su CPU automaticamente."
)
logger.warning(msg)
self.startup_log.append((msg, 'warning'))
# CARICAMENTO PROFILI OTTIMIZZAZIONE DA CONFIG
self.optimization_profiles = self._load_optimization_profiles()
# Traduttore query → EN (per CLIP)
self.translator = None
if self.embedding_config.get('translation', {}).get('enabled', True):
self._init_translator()
# Traduttore EN → lingua contenuti (per ricerca tag)
self._tag_lang = self.config.get('ui', {}).get('llm_output_language', 'it')
self._tag_translator_ready = False
self._init_tag_translator()
# Plugin LLM Vision (Ollama / LM Studio / altro)
self.llm_plugin = None
self._init_llm_plugin()
# Inizializzazione selettiva
if self.enabled:
if initialization_mode == 'llm_only':
self._init_llm_only()
elif initialization_mode == 'bioclip_only':
self._init_bioclip_only()
else: # 'full' - processing batch
self._initialize_models()
def _init_llm_only(self):
"""Inizializza solo componenti LLM"""
# Il plugin viene già inizializzato in __init__ tramite _init_llm_plugin()
logger.info("Modalità LLM only - nessun modello AI caricato")
def _init_llm_plugin(self):
"""Carica il plugin LLM attivo dalla directory /plugins/.
Delegato interamente al loader: nessuna logica backend-specifica qui.
Se nessun backend è disponibile, self.llm_plugin rimane None e la
generazione tag/descrizione/titolo viene saltata con warning.
"""
try:
import sys
from utils.paths import get_app_dir
_plugins_dir = str(get_app_dir() / 'plugins')
if _plugins_dir not in sys.path:
sys.path.insert(0, _plugins_dir)
from plugins.loader import load_plugin
self.llm_plugin = load_plugin(self.config)
if self.llm_plugin:
logger.debug(f"Plugin LLM caricato: {type(self.llm_plugin).__name__}")
except Exception as e:
logger.debug(f"Plugin LLM non disponibile: {e}")
self.llm_plugin = None
def _init_bioclip_only(self):
"""Inizializza solo BioCLIP"""
models_config = self.embedding_config.get('models', {})
if models_config.get('bioclip', {}).get('enabled', False):
self._init_bioclip()
self.bioclip_enabled = hasattr(self, 'bioclip_classifier') and self.bioclip_classifier is not None
def warmup_llm(self):
"""Pre-carica il modello LLM in VRAM tramite il plugin attivo."""
if self.llm_plugin:
self.llm_plugin.warmup()
else:
logger.warning("⚠️ Nessun plugin LLM disponibile — warmup saltato")
def _device_for(self, model_key: str) -> str:
"""Restituisce device torch per un modello specifico (con cache)."""
if model_key not in self._model_devices:
from device_allocator import resolve_device
device = resolve_device(model_key, self.config, self._hw_backend)
self._model_devices[model_key] = device
logger.info(f"📍 {model_key.upper()} → device: {device}")
return self._model_devices[model_key]
def _load_optimization_profiles(self) -> Dict:
"""
Carica profili di ottimizzazione da config.
Ogni profilo definisce: target_size, method, resampling, quality
"""
from PIL import Image
config_profiles = self.config.get('image_optimization', {}).get('profiles', {})
# Profili di default (fallback)
default_profiles = {
'clip_embedding': {'target_size': 224, 'resampling': Image.Resampling.LANCZOS}, # ViT-L/14 input 224x224
'dinov2_embedding': {'target_size': 518, 'resampling': Image.Resampling.LANCZOS}, # DINOv2 input 518x518 (14x37)
'bioclip_classification': {'target_size': 224, 'resampling': Image.Resampling.LANCZOS}, # ViT-B/16 input 224x224
'aesthetic_score': {'target_size': 224, 'resampling': Image.Resampling.BILINEAR}, # CLIP-based input 224x224
'technical_score': {'target_size': 1024, 'resampling': Image.Resampling.LANCZOS}, # MUSIQ a 1024px
'llm_vision': {'target_size': 512, 'resampling': Image.Resampling.LANCZOS}, # Qwen3-VL 448-512px
'default': {'target_size': 512, 'resampling': Image.Resampling.LANCZOS}
}
# Mapping nomi resampling -> costanti PIL
resampling_map = {
'LANCZOS': Image.Resampling.LANCZOS,
'BILINEAR': Image.Resampling.BILINEAR,
'BICUBIC': Image.Resampling.BICUBIC,
'NEAREST': Image.Resampling.NEAREST
}
# Merge config con default
final_profiles = {}
for name, default_profile in default_profiles.items():
cfg_profile = config_profiles.get(name, {})
final_profiles[name] = {
'target_size': cfg_profile.get('target_size', default_profile['target_size']),
'resampling': resampling_map.get(
cfg_profile.get('resampling', 'LANCZOS').upper(),
default_profile['resampling']
)
}
return final_profiles
def _prepare_image_for_model(self, image_input, profile_name: str):
"""
Prepara immagine per un modello specifico usando il profilo configurato.
Ridimensiona alla target_size del profilo con il resampling corretto.
Args:
image_input: PIL Image, Path, o stringa path
profile_name: nome profilo (es. 'clip_embedding', 'dinov2_embedding')
Returns:
PIL Image ridimensionata secondo il profilo
"""
from PIL import Image
profile = self.optimization_profiles.get(profile_name, self.optimization_profiles['default'])
target_size = profile['target_size']
resampling = profile['resampling']
# Carica immagine se necessario
if isinstance(image_input, Image.Image):
image = image_input.copy()
elif isinstance(image_input, (str, Path)):
image = Image.open(image_input)
else:
logger.warning(f"Tipo input non supportato per prepare_image_for_model: {type(image_input)}")
return image_input
# Converti in RGB se necessario
if image.mode not in ['RGB', 'L']:
image = image.convert('RGB')
# Ridimensiona se necessario (mantiene aspect ratio)
w, h = image.size
max_side = max(w, h)
if max_side > target_size:
scale = target_size / max_side
new_size = (int(w * scale), int(h * scale))
image = image.resize(new_size, resampling)
logger.debug(f"🎯 {profile_name}: {w}x{h} → {image.size[0]}x{image.size[1]} ({resampling})")
return image
def _init_translator(self):
"""Inizializza traduttore Argos IT->EN dal repo congelato o server ufficiale"""
try:
import argostranslate.package
import argostranslate.translate
# Verifica se pacchetto IT->EN già installato
# Cattura FileNotFoundError: argostranslate crasha se trova sottodirectory
# prive di metadata.json (installazione parziale/corrotta)
try:
installed = argostranslate.package.get_installed_packages()
except Exception as e:
logger.warning(f"Argos: directory pacchetti corrotta ({e}) - pulizia in corso...")
# Rimuovi sottodirectory senza metadata.json (installazioni incomplete)
import shutil
argos_pkg_dir = Path.home() / '.local' / 'share' / 'argos-translate' / 'packages'
if argos_pkg_dir.exists():
for sub in argos_pkg_dir.iterdir():
if sub.is_dir() and not (sub / 'metadata.json').exists():
shutil.rmtree(str(sub), ignore_errors=True)
logger.info(f"Argos: rimossa directory corrotta: {sub.name}")
try:
installed = argostranslate.package.get_installed_packages()
except Exception:
installed = []
it_en_installed = any(pkg.from_code == 'it' and pkg.to_code == 'en' for pkg in installed)
if not it_en_installed:
logger.info("Argos IT->EN: installazione...")
frozen_repo = self.config.get('models_repository', {}).get('huggingface_repo', '')
models_mapping = self.config.get('models_repository', {}).get('models', {})
argos_subfolder = models_mapping.get('argos_it_en', 'argos-it-en')
downloaded = False
# Prova repo congelato
if frozen_repo:
try:
from huggingface_hub import hf_hub_download
import tempfile
import shutil
# Scarica metadata per verificare presenza
metadata_path = hf_hub_download(
repo_id=frozen_repo,
filename=f"{argos_subfolder}/metadata.json",
repo_type="model"
)
# Se arriviamo qui, il pacchetto esiste nel repo
# Scarica tutti i file necessari in temp dir
temp_dir = Path(tempfile.mkdtemp())
package_dir = temp_dir / argos_subfolder
from huggingface_hub import snapshot_download
snapshot_download(
repo_id=frozen_repo,
allow_patterns=f"{argos_subfolder}/**",
local_dir=str(temp_dir),
repo_type="model"
)
# Crea file .argosmodel (è uno zip)
import zipfile
argosmodel_path = temp_dir / "translate-it_en.argosmodel"
with zipfile.ZipFile(argosmodel_path, 'w', zipfile.ZIP_DEFLATED) as zf:
for file_path in package_dir.rglob('*'):
if file_path.is_file():
arcname = file_path.relative_to(package_dir)
zf.write(file_path, arcname)
# Installa pacchetto
argostranslate.package.install_from_path(str(argosmodel_path))
downloaded = True
logger.info("[OK] Argos IT->EN installato")
# Pulizia
shutil.rmtree(temp_dir, ignore_errors=True)
except Exception as e:
logger.warning(f"Argos: repo congelato non disponibile ({e}), uso fallback...")
# Fallback: server Argos ufficiale
if not downloaded:
try:
argostranslate.package.update_package_index()
available = argostranslate.package.get_available_packages()
pkg_to_install = None
for pkg in available:
if pkg.from_code == 'it' and pkg.to_code == 'en':
pkg_to_install = pkg
break
if pkg_to_install:
download_path = pkg_to_install.download()
argostranslate.package.install_from_path(download_path)
logger.info("[OK] Argos IT->EN installato (fallback)")
else:
logger.warning("Argos: pacchetto IT->EN non trovato nel server")
except Exception as e:
logger.warning(f"Argos fallback: {e}")
self.translator = argostranslate.translate
logger.info("[OK] Traduttore inizializzato")
except ImportError:
logger.warning("Argostranslate non disponibile - traduzioni disabilitate")
self.translator = None
def _init_tag_translator(self):
"""Verifica/installa pacchetto Argos EN→lingua_contenuti per ricerca tag.
Chiamato a startup: stesso pattern di _init_translator, nessun side effect a runtime."""
if self._tag_lang == 'en':
# I tag sono in inglese: nessuna traduzione necessaria
self._tag_translator_ready = True
return
try:
import argostranslate.package
import argostranslate.translate
import logging
logging.getLogger('argostranslate.utils').setLevel(logging.WARNING)
# Verifica se il pacchetto EN→X è già installato
try:
installed = argostranslate.package.get_installed_packages()
except Exception:
installed = []
has_pkg = any(
p.from_code == 'en' and p.to_code == self._tag_lang
for p in installed
)
if has_pkg:
self._tag_translator_ready = True
logger.info(f"[OK] Traduttore EN→{self._tag_lang} disponibile per ricerca tag")
return
# Pacchetto non installato: tenta download dall'indice ufficiale Argos
logger.warning(
f"⚠️ Pacchetto traduzione EN→{self._tag_lang} non installato. "
f"Tentativo download in corso..."
)
try:
argostranslate.package.update_package_index()
available = argostranslate.package.get_available_packages()
pkg = next(
(p for p in available
if p.from_code == 'en' and p.to_code == self._tag_lang),
None
)
if pkg:
download_path = pkg.download()
argostranslate.package.install_from_path(download_path)
self._tag_translator_ready = True
logger.info(f"[OK] Pacchetto EN→{self._tag_lang} installato — ricerca tag attiva")
else:
logger.warning(
f"⚠️ Pacchetto EN→{self._tag_lang} non trovato nell'indice Argos. "
f"La ricerca tag userà la query in inglese (risultati parziali possibili)."
)
except Exception as e:
logger.warning(
f"⚠️ Download EN→{self._tag_lang} fallito ({e}). "
f"La ricerca tag userà la query in inglese (risultati parziali possibili)."
)
except ImportError:
logger.warning("Argostranslate non disponibile — ricerca tag senza traduzione")
def _translate_to_tag_language(self, text_en: str) -> str:
"""Traduce la query EN nella lingua dei contenuti per il matching tag.
Ritorna il testo originale se la traduzione non è disponibile."""
if self._tag_lang == 'en' or not self._tag_translator_ready:
return text_en
try:
import argostranslate.translate
result = argostranslate.translate.translate(text_en, 'en', self._tag_lang)
logger.debug(f"Tag query: '{text_en}' → '{result}' ({self._tag_lang})")
return result
except Exception as e:
logger.debug(f"Traduzione EN→{self._tag_lang} fallita: {e}")
return text_en
def _get_models_dir(self) -> Path:
"""Restituisce il percorso assoluto della directory modelli dal config."""
rel = self.config.get('models_repository', {}).get('models_dir', 'Models')
p = Path(rel)
return p if p.is_absolute() else get_app_dir() / p
def _initialize_models(self):
"""Inizializza modelli abilitati.
Tutti i messaggi logger emessi durante l'init vengono anche accumulati
in self.startup_log, così la tab li mostra all'apertura.
"""
import logging as _logging
class _StartupLogHandler(_logging.Handler):
def __init__(self, buf):
super().__init__()
self._buf = buf
def emit(self, record):
level = 'warning' if record.levelno >= _logging.WARNING else 'info'
self._buf.append((record.getMessage(), level))
_handler = _StartupLogHandler(self.startup_log)
_handler.setLevel(_logging.DEBUG)
logger.addHandler(_handler)
try:
models_config = self.embedding_config.get('models', {})
if models_config.get('clip', {}).get('enabled', False):
self._init_clip()
if models_config.get('dinov2', {}).get('enabled', False):
self._init_dinov2()
if models_config.get('aesthetic', {}).get('enabled', False):
self._init_aesthetic()
# MUSIQ/Technical: valutazione qualità tecnica
if models_config.get('technical', {}).get('enabled', False):
self._init_musiq()
if models_config.get('bioclip', {}).get('enabled', False):
self._init_bioclip()
self.bioclip_enabled = hasattr(self, 'bioclip_classifier') and self.bioclip_classifier is not None
finally:
logger.removeHandler(_handler)
def _init_clip(self):
"""Inizializza CLIP: prima da models_dir locale, poi repo congelato (hf_hub_download), poi fallback ufficiale (snapshot_download)"""
try:
from transformers import CLIPProcessor, CLIPModel
models_dir = self._get_models_dir()
clip_subfolder = self.config.get('models_repository', {}).get('models', {}).get('clip', 'clip')
clip_local = models_dir / clip_subfolder
frozen_repo = self.config.get('models_repository', {}).get('huggingface_repo', '')
fallback_model = self.embedding_config.get('models', {}).get('clip', {}).get('model_name', 'laion/CLIP-ViT-B-32-laion2B-s34B-b79K')
loaded = False
# 1. Cartella locale (models_dir/clip/)
if clip_local.exists() and (clip_local / 'config.json').exists():
try:
self.clip_model = CLIPModel.from_pretrained(str(clip_local)).to(self._device_for('clip'))
self.clip_processor = CLIPProcessor.from_pretrained(str(clip_local))
loaded = True
logger.info("[OK] CLIP caricato da locale")
except Exception as e:
logger.warning(f"CLIP: cartella locale non valida ({e}), uso repo...")
# 2. Repo congelato: copia file per file come BioCLIP (evita save_pretrained)
if not loaded and frozen_repo:
try:
from huggingface_hub import hf_hub_download
import shutil as _shutil
clip_local.mkdir(parents=True, exist_ok=True)
_clip_files = [
'config.json', 'model.safetensors', 'preprocessor_config.json',
'special_tokens_map.json', 'tokenizer.json', 'tokenizer_config.json',
'vocab.json', 'merges.txt'
]
for _fname in _clip_files:
try:
_dl = hf_hub_download(
repo_id=frozen_repo,
filename=f"{clip_subfolder}/{_fname}",
repo_type="model"
)
_shutil.copy2(_dl, clip_local / _fname)
except Exception:
pass # file opzionale o non presente
if (clip_local / 'config.json').exists() and (clip_local / 'model.safetensors').exists():
self.clip_model = CLIPModel.from_pretrained(str(clip_local)).to(self._device_for('clip'))
self.clip_processor = CLIPProcessor.from_pretrained(str(clip_local))
loaded = True
logger.info("[OK] CLIP caricato da repo")
else:
logger.warning("CLIP: repo congelato incompleto, uso fallback...")
except Exception as e:
logger.warning(f"CLIP: repo congelato non disponibile ({e}), uso fallback...")
# 3. Fallback repo ufficiale: snapshot_download diretto in Models/clip/ (evita save_pretrained)
if not loaded:
try:
from huggingface_hub import snapshot_download
clip_local.mkdir(parents=True, exist_ok=True)
snapshot_download(
repo_id=fallback_model,
local_dir=str(clip_local),
local_dir_use_symlinks=False,
ignore_patterns=['*.msgpack', '*.h5', 'rust_model.ot', 'tf_model.h5', 'flax_model.msgpack']
)
self.clip_model = CLIPModel.from_pretrained(str(clip_local)).to(self._device_for('clip'))
self.clip_processor = CLIPProcessor.from_pretrained(str(clip_local))
logger.info(f"[OK] CLIP caricato e salvato (fallback: {fallback_model})")
loaded = True
except Exception as fe:
logger.error(f"CLIP: snapshot_download fallito ({fe}), provo from_pretrained in memoria...")
self.clip_model = CLIPModel.from_pretrained(fallback_model).to(self._device_for('clip'))
self.clip_processor = CLIPProcessor.from_pretrained(fallback_model)
logger.info(f"[OK] CLIP caricato in memoria senza persistenza (fallback: {fallback_model})")
loaded = True
self.clip_model.eval()
self.clip_enabled = True
# Log versione transformers per diagnostica compatibilità embedding
try:
import transformers as _tf
logger.info(f"CLIP caricato con transformers=={_tf.__version__}")
except Exception:
pass
# Log diagnostico: mostra architettura effettiva del modello caricato
try:
_vcfg = self.clip_model.vision_model.config
_proj = self.clip_model.visual_projection.weight.shape # (projection_dim, hidden_size)
logger.info(
f"CLIP architettura — hidden_size={_vcfg.hidden_size}, "
f"projection_dim={_proj[0]}, "
f"patch_size={getattr(_vcfg, 'patch_size', '?')}, "
f"num_hidden_layers={getattr(_vcfg, 'num_hidden_layers', '?')}"
)
except Exception:
pass
except Exception as e:
logger.error(f"CLIP: {e}")
self.clip_enabled = False
def _init_dinov2(self):
"""Inizializza DINOv2: prima da models_dir locale, poi repo congelato, poi fallback ufficiale"""
try:
from transformers import AutoImageProcessor, AutoModel
models_dir = self._get_models_dir()
dinov2_subfolder = self.config.get('models_repository', {}).get('models', {}).get('dinov2', 'dinov2')
dinov2_local = models_dir / dinov2_subfolder
frozen_repo = self.config.get('models_repository', {}).get('huggingface_repo', '')
fallback_model = self.embedding_config.get('models', {}).get('dinov2', {}).get('model_name', 'facebook/dinov2-base')
loaded = False
# 1. Cartella locale (models_dir/dinov2/)
if dinov2_local.exists() and (dinov2_local / 'config.json').exists():
try:
self.dinov2_model = AutoModel.from_pretrained(str(dinov2_local)).to(self._device_for('dinov2'))
self.dinov2_processor = AutoImageProcessor.from_pretrained(str(dinov2_local))
loaded = True
logger.info("[OK] DINOv2 caricato da locale")
except Exception as e:
logger.warning(f"DINOv2: cartella locale non valida ({e}), uso repo...")
# 2. Repo congelato: copia file per file (evita save_pretrained che fallisce su CUDA)
if not loaded and frozen_repo:
try:
from huggingface_hub import hf_hub_download
import shutil as _shutil
dinov2_local.mkdir(parents=True, exist_ok=True)
_dinov2_files = [
'config.json', 'model.safetensors', 'preprocessor_config.json'
]
for _fname in _dinov2_files:
try:
_dl = hf_hub_download(
repo_id=frozen_repo,
filename=f"{dinov2_subfolder}/{_fname}",
repo_type="model"
)
_shutil.copy2(_dl, dinov2_local / _fname)
except Exception:
pass # file opzionale o non presente
if (dinov2_local / 'config.json').exists() and (dinov2_local / 'model.safetensors').exists():
self.dinov2_model = AutoModel.from_pretrained(str(dinov2_local)).to(self._device_for('dinov2'))
self.dinov2_processor = AutoImageProcessor.from_pretrained(str(dinov2_local))
loaded = True
logger.info("[OK] DINOv2 caricato da repo")
else:
logger.warning("DINOv2: repo congelato incompleto, uso fallback...")
except Exception as e:
logger.warning(f"DINOv2: repo congelato non disponibile ({e}), uso fallback...")
# 3. Fallback repo ufficiale: snapshot_download diretto in Models/dinov2/
if not loaded:
try:
from huggingface_hub import snapshot_download
dinov2_local.mkdir(parents=True, exist_ok=True)
snapshot_download(
repo_id=fallback_model,
local_dir=str(dinov2_local),
local_dir_use_symlinks=False,
ignore_patterns=['*.msgpack', '*.h5', 'rust_model.ot', 'tf_model.h5', 'flax_model.msgpack']
)
self.dinov2_model = AutoModel.from_pretrained(str(dinov2_local)).to(self._device_for('dinov2'))
self.dinov2_processor = AutoImageProcessor.from_pretrained(str(dinov2_local))
logger.info(f"[OK] DINOv2 caricato e salvato (fallback: {fallback_model})")
loaded = True
except Exception as fe:
logger.error(f"DINOv2: snapshot_download fallito ({fe}), provo from_pretrained in memoria...")
self.dinov2_model = AutoModel.from_pretrained(fallback_model).to(self._device_for('dinov2'))
self.dinov2_processor = AutoImageProcessor.from_pretrained(fallback_model)
logger.info(f"[OK] DINOv2 caricato in memoria senza persistenza (fallback: {fallback_model})")
loaded = True
self.dinov2_model.eval()
self.dinov2_enabled = True
except Exception as e:
logger.error(f"DINOv2: {e}")
self.dinov2_enabled = False
def _init_aesthetic(self):
"""Inizializza Aesthetic Score: prima da models_dir locale, poi repo congelato (hf_hub_download), poi fallback ufficiale (snapshot_download)"""
try:
from transformers import CLIPProcessor, CLIPModel
import torch
import torch.nn as nn
models_dir = self._get_models_dir()
aesthetic_subfolder = self.config.get('models_repository', {}).get('models', {}).get('aesthetic', 'aesthetic')
aesthetic_dir = models_dir / aesthetic_subfolder
# Repo congelato e fallback
frozen_repo = self.config.get('models_repository', {}).get('huggingface_repo', '')
fallback_model = 'openai/clip-vit-large-patch14'
# Verifica se già presente in locale (accetta sia pytorch_model.bin che model.safetensors)
local_exists = aesthetic_dir.exists() and (
(aesthetic_dir / 'pytorch_model.bin').exists() or
(aesthetic_dir / 'model.safetensors').exists()
)
clip_model = None
# 1. Prova a caricare da directory locale (già scaricato)
if local_exists:
try:
clip_model = CLIPModel.from_pretrained(str(aesthetic_dir)).to(self._device_for('aesthetic'))
self.aesthetic_processor = CLIPProcessor.from_pretrained(str(aesthetic_dir))
logger.info("[OK] Aesthetic caricato da locale")
except Exception as e:
logger.warning(f"Aesthetic: cartella locale non valida ({e}), uso repo...")
clip_model = None
# 2. Repo congelato: copia file per file come CLIP (evita save_pretrained)
if clip_model is None and frozen_repo:
try:
from huggingface_hub import hf_hub_download
import shutil as _shutil
aesthetic_dir.mkdir(parents=True, exist_ok=True)
_aesthetic_files = [
'config.json', 'model.safetensors', 'preprocessor_config.json',
'special_tokens_map.json', 'tokenizer.json', 'tokenizer_config.json',
'vocab.json', 'merges.txt'
]
for _fname in _aesthetic_files:
try:
_dl = hf_hub_download(
repo_id=frozen_repo,
filename=f"{aesthetic_subfolder}/{_fname}",
repo_type="model"
)
_shutil.copy2(_dl, aesthetic_dir / _fname)
except Exception:
pass # file opzionale o non presente
if (aesthetic_dir / 'config.json').exists() and (aesthetic_dir / 'model.safetensors').exists():
clip_model = CLIPModel.from_pretrained(str(aesthetic_dir)).to(self._device_for('aesthetic'))
self.aesthetic_processor = CLIPProcessor.from_pretrained(str(aesthetic_dir))
logger.info("[OK] Aesthetic caricato da repo")
else:
logger.warning("Aesthetic: repo congelato incompleto, uso fallback...")
except Exception as e:
logger.error(f"Aesthetic: repo congelato fallito ({e}), uso fallback...")
clip_model = None
# 3. Fallback repo ufficiale: snapshot_download diretto in Models/aesthetic/ (evita save_pretrained)
if clip_model is None:
try:
from huggingface_hub import snapshot_download
aesthetic_dir.mkdir(parents=True, exist_ok=True)
snapshot_download(
repo_id=fallback_model,
local_dir=str(aesthetic_dir),
local_dir_use_symlinks=False,
ignore_patterns=['*.msgpack', '*.h5', 'rust_model.ot', 'tf_model.h5', 'flax_model.msgpack']
)
clip_model = CLIPModel.from_pretrained(str(aesthetic_dir)).to(self._device_for('aesthetic'))
self.aesthetic_processor = CLIPProcessor.from_pretrained(str(aesthetic_dir))
logger.info(f"[OK] Aesthetic caricato e salvato (fallback: {fallback_model})")
except Exception as fe:
logger.error(f"Aesthetic: snapshot_download fallito ({fe}), provo from_pretrained in memoria...")
clip_model = CLIPModel.from_pretrained(fallback_model).to(self._device_for('aesthetic'))
self.aesthetic_processor = CLIPProcessor.from_pretrained(fallback_model)
logger.info(f"[OK] Aesthetic caricato in memoria senza persistenza (fallback: {fallback_model})")
# Head per score estetico
pooler_dim = clip_model.vision_model.config.hidden_size
self.aesthetic_head = nn.Linear(pooler_dim, 1).to(self._device_for('aesthetic'))
torch.nn.init.xavier_normal_(self.aesthetic_head.weight)
torch.nn.init.constant_(self.aesthetic_head.bias, 0.0)
self.aesthetic_model = clip_model.vision_model
self.aesthetic_model.eval()
self.aesthetic_head.eval()
self.aesthetic_enabled = True
except Exception as e:
logger.error(f"Aesthetic: {e}")
self.aesthetic_enabled = False
def _init_musiq(self):
"""Inizializza MUSIQ per valutazione qualità tecnica.
Priorità: locale Models/musiq/ → repo HF frozen → download pyiqa.
Usa pyiqa per architettura, pesi dal repo congelato. Fallback CPU come BioCLIP."""
try:
import pyiqa
import torch
from pyiqa.archs.arch_util import load_pretrained_network
_MUSIQ_WEIGHTS = 'musiq_koniq_ckpt-e95806b9.pth'
models_dir = self._get_models_dir()
musiq_local = models_dir / 'musiq'
local_weights = musiq_local / _MUSIQ_WEIGHTS
frozen_repo = self.config.get('models_repository', {}).get('huggingface_repo', '')
# 1. Scarica pesi se non presenti in locale
if not local_weights.exists():
# Prova repo HF frozen
if frozen_repo:
try:
from huggingface_hub import hf_hub_download
import shutil as _shutil
musiq_local.mkdir(parents=True, exist_ok=True)
_dl = hf_hub_download(
repo_id=frozen_repo,
filename=f"musiq/{_MUSIQ_WEIGHTS}",
repo_type="model"
)
_shutil.copy2(_dl, local_weights)
logger.info(f"MUSIQ: pesi scaricati da repo frozen → {local_weights}")
except Exception as e:
logger.warning(f"MUSIQ: repo frozen non disponibile ({e})")
# 2. Crea modello e carica pesi
musiq_device = self._device_for('technical')
def _create_and_load(device):
if local_weights.exists():
# Crea architettura senza scaricare pesi, poi carica da locale
model = pyiqa.create_metric('musiq', device=device, pretrained=False)
load_pretrained_network(model.net, str(local_weights), strict=True)
model.net = model.net.to(device)
logger.info(f"[OK] MUSIQ: caricato da locale su {device}")
else:
# Fallback: lascia che pyiqa scarichi i pesi (primo avvio senza HF)
model = pyiqa.create_metric('musiq', device=device)
# Salva pesi in locale per avvii successivi
try:
musiq_local.mkdir(parents=True, exist_ok=True)
torch.save(model.net.state_dict(), local_weights)
logger.info(f"MUSIQ: pesi salvati in {local_weights}")
except Exception:
pass
logger.info(f"[OK] MUSIQ: caricato da pyiqa su {device}")
return model
try:
self.musiq_model = _create_and_load(musiq_device)
self.musiq_device = musiq_device
except Exception as vram_err:
# Fallback CPU per qualsiasi errore su GPU: OOM, CUDA error, VRAM satura.
# Il catch precedente (solo RuntimeError + "out of memory") non intercettava
# errori CUDA diversi (es. allocazione fallita con VRAM piena ma messaggio
# diverso), lasciando MUSIQ rosso senza tentare CPU.
if musiq_device != 'cpu':
logger.warning(
f"MUSIQ: errore su {musiq_device} "
f"({type(vram_err).__name__}: {str(vram_err)[:120]}), "
f"fallback CPU...")
self.musiq_model = _create_and_load('cpu')
self.musiq_device = 'cpu'
else:
raise
self.musiq_available = True
except ImportError:
logger.warning("MUSIQ: pyiqa non installato (pip install pyiqa)")
self.musiq_available = False
except Exception as e:
import traceback
logger.error(f"MUSIQ: errore inizializzazione: {e}\n{traceback.format_exc()}")
self.musiq_available = False
def _init_bioclip(self):
"""
Inizializza BioCLIP TreeOfLife classifier.
Priorità: cartella locale bioclip/ -> download da HuggingFace -> fallback repo ufficiale
"""
if self.bioclip_classifier is not None:
return True
try:
from bioclip import TreeOfLifeClassifier
from bioclip.predict import BaseClassifier
import open_clip
import torch
import numpy as np
import json
models_dir = self._get_models_dir()
models_mapping = self.config.get('models_repository', {}).get('models', {})
bioclip_subfolder = models_mapping.get('bioclip', 'bioclip')
treeoflife_subfolder = models_mapping.get('treeoflife', 'treeoflife')
bioclip_dir = models_dir / bioclip_subfolder
treeoflife_dir = models_dir / treeoflife_subfolder
frozen_repo = self.config.get('models_repository', {}).get('huggingface_repo', '')
# File necessari per BioCLIP
bioclip_files = ['open_clip_config.json', 'open_clip_model.safetensors']
treeoflife_files = ['txt_emb_species.npy', 'txt_emb_species.json']
# Verifica se i file locali esistono
bioclip_local_ok = bioclip_dir.exists() and all(
(bioclip_dir / f).exists() for f in bioclip_files
)
treeoflife_local_ok = treeoflife_dir.exists() and all(
(treeoflife_dir / f).exists() for f in treeoflife_files
)
# Se mancano file locali, scarica da HuggingFace
if not bioclip_local_ok or not treeoflife_local_ok:
if frozen_repo:
try:
from huggingface_hub import hf_hub_download
# Scarica BioCLIP model
if not bioclip_local_ok:
logger.info("BioCLIP: download modelli...")
bioclip_dir.mkdir(exist_ok=True)
for filename in bioclip_files:
try:
downloaded = hf_hub_download(
repo_id=frozen_repo,
filename=f"{bioclip_subfolder}/{filename}",
repo_type="model"
)
# Copia nella cartella locale
import shutil
shutil.copy2(downloaded, bioclip_dir / filename)
except Exception as e:
logger.warning(f"BioCLIP: errore download {filename}: {e}")
bioclip_local_ok = all((bioclip_dir / f).exists() for f in bioclip_files)
# Scarica TreeOfLife embeddings (sono in treeoflife/embeddings/)
if not treeoflife_local_ok:
logger.info("TreeOfLife: download embeddings...")
treeoflife_dir.mkdir(exist_ok=True)
for filename in treeoflife_files:
try:
downloaded = hf_hub_download(
repo_id=frozen_repo,
filename=f"{treeoflife_subfolder}/embeddings/{filename}",
repo_type="model"
)
import shutil
shutil.copy2(downloaded, treeoflife_dir / filename)
except Exception as e:
logger.warning(f"TreeOfLife: errore download {filename}: {e}")
treeoflife_local_ok = all((treeoflife_dir / f).exists() for f in treeoflife_files)
except Exception as e:
logger.warning(f"BioCLIP: download da repo congelato fallito ({e})")
# Carica da cartella locale se disponibile
if bioclip_local_ok and treeoflife_local_ok:
try:
# Determina device per BioCLIP (fallback CPU se VRAM insufficiente)
bioclip_device = self._device_for('bioclip')
try:
model, _, preprocess = open_clip.create_model_and_transforms(
model_name='ViT-L-14',
pretrained=str(bioclip_dir / 'open_clip_model.safetensors'),
device=bioclip_device
)
except RuntimeError as vram_err:
if 'not enough' in str(vram_err).lower() or 'out of memory' in str(vram_err).lower():
logger.warning(f"BioCLIP: VRAM insufficiente, caricamento su CPU...")
bioclip_device = 'cpu'
model, _, preprocess = open_clip.create_model_and_transforms(
model_name='ViT-L-14',
pretrained=str(bioclip_dir / 'open_clip_model.safetensors'),
device=bioclip_device
)
else:
raise
# Carica TreeOfLife embeddings
txt_emb = torch.from_numpy(
np.load(treeoflife_dir / 'txt_emb_species.npy')
).to(bioclip_device)
# Normalizza shape: il file può essere (dim, N_specie) o (N_specie, dim)
# Deve essere (N_specie, dim) per matmul con image_features (1, dim)
if txt_emb.ndim == 2 and txt_emb.shape[0] < txt_emb.shape[1]:
txt_emb = txt_emb.T
logger.info(f"TreeOfLife: embeddings trasposti → {txt_emb.shape}")
with open(treeoflife_dir / 'txt_emb_species.json', 'r') as f:
txt_names = json.load(f)
# Crea classifier wrapper compatibile con TreeOfLifeClassifier
class LocalTreeOfLifeClassifier:
"""TreeOfLifeClassifier con modello locale, interfaccia compatibile"""
def __init__(self, model, preprocess, txt_emb, txt_names, device):
self.model = model
self.preprocess = preprocess
self.txt_embeddings = txt_emb
self.txt_names = txt_names
self.device = device
def predict(self, images, rank=None, k=5, min_prob=0.0):
"""
Predice le top-k specie per una lista di immagini.
Interfaccia compatibile con TreeOfLifeClassifier.
Args:
images: Lista di PIL Images
rank: Ignorato (per compatibilità)
k: Numero di predizioni top
min_prob: Probabilità minima per includere risultato
Returns:
Lista di dict con species, genus, family, common_name, score
"""
from PIL import Image
if not images:
return []
# Prendi la prima immagine (batch di 1)
image = images[0]
if isinstance(image, (str, Path)):