File size: 5,484 Bytes
4387c41 ec56d92 40180ec ec56d92 40180ec ec56d92 ab08f57 40180ec 4387c41 ab08f57 80775ab ab08f57 e20e1d6 ab08f57 80775ab ab08f57 40180ec 4387c41 6f13d63 4387c41 1e4c550 4387c41 1e4c550 68ad585 4387c41 e4bec56 4387c41 877091a 4387c41 68ad585 4387c41 |
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 |
#!/usr/bin/env python3
# from doctest import OutputChecker
# import sys
# import torch
# import re
# import os
# import gradio as gr
# import requests
# 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 huggingface_hub import login
#!/usr/bin/env python3
from doctest import OutputChecker
import sys
import torch
import re
import os
import gradio as gr
import requests
import torch
from torch.nn.functional import softmax
import numpy as np
from transformers import AutoTokenizer, AutoModelForCausalLM
#from torch.nn.functional import softmax
from huggingface_hub import login
#url = "https://github.com/simonepri/lm-scorer/tree/master/lm_scorer/models"
#resp = requests.get(url)
from sentence_transformers import SentenceTransformer, util
#model_sts = SentenceTransformer('stsb-distilbert-base')
model_sts = SentenceTransformer('roberta-large-nli-stsb-mean-tokens')
#batch_size = 1
#scorer = LMScorer.from_pretrained('gpt2' , device=device, batch_size=batch_size)
#import torch
from transformers import GPT2Tokenizer, GPT2LMHeadModel
import numpy as np
import re
def get_sim(x):
x = str(x)[1:-1]
x = str(x)[1:-1]
return x
import os
#print(os.getenv('HF_token'))
hf_api_token = os.getenv("HF_token") # For sensitive secrets
#app_mode = os.getenv("APP_MODE") # For public variables
access_token = hf_api_token
print(login(token = access_token))
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.2-1B")
model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B")
#tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
#model = GPT2LMHeadModel.from_pretrained('gpt2')
def sentence_prob_mean(text):
# Tokenize the input text and add special tokens
input_ids = tokenizer.encode(text, return_tensors='pt')
# Obtain model outputs
with torch.no_grad():
outputs = model(input_ids, labels=input_ids)
logits = outputs.logits # logits are the model outputs before applying softmax
# Shift logits and labels so that tokens are aligned:
shift_logits = logits[..., :-1, :].contiguous()
shift_labels = input_ids[..., 1:].contiguous()
# Calculate the softmax probabilities
probs = softmax(shift_logits, dim=-1)
# Gather the probabilities of the actual token IDs
gathered_probs = torch.gather(probs, 2, shift_labels.unsqueeze(-1)).squeeze(-1)
# Compute the mean probability across the tokens
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_G, caption_B, caption_VR, visual_context_label, visual_context_prob):
caption_G = caption_G
caption_B = caption_B
caption_VR = caption_VR
visual_context_label= visual_context_label
visual_context_prob = visual_context_prob
caption_emb_G = model_sts.encode(caption_G, convert_to_tensor=True)
caption_emb_B = model_sts.encode(caption_B, convert_to_tensor=True)
caption_emb_VR = model_sts.encode(caption_VR, convert_to_tensor=True)
visual_context_label_emb = model_sts.encode(visual_context_label, convert_to_tensor=True)
sim_1 = cosine_scores = util.pytorch_cos_sim(caption_emb_G, visual_context_label_emb)
sim_1 = sim_1.cpu().numpy()
sim_1 = get_sim(sim_1)
sim_2 = cosine_scores = util.pytorch_cos_sim(caption_emb_B, visual_context_label_emb)
sim_2 = sim_2.cpu().numpy()
sim_2 = get_sim(sim_2)
sim_3 = cosine_scores = util.pytorch_cos_sim(caption_emb_VR, visual_context_label_emb)
sim_3 = sim_3.cpu().numpy()
sim_3 = get_sim(sim_3)
LM_1 = sentence_prob_mean(caption_G)
LM_2 = sentence_prob_mean(caption_B)
LM_3 = sentence_prob_mean(caption_VR)
#LM = scorer.sentence_score(caption, reduce="mean")
score_1 = pow(float(LM_1),pow((1-float(sim_1))/(1+ float(sim_1)),1-float(visual_context_prob)))
score_2 = pow(float(LM_2),pow((1-float(sim_2))/(1+ float(sim_2)),1-float(visual_context_prob)))
score_3 = pow(float(LM_3),pow((1-float(sim_3))/(1+ float(sim_3)),1-float(visual_context_prob)))
#return {"LM": float(LM)/1, "sim": float(sim)/1, "score": float(score)/1 }
return {"Greedy": float(score_1)/1, "Best-Beam-5": float(score_2)/1, "Visual_re-Ranker": float(score_3)/1 }
#return LM, sim, score
demo = gr.Interface(
fn=Visual_re_ranker,
#description="Demo for Belief Revision based Caption Re-ranker with Visual Semantic Information",
description="Demo for 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")],
# a baby is eating in front of a birthday cake /a baby sitting in front of a giant cake
inputs=[gr.Textbox(value="baby is eating in front of a birthday cake") , gr.Textbox(value="a baby sitting in front of a cake"), gr.Textbox(value="a baby sitting in front of a birthday cake"), gr.Textbox(value="candle wax light"), gr.Textbox(value="0.958")],
#outputs=[gr.Textbox(value="Language Model Score") , gr.Textbox(value="Semantic Similarity Score"), gr.Textbox(value="Belief revision score via visual context")],
outputs="label",
)
demo.launch() |