This repository was archived by the owner on Nov 30, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache_manager.py
More file actions
1642 lines (1341 loc) · 55.1 KB
/
Copy pathcache_manager.py
File metadata and controls
1642 lines (1341 loc) · 55.1 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
#!/usr/bin/env python3
"""
Cache Manager - Intelligent Semantic Asset Reuse System
Maintains cache/index.json with hash→file mapping and tracks cache lineage
in metadata for full transparency of which cached assets contributed to each output.
Enhanced Features:
- Semantic asset tagging and metadata system
- Intelligent asset matching algorithms with similarity scoring
- Cross-campaign asset discovery mechanisms
- Asset versioning and variant tracking
- Background adaptation and seasonal updating logic
- Learning system for asset reuse pattern tracking
- Clean API for seamless CLI integration
"""
import json
import logging
from collections import defaultdict
from datetime import datetime
from enum import Enum
from pathlib import Path
from typing import Any
logger = logging.getLogger(__name__)
# ============================================================================
# SEMANTIC METADATA SCHEMA
# ============================================================================
class AssetType(Enum):
"""Asset type classifications"""
PRODUCT_TRANSPARENT = "product_transparent" # Background-removed product
PRODUCT_ORIGINAL = "product_original" # Original product with background
SCENE_BACKGROUND = "scene_background" # Lifestyle/contextual backgrounds
CONTEXTUAL_BACKGROUND = "contextual_background" # Product-specific contexts
GRADIENT_BACKGROUND = "gradient_background" # Gradient backgrounds
SOLID_BACKGROUND = "solid_background" # Solid color backgrounds
COMPOSITE = "composite" # Final composed creative
class Season(Enum):
"""Seasonal classifications for adaptive backgrounds"""
SPRING = "spring"
SUMMER = "summer"
FALL = "fall"
WINTER = "winter"
HOLIDAY = "holiday"
BACK_TO_SCHOOL = "back_to_school"
NONE = "none" # Season-neutral assets
class VisualStyle(Enum):
"""Visual style classifications"""
MINIMAL = "minimal"
VIBRANT = "vibrant"
ELEGANT = "elegant"
WARM = "warm"
COOL = "cool"
PROFESSIONAL = "professional"
CASUAL = "casual"
class ProductCategory(Enum):
"""Product category classifications"""
LAUNDRY_DETERGENT = "laundry_detergent"
DISH_SOAP = "dish_soap"
HAIR_CARE = "hair_care"
ORAL_CARE = "oral_care"
PERSONAL_CARE = "personal_care"
GENERAL_CPG = "general_cpg"
class SemanticMetadata:
"""
Semantic metadata for intelligent asset reuse.
This rich metadata enables cross-campaign asset discovery,
intelligent matching, and adaptive background selection.
"""
def __init__(
self,
asset_type: AssetType,
product_category: ProductCategory | None = None,
region: str | None = None,
visual_style: VisualStyle | None = None,
season: Season = Season.NONE,
color_palette: list[str] | None = None,
tags: list[str] | None = None,
dimensions: tuple[int, int] | None = None,
aspect_ratio: str | None = None,
):
self.asset_type = asset_type
self.product_category = product_category
self.region = region
self.visual_style = visual_style
self.season = season
self.color_palette = color_palette or []
self.tags = tags or []
self.dimensions = dimensions
self.aspect_ratio = aspect_ratio
def to_dict(self) -> dict[str, Any]:
"""Convert to dictionary for JSON serialization"""
return {
"asset_type": self.asset_type.value,
"product_category": self.product_category.value if self.product_category else None,
"region": self.region,
"visual_style": self.visual_style.value if self.visual_style else None,
"season": self.season.value,
"color_palette": self.color_palette,
"tags": self.tags,
"dimensions": self.dimensions,
"aspect_ratio": self.aspect_ratio,
}
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "SemanticMetadata":
"""Create from dictionary"""
return cls(
asset_type=AssetType(data["asset_type"]),
product_category=(
ProductCategory(data["product_category"]) if data.get("product_category") else None
),
region=data.get("region"),
visual_style=VisualStyle(data["visual_style"]) if data.get("visual_style") else None,
season=Season(data.get("season", "none")),
color_palette=data.get("color_palette", []),
tags=data.get("tags", []),
dimensions=tuple(data["dimensions"]) if data.get("dimensions") else None,
aspect_ratio=data.get("aspect_ratio"),
)
# ============================================================================
# ASSET MATCHING & DISCOVERY
# ============================================================================
class AssetMatcher:
"""
Intelligent asset matching for cross-campaign reuse.
Uses weighted scoring across multiple dimensions:
- Visual style similarity
- Seasonal appropriateness
- Product category compatibility
- Regional aesthetic match
- Color palette harmony
"""
# Matching weights for similarity scoring
WEIGHTS = {
"visual_style": 0.25,
"season": 0.20,
"product_category": 0.20,
"region": 0.15,
"color_palette": 0.10,
"tags": 0.10,
}
@staticmethod
def calculate_similarity(
target_metadata: SemanticMetadata,
candidate_metadata: SemanticMetadata,
) -> float:
"""
Calculate similarity score between target and candidate assets.
Args:
target_metadata: Target asset metadata
candidate_metadata: Candidate asset metadata
Returns:
Similarity score (0.0 to 1.0, higher is better match)
"""
score = 0.0
# Visual style match
if target_metadata.visual_style and candidate_metadata.visual_style:
if target_metadata.visual_style == candidate_metadata.visual_style:
score += AssetMatcher.WEIGHTS["visual_style"]
# Seasonal appropriateness
if AssetMatcher._is_season_compatible(target_metadata.season, candidate_metadata.season):
score += AssetMatcher.WEIGHTS["season"]
# Product category match
if target_metadata.product_category and candidate_metadata.product_category:
if target_metadata.product_category == candidate_metadata.product_category:
score += AssetMatcher.WEIGHTS["product_category"]
# Regional aesthetic match
if target_metadata.region and candidate_metadata.region:
if target_metadata.region == candidate_metadata.region:
score += AssetMatcher.WEIGHTS["region"]
# Color palette harmony
color_similarity = AssetMatcher._calculate_color_similarity(
target_metadata.color_palette,
candidate_metadata.color_palette,
)
score += color_similarity * AssetMatcher.WEIGHTS["color_palette"]
# Tag overlap
tag_similarity = AssetMatcher._calculate_tag_similarity(
target_metadata.tags,
candidate_metadata.tags,
)
score += tag_similarity * AssetMatcher.WEIGHTS["tags"]
return min(score, 1.0)
@staticmethod
def _is_season_compatible(target_season: Season, candidate_season: Season) -> bool:
"""Check if seasons are compatible"""
# Season-neutral assets work with anything
if target_season == Season.NONE or candidate_season == Season.NONE:
return True
# Exact match is best
if target_season == candidate_season:
return True
# Some seasons are compatible (e.g., spring/summer, fall/winter)
compatible_pairs = [
{Season.SPRING, Season.SUMMER},
{Season.FALL, Season.WINTER},
]
for pair in compatible_pairs:
if target_season in pair and candidate_season in pair:
return True
return False
@staticmethod
def _calculate_color_similarity(colors1: list[str], colors2: list[str]) -> float:
"""Calculate color palette similarity (basic overlap metric)"""
if not colors1 or not colors2:
return 0.0
set1 = set(colors1)
set2 = set(colors2)
overlap = len(set1 & set2)
total = len(set1 | set2)
return overlap / total if total > 0 else 0.0
@staticmethod
def _calculate_tag_similarity(tags1: list[str], tags2: list[str]) -> float:
"""Calculate tag similarity (Jaccard index)"""
if not tags1 or not tags2:
return 0.0
set1 = set(tags1)
set2 = set(tags2)
intersection = len(set1 & set2)
union = len(set1 | set2)
return intersection / union if union > 0 else 0.0
# ============================================================================
# ASSET VERSIONING & VARIANTS
# ============================================================================
class AssetVersion:
"""
Asset versioning for tracking updates and variants.
Enables seasonal refreshes, A/B testing, and variant management.
"""
def __init__(
self,
version: str,
cache_key: str,
file_path: str,
created_at: str,
variant_type: str | None = None,
parent_version: str | None = None,
change_notes: str | None = None,
):
self.version = version
self.cache_key = cache_key
self.file_path = file_path
self.created_at = created_at
self.variant_type = variant_type
self.parent_version = parent_version
self.change_notes = change_notes
def to_dict(self) -> dict[str, Any]:
"""Convert to dictionary"""
return {
"version": self.version,
"cache_key": self.cache_key,
"file_path": self.file_path,
"created_at": self.created_at,
"variant_type": self.variant_type,
"parent_version": self.parent_version,
"change_notes": self.change_notes,
}
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "AssetVersion":
"""Create from dictionary"""
return cls(
version=data["version"],
cache_key=data["cache_key"],
file_path=data["file_path"],
created_at=data["created_at"],
variant_type=data.get("variant_type"),
parent_version=data.get("parent_version"),
change_notes=data.get("change_notes"),
)
# ============================================================================
# LEARNING SYSTEM FOR REUSE PATTERNS
# ============================================================================
class ReusePattern:
"""
Tracks successful asset reuse patterns to learn over time.
This enables the system to get smarter about asset selection
based on what has worked well in the past.
"""
def __init__(
self,
source_asset: str,
target_campaign: str,
reuse_count: int = 0,
success_rate: float = 0.0,
contexts: list[str] | None = None,
):
self.source_asset = source_asset
self.target_campaign = target_campaign
self.reuse_count = reuse_count
self.success_rate = success_rate
self.contexts = contexts or []
def record_reuse(self, success: bool, context: str | None = None):
"""Record a reuse instance"""
self.reuse_count += 1
# Update success rate (weighted average)
if success:
self.success_rate = (
self.success_rate * (self.reuse_count - 1) + 1.0
) / self.reuse_count
else:
self.success_rate = (self.success_rate * (self.reuse_count - 1)) / self.reuse_count
if context and context not in self.contexts:
self.contexts.append(context)
def to_dict(self) -> dict[str, Any]:
"""Convert to dictionary"""
return {
"source_asset": self.source_asset,
"target_campaign": self.target_campaign,
"reuse_count": self.reuse_count,
"success_rate": self.success_rate,
"contexts": self.contexts,
}
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "ReusePattern":
"""Create from dictionary"""
return cls(
source_asset=data["source_asset"],
target_campaign=data["target_campaign"],
reuse_count=data.get("reuse_count", 0),
success_rate=data.get("success_rate", 0.0),
contexts=data.get("contexts", []),
)
class CacheManager:
"""
Manages cache index, lineage tracking, and intelligent semantic asset reuse.
Enhanced with semantic tagging, cross-campaign discovery, versioning,
adaptive backgrounds, and learning-based asset recommendations.
"""
def __init__(self, cache_dir: str = "cache"):
"""
Initialize cache manager.
Args:
cache_dir: Base cache directory
"""
self.cache_dir = Path(cache_dir)
self.cache_dir.mkdir(exist_ok=True)
self.index_path = self.cache_dir / "index.json"
self.index = self._load_index()
# Ensure all required sections exist
if "products" not in self.index:
self.index["products"] = {}
if "cache_entries" not in self.index:
self.index["cache_entries"] = {}
if "semantic_assets" not in self.index:
self.index["semantic_assets"] = {}
if "asset_versions" not in self.index:
self.index["asset_versions"] = {}
if "reuse_patterns" not in self.index:
self.index["reuse_patterns"] = {}
if "background_library" not in self.index:
self.index["background_library"] = {}
# Save the initialized index structure
self._save_index()
# Initialize matcher
self.matcher = AssetMatcher()
logger.info(f"CacheManager initialized with directory: {self.cache_dir}")
logger.info("Intelligent semantic asset reuse enabled")
def _load_index(self) -> dict[Any, Any]:
"""Load cache index from disk"""
if self.index_path.exists():
try:
with open(self.index_path) as f:
loaded: dict[Any, Any] = json.load(f)
return loaded
except Exception as e:
logger.warning(f"Failed to load cache index: {e}")
return {}
return {}
def _save_index(self) -> None:
"""Save cache index to disk"""
try:
with open(self.index_path, "w") as f:
json.dump(self.index, f, indent=2)
logger.debug("Cache index saved")
except Exception as e:
logger.error(f"Failed to save cache index: {e}")
def register_cache_entry(self, cache_key: str, file_path: str, metadata: dict) -> None:
"""
Register a cache entry in the index.
Args:
cache_key: Cache hash key
file_path: Path to cached file
metadata: Additional metadata (product_slug, type, etc.)
"""
entry = {
"file_path": str(file_path),
"cache_key": cache_key,
"created_at": datetime.now().isoformat(),
"metadata": metadata,
}
self.index[cache_key] = entry
self._save_index()
logger.debug(f"Registered cache entry: {cache_key} -> {file_path}")
def get_cache_entry(self, cache_key: str) -> dict | None:
"""
Get cache entry by key.
Args:
cache_key: Cache hash key
Returns:
Cache entry dict or None if not found
"""
return self.index.get(cache_key)
def find_by_metadata(self, **kwargs) -> list[dict]:
"""
Find cache entries matching metadata criteria.
Args:
**kwargs: Metadata key-value pairs to match
Returns:
List of matching cache entries
"""
matches = []
for _cache_key, entry in self.index.items():
metadata = entry.get("metadata", {})
if all(metadata.get(k) == v for k, v in kwargs.items()):
matches.append(entry)
return matches
def query_cache(self, **kwargs) -> list[dict]:
"""
Query cache entries by metadata (alias for find_by_metadata).
Args:
**kwargs: Metadata key-value pairs to match
Returns:
List of matching cache entries
"""
return self.find_by_metadata(**kwargs)
def build_lineage_metadata(self, cache_hits: dict) -> dict:
"""
Build cache lineage metadata for output.
Args:
cache_hits: Dict of {cache_type: cache_filename}
Returns:
Lineage metadata dict
"""
lineage = {
"cache_hits": cache_hits,
"cache_count": len(cache_hits),
"fully_cached": all(v for v in cache_hits.values()),
}
# Add cache entry details
for cache_type, cache_filename in cache_hits.items():
if cache_filename:
# Try to find entry in index
for cache_key, entry in self.index.items():
if cache_filename in entry.get("file_path", ""):
lineage[f"{cache_type}_cache_key"] = cache_key
lineage[f"{cache_type}_created_at"] = entry.get("created_at")
break
return lineage
def get_cache_stats(self) -> dict:
"""
Get comprehensive cache statistics.
Returns:
Dict with cache statistics
"""
total_entries = len(self.index)
total_size = 0
# Calculate total size of cached files
for entry in self.index.values():
file_path = Path(entry.get("file_path", ""))
if file_path.exists():
total_size += file_path.stat().st_size
# Group by type
by_type: dict[str, int] = {}
for entry in self.index.values():
cache_type = entry.get("metadata", {}).get("type", "unknown")
by_type[cache_type] = by_type.get(cache_type, 0) + 1
return {
"total_entries": total_entries,
"total_size_bytes": total_size,
"total_size_mb": round(total_size / (1024 * 1024), 2),
"by_type": by_type,
"index_path": str(self.index_path),
}
def clear_cache(self, cache_type: str | None = None) -> int:
"""
Clear cache entries and files.
Args:
cache_type: Optional cache type filter (transparent, scene, etc.)
Returns:
Number of entries cleared
"""
entries_to_remove = []
# Ensure cache_entries section exists
if "cache_entries" not in self.index:
self.index["cache_entries"] = {}
# Only iterate over cache_entries, not the special sections like "products"
for cache_key, entry in self.index.get("cache_entries", {}).items():
if cache_type is None or entry.get("metadata", {}).get("type") == cache_type:
# Delete file
file_path = Path(entry.get("file_path", ""))
if file_path.exists():
try:
file_path.unlink()
logger.debug(f"Deleted cache file: {file_path}")
except Exception as e:
logger.warning(f"Failed to delete {file_path}: {e}")
entries_to_remove.append(cache_key)
# Remove from cache_entries section
for cache_key in entries_to_remove:
del self.index["cache_entries"][cache_key]
self._save_index()
cleared_count = len(entries_to_remove)
logger.info(f"Cleared {cleared_count} cache entries")
return cleared_count
# ========================================================================
# PRODUCT REGISTRY METHODS
# ========================================================================
def register_product(
self,
product_name: str,
file_path: str,
campaign_id: str,
tags: list[str] | None = None,
cache_filename: str | None = None,
product_cache_filename: str | None = None,
) -> str:
"""
Register a product in the product registry.
Args:
product_name: Full product name
file_path: Path to the product file
campaign_id: Campaign that created this product
tags: Optional tags for categorization
cache_filename: Background-removed cache filename (optional, for backwards compatibility)
product_cache_filename: Original product cache filename (optional, for backwards compatibility)
Returns:
Product slug
"""
product_slug = self._slugify_product_name(product_name)
# Check if product already exists
existing = self.index["products"].get(product_slug)
if existing:
# Update campaigns_used list
if campaign_id and campaign_id not in existing.get("campaigns_used", []):
existing["campaigns_used"].append(campaign_id)
self._save_index()
logger.info(f"Product already registered: {product_slug}")
return product_slug
# Register new product
product_entry = {
"name": product_name,
"slug": product_slug,
"file_path": file_path,
"cache_filename": cache_filename or file_path, # For backwards compatibility
"product_cache_filename": product_cache_filename
or file_path, # For backwards compatibility
"created_at": datetime.now().isoformat(),
"campaigns_used": [campaign_id] if campaign_id else [],
"status": "ready",
"tags": tags or [],
}
self.index["products"][product_slug] = product_entry
self._save_index()
logger.info(f"Registered product: {product_name} -> {product_slug}")
return product_slug
def lookup_product(self, product_name: str) -> dict | None:
"""
Look up product by name in the registry.
Args:
product_name: Full product name to search for
Returns:
Product entry dict or None if not found
"""
product_slug = self._slugify_product_name(product_name)
result = self.index["products"].get(product_slug)
return dict(result) if result else None
def get_product_by_slug(self, product_slug: str) -> dict | None:
"""
Get product info by slug.
Args:
product_slug: Product slug
Returns:
Product entry dict or None if not found
"""
result = self.index["products"].get(product_slug)
return dict(result) if result else None
def list_all_products(self) -> dict[str, dict[Any, Any]]:
"""
Get all registered products.
Returns:
Dict of {product_slug: product_info}
"""
return dict(self.index["products"])
def _slugify_product_name(self, product_name: str) -> str:
"""
Convert product name to slug format.
Args:
product_name: Full product name
Returns:
Slugified product name
"""
import re
# Convert to lowercase and replace spaces/special chars with hyphens
slug = re.sub(r"[^\w\s-]", "", product_name.lower())
slug = re.sub(r"[\s_-]+", "-", slug)
return slug.strip("-")
def validate_cache(self) -> dict:
"""
Validate cache integrity (check for missing files).
Returns:
Dict with validation results
"""
total = len(self.index)
valid = 0
missing = []
for cache_key, entry in self.index.items():
file_path = Path(entry.get("file_path", ""))
if file_path.exists():
valid += 1
else:
missing.append(cache_key)
return {
"total_entries": total,
"valid_entries": valid,
"missing_entries": len(missing),
"missing_keys": missing,
}
# ========================================================================
# SEMANTIC ASSET REGISTRATION & TAGGING
# ========================================================================
def register_semantic_asset(
self,
cache_key: str,
file_path: str,
metadata: SemanticMetadata,
campaign_id: str | None = None,
) -> None:
"""
Register asset with semantic metadata for intelligent reuse.
Args:
cache_key: Unique cache key
file_path: Path to asset file
metadata: Semantic metadata for the asset
campaign_id: Campaign that created this asset
"""
asset_entry = {
"cache_key": cache_key,
"file_path": str(file_path),
"semantic_metadata": metadata.to_dict(),
"campaign_id": campaign_id,
"created_at": datetime.now().isoformat(),
"last_used": datetime.now().isoformat(),
"usage_count": 0,
"campaigns_used": [campaign_id] if campaign_id else [],
}
self.index["semantic_assets"][cache_key] = asset_entry
self._save_index()
logger.info(f"Registered semantic asset: {cache_key} ({metadata.asset_type.value})")
def update_semantic_metadata(
self,
cache_key: str,
metadata_updates: dict[str, Any],
) -> bool:
"""
Update semantic metadata for an existing asset.
Args:
cache_key: Asset cache key
metadata_updates: Dictionary of metadata fields to update
Returns:
True if successful, False if asset not found
"""
if cache_key not in self.index["semantic_assets"]:
logger.warning(f"Asset not found: {cache_key}")
return False
asset_entry = self.index["semantic_assets"][cache_key]
current_metadata = asset_entry.get("semantic_metadata", {})
# Merge updates
current_metadata.update(metadata_updates)
asset_entry["semantic_metadata"] = current_metadata
self._save_index()
logger.info(f"Updated semantic metadata for: {cache_key}")
return True
def tag_asset(self, cache_key: str, tags: list[str]) -> bool:
"""
Add tags to an asset for better discovery.
Args:
cache_key: Asset cache key
tags: List of tags to add
Returns:
True if successful, False if asset not found
"""
if cache_key not in self.index["semantic_assets"]:
logger.warning(f"Asset not found: {cache_key}")
return False
asset_entry = self.index["semantic_assets"][cache_key]
metadata = asset_entry.get("semantic_metadata", {})
existing_tags = set(metadata.get("tags", []))
existing_tags.update(tags)
metadata["tags"] = list(existing_tags)
asset_entry["semantic_metadata"] = metadata
self._save_index()
logger.info(f"Tagged asset {cache_key} with: {', '.join(tags)}")
return True
# ========================================================================
# INTELLIGENT ASSET DISCOVERY & MATCHING
# ========================================================================
def find_similar_assets(
self,
target_metadata: SemanticMetadata,
asset_type: AssetType | None = None,
min_similarity: float = 0.5,
max_results: int = 10,
exclude_campaigns: list[str] | None = None,
) -> list[tuple[str, float, dict[str, Any]]]:
"""
Find similar assets using intelligent matching.
Args:
target_metadata: Target asset metadata to match against
asset_type: Optional filter by asset type
min_similarity: Minimum similarity threshold (0.0 to 1.0)
max_results: Maximum number of results to return
exclude_campaigns: Optional list of campaign IDs to exclude
Returns:
List of (cache_key, similarity_score, asset_entry) tuples,
sorted by similarity (highest first)
"""
candidates = []
for cache_key, asset_entry in self.index["semantic_assets"].items():
# Filter by asset type if specified
if asset_type:
entry_type = asset_entry.get("semantic_metadata", {}).get("asset_type")
if entry_type != asset_type.value:
continue
# Exclude specific campaigns if requested
if exclude_campaigns:
campaign_id = asset_entry.get("campaign_id")
if campaign_id in exclude_campaigns:
continue
# Calculate similarity
try:
candidate_metadata = SemanticMetadata.from_dict(asset_entry["semantic_metadata"])
similarity = self.matcher.calculate_similarity(target_metadata, candidate_metadata)
if similarity >= min_similarity:
candidates.append((cache_key, similarity, asset_entry))
except Exception as e:
logger.warning(f"Error calculating similarity for {cache_key}: {e}")
continue
# Sort by similarity (highest first) and limit results
candidates.sort(key=lambda x: x[1], reverse=True)
results = candidates[:max_results]
logger.info(
f"Found {len(results)} similar assets (threshold: {min_similarity}, "
f"best match: {results[0][1]:.2f})"
if results
else "No similar assets found"
)
return results
def find_backgrounds_for_product(
self,
product_category: ProductCategory,
region: str,
season: Season = Season.NONE,
visual_style: VisualStyle | None = None,
aspect_ratio: str | None = None,
min_similarity: float = 0.4,
) -> list[tuple[str, float, dict[str, Any]]]:
"""
Find suitable background assets for a product.
Args:
product_category: Product category
region: Target region
season: Seasonal preference
visual_style: Visual style preference
aspect_ratio: Optional aspect ratio filter
min_similarity: Minimum similarity threshold
Returns:
List of (cache_key, similarity_score, asset_entry) tuples
"""
# Build target metadata for background search
target_metadata = SemanticMetadata(
asset_type=AssetType.SCENE_BACKGROUND,
product_category=product_category,
region=region,
season=season,
visual_style=visual_style,
aspect_ratio=aspect_ratio,
)
# Search for matching backgrounds
candidates = self.find_similar_assets(
target_metadata=target_metadata,
asset_type=AssetType.SCENE_BACKGROUND,
min_similarity=min_similarity,
max_results=20,
)
# Filter by aspect ratio if specified
if aspect_ratio:
candidates = [
(key, score, entry)
for key, score, entry in candidates
if entry.get("semantic_metadata", {}).get("aspect_ratio") == aspect_ratio
]
logger.info(
f"Found {len(candidates)} suitable backgrounds for {product_category.value} "
f"in {region} (season: {season.value})"
)
return candidates
def discover_cross_campaign_assets(
self,
campaign_id: str,
asset_types: list[AssetType] | None = None,
) -> dict[str, list[tuple[str, dict[str, Any]]]]:
"""
Discover reusable assets from other campaigns.
Args:
campaign_id: Current campaign ID
asset_types: Optional filter by asset types
Returns:
Dictionary mapping asset type to list of (cache_key, asset_entry) tuples
"""
discovered = defaultdict(list)
for cache_key, asset_entry in self.index["semantic_assets"].items():
# Skip assets from current campaign
if asset_entry.get("campaign_id") == campaign_id:
continue
# Check file still exists
file_path = Path(asset_entry.get("file_path", ""))
if not file_path.exists():
continue