|
|
|
from doctest import OutputChecker |
|
import sys |
|
import torch |
|
import re |
|
import os |
|
import gradio as gr |
|
import requests |
|
import torch |
|
from transformers import GPT2Tokenizer, GPT2LMHeadModel |
|
from torch.nn.functional import softmax |
|
import numpy as np |
|
|
|
|
|
|
|
|
|
from sentence_transformers import SentenceTransformer, util |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
model_sts = SentenceTransformer('stsb-distilbert-base') |
|
|
|
|
|
|
|
|
|
|
|
|
|
from transformers import GPT2Tokenizer, GPT2LMHeadModel |
|
import numpy as np |
|
import re |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tokenizer = GPT2Tokenizer.from_pretrained('gpt2') |
|
model = GPT2LMHeadModel.from_pretrained('gpt2') |
|
|
|
|
|
def sentence_prob_mean(text): |
|
|
|
input_ids = tokenizer.encode(text, return_tensors='pt') |
|
|
|
|
|
with torch.no_grad(): |
|
outputs = model(input_ids, labels=input_ids) |
|
logits = outputs.logits |
|
|
|
|
|
shift_logits = logits[..., :-1, :].contiguous() |
|
shift_labels = input_ids[..., 1:].contiguous() |
|
|
|
|
|
probs = softmax(shift_logits, dim=-1) |
|
|
|
|
|
gathered_probs = torch.gather(probs, 2, shift_labels.unsqueeze(-1)).squeeze(-1) |
|
|
|
|
|
mean_prob = torch.mean(gathered_probs).item() |
|
|
|
return mean_prob |
|
|
|
|
|
|
|
|
|
def cos_sim(a, b): |
|
return np.inner(a, b) / (np.linalg.norm(a) * (np.linalg.norm(b))) |
|
|
|
|
|
|
|
def Visual_re_ranker(caption, visual_context_label, visual_context_prob): |
|
caption = caption |
|
visual_context_label= visual_context_label |
|
visual_context_prob = visual_context_prob |
|
caption_emb = model_sts.encode(caption, convert_to_tensor=True) |
|
visual_context_label_emb = model_sts.encode(visual_context_label, convert_to_tensor=True) |
|
|
|
|
|
sim = cosine_scores = util.pytorch_cos_sim(caption_emb, visual_context_label_emb) |
|
sim = sim.cpu().numpy() |
|
sim = str(sim)[1:-1] |
|
sim = str(sim)[1:-1] |
|
|
|
|
|
LM = sentence_prob_mean(caption) |
|
|
|
score = pow(float(LM),pow((1-float(sim))/(1+ float(sim)),1-float(visual_context_prob))) |
|
|
|
|
|
|
|
return {"init hypothesis": float(LM)/1, "Visual Belief Revision": float(score)/1 } |
|
|
|
|
|
|
|
|
|
demo = gr.Interface( |
|
fn=Visual_re_ranker, |
|
description="Demo for Belief Revision based Caption Re-ranker with Visual Semantic Information", |
|
inputs=[gr.Textbox(value="a city street filled with traffic at night") , gr.Textbox(value="traffic"), gr.Textbox(value="0.7458009")], |
|
|
|
outputs="label", |
|
share=True, |
|
) |
|
demo.launch() |
|
|
|
|