mdanish commited on
Commit
cb18289
·
verified ·
1 Parent(s): 35edfe0

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +25 -1
app.py CHANGED
@@ -11,6 +11,7 @@ knnpath = '20241204-ams-no-env-open_clip_ViT-H-14-378-quickgelu.npz'
11
  clip_model_name = 'ViT-H-14-378-quickgelu'
12
  pretrained_name = 'dfn5b'
13
 
 
14
 
15
  # Set page config
16
  st.set_page_config(
@@ -47,6 +48,25 @@ def process_image(image, preprocess):
47
  processed_image = preprocess(image).unsqueeze(0)
48
  return processed_image
49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  @st.cache_resource
51
  def load_knn():
52
  return np.load(knnpath)
@@ -73,7 +93,7 @@ def main():
73
  try:
74
  image = Image.open(file)
75
 
76
- st.image(image, caption="Uploaded Image", use_column_width=True)
77
 
78
  # Process image
79
  with st.spinner('Processing image...'):
@@ -87,6 +107,10 @@ def main():
87
  # Normalize vector
88
  vec /= vec.norm(dim=-1, keepdim=True)
89
  st.write(vec.shape)
 
 
 
 
90
  except Exception as e:
91
  st.error(f"Error processing image: {str(e)}")
92
 
 
11
  clip_model_name = 'ViT-H-14-378-quickgelu'
12
  pretrained_name = 'dfn5b'
13
 
14
+ categories = ['walkability', 'bikeability', 'pleasantness', 'greenness', 'safety']
15
 
16
  # Set page config
17
  st.set_page_config(
 
48
  processed_image = preprocess(image).unsqueeze(0)
49
  return processed_image
50
 
51
+ def knn_get_score(knn, k, cat, vec):
52
+ allvecs = knn[f'{cat}_vecs']
53
+ scores = knn[f'{cat}_scores']
54
+ # Compute cosine similiarity of vec against allvecs
55
+ # (both are already normalized)
56
+ cos_sim_table = vec @ allvecs.T
57
+ # Get sorted array indices by similiarity in descending order
58
+ sortinds = np.flip(np.argsort(cos_sim_table))
59
+ # Get corresponding scores for the sorted vectors
60
+ kscores = scores[sortinds][:k]
61
+ # Get actual sorted similiarity scores
62
+ ksims = np.expand_dims(cos_sim_table[sortinds][:k], axis=0)
63
+ # Apply normalization after exponential formula
64
+ ksims = softmax(10**ksims)
65
+ # Weighted sum
66
+ kweightedscore = np.sum(kscores * ksims)
67
+ return kweightedscore
68
+
69
+
70
  @st.cache_resource
71
  def load_knn():
72
  return np.load(knnpath)
 
93
  try:
94
  image = Image.open(file)
95
 
96
+ st.image(image, caption="Uploaded Image", width=640)
97
 
98
  # Process image
99
  with st.spinner('Processing image...'):
 
107
  # Normalize vector
108
  vec /= vec.norm(dim=-1, keepdim=True)
109
  st.write(vec.shape)
110
+ k = 40
111
+ for cat in categories:
112
+ st.write(cat, 'rating =', knn_get_score(knn, k, cat, vec))
113
+
114
  except Exception as e:
115
  st.error(f"Error processing image: {str(e)}")
116