Spaces:
Sleeping

shfatime commited on
Commit
f27422a
·
verified ·
1 Parent(s): 3f7def2

Delete backend/unified_search.py

Browse files
Files changed (1) hide show
  1. backend/unified_search.py +0 -106
backend/unified_search.py DELETED
@@ -1,106 +0,0 @@
1
- """Unified hybrid text and CLIP image search with catalog filters."""
2
- import argparse
3
- import json
4
- import math
5
- import sys
6
-
7
- class UnifiedSearch:
8
- def __init__(self):
9
- self.text_search = None
10
- self.image_search = None
11
-
12
- @staticmethod
13
- def filter_results(results, category=None, min_price=None, max_price=None, limit=5):
14
- if limit < 1:
15
- raise ValueError('Limit must be positive')
16
- if category is not None and not category.strip():
17
- raise ValueError('Category must not be empty')
18
- for price in (min_price, max_price):
19
- if price is not None and (not math.isfinite(price) or price < 0):
20
- raise ValueError('Price bounds must be finite and nonnegative')
21
- if min_price is not None and max_price is not None and min_price > max_price:
22
- raise ValueError('Minimum price cannot exceed maximum price')
23
- category = category.strip().casefold() if category is not None else None
24
- filtered = []
25
- for result in results:
26
- product = result['product']
27
- if category and category not in (str(product.get('main_category') or '').casefold(),
28
- str(product.get('original_category') or '').casefold()):
29
- continue
30
- price = product.get('price')
31
- if (min_price is not None or max_price is not None) and (price is None or not math.isfinite(price)):
32
- continue
33
- if min_price is not None and price < min_price or max_price is not None and price > max_price:
34
- continue
35
- filtered.append({
36
- 'product_id': product['parent_asin'], 'title': product['title'],
37
- 'price': price, 'category': product['main_category'],
38
- 'original_category': product['original_category'], 'image_path': product['image_path'],
39
- 'relevance_score': result['score'], 'ranking_reasons': result['reasons'],
40
- })
41
- if len(filtered) == limit:
42
- break
43
- return filtered
44
-
45
- def text(self, query, category=None, min_price=None, max_price=None, limit=5):
46
- if not query.strip():
47
- raise ValueError('Text query must not be empty')
48
- if self.text_search is None:
49
- from backend.search import ProductSearch
50
- self.text_search = ProductSearch()
51
- search = self.text_search
52
- products = {product['parent_asin']: product for product in search.products}
53
- lexical = search.keyword(query, len(products))
54
- semantic = search.semantic(query, len(products))
55
- keyword_ranks = {result['parent_asin']: rank for rank, result in enumerate(lexical, 1)}
56
- results = []
57
- for rank, result in enumerate(semantic, 1):
58
- product_id = result['parent_asin']
59
- keyword_rank = keyword_ranks.get(product_id)
60
- # Equal-weight reciprocal rank fusion; missing keyword matches contribute zero.
61
- score = 61 / 2 * (1 / (60 + rank) + (1 / (60 + keyword_rank) if keyword_rank else 0))
62
- reasons = [f'E5 semantic rank {rank}; cosine {result["score"]:.4f}',
63
- f'BM25 keyword rank {keyword_rank}' if keyword_rank else 'No BM25 token match']
64
- results.append({'product': products[product_id], 'score': score, 'reasons': reasons})
65
- results.sort(key=lambda result: (-result['score'], result['product']['parent_asin']))
66
- return self.filter_results(results, category, min_price, max_price, limit)
67
-
68
- def image(self, path, category=None, min_price=None, max_price=None, limit=5):
69
- if self.image_search is None:
70
- from backend.image_search import ImageSearch
71
- self.image_search = ImageSearch()
72
- search = self.image_search
73
- products = {product['parent_asin']: product for product in search.products}
74
- matches = search.search(path, len(products))
75
- results = [{'product': products[match['parent_asin']], 'score': match['score'],
76
- 'reasons': [f'CLIP image cosine similarity {match["score"]:.4f}']}
77
- for match in matches]
78
- return self.filter_results(results, category, min_price, max_price, limit)
79
-
80
-
81
- def main():
82
- parser = argparse.ArgumentParser(description='Search products by text or image.')
83
- query = parser.add_mutually_exclusive_group(required=True)
84
- query.add_argument('--text', help='English or Azerbaijani text query')
85
- query.add_argument('--image', help='Path to a query image')
86
- parser.add_argument('--category', help='Exact main or original category, case-insensitive')
87
- parser.add_argument('--min-price', type=float, help='Inclusive minimum price')
88
- parser.add_argument('--max-price', type=float, help='Inclusive maximum price')
89
- parser.add_argument('--top', type=int, default=5, help='Maximum number of results')
90
- args = parser.parse_args()
91
- # Validate filters before loading models and indexes.
92
- try:
93
- UnifiedSearch.filter_results([], args.category, args.min_price, args.max_price, args.top)
94
- search = UnifiedSearch()
95
- options = dict(category=args.category, min_price=args.min_price, max_price=args.max_price, limit=args.top)
96
- results = search.text(args.text, **options) if args.text is not None else search.image(args.image, **options)
97
- except (ValueError, OSError) as exc:
98
- parser.exit(1, f'{exc}\n')
99
- if hasattr(sys.stdout, 'reconfigure'):
100
- sys.stdout.reconfigure(encoding='utf-8')
101
- print(json.dumps({'mode': 'text' if args.text is not None else 'image', 'results': results},
102
- ensure_ascii=False, indent=2))
103
-
104
-
105
- if __name__ == '__main__':
106
- main()