Maximef commited on
Commit
3d16530
·
1 Parent(s): f32bd53

add recommendation.py

Browse files
Files changed (3) hide show
  1. TopBrands.xlsx +0 -0
  2. app.py +16 -4
  3. recommendation.py +29 -0
TopBrands.xlsx ADDED
Binary file (13.2 kB). View file
 
app.py CHANGED
@@ -9,6 +9,8 @@ from PIL import Image
9
  from numpy import random
10
  from pathlib import Path
11
  import torch.backends.cudnn as cudnn
 
 
12
  from models.experimental import attempt_load
13
 
14
  from utils.datasets import LoadStreams, LoadImages
@@ -35,6 +37,7 @@ def print_output(txt_path):
35
  def detect_logo(img, model, confidence):
36
  if model == 'Yologo':
37
  model = 'best_logo' # Naming Convention for yolov7 See output file of https://www.kaggle.com/code/owaiskhan9654/training-yolov7-on-kaggle-on-custom-dataset/data
 
38
  parser = argparse.ArgumentParser()
39
  parser.add_argument('--weights', nargs='+', type=str, default=model + ".pt", help='model.pt path(s)')
40
  parser.add_argument('--source', type=str, default='inference/', help='source')
@@ -119,14 +122,18 @@ def detect_logo(img, model, confidence):
119
  txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
120
  s += '%gx%g ' % img.shape[2:]
121
  gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]
 
 
122
  if len(det):
123
  det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
124
 
125
  for c in det[:, -1].unique():
126
  n = (det[:, -1] == c).sum()
127
  s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "
128
-
129
  for *xyxy, conf, cls in reversed(det):
 
 
 
130
  if save_txt:
131
  xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()
132
  line = (names[int(cls.item())], *xywh, conf) if opt.save_conf else (names[int(cls.item())], *xywh)
@@ -165,7 +172,7 @@ def detect_logo(img, model, confidence):
165
  print(f'Done. ({time.time() - t0:.3f}s)')
166
  img_output = Image.fromarray(im0[:, :, ::-1])
167
  txt_output = print_output(txt_path)
168
- return img_output, txt_output
169
 
