Spaces:
Runtime error
Runtime error
File size: 50,379 Bytes
8cbe6eb | 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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 | """
Cache Manager implementation for the voice control optimization system.
This module provides intelligent caching of transcription results using audio
fingerprinting to avoid redundant API calls and improve response times.
"""
import asyncio
import hashlib
import logging
import time
from collections import OrderedDict
from typing import Dict, Optional, Any, Set, List, Callable
from datetime import datetime, timedelta
from dataclasses import dataclass, field
from .interfaces import CacheManagerInterface
from .models import TranscriptionResult, CacheStats
from .exceptions import CacheError
logger = logging.getLogger(__name__)
@dataclass
class CacheEntry:
"""Represents a cached transcription result with metadata."""
result: TranscriptionResult
created_at: float
last_accessed: float
ttl: int
access_count: int = 0
size_bytes: int = 0
def __post_init__(self):
"""Calculate entry size after initialization."""
if self.size_bytes == 0:
self.size_bytes = self._calculate_size()
def _calculate_size(self) -> int:
"""Calculate approximate memory size of the cache entry."""
# Base size for the entry object
size = 200 # Approximate overhead
# Size of transcription result
size += len(self.result.text.encode('utf-8'))
size += len(self.result.provider.encode('utf-8'))
size += len(self.result.language.encode('utf-8'))
# Size of alternatives
for alt in self.result.alternatives:
size += len(alt.encode('utf-8'))
# Size of word timestamps if present
if self.result.word_timestamps:
for word_ts in self.result.word_timestamps:
size += len(word_ts.word.encode('utf-8')) + 32 # word + timestamps
return size
@property
def is_expired(self) -> bool:
"""Check if the cache entry has expired."""
return time.time() - self.created_at > self.ttl
def touch(self) -> None:
"""Update last accessed time and increment access count."""
self.last_accessed = time.time()
self.access_count += 1
class CacheManager(CacheManagerInterface):
"""
Manages caching of transcription results with LRU eviction and TTL expiration.
Features:
- Audio fingerprint-based cache keys
- LRU (Least Recently Used) eviction policy
- TTL (Time To Live) based expiration
- Configurable size limits
- Cache statistics tracking
"""
def __init__(
self,
max_size_mb: int = 100,
default_ttl: int = 3600,
cleanup_interval: int = 600,
enable_stats: bool = True
):
"""
Initialize the cache manager.
Args:
max_size_mb: Maximum cache size in megabytes
default_ttl: Default time-to-live in seconds
cleanup_interval: Interval for cleanup tasks in seconds
enable_stats: Whether to track cache statistics
"""
self.max_size_bytes = max_size_mb * 1024 * 1024
self.default_ttl = default_ttl
self.cleanup_interval = cleanup_interval
self.enable_stats = enable_stats
# Cache storage using OrderedDict for LRU behavior
self._cache: OrderedDict[str, CacheEntry] = OrderedDict()
# Cache statistics
self._stats = {
"total_requests": 0,
"cache_hits": 0,
"cache_misses": 0,
"evictions": 0,
"expirations": 0,
"current_size_bytes": 0,
"entry_count": 0,
# Cache hit optimization metrics
"cache_hit_times": [], # Track cache hit response times
"cache_miss_times": [], # Track cache miss response times
"sequential_hits": 0, # Track consecutive cache hits
"sequential_misses": 0, # Track consecutive cache misses
"hot_entries": {}, # Track frequently accessed entries
"last_operation": None, # Track last operation type ('hit' or 'miss')
}
# Cleanup task
self._cleanup_task: Optional[asyncio.Task] = None
self._running = False
# Lock for thread safety
self._lock = asyncio.Lock()
logger.info(f"CacheManager initialized with max_size={max_size_mb}MB, ttl={default_ttl}s")
async def start(self) -> None:
"""Start the cache manager and background cleanup task."""
if self._running:
return
self._running = True
self._cleanup_task = asyncio.create_task(self._cleanup_loop())
logger.info("CacheManager started")
async def stop(self) -> None:
"""Stop the cache manager and cleanup task."""
if not self._running:
return
self._running = False
if self._cleanup_task:
self._cleanup_task.cancel()
try:
await self._cleanup_task
except asyncio.CancelledError:
pass
logger.info("CacheManager stopped")
async def get_cached_transcription(
self,
audio_fingerprint: str
) -> Optional[TranscriptionResult]:
"""
Retrieve cached transcription result with optimized lookup.
This method implements cache hit optimization by:
1. Fast lookup without API calls for cached results
2. Tracking cache hit performance metrics
3. Optimizing frequently accessed entries
4. Monitoring cache hit patterns
Args:
audio_fingerprint: Unique fingerprint of audio data
Returns:
Cached TranscriptionResult or None if not found
"""
start_time = time.time()
async with self._lock:
if self.enable_stats:
self._stats["total_requests"] += 1
entry = self._cache.get(audio_fingerprint)
if entry is None:
# Cache miss - track timing and patterns
miss_time = time.time() - start_time
if self.enable_stats:
self._stats["cache_misses"] += 1
self._stats["cache_miss_times"].append(miss_time)
# Keep only last 100 measurements for efficiency
if len(self._stats["cache_miss_times"]) > 100:
self._stats["cache_miss_times"] = self._stats["cache_miss_times"][-100:]
# Track sequential misses
if self._stats["last_operation"] == "miss":
self._stats["sequential_misses"] += 1
else:
self._stats["sequential_misses"] = 1
self._stats["last_operation"] = "miss"
logger.debug(f"Cache miss for fingerprint: {audio_fingerprint[:16]}... "
f"(lookup time: {miss_time*1000:.2f}ms)")
return None
# Check if entry has expired
if entry.is_expired:
miss_time = time.time() - start_time
logger.debug(f"Cache entry expired for fingerprint: {audio_fingerprint[:16]}... "
f"(lookup time: {miss_time*1000:.2f}ms)")
await self._remove_entry(audio_fingerprint)
if self.enable_stats:
self._stats["cache_misses"] += 1
self._stats["expirations"] += 1
self._stats["cache_miss_times"].append(miss_time)
if len(self._stats["cache_miss_times"]) > 100:
self._stats["cache_miss_times"] = self._stats["cache_miss_times"][-100:]
# Track sequential misses
if self._stats["last_operation"] == "miss":
self._stats["sequential_misses"] += 1
else:
self._stats["sequential_misses"] = 1
self._stats["last_operation"] = "miss"
return None
# Cache hit - optimize and track performance
hit_time = time.time() - start_time
# Update access information and move to end (most recently used)
entry.touch()
self._cache.move_to_end(audio_fingerprint)
if self.enable_stats:
self._stats["cache_hits"] += 1
self._stats["cache_hit_times"].append(hit_time)
# Keep only last 100 measurements for efficiency
if len(self._stats["cache_hit_times"]) > 100:
self._stats["cache_hit_times"] = self._stats["cache_hit_times"][-100:]
# Track hot entries (frequently accessed)
if audio_fingerprint not in self._stats["hot_entries"]:
self._stats["hot_entries"][audio_fingerprint] = 0
self._stats["hot_entries"][audio_fingerprint] += 1
# Keep only top 50 hot entries to prevent memory growth
if len(self._stats["hot_entries"]) > 50:
# Keep only the most frequently accessed entries
sorted_entries = sorted(
self._stats["hot_entries"].items(),
key=lambda x: x[1],
reverse=True
)
self._stats["hot_entries"] = dict(sorted_entries[:50])
# Track sequential hits
if self._stats["last_operation"] == "hit":
self._stats["sequential_hits"] += 1
else:
self._stats["sequential_hits"] = 1
self._stats["last_operation"] = "hit"
logger.debug(f"Cache hit for fingerprint: {audio_fingerprint[:16]}... "
f"(access count: {entry.access_count}, lookup time: {hit_time*1000:.2f}ms)")
return entry.result
async def get_cached_transcription_batch(
self,
audio_fingerprints: List[str]
) -> Dict[str, Optional[TranscriptionResult]]:
"""
Retrieve multiple cached transcription results in a single operation.
Args:
audio_fingerprints: List of unique fingerprints of audio data
Returns:
Dictionary mapping fingerprints to cached results (None if not found)
"""
results = {}
async with self._lock:
for fingerprint in audio_fingerprints:
if self.enable_stats:
self._stats["total_requests"] += 1
entry = self._cache.get(fingerprint)
if entry is None:
if self.enable_stats:
self._stats["cache_misses"] += 1
results[fingerprint] = None
continue
# Check if entry has expired
if entry.is_expired:
await self._remove_entry(fingerprint)
if self.enable_stats:
self._stats["cache_misses"] += 1
self._stats["expirations"] += 1
results[fingerprint] = None
continue
# Update access information and move to end (most recently used)
entry.touch()
self._cache.move_to_end(fingerprint)
if self.enable_stats:
self._stats["cache_hits"] += 1
results[fingerprint] = entry.result
hit_count = sum(1 for result in results.values() if result is not None)
logger.debug(f"Batch cache lookup: {hit_count}/{len(audio_fingerprints)} hits")
return results
async def cache_transcription(
self,
audio_fingerprint: str,
result: TranscriptionResult,
ttl: Optional[int] = None
) -> bool:
"""
Cache a transcription result.
Args:
audio_fingerprint: Unique fingerprint of audio data
result: TranscriptionResult to cache
ttl: Time to live in seconds (uses default if None)
Returns:
True if caching was successful, False otherwise
"""
if ttl is None:
ttl = self.default_ttl
try:
async with self._lock:
# Create cache entry
entry = CacheEntry(
result=result,
created_at=time.time(),
last_accessed=time.time(),
ttl=ttl
)
# Check if we need to make space
await self._ensure_space(entry.size_bytes)
# Add to cache
self._cache[audio_fingerprint] = entry
self._stats["current_size_bytes"] += entry.size_bytes
self._stats["entry_count"] += 1
logger.debug(f"Cached transcription for fingerprint: {audio_fingerprint[:16]}... "
f"(size: {entry.size_bytes} bytes, ttl: {ttl}s)")
return True
except Exception as e:
logger.error(f"Failed to cache transcription: {e}")
return False
async def generate_audio_fingerprint(self, audio_data: bytes) -> str:
"""
Generate a unique fingerprint for audio data.
Uses SHA-256 hashing of the audio content to create a consistent
fingerprint that will be identical for the same audio data.
Args:
audio_data: Raw audio bytes
Returns:
Unique fingerprint string
"""
try:
# Use SHA-256 for consistent, collision-resistant hashing
hasher = hashlib.sha256()
# Hash the audio data in chunks to handle large files efficiently
chunk_size = 8192
for i in range(0, len(audio_data), chunk_size):
chunk = audio_data[i:i + chunk_size]
hasher.update(chunk)
# Generate hexadecimal fingerprint
fingerprint = hasher.hexdigest()
logger.debug(f"Generated audio fingerprint: {fingerprint[:16]}... "
f"(audio size: {len(audio_data)} bytes)")
return fingerprint
except Exception as e:
logger.error(f"Failed to generate audio fingerprint: {e}")
raise CacheError("fingerprint_generation", f"Failed to generate fingerprint: {e}")
async def get_cache_stats(self) -> CacheStats:
"""
Get cache performance statistics with hit optimization metrics.
Returns:
CacheStats with hit rates and usage information
"""
async with self._lock:
return CacheStats(
total_requests=self._stats["total_requests"],
cache_hits=self._stats["cache_hits"],
cache_misses=self._stats["cache_misses"],
hit_rate=0.0, # Will be calculated in __post_init__
total_size_bytes=self._stats["current_size_bytes"],
entry_count=self._stats["entry_count"],
evictions=self._stats["evictions"]
)
async def get_detailed_cache_stats(self) -> Dict[str, Any]:
"""
Get detailed cache performance statistics for optimization analysis.
Returns:
Dictionary with comprehensive cache metrics including hit optimization data
"""
async with self._lock:
stats = await self.get_cache_stats()
# Calculate additional optimization metrics
avg_entry_size = (
stats.total_size_bytes / stats.entry_count
if stats.entry_count > 0 else 0
)
cache_efficiency = (
stats.hit_rate * (1 - (stats.evictions / max(stats.total_requests, 1)))
if stats.total_requests > 0 else 0.0
)
# Calculate cache hit optimization metrics
hit_optimization_stats = self._calculate_hit_optimization_metrics()
# Analyze access patterns
access_pattern_stats = self._analyze_access_patterns()
return {
"basic_stats": {
"total_requests": stats.total_requests,
"cache_hits": stats.cache_hits,
"cache_misses": stats.cache_misses,
"hit_rate": stats.hit_rate,
"miss_rate": stats.miss_rate,
"evictions": stats.evictions
},
"size_stats": {
"total_size_bytes": stats.total_size_bytes,
"total_size_mb": stats.total_size_bytes / (1024 * 1024),
"entry_count": stats.entry_count,
"avg_entry_size_bytes": avg_entry_size,
"max_size_bytes": self.max_size_bytes,
"utilization_rate": stats.total_size_bytes / self.max_size_bytes
},
"performance_stats": {
"cache_efficiency": cache_efficiency,
"eviction_rate": stats.evictions / max(stats.total_requests, 1),
"access_patterns": access_pattern_stats
},
"hit_optimization_stats": hit_optimization_stats,
"optimization_recommendations": self._get_optimization_recommendations(stats)
}
def _calculate_hit_optimization_metrics(self) -> Dict[str, Any]:
"""
Calculate cache hit optimization metrics.
Returns:
Dictionary with hit optimization statistics
"""
hit_times = self._stats.get("cache_hit_times", [])
miss_times = self._stats.get("cache_miss_times", [])
# Calculate timing statistics
avg_hit_time = sum(hit_times) / len(hit_times) if hit_times else 0.0
avg_miss_time = sum(miss_times) / len(miss_times) if miss_times else 0.0
# Calculate hit time improvement (how much faster hits are than misses)
hit_time_improvement = (
((avg_miss_time - avg_hit_time) / avg_miss_time * 100)
if avg_miss_time > 0 else 0.0
)
# Calculate sequential operation patterns
sequential_hits = self._stats.get("sequential_hits", 0)
sequential_misses = self._stats.get("sequential_misses", 0)
# Calculate hot entry statistics
hot_entries = self._stats.get("hot_entries", {})
hot_entry_count = len(hot_entries)
total_hot_accesses = sum(hot_entries.values()) if hot_entries else 0
avg_hot_entry_accesses = (
total_hot_accesses / hot_entry_count if hot_entry_count > 0 else 0.0
)
# Calculate cache hit efficiency score (0-100)
hit_rate = (
self._stats["cache_hits"] / max(self._stats["total_requests"], 1)
if self._stats["total_requests"] > 0 else 0.0
)
timing_efficiency = min(hit_time_improvement / 50.0, 1.0) if hit_time_improvement > 0 else 0.0
pattern_efficiency = min(sequential_hits / max(sequential_hits + sequential_misses, 1), 1.0)
overall_efficiency = (hit_rate * 0.5 + timing_efficiency * 0.3 + pattern_efficiency * 0.2) * 100
return {
"timing_metrics": {
"avg_hit_time_ms": avg_hit_time * 1000,
"avg_miss_time_ms": avg_miss_time * 1000,
"hit_time_improvement_percent": hit_time_improvement,
"hit_samples": len(hit_times),
"miss_samples": len(miss_times)
},
"pattern_metrics": {
"sequential_hits": sequential_hits,
"sequential_misses": sequential_misses,
"hit_streak_ratio": sequential_hits / max(sequential_hits + sequential_misses, 1)
},
"hot_entry_metrics": {
"hot_entry_count": hot_entry_count,
"total_hot_accesses": total_hot_accesses,
"avg_accesses_per_hot_entry": avg_hot_entry_accesses,
"hot_entry_hit_contribution": (
total_hot_accesses / max(self._stats["cache_hits"], 1) * 100
if self._stats["cache_hits"] > 0 else 0.0
)
},
"efficiency_score": {
"overall_efficiency_percent": overall_efficiency,
"hit_rate_component": hit_rate * 50, # 50% weight
"timing_component": timing_efficiency * 30, # 30% weight
"pattern_component": pattern_efficiency * 20 # 20% weight
}
}
def _analyze_access_patterns(self) -> Dict[str, Any]:
"""
Analyze cache access patterns for optimization insights.
Returns:
Dictionary with access pattern analysis
"""
if not self._cache:
return {
"most_accessed_entries": 0,
"least_accessed_entries": 0,
"avg_access_count": 0.0,
"access_distribution": "empty"
}
access_counts = [entry.access_count for entry in self._cache.values()]
return {
"most_accessed_entries": max(access_counts) if access_counts else 0,
"least_accessed_entries": min(access_counts) if access_counts else 0,
"avg_access_count": sum(access_counts) / len(access_counts) if access_counts else 0.0,
"access_distribution": "varied" if len(set(access_counts)) > 1 else "uniform"
}
def _get_optimization_recommendations(self, stats: CacheStats) -> List[str]:
"""
Generate optimization recommendations based on cache statistics.
Args:
stats: Current cache statistics
Returns:
List of optimization recommendations
"""
recommendations = []
# Hit rate optimization
if stats.hit_rate < 0.5:
recommendations.append("Consider increasing cache size - low hit rate detected")
elif stats.hit_rate < 0.7:
recommendations.append("Cache hit rate could be improved - consider TTL optimization")
# Eviction optimization
if stats.evictions > stats.cache_hits * 0.1:
recommendations.append("High eviction rate - consider increasing cache size")
# Size optimization
utilization = stats.total_size_bytes / self.max_size_bytes
if utilization > 0.9:
recommendations.append("Cache near capacity - consider size increase or TTL reduction")
elif utilization < 0.3:
recommendations.append("Cache underutilized - consider size reduction for memory efficiency")
# Performance optimization
if stats.entry_count > 1000 and stats.hit_rate > 0.8:
recommendations.append("High performance cache - consider implementing cache warming")
# Cache hit optimization specific recommendations
hit_times = self._stats.get("cache_hit_times", [])
miss_times = self._stats.get("cache_miss_times", [])
if hit_times and miss_times:
avg_hit_time = sum(hit_times) / len(hit_times)
avg_miss_time = sum(miss_times) / len(miss_times)
if avg_hit_time > 0.001: # 1ms threshold
recommendations.append("Cache hit times are high - consider cache structure optimization")
if avg_hit_time > avg_miss_time * 0.5:
recommendations.append("Cache hits not significantly faster than misses - investigate cache overhead")
# Sequential pattern optimization
sequential_hits = self._stats.get("sequential_hits", 0)
sequential_misses = self._stats.get("sequential_misses", 0)
if sequential_misses > sequential_hits * 2:
recommendations.append("High sequential miss pattern - consider cache warming or preloading")
# Hot entry optimization
hot_entries = self._stats.get("hot_entries", {})
if len(hot_entries) > 0:
total_hot_accesses = sum(hot_entries.values())
if total_hot_accesses > stats.cache_hits * 0.8:
recommendations.append("High hot entry concentration - consider dedicated hot cache tier")
if not recommendations:
recommendations.append("Cache performance is optimal")
return recommendations
async def warm_cache(
self,
audio_fingerprints: List[str],
transcription_callback: Optional[Callable] = None
) -> Dict[str, bool]:
"""
Warm the cache by preloading frequently accessed transcriptions.
Args:
audio_fingerprints: List of audio fingerprints to warm
transcription_callback: Optional callback to generate transcriptions
Returns:
Dictionary mapping fingerprints to success status
"""
results = {}
for fingerprint in audio_fingerprints:
try:
# Check if already cached
cached_result = await self.get_cached_transcription(fingerprint)
if cached_result is not None:
results[fingerprint] = True
continue
# If callback provided, generate and cache transcription
if transcription_callback:
try:
result = await transcription_callback(fingerprint)
if result:
success = await self.cache_transcription(fingerprint, result)
results[fingerprint] = success
else:
results[fingerprint] = False
except Exception as e:
logger.warning(f"Failed to generate transcription for warming: {e}")
results[fingerprint] = False
else:
results[fingerprint] = False
except Exception as e:
logger.error(f"Error warming cache for fingerprint {fingerprint[:16]}...: {e}")
results[fingerprint] = False
warmed_count = sum(1 for success in results.values() if success)
logger.info(f"Cache warming completed: {warmed_count}/{len(audio_fingerprints)} entries warmed")
return results
async def get_cache_hit_optimization_stats(self) -> Dict[str, Any]:
"""
Get specialized cache hit optimization statistics.
This method provides detailed metrics specifically for cache hit optimization,
including timing analysis, pattern recognition, and performance recommendations.
Returns:
Dictionary with cache hit optimization metrics
"""
async with self._lock:
hit_optimization_stats = self._calculate_hit_optimization_metrics()
basic_stats = await self.get_cache_stats()
# Calculate additional hit-specific metrics
cache_effectiveness = {
"api_calls_avoided": basic_stats.cache_hits,
"api_call_reduction_percent": (
basic_stats.cache_hits / max(basic_stats.total_requests, 1) * 100
if basic_stats.total_requests > 0 else 0.0
),
"estimated_time_saved_ms": (
len(self._stats.get("cache_hit_times", [])) *
(sum(self._stats.get("cache_miss_times", [0])) / max(len(self._stats.get("cache_miss_times", [1])), 1) -
sum(self._stats.get("cache_hit_times", [0])) / max(len(self._stats.get("cache_hit_times", [1])), 1)) * 1000
if self._stats.get("cache_hit_times") and self._stats.get("cache_miss_times") else 0.0
)
}
# Identify optimization opportunities
optimization_opportunities = []
if basic_stats.hit_rate < 0.8:
optimization_opportunities.append({
"type": "hit_rate_improvement",
"description": f"Hit rate is {basic_stats.hit_rate:.1%}, target is 80%+",
"potential_improvement": f"{(0.8 - basic_stats.hit_rate) * 100:.1f}% hit rate increase possible"
})
hit_times = self._stats.get("cache_hit_times", [])
if hit_times and sum(hit_times) / len(hit_times) > 0.001: # 1ms threshold
optimization_opportunities.append({
"type": "lookup_speed_improvement",
"description": f"Average hit time is {sum(hit_times) / len(hit_times) * 1000:.2f}ms",
"potential_improvement": "Consider cache structure optimization for faster lookups"
})
hot_entries = self._stats.get("hot_entries", {})
if len(hot_entries) > 10:
optimization_opportunities.append({
"type": "hot_entry_optimization",
"description": f"{len(hot_entries)} frequently accessed entries identified",
"potential_improvement": "Consider implementing a dedicated hot cache tier"
})
return {
"cache_effectiveness": cache_effectiveness,
"hit_optimization_metrics": hit_optimization_stats,
"optimization_opportunities": optimization_opportunities,
"performance_summary": {
"total_requests": basic_stats.total_requests,
"cache_hits": basic_stats.cache_hits,
"hit_rate": basic_stats.hit_rate,
"api_calls_avoided": basic_stats.cache_hits,
"efficiency_score": hit_optimization_stats.get("efficiency_score", {}).get("overall_efficiency_percent", 0.0)
}
}
async def optimize_cache_performance(self) -> Dict[str, Any]:
"""
Perform cache performance optimization operations with hit optimization focus.
Returns:
Dictionary with optimization results
"""
async with self._lock:
initial_stats = await self.get_cache_stats()
initial_hit_stats = self._calculate_hit_optimization_metrics()
# Remove expired entries
expired_count = await self.evict_expired()
# Analyze and optimize entry access patterns
optimization_results = {
"initial_stats": {
"entry_count": initial_stats.entry_count,
"hit_rate": initial_stats.hit_rate,
"size_bytes": initial_stats.total_size_bytes,
"efficiency_score": initial_hit_stats.get("efficiency_score", {}).get("overall_efficiency_percent", 0.0)
},
"expired_evicted": expired_count,
"optimizations_applied": []
}
# Promote frequently accessed entries (move to end for LRU)
frequent_entries = []
hot_entries = self._stats.get("hot_entries", {})
# Promote hot entries to the end of the cache (most recently used)
for key, access_count in hot_entries.items():
if key in self._cache and access_count > 5: # Threshold for frequent access
frequent_entries.append(key)
self._cache.move_to_end(key)
if frequent_entries:
optimization_results["optimizations_applied"].append(
f"Promoted {len(frequent_entries)} frequently accessed entries to improve hit rates"
)
# Optimize cache structure for better hit performance
if len(self._cache) > 100:
# Reorganize cache to put most accessed items at the end (LRU optimization)
sorted_entries = []
for key, entry in self._cache.items():
access_weight = hot_entries.get(key, 0) + entry.access_count
sorted_entries.append((key, entry, access_weight))
# Sort by access weight and reorganize
sorted_entries.sort(key=lambda x: x[2])
# Clear and rebuild cache in optimized order
temp_cache = self._cache.copy()
self._cache.clear()
for key, entry, _ in sorted_entries:
self._cache[key] = entry
optimization_results["optimizations_applied"].append(
"Reorganized cache structure for optimal hit performance"
)
# Clean up old timing data to prevent memory growth
if len(self._stats.get("cache_hit_times", [])) > 100:
self._stats["cache_hit_times"] = self._stats["cache_hit_times"][-100:]
optimization_results["optimizations_applied"].append("Cleaned up old hit timing data")
if len(self._stats.get("cache_miss_times", [])) > 100:
self._stats["cache_miss_times"] = self._stats["cache_miss_times"][-100:]
optimization_results["optimizations_applied"].append("Cleaned up old miss timing data")
# Compact cache if fragmented (remove and re-add entries to optimize memory)
if initial_stats.entry_count > 100 and expired_count > initial_stats.entry_count * 0.1:
# Cache is fragmented, perform compaction
entries_to_compact = list(self._cache.items())
self._cache.clear()
self._stats["current_size_bytes"] = 0
self._stats["entry_count"] = 0
# Re-add entries in access order (most recent first)
for key, entry in reversed(entries_to_compact):
self._cache[key] = entry
self._stats["current_size_bytes"] += entry.size_bytes
self._stats["entry_count"] += 1
optimization_results["optimizations_applied"].append("Performed cache compaction for better memory efficiency")
final_stats = await self.get_cache_stats()
final_hit_stats = self._calculate_hit_optimization_metrics()
optimization_results["final_stats"] = {
"entry_count": final_stats.entry_count,
"hit_rate": final_stats.hit_rate,
"size_bytes": final_stats.total_size_bytes,
"efficiency_score": final_hit_stats.get("efficiency_score", {}).get("overall_efficiency_percent", 0.0)
}
# Calculate optimization impact
efficiency_improvement = (
optimization_results["final_stats"]["efficiency_score"] -
optimization_results["initial_stats"]["efficiency_score"]
)
optimization_results["optimization_impact"] = {
"efficiency_improvement_percent": efficiency_improvement,
"hit_rate_change": final_stats.hit_rate - initial_stats.hit_rate,
"size_reduction_bytes": initial_stats.total_size_bytes - final_stats.total_size_bytes
}
logger.info(f"Cache optimization completed: {optimization_results}")
return optimization_results
async def clear_cache(self) -> None:
"""Clear all cached entries."""
async with self._lock:
self._cache.clear()
self._stats["current_size_bytes"] = 0
self._stats["entry_count"] = 0
logger.info("Cache cleared")
async def evict_expired(self) -> int:
"""
Remove expired cache entries.
Returns:
Number of entries evicted
"""
async with self._lock:
expired_keys = []
current_time = time.time()
for key, entry in self._cache.items():
if current_time - entry.created_at > entry.ttl:
expired_keys.append(key)
evicted_count = 0
for key in expired_keys:
await self._remove_entry(key)
evicted_count += 1
if self.enable_stats:
self._stats["expirations"] += 1
if evicted_count > 0:
logger.debug(f"Evicted {evicted_count} expired cache entries")
return evicted_count
async def _ensure_space(self, required_bytes: int) -> None:
"""
Ensure there's enough space in the cache for a new entry.
Args:
required_bytes: Number of bytes needed
"""
# Check if we have enough space
if self._stats["current_size_bytes"] + required_bytes <= self.max_size_bytes:
return
# Need to evict entries using LRU policy
bytes_to_free = (self._stats["current_size_bytes"] + required_bytes) - self.max_size_bytes
bytes_freed = 0
evicted_count = 0
# Evict least recently used entries until we have enough space
while bytes_freed < bytes_to_free and self._cache:
# Get least recently used entry (first in OrderedDict)
key = next(iter(self._cache))
entry = self._cache[key]
bytes_freed += entry.size_bytes
await self._remove_entry(key)
evicted_count += 1
if self.enable_stats:
self._stats["evictions"] += 1
logger.debug(f"Evicted {evicted_count} entries to free {bytes_freed} bytes")
async def _remove_entry(self, key: str) -> None:
"""
Remove a cache entry and update statistics.
Args:
key: Cache key to remove
"""
entry = self._cache.pop(key, None)
if entry:
self._stats["current_size_bytes"] -= entry.size_bytes
self._stats["entry_count"] -= 1
async def _cleanup_loop(self) -> None:
"""Background task for periodic cache cleanup."""
while self._running:
try:
await asyncio.sleep(self.cleanup_interval)
if not self._running:
break
# Remove expired entries
expired_count = await self.evict_expired()
# Log cache statistics periodically
stats = await self.get_cache_stats()
logger.debug(f"Cache stats: {stats.entry_count} entries, "
f"{stats.total_size_bytes / 1024 / 1024:.1f}MB, "
f"hit rate: {stats.hit_rate:.2%}")
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"Error in cache cleanup loop: {e}")
def get_cache_info(self) -> Dict[str, Any]:
"""
Get detailed cache information for debugging.
Returns:
Dictionary with cache details
"""
return {
"max_size_bytes": self.max_size_bytes,
"current_size_bytes": self._stats["current_size_bytes"],
"entry_count": self._stats["entry_count"],
"default_ttl": self.default_ttl,
"cleanup_interval": self.cleanup_interval,
"running": self._running,
"stats": self._stats.copy()
}
async def __aenter__(self):
"""Async context manager entry."""
await self.start()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
"""Async context manager exit."""
await self.stop()
class RedisCacheManager(CacheManagerInterface):
"""
Redis-based cache manager for distributed caching.
This implementation uses Redis for persistent, distributed caching
across multiple application instances.
"""
def __init__(
self,
redis_url: str,
key_prefix: str = "voice_control:cache:",
default_ttl: int = 3600,
max_connections: int = 10
):
"""
Initialize Redis cache manager.
Args:
redis_url: Redis connection URL
key_prefix: Prefix for cache keys
default_ttl: Default time-to-live in seconds
max_connections: Maximum Redis connections
"""
self.redis_url = redis_url
self.key_prefix = key_prefix
self.default_ttl = default_ttl
self.max_connections = max_connections
self._redis = None
self._stats_key = f"{key_prefix}stats"
logger.info(f"RedisCacheManager initialized with URL: {redis_url}")
async def start(self) -> None:
"""Initialize Redis connection."""
try:
import redis.asyncio as redis
self._redis = redis.from_url(
self.redis_url,
max_connections=self.max_connections,
decode_responses=False # We handle bytes directly
)
# Test connection
await self._redis.ping()
logger.info("Redis cache manager connected")
except ImportError:
raise CacheError("redis_import", "redis package not installed")
except Exception as e:
raise CacheError("redis_connection", f"Failed to connect to Redis: {e}")
async def stop(self) -> None:
"""Close Redis connection."""
if self._redis:
await self._redis.close()
logger.info("Redis cache manager disconnected")
async def get_cached_transcription(
self,
audio_fingerprint: str
) -> Optional[TranscriptionResult]:
"""
Retrieve cached transcription result from Redis.
Args:
audio_fingerprint: Unique fingerprint of audio data
Returns:
Cached TranscriptionResult or None if not found
"""
if not self._redis:
raise CacheError("redis_not_connected", "Redis not connected")
try:
key = f"{self.key_prefix}{audio_fingerprint}"
# Get cached data
cached_data = await self._redis.get(key)
if cached_data is None:
await self._increment_stat("cache_misses")
return None
# Deserialize transcription result
import pickle
result = pickle.loads(cached_data)
await self._increment_stat("cache_hits")
logger.debug(f"Redis cache hit for fingerprint: {audio_fingerprint[:16]}...")
return result
except Exception as e:
logger.error(f"Failed to get cached transcription from Redis: {e}")
await self._increment_stat("cache_misses")
return None
async def cache_transcription(
self,
audio_fingerprint: str,
result: TranscriptionResult,
ttl: Optional[int] = None
) -> bool:
"""
Cache a transcription result in Redis.
Args:
audio_fingerprint: Unique fingerprint of audio data
result: TranscriptionResult to cache
ttl: Time to live in seconds (uses default if None)
Returns:
True if caching was successful, False otherwise
"""
if not self._redis:
raise CacheError("redis_not_connected", "Redis not connected")
if ttl is None:
ttl = self.default_ttl
try:
key = f"{self.key_prefix}{audio_fingerprint}"
# Serialize transcription result
import pickle
cached_data = pickle.dumps(result)
# Store in Redis with TTL
await self._redis.setex(key, ttl, cached_data)
logger.debug(f"Cached transcription in Redis for fingerprint: {audio_fingerprint[:16]}... "
f"(ttl: {ttl}s)")
return True
except Exception as e:
logger.error(f"Failed to cache transcription in Redis: {e}")
return False
async def generate_audio_fingerprint(self, audio_data: bytes) -> str:
"""
Generate a unique fingerprint for audio data.
Args:
audio_data: Raw audio bytes
Returns:
Unique fingerprint string
"""
# Use the same implementation as in-memory cache
cache_manager = CacheManager()
return await cache_manager.generate_audio_fingerprint(audio_data)
async def get_cache_stats(self) -> CacheStats:
"""
Get cache performance statistics from Redis.
Returns:
CacheStats with hit rates and usage information
"""
if not self._redis:
raise CacheError("redis_not_connected", "Redis not connected")
try:
# Get stats from Redis hash
stats_data = await self._redis.hgetall(self._stats_key)
# Convert bytes to integers
stats = {}
for key, value in stats_data.items():
if isinstance(key, bytes):
key = key.decode('utf-8')
if isinstance(value, bytes):
value = int(value.decode('utf-8'))
stats[key] = value
# Get cache size info
cache_keys = await self._redis.keys(f"{self.key_prefix}*")
entry_count = len([k for k in cache_keys if not k.decode('utf-8').endswith(':stats')])
return CacheStats(
total_requests=stats.get("total_requests", 0),
cache_hits=stats.get("cache_hits", 0),
cache_misses=stats.get("cache_misses", 0),
hit_rate=0.0, # Will be calculated in __post_init__
total_size_bytes=0, # Not easily calculable in Redis
entry_count=entry_count,
evictions=stats.get("evictions", 0)
)
except Exception as e:
logger.error(f"Failed to get cache stats from Redis: {e}")
return CacheStats(0, 0, 0, 0.0, 0, 0, 0)
async def clear_cache(self) -> None:
"""Clear all cached entries from Redis."""
if not self._redis:
raise CacheError("redis_not_connected", "Redis not connected")
try:
# Get all cache keys
cache_keys = await self._redis.keys(f"{self.key_prefix}*")
if cache_keys:
await self._redis.delete(*cache_keys)
logger.info(f"Cleared {len(cache_keys)} entries from Redis cache")
except Exception as e:
logger.error(f"Failed to clear Redis cache: {e}")
async def evict_expired(self) -> int:
"""
Remove expired cache entries from Redis.
Redis handles TTL expiration automatically, so this is a no-op.
Returns:
Number of entries evicted (always 0 for Redis)
"""
# Redis handles TTL expiration automatically
return 0
async def _increment_stat(self, stat_name: str) -> None:
"""Increment a statistic counter in Redis."""
try:
await self._redis.hincrby(self._stats_key, stat_name, 1)
except Exception as e:
logger.error(f"Failed to increment stat {stat_name}: {e}")
async def __aenter__(self):
"""Async context manager entry."""
await self.start()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
"""Async context manager exit."""
await self.stop()
def create_cache_manager(
cache_config: Dict[str, Any]
) -> CacheManagerInterface:
"""
Factory function to create appropriate cache manager based on configuration.
Args:
cache_config: Cache configuration dictionary
Returns:
CacheManagerInterface implementation
"""
redis_url = cache_config.get("redis_url")
if redis_url:
return RedisCacheManager(
redis_url=redis_url,
default_ttl=cache_config.get("default_ttl", 3600),
max_connections=cache_config.get("max_connections", 10)
)
else:
return CacheManager(
max_size_mb=cache_config.get("max_size_mb", 100),
default_ttl=cache_config.get("default_ttl", 3600),
cleanup_interval=cache_config.get("cleanup_interval", 600)
) |