-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathraw_processor.py
More file actions
1526 lines (1301 loc) · 65.2 KB
/
raw_processor.py
File metadata and controls
1526 lines (1301 loc) · 65.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
"""
RAW Processor - Estrazione completa EXIF + XMP + Thumbnail ottimizzato
Sistema ottimizzato con ExifTool per tutto (metadati + thumbnail)
VERSIONE RISTRUTTURATA con OTTIMIZZAZIONE AUTOMATICA PER MODELLI AI
"""
import logging
import subprocess
import json
import tempfile
import inspect
import threading
import os
from pathlib import Path
from typing import Dict, List, Optional, Any, Union
from PIL import Image
from io import BytesIO
from utils.subprocess_utils import subprocess_creation_kwargs
# Registra il supporto HEIC/HEIF in Pillow (se pillow-heif è installato)
try:
import pillow_heif
pillow_heif.register_heif_opener()
except ImportError:
pass
logger = logging.getLogger(__name__)
class ExifToolStayOpen:
"""Processo ExifTool persistente per comandi JSON (metadati).
Usato SOLO per output testuale (JSON). I comandi binari (-b)
usano subprocess separati perché {ready} non viene emesso
dopo output binario.
Thread-safe tramite lock interno.
"""
def __init__(self):
self._proc = None
self._lock = threading.Lock()
self._call_count = 0 # contatore comandi eseguiti
def restart(self):
"""Riavvia il processo ExifTool — azzera eventuale stato accumulato."""
with self._lock:
if self._proc is not None and self._proc.poll() is None:
try:
self._proc.stdin.write(b'-stay_open\nFalse\n')
self._proc.stdin.flush()
self._proc.wait(timeout=5)
except Exception:
self._proc.terminate()
self._proc = None
self._call_count = 0
logger.info("ExifTool stay_open: processo riavviato (reset periodico)")
def _start(self):
"""Avvia il processo ExifTool in stay_open mode."""
if self._proc is not None and self._proc.poll() is None:
return
kwargs = {}
if os.name == 'nt':
kwargs['creationflags'] = 0x08000000 # CREATE_NO_WINDOW
self._proc = subprocess.Popen(
['exiftool', '-stay_open', 'True', '-@', '-'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
**kwargs
)
logger.info("ExifTool stay_open: processo avviato")
def execute_json(self, *args: str) -> list:
"""Esegue un comando ExifTool e ritorna il risultato come lista JSON.
Solo per comandi che producono output testuale (no -b).
"""
with self._lock:
# Avvia o riavvia se necessario
try:
self._start()
except Exception as e:
logger.error(f"ExifTool stay_open: impossibile avviare: {e}")
return []
cmd = '\n'.join(args) + '\n-execute\n'
try:
self._proc.stdin.write(cmd.encode('utf-8'))
self._proc.stdin.flush()
except (BrokenPipeError, OSError):
# Processo morto, riavvia e riprova una volta
logger.warning("ExifTool stay_open: processo morto, riavvio")
self._proc = None
try:
self._start()
self._proc.stdin.write(cmd.encode('utf-8'))
self._proc.stdin.flush()
except Exception as e:
logger.error(f"ExifTool stay_open: riavvio fallito: {e}")
return []
# Leggi risposta riga per riga fino a {ready}
lines = []
try:
while True:
line = self._proc.stdout.readline()
if not line:
logger.error("ExifTool stay_open: stdout chiuso inaspettatamente")
self._proc = None
break
if line.strip() == b'{ready}':
break
lines.append(line.decode('utf-8', errors='replace'))
except Exception as e:
logger.error(f"ExifTool stay_open: errore lettura: {e}")
self._proc = None
return []
self._call_count += 1
text = ''.join(lines).strip()
if text:
try:
return json.loads(text)
except json.JSONDecodeError as e:
logger.error(f"ExifTool stay_open JSON error: {e}")
return []
def close(self):
"""Chiude il processo ExifTool."""
with self._lock:
if self._proc is not None and self._proc.poll() is None:
try:
self._proc.stdin.write(b'-stay_open\nFalse\n')
self._proc.stdin.flush()
self._proc.wait(timeout=5)
except Exception:
self._proc.terminate()
logger.info("ExifTool stay_open: processo chiuso")
self._proc = None
def __del__(self):
try:
self.close()
except Exception:
pass
# Istanza globale — un solo processo ExifTool per tutta l'app
_exiftool_instance = None
_exiftool_instance_lock = threading.Lock()
def get_exiftool() -> ExifToolStayOpen:
"""Ritorna l'istanza globale ExifTool stay_open (lazy init)."""
global _exiftool_instance
if _exiftool_instance is None:
with _exiftool_instance_lock:
if _exiftool_instance is None:
_exiftool_instance = ExifToolStayOpen()
return _exiftool_instance
class CallerOptimizer:
"""Sistema di rilevamento automatico del chiamante per ottimizzazione"""
@staticmethod
def detect_caller_purpose():
"""
Rileva il contesto del chiamante per ottimizzare l'estrazione.
NON restituisce size hardcoded - le size vengono dai profili config.
Returns: (purpose, None, quality_level)
- purpose: nome del profilo da usare (es. 'clip_embedding', 'llm_vision')
- None: la size viene determinata dal profilo config
- quality_level: hint per il livello di qualità
"""
try:
# Analizza lo stack delle chiamate
stack = inspect.stack()
for frame_info in stack[2:6]: # Salta i primi 2 frame (questo metodo + extract_thumbnail)
filename = Path(frame_info.filename).name
function_name = frame_info.function
logger.debug(f"🔍 CALLER DEBUG: filename={filename}, function={function_name}")
# EMBEDDING GENERATOR - Modelli AI
if 'embedding_generator' in filename:
if 'llm' in function_name.lower():
logger.debug(f"🔍 DETECTED PURPOSE: llm_vision")
return 'llm_vision', None, 'high'
elif 'clip' in function_name.lower():
return 'clip_embedding', None, 'high'
elif 'dinov2' in function_name.lower():
return 'dinov2_embedding', None, 'high'
elif 'aesthetic' in function_name.lower():
return 'aesthetic_score', None, 'standard'
elif 'bioclip' in function_name.lower():
return 'bioclip_classification', None, 'high'
else:
return 'ai_processing', None, 'standard'
# PROCESSING TAB - Batch processing
elif 'processing_tab' in filename:
if 'ai' in function_name.lower():
return 'ai_processing', None, 'standard'
else:
return 'metadata_extraction', None, 'fast'
# GALLERY - Visualizzazione veloce
elif 'gallery' in filename:
return 'gallery_display', None, 'fast'
# LLM WORKER
elif 'llm_worker' in filename:
return 'llm_vision', None, 'high'
except Exception as e:
logger.debug(f"Caller detection failed: {e}")
# Fallback default
return 'default', None, 'standard'
class RAWProcessor:
"""Processore unificato RAW con ExifTool per tutto + ottimizzazione automatica"""
def __init__(self, config: Dict[str, Any]):
self.config = config
self.raw_config = config.get('image_processing', {}).get('raw_processing', {})
# CARICAMENTO PROFILI DA CONFIG YAML
self.optimization_enabled = config.get('image_optimization', {}).get('enabled', True)
config_profiles = config.get('image_optimization', {}).get('profiles', {})
# PROFILI OTTIMIZZATI (fallback hardcoded + override da config)
self.optimization_profiles = self._load_optimization_profiles(config_profiles)
# Dimensioni ottimali per CLIP - CRITICO per embedding validi (DEPRECATO)
self.ai_target_size = 512 # Mantenuto per compatibilità
def _load_optimization_profiles(self, config_profiles: Dict) -> Dict:
"""Carica profili ottimizzazione da config con fallback hardcoded"""
# PROFILI HARDCODED OTTIMIZZATI (fallback di sicurezza)
hardcoded_profiles = {
'llm_vision': {
'target_size': 1024,
'quality': 95,
'method': 'rawpy_full',
'resampling': 'LANCZOS',
'upscale': False
},
'clip_embedding': {
'target_size': 512,
'quality': 90,
'method': 'high_quality',
'resampling': 'LANCZOS',
'upscale': False
},
'dinov2_embedding': {
'target_size': 518,
'quality': 90,
'method': 'high_quality',
'resampling': 'LANCZOS',
'upscale': False
},
'aesthetic_score': {
'target_size': 336,
'quality': 85,
'method': 'preview_optimized',
'resampling': 'BILINEAR',
'upscale': False
},
'technical_score': {
'target_size': 512,
'quality': 90,
'method': 'preview_optimized',
'resampling': 'LANCZOS',
'upscale': False
},
'bioclip_classification': {
'target_size': 384,
'quality': 90,
'method': 'high_quality',
'resampling': 'LANCZOS',
'upscale': False
},
'ai_processing': {
'target_size': 512,
'quality': 85,
'method': 'preview_optimized',
'resampling': 'LANCZOS',
'upscale': False
},
'gallery_display': {
'target_size': 256,
'quality': 75,
'method': 'fast_thumbnail',
'resampling': 'BILINEAR',
'upscale': False
},
'metadata_extraction': {
'target_size': 256,
'quality': 75,
'method': 'fast_thumbnail',
'resampling': 'BILINEAR',
'upscale': False
},
'default': {
'target_size': 512,
'quality': 85,
'method': 'preview_optimized',
'resampling': 'LANCZOS',
'upscale': False
}
}
# Merge config con hardcoded (config ha priorità)
final_profiles = {}
for profile_name, hardcoded_profile in hardcoded_profiles.items():
config_profile = config_profiles.get(profile_name, {})
# Merge con priorità al config
merged_profile = hardcoded_profile.copy()
merged_profile.update(config_profile)
# Converti resampling string in PIL constant
merged_profile['resampling'] = self._get_resampling_method(merged_profile.get('resampling', 'LANCZOS'))
final_profiles[profile_name] = merged_profile
logger.info(f"✓ Loaded optimization profiles: {len(final_profiles)} profiles")
if config_profiles:
logger.info(f"✓ Config overrides: {list(config_profiles.keys())}")
return final_profiles
def _get_resampling_method(self, resampling_name: str):
"""Converte nome resampling in costante PIL"""
resampling_map = {
'LANCZOS': Image.Resampling.LANCZOS,
'BILINEAR': Image.Resampling.BILINEAR,
'BICUBIC': Image.Resampling.BICUBIC,
'NEAREST': Image.Resampling.NEAREST
}
return resampling_map.get(resampling_name.upper(), Image.Resampling.LANCZOS)
def get_max_target_size(self, profile_names: List[str] = None) -> int:
"""
Calcola la MAX target_size tra i profili specificati.
Utile per estrarre thumbnail una volta alla dimensione massima necessaria.
Args:
profile_names: lista di nomi profilo (es. ['clip_embedding', 'dinov2_embedding'])
Se None, usa tutti i profili AI-related
Returns:
int: la dimensione massima tra i profili
"""
if profile_names is None:
# Default: tutti i profili AI (esclusi gallery/metadata)
profile_names = [
'clip_embedding', 'dinov2_embedding', 'bioclip_classification',
'aesthetic_score', 'llm_vision', 'ai_processing'
]
max_size = self.ai_target_size # fallback default
for name in profile_names:
profile = self.optimization_profiles.get(name)
if profile:
size = profile.get('target_size', 0)
if size > max_size:
max_size = size
logger.debug(f"Max size updated: {name} → {size}px")
logger.info(f"📐 Max target size calculated: {max_size}px from profiles: {profile_names}")
return max_size
def get_profile(self, profile_name: str) -> dict:
"""
Ottiene un profilo di ottimizzazione per nome.
Args:
profile_name: nome del profilo (es. 'clip_embedding')
Returns:
dict con target_size, method, resampling, quality, upscale
"""
return self.optimization_profiles.get(profile_name, self.optimization_profiles['default'])
def extract_raw_metadata(self, raw_path: Path, local_path: Path = None) -> Dict[str, Any]:
"""
Estrazione unificata EXIF + XMP completi per tutti i formati.
raw_path: path originale (USB/rete) — usato per EXIF stay_open e sidecar XMP
local_path: path copia locale su SSD (opzionale) — usato per analisi B/N su file
non-RAW (evita lettura PIL da USB). Se None usa raw_path.
Strategia:
- RAW (ORF, CR2, etc.): EXIF embedded + XMP sidecar (.xmp)
- JPEG/TIFF: EXIF + XMP embedded
- DNG: EXIF + XMP embedded + XMP sidecar merge
"""
metadata = {
'is_raw': self.is_raw_file(raw_path),
'raw_format': raw_path.suffix.lower()[1:] if raw_path.suffix else None, # → 'orf'
'raw_info': self.get_raw_info(raw_path)
}
try:
# ===== ESTRAZIONE EXIF + XMP EMBEDDED =====
# Usa raw_path originale: ExifTool stay_open e sidecar XMP
# devono puntare al file sorgente (il sidecar è accanto all'originale)
exif_data = self._extract_with_exiftool(raw_path)
# ===== ESTRAZIONE XMP SIDECAR (solo per RAW) =====
xmp_sidecar_data = {}
if self.is_raw_file(raw_path):
xmp_sidecar_data = self._extract_xmp_sidecar(raw_path)
# ===== MERGE INTELLIGENTE =====
# Priorità: Sidecar > Embedded > Default
final_data = self._merge_xmp_data(exif_data, xmp_sidecar_data)
# ===== MAPPING CAMPI STANDARDIZZATO =====
metadata.update(self._map_all_fields(final_data))
# ===== ANALISI BIANCO/NERO (ottimizzata) =====
# Per file non-RAW usa local_path (SSD) se disponibile: PIL evita USB
_bw_path = local_path if (local_path is not None and not self.is_raw_file(raw_path)) else raw_path
try:
# Estrazione veloce dedicata per analisi B/N
bw_image = self._extract_for_bw_analysis(_bw_path)
if bw_image:
is_mono = self._is_monochrome_image(bw_image)
metadata['is_monochrome'] = 1 if is_mono else 0
logger.info(f"🎨 Analisi B/N per {raw_path.name}: {is_mono}")
# Chiudi l'immagine per liberare memoria
try:
bw_image.close()
except:
pass
else:
metadata['is_monochrome'] = 0
logger.warning(f"❌ Immagine non estratta per analisi B/N: {raw_path.name}")
except Exception as e:
logger.error(f"Errore analisi B/N per {raw_path.name}: {e}")
metadata['is_monochrome'] = 0
logger.debug(f"Estrazione completata per {raw_path.name}: {len(metadata)} campi")
except Exception as e:
logger.error(f"Errore estrazione metadata per {raw_path.name}: {e}")
return metadata
def extract_thumbnail(self, raw_path: Path, target_size: int = None, profile_name: str = None) -> Optional[Image.Image]:
"""
Estrai thumbnail da qualsiasi file con OTTIMIZZAZIONE AUTOMATICA
Il metodo di estrazione si adatta automaticamente al chiamante.
PRIORITÀ SIZE:
1. target_size esplicito (se passato)
2. profile_name esplicito → size dal profilo config
3. CallerOptimizer detection → size dal profilo config
4. Fallback default (512px)
Args:
raw_path: Path del file (RAW, JPEG, etc.)
target_size: dimensione target esplicita (opzionale)
profile_name: nome profilo da usare (opzionale, es. 'clip_embedding')
Returns:
PIL Image ottimizzata per il contesto d'uso
"""
try:
# RILEVAMENTO AUTOMATICO DEL CHIAMANTE (solo se ottimizzazione abilitata)
if self.optimization_enabled:
# Determina il profilo da usare
if profile_name:
# Profilo esplicito specificato
purpose = profile_name
else:
# Rilevamento automatico dal chiamante
purpose, _, quality_level = CallerOptimizer.detect_caller_purpose()
# Ottieni profilo di ottimizzazione
profile = self.optimization_profiles.get(purpose, self.optimization_profiles['default'])
# PRIORITÀ SIZE: esplicito > profilo config > fallback
if target_size is None:
target_size = profile.get('target_size', self.ai_target_size)
logger.info(f"🎯 Profile: {purpose} | Size: {target_size}px | Method: {profile['method']}")
# ESTRAZIONE OTTIMIZZATA IN BASE AL PROFILO
if profile['method'] == 'rawpy_full':
thumbnail = self._extract_rawpy_full_quality(raw_path, target_size, profile)
elif profile['method'] == 'high_quality':
thumbnail = self._extract_high_quality(raw_path, target_size, profile)
elif profile['method'] == 'preview_optimized':
thumbnail = self._extract_preview_optimized(raw_path, target_size, profile)
elif profile['method'] == 'fast_thumbnail':
thumbnail = self._extract_fast_thumbnail(raw_path, target_size, profile)
else:
# Fallback al metodo originale
thumbnail = self._extract_original_method(raw_path, target_size)
if thumbnail:
logger.debug(f"✓ Extracted for {purpose}: {raw_path.name} → {thumbnail.size}")
return thumbnail
else:
logger.warning(f"❌ Failed extraction for {purpose}: {raw_path.name}")
# Fallback al metodo originale
return self._extract_original_method(raw_path, target_size or self.ai_target_size)
else:
# Ottimizzazione disabilitata - usa metodo originale
logger.debug("⚠️ Optimization disabled - using original method")
return self._extract_original_method(raw_path, target_size or self.ai_target_size)
except Exception as e:
logger.error(f"Errore extract_thumbnail per {raw_path.name}: {e}")
# Fallback di emergenza
return self._extract_original_method(raw_path, target_size or self.ai_target_size)
# ===== METODI DI ESTRAZIONE OTTIMIZZATI =====
def _extract_rawpy_full_quality(self, raw_path: Path, target_size: int, profile: dict) -> Optional[Image.Image]:
"""Estrazione RAW massima qualità per LLM Vision (usa rawpy direttamente)"""
if not self.is_raw_file(raw_path):
return self._extract_high_quality(raw_path, target_size, profile)
try:
import rawpy
with rawpy.imread(str(raw_path)) as raw:
# Postprocessing completo per massima qualità
rgb = raw.postprocess(
use_camera_wb=True,
no_auto_bright=False,
output_bps=16 # 16-bit per massima qualità
)
image = Image.fromarray(rgb)
# Resize mantenendo proporzioni
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, profile['resampling'])
return image.convert('RGB')
except ImportError:
logger.warning("rawpy non disponibile - fallback a metodo alternativo")
return self._extract_high_quality(raw_path, target_size, profile)
except Exception as e:
logger.debug(f"rawpy extraction failed: {e}")
return self._extract_high_quality(raw_path, target_size, profile)
def _extract_high_quality(self, raw_path: Path, target_size: int, profile: dict) -> Optional[Image.Image]:
"""Estrazione alta qualità per modelli AI critici (BioCLIP, etc.)"""
try:
# STRATEGIA 0: Per non-RAW (TIFF, JPEG) PIL è più veloce di ExifTool
if not self.is_raw_file(raw_path):
thumbnail = self._extract_full_image_resized(raw_path, target_size)
if thumbnail and thumbnail.mode in ('RGB', 'RGBA') and min(thumbnail.size) >= 100:
logger.debug(f"🖼 PIL {raw_path.name}")
return self._resize_with_quality(thumbnail, target_size, profile)
logger.debug(f"🔧 XTL {raw_path.name} (PIL anomalo, fallback ExifTool)")
# STRATEGIA 1: Preview Image se grande (RAW o fallback non-RAW)
thumbnail = self._extract_preview_image(raw_path)
if thumbnail and max(thumbnail.size) >= 400:
thumbnail = self._resize_with_quality(thumbnail, target_size, profile)
return thumbnail
# STRATEGIA 2: JPEG from RAW
if self.is_raw_file(raw_path):
thumbnail = self._extract_jpeg_from_raw(raw_path, target_size)
if thumbnail:
return thumbnail
# STRATEGIA 3: Full image resized
thumbnail = self._extract_full_image_resized(raw_path, target_size)
if thumbnail:
return self._resize_with_quality(thumbnail, target_size, profile)
return None
except Exception as e:
logger.debug(f"High quality extraction failed: {e}")
return None
def _extract_preview_optimized(self, raw_path: Path, target_size: int, profile: dict) -> Optional[Image.Image]:
"""Estrazione bilanciata qualità/velocità per CLIP, DINOv2, Aesthetic"""
try:
# STRATEGIA 0: Per non-RAW PIL è più veloce di ExifTool
if not self.is_raw_file(raw_path):
thumbnail = self._extract_full_image_resized(raw_path, target_size)
if thumbnail and thumbnail.mode in ('RGB', 'RGBA') and min(thumbnail.size) >= 100:
logger.debug(f"🖼 PIL {raw_path.name}")
return self._resize_with_quality(thumbnail, target_size, profile)
logger.debug(f"🔧 XTL {raw_path.name} (PIL anomalo, fallback ExifTool)")
# STRATEGIA 1: Preview Image (RAW o fallback non-RAW)
thumbnail = self._extract_preview_image(raw_path)
if thumbnail and max(thumbnail.size) >= 250:
return self._resize_with_quality(thumbnail, target_size, profile)
# STRATEGIA 2: Thumbnail embedded ridimensionato
thumbnail = self._extract_thumbnail_embedded(raw_path)
if thumbnail:
return self._resize_with_quality(thumbnail, target_size, profile)
return None
except Exception as e:
logger.debug(f"Preview optimized extraction failed: {e}")
return None
def _extract_fast_thumbnail(self, raw_path: Path, target_size: int, profile: dict) -> Optional[Image.Image]:
"""Estrazione veloce per gallery e preview"""
try:
# STRATEGIA 1: Thumbnail embedded (più veloce)
thumbnail = self._extract_thumbnail_embedded(raw_path)
if thumbnail:
return self._resize_with_quality(thumbnail, target_size, profile)
# STRATEGIA 2: Preview se necessario
thumbnail = self._extract_preview_image(raw_path)
if thumbnail:
return self._resize_with_quality(thumbnail, target_size, profile)
return None
except Exception as e:
logger.debug(f"Fast thumbnail extraction failed: {e}")
return None
def _extract_original_method(self, raw_path: Path, target_size: int) -> Optional[Image.Image]:
"""Metodo di estrazione originale (fallback)"""
try:
# Per non-RAW PIL è più veloce di ExifTool
if not self.is_raw_file(raw_path):
thumbnail = self._extract_full_image_resized(raw_path, target_size)
if thumbnail and thumbnail.mode in ('RGB', 'RGBA') and min(thumbnail.size) >= 100:
logger.debug(f"🖼 PIL {raw_path.name}")
return thumbnail
logger.debug(f"🔧 XTL {raw_path.name} (PIL anomalo, fallback ExifTool)")
thumbnail = self._extract_preview_image(raw_path)
if thumbnail and max(thumbnail.size) >= 300:
thumbnail.thumbnail((target_size, target_size), Image.Resampling.LANCZOS)
return thumbnail
if self.is_raw_file(raw_path):
thumbnail = self._extract_jpeg_from_raw(raw_path, target_size)
if thumbnail:
return thumbnail
thumbnail = self._extract_thumbnail_embedded(raw_path)
if thumbnail:
thumbnail = thumbnail.resize((target_size, target_size), Image.Resampling.LANCZOS)
return thumbnail
if not self.is_raw_file(raw_path):
thumbnail = self._extract_full_image_resized(raw_path, target_size)
if thumbnail:
return thumbnail
# Ultimo tentativo: prova tag ExifTool alternativi (es. Nikon High-Efficiency)
if self.is_raw_file(raw_path):
thumbnail = self._extract_exiftool_any_preview(raw_path, target_size)
if thumbnail:
return thumbnail
return None
except Exception as e:
logger.debug(f"Original method failed: {e}")
return None
def _extract_exiftool_any_preview(self, file_path: Path, target_size: int) -> Optional[Image.Image]:
"""Ultimo tentativo per formati RAW insoliti: prova tag ExifTool alternativi in sequenza.
Utile per Nikon High-Efficiency NEF, fotocamere recenti non ancora supportate da rawpy."""
tags_to_try = [
'-LargePreview',
'-SubIFD:PreviewImage',
'-OriginalRawImage',
'-PreviewTIFF',
'-RawThumbnailImage',
]
for tag in tags_to_try:
try:
result = subprocess.run(
['exiftool', '-b', tag, str(file_path)],
capture_output=True, timeout=15,
**subprocess_creation_kwargs()
)
if result.returncode == 0 and result.stdout and len(result.stdout) > 1000:
try:
thumbnail = Image.open(BytesIO(result.stdout)).convert('RGB')
if max(thumbnail.size) > target_size:
thumbnail.thumbnail((target_size, target_size), Image.Resampling.LANCZOS)
logger.info(f"✅ ExifTool fallback ({tag}): {file_path.name} → {thumbnail.size}")
return thumbnail
except Exception:
pass
except Exception:
pass
return None
def _resize_with_quality(self, image: Image.Image, target_size: int, profile: dict) -> Image.Image:
"""Ridimensiona immagine con parametri di qualità del profilo"""
w, h = image.size
# Ridimensiona mantenendo proporzioni se necessario
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, profile['resampling'])
elif max_side < target_size and profile.get('upscale', False):
# Upscale solo se richiesto dal profilo
scale = target_size / max_side
new_size = (int(w * scale), int(h * scale))
image = image.resize(new_size, profile['resampling'])
return image.convert('RGB')
# ===== METODI ORIGINALI (mantenuti per compatibilità) =====
def _extract_thumbnail_embedded(self, file_path: Path) -> Optional[Image.Image]:
"""Estrai thumbnail embedded con ExifTool"""
try:
result = subprocess.run([
'exiftool', '-ThumbnailImage', '-b', str(file_path)
], capture_output=True, timeout=15, **subprocess_creation_kwargs())
if result.returncode == 0 and result.stdout and len(result.stdout) > 1000:
# Converti bytes in PIL Image
thumbnail = Image.open(BytesIO(result.stdout))
logger.debug(f"ExifTool thumbnail: {file_path.name} → {thumbnail.size}")
return thumbnail
except Exception as e:
logger.debug(f"ExifTool thumbnail failed for {file_path.name}: {e}")
return None
def _extract_preview_image(self, file_path: Path) -> Optional[Image.Image]:
"""Estrai preview image con ExifTool (spesso più grande del thumbnail)"""
try:
result = subprocess.run([
'exiftool', '-PreviewImage', '-b', str(file_path)
], capture_output=True, timeout=15, **subprocess_creation_kwargs())
if result.returncode == 0 and result.stdout and len(result.stdout) > 1000:
thumbnail = Image.open(BytesIO(result.stdout))
logger.debug(f"ExifTool preview: {file_path.name} → {thumbnail.size}")
return thumbnail
except Exception as e:
logger.debug(f"ExifTool preview failed for {file_path.name}: {e}")
return None
def _extract_jpeg_from_raw(self, file_path: Path, target_size: int) -> Optional[Image.Image]:
"""Estrai JPEG completo da RAW usando ExifTool (legge stdout direttamente)."""
for tag in ('-JpgFromRaw', '-OtherImage'):
try:
result = subprocess.run(
['exiftool', '-b', tag, str(file_path)],
capture_output=True, timeout=30,
**subprocess_creation_kwargs()
)
if result.returncode == 0 and result.stdout and len(result.stdout) > 1000:
try:
thumbnail = Image.open(BytesIO(result.stdout)).convert('RGB')
if max(thumbnail.size) > target_size:
thumbnail.thumbnail((target_size, target_size), Image.Resampling.LANCZOS)
logger.debug(f"ExifTool {tag}: {file_path.name} → {thumbnail.size}")
return thumbnail
except Exception:
pass
except Exception as e:
logger.debug(f"ExifTool {tag} error for {file_path.name}: {e}")
logger.debug(f"ExifTool JPEG from RAW failed for {file_path.name}")
return None
def _extract_full_image_resized(self, file_path: Path, target_size: int) -> Optional[Image.Image]:
"""Estrai e ridimensiona immagine completa (per JPEG, TIFF, etc.)"""
try:
# Apri immagine direttamente con PIL
with Image.open(file_path) as img:
img = img.convert('RGB')
w, h = img.size
# Ridimensiona solo se necessario
max_side = max(w, h)
if max_side > target_size:
scale = target_size / max_side
new_size = (int(w * scale), int(h * scale))
img = img.resize(new_size, Image.Resampling.LANCZOS)
logger.debug(f"Full image resized: {file_path.name} → {img.size}")
return img.copy()
except Exception as e:
logger.debug(f"Full image resize failed for {file_path.name}: {e}")
return None
# ===== RESTO DEI METODI ORIGINALI (invariati) =====
def _extract_with_exiftool(self, file_path: Path) -> Dict[str, Any]:
"""Estrazione EXIF + XMP embedded con ExifTool JSON.
Usa processo stay_open per eliminare l'overhead di avvio Perl per ogni foto.
Fallback a subprocess separato in caso di errore."""
try:
et = get_exiftool()
data_list = et.execute_json('-json', '-G', '-a', '-s', '-e', str(file_path))
if data_list:
return data_list[0]
logger.warning(f"ExifTool extraction failed for {file_path.name}")
return {}
except Exception as e:
# Fallback a subprocess classico
logger.warning(f"ExifTool stay_open fallback per {file_path.name}: {e}")
try:
result = subprocess.run([
'exiftool', '-json', '-G', '-a', '-s', '-e', str(file_path)
], capture_output=True, text=True, timeout=30, **subprocess_creation_kwargs())
if result.returncode == 0 and result.stdout:
data_list = json.loads(result.stdout)
if data_list:
return data_list[0]
except Exception as e2:
logger.error(f"ExifTool error for {file_path.name}: {e2}")
return {}
def _extract_xmp_sidecar(self, raw_path: Path) -> Dict[str, Any]:
"""Estrazione XMP sidecar per file RAW.
Usa processo stay_open per eliminare l'overhead di avvio Perl."""
xmp_path = raw_path.with_suffix('.xmp')
if not xmp_path.exists():
xmp_path = raw_path.with_suffix('.XMP')
if not xmp_path.exists():
return {}
try:
et = get_exiftool()
data_list = et.execute_json('-json', '-G', '-a', '-s', '-e', str(xmp_path))
if data_list:
logger.debug(f"XMP sidecar estratto: {xmp_path.name}")
return data_list[0]
except Exception as e:
logger.debug(f"Errore estrazione XMP sidecar {xmp_path.name}: {e}")
return {}
def _merge_xmp_data(self, exif_data: Dict, xmp_sidecar_data: Dict) -> Dict[str, Any]:
"""Merge intelligente dati XMP con priorità sidecar"""
merged = exif_data.copy()
# Sovrascrivi con dati sidecar (priorità alta).
# Usare `is not None` invece di `if value` per preservare valori
# numerici legittimi come 0.0 (es. coordinate GPS sull'equatore/meridiano).
for key, value in xmp_sidecar_data.items():
if value is not None and value != '':
merged[key] = value
return merged
def _map_all_fields(self, xmp_data: Dict) -> Dict[str, Any]:
"""
MAPPING UNIVERSALE con strategia GET_VAL a cascata
Supporta tutte le marche: Olympus, Canon, Nikon, Sony, DJI, etc.
"""
mapped = {}
def get_val(keys: list):
"""Cerca la prima chiave disponibile con fallback multi-prefisso"""
for k in keys:
# Prova prefissi in ordine di priorità (incluso XMP-dc per Dublin Core)
for prefix in ['XMP-dc:', 'XMP-lr:', 'XMP-xmp:', 'XMP-exif:', 'XMP:', 'EXIF:', 'GPS:', 'IFD0:', 'Main:', 'Composite:', 'IPTC:', '']:
full_key = f"{prefix}{k}" if prefix else k
if full_key in xmp_data and xmp_data[full_key]:
return xmp_data[full_key]
return None
# ===== IDENTIFICAZIONE CAMERA & LENS (Multi-brand) =====
mapped['camera_make'] = get_val(['Make', 'Manufacturer'])
mapped['camera_model'] = get_val(['Model'])
mapped['lens_model'] = get_val(['LensModel', 'LensType', 'LensID', 'Lens', 'LensInfo'])
# ===== DIMENSIONI (Risolve problema campi vuoti) =====
mapped['width'] = self._parse_int(get_val(['ExifImageWidth', 'ImageWidth', 'RelatedImageWidth']))
mapped['height'] = self._parse_int(get_val(['ExifImageHeight', 'ImageHeight', 'RelatedImageHeight']))
# Gestione speciale Composite:ImageSize formato "5184x3888"
if not mapped['width'] or not mapped['height']:
composite_size = get_val(['ImageSize'])
if composite_size and 'x' in str(composite_size):
try:
parts = str(composite_size).split('x')
if not mapped['width']:
mapped['width'] = self._parse_int(parts[0])
if not mapped['height']:
mapped['height'] = self._parse_int(parts[1])
except:
pass
# ===== PARAMETRI FOTOGRAFICI =====
mapped['focal_length'] = self._parse_numeric(get_val(['FocalLength']))
mapped['focal_length_35mm'] = self._parse_numeric(get_val(['FocalLengthIn35mmFormat', 'ScaleFactor35efl', 'FocalLengthIn35mmFilm']))
mapped['aperture'] = self._parse_numeric(get_val(['FNumber', 'ApertureValue', 'Aperture']))
mapped['iso'] = self._parse_int(get_val(['ISO', 'ISOSpeedRatings']))
# Shutter speed con doppio formato
raw_shutter = get_val(['ExposureTime', 'ShutterSpeed', 'ShutterSpeedValue'])
mapped['shutter_speed'] = self._format_shutter_speed(raw_shutter)
mapped['shutter_speed_decimal'] = self._parse_shutter_speed_decimal(raw_shutter)
# ===== IMPOSTAZIONI ESPOSIZIONE =====
mapped['exposure_mode'] = self._parse_exposure_mode(get_val(['ExposureMode']))
mapped['exposure_bias'] = self._parse_numeric(get_val(['ExposureBias', 'ExposureCompensation']))
mapped['metering_mode'] = get_val(['MeteringMode'])
mapped['white_balance'] = get_val(['WhiteBalance'])
mapped['flash_used'] = self._parse_flash_used(get_val(['Flash']))
mapped['flash_mode'] = get_val(['FlashMode'])
mapped['color_space'] = get_val(['ColorSpace'])
mapped['orientation'] = self._parse_orientation(get_val(['Orientation']))
# ===== DATE E ORA =====
mapped['datetime_original'] = self._normalize_datetime(get_val(['DateTimeOriginal', 'CreateDate']))
mapped['datetime_digitized'] = self._normalize_datetime(get_val(['DateTimeDigitized']))
mapped['datetime_modified'] = self._normalize_datetime(get_val(['FileModifyDate']))
# ===== GPS =====
lat_ref = get_val(['GPSLatitudeRef'])
lon_ref = get_val(['GPSLongitudeRef'])
mapped['gps_latitude'] = self._parse_gps_coordinate(get_val(['GPSLatitude']), lat_ref)
mapped['gps_longitude'] = self._parse_gps_coordinate(get_val(['GPSLongitude']), lon_ref)
mapped['gps_altitude'] = self._parse_numeric(get_val(['GPSAltitude']))
mapped['gps_direction'] = self._parse_numeric(get_val(['GPSDirection', 'GPSImgDirection']))
# ===== GPS LOCATION =====
mapped['gps_city'] = get_val(['City'])
mapped['gps_state'] = get_val(['State', 'Province'])
mapped['gps_country'] = get_val(['Country', 'Country-PrimaryLocationName'])
mapped['gps_location'] = get_val(['Location', 'SubLocation', 'Sub-location'])
# ===== CALCOLI DERIVATI =====
if mapped.get('width') and mapped.get('height'):
mapped['aspect_ratio'] = round(mapped['width'] / mapped['height'], 3)
mapped['megapixels'] = round((mapped['width'] * mapped['height']) / 1000000, 2)
# ===== FILE INFO =====
mapped['file_size'] = self._parse_int(get_val(['FileSize']))
mapped['file_format'] = self._extract_format(get_val(['FileType']))
# ===== AUTHOR/COPYRIGHT =====
mapped['artist'] = get_val(['Artist', 'Creator'])
mapped['copyright'] = get_val(['Copyright', 'Rights'])
mapped['software'] = get_val(['Software'])
# ===== METADATA =====
mapped['title'] = get_val(['Title', 'ObjectName'])
mapped['description'] = get_val(['Description', 'Caption-Abstract'])
# ===== LIGHTROOM/XMP =====
# Rating con priorità Adobe-first: XMP-xmp > XMP-lr > EXIF > Microsoft > Altri
mapped['lr_rating'] = self._extract_rating_with_priority(xmp_data)
# Color Label con priorità Adobe-first
mapped['color_label'] = self._extract_color_label_with_priority(xmp_data)
mapped['lr_instructions'] = get_val(['Instructions'])
# ===== KEYWORDS/TAGS =====
keywords_raw = get_val(['Keywords', 'Subject'])
mapped['tags'] = self._extract_keywords_as_json(keywords_raw)
# ===== EXIF COMPLETO JSON =====
mapped['exif_json'] = json.dumps(xmp_data, ensure_ascii=False)
# Pulizia finale - rimuovi None/vuoti
return {k: v for k, v in mapped.items() if v is not None and v != ''}
def _extract_keywords_as_json(self, keywords_raw) -> Optional[str]:
"""
Converte keywords XMP in formato JSON per database
Supporta:
- JSON: ["tag1", "tag2"]
- CSV: "tag1, tag2, tag3"
- Lista: [tag1, tag2]
"""
if not keywords_raw:
return None