Update app.py
Browse files
app.py
CHANGED
@@ -1,44 +1,56 @@
|
|
1 |
import gradio as gr
|
2 |
-
import torch
|
3 |
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
|
|
4 |
|
5 |
# Load model and tokenizer
|
6 |
model_name = "cross-encoder/ms-marco-MiniLM-L-12-v2"
|
7 |
-
model = AutoModelForSequenceClassification.from_pretrained(model_name, output_attentions=True)
|
8 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
9 |
-
|
10 |
-
# Set model to evaluation mode
|
11 |
model.eval()
|
12 |
|
13 |
-
# Function to compute relevance and
|
14 |
-
def
|
15 |
-
|
16 |
-
|
17 |
-
|
|
|
|
|
18 |
|
19 |
-
# Get model outputs with attentions
|
20 |
with torch.no_grad():
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
40 |
highlighted_text = ""
|
41 |
-
for idx, token in enumerate(
|
42 |
if idx in relevant_indices:
|
43 |
highlighted_text += f"<b>{token}</b> "
|
44 |
else:
|
@@ -46,25 +58,26 @@ def process_text(query, document, weight):
|
|
46 |
|
47 |
highlighted_text = tokenizer.convert_tokens_to_string(highlighted_text.split())
|
48 |
|
49 |
-
|
50 |
-
print(f"Relevance Score: {relevance_score}")
|
51 |
-
print(f"Dynamic Threshold: {dynamic_threshold}")
|
52 |
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
iface = gr.Interface(
|
57 |
-
fn=process_text,
|
58 |
inputs=[
|
59 |
-
gr.Textbox(label="Query"),
|
60 |
-
gr.Textbox(label="Document Paragraph"),
|
61 |
-
gr.Slider(minimum=0.
|
62 |
],
|
63 |
outputs=[
|
64 |
gr.Textbox(label="Relevance Score"),
|
65 |
gr.Textbox(label="Dynamic Threshold"),
|
66 |
gr.HTML(label="Highlighted Document Paragraph")
|
67 |
-
]
|
|
|
|
|
|
|
|
|
68 |
)
|
69 |
|
70 |
-
|
|
|
|
1 |
import gradio as gr
|
|
|
2 |
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
3 |
+
import torch
|
4 |
|
5 |
# Load model and tokenizer
|
6 |
model_name = "cross-encoder/ms-marco-MiniLM-L-12-v2"
|
|
|
7 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
8 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_name)
|
|
|
9 |
model.eval()
|
10 |
|
11 |
+
# Function to compute relevance score and dynamically adjust threshold
|
12 |
+
def get_relevance_score_and_excerpt(query, paragraph, threshold_weight):
|
13 |
+
if not query.strip() or not paragraph.strip():
|
14 |
+
return "Please provide both a query and a document paragraph.", "", ""
|
15 |
+
|
16 |
+
# Tokenize the input
|
17 |
+
inputs = tokenizer(query, paragraph, return_tensors="pt", truncation=True, padding=True)
|
18 |
|
|
|
19 |
with torch.no_grad():
|
20 |
+
output = model(**inputs, output_attentions=True)
|
21 |
+
|
22 |
+
# Extract logits and calculate base relevance score
|
23 |
+
logit = output.logits.squeeze().item()
|
24 |
+
base_relevance_score = torch.sigmoid(torch.tensor(logit)).item()
|
25 |
+
|
26 |
+
# Dynamically adjust the attention threshold based on user weight
|
27 |
+
dynamic_threshold = max(0.02, threshold_weight)
|
28 |
+
|
29 |
+
# Extract attention scores (last layer)
|
30 |
+
attention = output.attentions[-1]
|
31 |
+
attention_scores = attention.mean(dim=1).mean(dim=0)
|
32 |
+
|
33 |
+
query_tokens = tokenizer.tokenize(query)
|
34 |
+
paragraph_tokens = tokenizer.tokenize(paragraph)
|
35 |
+
|
36 |
+
query_len = len(query_tokens) + 2 # +2 for special tokens [CLS] and first [SEP]
|
37 |
+
para_start_idx = query_len
|
38 |
+
para_end_idx = len(inputs["input_ids"][0]) - 1
|
39 |
+
|
40 |
+
if para_end_idx <= para_start_idx:
|
41 |
+
return round(base_relevance_score, 4), round(dynamic_threshold, 4), "No relevant tokens extracted."
|
42 |
+
|
43 |
+
para_attention_scores = attention_scores[para_start_idx:para_end_idx, para_start_idx:para_end_idx].mean(dim=0)
|
44 |
+
|
45 |
+
if para_attention_scores.numel() == 0:
|
46 |
+
return round(base_relevance_score, 4), round(dynamic_threshold, 4), "No relevant tokens extracted."
|
47 |
+
|
48 |
+
# Get indices of relevant tokens above dynamic threshold
|
49 |
+
relevant_indices = (para_attention_scores > dynamic_threshold).nonzero(as_tuple=True)[0].tolist()
|
50 |
+
|
51 |
+
# Reconstruct paragraph with bolded relevant tokens using HTML tags
|
52 |
highlighted_text = ""
|
53 |
+
for idx, token in enumerate(paragraph_tokens):
|
54 |
if idx in relevant_indices:
|
55 |
highlighted_text += f"<b>{token}</b> "
|
56 |
else:
|
|
|
58 |
|
59 |
highlighted_text = tokenizer.convert_tokens_to_string(highlighted_text.split())
|
60 |
|
61 |
+
return round(base_relevance_score, 4), round(dynamic_threshold, 4), highlighted_text
|
|
|
|
|
62 |
|
63 |
+
# Define Gradio interface with a slider for threshold adjustment
|
64 |
+
interface = gr.Interface(
|
65 |
+
fn=get_relevance_score_and_excerpt,
|
|
|
|
|
66 |
inputs=[
|
67 |
+
gr.Textbox(label="Query", placeholder="Enter your search query..."),
|
68 |
+
gr.Textbox(label="Document Paragraph", placeholder="Enter a paragraph to match..."),
|
69 |
+
gr.Slider(minimum=0.02, maximum=0.5, value=0.1, step=0.01, label="Attention Threshold")
|
70 |
],
|
71 |
outputs=[
|
72 |
gr.Textbox(label="Relevance Score"),
|
73 |
gr.Textbox(label="Dynamic Threshold"),
|
74 |
gr.HTML(label="Highlighted Document Paragraph")
|
75 |
+
],
|
76 |
+
title="Cross-Encoder Attention Highlighting",
|
77 |
+
description="Adjust the attention threshold to control token highlighting sensitivity.",
|
78 |
+
allow_flagging="never",
|
79 |
+
live=True
|
80 |
)
|
81 |
|
82 |
+
if __name__ == "__main__":
|
83 |
+
interface.launch()
|