import streamlit as st
import numpy as np
import base64
from io import BytesIO
from multilingual_clip import pt_multilingual_clip
from transformers import CLIPTokenizerFast, AutoTokenizer, CLIPModel
import torch
import logging
from os import environ
from parse import parse
from clickhouse_connect import get_client
environ['TOKENIZERS_PARALLELISM'] = 'true'
db_name_map = {
"Unsplash Photos 25K": lambda feat: f"mqdb_demo.unsplash_25k_{feat}_indexer",
"RSICD: Remote Sensing Images 11K": lambda feat: f"mqdb_demo.rsicd_{feat}_b_32",
}
feat_name_map = {
'Vanilla CLIP': "clip",
'CLIP finetuned on RSICD': "cliprsicd"
}
DB_NAME = "mqdb_demo.unsplash_25k_clip_indexer"
DIMS = 512
# Ignore some bad links (broken in the dataset already)
BAD_IDS = {'9_9hzZVjV8s', 'RDs0THr4lGs', 'vigsqYux_-8',
'rsJtMXn3p_c', 'AcG-unN00gw', 'r1R_0ZNUcx0'}
@st.experimental_singleton(show_spinner=False)
def init_db():
""" Initialize the Database Connection
Returns:
meta_field: Meta field that records if an image is viewed or not
client: Database connection object
"""
r = parse("{http_pre}://{host}:{port}", st.secrets["DB_URL"])
client = get_client(
host=r['host'], port=r['port'], user=st.secrets["USER"], password=st.secrets["PASSWD"],
interface=r['http_pre'],
)
meta_field = {}
return meta_field, client
@st.experimental_singleton(show_spinner=False)
def init_query_num():
print("init query_num")
return 0
def query(xq, top_k=10):
""" Query TopK matched w.r.t a given vector
Args:
xq (numpy.ndarray or list of floats): Query vector
top_k (int, optional): Number of matched vectors. Defaults to 10.
Returns:
matches: list of Records object. Keys referrring to selected columns
"""
attempt = 0
xq = xq / np.linalg.norm(xq)
while attempt < 3:
try:
xq_s = f"[{', '.join([str(float(fnum)) for fnum in list(xq)])}]"
print('Excluded pre:', st.session_state.meta)
if len(st.session_state.meta) > 0:
exclude_list = ','.join(
[f'\'{i}\'' for i, v in st.session_state.meta.items() if v >= 1])
print("Excluded:", exclude_list)
# Using PREWHERE allows you to do column filter before vector search
xc = st.session_state.index.query(f"SELECT id, url, vector,\
distance(vector, {xq_s}) AS dist\
FROM {db_name_map[st.session_state.db_name_ref](feat_name_map[st.session_state.feat_name])} \
WHERE id NOT IN ({exclude_list}) ORDER BY dist LIMIT {top_k}").named_results()
else:
xc = st.session_state.index.query(f"SELECT id, url, vector,\
distance(vector, {xq_s}) AS dist\
FROM {db_name_map[st.session_state.db_name_ref](feat_name_map[st.session_state.feat_name])} \
ORDER BY dist LIMIT {top_k}").named_results()
real_xc = st.session_state.index.query(f"SELECT id, url, vector,\
distance(vector, {xq_s}) AS dist \
FROM {db_name_map[st.session_state.db_name_ref](feat_name_map[st.session_state.feat_name])} \
ORDER BY dist LIMIT {top_k}").named_results()
top_k = [{k: v for k, v in r.items()} for r in real_xc]
xc = [xi for xi in xc if xi['id'] not in st.session_state.meta or
st.session_state.meta[xi['id']] < 1]
logging.info(
f'{len(xc)} records returned, {[_i["id"] for _i in xc]}')
matches = xc
break
except Exception as e:
# force reload if we have trouble on connections or something else
logging.warning(str(e))
_, st.session_state.index = init_db()
attempt += 1
matches = []
if len(matches) == 0:
logging.error(f"No matches found for '{DB_NAME}'")
return matches, top_k
@st.experimental_singleton(show_spinner=False)
def init_random_query():
xq = np.random.rand(DIMS).tolist()
return xq, xq.copy()
class Classifier:
""" Zero-shot Classifier
This Classifier provides proxy regarding to the user's reaction to the probed images.
The proxy will replace the original query vector generated by prompted vector and finally
give the user a satisfying retrieval result.
This can be commonly seen in a recommendation system. The classifier will recommend more
precise result as it accumulating user's activity.
"""
def __init__(self, xq: list):
# initialize model with DIMS input size and 1 output
# note that the bias is ignored, as we only focus on the inner product result
self.model = torch.nn.Linear(DIMS, 1, bias=False)
# convert initial query `xq` to tensor parameter to init weights
init_weight = torch.Tensor(xq).reshape(1, -1)
self.model.weight = torch.nn.Parameter(init_weight)
# init loss and optimizer
self.loss = torch.nn.BCEWithLogitsLoss()
self.optimizer = torch.optim.SGD(self.model.parameters(), lr=0.1)
def fit(self, X: list, y: list, iters: int = 5):
# convert X and y to tensor
X = torch.Tensor(X)
y = torch.Tensor(y).reshape(-1, 1)
for i in range(iters):
# zero gradients
self.optimizer.zero_grad()
# Normalize the weight before inference
# This will constrain the gradient or you will have an explosion on query vector
self.model.weight.data = self.model.weight.data / \
torch.norm(self.model.weight.data, p=2, dim=-1)
# forward pass
out = self.model(X)
# compute loss
loss = self.loss(out, y)
# backward pass
loss.backward()
# update weights
self.optimizer.step()
def get_weights(self):
xq = self.model.weight.detach().numpy()[0].tolist()
return xq
class NormalizingLayer(torch.nn.Module):
def forward(self, x):
return x / torch.norm(x, dim=-1, keepdim=True)
def card(i, url):
return f''
def card_with_conf(i, conf, url):
conf = "%.4f" % (conf)
return f'
Relevance: {conf}
Don\'t know what to search? Try Random!
\🌟 We also support multi-language search. Type any language you know to search! ⌨️
', unsafe_allow_html=True) upld_model = start[6].file_uploader( "Or you can upload your previous run!", type='onnx') upld_btn = start[7].button( "Use Loaded Weights", disabled=upld_model is None) prompt = start[3].text_input( "Prompt:", value="An aerial photograph of "if st.session_state.db_name_ref == "RSICD: Remote Sensing Images 11K" else "", placeholder="Examples: playing corgi, 女人举着雨伞, mouette volant au-dessus de la mer, ガラスの花瓶の花 ...",) with start[5]: col = st.columns(8) has_no_prompt = (len(prompt) == 0 and upld_model is None) prompt_xq = col[6].button("Prompt", disabled=len(prompt) == 0) random_xq = col[7].button("Random", disabled=not ( len(prompt) == 0 and upld_model is None)) if random_xq: # Randomly pick a vector to query xq, orig_xq = init_random_query() st.session_state.xq = xq st.session_state.orig_xq = orig_xq _ = [elem.empty() for elem in start] elif prompt_xq or upld_btn: if upld_model is not None: # Import vector from a file import onnx from onnx import numpy_helper _model = onnx.load(upld_model) weights = _model.graph.initializer assert len(weights) == 1 xq = numpy_helper.to_array(weights[0]).tolist() assert len(xq) == DIMS st.session_state.prompt = upld_model.name.split(".onnx")[ 0].replace(' ', '_') else: print(f"Input prompt is {prompt}") # Tokenize the vectors p2v_func, args = text_model_map[st.session_state.lang][st.session_state.feat_name] xq = p2v_func(prompt, *args) st.session_state.xq = xq st.session_state.orig_xq = xq _ = [elem.empty() for elem in start] if 'xq' in st.session_state: # If it is not a fresh start if st.session_state.query_num+1 < len(messages): msg = messages[st.session_state.query_num+1] else: msg = messages[-1] # initialize classifier if 'clf' not in st.session_state: st.session_state.clf = Classifier(st.session_state.xq) # if we want to display images we end up here st.info(msg) # first retrieve images from pinecone st.session_state.matches, st.session_state.top_k = get_top_k( st.session_state.clf.get_weights(), top_k=9) # export the model into executable ONNX st.session_state.dnld_model = BytesIO() torch.onnx.export(torch.nn.Sequential(NormalizingLayer(), st.session_state.clf.model), torch.as_tensor(st.session_state.xq).reshape(1, -1), st.session_state.dnld_model, input_names=['input'], output_names=['output']) with st.container(): with st.sidebar: with st.container(): st.header("Top K Nearest in Database") for i, k in enumerate(st.session_state.top_k): url = k["url"] url += "?q=75&fm=jpg&w=200&fit=max" if k["id"] not in BAD_IDS: disabled = False else: disable = True dist = np.matmul(st.session_state.clf.get_weights() / np.linalg.norm(st.session_state.clf.get_weights()), np.array(k["vector"]).T) st.markdown(card_with_conf(i, dist, url), unsafe_allow_html=True) dnld_nam = st.text_input('Download Name:', f'{(st.session_state.prompt if "prompt" in st.session_state else "model")}.onnx', max_chars=50) dnld_btn = st.download_button('Download your classifier!', st.session_state.dnld_model, dnld_nam,) # once retrieved, display them alongside checkboxes in a form with st.form("batch", clear_on_submit=False): st.session_state.iters = st.slider( "Number of Iterations to Update", min_value=0, max_value=10, step=1, value=2) col = st.columns([1, 9]) col[0].form_submit_button("Train!", on_click=submit) col[1].form_submit_button( "Choose a new prompt", on_click=refresh_index) # we have three columns in the form cols = st.columns(3) for i, match in enumerate(st.session_state.matches): # find good url url = match["url"] url += "?q=75&fm=jpg&w=200&fit=max" if match["id"] not in BAD_IDS: disabled = False else: disable = True # the card shows an image and a checkbox cols[i % 3].markdown(card(i, url), unsafe_allow_html=True) # we access the values of the checkbox via st.session_state[f"input{i}"] cols[i % 3].slider( "Relevance", min_value=0.0, max_value=1.0, value=1.0, step=0.05, key=f"input{i}", disabled=disabled )