Spaces:
Sleeping
Sleeping
import streamlit as st | |
from streamlit_tags import st_tags, st_tags_sidebar | |
from keytotext import pipeline | |
from PIL import Image | |
import json | |
from sentence_transformers import SentenceTransformer, CrossEncoder, util | |
import gzip | |
import os | |
import torch | |
import pickle | |
import yake | |
############ | |
## Main page | |
############ | |
st.write("# Demonstration for Etsy Query Expansion(Etsy-QE)") | |
st.markdown("***Idea is to build a model which will take query as inputs and generate expansion information as outputs.***") | |
image = Image.open('top.png') | |
st.image(image) | |
st.sidebar.write("# Top-N Selection") | |
maxtags_sidebar = st.sidebar.slider('Number of query allowed?', 1, 20, 1, key='ehikwegrjifbwreuk') | |
#user_query = st_tags( | |
# label='# Enter Query:', | |
# text='Press enter to add more', | |
# value=['Mother'], | |
# suggestions=['gift', 'nike', 'wool'], | |
# maxtags=maxtags_sidebar, | |
# key="aljnf") | |
user_query = st.text_input("Enter a query for the generated text: e.g., gift, home decoration ...") | |
# Add selectbox in streamlit | |
option1 = st.sidebar.selectbox( | |
'Which transformers model would you like to be selected?', | |
('multi-qa-MiniLM-L6-cos-v1','louis030195/multi-qa-MiniLM-L6-cos-v1-de-ecommerce','null')) | |
option2 = st.sidebar.selectbox( | |
'Which corss-encoder model would you like to be selected?', | |
('cross-encoder/ms-marco-MiniLM-L-6-v2','null','null')) | |
st.sidebar.success("Load Successfully!") | |
#if not torch.cuda.is_available(): | |
# print("Warning: No GPU found. Please add GPU to your notebook") | |
#We use the Bi-Encoder to encode all passages, so that we can use it with sematic search | |
bi_encoder = SentenceTransformer(option1,device='cpu') | |
bi_encoder.max_seq_length = 256 #Truncate long passages to 256 tokens | |
top_k = 32 #Number of passages we want to retrieve with the bi-encoder | |
#The bi-encoder will retrieve 100 documents. We use a cross-encoder, to re-rank the results list to improve the quality | |
cross_encoder = CrossEncoder(option2, device='cpu') | |
passages = [] | |
# load pre-train embeedings files | |
embedding_cache_path = 'etsy-embeddings-cpu.pkl' | |
print("Load pre-computed embeddings from disc") | |
with open(embedding_cache_path, "rb") as fIn: | |
cache_data = pickle.load(fIn) | |
passages = cache_data['sentences'] | |
corpus_embeddings = cache_data['embeddings'] | |
kw_extractor = yake.KeywordExtractor() | |
language = "en" | |
max_ngram_size = 3 | |
deduplication_threshold = 0.9 | |
numOfKeywords = 20 | |
custom_kw_extractor=yake.KeywordExtractor(lan=language, n=max_ngram_size, dedupLim=deduplication_threshold, top=numOfKeywords, features=None) | |
# This function will search all wikipedia articles for passages that | |
# answer the query | |
def search(query): | |
st.write("Input question:", query) | |
##### Sematic Search ##### | |
# Encode the query using the bi-encoder and find potentially relevant passages | |
query_embedding = bi_encoder.encode(query, convert_to_tensor=True) | |
hits = util.semantic_search(query_embedding, corpus_embeddings, top_k=top_k) | |
hits = hits[0] # Get the hits for the first query | |
##### Re-Ranking ##### | |
# Now, score all retrieved passages with the cross_encoder | |
cross_inp = [[query, passages[hit['corpus_id']]] for hit in hits] | |
cross_scores = cross_encoder.predict(cross_inp) | |
# Sort results by the cross-encoder scores | |
for idx in range(len(cross_scores)): | |
hits[idx]['cross-score'] = cross_scores[idx] | |
# Output of top-N hits from bi-encoder | |
#st.write("\n-------------------------\n") | |
#st.subheader("Top-N Bi-Encoder Retrieval hits") | |
#hits = sorted(hits, key=lambda x: x['score'], reverse=True) | |
#for hit in hits[0:maxtags_sidebar]: | |
# st.write("\t{:.3f}\t{}".format(hit['score'], passages[hit['corpus_id']].replace("\n", " "))) | |
# Output of top-N hits from re-ranker | |
st.write("\n-------------------------\n") | |
st.subheader("Top-N Cross-Encoder Re-ranker hits") | |
hits = sorted(hits, key=lambda x: x['cross-score'], reverse=True) | |
#for hit in hits[0:maxtags_sidebar]: | |
# st.write("\t{:.3f}\t{}".format(hit['cross-score'], passages[hit['corpus_id']].replace("\n", " "))) | |
hit_res = [] | |
for hit in hits[0:1000]: | |
q = passages[hit['corpus_id']].replace("\n", " ") | |
if q not in hit_res: | |
hit_res.append(q) | |
for res in hit_res[0:maxtags_sidebar]: | |
keywords = custom_kw_extractor.extract_keywords(res) | |
for kw in keywords: | |
st.write(kw) | |
st.write("## Results:") | |
if st.button('Generated Expansion'): | |
out = search(query = user_query) | |
#st.success(out) |