wilwork commited on
Commit
a1e51f4
·
verified ·
1 Parent(s): e64db30

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -43
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 highlight relevant tokens
14
- def process_text(query, document, weight):
15
- # Tokenize input
16
- inputs = tokenizer(query, document, return_tensors="pt", truncation=True, padding=True)
17
- input_ids = inputs["input_ids"]
 
 
18
 
19
- # Get model outputs with attentions
20
  with torch.no_grad():
21
- outputs = model(**inputs, output_attentions=True)
22
- relevance_score = torch.sigmoid(outputs.logits).item() # Convert logits to relevance score
23
- attentions = outputs.attentions[-1].squeeze(0).mean(0) # Mean attention across heads
24
-
25
- # Calculate dynamic threshold using sigmoid function
26
- def calculate_threshold(base_relevance, min_threshold=0.0, max_threshold=0.5, k=10):
27
- base_relevance_tensor = torch.tensor(base_relevance)
28
- threshold = min_threshold + (max_threshold - min_threshold) * (
29
- 1 / (1 + torch.exp(-k * (base_relevance_tensor - 0.5)))
30
- )
31
- return threshold.item()
32
-
33
- dynamic_threshold = calculate_threshold(relevance_score) * weight
34
-
35
- # Extract important tokens based on attention scores
36
- relevant_indices = (attentions > dynamic_threshold).nonzero(as_tuple=True)[0].tolist()
37
-
38
- # Highlight tokens in the original order, using HTML bold tags
39
- tokens = tokenizer.convert_ids_to_tokens(input_ids[0])
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  highlighted_text = ""
41
- for idx, token in enumerate(tokens):
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
- # Print values to debug
50
- print(f"Relevance Score: {relevance_score}")
51
- print(f"Dynamic Threshold: {dynamic_threshold}")
52
 
53
- return relevance_score, dynamic_threshold, highlighted_text
54
-
55
- # Create Gradio interface with a slider for threshold adjustment weight
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.0, maximum=2.0, step=0.1, value=1.0, label="Threshold Weight"),
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
- iface.launch()
 
 
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()