Spaces:
Running

raij-ai / utils.py
github-actions[bot]
chore: sync from GitHub 2026-06-26 20:03:54 UTC
53a12c2
Raw History Blame Contribute Delete
6.64 kB
import os
import time
import numpy as np
from pathlib import Path
from dotenv import load_dotenv
from supabase import create_client, Client
## Get the base directory (src folder)
BASE_DIR = Path(__file__).parent
## Loading Environment Variables
env_path = os.environ.get("ENV_FILE", BASE_DIR / "config.env")
if os.path.exists(env_path):
load_dotenv(env_path)
SUPABASE_URL = os.getenv("NEXT_PUBLIC_SUPABASE_URL")
SUPABASE_KEY = os.getenv("NEXT_PUBLIC_SUPABASE_ANON_KEY")
SUPABASE_SERVICE_KEY = os.getenv("SUPABASE_SERVICE_ROLE_KEY")
if not SUPABASE_URL or not SUPABASE_KEY:
print("⚠️ Warning: Supabase env vars not set. Check HF Spaces secrets.")
supabase = None
else:
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
# Service-role client — bypasses RLS, used by recommenders to read user data
if not SUPABASE_URL or not SUPABASE_SERVICE_KEY:
supabase_service = None
else:
supabase_service: Client = create_client(SUPABASE_URL, SUPABASE_SERVICE_KEY)
def get_product_images(product_ids: list) -> dict:
"""
Fetch product images from the product_images table in Supabase.
Returns a dict mapping product_id -> image_url
"""
if not product_ids:
return {}
try:
# Query product_images table for the given product IDs
response = supabase.table("product_images").select("product_id, url").in_("product_id", list(product_ids)).execute()
# Build a mapping of product_id -> url (use first image if multiple)
images_map = {}
for row in response.data:
pid = row.get("product_id")
url = row.get("url")
if pid and url and pid not in images_map:
images_map[pid] = url
return images_map
except Exception as e:
print(f"Error fetching product images: {e}")
return {}
def get_product_prices(product_ids: list) -> dict:
"""
Fetch product prices from the products table in Supabase.
Returns a dict mapping product_id -> price
"""
if not product_ids:
return {}
try:
response = supabase.table("products").select("id, price").in_("id", list(product_ids)).execute()
prices_map = {}
for row in response.data:
pid = row.get("id")
price = row.get("price")
if pid:
prices_map[pid] = price
return prices_map
except Exception as e:
print(f"Error fetching product prices: {e}")
return {}
def get_product_details(product_id: str) -> dict:
"""
Fetch complete product details from Supabase by product ID.
Returns product info including title, description, price, old_price, sku, stock, store name, etc.
"""
try:
response = supabase.table("products").select("*").eq("id", product_id).execute()
if not response.data:
return None
product = response.data[0]
# Get product images
images_response = supabase.table("product_images").select("url").eq("product_id", product_id).execute()
images = [img.get("url") for img in images_response.data if img.get("url")]
# Get store name
store_name = None
store_id = product.get("store_id")
if store_id:
store_response = supabase.table("stores").select("name").eq("id", store_id).execute()
if store_response.data:
store_name = store_response.data[0].get("name")
return {
"id": product.get("id"),
"title": product.get("title"),
"description": product.get("description"),
"price": product.get("price"),
"old_price": product.get("old_price"),
"sku": product.get("sku"),
"stock": product.get("stock", 0),
"sold_by": store_name,
"images": images,
}
except Exception as e:
print(f"Error fetching product details: {e}")
return None
def get_random_products(limit: int = 10) -> list:
"""
Fetch products from Supabase to display before searching.
Returns a list of products with id, title, price, and image_url.
"""
try:
response = supabase.table("products").select("id, title, price").limit(limit).execute()
if not response.data:
return []
products = response.data
product_ids = [p.get("id") for p in products]
images_map = get_product_images(product_ids)
return [
{
"id": p.get("id"),
"title": p.get("title"),
"price": p.get("price"),
"image_url": images_map.get(p.get("id"))
}
for p in products
]
except Exception as e:
print(f"Error fetching random products: {e}")
return []
def load_categories(file_name=None, clean=False):
categories_path = BASE_DIR / "smart_search" / "categories.txt"
if file_name is None:
file_name = str(categories_path)
try:
with open(file_name, 'r') as file:
lines = [line.strip() for line in file.readlines() if line.strip()]
if clean:
return [line.split(":", 1)[0].strip() for line in lines]
return lines
except FileNotFoundError:
print("Categories.txt file is not found")
return ["Product", "Electronics", "Fashion", "Home"]
def _parse_vector(raw_vector) -> np.ndarray | None:
if not raw_vector:
return None
if isinstance(raw_vector, list):
return np.array(raw_vector, dtype=np.float32)
if isinstance(raw_vector, np.ndarray):
return raw_vector
try:
import json
if isinstance(raw_vector, str):
if raw_vector.startswith('['):
return np.array(json.loads(raw_vector), dtype=np.float32)
else:
return np.array([float(x) for x in raw_vector.replace('(', '').replace(')', '').split(',')], dtype=np.float32)
except Exception:
pass
return None
class _LazyProxy:
def __init__(self, loader):
object.__setattr__(self, '_loader', loader)
object.__setattr__(self, '_obj', None)
def _load(self):
if object.__getattribute__(self, '_obj') is None:
obj = object.__getattribute__(self, '_loader')()
object.__setattr__(self, '_obj', obj)
return object.__getattribute__(self, '_obj')
def __getattr__(self, name):
return getattr(self._load(), name)
def __call__(self, *args, **kwargs):
return self._load()(*args, **kwargs)