dejanseo commited on
Commit
a835867
·
verified ·
1 Parent(s): b7ad822

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +166 -85
src/streamlit_app.py CHANGED
@@ -1,86 +1,167 @@
1
- """
2
- Drop-in replacement for: from lxml.html.clean import Cleaner
3
- Implements Cleaner.clean_html(html) via bleach.
4
- """
5
-
6
- from __future__ import annotations
7
- from typing import Dict, Iterable, Optional, Set, Union
8
-
9
- import bleach
10
- from bleach.css_sanitizer import CSSSanitizer
11
-
12
- _DEFAULT_TAGS: Set[str] = set(bleach.sanitizer.ALLOWED_TAGS) | {
13
- "p", "div", "span", "br", "hr", "pre", "code",
14
- "img", "figure", "figcaption",
15
- "h1", "h2", "h3", "h4", "h5", "h6",
16
- "table", "thead", "tbody", "tfoot", "tr", "th", "td"
17
- }
18
-
19
- _DEFAULT_ATTRS: Dict[str, Union[Iterable[str], dict]] = {
20
- **bleach.sanitizer.ALLOWED_ATTRIBUTES,
21
- "a": {"href", "title", "name", "target", "rel"},
22
- "img": {"src", "alt", "title", "width", "height"},
23
- "*": {"class", "id", "data-*", "dir", "lang", "title", "aria-*"},
24
- }
25
-
26
- _DEFAULT_PROTOCOLS: Set[str] = set(bleach.sanitizer.ALLOWED_PROTOCOLS) | {
27
- "data" # allow data: for small inline images if you wish
28
- }
29
-
30
-
31
- class Cleaner:
32
- """
33
- Minimal API-compatible shim:
34
- - init(...) accepts common lxml Cleaner flags (ignored/mapped as sensible)
35
- - clean_html(html: str) -> str
36
- """
37
-
38
- def __init__(
39
- self,
40
- allow_tags: Optional[Iterable[str]] = None,
41
- safe_attrs: Optional[Dict[str, Iterable[str]]] = None,
42
- strip: bool = True,
43
- strip_comments: bool = True,
44
- scripts: bool = True, # kept for signature parity (ignored; bleach strips <script>)
45
- javascript: bool = True, # kept for signature parity
46
- style: bool = True, # if True, drop <style> blocks
47
- inline_style: bool = False, # if True, allow style="" with CSS sanitizer
48
- links: bool = True, # kept for parity
49
- allow_protocols: Optional[Iterable[str]] = None,
50
- ):
51
- self.tags = set(allow_tags) if allow_tags else _DEFAULT_TAGS.copy()
52
- # Always forbid script/style elements via tags unless explicitly allowed
53
- if style:
54
- self.tags.discard("style")
55
- self.tags.discard("script")
56
-
57
- self.attrs = dict(_DEFAULT_ATTRS)
58
- if safe_attrs:
59
- # merge/override
60
- for k, v in safe_attrs.items():
61
- self.attrs[k] = set(v)
62
-
63
- self.protocols = set(allow_protocols) if allow_protocols else _DEFAULT_PROTOCOLS.copy()
64
-
65
- self.strip = bool(strip)
66
- self.strip_comments = bool(strip_comments)
67
-
68
- self.css_sanitizer = None
69
- if inline_style:
70
- # allow inline style with safe CSS
71
- self.css_sanitizer = CSSSanitizer(allowed_css_properties=None) # default safe list
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  else:
73
- # disallow style="" attributes
74
- if "*" in self.attrs:
75
- self.attrs["*"] = {a for a in self.attrs["*"] if a != "style"}
76
-
77
- def clean_html(self, html: str) -> str:
78
- return bleach.clean(
79
- html,
80
- tags=list(self.tags),
81
- attributes=self.attrs,
82
- protocols=list(self.protocols),
83
- strip=self.strip,
84
- strip_comments=self.strip_comments,
85
- css_sanitizer=self.css_sanitizer,
86
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 AutoTokenizer, 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 (correct for XLM-RoBERTa Large)
13
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
14
+ tokenizer = AutoTokenizer.from_pretrained("dejanseo/LinkBERT-XL")
15
+ model = AutoModelForTokenClassification.from_pretrained("dejanseo/LinkBERT-XL").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
+
43
+ else:
44
+ current_chunk.append(word)
45
+ current_length += len(tokenizer.tokenize(word))
46
+ chunk_texts.append(" ".join(current_chunk))
47
+
48
+ df_data = {
49
+ 'Word': [],
50
+ 'Prediction': [],
51
+ 'Confidence': [],
52
+ 'Start': [],
53
+ 'End': []
54
+ }
55
+ reconstructed_text = ""
56
+ original_position_offset = 0
57
+
58
+ for chunk in chunk_texts:
59
+ input_ids, token_offsets = tokenize_with_indices(chunk)
60
+ input_ids_tensor = torch.tensor(input_ids).unsqueeze(0).to(device)
61
+ with torch.no_grad():
62
+ outputs = model(input_ids_tensor)
63
+ logits = outputs.logits
64
+ predictions = torch.argmax(logits, dim=-1).squeeze().tolist()
65
+ softmax_scores = F.softmax(logits, dim=-1).squeeze().tolist()
66
+
67
+ word_info = {}
68
+
69
+ for idx, (start, end) in enumerate(token_offsets):
70
+ if idx == 0 or idx == len(token_offsets) - 1:
71
+ continue
72
+
73
+ word_start = start
74
+ while word_start > 0 and chunk[word_start-1] != ' ':
75
+ word_start -= 1
76
+
77
+ if word_start not in word_info:
78
+ word_info[word_start] = {'prediction': 0, 'confidence': 0.0, 'subtokens': []}
79
+
80
+ confidence_percentage = softmax_scores[idx][predictions[idx]] * 100
81
+
82
+ if predictions[idx] == 1 and confidence_percentage >= confidence_threshold:
83
+ word_info[word_start]['prediction'] = 1
84
+
85
+ word_info[word_start]['confidence'] = max(word_info[word_start]['confidence'], confidence_percentage)
86
+ word_info[word_start]['subtokens'].append((start, end, chunk[start:end]))
87
+
88
+ last_end = 0
89
+ for word_start in sorted(word_info.keys()):
90
+ word_data = word_info[word_start]
91
+ for subtoken_start, subtoken_end, subtoken_text in word_data['subtokens']:
92
+ escaped_subtoken_text = subtoken_text.replace('$', '\\$')
93
+ if last_end < subtoken_start:
94
+ reconstructed_text += chunk[last_end:subtoken_start]
95
+ if word_data['prediction'] == 1:
96
+ reconstructed_text += f"<span style='background-color: rgba(0, 255, 0); display: inline;'>{escaped_subtoken_text}</span>"
97
+ else:
98
+ reconstructed_text += escaped_subtoken_text
99
+ last_end = subtoken_end
100
+
101
+ df_data['Word'].append(escaped_subtoken_text)
102
+ df_data['Prediction'].append(word_data['prediction'])
103
+ df_data['Confidence'].append(word_info[word_start]['confidence'])
104
+ df_data['Start'].append(subtoken_start + original_position_offset)
105
+ df_data['End'].append(subtoken_end + original_position_offset)
106
+
107
+ original_position_offset += len(chunk) + 1
108
+
109
+ reconstructed_text += chunk[last_end:].replace('$', '\\$')
110
+
111
+ df_tokens = pd.DataFrame(df_data)
112
+ return reconstructed_text, df_tokens
113
+
114
+ # Streamlit Interface
115
+
116
+ st.title('LinkBERT')
117
+ st.markdown("""
118
+ 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.
119
+ """)
120
+
121
+ confidence_threshold = st.slider('Confidence Threshold', 50, 100, 50)
122
+
123
+ tab1, tab2 = st.tabs(["Text Input", "URL Input"])
124
+
125
+ with tab1:
126
+ user_input = st.text_area("Enter text to process:")
127
+ if st.button('Process Text'):
128
+ highlighted_text, df_tokens = process_text(user_input, confidence_threshold)
129
+ st.markdown(highlighted_text, unsafe_allow_html=True)
130
+ st.dataframe(df_tokens)
131
+
132
+ with tab2:
133
+ url_input = st.text_input("Enter URL to process:")
134
+ if st.button('Fetch and Process'):
135
+ content = fetch_and_extract_content(url_input)
136
+ if content:
137
+ highlighted_text, df_tokens = process_text(content, confidence_threshold)
138
+ st.markdown(highlighted_text, unsafe_allow_html=True)
139
+ st.dataframe(df_tokens)
140
  else:
141
+ st.error("Could not fetch content from the URL. Please check the URL and try again.")
142
+
143
+ # Additional information at the end
144
+ st.divider()
145
+ st.markdown("""
146
+
147
+ ## Applications of LinkBERT
148
+
149
+ LinkBERT's applications are vast and diverse, tailored to enhance both the efficiency and quality of web content creation and analysis:
150
+
151
+ - **Anchor Text Suggestion:** Acts as a mechanism during internal link optimization, suggesting potential anchor texts to web authors.
152
+ - **Evaluation of Existing Links:** Assesses the naturalness of link placements within existing content, aiding in the refinement of web pages.
153
+ - **Link Placement Guide:** Offers guidance to link builders by suggesting optimal placement for links within content.
154
+ - **Anchor Text Idea Generator:** Provides creative anchor text suggestions to enrich content and improve SEO strategies.
155
+ - **Spam and Inorganic SEO Detection:** Helps identify unnatural link patterns, contributing to the detection of spam and inorganic SEO tactics.
156
+
157
+ ## Training and Performance
158
+
159
+ LinkBERT was fine-tuned on a dataset of organic web content and editorial links.
160
+
161
+ [Watch the video](https://www.youtube.com/watch?v=A0ZulyVqjZo)
162
+
163
+ # Engage Our Team
164
+ Interested in using this in an automated pipeline for bulk link prediction?
165
+
166
+ Please [book an appointment](https://dejanmarketing.com/conference/) to discuss your needs.
167
+ """)