CoolFace
Apppublic

ghstedpixel/app.py

sourceHugging Faceupdated 4mo agoView on Hugging Face
0likes
database.py112 linesDownload Raw Back to root
1import json2import time3import re4from config import REDIS_URL5 6REDIS_AVAILABLE = False7try:8    import redis9    REDIS_AVAILABLE = True10except ImportError:11    print("⚠️ WARNING: 'redis' library not installed. Caching will fall back to local in-memory dictionaries.")12 13# --- SMART STORAGE MEMORY NODE LAYERS ---14redis_client = None15IN_MEMORY_CACHE = {}16IN_MEMORY_EXPIRY = {}17 18if REDIS_AVAILABLE and REDIS_URL:19    try:20        redis_client = redis.Redis.from_url(REDIS_URL, decode_responses=True)21        redis_client.ping()22        print("📶 [Cache Setup] Connected securely to remote Redis server node.")23    except Exception as e:24        print(f"⚠️ [Cache Setup] Redis connection failed ({e}). Defaulting to internal memory arrays.")25        redis_client = None26 27def get_cache_key(product_name: str, size: str = "", mode: str = "balanced") -> str:28    """Generates a unique deterministic cache key combining name, size, and search mode"""29    clean_name = re.sub(r'[^a-z0-9 ]', '', product_name.lower().strip())30    clean_size = re.sub(r'[^a-z0-9 ]', '', size.lower().strip()) if size else "nosize"31    clean_name = clean_name.replace(" ", "_")32    clean_size = clean_size.replace(" ", "_")33    return f"tarz:cache:{clean_name}:{clean_size}:{mode}"34 35def get_cached_deals(product_name: str, size: str = "", mode: str = "balanced") -> list:36    """Retrieves cached pricing data array if available and unexpired"""37    key = get_cache_key(product_name, size, mode)38    if redis_client:39        try:40            data = redis_client.get(key)41            if data: return json.loads(data)42        except Exception as e:43            print(f"⚠️ [Redis Cache Error] Read failed: {e}")44    else:45        if key in IN_MEMORY_CACHE:46            if time.time() < IN_MEMORY_EXPIRY.get(key, 0):47                return IN_MEMORY_CACHE[key]48            else:49                del IN_MEMORY_CACHE[key]50                del IN_MEMORY_EXPIRY[key]51    return None52 53def set_cached_deals(product_name: str, size: str, mode: str, deals: list):54    """Caches product list matrix with strict 2-hour sliding validation lifetime"""55    if not deals: return56    key = get_cache_key(product_name, size, mode)57    if redis_client:58        try:59            redis_client.setex(key, 7200, json.dumps(deals))60        except Exception as e:61            print(f"⚠️ [Redis Cache Error] Write failed: {e}")62    else:63        IN_MEMORY_CACHE[key] = deals64        IN_MEMORY_EXPIRY[key] = time.time() + 720065 66def get_base_price(product_name: str, size: str = "", mode: str = "balanced") -> float:67    """Retrieves the previous cycle's lowest observed stable price benchmark"""68    key = get_cache_key(product_name, size, mode).replace("tarz:cache:", "tarz:baseprice:")69    if redis_client:70        try:71            val = redis_client.get(key)72            if val: return float(val)73        except: pass74    else:75        return IN_MEMORY_CACHE.get(key)76    return None77 78def set_base_price(product_name: str, size: str, mode: str, price: float):79    """Saves a new lowest benchmark configuration when an active shift is confirmed"""80    key = get_cache_key(product_name, size, mode).replace("tarz:cache:", "tarz:baseprice:")81    if redis_client:82        try: redis_client.set(key, str(price))83        except: pass84    else:85        IN_MEMORY_CACHE[key] = price86 87def get_cached_coupons(product_name: str) -> list:88    """Retrieves isolated promotional matrices matching strict text layout structures"""89    clean_name = re.sub(r'[^a-z0-9 ]', '', product_name.lower().strip()).replace(" ", "_")90    key = f"tarz:coupons:{clean_name}"91    if redis_client:92        try:93            data = redis_client.get(key)94            if data: return json.loads(data)95        except: pass96    else:97        if key in IN_MEMORY_CACHE:98            if time.time() < IN_MEMORY_EXPIRY.get(key, 0):99                return IN_MEMORY_CACHE[key]100    return None101 102def set_cached_coupons(product_name: str, coupons: list):103    """Caches discovered active promo strings (saves empty results for 15 mins to prevent loop spam)"""104    clean_name = re.sub(r'[^a-z0-9 ]', '', product_name.lower().strip()).replace(" ", "_")105    key = f"tarz:coupons:{clean_name}"106    duration = 7200 if coupons else 900107    if redis_client:108        try: redis_client.setex(key, duration, json.dumps(coupons))109        except: pass110    else:111        IN_MEMORY_CACHE[key] = coupons112        IN_MEMORY_EXPIRY[key] = time.time() + duration