File size: 9,498 Bytes
61448a4
 
 
 
9e74540
61448a4
 
08fb6d9
61448a4
08fb6d9
dc3cb2a
 
61448a4
dc3cb2a
fe5d243
61448a4
fe5d243
 
 
 
 
 
 
 
61448a4
e66a8fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61448a4
 
 
 
9e74540
08fb6d9
9e74540
7ee7b26
 
 
 
 
fe5d243
7ee7b26
34d1458
61448a4
 
08fb6d9
 
 
 
34d1458
 
 
08fb6d9
 
 
 
34d1458
 
 
08fb6d9
34d1458
 
08fb6d9
34d1458
 
08fb6d9
34d1458
 
 
 
9e74540
08fb6d9
9e74540
 
 
 
 
 
 
 
 
08fb6d9
 
9e74540
08fb6d9
9e74540
 
 
 
08fb6d9
9e74540
 
 
 
 
 
 
 
34d1458
 
08fb6d9
 
 
 
34d1458
08fb6d9
34d1458
 
08fb6d9
 
 
34d1458
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08fb6d9
34ca5d9
 
fe5d243
 
34d1458
9e74540
34d1458
 
 
 
 
 
 
 
 
 
 
 
 
 
fe5d243
34d1458
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc3cb2a
 
 
fe5d243
9e74540
 
dc3cb2a
f58e4d2
 
 
dc3cb2a
 
 
 
 
 
 
 
 
 
61448a4
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import streamlit as st
import pandas as pd
import numpy as np
from PIL import Image
import pickle
import tokenizers
import torch

from transformers import (

    CLIPModel,
    AutoProcessor
)
import streamlit.components.v1 as components
import base64

def render_svg(svg_filename):
    with open(svg_filename,"r") as f:
        lines = f.readlines()
        svg=''.join(lines)
    """Renders the given svg string."""
    b64 = base64.b64encode(svg.encode('utf-8')).decode("utf-8")
    html = r'<img src="data:image/svg+xml;base64,%s"/>' % b64
    st.write(html, unsafe_allow_html=True)

@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

@st.cache
def init():
    with open('data/twitter.asset', 'rb') as f:
        data = pickle.load(f)
    meta = data['meta'].reset_index(drop=True)
    image_embedding = data['image_embedding']
    text_embedding = data['text_embedding']
    print(meta.shape, image_embedding.shape)
    validation_subset_index = meta['source'].values == 'Val_Tweets'
    return meta, image_embedding, text_embedding, validation_subset_index

def embed_images(model, images, processor):
    inputs = processor(images=images)
    pixel_values = torch.tensor(np.array(inputs["pixel_values"]))

    with torch.no_grad():
        embeddings = model.get_image_features(pixel_values=pixel_values)
    return embeddings

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


def app():

    st.title('Text to Image Retrieval')
    st.markdown('#### A pathology image search engine that geos from texts to images.')
    
    col1, col2 = st.columns([1,1])
    with col1:
        st.markdown("The text-to-image retrieval system can serve as an image search engine, enabling users to match images from multiple queries and retrieve the most relevant image based on a sentence description. This generic system can comprehend semantic and interrelated knowledge, such as “Breast tumor surrounded by fat”.")
        st.markdown("Unlike searching keywords and sentences from Google and indirectly matching the images from the target text, our proposed pathology image retrieval allows direct comparison between input sentences and images.")
    with col2:
        render_svg("resources/SVG/Asset 54.svg")

    meta, image_embedding, text_embedding, validation_subset_index = init()
    model, processor = load_path_clip()

    st.markdown('### Search')
    st.markdown('How to use this: first of all, select a dataset on which to do retrieval.\n'
                'Then, either select a predefined search query or input one yourself.')


    col1, col2 = st.columns(2)
    with col1:
        data_options = ["All Twitter Data (03/21/2006 — 01/15/2023)",
                        "Validation Twitter data (11/16/2022 — 01/15/2023)"]
        st.selectbox(
            "Dataset",
            key="datapool",
            options=data_options,
        )

    with col2:
        retrieval_options = ["Image only",
                             "Text and image (beta)",
                             ]
        st.radio(
            "Similarity calcuation 👉",
            key="calculation_option",
            options=retrieval_options,
        )

    col1, col2 = st.columns(2)

    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("Select an example", options=examples)

        col1_submit = 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

    if col1_submit:
        query = query_1
    else:
        query = query_2

    input_text = embed_texts(model, [query], processor)[0].detach().cpu().numpy()
    input_text = input_text/np.linalg.norm(input_text)

    # Sort IDs by cosine-similarity from high to low

    if st.session_state.calculation_option == retrieval_options[0]:  # Image only
        similarity_scores = input_text.dot(image_embedding.T)
    else:  # Text and Image
        similarity_scores_i = input_text.dot(image_embedding.T)
        similarity_scores_t = input_text.dot(text_embedding.T)
        similarity_scores_i = similarity_scores_i / np.max(similarity_scores_i)
        similarity_scores_t = similarity_scores_t / np.max(similarity_scores_t)
        similarity_scores = (similarity_scores_i + similarity_scores_t) / 2

    ############################################################
    # Get top results
    ############################################################
    topn = 5
    df = pd.DataFrame(np.c_[np.arange(len(meta)), similarity_scores, meta['weblink'].values], columns = ['idx', 'score', 'twitterlink'])
    if st.session_state.datapool == data_options[1]: #Use val twitter data
        df = df.loc[validation_subset_index,:]
    df = df.sort_values('score', ascending=False)
    df = df.drop_duplicates(subset=['twitterlink'])
    best_id_topk = df['idx'].values[:topn]
    target_scores = df['score'].values[:topn]
    target_weblinks = df['twitterlink'].values[:topn]


    ############################################################
    # Display results
    ############################################################

    text = '<font size="4">Your input query: <span style="background-color: rgb(230,230,230);"><b>%s</b></span>' % query + \
        ' (Try search it directly on [Twitter](https://twitter.com/search?q=%s&src=typed_query) or [Google](https://www.google.com/search?q=%s))</font>' % (query.replace(' ', '%20'), query.replace(' ', '+'))
    st.markdown(text, unsafe_allow_html=True)

    st.markdown('#### Top 5 results:')
    topk_options = ['1st', '2nd', '3rd', '4th', '5th']
    tab = {}
    tab[0], tab[1], tab[2] = st.columns(3)
    for i in [0,1,2]:
        with tab[i]:
            topn_value = i
            topn_txt = topk_options[i]
            st.caption(f'The {topn_txt} relevant image (similarity = {target_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=600)

    tab[3], tab[4], tab[5] = st.columns(3)
    for i in [3,4]:
        with tab[i]:
            topn_value = i
            topn_txt = topk_options[i]
            st.caption(f'The {topn_txt} relevant image (similarity = {target_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("""---""")
    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.')

    st.markdown('Privacy statement')
    st.caption('In accordance with the privacy and control policy of Twitter, we hereby declared that the data redistributed by us shall only comprise of Tweet IDs. The Tweet IDs will be employed to establish a linkage with the original Twitter post, as long as the original post is still accessible. The hyperlink will cease to function if the user deletes the original post. It is important to note that all tweets displayed on our service have already been classified as non-sensitive by Twitter. It is strictly prohibited to redistribute any content apart from the Tweet IDs. Any distribution carried out must adhere to the laws and regulations applicable in your jurisdiction, including export control laws and embargoes.')