blazingbunny commited on
Commit
9c39f78
·
1 Parent(s): 8521e74

Upload 3 files

Browse files
Files changed (3) hide show
  1. bert_semantic_interlinker.py +328 -0
  2. readme.md +17 -0
  3. requirements.txt +6 -0
bert_semantic_interlinker.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+
3
+ # region format
4
+ st.set_page_config(page_title="BERT Semantic Interlinking App", page_icon="🔗",
5
+ layout="wide") # needs to be the first thing after the streamlit import
6
+
7
+ from io import BytesIO
8
+ from streamlit_echarts import st_echarts
9
+ from urllib.parse import urlparse
10
+ import chardet
11
+ import pandas as pd
12
+ from sentence_transformers import SentenceTransformer, util
13
+
14
+ finish = False
15
+
16
+
17
+ st.write(
18
+ "Made in [![this is an image link](https://i.imgur.com/iIOA6kU.png)](https://www.streamlit.io/) by [@LeeFootSEO](https://twitter.com/LeeFootSEO) / [![this is an image link](https://i.imgur.com/bjNRJra.png)](https://www.buymeacoffee.com/leefootseo) [Support My Work! Buy me a coffee!](https://www.buymeacoffee.com/leefootseo)")
19
+
20
+ st.title("BERT Semantic Interlinking Tool")
21
+ st.subheader("Upload a crawl file to find semantically relevant pages to interlink. (Unlimited Version)")
22
+ model_radio_button = st.sidebar.radio(
23
+ "Transformer model",
24
+ [
25
+ "multi-qa-mpnet-base-dot-v1",
26
+ "paraphrase-multilingual-MiniLM-L12-v2",
27
+ "paraphrase-MiniLM-L3-v2",
28
+ ],
29
+ help="""the model to use for the clustering.
30
+
31
+ - multi-qa-mpnet-base-dot-v1 - Best Semantic Clustering (🐌)
32
+ - paraphrase-multilingual-MiniLM-L12-v2 - Best Multi-Lingual Clustering (💬)
33
+ - paraphrase-MiniLM-L3-v2 - Best Performance (💨)"""
34
+ )
35
+
36
+ @st.cache(allow_output_mutation=True)
37
+ def get_model():
38
+ model = SentenceTransformer(model_radio_button)
39
+ return model
40
+
41
+ model = get_model()
42
+
43
+ accuracy_slide = st.sidebar.slider("Set Cluster Accuracy: 0-100", value=75)
44
+ min_cluster_size = st.sidebar.slider("Set Minimum Cluster Size: 0-100", value=2)
45
+ source_filter = st.sidebar.text_input('Filter Source URL Type')
46
+ destination_filter = st.sidebar.text_input('Filter Destination URL Type')
47
+ min_similarity = accuracy_slide / 100
48
+
49
+ uploaded_file = st.file_uploader(
50
+ "Upload your crawl file",
51
+ help="""Upload a Screaming Frog internal_html.csv file""")
52
+
53
+ if uploaded_file is not None:
54
+
55
+ try:
56
+
57
+ result = chardet.detect(uploaded_file.getvalue())
58
+ encoding_value = result["encoding"]
59
+
60
+ if encoding_value == "UTF-16":
61
+ white_space = True
62
+ else:
63
+ white_space = False
64
+
65
+ df = pd.read_csv(
66
+ uploaded_file,
67
+ encoding=encoding_value,
68
+ delim_whitespace=white_space,
69
+ error_bad_lines=False,
70
+ )
71
+
72
+ # rename multi language columns
73
+ df.rename(columns={"Adresse": "Address", "Dirección": "Address", "Indirizzo": "Address"}, inplace=True)
74
+ number_of_rows = len(df)
75
+
76
+ if number_of_rows == 0:
77
+ st.caption("Your sheet seems empty!")
78
+
79
+ with st.expander("↕️ View raw data", expanded=False):
80
+ st.write(df)
81
+
82
+ except UnicodeDecodeError:
83
+ st.warning(
84
+ """
85
+ 🚨 The file doesn't seem to load. Check the filetype, file format and Schema
86
+
87
+ """
88
+ )
89
+
90
+ else:
91
+ st.stop()
92
+
93
+ with st.form(key='columns_in_form_2'):
94
+ st.subheader("Please Select the Column to Match (Recommend H1 / Title or Extracted Content)")
95
+ kw_col = st.selectbox('Select the keyword column:', df.columns)
96
+ submitted = st.form_submit_button('Submit')
97
+ if submitted:
98
+ df[kw_col] = df[kw_col].str.encode('ascii', 'ignore').str.decode('ascii')
99
+ df.drop_duplicates(subset=kw_col, inplace=True)
100
+ st.info("Finding Interlinking Opportunities, This May Take a While! Please Wait!")
101
+
102
+ # store the data
103
+ cluster_name_list = []
104
+ corpus_sentences_list = []
105
+ df_all = []
106
+
107
+ corpus_set = set(df[kw_col])
108
+ corpus_set_all = corpus_set
109
+
110
+ cluster = True
111
+
112
+ while cluster:
113
+
114
+ corpus_sentences = list(corpus_set)
115
+ check_len = len(corpus_sentences)
116
+ corpus_embeddings = model.encode(corpus_sentences, batch_size=256, show_progress_bar=True,
117
+ convert_to_tensor=True)
118
+ clusters = util.community_detection(corpus_embeddings, min_community_size=2, threshold=min_similarity)
119
+
120
+ for keyword, cluster in enumerate(clusters):
121
+ for sentence_id in cluster[0:]:
122
+ corpus_sentences_list.append(corpus_sentences[sentence_id])
123
+ cluster_name_list.append("Cluster {}, #{} Elements ".format(keyword + 1, len(cluster)))
124
+
125
+ df_new = pd.DataFrame(None)
126
+ df_new['source_h1'] = cluster_name_list
127
+ df_new[kw_col] = corpus_sentences_list
128
+
129
+ df_all.append(df_new)
130
+ have = set(df_new[kw_col])
131
+
132
+ corpus_set = corpus_set_all - have
133
+ remaining = len(corpus_set)
134
+
135
+ if check_len == remaining:
136
+ break
137
+
138
+ df_new = pd.concat(df_all)
139
+ df = df.merge(df_new.drop_duplicates(kw_col), how='left', on=kw_col)
140
+
141
+ # ------------------------------ rename the clusters to the shortest keyword -----------------------------------
142
+
143
+ df['length'] = df[kw_col].astype(str).map(len)
144
+ df = df.sort_values(by="length", ascending=True)
145
+ df['source_h1'] = df.groupby('source_h1')[kw_col].transform('first')
146
+ df.sort_values(['source_h1', kw_col], ascending=[True, True], inplace=True)
147
+ df['source_h1'] = df['source_h1'].fillna("zzz_no_cluster")
148
+ del df['length']
149
+
150
+ col = df.pop(kw_col)
151
+ df.insert(0, col.name, col)
152
+ col = df.pop('source_h1')
153
+ df.insert(0, col.name, col)
154
+ df2 = df[["Address", kw_col]].copy()
155
+ df2.rename(columns={"Address": "source_url", kw_col: "source_h1"}, inplace=True)
156
+
157
+ df2 = df2.loc[:, ~df2.columns.duplicated()].copy()
158
+ if 'source_url' not in df2.columns:
159
+ df2['source_url'] = df2['source_h1']
160
+
161
+ df = df.merge(df2.drop_duplicates('source_h1'), how='left', on="source_h1") # merge on first instance only
162
+ df = df[["source_url", "source_h1", "Address", kw_col]]
163
+ try:
164
+ df.drop_duplicates(subset=["Address", "source_url"], keep="first", inplace=True)
165
+ except AttributeError:
166
+ st.warning("No Results Found! Try Matching on a Different Column! (Recommend H1 or Extracted Content)")
167
+ st.stop()
168
+
169
+ try:
170
+ df = df[df["Address"].str.contains(destination_filter, na=False)]
171
+ except AttributeError:
172
+ st.warning("No Results Found! Try Matching on a Different Column! (Recommend H1 / Title or Extracted Content)")
173
+ st.stop()
174
+
175
+ df = df[df["source_url"].str.contains(source_filter, na=False)]
176
+
177
+ df = df[~df["Address"].str.contains("zzz_no_cluster", na=False)]
178
+ df.rename(columns={"Address": "destination_url", kw_col: "destination_url_h1"}, inplace=True)
179
+ df['source_h1'] = df['source_h1'].str.lower()
180
+ df['destination_url_h1'] = df['destination_url_h1'].str.lower()
181
+ df['check'] = df['source_url'] == df['destination_url']
182
+ df = df[~df["check"].isin([True])]
183
+ del df['check']
184
+ finish = True
185
+
186
+ # make excel output and visualise results ------------------------------------------------------------------------------
187
+ if finish == True:
188
+
189
+ df_list = []
190
+ sheet_list = []
191
+
192
+ # clean special characters
193
+ spec_chars = ["!", '"', "#", "%", "&", "'", "(", ")",
194
+ "*", "+", ",", ".", "/", ":", ";", "<",
195
+ "=", ">", "?", "@", "[", "\\", "]", "^",
196
+ "`", "{", "|", "}", "~", "–"]
197
+
198
+ df['source_h1'] = df['source_h1'].str.encode('ascii', 'ignore').str.decode('ascii')
199
+
200
+ # make the dataframe for visualisation
201
+ df_autocomplete_full = df.copy()
202
+
203
+ # extracts the domain from the address column if present
204
+ try:
205
+ extracted_domain = df['source_url'].iloc[0]
206
+ url = extracted_domain
207
+ o = urlparse(url)
208
+ domain = o.netloc
209
+ df_autocomplete_full['seed'] = domain
210
+ except IndexError:
211
+ df_autocomplete_full['seed'] = "crawl"
212
+ filt = list(set(df['source_h1']))
213
+
214
+ df_list.append(df)
215
+ sheet_list.append("All Results")
216
+
217
+ for i in filt:
218
+
219
+ worksheet_name = i.replace(" ", "_")
220
+ for char in spec_chars:
221
+ worksheet_name = worksheet_name.replace(char, "")
222
+ worksheet_name = worksheet_name.replace(" ", "_")
223
+
224
+ worksheet_name = worksheet_name[0:31]
225
+ sheet_list.append(worksheet_name)
226
+ try:
227
+ df_list.append(df[df['source_h1'].str.contains(i)].copy())
228
+ except Exception:
229
+ pass
230
+
231
+ # save to Excel sheet
232
+ def dfs_tabs(df_list, sheet_list, file_name): # function to save all dataframes to one single excel doc
233
+
234
+ output = BytesIO()
235
+ writer = pd.ExcelWriter(output, engine='xlsxwriter')
236
+ for dataframe, sheet in zip(df_list, sheet_list):
237
+ dataframe.to_excel(writer, sheet_name=sheet, startrow=0, startcol=0, index=False)
238
+
239
+ writer.save()
240
+ processed_data = output.getvalue()
241
+ return processed_data
242
+
243
+ df_xlsx = dfs_tabs(df_list, sheet_list, 'serp-cluster-output.xlsx')
244
+ st.download_button(label='📥 Download BERT Interlinking Opportunities', data=df_xlsx, file_name='bert_interlinking_opportunities.xlsx')
245
+
246
+ # visualise result -----------------------------------------------------------------------------------------------------
247
+ def visualize_autocomplete(df_autocomplete_full):
248
+ try:
249
+ query = df_autocomplete_full['seed'].iloc[0]
250
+ except IndexError:
251
+ query = ""
252
+
253
+ for query in df_autocomplete_full['seed'].unique():
254
+ df_autocomplete_full = df_autocomplete_full[df_autocomplete_full['seed'] == query]
255
+ children_list = []
256
+ children_list_level_1 = []
257
+
258
+ for int_word in df_autocomplete_full['source_h1']:
259
+ q_lv1_line = {"name": int_word}
260
+ if not q_lv1_line in children_list_level_1:
261
+ children_list_level_1.append(q_lv1_line)
262
+
263
+ children_list_level_2 = []
264
+
265
+ for query_2 in df_autocomplete_full[df_autocomplete_full['source_h1'] == int_word][
266
+ 'destination_url_h1']:
267
+ q_lv2_line = {"name": query_2}
268
+ children_list_level_2.append(q_lv2_line)
269
+
270
+ level2_tree = {'name': int_word, 'children': children_list_level_2}
271
+
272
+ if not level2_tree in children_list:
273
+ children_list.append(level2_tree)
274
+
275
+ tree = {'name': query, 'children': children_list}
276
+
277
+ opts = {
278
+ "backgroundColor": "#F0F2F6",
279
+
280
+
281
+ "title": {
282
+ # "subtext": "https://tools.alekseo.com/askey.html",
283
+ # "text": f"Questions Map for: «{query}»",
284
+ "x": 'center',
285
+ "y": 'top',
286
+ "top": "5%",
287
+
288
+ "textStyle": {
289
+ "fontSize": 22,
290
+
291
+ },
292
+ "subtextStyle": {
293
+ "fontSize": 15,
294
+ "color": '#2ec4b6',
295
+
296
+ },
297
+ },
298
+
299
+ "series": [
300
+ {
301
+ "type": "tree",
302
+ "data": [tree],
303
+ "layout": "radial",
304
+ "top": "10%",
305
+ "left": "25%",
306
+ "bottom": "5%",
307
+ "right": "25%",
308
+ "symbolSize": 20,
309
+ "itemStyle": {
310
+ "color": '#2ec4b6',
311
+ },
312
+ "label": {
313
+ "fontSize": 14,
314
+
315
+ },
316
+
317
+ "expandAndCollapse": True,
318
+ "animationDuration": 550,
319
+ "animationDurationUpdate": 750,
320
+ }
321
+ ],
322
+ }
323
+ st.caption("Right mouse click to save as image.")
324
+ st_echarts(opts, key=query, height=1700)
325
+
326
+ st.header("Visualising First 100 Results")
327
+ df_autocomplete_full = df_autocomplete_full[:100]
328
+ visualize_autocomplete(df_autocomplete_full)
readme.md ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # BERT Semantic Page Interlinker
2
+
3
+ ## Features
4
+ Automatically finds semantically relevant pages to link to. Just feed it a crawl file and the script will do the rest!
5
+
6
+ Great for finding sementally related categories for ecommerce sites.
7
+
8
+ For example, it can match semantically related categories like Dustbins and Cleaning Equipment even though syntically those words are very different.
9
+
10
+ ## Support
11
+
12
+ If you find this project helpful or would like to support its development, you can show your appreciation by:
13
+
14
+ - [Buying me a coffee on Buy Me a Coffee](https://www.buymeacoffee.com/leefootseo)
15
+ - [Becoming a patron on Patreon](https://www.patreon.com/leefootseo)
16
+
17
+ Your support helps keep this project alive and enables me to continue working on it. Thank you!
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ git+https://github.com/searchsolved/sentence-transformers-master
2
+ pandas==1.3.5
3
+ chardet
4
+ stqdm
5
+ detect_delimiter
6
+ #anytree