Spaces:
Runtime error
Runtime error
Merged API description
Browse files
app.py
CHANGED
@@ -1,4 +1,5 @@
|
|
1 |
import io
|
|
|
2 |
import ast
|
3 |
import json
|
4 |
import base64
|
@@ -12,6 +13,7 @@ import face_recognition
|
|
12 |
from turtle import title
|
13 |
from openai import OpenAI
|
14 |
from collections import Counter, defaultdict
|
|
|
15 |
from transformers import pipeline
|
16 |
|
17 |
import urllib.request
|
@@ -27,7 +29,6 @@ pipe = pipeline("zero-shot-image-classification", model="patrickjohncyh/fashion-
|
|
27 |
|
28 |
color_file_path = 'color_config.json'
|
29 |
attributes_file_path = 'attributes_config.json'
|
30 |
-
import os
|
31 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
32 |
|
33 |
|
@@ -42,7 +43,9 @@ with open(attributes_file_path, 'r') as file:
|
|
42 |
COLOURS_DICT = color_data['color_mapping']
|
43 |
ATTRIBUTES_DICT = attributes_data['attribute_mapping']
|
44 |
|
45 |
-
|
|
|
|
|
46 |
|
47 |
|
48 |
def shot(input, category, level):
|
@@ -67,6 +70,7 @@ def shot(input, category, level):
|
|
67 |
common_result = get_predicted_attributes(ast.literal_eval(str(input)), category)
|
68 |
output_dict['attributes'] = common_result
|
69 |
output_dict['subcategory'] = category
|
|
|
70 |
|
71 |
# # Convert the dictionary to a JSON-serializable format
|
72 |
# try:
|
@@ -159,7 +163,7 @@ def get_most_common_label(responses):
|
|
159 |
def get_predicted_attributes(image_urls, category):
|
160 |
# Assuming ATTRIBUTES_DICT and pipe are defined outside this function
|
161 |
attributes = list(ATTRIBUTES_DICT.get(category, {}).keys())
|
162 |
-
|
163 |
# Mapping of possible values per attribute
|
164 |
common_result = []
|
165 |
for attribute in attributes:
|
@@ -169,22 +173,22 @@ def get_predicted_attributes(image_urls, category):
|
|
169 |
continue
|
170 |
|
171 |
# Adjust labels for the pipeline
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
|
189 |
# Convert common_result into a dictionary
|
190 |
final = {}
|
@@ -201,6 +205,73 @@ def get_predicted_attributes(image_urls, category):
|
|
201 |
|
202 |
return final
|
203 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
204 |
def get_openAI_tags(image_urls):
|
205 |
# Create list containing JSONs of each image URL
|
206 |
imageList = []
|
|
|
1 |
import io
|
2 |
+
import os
|
3 |
import ast
|
4 |
import json
|
5 |
import base64
|
|
|
13 |
from turtle import title
|
14 |
from openai import OpenAI
|
15 |
from collections import Counter, defaultdict
|
16 |
+
from typing import List, Optional, Set, Dict, Any
|
17 |
from transformers import pipeline
|
18 |
|
19 |
import urllib.request
|
|
|
29 |
|
30 |
color_file_path = 'color_config.json'
|
31 |
attributes_file_path = 'attributes_config.json'
|
|
|
32 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
33 |
|
34 |
|
|
|
43 |
COLOURS_DICT = color_data['color_mapping']
|
44 |
ATTRIBUTES_DICT = attributes_data['attribute_mapping']
|
45 |
|
46 |
+
|
47 |
+
OPENAI_USER_PROMPT = "I have a product called 'Round Neck Knitted Ribbed Crop Top with a Neck Detail'. The description reads: 'Introducing the Round Neck Knitted Ribbed Crop Top with a Neck Detail. This sleeveless top is a must-have addition to your wardrobe. Its round neck and ribbed design give it a modern and stylish look, while the neck detail adds a unique touch. Made from high-quality materials, this crop top is comfortable to wear all day long. The solid white color makes it easy to pair with any outfit, making it a versatile piece for any occasion. Whether you're dressing up for a night out or keeping it casual, this crop top is sure to become one of your favorite go-to staples. Upgrade your style with this trendy and chic top today!'. Arabic naming: 'بلوزة قصيرة محبوكة ومضلعة بياقة دائرية وتفاصيل رقبة'. Arabic description: 'نقدم لك بلوزة قصيرة محبوكة ومضلعة برقبة دائرية مع تفاصيل الرقبة. يعد هذا القميص بلا أكمام إضافة لا غنى عنها لخزانة ملابسك. تمنحه رقبته المستديرة وتصميمه المضلع مظهرًا عصريًا وأنيقًا، بينما تضيف تفاصيل الرقبة لمسة فريدة. مصنوع من مواد عالية الجودة، هذا القميص القصير مريح للارتداء طوال اليوم. اللون الأبيض الصلب يجعل من السهل ارتداؤه مع أي ملابس، مما يجعله قطعة متعددة الاستخدامات لأي مناسبة. سواء كنت ترتدي ملابس ليلية أو تبقيها غير رسمية، فمن المؤكد أن هذه السترة القصيرة ستصبح واحدة من القطع الأساسية المفضلة لديك. قم بترقية أسلوبك مع هذا القميص العصري والأنيق اليوم!'\n The attributes are:\n\t• Category: 'top > croptop'\n\t• Material: 'polyamide'\n\t• Target Audience: women\n\t• Fabric Style: Knitted\n\t• Pattern: Solid\n\t• Colar Type: Round Neck\n\t• Sleeve Length: Sleeveless\n\t• Details: Ribbed Neck Detail \n\t• Tags: 'neutral, staples, casual, springsummer, bestseller, summer_light_palette, coastal_charm, allnewin' (do not use any seasonal tags or other discount info nothing with '_' or color)\n \n\nI have a product called 'Crew Neck Crop Top with a V-Shaped Front'. The description reads: 'Step up your casual style with this Crew Neck Crop Top with a V-Shaped Front. Crafted from high-quality materials, this sleeveless top features a flattering v-shaped front design that adds a touch of sophistication to any outfit. The Sacramento Green color adds a pop of freshness and pairs perfectly with neutral tones. Whether you're lounging at home or running errands, this crop top is a staple in your wardrobe. Its versatile design makes it easy to dress up or down for any occasion. Elevate your loungewear game and add this Crew Neck Crop Top to your collection today.'. Arabic naming: 'بلوزة قصيرة بياقة دائرية ومقدمة على شكل حرف V'. Arabic description: 'ارتقي بأسلوبك الكاجوال مع هذا القميص القصير ذو الرقبة الدائرية والمقدمة على شكل حرف V. مصنوع من مواد عالية الجودة، يتميز هذا القميص بدون أكمام بتصميم أمامي جذاب على شكل حرف V يضيف لمسة من الرقي إلى أي ملابس. يضيف لون Sacramento Green لمسة من النضارة ويمتزج بشكل مثالي مع الألوان المحايدة. سواء كنت تسترخي في المنزل أو تقوم بمهمات، فإن هذا القميص القصير هو قطعة أساسية في خزانة ملابسك. تصميمه متعدد الاستخدامات يجعل من السهل ارتداؤه لأعلى أو لأسفل في أي مناسبة. ارفع مستوى ملابسك المريحة وأضف هذا القميص ذو الرقبة الدائرية إلى مجموعتك اليوم.'\n The attributes are:\n\t• Category: 'top > croptop'\n\t• Material: 'cotton, polyester'\n\t• Target Audience: women\n\t• Fabric Style: Woven\n\t• Pattern: Solid\n\t• Colar Type: Crew Neck\n\t• Sleeve Length: Sleeveless\n\t• Details: V-Shaped Front \n\t• Tags: 'neutral, casual, staples, loungewear, bestseller' (do not use any seasonal tags or other discount info nothing with '_' or color)\n \n\nI have a product called 'Corduroy Polo Collar Buttoned Pocket Jacket'. The description reads: 'Step up your fashion game with this Corduroy Polo Collar Buttoned Pocket Jacket. Made from high-quality corduroy fabric, this jacket is both stylish and comfortable. The unique polo collar adds a touch of sophistication, while the buttoned pockets provide a practical yet fashionable twist. Whether you're heading to a casual outing or a night on the town, this jacket is sure to turn heads. Its versatile design makes it easy to pair with any outfit, giving you endless options for creating trendy looks. Upgrade your wardrobe with this Hiccup fashion statement and be the envy of everyone around you.'. Arabic naming: 'سترة سروال قصير بياقة بولو وجيب بأزرار'. Arabic description: 'ارتقِ بأسلوبك في عالم الموضة مع سترة الجيب ذات الأزرار بياقة بولو من سروال قصير. مصنوع من قماش كوردروي عالي الجودة، هذا الجاكيت أنيق ومريح. تضيف ياقة البولو الفريدة لمسة من الرقي، بينما توفر الجيوب ذات الأزرار لمسة عملية وعصرية. سواء كنت متجهًا إلى نزهة غير رسمية أو ليلة في المدينة، فمن المؤكد أن هذه السترة ستلفت الأنظار. تصميمه متعدد الاستخدامات يجعل من السهل ارتداؤه مع أي ملابس، مما يمنحك خيارات لا حصر لها للحصول على إطلالات عصرية. قم بترقية خزانة ملابسك مع هذا التصميم الأنيق من Hiccup وكن موضع حسد الجميع من حولك.'\n The attributes are:\n\t• Category: 'outwear > coatjacket'\n\t• Material: 'polyester'\n\t• Target Audience: women\n\t• Fabric Style: Corduroy\n\t• Pattern: Solid\n\t• Colar Type: Polo Collar\n\t• Sleeve Length: Long Sleeve\n\t• Details: Buttoned, Pocket\n\t• Tags: 'autumn, black, cosy, onsale, discount55_2403' (do not use any seasonal tags or other discount info nothing with '_' or color)\n \n\nI have a product called 'High Waist Skirt with a Belt'. The description reads: 'Step into style with our High Waist Skirt with a Belt in Brown. This chic and versatile skirt is designed to flatter your figure and elevate your fashion game. The high waistline accentuates your curves while the belt adds a touch of sophistication. Made from a premium blend of fabrics, this skirt is comfortable and durable, ensuring that it will become a staple in your wardrobe for years to come. Whether you're dressing up for a special occasion or keeping it casual for everyday wear, this High Waist Skirt with a Belt in Brown is the perfect choice. Embrace timeless elegance and make a statement with this must-have piece.'. Arabic naming: 'تنورة عالية الخصر مع حزام'. Arabic description: 'نقدم لك تنورة عالية الخصر مع حزام، وهي إضافة لا بد منها لأي خزانة ملابس مواكبة للموضة. ارتقي بأسلوبك مع هذه القطعة الأنيقة والمتعددة الاستخدامات التي تجمع بين الرقي والراحة بسهولة. يبرز تصميم الخصر العالي منحنياتك، بينما يشد الحزام المتضمن خصرك للحصول على مظهر جذاب. مصنوعة من قماش عالي الجودة، هذه التنورة تنسدل بشكل جميل ومثالية للمناسبات غير الرسمية والرسمية. ارتديه مع بلوزة وحذاء بكعب لإطلالة أنيقة، أو ارتديه مع تي شيرت وحذاء رياضي لإطلالة أكثر استرخاءً. تمتعي بالأناقة الخالدة مع تنورتنا ذات الخصر العالي مع الحزام واخرجي بأناقة.'\n The attributes are:\n\t• Category: 'bottom > skirt'\n\t• Material: 'polyester'\n\t• Target Audience: women\n\t• Fabric Style: Woven\n\t• Waist: High Waist\n\t• Style: Mini\n\t• Details: Belt\n\t• Tags: 'black, springsummer, allnewin, neutral, tailoring' (do not use any seasonal tags or other discount info nothing with '_' or color)\n \n\nI have a product called 'Knitted Crew Neck Crop Top'. The description reads: 'Introducing our Knitted Crew Neck Crop Top, the perfect addition to your wardrobe. Made from high-quality knitted fabric, this crop top offers both style and comfort. The crew neck design adds a touch of sophistication, while the cropped length adds a modern twist. Whether you pair it with high-waisted jeans for a casual look or dress it up with a skirt for a night out, this crop top is versatile and effortlessly chic. The soft fabric feels luxurious against the skin, making it a pleasure to wear all day long. Upgrade your style game with our Knitted Crew Neck Crop Top and turn heads wherever you go.'. Arabic naming: 'محبوك طاقم الرقبة المحاصيل الأعلى'. \nArabic description: 'نقدم لك القميص القصير ذو الرقبة الدائرية المحبوك، الإضافة المثالية لخزانة ملابسك. مصنوع من قماش محبوك عالي الجودة، هذا القميص القصير يوفر الأناقة والراحة. يضيف تصميم الرقبة الدائرية لمسة من الرقي، بينما يضيف الطول القصير لمسة عصرية. سواء كنت ترتديه مع بنطال جينز عالي الخصر لمظهر غير رسمي أو ترتديه مع تنورة لقضاء ليلة في الخارج، فإن هذا القميص القصير متعدد الاستخدامات وأنيق دون عناء. يعطي النسيج الناعم ملمسًا فاخرًا على البشرة، مما يجعل ارتداؤه ممتعًا طوال اليوم. قم بترقية أسلوبك في الأناقة مع القميص المحبوك ذو الرقبة الدائرية وجذب الأنظار أينما ذهبت.'\n The attributes are:\n\t• Category: 'top > croptop'\n\t• Material: 'viscose, polyamide'\n\t• Target Audience: women\n\t• Fabric Style: Knitted\n\t• Pattern: Solid\n\t• Colar Type: Crew Neck\n\t• Sleeve Length: Sleeveless\n\t• Tags: 'autumn, neutral' (do not use any seasonal tags or other discount info nothing with '_' or color)\n "
|
48 |
+
|
49 |
|
50 |
|
51 |
def shot(input, category, level):
|
|
|
70 |
common_result = get_predicted_attributes(ast.literal_eval(str(input)), category)
|
71 |
output_dict['attributes'] = common_result
|
72 |
output_dict['subcategory'] = category
|
73 |
+
output_dict['description'] = get_product_description(category=category, attributes=common_result)
|
74 |
|
75 |
# # Convert the dictionary to a JSON-serializable format
|
76 |
# try:
|
|
|
163 |
def get_predicted_attributes(image_urls, category):
|
164 |
# Assuming ATTRIBUTES_DICT and pipe are defined outside this function
|
165 |
attributes = list(ATTRIBUTES_DICT.get(category, {}).keys())
|
166 |
+
|
167 |
# Mapping of possible values per attribute
|
168 |
common_result = []
|
169 |
for attribute in attributes:
|
|
|
173 |
continue
|
174 |
|
175 |
# Adjust labels for the pipeline
|
176 |
+
attribute = attribute.replace("colartype", "collar").replace("sleevelength", "sleeve length").replace("fabricstyle", "fabric")
|
177 |
+
values = [f"{attribute}: {value.strip()}, clothing: {category}" for value in values]
|
178 |
+
|
179 |
+
# Get the predicted values for the attribute
|
180 |
+
responses = pipe(product['Images'].values[0], candidate_labels=values, device=device)
|
181 |
+
most_common, score = get_most_common_label(responses)
|
182 |
+
common_result.append(most_common)
|
183 |
+
|
184 |
+
if attribute == "details":
|
185 |
+
# Process additional details labels if the score is higher than 0.8
|
186 |
+
for _ in range(2):
|
187 |
+
values = [value for value in values if value != f"{most_common}, clothing: {category}"]
|
188 |
+
responses = pipe(product['Images'].values[0], candidate_labels=values, device=device)
|
189 |
+
most_common, score = get_most_common_label(responses)
|
190 |
+
if score > 0.8:
|
191 |
+
common_result.append(most_common)
|
192 |
|
193 |
# Convert common_result into a dictionary
|
194 |
final = {}
|
|
|
205 |
|
206 |
return final
|
207 |
|
208 |
+
|
209 |
+
|
210 |
+
def generate_prompt(category: Optional[str], tags: Optional[Set[str]],
|
211 |
+
materials: Optional[List[Dict[str, int]]], attributes: Optional[List[Dict[str, str]]]) -> str:
|
212 |
+
|
213 |
+
formatted_attributes = [f"{attr['key']}: {attr['value']}" for attr in attributes] if attributes else []
|
214 |
+
|
215 |
+
formatted_string = "\\n".join(formatted_attributes) if formatted_attributes else "No attributes provided."
|
216 |
+
|
217 |
+
processed_category = category.replace("women-", "").replace("-", " > ") if category else None
|
218 |
+
|
219 |
+
material_keys = ", ".join([str(material['key']) for material in materials]) if materials else None
|
220 |
+
|
221 |
+
processed_tags = ", ".join(tags) if tags else None
|
222 |
+
|
223 |
+
return (
|
224 |
+
f"I have a new product.\\nThe attributes are: Category: {processed_category}\\n"
|
225 |
+
f"Material: {material_keys}\\n{formatted_string}\\n"
|
226 |
+
f"Tags: {processed_tags} (do not use any seasonal tags or other discount info nothing with '_' or color)\\n"
|
227 |
+
"Print the output as a json object no extra text, keys are name_en, name_ar, summary_en, summary_ar"
|
228 |
+
).strip()
|
229 |
+
|
230 |
+
def send_request_to_openai(prompt: str) -> Optional[Dict[str, Any]]:
|
231 |
+
messages = [
|
232 |
+
{"role": "system", "content": "You are a labelling assistant, you will help create product metadata for my online e-commerce platform. Your tasks will be to return product names and product descriptions. You will be given some product attributes and/or metadata guideline outputs and are expected to follow the sample output to generate new outputs.\n\nYou will be asked to generate product names and descriptions in both english and arabic."},
|
233 |
+
{"role": "user", "content": "Hello, I need help creating product metadata for new apparel items. I will provide examples, I want you to understand the current structure and setup. You are expected to match the current tone of voice and overall information."},
|
234 |
+
{"role": "assistant", "content": "Sure, I'd be happy to help! Please provide the attributes and any existing product names you'd like me to consider"},
|
235 |
+
{"role": "user", "content": OPENAI_USER_PROMPT},
|
236 |
+
{"role": "assistant", "content": "This was very helpful, I have taken note of the overall data inputs and expected product name and description outputs. Please provide the attributes for the newly listed product so I can generate the name and description for you."},
|
237 |
+
{"role": "user", "content": prompt}
|
238 |
+
]
|
239 |
+
|
240 |
+
try:
|
241 |
+
response = client.chat.completions.create(
|
242 |
+
model="gpt-3.5-turbo-16k",
|
243 |
+
messages=messages,
|
244 |
+
temperature=1.0,
|
245 |
+
max_tokens=512,
|
246 |
+
top_p=1.0,
|
247 |
+
frequency_penalty=0.0,
|
248 |
+
presence_penalty=0.0
|
249 |
+
)
|
250 |
+
|
251 |
+
json_string = response['choices'][0]['message']['content']
|
252 |
+
parsed_response = json.loads(json_string)
|
253 |
+
|
254 |
+
print(f"English name: {parsed_response['name_en']}")
|
255 |
+
print(f"Arabic name: {parsed_response['name_ar']}")
|
256 |
+
print(f"English description: {parsed_response['summary_en']}")
|
257 |
+
print(f"Arabic description: {parsed_response['summary_ar']}")
|
258 |
+
|
259 |
+
return parsed_response
|
260 |
+
|
261 |
+
except openai.error.OpenAIError as e:
|
262 |
+
print(f"Failed to fetch details: {e}")
|
263 |
+
return None
|
264 |
+
|
265 |
+
|
266 |
+
|
267 |
+
def get_product_description(category: Optional[str] = None, tags: Optional[Set[str]] = None,
|
268 |
+
attributes: Optional[List[Dict[str, str]]] = None, materials: Optional[List[Dict[str, int]]] = None) -> Optional[Dict[str, Any]]:
|
269 |
+
prompt = generate_prompt(category, tags, materials, attributes)
|
270 |
+
return send_request_to_openai(prompt)
|
271 |
+
|
272 |
+
# Example usage:
|
273 |
+
# response = get_product_description(api_key, category="women-shirts", tags={"summer", "casual"}, attributes=[{"key": "color", "value": "blue"}], materials=[{"key": "cotton", "value": 100}])
|
274 |
+
|
275 |
def get_openAI_tags(image_urls):
|
276 |
# Create list containing JSONs of each image URL
|
277 |
imageList = []
|