170
  examples1 = [["exemple1.jpg", "Yologo", 0.60], ["exemple2.jpg", "Yologo", 0.60],
171
  ["exemple3.jpg", "Yologo", 0.60 ], ["exemple4.jpg", "Yologo", 0.60],
@@ -176,8 +183,13 @@ examples1 = [["exemple1.jpg", "Yologo", 0.60], ["exemple2.jpg", "Yologo", 0.60],
176
  Top_Title = "<center>Yolov7 🚀 Custom Trained by ISAI Team (Capgemini) </center> Logo detection model"
177
  Custom_description="Yologo can detect 44 brands : A.P.C, Abercrombie, Acne Studio, Adidas, Aigle, Airness, Armarni, Balenciaga, Bulgari, Cacharel, Calvin Klein, Carhatt, Champion, Columbia, Converse, Gap, Chanel, Lacoste, Levis, Louis vuitton, Moncler, Mossimo, New Balance, Obey, Pepe jeans, Ralph Lauren, Prada, Rolex, Seiko, Stussy, The North Face, Timberland, Tom Ford, Tommy Hilfiger, Uniqlo, Valentino, Versace, Zara, Asics, Le coq, Oakley, Nike, Puma, Reebok "
178
 
179
- gr.Interface(detect_logo, [gr.Image(type="pil"), gr.Dropdown(value="Yologo",
180
- choices=["Yologo"]), gr.Slider(0.10, 1.0, value=0.60)], [gr.Image(type="pil"), "text"],
 
 
 
 
 
181
  title=Top_Title,
182
  description=Custom_description,
183
  examples=examples1, cache_examples=True).launch()
 
9
  from numpy import random
10
  from pathlib import Path
11
  import torch.backends.cudnn as cudnn
12
+
13
+ from recommendation import SimilarityRecommender
14
  from models.experimental import attempt_load
15
 
16
  from utils.datasets import LoadStreams, LoadImages
 
37
  def detect_logo(img, model, confidence):
38
  if model == 'Yologo':
39
  model = 'best_logo' # Naming Convention for yolov7 See output file of https://www.kaggle.com/code/owaiskhan9654/training-yolov7-on-kaggle-on-custom-dataset/data
40
+ recommender = SimilarityRecommender("./TopBrands.xlsx")
41
  parser = argparse.ArgumentParser()
42
  parser.add_argument('--weights', nargs='+', type=str, default=model + ".pt", help='model.pt path(s)')
43
  parser.add_argument('--source', type=str, default='inference/', help='source')
 
122
  txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
123
  s += '%gx%g ' % img.shape[2:]
124
  gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]
125
+ all_classes_detected = []
126
+ all_recommendations = []
127
  if len(det):
128
  det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
129
 
130
  for c in det[:, -1].unique():
131
  n = (det[:, -1] == c).sum()
132
  s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "
 
133
  for *xyxy, conf, cls in reversed(det):
134
+ name_class = names[int(cls.item())]
135
+ all_classes_detected.append(name_class)
136
+ all_recommendations.append(recommender.make_recommendation(name_class))
137
  if save_txt:
138
  xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()
139
  line = (names[int(cls.item())], *xywh, conf) if opt.save_conf else (names[int(cls.item())], *xywh)
 
172
  print(f'Done. ({time.time() - t0:.3f}s)')
173
  img_output = Image.fromarray(im0[:, :, ::-1])
174
  txt_output = print_output(txt_path)
175
+ return img_output, txt_output, "Recommendations : "+str(set(all_recommendations))
176
 
177
  examples1 = [["exemple1.jpg", "Yologo", 0.60], ["exemple2.jpg", "Yologo", 0.60],
178
  ["exemple3.jpg", "Yologo", 0.60 ], ["exemple4.jpg", "Yologo", 0.60],
 
183
  Top_Title = "<center>Yolov7 🚀 Custom Trained by ISAI Team (Capgemini) </center> Logo detection model"
184
  Custom_description="Yologo can detect 44 brands : A.P.C, Abercrombie, Acne Studio, Adidas, Aigle, Airness, Armarni, Balenciaga, Bulgari, Cacharel, Calvin Klein, Carhatt, Champion, Columbia, Converse, Gap, Chanel, Lacoste, Levis, Louis vuitton, Moncler, Mossimo, New Balance, Obey, Pepe jeans, Ralph Lauren, Prada, Rolex, Seiko, Stussy, The North Face, Timberland, Tom Ford, Tommy Hilfiger, Uniqlo, Valentino, Versace, Zara, Asics, Le coq, Oakley, Nike, Puma, Reebok "
185
 
186
+ # Recommendation#
187
+
188
+
189
+ gr.Interface(detect_logo, [gr.Image(type="pil"),
190
+ gr.Dropdown(value="Yologo",choices=["Yologo"]),
191
+ gr.Slider(0.10, 1.0, value=0.60)],
192
+ [gr.Image(type="pil"), "text", "text"],
193
  title=Top_Title,
194
  description=Custom_description,
195
  examples=examples1, cache_examples=True).launch()
recommendation.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np # linear algebra
2
+ import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
3
+ from sklearn.metrics.pairwise import cosine_similarity
4
+ import re
5
+
6
+ class SimilarityRecommender():
7
+
8
+ def __init__(self, file):
9
+ data = pd.read_excel(file, index_col=0)
10
+ columns_brands = [re.sub(r'[^a-zA-Z ]', '', brand.upper()) for brand in list(data.index)]
11
+ ex = pd.DataFrame(cosine_similarity(data), index=columns_brands,
12
+ columns=columns_brands)
13
+ for brand in ex.index:
14
+ ex.loc[brand, brand] = np.nan
15
+ self.similarity_matrix = ex.assign(best_similarity=ex.idxmax())['best_similarity']
16
+
17
+ def make_recommendation(self, item):
18
+ key = re.sub(r'[^a-zA-Z ]', '', item.upper())
19
+ if key not in self.similarity_matrix.index:
20
+ print(self.similarity_matrix.index)
21
+ raise ValueError(f'{key} not in matrix')
22
+ return self.similarity_matrix[key]
23
+
24
+
25
+ if __name__ == '__main__':
26
+ rec = SimilarityRecommender("./TopBrands.xlsx")
27
+ print(rec.make_recommendation("louis vuitton-1"))
28
+ print(rec.similarity_matrix)
29
+ print(rec.make_recommendation("Lacoste"))