webplip / text2image.py
huangzhii
update
1bf0164
raw
history blame
5.75 kB
import streamlit as st
import pandas as pd
from plip_support import embed_text
import numpy as np
from PIL import Image
import requests
import pickle
import tokenizers
from io import BytesIO
import torch
from transformers import (
VisionTextDualEncoderModel,
AutoFeatureExtractor,
AutoTokenizer,
CLIPModel,
AutoProcessor
)
import streamlit.components.v1 as components
def embed_texts(model, texts, processor):
inputs = processor(text=texts, padding="longest")
input_ids = torch.tensor(inputs["input_ids"])
attention_mask = torch.tensor(inputs["attention_mask"])
with torch.no_grad():
embeddings = model.get_text_features(
input_ids=input_ids, attention_mask=attention_mask
)
return embeddings
@st.cache
def load_embeddings(embeddings_path):
print("loading embeddings")
return np.load(embeddings_path)
@st.cache(
hash_funcs={
torch.nn.parameter.Parameter: lambda _: None,
tokenizers.Tokenizer: lambda _: None,
tokenizers.AddedToken: lambda _: None
}
)
def load_path_clip():
model = CLIPModel.from_pretrained("vinid/plip")
processor = AutoProcessor.from_pretrained("vinid/plip")
return model, processor
def init():
with open('data/twitter.asset', 'rb') as f:
data = pickle.load(f)
meta = data['meta'].reset_index(drop=True)
image_embedding = data['embedding']
print(meta.shape, image_embedding.shape)
validation_subset_index = meta['source'].values == 'Val_Tweets'
return meta, image_embedding, validation_subset_index
def app():
st.title('Text to Image Retrieval')
st.markdown('#### A pathology image search engine that correlate texts directly with images.')
st.caption('Note: The searching query matches images only. The twitter text does not used for searching.')
meta, image_embedding, validation_subset_index = init()
model, processor = load_path_clip()
data_options = ["All twitter data (2006-03-21 β€” 2023-01-15)",
"Twitter validation data (2022-11-16 β€” 2023-01-15)"]
st.radio(
"Choose dataset for image retrieval πŸ‘‰",
key="datapool",
options=data_options,
)
col1, col2 = st.columns(2)
#query = st.text_input('Search Query', '')
col1_submit = False
show = False
with col1:
# Create selectbox
examples = ['Breast tumor surrounded by fat',
'HER2+ breast tumor',
'Colorectal cancer tumor on epithelium',
'An image of endometrium epithelium',
'Breast cancer DCIS',
'Papillary carcinoma in breast tissue',
]
query_1 = st.selectbox("Please select an example query", options=examples)
#st.info(f":white_check_mark: The written option is {query_1} ")
col1_submit = True
show = True
with col2:
form = st.form(key='my_form')
query_2 = form.text_input(label='Or input your custom query:')
submit_button = form.form_submit_button(label='Submit')
if submit_button:
col1_submit = False
show = True
if col1_submit:
query = query_1
else:
query = query_2
text_embedding = embed_texts(model, [query], processor)[0].detach().cpu().numpy()
text_embedding = text_embedding/np.linalg.norm(text_embedding)
similarity_scores = text_embedding.dot(image_embedding.T)
topn = 5
if st.session_state.datapool == data_options[0]:
#Use all twitter data
id_sorted = np.argsort(similarity_scores)[::-1]
best_ids = id_sorted[:topn]
best_scores = similarity_scores[best_ids]
target_weblinks = meta["weblink"].values[best_ids]
else:
#Use validation twitter data
similarity_scores = similarity_scores[validation_subset_index]
# Sort IDs by cosine-similarity from high to low
id_sorted = np.argsort(similarity_scores)[::-1]
best_ids = id_sorted[:topn]
best_scores = similarity_scores[best_ids]
target_weblinks = meta["weblink"].values[validation_subset_index][best_ids]
#TODO: Avoid duplicated ID
topk_options = ['1st', '2nd', '3rd', '4th', '5th']
st.radio(
"Choose the most similar πŸ‘‰",
key="top_k",
options=topk_options,
horizontal=True
)
topn_txt = st.session_state.top_k
topn_value = int(st.session_state.top_k[0])-1
st.caption(f'The {topn_txt} relevant image (similarity = {best_scores[topn_value]:.4f})')
components.html('''
<blockquote class="twitter-tweet">
<a href="%s"></a>
</blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8">
</script>
''' % target_weblinks[topn_value],
height=800)
st.markdown('Disclaimer')
st.caption('Please be advised that this function has been developed in compliance with the Twitter policy of data usage and sharing. It is important to note that the results obtained from this function are not intended to constitute medical advice or replace consultation with a qualified medical professional. The use of this function is solely at your own risk and should be consistent with applicable laws, regulations, and ethical considerations. We do not warrant or guarantee the accuracy, completeness, suitability, or usefulness of this function for any particular purpose, and we hereby disclaim any liability arising from any reliance placed on this function or any results obtained from its use. If you wish to review the original Twitter post, you should access the source page directly on Twitter.')