JoJosmin commited on
Commit
3d166f5
1 Parent(s): 4097cc9

Upload 9 files

Browse files
.gitattributes CHANGED
@@ -1,35 +1,36 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ clothesDB/chroma.sqlite3 filter=lfs diff=lfs merge=lfs -text
Dockerfile ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use Python 3.10
2
+ FROM python:3.10-slim
3
+
4
+ # Set the working directory in the container
5
+ WORKDIR /app
6
+
7
+ # Copy the current directory contents into the container at /app
8
+ COPY . /app
9
+
10
+ # Install system dependencies
11
+ RUN apt-get update && apt-get install -y \
12
+ build-essential \
13
+ curl \
14
+ software-properties-common \
15
+ git \
16
+ && rm -rf /var/lib/apt/lists/*
17
+
18
+ # Upgrade pip and install required python packages
19
+ RUN pip install --no-cache-dir --upgrade pip
20
+ RUN pip install --no-cache-dir -r requirements.txt
21
+
22
+ # Make port 8501 available to the world outside this container
23
+ EXPOSE 8501
24
+
25
+ # Run app.py when the container launches
26
+ CMD ["streamlit", "run", "app.py"]
README.md CHANGED
@@ -1,12 +1,13 @@
1
- ---
2
- title: Accessary
3
- emoji: 🔥
4
- colorFrom: purple
5
- colorTo: green
6
- sdk: streamlit
7
- sdk_version: 1.38.0
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
1
+ ---
2
+ title: Itda Nosegmentation
3
+ emoji: 🐨
4
+ colorFrom: gray
5
+ colorTo: purple
6
+ sdk: streamlit
7
+ sdk_version: 1.38.0
8
+ app_file: app.py
9
+ pinned: false
10
+ license: apache-2.0
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
accessaryDB/682a1a15-1caf-49d8-b42d-7cff88354fa2/data_level0.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:087859641a3f3e1a4061db9e09e79d89cb7c93a6f440ac35177054e84edd526f
3
+ size 3212000
accessaryDB/682a1a15-1caf-49d8-b42d-7cff88354fa2/header.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0ec6df10978b056a10062ed99efeef2702fa4a1301fad702b53dd2517103c746
3
+ size 100
accessaryDB/682a1a15-1caf-49d8-b42d-7cff88354fa2/length.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:362388e29bdbd934f2632e034681ddfe492580bccb44c187d7132e9e365f9990
3
+ size 4000
accessary_weights.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f7647fb4791077446a1b5ff2fb97fab43af297957ad65ec6d429408431ce5688
3
+ size 44731025
app.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import open_clip
3
+ import torch
4
+ import requests
5
+ from PIL import Image
6
+ from io import BytesIO
7
+ import time
8
+ import json
9
+ import numpy as np
10
+ import onnxruntime as ort
11
+ import cv2
12
+ import chromadb
13
+
14
+ @st.cache_resource
15
+ def load_clip_model():
16
+ model, preprocess_train, preprocess_val = open_clip.create_model_and_transforms('hf-hub:Marqo/marqo-fashionSigLIP')
17
+ tokenizer = open_clip.get_tokenizer('hf-hub:Marqo/marqo-fashionSigLIP')
18
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
19
+ model.to(device)
20
+ return model, preprocess_val, tokenizer, device
21
+
22
+ clip_model, preprocess_val, tokenizer, device = load_clip_model()
23
+
24
+ @st.cache_resource
25
+ def load_onnx_model():
26
+ session = ort.InferenceSession("./accessary_weights.onnx")
27
+ return session
28
+
29
+ onnx_session = load_onnx_model()
30
+
31
+ def load_image_from_url(url, max_retries=3):
32
+ for attempt in range(max_retries):
33
+ try:
34
+ response = requests.get(url, timeout=10)
35
+ response.raise_for_status()
36
+ img = Image.open(BytesIO(response.content)).convert('RGB')
37
+ return img
38
+ except (requests.RequestException, Image.UnidentifiedImageError) as e:
39
+ if attempt < max_retries - 1:
40
+ time.sleep(1)
41
+ else:
42
+ return None
43
+
44
+ client = chromadb.PersistentClient(path="./accessaryDB")
45
+ collection = client.get_collection(name="accessary_items_ver2")
46
+
47
+ def get_image_embedding(image):
48
+ image_tensor = preprocess_val(image).unsqueeze(0).to(device)
49
+ with torch.no_grad():
50
+ image_features = clip_model.encode_image(image_tensor)
51
+ image_features /= image_features.norm(dim=-1, keepdim=True)
52
+ return image_features.cpu().numpy()
53
+
54
+ def get_text_embedding(text):
55
+ text_tokens = tokenizer([text]).to(device)
56
+ with torch.no_grad():
57
+ text_features = clip_model.encode_text(text_tokens)
58
+ text_features /= text_features.norm(dim=-1, keepdim=True)
59
+ return text_features.cpu().numpy()
60
+
61
+ def get_all_embeddings_from_collection(collection):
62
+ all_embeddings = collection.get(include=['embeddings'])['embeddings']
63
+ return np.array(all_embeddings)
64
+
65
+ def get_metadata_from_ids(collection, ids):
66
+ results = collection.get(ids=ids)
67
+ return results['metadatas']
68
+
69
+ def find_similar_images(query_embedding, collection, top_k=5):
70
+ database_embeddings = get_all_embeddings_from_collection(collection)
71
+ similarities = np.dot(database_embeddings, query_embedding.T).squeeze()
72
+ top_indices = np.argsort(similarities)[::-1][:top_k]
73
+
74
+ all_data = collection.get(include=['metadatas'])['metadatas']
75
+
76
+ top_metadatas = [all_data[idx] for idx in top_indices]
77
+
78
+ results = []
79
+ for idx, metadata in enumerate(top_metadatas):
80
+ results.append({
81
+ 'info': metadata,
82
+ 'similarity': similarities[top_indices[idx]]
83
+ })
84
+ return results
85
+
86
+ def detect_clothing_onnx(image):
87
+ input_image = np.array(image.resize((640, 640)), dtype=np.float32)
88
+ input_image = np.transpose(input_image, [2, 0, 1])
89
+ input_image = np.expand_dims(input_image, axis=0)
90
+ input_image /= 255.0
91
+
92
+ inputs = {onnx_session.get_inputs()[0].name: input_image}
93
+ outputs = onnx_session.run(None, inputs)
94
+
95
+ detections = outputs[0]
96
+ categories = []
97
+ for detection in detections:
98
+ x1, y1, x2, y2, conf, cls = detection
99
+ category = str(int(cls))
100
+ if category in ['Bracelets', 'Broches', 'belt', 'earring', 'maangtika', 'necklace', 'nose ring', 'ring', 'tiara']:
101
+ categories.append({
102
+ 'category': category,
103
+ 'bbox': [int(x1), int(y1), int(x2), int(y2)],
104
+ 'confidence': conf
105
+ })
106
+ return categories
107
+
108
+ def crop_image(image, bbox):
109
+ return image.crop((bbox[0], bbox[1], bbox[2], bbox[3]))
110
+
111
+ # 세션 상태 초기화
112
+ if 'step' not in st.session_state:
113
+ st.session_state.step = 'input'
114
+ if 'query_image_url' not in st.session_state:
115
+ st.session_state.query_image_url = ''
116
+ if 'detections' not in st.session_state:
117
+ st.session_state.detections = []
118
+ if 'selected_category' not in st.session_state:
119
+ st.session_state.selected_category = None
120
+
121
+ # Streamlit app
122
+ st.title("Advanced Fashion Search App")
123
+
124
+ # 단계별 처리
125
+ if st.session_state.step == 'input':
126
+ st.session_state.query_image_url = st.text_input("Enter image URL:", st.session_state.query_image_url)
127
+ if st.button("Detect Clothing"):
128
+ if st.session_state.query_image_url:
129
+ query_image = load_image_from_url(st.session_state.query_image_url)
130
+ if query_image is not None:
131
+ st.session_state.query_image = query_image
132
+ st.session_state.detections = detect_clothing_onnx(query_image)
133
+ if st.session_state.detections:
134
+ st.session_state.step = 'select_category'
135
+ else:
136
+ st.warning("No clothing items detected in the image.")
137
+ else:
138
+ st.error("Failed to load the image. Please try another URL.")
139
+ else:
140
+ st.warning("Please enter an image URL.")
141
+
142
+ # Update the 'select_category' step
143
+ elif st.session_state.step == 'select_category':
144
+ st.image(st.session_state.query_image, caption="Query Image", use_column_width=True)
145
+ st.subheader("Detected Clothing Items:")
146
+
147
+ for detection in st.session_state.detections:
148
+ col1, col2 = st.columns([1, 3])
149
+ with col1:
150
+ st.write(f"{detection['category']} (Confidence: {detection['confidence']:.2f})")
151
+ with col2:
152
+ cropped_image = crop_image(st.session_state.query_image, detection['bbox'])
153
+ st.image(cropped_image, caption=detection['category'], use_column_width=True)
154
+
155
+ options = [f"{d['category']} (Confidence: {d['confidence']:.2f})" for d in st.session_state.detections]
156
+ selected_option = st.selectbox("Select a category to search:", options)
157
+
158
+ if st.button("Search Similar Items"):
159
+ st.session_state.selected_category = selected_option
160
+ st.session_state.step = 'show_results'
161
+
162
+ elif st.session_state.step == 'show_results':
163
+ st.image(st.session_state.query_image, caption="Query Image", use_column_width=True)
164
+ selected_detection = next(d for d in st.session_state.detections
165
+ if f"{d['category']} (Confidence: {d['confidence']:.2f})" == st.session_state.selected_category)
166
+ cropped_image = crop_image(st.session_state.query_image, selected_detection['bbox'])
167
+ st.image(cropped_image, caption="Cropped Image", use_column_width=True)
168
+ query_embedding = get_image_embedding(cropped_image)
169
+ similar_images = find_similar_images(query_embedding, collection)
170
+
171
+ st.subheader("Similar Items:")
172
+ for img in similar_images:
173
+ col1, col2 = st.columns(2)
174
+ with col1:
175
+ st.image(img['info']['image_url'], use_column_width=True)
176
+ with col2:
177
+ st.write(f"Name: {img['info']['name']}")
178
+ st.write(f"Brand: {img['info']['brand']}")
179
+ st.write(f"Category: {img['info']['category']}")
180
+ st.write(f"Price: {img['info']['price']}")
181
+ st.write(f"Discount: {img['info']['discount']}%")
182
+ st.write(f"Similarity: {img['similarity']:.2f}")
183
+
184
+ if st.button("Start New Search"):
185
+ st.session_state.step = 'input'
186
+ st.session_state.query_image_url = ''
187
+ st.session_state.detections = []
188
+ st.session_state.selected_category = None
189
+
190
+ else: # Text search
191
+ query_text = st.text_input("Enter search text:")
192
+ if st.button("Search by Text"):
193
+ if query_text:
194
+ text_embedding = get_text_embedding(query_text)
195
+ similar_images = find_similar_images(text_embedding, collection)
196
+ st.subheader("Similar Items:")
197
+ for img in similar_images:
198
+ col1, col2 = st.columns(2)
199
+ with col1:
200
+ st.image(img['info']['image_url'], use_column_width=True)
201
+ with col2:
202
+ st.write(f"Name: {img['info']['name']}")
203
+ st.write(f"Brand: {img['info']['brand']}")
204
+ st.write(f"Category: {img['info']['category']}")
205
+ st.write(f"Price: {img['info']['price']}")
206
+ st.write(f"Discount: {img['info']['discount']}%")
207
+ st.write(f"Similarity: {img['similarity']:.2f}")
208
+ else:
209
+ st.warning("Please enter a search text.")
requirements.txt ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ open_clip_torch
3
+ torch
4
+ torchvision
5
+ transformers
6
+ requests
7
+ Pillow
8
+ numpy
9
+ pandas
10
+ matplotlib
11
+ scikit-learn
12
+ scipy
13
+ opencv-python-headless
14
+ inference_sdk
15
+ ultralytics
16
+ streamlit-img-label
17
+ pascal-voc-writer
18
+ chromadb