Spaces:
Running
Running
File size: 2,227 Bytes
4d1849f |
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 |
import logging
from collections import defaultdict
from typing import Dict
logger = logging.getLogger(__name__)
class ResponseOptimizer:
"""π Public Response Optimizer (Basic Filtering + Length Control)"""
def __init__(self):
self.response_cache = {} # Stores past responses to reduce redundant processing
self.optim_rules = defaultdict(list) # Holds rule-based response refinements
self.cache_limit = 100 # β
Limit cache size to avoid overflow
async def optimize_response(self, response: str, context: Dict) -> str:
"""β
Optimizes AI-generated responses (Fast + Secure)."""
# β
Return cached response if available
if response in self.response_cache:
logger.info("β
Returning cached optimized response.")
return self.response_cache[response]
# β
Apply context-based optimization (length, profanity)
optimized_response = self.apply_optimizations(response, context)
# β
Store in cache (Respect size limit)
if len(self.response_cache) >= self.cache_limit:
oldest_response = next(iter(self.response_cache))
del self.response_cache[oldest_response]
self.response_cache[response] = optimized_response
return optimized_response
def apply_optimizations(self, response: str, context: Dict) -> str:
"""β
Applies context-specific response optimization."""
if "filter_profanity" in context and context["filter_profanity"]:
response = self.remove_profanity(response)
if "trim_length" in context:
response = response[:context["trim_length"]].strip() + "..." # Trims to desired length
return response
def remove_profanity(self, response: str) -> str:
"""π« Removes flagged words from AI-generated responses."""
banned_words = [
"badword1", "badword2", "badword3", "shit", "fuck", "damn", "bitch", "asshole"
] # β
Add or remove based on testing
for word in banned_words:
response = response.replace(word, "***") # β
Replace with censorship symbol
return response
|