sohamnk commited on
Commit
da0d66d
Β·
verified Β·
1 Parent(s): 9ad8225

Update pipeline/routes.py

Browse files
Files changed (1) hide show
  1. pipeline/routes.py +14 -29
pipeline/routes.py CHANGED
@@ -6,20 +6,17 @@ from flask import request, jsonify
6
  # Import app, models, and logic functions
7
  from pipeline import app, models, logic
8
 
9
-
10
  @app.route('/process', methods=['POST'])
11
  def process_item():
12
- print("\n" + "=" * 50)
13
  print("➑ [Request] Received new request to /process")
14
-
15
  try:
16
  data = request.get_json()
17
- if not data:
18
- return jsonify({"error": "Invalid JSON payload"}), 400
19
 
20
  object_name = data.get('objectName')
21
  description = data.get('objectDescription')
22
- image_url = data.get('objectImage')
23
 
24
  if not all([object_name, description]):
25
  return jsonify({"error": "objectName and objectDescription are required."}), 400
@@ -42,7 +39,7 @@ def process_item():
42
  print("--- No image URL provided, skipping visual feature extraction. ---")
43
 
44
  print("βœ… Successfully processed item.")
45
- print("=" * 50)
46
  return jsonify(response_data), 200
47
 
48
  except Exception as e:
@@ -50,23 +47,20 @@ def process_item():
50
  traceback.print_exc()
51
  return jsonify({"error": str(e)}), 500
52
 
53
-
54
  @app.route('/compare', methods=['POST'])
55
  def compare_items():
56
- print("\n" + "=" * 50)
57
  print("➑ [Request] Received new request to /compare")
58
-
59
  try:
60
  data = request.get_json()
61
- if not data:
62
- return jsonify({"error": "Invalid JSON payload"}), 400
63
 
64
  query_item = data.get('queryItem')
65
  search_list = data.get('searchList')
66
 
67
  if not all([query_item, search_list]):
68
  return jsonify({"error": "queryItem and searchList are required."}), 400
69
-
70
  query_text_emb = np.array(query_item['text_embedding'])
71
  results = []
72
  print(f"--- Comparing 1 query item against {len(search_list)} items ---")
@@ -74,7 +68,6 @@ def compare_items():
74
  for item in search_list:
75
  item_id = item.get('_id')
76
  print(f"\n [Checking] Item ID: {item_id}")
77
-
78
  try:
79
  text_emb_found = np.array(item['text_embedding'])
80
  text_score = logic.cosine_similarity(query_text_emb, text_emb_found)
@@ -85,27 +78,20 @@ def compare_items():
85
 
86
  if has_query_image and has_item_image:
87
  print(" - Both items have images. Performing visual comparison.")
88
- from pipeline import FEATURE_WEIGHTS # Import constant
89
-
90
  query_shape = np.array(query_item['shape_features'])
91
  query_color = np.array(query_item['color_features']).astype("float32")
92
  query_texture = np.array(query_item['texture_features']).astype("float32")
93
-
94
  found_shape = np.array(item['shape_features'])
95
  found_color = np.array(item['color_features']).astype("float32")
96
  found_texture = np.array(item['texture_features']).astype("float32")
97
-
98
  shape_dist = cv2.matchShapes(query_shape, found_shape, cv2.CONTOURS_MATCH_I1, 0.0)
99
  shape_score = 1.0 / (1.0 + shape_dist)
100
  color_score = cv2.compareHist(query_color, found_color, cv2.HISTCMP_CORREL)
101
  texture_score = cv2.compareHist(query_texture, found_texture, cv2.HISTCMP_CORREL)
102
-
103
- raw_image_score = (
104
- FEATURE_WEIGHTS["shape"] * shape_score +
105
- FEATURE_WEIGHTS["color"] * color_score +
106
- FEATURE_WEIGHTS["texture"] * texture_score
107
- )
108
-
109
  print(f"Raw Image Score: {raw_image_score:.4f}")
110
  image_score = logic.stretch_image_score(raw_image_score)
111
  final_score = 0.4 * image_score + 0.6 * text_score
@@ -114,7 +100,7 @@ def compare_items():
114
  print(" - One or both items missing image. Using text score only.")
115
  final_score = text_score
116
 
117
- from pipeline import FINAL_SCORE_THRESHOLD # Import constant
118
  if final_score >= FINAL_SCORE_THRESHOLD:
119
  print(f" - βœ… ACCEPTED (Score >= {FINAL_SCORE_THRESHOLD})")
120
  results.append({
@@ -126,17 +112,16 @@ def compare_items():
126
  })
127
  else:
128
  print(f" - ❌ REJECTED (Score < {FINAL_SCORE_THRESHOLD})")
129
-
130
  except Exception as e:
131
  print(f" [Skipping] Item {item_id} due to processing error: {e}")
132
  continue
133
 
134
  results.sort(key=lambda x: x["score"], reverse=True)
