Spaces:
Runtime error
Runtime error
Upload 2 files
Browse files- app.py +168 -0
- requirements.txt +5 -0
app.py
ADDED
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import torch
|
3 |
+
import torch.nn.functional as F
|
4 |
+
from torch.nn.functional import softmax
|
5 |
+
from transformers import AlbertTokenizerFast, AutoModelForTokenClassification
|
6 |
+
import pandas as pd
|
7 |
+
import trafilatura
|
8 |
+
|
9 |
+
# Set Streamlit configuration
|
10 |
+
st.set_page_config(layout="wide", page_title="LinkBERT")
|
11 |
+
|
12 |
+
# Load model and tokenizer
|
13 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
14 |
+
tokenizer = AlbertTokenizerFast.from_pretrained("dejanseo/LinkBERT-mini")
|
15 |
+
model = AutoModelForTokenClassification.from_pretrained("dejanseo/LinkBERT-mini").to(device)
|
16 |
+
model.eval()
|
17 |
+
|
18 |
+
# Functions
|
19 |
+
|
20 |
+
def tokenize_with_indices(text: str):
|
21 |
+
encoded = tokenizer.encode_plus(text, return_offsets_mapping=True, add_special_tokens=True)
|
22 |
+
return encoded['input_ids'], encoded['offset_mapping']
|
23 |
+
|
24 |
+
def fetch_and_extract_content(url: str):
|
25 |
+
downloaded = trafilatura.fetch_url(url)
|
26 |
+
if downloaded:
|
27 |
+
content = trafilatura.extract(downloaded, include_comments=False, include_tables=False)
|
28 |
+
return content
|
29 |
+
return None
|
30 |
+
|
31 |
+
def process_text(inputs: str, confidence_threshold: float):
|
32 |
+
max_chunk_length = 512 - 2
|
33 |
+
words = inputs.split()
|
34 |
+
chunk_texts = []
|
35 |
+
current_chunk = []
|
36 |
+
current_length = 0
|
37 |
+
for word in words:
|
38 |
+
if len(tokenizer.tokenize(word)) + current_length > max_chunk_length:
|
39 |
+
chunk_texts.append(" ".join(current_chunk))
|
40 |
+
current_chunk = [word]
|
41 |
+
current_length = len(tokenizer.tokenize(word))
|
42 |
+
else:
|
43 |
+
current_chunk.append(word)
|
44 |
+
current_length += len(tokenizer.tokenize(word))
|
45 |
+
chunk_texts.append(" ".join(current_chunk))
|
46 |
+
|
47 |
+
df_data = {
|
48 |
+
'Word': [],
|
49 |
+
'Prediction': [],
|
50 |
+
'Confidence': [],
|
51 |
+
'Start': [],
|
52 |
+
'End': []
|
53 |
+
}
|
54 |
+
reconstructed_text = ""
|
55 |
+
original_position_offset = 0
|
56 |
+
|
57 |
+
for chunk in chunk_texts:
|
58 |
+
input_ids, token_offsets = tokenize_with_indices(chunk)
|
59 |
+
predictions = []
|
60 |
+
|
61 |
+
input_ids_tensor = torch.tensor(input_ids).unsqueeze(0).to(device)
|
62 |
+
with torch.no_grad():
|
63 |
+
outputs = model(input_ids_tensor)
|
64 |
+
logits = outputs.logits
|
65 |
+
predictions = torch.argmax(logits, dim=-1).squeeze().tolist()
|
66 |
+
softmax_scores = F.softmax(logits, dim=-1).squeeze().tolist()
|
67 |
+
|
68 |
+
word_info = {}
|
69 |
+
|
70 |
+
for idx, (start, end) in enumerate(token_offsets):
|
71 |
+
if idx == 0 or idx == len(token_offsets) - 1:
|
72 |
+
continue
|
73 |
+
|
74 |
+
word_start = start
|
75 |
+
while word_start > 0 and chunk[word_start-1] != ' ':
|
76 |
+
word_start -= 1
|
77 |
+
|
78 |
+
if word_start not in word_info:
|
79 |
+
word_info[word_start] = {'prediction': 0, 'confidence': 0.0, 'subtokens': []}
|
80 |
+
|
81 |
+
confidence_percentage = softmax_scores[idx][predictions[idx]] * 100
|
82 |
+
|
83 |
+
if predictions[idx] == 1 and confidence_percentage >= confidence_threshold:
|
84 |
+
word_info[word_start]['prediction'] = 1
|
85 |
+
|
86 |
+
word_info[word_start]['confidence'] = max(word_info[word_start]['confidence'], confidence_percentage)
|
87 |
+
word_info[word_start]['subtokens'].append((start, end, chunk[start:end]))
|
88 |
+
|
89 |
+
last_end = 0
|
90 |
+
for word_start in sorted(word_info.keys()):
|
91 |
+
word_data = word_info[word_start]
|
92 |
+
for subtoken_start, subtoken_end, subtoken_text in word_data['subtokens']:
|
93 |
+
escaped_subtoken_text = subtoken_text.replace('$', '\\$') # Perform replacement outside f-string
|
94 |
+
if last_end < subtoken_start:
|
95 |
+
reconstructed_text += chunk[last_end:subtoken_start]
|
96 |
+
if word_data['prediction'] == 1:
|
97 |
+
reconstructed_text += f"<span style='background-color: rgba(0, 255, 0); display: inline;'>{escaped_subtoken_text}</span>"
|
98 |
+
else:
|
99 |
+
reconstructed_text += escaped_subtoken_text
|
100 |
+
last_end = subtoken_end
|
101 |
+
|
102 |
+
df_data['Word'].append(escaped_subtoken_text)
|
103 |
+
df_data['Prediction'].append(word_data['prediction'])
|
104 |
+
df_data['Confidence'].append(word_info[word_start]['confidence'])
|
105 |
+
df_data['Start'].append(subtoken_start + original_position_offset)
|
106 |
+
df_data['End'].append(subtoken_end + original_position_offset)
|
107 |
+
|
108 |
+
original_position_offset += len(chunk) + 1
|
109 |
+
|
110 |
+
reconstructed_text += chunk[last_end:].replace('$', '\\$')
|
111 |
+
|
112 |
+
df_tokens = pd.DataFrame(df_data)
|
113 |
+
return reconstructed_text, df_tokens
|
114 |
+
|
115 |
+
# Streamlit Interface
|
116 |
+
|
117 |
+
st.title('LinkBERT')
|
118 |
+
st.markdown("""
|
119 |
+
LinkBERT is a model developed by [Dejan Marketing](https://dejanmarketing.com/) designed to predict natural link placement within web content. You can either enter plain text or the URL for automated plain text extraction. To reduce the number of link predictions increase the threshold slider value.
|
120 |
+
""")
|
121 |
+
|
122 |
+
confidence_threshold = st.slider('Confidence Threshold', 50, 100, 50)
|
123 |
+
|
124 |
+
tab1, tab2 = st.tabs(["Text Input", "URL Input"])
|
125 |
+
|
126 |
+
with tab1:
|
127 |
+
user_input = st.text_area("Enter text to process:")
|
128 |
+
if st.button('Process Text'):
|
129 |
+
highlighted_text, df_tokens = process_text(user_input, confidence_threshold)
|
130 |
+
st.markdown(highlighted_text, unsafe_allow_html=True)
|
131 |
+
st.dataframe(df_tokens)
|
132 |
+
|
133 |
+
with tab2:
|
134 |
+
url_input = st.text_input("Enter URL to process:")
|
135 |
+
if st.button('Fetch and Process'):
|
136 |
+
content = fetch_and_extract_content(url_input)
|
137 |
+
if content:
|
138 |
+
highlighted_text, df_tokens = process_text(content, confidence_threshold)
|
139 |
+
st.markdown(highlighted_text, unsafe_allow_html=True)
|
140 |
+
st.dataframe(df_tokens)
|
141 |
+
else:
|
142 |
+
st.error("Could not fetch content from the URL. Please check the URL and try again.")
|
143 |
+
|
144 |
+
# Additional information at the end
|
145 |
+
st.divider()
|
146 |
+
st.markdown("""
|
147 |
+
|
148 |
+
## Applications of LinkBERT
|
149 |
+
|
150 |
+
LinkBERT's applications are vast and diverse, tailored to enhance both the efficiency and quality of web content creation and analysis:
|
151 |
+
|
152 |
+
- **Anchor Text Suggestion:** Acts as a mechanism during internal link optimization, suggesting potential anchor texts to web authors.
|
153 |
+
- **Evaluation of Existing Links:** Assesses the naturalness of link placements within existing content, aiding in the refinement of web pages.
|
154 |
+
- **Link Placement Guide:** Offers guidance to link builders by suggesting optimal placement for links within content.
|
155 |
+
- **Anchor Text Idea Generator:** Provides creative anchor text suggestions to enrich content and improve SEO strategies.
|
156 |
+
- **Spam and Inorganic SEO Detection:** Helps identify unnatural link patterns, contributing to the detection of spam and inorganic SEO tactics.
|
157 |
+
|
158 |
+
## Training and Performance
|
159 |
+
|
160 |
+
LinkBERT was fine-tuned on a dataset of organic web content and editorial links.
|
161 |
+
|
162 |
+
[Watch the video](https://www.youtube.com/watch?v=A0ZulyVqjZo)
|
163 |
+
|
164 |
+
# Engage Our Team
|
165 |
+
Interested in using this in an automated pipeline for bulk link prediction?
|
166 |
+
|
167 |
+
Please [book an appointment](https://dejanmarketing.com/conference/) to discuss your needs.
|
168 |
+
""")
|
requirements.txt
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
streamlit
|
2 |
+
torch
|
3 |
+
transformers
|
4 |
+
pandas
|
5 |
+
trafilatura
|