Spaces:
Sleeping
Sleeping
Upload 3 files
Browse files- app.py +11 -18
- data_prep.py +20 -17
- model_predict.py +64 -9
app.py
CHANGED
|
@@ -2,40 +2,33 @@ import data_prep
|
|
| 2 |
import model_predict
|
| 3 |
import gradio as gr
|
| 4 |
|
| 5 |
-
# Dictionary of model names and corresponding display names
|
| 6 |
model_dict = {
|
| 7 |
-
"
|
| 8 |
-
"
|
| 9 |
-
"
|
|
|
|
| 10 |
}
|
| 11 |
|
| 12 |
def process_url(url, model_key):
|
| 13 |
-
# Get the actual model path from the model_dict
|
| 14 |
model_name = model_dict[model_key]
|
| 15 |
-
|
| 16 |
-
# Process the text from the URL
|
| 17 |
processed_text = data_prep.process_data(url)
|
| 18 |
-
|
| 19 |
-
# Predict the labels and their probabilities
|
| 20 |
-
final_scores = model_predict.predict_text(processed_text, model_name)
|
| 21 |
-
|
| 22 |
-
# Find the label with the highest probability
|
| 23 |
highest_prob_label = max(final_scores, key=final_scores.get)
|
| 24 |
highest_prob = final_scores[highest_prob_label]
|
| 25 |
-
|
| 26 |
-
# Create progress bar style output for all labels
|
| 27 |
progress_bars = {label: score for label, score in final_scores.items()}
|
| 28 |
|
| 29 |
-
return highest_prob_label, highest_prob, progress_bars
|
|
|
|
| 30 |
|
| 31 |
-
# Define the interface for the Gradio app
|
| 32 |
url_input = gr.Textbox(label="URL")
|
| 33 |
model_name_input = gr.Dropdown(label="Model Name", choices=list(model_dict.keys()), value=list(model_dict.keys())[0])
|
| 34 |
outputs = [
|
|
|
|
| 35 |
gr.Textbox(label="Label with Highest Probability"),
|
| 36 |
gr.Textbox(label="Probability"),
|
| 37 |
-
gr.JSON(label="All Labels and Probabilities")
|
|
|
|
| 38 |
]
|
| 39 |
|
| 40 |
demo = gr.Interface(fn=process_url, inputs=[url_input, model_name_input], outputs=outputs)
|
| 41 |
-
demo.launch()
|
|
|
|
| 2 |
import model_predict
|
| 3 |
import gradio as gr
|
| 4 |
|
|
|
|
| 5 |
model_dict = {
|
| 6 |
+
"BERT-Base": "research-dump/bert-base-uncased_deletion_multiclass_complete_Final",
|
| 7 |
+
"BERT-Large": "research-dump/bert-large-uncased_deletion_multiclass_complete_final",
|
| 8 |
+
"RoBERTa-Base": "research-dump/roberta-base_deletion_multiclass_complete_final",
|
| 9 |
+
"RoBERTa-Large": "research-dump/roberta-large_deletion_multiclass_complete_final"
|
| 10 |
}
|
| 11 |
|
| 12 |
def process_url(url, model_key):
|
|
|
|
| 13 |
model_name = model_dict[model_key]
|
|
|
|
|
|
|
| 14 |
processed_text = data_prep.process_data(url)
|
| 15 |
+
final_scores,highlighted_text = model_predict.predict_text(processed_text, model_name)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
highest_prob_label = max(final_scores, key=final_scores.get)
|
| 17 |
highest_prob = final_scores[highest_prob_label]
|
|
|
|
|
|
|
| 18 |
progress_bars = {label: score for label, score in final_scores.items()}
|
| 19 |
|
| 20 |
+
return processed_text, highest_prob_label, highest_prob, progress_bars #,highlighted_text
|
| 21 |
+
|
| 22 |
|
|
|
|
| 23 |
url_input = gr.Textbox(label="URL")
|
| 24 |
model_name_input = gr.Dropdown(label="Model Name", choices=list(model_dict.keys()), value=list(model_dict.keys())[0])
|
| 25 |
outputs = [
|
| 26 |
+
gr.Textbox(label="Processed Text"),
|
| 27 |
gr.Textbox(label="Label with Highest Probability"),
|
| 28 |
gr.Textbox(label="Probability"),
|
| 29 |
+
gr.JSON(label="All Labels and Probabilities"),
|
| 30 |
+
#gr.HTML(label="Processed Text")
|
| 31 |
]
|
| 32 |
|
| 33 |
demo = gr.Interface(fn=process_url, inputs=[url_input, model_name_input], outputs=outputs)
|
| 34 |
+
demo.launch() #share=True)
|
data_prep.py
CHANGED
|
@@ -1,19 +1,18 @@
|
|
| 1 |
import requests
|
| 2 |
import pandas as pd
|
| 3 |
from bs4 import BeautifulSoup
|
| 4 |
-
import pandas as pd
|
| 5 |
-
from datetime import datetime
|
| 6 |
-
|
| 7 |
|
| 8 |
def extract_div_contents_from_url(url):
|
| 9 |
response = requests.get(url)
|
| 10 |
if response.status_code != 200:
|
|
|
|
| 11 |
return pd.DataFrame(columns=['title', 'text_url', 'deletion_discussion', 'label', 'confirmation', 'discussion', 'verdict'])
|
| 12 |
|
| 13 |
soup = BeautifulSoup(response.content, 'html.parser')
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
|
|
|
| 17 |
url_fragment = url.split('#')[-1].replace('_', ' ')
|
| 18 |
|
| 19 |
data = []
|
|
@@ -43,9 +42,10 @@ def extract_div_contents_from_url(url):
|
|
| 43 |
title = title_tag.text
|
| 44 |
text_url = 'https://en.wikipedia.org' + title_tag['href']
|
| 45 |
|
| 46 |
-
if title
|
| 47 |
-
continue
|
| 48 |
-
|
|
|
|
| 49 |
deletion_discussion = div.prettify()
|
| 50 |
|
| 51 |
# Extract label
|
|
@@ -58,11 +58,13 @@ def extract_div_contents_from_url(url):
|
|
| 58 |
|
| 59 |
# Extract confirmation
|
| 60 |
confirmation = ''
|
| 61 |
-
discussion_tag = div.find('dd')
|
| 62 |
if discussion_tag:
|
| 63 |
-
|
| 64 |
-
if
|
| 65 |
-
|
|
|
|
|
|
|
| 66 |
|
| 67 |
# Split deletion_discussion into discussion and verdict
|
| 68 |
parts = deletion_discussion.split('<div class="mw-heading mw-heading3">')
|
|
@@ -75,7 +77,8 @@ def extract_div_contents_from_url(url):
|
|
| 75 |
continue
|
| 76 |
|
| 77 |
df = pd.DataFrame(data, columns=['title', 'text_url', 'deletion_discussion', 'label', 'confirmation', 'verdict', 'discussion'])
|
| 78 |
-
df = df[['title','discussion','verdict','label']]
|
|
|
|
| 79 |
return df
|
| 80 |
|
| 81 |
|
|
@@ -108,6 +111,7 @@ def process_html_to_plaintext(df):
|
|
| 108 |
df = df[['title', 'discussion_cleaned', 'label']]
|
| 109 |
return df
|
| 110 |
|
|
|
|
| 111 |
import pysbd
|
| 112 |
def split_text_into_sentences(text):
|
| 113 |
seg = pysbd.Segmenter(language="en", clean=False)
|
|
@@ -117,8 +121,6 @@ def process_split_text_into_sentences(df):
|
|
| 117 |
df['discussion_cleaned'] = df['discussion_cleaned'].apply(split_text_into_sentences)
|
| 118 |
return df
|
| 119 |
|
| 120 |
-
|
| 121 |
-
|
| 122 |
def process_data(url):
|
| 123 |
df = extract_div_contents_from_url(url)
|
| 124 |
df = process_discussion(df)
|
|
@@ -128,4 +130,5 @@ def process_data(url):
|
|
| 128 |
if not df.empty:
|
| 129 |
return df.at[0,'title']+ ' : '+df.at[0, 'discussion_cleaned']
|
| 130 |
else:
|
| 131 |
-
return 'Empty DataFrame'
|
|
|
|
|
|
| 1 |
import requests
|
| 2 |
import pandas as pd
|
| 3 |
from bs4 import BeautifulSoup
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
def extract_div_contents_from_url(url):
|
| 6 |
response = requests.get(url)
|
| 7 |
if response.status_code != 200:
|
| 8 |
+
print(f"Error: Received status code {response.status_code} for URL: {url}")
|
| 9 |
return pd.DataFrame(columns=['title', 'text_url', 'deletion_discussion', 'label', 'confirmation', 'discussion', 'verdict'])
|
| 10 |
|
| 11 |
soup = BeautifulSoup(response.content, 'html.parser')
|
| 12 |
+
div_classes = ['boilerplate afd vfd xfd-closed', 'boilerplate afd vfd xfd-closed archived mw-archivedtalk']
|
| 13 |
+
divs = []
|
| 14 |
+
for div_class in div_classes:
|
| 15 |
+
divs.extend(soup.find_all('div', class_=div_class))
|
| 16 |
url_fragment = url.split('#')[-1].replace('_', ' ')
|
| 17 |
|
| 18 |
data = []
|
|
|
|
| 42 |
title = title_tag.text
|
| 43 |
text_url = 'https://en.wikipedia.org' + title_tag['href']
|
| 44 |
|
| 45 |
+
if not title:
|
| 46 |
+
continue
|
| 47 |
+
if title.lower() != url_fragment.lower():
|
| 48 |
+
continue
|
| 49 |
deletion_discussion = div.prettify()
|
| 50 |
|
| 51 |
# Extract label
|
|
|
|
| 58 |
|
| 59 |
# Extract confirmation
|
| 60 |
confirmation = ''
|
| 61 |
+
discussion_tag = div.find('dd')
|
| 62 |
if discussion_tag:
|
| 63 |
+
discussion_tag_i = discussion_tag.find('i')
|
| 64 |
+
if discussion_tag_i:
|
| 65 |
+
confirmation_b_tag = discussion_tag_i.find('b')
|
| 66 |
+
if confirmation_b_tag:
|
| 67 |
+
confirmation = confirmation_b_tag.text.strip()
|
| 68 |
|
| 69 |
# Split deletion_discussion into discussion and verdict
|
| 70 |
parts = deletion_discussion.split('<div class="mw-heading mw-heading3">')
|
|
|
|
| 77 |
continue
|
| 78 |
|
| 79 |
df = pd.DataFrame(data, columns=['title', 'text_url', 'deletion_discussion', 'label', 'confirmation', 'verdict', 'discussion'])
|
| 80 |
+
df = df[['title', 'discussion', 'verdict', 'label']]
|
| 81 |
+
print(f"DataFrame created with {len(df)} rows")
|
| 82 |
return df
|
| 83 |
|
| 84 |
|
|
|
|
| 111 |
df = df[['title', 'discussion_cleaned', 'label']]
|
| 112 |
return df
|
| 113 |
|
| 114 |
+
|
| 115 |
import pysbd
|
| 116 |
def split_text_into_sentences(text):
|
| 117 |
seg = pysbd.Segmenter(language="en", clean=False)
|
|
|
|
| 121 |
df['discussion_cleaned'] = df['discussion_cleaned'].apply(split_text_into_sentences)
|
| 122 |
return df
|
| 123 |
|
|
|
|
|
|
|
| 124 |
def process_data(url):
|
| 125 |
df = extract_div_contents_from_url(url)
|
| 126 |
df = process_discussion(df)
|
|
|
|
| 130 |
if not df.empty:
|
| 131 |
return df.at[0,'title']+ ' : '+df.at[0, 'discussion_cleaned']
|
| 132 |
else:
|
| 133 |
+
return 'Empty DataFrame'
|
| 134 |
+
|
model_predict.py
CHANGED
|
@@ -1,5 +1,39 @@
|
|
| 1 |
#using pipeline to predict the input text
|
| 2 |
-
from transformers import pipeline
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import torch
|
| 4 |
|
| 5 |
label_mapping = {
|
|
@@ -14,15 +48,36 @@ label_mapping = {
|
|
| 14 |
}
|
| 15 |
|
| 16 |
def predict_text(text, model_name):
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
-
for
|
|
|
|
| 22 |
for key, value in label_mapping.items():
|
| 23 |
-
if
|
| 24 |
-
final_scores[key] =
|
| 25 |
break
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
#using pipeline to predict the input text
|
| 2 |
+
# from transformers import pipeline, AutoTokenizer
|
| 3 |
+
# import torch
|
| 4 |
+
|
| 5 |
+
# label_mapping = {
|
| 6 |
+
# 'delete': [0, 'LABEL_0'],
|
| 7 |
+
# 'keep': [1, 'LABEL_1'],
|
| 8 |
+
# 'merge': [2, 'LABEL_2'],
|
| 9 |
+
# 'no consensus': [3, 'LABEL_3'],
|
| 10 |
+
# 'speedy keep': [4, 'LABEL_4'],
|
| 11 |
+
# 'speedy delete': [5, 'LABEL_5'],
|
| 12 |
+
# 'redirect': [6, 'LABEL_6'],
|
| 13 |
+
# 'withdrawn': [7, 'LABEL_7']
|
| 14 |
+
# }
|
| 15 |
+
|
| 16 |
+
# def predict_text(text, model_name):
|
| 17 |
+
# tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 18 |
+
# model = pipeline("text-classification", model=model_name, return_all_scores=True)
|
| 19 |
+
|
| 20 |
+
# # Tokenize and truncate the text
|
| 21 |
+
# tokens = tokenizer(text, truncation=True, max_length=512)
|
| 22 |
+
# truncated_text = tokenizer.decode(tokens['input_ids'], skip_special_tokens=True)
|
| 23 |
+
|
| 24 |
+
# results = model(truncated_text)
|
| 25 |
+
# final_scores = {key: 0.0 for key in label_mapping}
|
| 26 |
+
|
| 27 |
+
# for result in results[0]:
|
| 28 |
+
# for key, value in label_mapping.items():
|
| 29 |
+
# if result['label'] == value[1]:
|
| 30 |
+
# final_scores[key] = result['score']
|
| 31 |
+
# break
|
| 32 |
+
|
| 33 |
+
# return final_scores
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
|
| 37 |
import torch
|
| 38 |
|
| 39 |
label_mapping = {
|
|
|
|
| 48 |
}
|
| 49 |
|
| 50 |
def predict_text(text, model_name):
|
| 51 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 52 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_name, output_attentions=True)
|
| 53 |
+
|
| 54 |
+
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
|
| 55 |
+
outputs = model(**inputs)
|
| 56 |
+
predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
|
| 57 |
|
| 58 |
+
final_scores = {key: 0.0 for key in label_mapping}
|
| 59 |
+
for i, score in enumerate(predictions[0]):
|
| 60 |
for key, value in label_mapping.items():
|
| 61 |
+
if i == value[0]:
|
| 62 |
+
final_scores[key] = score.item()
|
| 63 |
break
|
| 64 |
|
| 65 |
+
# Calculate average attention
|
| 66 |
+
attentions = outputs.attentions
|
| 67 |
+
avg_attentions = torch.mean(torch.stack(attentions), dim=1) # Average over all layers
|
| 68 |
+
avg_attentions = avg_attentions.mean(dim=1)[0] # Average over heads
|
| 69 |
+
token_importance = avg_attentions.mean(dim=0)
|
| 70 |
+
|
| 71 |
+
# Decode tokens and highlight important ones
|
| 72 |
+
tokens = tokenizer.convert_ids_to_tokens(inputs['input_ids'][0])
|
| 73 |
+
highlighted_text = []
|
| 74 |
+
for token, importance in zip(tokens, token_importance):
|
| 75 |
+
if importance > token_importance.mean():
|
| 76 |
+
highlighted_text.append(f"<b>{token}</b>") #
|
| 77 |
+
else:
|
| 78 |
+
highlighted_text.append(token)
|
| 79 |
+
|
| 80 |
+
highlighted_text = " ".join(highlighted_text)
|
| 81 |
+
highlighted_text = highlighted_text.replace("##", "")
|
| 82 |
+
|
| 83 |
+
return final_scores, highlighted_text
|