135
  print(f"\nβœ… Search complete. Found {len(results)} potential matches.")
136
- print("=" * 50)
137
  return jsonify({"matches": results}), 200
138
 
139
  except Exception as e:
140
  print(f"❌ Error in /compare: {e}")
141
  traceback.print_exc()
142
- return jsonify({"error": str(e)}), 500
 
6
  # Import app, models, and logic functions
7
  from pipeline import app, models, logic
8
 
 
9
  @app.route('/process', methods=['POST'])
10
  def process_item():
11
+ print("\n" + "="*50)
12
  print("➑ [Request] Received new request to /process")
 
13
  try:
14
  data = request.get_json()
15
+ if not data: return jsonify({"error": "Invalid JSON payload"}), 400
 
16
 
17
  object_name = data.get('objectName')
18
  description = data.get('objectDescription')
19
+ image_url = data.get('objectImage')
20
 
21
  if not all([object_name, description]):
22
  return jsonify({"error": "objectName and objectDescription are required."}), 400
 
39
  print("--- No image URL provided, skipping visual feature extraction. ---")
40
 
41
  print("βœ… Successfully processed item.")
42
+ print("="*50)
43
  return jsonify(response_data), 200
44
 
45
  except Exception as e:
 
47
  traceback.print_exc()
48
  return jsonify({"error": str(e)}), 500
49
 
 
50
  @app.route('/compare', methods=['POST'])
51
  def compare_items():
52
+ print("\n" + "="*50)
53
  print("➑ [Request] Received new request to /compare")
 
54
  try:
55
  data = request.get_json()
56
+ if not data: return jsonify({"error": "Invalid JSON payload"}), 400
 
57
 
58
  query_item = data.get('queryItem')
59
  search_list = data.get('searchList')
60
 
61
  if not all([query_item, search_list]):
62
  return jsonify({"error": "queryItem and searchList are required."}), 400
63
+
64
  query_text_emb = np.array(query_item['text_embedding'])
65
  results = []
66
  print(f"--- Comparing 1 query item against {len(search_list)} items ---")
 
68
  for item in search_list:
69
  item_id = item.get('_id')
70
  print(f"\n [Checking] Item ID: {item_id}")
 
71
  try:
72
  text_emb_found = np.array(item['text_embedding'])
73
  text_score = logic.cosine_similarity(query_text_emb, text_emb_found)
 
78
 
79
  if has_query_image and has_item_image:
80
  print(" - Both items have images. Performing visual comparison.")
81
+ from pipeline import FEATURE_WEIGHTS # Import constant
 
82
  query_shape = np.array(query_item['shape_features'])
83
  query_color = np.array(query_item['color_features']).astype("float32")
84
  query_texture = np.array(query_item['texture_features']).astype("float32")
 
85
  found_shape = np.array(item['shape_features'])
86
  found_color = np.array(item['color_features']).astype("float32")
87
  found_texture = np.array(item['texture_features']).astype("float32")
 
88
  shape_dist = cv2.matchShapes(query_shape, found_shape, cv2.CONTOURS_MATCH_I1, 0.0)
89
  shape_score = 1.0 / (1.0 + shape_dist)
90
  color_score = cv2.compareHist(query_color, found_color, cv2.HISTCMP_CORREL)
91
  texture_score = cv2.compareHist(query_texture, found_texture, cv2.HISTCMP_CORREL)
92
+ raw_image_score = (FEATURE_WEIGHTS["shape"] * shape_score +
93
+ FEATURE_WEIGHTS["color"] * color_score +
94
+ FEATURE_WEIGHTS["texture"] * texture_score)
 
 
 
 
95
  print(f"Raw Image Score: {raw_image_score:.4f}")
96
  image_score = logic.stretch_image_score(raw_image_score)
97
  final_score = 0.4 * image_score + 0.6 * text_score
 
100
  print(" - One or both items missing image. Using text score only.")
101
  final_score = text_score
102
 
103
+ from pipeline import FINAL_SCORE_THRESHOLD # Import constant
104
  if final_score >= FINAL_SCORE_THRESHOLD:
105
  print(f" - βœ… ACCEPTED (Score >= {FINAL_SCORE_THRESHOLD})")
106
  results.append({
 
112
  })
113
  else:
114
  print(f" - ❌ REJECTED (Score < {FINAL_SCORE_THRESHOLD})")
 
115
  except Exception as e:
116
  print(f" [Skipping] Item {item_id} due to processing error: {e}")
117
  continue
118
 
119
  results.sort(key=lambda x: x["score"], reverse=True)
120
  print(f"\nβœ… Search complete. Found {len(results)} potential matches.")
121
+ print("="*50)
122
  return jsonify({"matches": results}), 200
123
 
124
  except Exception as e:
125
  print(f"❌ Error in /compare: {e}")
126
  traceback.print_exc()
127
+ return jsonify({"error": str(e)}), 500