Spaces:
Running
Running
twitter iframe
#2
by
zhihuang
- opened
This view is limited to 50 files because it contains too many changes.
See the raw diff here.
- .gitattributes +0 -8
- .gitignore +0 -2
- app.py +18 -15
- data/.gitignore +0 -1
- data/data_weblinks.csv +0 -3
- data/example_images/Books_0c29c0c4-8670-4aef-b1f1-2969a1859f86.png +0 -3
- data/example_images/Books_0fe87b11-b817-457d-9598-345a0479c11d.png +0 -3
- data/example_images/Books_3f9a06a8-a4b6-4f12-a980-8a7fabfcb44f.png +0 -3
- data/example_images/DigestPath_18-01592B_2019-05-07 22_04_43-lv1-17807-19672-6802-4901.jpg +0 -3
- data/example_images/DigestPath_18-01913A_2019-05-07 22_11_13-lv1-23474-19944-5901-4637.jpg +0 -3
- data/example_images/PubMed_5c725893-b7ac-4836-b573-bac87a2bfad6.jpg +0 -3
- data/example_images/PubMed_b8ccabaf-3d88-4f58-a391-71b42f81f209.jpg +0 -3
- data/example_images/Screenshot from 2023-03-09 00-17-50.png +0 -3
- data/example_images/WSSS4LUAD_1222870-21308-23101-[1, 1, 0].png +0 -3
- data/example_images/mitotic_figure.png +0 -3
- data/example_images/signet_1901991002_2019-06-11 10_08_35-lv0-74236-7501-2000-2000.jpeg +0 -3
- data/example_images/signet_2013-12622_2018-07-03 20_26_40-lv0-33518-23938-2000-2000.jpeg +0 -3
- data/example_images/signet_2019-06-11 09_58_43-lv0-91918-38650-2000-2000.jpeg +0 -3
- data/example_images/signetpos_2018_67251_1-3_2019-02-26 00_02_22-lv0-25023-19640-2066-2066.jpeg +0 -3
- data/img_2d_embedding.csv +0 -3
- data/twitter.asset +0 -3
- data/txt_2d_embedding.csv +0 -3
- details.py +0 -73
- home.py +3 -44
- image2image.py +0 -239
- introduction.md +2 -0
- plip_support.py +9 -0
- requirements.txt +5 -6
- resources/4x/Fig1.png +0 -3
- resources/4x/Fig1ab.png +0 -3
- resources/4x/Fig1c.png +0 -3
- resources/4x/Fig1d.png +0 -3
- resources/4x/Fig1e.png +0 -3
- resources/4x/Fig1f.png +0 -3
- resources/4x/image_retrieval.png +0 -3
- resources/SVG/.DS_Store +0 -0
- resources/SVG/Asset 47.svg +0 -3
- resources/SVG/Asset 48.svg +0 -3
- resources/SVG/Asset 49.svg +0 -3
- resources/SVG/Asset 50.svg +0 -3
- resources/SVG/Asset 51.svg +0 -3
- resources/SVG/Asset 52.svg +0 -3
- resources/SVG/Asset 53.svg +0 -3
- resources/SVG/Asset 54.svg +0 -3
- resources/example/1.png +0 -3
- resources/example/2.png +0 -3
- resources/example/3.png +0 -3
- text2image.py +40 -192
- data/example_images/Books_0f25e3de-2c23-46df-ac67-b7bcddd5e1e6.png β tweet_eval_embeddings.npy +2 -2
- tweet_eval_retrieval.tsv +0 -0
.gitattributes
CHANGED
@@ -32,11 +32,3 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
32 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
33 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
34 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
35 |
-
*.csv filter=lfs diff=lfs merge=lfs -text
|
36 |
-
*.asset filter=lfs diff=lfs merge=lfs -text
|
37 |
-
twitter.asset filter=lfs diff=lfs merge=lfs -text
|
38 |
-
*.psd filter=lfs diff=lfs merge=lfs -text
|
39 |
-
*.jpg filter=lfs diff=lfs merge=lfs -text
|
40 |
-
*.jpeg filter=lfs diff=lfs merge=lfs -text
|
41 |
-
*.png filter=lfs diff=lfs merge=lfs -text
|
42 |
-
*.svg filter=lfs diff=lfs merge=lfs -text
|
|
|
32 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
33 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
34 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
.gitignore
DELETED
@@ -1,2 +0,0 @@
|
|
1 |
-
/__pycache__
|
2 |
-
*.pyc
|
|
|
|
|
|
app.py
CHANGED
@@ -1,27 +1,30 @@
|
|
|
|
|
|
1 |
import home
|
|
|
|
|
|
|
|
|
2 |
import text2image
|
3 |
-
import
|
4 |
-
import
|
5 |
import streamlit as st
|
6 |
-
import
|
7 |
-
|
8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
-
st.sidebar.title("
|
11 |
-
st.sidebar.markdown("## Menu")
|
12 |
|
13 |
PAGES = {
|
14 |
"Introduction": home,
|
15 |
-
"Details": details,
|
16 |
"Text to Image": text2image,
|
17 |
-
"Image to Image": image2image,
|
18 |
-
"Visualization": visualization,
|
19 |
}
|
20 |
|
21 |
page = st.sidebar.radio("", list(PAGES.keys()))
|
22 |
-
st.sidebar.markdown("## Links")
|
23 |
-
|
24 |
-
st.sidebar.markdown("[PLIP Model](https://huggingface.co/vinid/plip)")
|
25 |
-
st.sidebar.markdown("[OpenPath Dataset](https://drive.google.com/drive/folders/1b5UT8BzUphkHZavRG-fmiyY9JWYIWZER)")
|
26 |
-
st.sidebar.markdown("[PLIP Code](https://github.com/vinid/path_eval)")
|
27 |
PAGES[page].app()
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import pandas as pd
|
3 |
import home
|
4 |
+
import numpy as np
|
5 |
+
from PIL import Image
|
6 |
+
import requests
|
7 |
+
import transformers
|
8 |
import text2image
|
9 |
+
import tokenizers
|
10 |
+
from io import BytesIO
|
11 |
import streamlit as st
|
12 |
+
from transformers import CLIPModel
|
13 |
+
import clip
|
14 |
+
import torch
|
15 |
+
from transformers import (
|
16 |
+
VisionTextDualEncoderModel,
|
17 |
+
AutoFeatureExtractor,
|
18 |
+
AutoTokenizer
|
19 |
+
)
|
20 |
+
from transformers import AutoProcessor
|
21 |
|
22 |
+
st.sidebar.title("Explore our PLIP Demo")
|
|
|
23 |
|
24 |
PAGES = {
|
25 |
"Introduction": home,
|
|
|
26 |
"Text to Image": text2image,
|
|
|
|
|
27 |
}
|
28 |
|
29 |
page = st.sidebar.radio("", list(PAGES.keys()))
|
|
|
|
|
|
|
|
|
|
|
30 |
PAGES[page].app()
|
data/.gitignore
DELETED
@@ -1 +0,0 @@
|
|
1 |
-
/data_ignore
|
|
|
|
data/data_weblinks.csv
DELETED
@@ -1,3 +0,0 @@
|
|
1 |
-
version https://git-lfs.github.com/spec/v1
|
2 |
-
oid sha256:962bb004ef3d4f3ba02659ece1c9d4ae8f61083410345f99ea525d1249662a4d
|
3 |
-
size 16380376
|
|
|
|
|
|
|
|
data/example_images/Books_0c29c0c4-8670-4aef-b1f1-2969a1859f86.png
DELETED
Git LFS Details
|
data/example_images/Books_0fe87b11-b817-457d-9598-345a0479c11d.png
DELETED
Git LFS Details
|
data/example_images/Books_3f9a06a8-a4b6-4f12-a980-8a7fabfcb44f.png
DELETED
Git LFS Details
|
data/example_images/DigestPath_18-01592B_2019-05-07 22_04_43-lv1-17807-19672-6802-4901.jpg
DELETED
Git LFS Details
|
data/example_images/DigestPath_18-01913A_2019-05-07 22_11_13-lv1-23474-19944-5901-4637.jpg
DELETED
Git LFS Details
|
data/example_images/PubMed_5c725893-b7ac-4836-b573-bac87a2bfad6.jpg
DELETED
Git LFS Details
|
data/example_images/PubMed_b8ccabaf-3d88-4f58-a391-71b42f81f209.jpg
DELETED
Git LFS Details
|
data/example_images/Screenshot from 2023-03-09 00-17-50.png
DELETED
Git LFS Details
|
data/example_images/WSSS4LUAD_1222870-21308-23101-[1, 1, 0].png
DELETED
Git LFS Details
|
data/example_images/mitotic_figure.png
DELETED
Git LFS Details
|
data/example_images/signet_1901991002_2019-06-11 10_08_35-lv0-74236-7501-2000-2000.jpeg
DELETED
Git LFS Details
|
data/example_images/signet_2013-12622_2018-07-03 20_26_40-lv0-33518-23938-2000-2000.jpeg
DELETED
Git LFS Details
|
data/example_images/signet_2019-06-11 09_58_43-lv0-91918-38650-2000-2000.jpeg
DELETED
Git LFS Details
|
data/example_images/signetpos_2018_67251_1-3_2019-02-26 00_02_22-lv0-25023-19640-2066-2066.jpeg
DELETED
Git LFS Details
|
data/img_2d_embedding.csv
DELETED
@@ -1,3 +0,0 @@
|
|
1 |
-
version https://git-lfs.github.com/spec/v1
|
2 |
-
oid sha256:2c94660a66598254f87494fbb931f01a78feda5452d54c3b3939543a392d2fb7
|
3 |
-
size 13600550
|
|
|
|
|
|
|
|
data/twitter.asset
DELETED
@@ -1,3 +0,0 @@
|
|
1 |
-
version https://git-lfs.github.com/spec/v1
|
2 |
-
oid sha256:533c5c023e099a2725be0241ca57d6218e37f1f355963ced8d2305270312e428
|
3 |
-
size 245669888
|
|
|
|
|
|
|
|
data/txt_2d_embedding.csv
DELETED
@@ -1,3 +0,0 @@
|
|
1 |
-
version https://git-lfs.github.com/spec/v1
|
2 |
-
oid sha256:d5e5cde958eda7b8e74f327326029df1f7480c3bb2879141bdab8f71dd71fdd4
|
3 |
-
size 13659850
|
|
|
|
|
|
|
|
details.py
DELETED
@@ -1,73 +0,0 @@
|
|
1 |
-
from pathlib import Path
|
2 |
-
import streamlit as st
|
3 |
-
import streamlit.components.v1 as components
|
4 |
-
from PIL import Image
|
5 |
-
import base64
|
6 |
-
|
7 |
-
def read_markdown_file(markdown_file):
|
8 |
-
return Path(markdown_file).read_text()
|
9 |
-
|
10 |
-
def render_svg(svg_filename):
|
11 |
-
with open(svg_filename,"r") as f:
|
12 |
-
lines = f.readlines()
|
13 |
-
svg=''.join(lines)
|
14 |
-
"""Renders the given svg string."""
|
15 |
-
b64 = base64.b64encode(svg.encode('utf-8')).decode("utf-8")
|
16 |
-
html = r'<img src="data:image/svg+xml;base64,%s"/>' % b64
|
17 |
-
st.write(html, unsafe_allow_html=True)
|
18 |
-
|
19 |
-
|
20 |
-
def app():
|
21 |
-
#intro_markdown = read_markdown_file("introduction.md")
|
22 |
-
#st.markdown(intro_markdown, unsafe_allow_html=True)
|
23 |
-
st.markdown("# Leveraging medical Twitter to build a visual-language foundation model for pathology")
|
24 |
-
|
25 |
-
|
26 |
-
st.markdown("The lack of annotated publicly available medical images is a major barrier for innovations. At the same time, many de-identified images and much knowledge are shared by clinicians on public forums such as medical Twitter. Here we harness these crowd platforms to curate OpenPath, a large dataset of <b>208,414</b> pathology images paired with natural language descriptions. This is the largest public dataset for pathology images annotated with natural text. We demonstrate the value of this resource by developing PLIP, a multimodal AI with both image and text understanding, which is trained on OpenPath. PLIP achieves state-of-the-art zero-shot and few-short performance for classifying new pathology images across diverse tasks. Moreover, PLIP enables users to retrieve similar cases by either image or natural language search, greatly facilitating knowledge sharing. Our approach demonstrates that publicly shared medical data is a tremendous opportunity that can be harnessed to advance biomedical AI.", unsafe_allow_html=True)
|
27 |
-
render_svg("resources/SVG/Asset 49.svg")
|
28 |
-
|
29 |
-
st.markdown('#### Watch our successful image-to-image retrieval via PLIP:')
|
30 |
-
col1, col2, col3, _, _ = st.columns([1, 1, 1, 1, 1])
|
31 |
-
with col1:
|
32 |
-
st.markdown("[Similar cells](https://twitter.com/ZhiHuangPhD/status/1641906064823312384)")
|
33 |
-
example1 = Image.open('resources/example/1.png')
|
34 |
-
st.image(example1, caption='Example 1', output_format='png')
|
35 |
-
with col2:
|
36 |
-
st.markdown("[Salient object](https://twitter.com/ZhiHuangPhD/status/1641899092195565569)")
|
37 |
-
example2 = Image.open('resources/example/2.png')
|
38 |
-
st.image(example2, caption='Example 2', output_format='png')
|
39 |
-
with col3:
|
40 |
-
st.markdown("[Similar region](https://twitter.com/ZhiHuangPhD/status/1641911235288645632)")
|
41 |
-
example3 = Image.open('resources/example/3.png')
|
42 |
-
st.image(example3, caption='Example 3', output_format='png')
|
43 |
-
|
44 |
-
|
45 |
-
st.markdown("#### PLIP is trained on the largest public visionβlanguage pathology dataset: OpenPath")
|
46 |
-
|
47 |
-
col1, col2 = st.columns([1, 1])
|
48 |
-
with col1:
|
49 |
-
st.markdown("Following the usage policy and guidelines from Twitter and other entities, we established so far the largest public visionβlanguage pathology dataset. To ensure the quality of the data, OpenPath followed rigorous protocols for cohort inclusion and exclusion, including the removal of retweets, sensitive tweets, and non-pathology images, as well as text cleaning.", unsafe_allow_html=True)
|
50 |
-
st.markdown("The final OpenPath dataset consists of:", unsafe_allow_html=True)
|
51 |
-
st.markdown("- Tweets: 116,504 imageβtext pairs from Twitter posts (tweets) during Mar. 21, 2006 β Nov. 15, 2022 across 32 pathology subspecialty-specific hashtags;", unsafe_allow_html=True)
|
52 |
-
st.markdown("- Replies: 59,869 imageβtext pairs from the associated replies that received the highest number of likes in the tweet, if applicable;", unsafe_allow_html=True)
|
53 |
-
st.markdown("- PathLAION: 32,041 additional imageβtext pairs from the Internet which are outside from the Twitter community extracted from the LAION dataset.", unsafe_allow_html=True)
|
54 |
-
st.markdown("Leveraging the largest publicly available pathology dataset which contains imageβtext pairs across 32 different pathology subspecialty-specific hashtags, where each image has detailed text descriptions, we fine-tuned a pre-trained CLIP model and proposed a multimodal deep learning model for pathology, PLIP.", unsafe_allow_html=True)
|
55 |
-
with col2:
|
56 |
-
render_svg("resources/SVG/Asset 50.svg")
|
57 |
-
render_svg("resources/SVG/Asset 51.svg")
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
st.markdown("#### PLIP is trained with connecting the image and text via contrastive learning")
|
62 |
-
|
63 |
-
col1, col2 = st.columns([3, 1])
|
64 |
-
with col1:
|
65 |
-
st.markdown("The proposed PLIP model generates two embedding vectors from both the text and image encoders. These vectors were then forced to be similar for each of the paired image and text vectors and dissimilar for non-paired image and text pairs via contrastive learning.", unsafe_allow_html=True)
|
66 |
-
fig1e = Image.open('resources/4x/Fig1e.png')
|
67 |
-
st.image(fig1e, caption='PLIP training', output_format='png')
|
68 |
-
|
69 |
-
with col2:
|
70 |
-
render_svg("resources/SVG/Asset 53.svg")
|
71 |
-
|
72 |
-
|
73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
home.py
CHANGED
@@ -1,52 +1,11 @@
|
|
1 |
from pathlib import Path
|
2 |
import streamlit as st
|
3 |
-
|
4 |
-
from PIL import Image
|
5 |
-
import base64
|
6 |
|
7 |
def read_markdown_file(markdown_file):
|
8 |
return Path(markdown_file).read_text()
|
9 |
|
10 |
-
def render_svg(svg_filename):
|
11 |
-
with open(svg_filename,"r") as f:
|
12 |
-
lines = f.readlines()
|
13 |
-
svg=''.join(lines)
|
14 |
-
"""Renders the given svg string."""
|
15 |
-
b64 = base64.b64encode(svg.encode('utf-8')).decode("utf-8")
|
16 |
-
html = r'<img src="data:image/svg+xml;base64,%s"/>' % b64
|
17 |
-
st.write(html, unsafe_allow_html=True)
|
18 |
-
|
19 |
|
20 |
def app():
|
21 |
-
|
22 |
-
st.markdown(
|
23 |
-
st.markdown("This is a webapp for PLIP, our new fundational AI model for pathology and OpenPath our new dataset, **from our recent work**: Leveraging medical Twitter to build a visual-language foundation model for pathology")
|
24 |
-
st.markdown("### Pathology Language and Image Pretraining (PLIP)\n We develop PLIP, a multimodal AI with both image and text understanding. PLIP achieves state-of-the-art zero-shot and few-short performance for classifying new pathology images across diverse tasks. Moreover, PLIP enables users to retrieve similar cases by either image or natural language search, greatly facilitating knowledge sharing. Our approach demonstrates that publicly shared medical data is a tremendous opportunity that can be harnessed to advance biomedical AI.")
|
25 |
-
|
26 |
-
fig1e = Image.open('resources/4x/Fig1e.png')
|
27 |
-
st.image(fig1e, caption='PLIP training procedure', output_format='png')
|
28 |
-
|
29 |
-
st.markdown("### OpenPath Dataset\nThe lack of annotated publicly available medical images is a major barrier for innovations. At the same time, many de-identified images and much knowledge are shared by clinicians on public forums such as medical Twitter. Here we harness these crowd platforms to curate OpenPath, a large dataset of **208,414** pathology images paired with natural language descriptions")
|
30 |
-
|
31 |
-
render_svg("resources/SVG/Asset 49.svg")
|
32 |
-
|
33 |
-
|
34 |
-
st.markdown("### Documentation\n"
|
35 |
-
"This webapp comes with different functionalities.\n"
|
36 |
-
"* Details: The details page guides you through our work.\n"
|
37 |
-
"* Text to Image: allows users to perform text search on a database of images.\n"
|
38 |
-
"* Image to Image: allows users to perform image search on a database of images.\n"
|
39 |
-
"")
|
40 |
-
|
41 |
-
st.markdown("### Other Links\n"
|
42 |
-
"* Download [OpenPath](https://drive.google.com/drive/folders/1b5UT8BzUphkHZavRG-fmiyY9JWYIWZER)\n"
|
43 |
-
"* Code to reproduce [PLIP](https://github.com/vinid/path_eval) results\n"
|
44 |
-
"* Link to the [PLIP Model](https://huggingface.co/vinid/plip)\n"
|
45 |
-
"")
|
46 |
-
|
47 |
-
st.markdown("""---""")
|
48 |
-
st.markdown('Disclaimer')
|
49 |
-
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.')
|
50 |
-
|
51 |
-
st.markdown('Privacy statement')
|
52 |
-
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.')
|
|
|
1 |
from pathlib import Path
|
2 |
import streamlit as st
|
3 |
+
|
|
|
|
|
4 |
|
5 |
def read_markdown_file(markdown_file):
|
6 |
return Path(markdown_file).read_text()
|
7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
def app():
|
10 |
+
intro_markdown = read_markdown_file("introduction.md")
|
11 |
+
st.markdown(intro_markdown, unsafe_allow_html=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
image2image.py
DELETED
@@ -1,239 +0,0 @@
|
|
1 |
-
import streamlit as st
|
2 |
-
import pandas as pd
|
3 |
-
import numpy as np
|
4 |
-
from PIL import Image
|
5 |
-
import requests
|
6 |
-
import tokenizers
|
7 |
-
import os
|
8 |
-
from io import BytesIO
|
9 |
-
import pickle
|
10 |
-
import base64
|
11 |
-
import datetime
|
12 |
-
|
13 |
-
import torch
|
14 |
-
from transformers import (
|
15 |
-
VisionTextDualEncoderModel,
|
16 |
-
AutoFeatureExtractor,
|
17 |
-
AutoTokenizer,
|
18 |
-
CLIPModel,
|
19 |
-
AutoProcessor
|
20 |
-
)
|
21 |
-
import streamlit.components.v1 as components
|
22 |
-
from st_clickable_images import clickable_images #pip install st-clickable-images
|
23 |
-
|
24 |
-
|
25 |
-
@st.cache(
|
26 |
-
hash_funcs={
|
27 |
-
torch.nn.parameter.Parameter: lambda _: None,
|
28 |
-
tokenizers.Tokenizer: lambda _: None,
|
29 |
-
tokenizers.AddedToken: lambda _: None
|
30 |
-
}
|
31 |
-
)
|
32 |
-
def load_path_clip():
|
33 |
-
model = CLIPModel.from_pretrained("vinid/plip")
|
34 |
-
processor = AutoProcessor.from_pretrained("vinid/plip")
|
35 |
-
return model, processor
|
36 |
-
|
37 |
-
@st.cache
|
38 |
-
def init():
|
39 |
-
with open('data/twitter.asset', 'rb') as f:
|
40 |
-
data = pickle.load(f)
|
41 |
-
meta = data['meta'].reset_index(drop=True)
|
42 |
-
image_embedding = data['image_embedding']
|
43 |
-
text_embedding = data['text_embedding']
|
44 |
-
print(meta.shape, image_embedding.shape)
|
45 |
-
validation_subset_index = meta['source'].values == 'Val_Tweets'
|
46 |
-
return meta, image_embedding, text_embedding, validation_subset_index
|
47 |
-
|
48 |
-
def embed_images(model, images, processor):
|
49 |
-
inputs = processor(images=images)
|
50 |
-
pixel_values = torch.tensor(np.array(inputs["pixel_values"]))
|
51 |
-
|
52 |
-
with torch.no_grad():
|
53 |
-
embeddings = model.get_image_features(pixel_values=pixel_values)
|
54 |
-
return embeddings
|
55 |
-
|
56 |
-
def embed_texts(model, texts, processor):
|
57 |
-
inputs = processor(text=texts, padding="longest")
|
58 |
-
input_ids = torch.tensor(inputs["input_ids"])
|
59 |
-
attention_mask = torch.tensor(inputs["attention_mask"])
|
60 |
-
|
61 |
-
with torch.no_grad():
|
62 |
-
embeddings = model.get_text_features(
|
63 |
-
input_ids=input_ids, attention_mask=attention_mask
|
64 |
-
)
|
65 |
-
return embeddings
|
66 |
-
def app():
|
67 |
-
st.title('Image to Image Retrieval')
|
68 |
-
st.markdown('#### A pathology image search engine that correlate images with images.')
|
69 |
-
st.markdown("Image-to-image retrieval can be used to retrieve pathology images that have contents similar to the target image input, with the ability to comprehend the key components from the input image.")
|
70 |
-
|
71 |
-
st.markdown('#### Demo')
|
72 |
-
|
73 |
-
meta, image_embedding, text_embedding, validation_subset_index = init()
|
74 |
-
model, processor = load_path_clip()
|
75 |
-
|
76 |
-
|
77 |
-
col1, col2 = st.columns(2)
|
78 |
-
with col1:
|
79 |
-
data_options = ["All twitter data (03/21/2006 β 01/15/2023)",
|
80 |
-
"Twitter validation data (11/16/2022 β 01/15/2023)"]
|
81 |
-
st.radio(
|
82 |
-
"Choose dataset for image retrieval π",
|
83 |
-
key="datapool",
|
84 |
-
options=data_options,
|
85 |
-
)
|
86 |
-
with col2:
|
87 |
-
retrieval_options = ["Image only",
|
88 |
-
"Text and image (beta)",
|
89 |
-
]
|
90 |
-
st.radio(
|
91 |
-
"Similarity calcuation π",
|
92 |
-
key="calculation_option",
|
93 |
-
options=retrieval_options,
|
94 |
-
)
|
95 |
-
|
96 |
-
|
97 |
-
st.markdown('Try out following examples:')
|
98 |
-
example_path = 'data/example_images'
|
99 |
-
list_of_examples = [os.path.join(example_path, v) for v in os.listdir(example_path)]
|
100 |
-
example_imgs = []
|
101 |
-
for file in list_of_examples:
|
102 |
-
with open(file, "rb") as image:
|
103 |
-
encoded = base64.b64encode(image.read()).decode()
|
104 |
-
example_imgs.append(f"data:image/jpeg;base64,{encoded}")
|
105 |
-
clicked = clickable_images(
|
106 |
-
example_imgs,
|
107 |
-
titles=[f"Image #{str(i)}" for i in range(len(example_imgs))],
|
108 |
-
div_style={"display": "flex", "justify-content": "center", "flex-wrap": "wrap"},
|
109 |
-
img_style={"margin": "5px", "height": "70px"},
|
110 |
-
)
|
111 |
-
isExampleClicked = False
|
112 |
-
if clicked > -1:
|
113 |
-
image = Image.open(list_of_examples[clicked])
|
114 |
-
isExampleClicked = True
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
col1, col2, _ = st.columns(3)
|
122 |
-
with col1:
|
123 |
-
query = st.file_uploader("Choose a file to upload")
|
124 |
-
|
125 |
-
|
126 |
-
proceed = False
|
127 |
-
if query:
|
128 |
-
image = Image.open(query)
|
129 |
-
proceed = True
|
130 |
-
elif isExampleClicked:
|
131 |
-
proceed = True
|
132 |
-
|
133 |
-
if proceed:
|
134 |
-
with col2:
|
135 |
-
st.image(image, caption='Your upload')
|
136 |
-
|
137 |
-
input_image = embed_images(model, [image], processor)[0].detach().cpu().numpy()
|
138 |
-
|
139 |
-
input_image = input_image/np.linalg.norm(input_image)
|
140 |
-
|
141 |
-
# Sort IDs by cosine-similarity from high to low
|
142 |
-
|
143 |
-
if st.session_state.calculation_option == retrieval_options[0]: # Image only
|
144 |
-
similarity_scores = input_image.dot(image_embedding.T)
|
145 |
-
else: # Text and Image
|
146 |
-
similarity_scores_i = input_image.dot(image_embedding.T)
|
147 |
-
similarity_scores_t = input_image.dot(text_embedding.T)
|
148 |
-
similarity_scores_i = similarity_scores_i/np.max(similarity_scores_i)
|
149 |
-
similarity_scores_t = similarity_scores_t/np.max(similarity_scores_t)
|
150 |
-
similarity_scores = (similarity_scores_i + similarity_scores_t)/2
|
151 |
-
|
152 |
-
|
153 |
-
############################################################
|
154 |
-
# Get top results
|
155 |
-
############################################################
|
156 |
-
topn = 5
|
157 |
-
df = pd.DataFrame(np.c_[np.arange(len(meta)), similarity_scores, meta['weblink'].values], columns = ['idx', 'score', 'twitterlink'])
|
158 |
-
if st.session_state.datapool == data_options[1]: #Use val twitter data
|
159 |
-
df = df.loc[validation_subset_index,:]
|
160 |
-
df = df.sort_values('score', ascending=False)
|
161 |
-
df = df.drop_duplicates(subset=['twitterlink'])
|
162 |
-
best_id_topk = df['idx'].values[:topn]
|
163 |
-
target_scores = df['score'].values[:topn]
|
164 |
-
target_weblinks = df['twitterlink'].values[:topn]
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
############################################################
|
169 |
-
# Display results
|
170 |
-
############################################################
|
171 |
-
|
172 |
-
st.markdown('#### Top 5 results:')
|
173 |
-
topk_options = ['1st', '2nd', '3rd', '4th', '5th']
|
174 |
-
tab = {}
|
175 |
-
tab[0], tab[1], tab[2] = st.columns(3)
|
176 |
-
for i in [0,1,2]:
|
177 |
-
with tab[i]:
|
178 |
-
topn_value = i
|
179 |
-
topn_txt = topk_options[i]
|
180 |
-
st.caption(f'The {topn_txt} relevant image (similarity = {target_scores[topn_value]:.4f})')
|
181 |
-
components.html('''
|
182 |
-
<blockquote class="twitter-tweet">
|
183 |
-
<a href="%s"></a>
|
184 |
-
</blockquote>
|
185 |
-
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8">
|
186 |
-
</script>
|
187 |
-
''' % target_weblinks[topn_value],
|
188 |
-
height=600)
|
189 |
-
|
190 |
-
tab[3], tab[4], tab[5] = st.columns(3)
|
191 |
-
for i in [3,4]:
|
192 |
-
with tab[i]:
|
193 |
-
topn_value = i
|
194 |
-
topn_txt = topk_options[i]
|
195 |
-
st.caption(f'The {topn_txt} relevant image (similarity = {target_scores[topn_value]:.4f})')
|
196 |
-
components.html('''
|
197 |
-
<blockquote class="twitter-tweet">
|
198 |
-
<a href="%s"></a>
|
199 |
-
</blockquote>
|
200 |
-
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8">
|
201 |
-
</script>
|
202 |
-
''' % target_weblinks[topn_value],
|
203 |
-
height=800)
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
st.markdown("""---""")
|
215 |
-
st.markdown('Disclaimer')
|
216 |
-
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.')
|
217 |
-
|
218 |
-
st.markdown('Privacy statement')
|
219 |
-
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.')
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
introduction.md
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
|
2 |
+
# Welcome to our PLIP Demo
|
plip_support.py
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import clip
|
2 |
+
import torch
|
3 |
+
|
4 |
+
|
5 |
+
|
6 |
+
|
7 |
+
def embed_text(plip, text, device="cpu"):
|
8 |
+
idx = clip.tokenize([text], truncate=True).to(device)
|
9 |
+
return plip.encode_text(idx).detach().cpu().numpy()[0]
|
requirements.txt
CHANGED
@@ -1,8 +1,7 @@
|
|
1 |
-
|
2 |
-
tokenizers
|
3 |
-
pandas
|
4 |
torch
|
5 |
transformers
|
6 |
-
|
7 |
-
|
8 |
-
|
|
|
|
1 |
+
git+https://github.com/openai/CLIP.git
|
|
|
|
|
2 |
torch
|
3 |
transformers
|
4 |
+
pandas
|
5 |
+
numpy
|
6 |
+
Pillow
|
7 |
+
streamlit==1.19.0
|
resources/4x/Fig1.png
DELETED
Git LFS Details
|
resources/4x/Fig1ab.png
DELETED
Git LFS Details
|
resources/4x/Fig1c.png
DELETED
Git LFS Details
|
resources/4x/Fig1d.png
DELETED
Git LFS Details
|
resources/4x/Fig1e.png
DELETED
Git LFS Details
|
resources/4x/Fig1f.png
DELETED
Git LFS Details
|
resources/4x/image_retrieval.png
DELETED
Git LFS Details
|
resources/SVG/.DS_Store
DELETED
Binary file (6.15 kB)
|
|
resources/SVG/Asset 47.svg
DELETED
Git LFS Details
|
resources/SVG/Asset 48.svg
DELETED
Git LFS Details
|
resources/SVG/Asset 49.svg
DELETED
Git LFS Details
|
resources/SVG/Asset 50.svg
DELETED
Git LFS Details
|
resources/SVG/Asset 51.svg
DELETED
Git LFS Details
|
resources/SVG/Asset 52.svg
DELETED
Git LFS Details
|
resources/SVG/Asset 53.svg
DELETED
Git LFS Details
|
resources/SVG/Asset 54.svg
DELETED
Git LFS Details
|
resources/example/1.png
DELETED
Git LFS Details
|
resources/example/2.png
DELETED
Git LFS Details
|
resources/example/3.png
DELETED
Git LFS Details
|
text2image.py
CHANGED
@@ -1,58 +1,23 @@
|
|
1 |
import streamlit as st
|
2 |
import pandas as pd
|
|
|
3 |
import numpy as np
|
4 |
from PIL import Image
|
5 |
-
import
|
|
|
6 |
import tokenizers
|
|
|
|
|
|
|
|
|
7 |
import torch
|
8 |
-
|
9 |
from transformers import (
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
)
|
14 |
-
|
15 |
-
import base64
|
16 |
-
|
17 |
-
def render_svg(svg_filename):
|
18 |
-
with open(svg_filename,"r") as f:
|
19 |
-
lines = f.readlines()
|
20 |
-
svg=''.join(lines)
|
21 |
-
"""Renders the given svg string."""
|
22 |
-
b64 = base64.b64encode(svg.encode('utf-8')).decode("utf-8")
|
23 |
-
html = r'<img src="data:image/svg+xml;base64,%s"/>' % b64
|
24 |
-
st.write(html, unsafe_allow_html=True)
|
25 |
-
|
26 |
-
@st.cache(
|
27 |
-
hash_funcs={
|
28 |
-
torch.nn.parameter.Parameter: lambda _: None,
|
29 |
-
tokenizers.Tokenizer: lambda _: None,
|
30 |
-
tokenizers.AddedToken: lambda _: None
|
31 |
-
}
|
32 |
-
)
|
33 |
-
def load_path_clip():
|
34 |
-
model = CLIPModel.from_pretrained("vinid/plip")
|
35 |
-
processor = AutoProcessor.from_pretrained("vinid/plip")
|
36 |
-
return model, processor
|
37 |
|
38 |
-
@st.cache
|
39 |
-
def init():
|
40 |
-
with open('data/twitter.asset', 'rb') as f:
|
41 |
-
data = pickle.load(f)
|
42 |
-
meta = data['meta'].reset_index(drop=True)
|
43 |
-
image_embedding = data['image_embedding']
|
44 |
-
text_embedding = data['text_embedding']
|
45 |
-
print(meta.shape, image_embedding.shape)
|
46 |
-
validation_subset_index = meta['source'].values == 'Val_Tweets'
|
47 |
-
return meta, image_embedding, text_embedding, validation_subset_index
|
48 |
-
|
49 |
-
def embed_images(model, images, processor):
|
50 |
-
inputs = processor(images=images)
|
51 |
-
pixel_values = torch.tensor(np.array(inputs["pixel_values"]))
|
52 |
-
|
53 |
-
with torch.no_grad():
|
54 |
-
embeddings = model.get_image_features(pixel_values=pixel_values)
|
55 |
-
return embeddings
|
56 |
|
57 |
def embed_texts(model, texts, processor):
|
58 |
inputs = processor(text=texts, padding="longest")
|
@@ -65,162 +30,45 @@ def embed_texts(model, texts, processor):
|
|
65 |
)
|
66 |
return embeddings
|
67 |
|
|
|
|
|
|
|
|
|
68 |
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
meta, image_embedding, text_embedding, validation_subset_index = init()
|
82 |
-
model, processor = load_path_clip()
|
83 |
-
|
84 |
-
st.markdown('### Search')
|
85 |
-
st.markdown('How to use this: first of all, select a dataset on which to do retrieval.\n'
|
86 |
-
'Then, either select a predefined search query or input one yourself.')
|
87 |
-
|
88 |
-
|
89 |
-
col1, col2 = st.columns(2)
|
90 |
-
with col1:
|
91 |
-
data_options = ["All Twitter Data (03/21/2006 β 01/15/2023)",
|
92 |
-
"Validation Twitter data (11/16/2022 β 01/15/2023)"]
|
93 |
-
st.selectbox(
|
94 |
-
"Dataset",
|
95 |
-
key="datapool",
|
96 |
-
options=data_options,
|
97 |
-
)
|
98 |
-
|
99 |
-
with col2:
|
100 |
-
retrieval_options = ["Image only",
|
101 |
-
"Text and image (beta)",
|
102 |
-
]
|
103 |
-
st.radio(
|
104 |
-
"Similarity calcuation π",
|
105 |
-
key="calculation_option",
|
106 |
-
options=retrieval_options,
|
107 |
-
)
|
108 |
-
|
109 |
-
col1, col2 = st.columns(2)
|
110 |
-
|
111 |
-
with col1:
|
112 |
-
# Create selectbox
|
113 |
-
examples = ['Breast tumor surrounded by fat',
|
114 |
-
'HER2+ breast tumor',
|
115 |
-
'Colorectal cancer tumor on epithelium',
|
116 |
-
'An image of endometrium epithelium',
|
117 |
-
'Breast cancer DCIS',
|
118 |
-
'Papillary carcinoma in breast tissue',
|
119 |
-
]
|
120 |
-
query_1 = st.selectbox("Select an example", options=examples)
|
121 |
-
|
122 |
-
col1_submit = True
|
123 |
-
|
124 |
-
with col2:
|
125 |
-
form = st.form(key='my_form')
|
126 |
-
query_2 = form.text_input(label='Or input your custom query:')
|
127 |
-
submit_button = form.form_submit_button(label='Submit')
|
128 |
-
|
129 |
-
if submit_button:
|
130 |
-
col1_submit = False
|
131 |
-
|
132 |
-
if col1_submit:
|
133 |
-
query = query_1
|
134 |
-
else:
|
135 |
-
query = query_2
|
136 |
-
|
137 |
-
input_text = embed_texts(model, [query], processor)[0].detach().cpu().numpy()
|
138 |
-
input_text = input_text/np.linalg.norm(input_text)
|
139 |
-
|
140 |
-
# Sort IDs by cosine-similarity from high to low
|
141 |
-
|
142 |
-
if st.session_state.calculation_option == retrieval_options[0]: # Image only
|
143 |
-
similarity_scores = input_text.dot(image_embedding.T)
|
144 |
-
else: # Text and Image
|
145 |
-
similarity_scores_i = input_text.dot(image_embedding.T)
|
146 |
-
similarity_scores_t = input_text.dot(text_embedding.T)
|
147 |
-
similarity_scores_i = similarity_scores_i / np.max(similarity_scores_i)
|
148 |
-
similarity_scores_t = similarity_scores_t / np.max(similarity_scores_t)
|
149 |
-
similarity_scores = (similarity_scores_i + similarity_scores_t) / 2
|
150 |
-
|
151 |
-
############################################################
|
152 |
-
# Get top results
|
153 |
-
############################################################
|
154 |
-
topn = 5
|
155 |
-
df = pd.DataFrame(np.c_[np.arange(len(meta)), similarity_scores, meta['weblink'].values], columns = ['idx', 'score', 'twitterlink'])
|
156 |
-
if st.session_state.datapool == data_options[1]: #Use val twitter data
|
157 |
-
df = df.loc[validation_subset_index,:]
|
158 |
-
df = df.sort_values('score', ascending=False)
|
159 |
-
df = df.drop_duplicates(subset=['twitterlink'])
|
160 |
-
best_id_topk = df['idx'].values[:topn]
|
161 |
-
target_scores = df['score'].values[:topn]
|
162 |
-
target_weblinks = df['twitterlink'].values[:topn]
|
163 |
-
|
164 |
-
|
165 |
-
############################################################
|
166 |
-
# Display results
|
167 |
-
############################################################
|
168 |
-
|
169 |
-
text = '<font size="4">Your input query: <span style="background-color: rgb(230,230,230);"><b>%s</b></span>' % query + \
|
170 |
-
' (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(' ', '+'))
|
171 |
-
st.markdown(text, unsafe_allow_html=True)
|
172 |
-
|
173 |
-
st.markdown('#### Top 5 results:')
|
174 |
-
topk_options = ['1st', '2nd', '3rd', '4th', '5th']
|
175 |
-
tab = {}
|
176 |
-
tab[0], tab[1], tab[2] = st.columns(3)
|
177 |
-
for i in [0,1,2]:
|
178 |
-
with tab[i]:
|
179 |
-
topn_value = i
|
180 |
-
topn_txt = topk_options[i]
|
181 |
-
st.caption(f'The {topn_txt} relevant image (similarity = {target_scores[topn_value]:.4f})')
|
182 |
-
components.html('''
|
183 |
-
<blockquote class="twitter-tweet">
|
184 |
-
<a href="%s"></a>
|
185 |
-
</blockquote>
|
186 |
-
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8">
|
187 |
-
</script>
|
188 |
-
''' % target_weblinks[topn_value],
|
189 |
-
height=600)
|
190 |
-
|
191 |
-
tab[3], tab[4], tab[5] = st.columns(3)
|
192 |
-
for i in [3,4]:
|
193 |
-
with tab[i]:
|
194 |
-
topn_value = i
|
195 |
-
topn_txt = topk_options[i]
|
196 |
-
st.caption(f'The {topn_txt} relevant image (similarity = {target_scores[topn_value]:.4f})')
|
197 |
-
components.html('''
|
198 |
-
<blockquote class="twitter-tweet">
|
199 |
-
<a href="%s"></a>
|
200 |
-
</blockquote>
|
201 |
-
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8">
|
202 |
-
</script>
|
203 |
-
''' % target_weblinks[topn_value],
|
204 |
-
height=800)
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
st.markdown("""---""")
|
209 |
-
st.markdown('Disclaimer')
|
210 |
-
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.')
|
211 |
-
|
212 |
-
st.markdown('Privacy statement')
|
213 |
-
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.')
|
214 |
-
|
215 |
|
216 |
|
|
|
|
|
217 |
|
|
|
218 |
|
|
|
219 |
|
|
|
220 |
|
|
|
221 |
|
222 |
|
|
|
223 |
|
|
|
224 |
|
|
|
225 |
|
|
|
|
|
226 |
|
|
|
|
|
|
|
|
1 |
import streamlit as st
|
2 |
import pandas as pd
|
3 |
+
from plip_support import embed_text
|
4 |
import numpy as np
|
5 |
from PIL import Image
|
6 |
+
import requests
|
7 |
+
import transformers
|
8 |
import tokenizers
|
9 |
+
from io import BytesIO
|
10 |
+
import streamlit as st
|
11 |
+
from transformers import CLIPModel
|
12 |
+
import clip
|
13 |
import torch
|
|
|
14 |
from transformers import (
|
15 |
+
VisionTextDualEncoderModel,
|
16 |
+
AutoFeatureExtractor,
|
17 |
+
AutoTokenizer
|
18 |
)
|
19 |
+
from transformers import AutoProcessor
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
def embed_texts(model, texts, processor):
|
23 |
inputs = processor(text=texts, padding="longest")
|
|
|
30 |
)
|
31 |
return embeddings
|
32 |
|
33 |
+
@st.cache
|
34 |
+
def load_embeddings(embeddings_path):
|
35 |
+
print("loading embeddings")
|
36 |
+
return np.load(embeddings_path)
|
37 |
|
38 |
+
@st.cache(
|
39 |
+
hash_funcs={
|
40 |
+
torch.nn.parameter.Parameter: lambda _: None,
|
41 |
+
tokenizers.Tokenizer: lambda _: None,
|
42 |
+
tokenizers.AddedToken: lambda _: None
|
43 |
+
}
|
44 |
+
)
|
45 |
+
def load_path_clip():
|
46 |
+
model = CLIPModel.from_pretrained("vinid/plip")
|
47 |
+
processor = AutoProcessor.from_pretrained("vinid/plip")
|
48 |
+
return model, processor
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
49 |
|
50 |
|
51 |
+
def app():
|
52 |
+
st.title('PLIP Image Search')
|
53 |
|
54 |
+
plip_dataset = pd.read_csv("tweet_eval_retrieval.tsv", sep="\t")
|
55 |
|
56 |
+
model, processor = load_path_clip()
|
57 |
|
58 |
+
image_embedding = load_embeddings("tweet_eval_embeddings.npy")
|
59 |
|
60 |
+
query = st.text_input('Search Query', '')
|
61 |
|
62 |
|
63 |
+
if query:
|
64 |
|
65 |
+
text_embedding = embed_texts(model, [query], processor)[0].detach().cpu().numpy()
|
66 |
|
67 |
+
text_embedding = text_embedding/np.linalg.norm(text_embedding)
|
68 |
|
69 |
+
best_id = np.argmax(text_embedding.dot(image_embedding.T))
|
70 |
+
url = (plip_dataset.iloc[best_id]["imageURL"])
|
71 |
|
72 |
+
response = requests.get(url)
|
73 |
+
img = Image.open(BytesIO(response.content))
|
74 |
+
st.image(img)
|
data/example_images/Books_0f25e3de-2c23-46df-ac67-b7bcddd5e1e6.png β tweet_eval_embeddings.npy
RENAMED
@@ -1,3 +1,3 @@
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
-
oid sha256:
|
3 |
-
size
|
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:36e445b069b1d937a0a780ddeab9239df5fd13264e8cd1f6cf033be3210352e1
|
3 |
+
size 2401408
|
tweet_eval_retrieval.tsv
ADDED
The diff for this file is too large to render.
See raw diff
|
|