Calvin commited on
Commit ·
f94a42e
1
Parent(s): 8a1aceb
final touches
Browse filesFiles changed (3)
- Exploration.ipynbAdded
- offer_pipeline.py+119-24
- requirements.txt-1
2 unmodified lines34567894 unmodified lines141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091923 unmodified lines969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361372 unmodified linesimport pickleimport osimport pandas as pd# import seaborn as snsimport astimport stringimport re4 unmodified lineslayout="wide")pipe = pipeline(task="zero-shot-classification", model="facebook/bart-large-mnli")model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')dire = "DS_NLP_search_data"@st.cache_datadef get_processed_offers():processed_offers = pd.read_csv(os.path.join(dire, "processed_offers.csv"))processed_offers["CATEGORY"] = processed_offers["CATEGORY"].map(ast.literal_eval)return processed_offers@st.cache_datadef get_categories_data():cats = pd.read_csv(os.path.join(dire, "categories.csv"))return cats@st.cache_datadef get_offers_data():offers = pd.read_csv(os.path.join(dire, "offer_retailer.csv"))return offers@st.cache_datadef get_categories(cats_):categories = list(cats_["IS_CHILD_CATEGORY_TO"].unique())for x in ["Mature"]:if x in categories:categories.remove(x)return categoriesdef check_in_offer(search_str, offer_rets):offers = []# print(offer_rets)for i in range(len(offer_rets)):offer_str = offer_rets.iloc[i]["OFFER"]# print(offer_str)parsed_str = offer_str.lower().translate(str.maketrans('', '', string.punctuation))parsed_str = re.sub('[^a-zA-Z0-9 \n\.]', '', parsed_str)# print(parsed_str)if search_str.lower() in parsed_str.split(" "):offers.append(offer_str)df = pd.DataFrame({"OFFER":offers})# print(df)return dfdef is_retailer(search_str, threshold=0.5):processed_search_str = search_str.lower().capitalize()labels = pipe(processed_search_str,candidate_labels=["brand", "retailer", "item"],)return labels["labels"][0] == "retailer" and labels["scores"][0] > thresholddef perform_cat_inference(search_str, categories, cats, processed_offers):labels = pipe(search_str,candidate_labels=categories,)print(labels)# labels = [l for i, l in enumerate(labels["labels"]) if labels["scores"][i] > 0.20]filtered_cats = list(cats[cats["IS_CHILD_CATEGORY_TO"].isin(labels["labels"][:3])]["PRODUCT_CATEGORY"].unique())labels_2 = pipe(search_str,candidate_labels=filtered_cats,)print(labels_2)top_labels = labels_2["labels"][:3]print(top_labels)offers = processed_offers[processed_offers["CATEGORY"].apply(lambda x: bool(set(x) & set(top_labels)))]["OFFER"].reset_index()return offers, labels, labels_2def sort_by_similarity(search_str, related_offers):temp_dict = {}embedding_1 = model.encode(search_str, convert_to_tensor=True)3 unmodified linestemp_dict[offer] = float(util.pytorch_cos_sim(embedding_1, embedding_2))sorted_dict = dict(sorted(temp_dict.items(), key=lambda x : x[1], reverse=True))# casted_scores = list(map(lambda x : int(x), ))df = pd.DataFrame({"OFFER":list(sorted_dict.keys())[:20], "scores":list(sorted_dict.values())[:20]})return dfdef main():col_1, col_2, col_3 = st.columns(3)search_str = col_2.text_input("Enter a retailer, brand, or category").capitalize()processed_offers = get_processed_offers()cats = get_categories_data()offer_rets = get_offers_data()categories = get_categories(cats)# retail_mapping = get_prod_categories()if col_2.button("Search", type="primary"):retail = is_retailer(search_str)direct_offers = check_in_offer(search_str, offer_rets)col_2.write("Directly related offers")col_2.table(direct_offers)if retail:related_offers = offer_rets[~offer_rets["OFFER"].isin(list(direct_offers["OFFER"]))]else:related_offers, labels_1, labels_2 = perform_cat_inference(search_str, categories, cats, processed_offers)related_offers = related_offers[~related_offers["OFFER"].isin(list(direct_offers["OFFER"]))]col_2.table(pd.DataFrame({"labels": labels_1["labels"][:5], "scores": labels_1["scores"][:5]}))col_2.table(pd.DataFrame({"labels": labels_2["labels"][:5], "scores": labels_2["scores"][:5]}))# df = get_confidence_charts(labels_2)# st.table(df)col_2.write("Other related offers")sorted_offers = sort_by_similarity(search_str, related_offers)col_2.table(sorted_offers)if __name__ == "__main__":main()2 unmodified lines3456784 unmodified lines1314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761773 unmodified lines1811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322 unmodified linesimport pickleimport osimport pandas as pdimport astimport stringimport re4 unmodified lineslayout="wide")# Download and cache modelspipe = pipeline(task="zero-shot-classification", model="valhalla/distilbart-mnli-12-3")model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')# Directory of csv filesdire = "DS_NLP_search_data"# Use Streamlit caching to load data once@st.cache_datadef get_processed_offers():'''Load processed offers from exploration notebook and cacheReturns:processed_offers (pd.DataFrame) : zero-shot categorized offers'''processed_offers = pd.read_csv(os.path.join(dire, "processed_offers.csv"))processed_offers["CATEGORY"] = processed_offers["CATEGORY"].map(ast.literal_eval)return processed_offers@st.cache_datadef get_categories_data():'''Load raw category data and cacheReturns:cats (pd.DataFrame) : raw category data'''cats = pd.read_csv(os.path.join(dire, "categories.csv"))return cats@st.cache_datadef get_offers_data():'''Load raw offfers data and cacheReturns:cats (pd.DataFrame) : raw offers data'''offers = pd.read_csv(os.path.join(dire, "offer_retailer.csv"))return offers@st.cache_datadef get_categories(cats_):'''Extract, load categories and cacheParameters:cats_ (pd.DataFrame) : raw categories dataReturns:categories (List) : child categories'''categories = list(cats_["IS_CHILD_CATEGORY_TO"].unique())for x in ["Mature"]:if x in categories:categories.remove(x)return categoriesdef check_in_offer(search_str, offer_rets):'''Determine if the input text is directly in the offer with basic string matchingParameters:search_str (string) : user text inputoffer_rets (pd.DataFrame) : raw offer dataReturns:df (pd.DataFrame) : offers with text input'''offers = []for i in range(len(offer_rets)):offer_str = offer_rets.iloc[i]["OFFER"]parsed_str = offer_str.lower().translate(str.maketrans('', '', string.punctuation))parsed_str = re.sub('[^a-zA-Z0-9 \n\.]', '', parsed_str)if search_str.lower() in parsed_str.split(" "):offers.append(offer_str)df = pd.DataFrame({"OFFER":offers})return dfdef is_retailer(search_str, threshold=0.5):'''Determine if the text input is highly likely to be a retailerParameters:search_str (string) : user text inputthreshold (int) : probability thresholdReturns:is_ret (boolean) : true if retailer, false otherwise'''processed_search_str = search_str.lower().capitalize()labels = pipe(processed_search_str,candidate_labels=["brand", "retailer", "item"],)is_ret = labels["labels"][0] == "retailer" and labels["scores"][0] > thresholdreturn is_retdef perform_cat_inference(search_str, categories, cats, processed_offers):'''Perform zero shot learning twice and return the offers relevant to the child categoriesParameters:search_str (string) : user text inputcategories (pd.DataFrame) : list of categoriescats (pd.DataFrame) : raw category dataprocessed_offers (pd.DataFrame) : processed_offer_dataReturns:offers (pd.DataFrame) : relevant offerslabels (dict) : parent categories and their probability scoreslabels_2 (dict) : child categories and their probability scores'''labels = pipe(search_str,candidate_labels=categories,)# labels = [l for i, l in enumerate(labels["labels"]) if labels["scores"][i] > 0.20]filtered_cats = list(cats[cats["IS_CHILD_CATEGORY_TO"].isin(labels["labels"][:3])]["PRODUCT_CATEGORY"].unique())labels_2 = pipe(search_str,candidate_labels=filtered_cats,)top_labels = labels_2["labels"][:3]offers = processed_offers[processed_offers["CATEGORY"].apply(lambda x: bool(set(x) & set(top_labels)))]["OFFER"].reset_index()return offers, labels, labels_2def sort_by_similarity(search_str, related_offers):'''Use sentence embeddings to evaluate the similarity of relevant offers to the text inputParameters:search_str (string) : user text inputrelated_offers (pd.DataFrame) : relevant offers discovered by zero shot learningReturns:df (pd.DataFrame) : relevant offers and their similiarity scores'''temp_dict = {}embedding_1 = model.encode(search_str, convert_to_tensor=True)3 unmodified linestemp_dict[offer] = float(util.pytorch_cos_sim(embedding_1, embedding_2))sorted_dict = dict(sorted(temp_dict.items(), key=lambda x : x[1], reverse=True))df = pd.DataFrame({"OFFER":list(sorted_dict.keys())[:20], "scores":list(sorted_dict.values())[:20]})return dfdef main():# Load and cache datacol_1, col_2, col_3 = st.columns(3)search_str = col_1.text_input("Enter a retailer, brand, or category").capitalize()processed_offers = get_processed_offers()cats = get_categories_data()offer_rets = get_offers_data()categories = get_categories(cats)if col_1.button("Search", type="primary"):# Check offers where the text is directly in itretail = is_retailer(search_str)direct_offers = check_in_offer(search_str, offer_rets)col_2.write("Directly related offers")if len(direct_offers) == 0:col_2.write("None found")else:col_2.table(direct_offers)if retail:# If retail, we directly compare every offer using sentence embeddingsrelated_offers = offer_rets[~offer_rets["OFFER"].isin(list(direct_offers["OFFER"]))]else:# Otherwise, we use zero shot learning with processed offers to narrow down our searchrelated_offers, labels_1, labels_2 = perform_cat_inference(search_str, categories, cats, processed_offers)related_offers = related_offers[~related_offers["OFFER"].isin(list(direct_offers["OFFER"]))]col_2.write("Parent categories probabilities")col_2.table(pd.DataFrame({"labels": labels_1["labels"][:5], "scores": labels_1["scores"][:5]}))col_2.write("Child categories probabilities")col_2.table(pd.DataFrame({"labels": labels_2["labels"][:5], "scores": labels_2["scores"][:5]}))col_2.write("Other related offers")sorted_offers = sort_by_similarity(search_str, related_offers)if len(sorted_offers) == 0:col_2.write("None found")else:col_2.table(sorted_offers)if __name__ == "__main__":main()
123456streamlittransformerspandasseaborntorchsentence-transformers12345streamlittransformerspandastorchsentence-transformers
Exploration.ipynbAdded
offer_pipeline.py+119-24
requirements.txt-1