cyberandy commited on
Commit
c0cf9ef
·
verified ·
1 Parent(s): c429157

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +332 -0
app.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Created on Tue Feb 20 2023
4
+ @author: cyberandy
5
+ """
6
+
7
+ # ---------------------------------------------------------------------------- #
8
+ # Imports
9
+ # ---------------------------------------------------------------------------- #
10
+ from io import StringIO # for redirect_stdout
11
+ from functools import wraps # for caching
12
+ import contextlib # for redirect_stdout
13
+ import tldextract
14
+ from langchain import PromptTemplate, LLMChain
15
+ from langchain.llms import OpenAIChat
16
+ import requests
17
+ import streamlit as st
18
+ import pandas as pd
19
+ import streamlit.components.v1 as components
20
+ import json
21
+ import os
22
+
23
+
24
+ # ---------------------------------------------------------------------------- #
25
+ # App Config. & Styling
26
+ # ---------------------------------------------------------------------------- #
27
+
28
+
29
+ PAGE_CONFIG = {
30
+ "page_title": "Structured Data Audit - a Free SEO Tool by WordLift",
31
+ "page_icon": "img/fav-ico.png",
32
+ "layout": "centered"
33
+ }
34
+
35
+
36
+ def local_css(file_name):
37
+ with open(file_name) as f:
38
+ st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True)
39
+
40
+
41
+ st.set_page_config(**PAGE_CONFIG)
42
+
43
+ local_css("style.css")
44
+
45
+
46
+ # ---------------------------------------------------------------------------- #
47
+ # Web Application
48
+ # ---------------------------------------------------------------------------- #
49
+ # st.title("🔥 Schema Audit 🔥")
50
+
51
+
52
+ # ---------------------------------------------------------------------------- #
53
+ # Sidebar
54
+ # ---------------------------------------------------------------------------- #
55
+ # st.sidebar.image("img/logo-wordlift.png", width=200)
56
+ # st.sidebar.info("Run the schema audit on any website to quickly get an overview of the available markup. \
57
+ # Simply add the naked domain without 'www.' (eg. etsy.com or etsy.com/about) URL and click on ""ANALYZE"" to get the results.")
58
+ # st.sidebar.subheader("Configuration")
59
+
60
+ # ---------------------------------------------------------------------------- #
61
+ # Functions
62
+ # ---------------------------------------------------------------------------- #
63
+
64
+ # Set the API endpoint and the API key
65
+ API_ENDPOINT = "https://api2.woorank.com/reviews"
66
+ API_KEY = st.secrets["woorank_api_key"]
67
+ os.environ["OPENAI_API_KEY"] = st.secrets["openai_api_key"]
68
+
69
+ # Generate the report by calling the ChatGPT Turbo API and the WooRank API
70
+
71
+
72
+ def analyze_data(_advice, _items, _topics, _issues, _technologies):
73
+ """
74
+ :param _advice: A list of strings, each string is a piece of advice
75
+ :param _items: a list of items that are being analyzed
76
+ :param _topics: a list of topics that the user is interested in
77
+ :param _issues: a list of issues that the user has selected
78
+ :param _technologies: A list of technologies that the user has selected
79
+ """
80
+ # Create the system message for ChatGPT Turbo
81
+ prefix_messages = [{"role": "system", "content": '''You are a helpful and truthful SEO that is very good at analyzing websites with a specific focus on structured data. /n
82
+ You are able to provide a detailed report on the website's structured data and how to improve it. /n
83
+ ADD AS LEARN MORE LINKS FOR THE FIRST TEXT BLOCK LINKS TO structured data https://wordlift.io/blog/en/entity/structured-data/ and schema.org https://wordlift.io/blog/en/entity/schema-org/ TO PROVIDE ADDITIONAL HELP./n/n
84
+ YOU ARE WRITING THE REPORT IN HTML USING A TEMPLATE.'''}]
85
+ llm = OpenAIChat(temperature=0, prefix_messages=prefix_messages)
86
+
87
+ # Create the prompt template and the run statement when there are NOT issues
88
+ if not _issues and len(_items) > 0:
89
+ template = """
90
+ First text block of the report./n
91
+ Analyze the: {advice}, consider that the site features the following schema classes: {items}./n/n
92
+
93
+ Second text block of the report./n
94
+ The website's homepage also references the following entities: {topics} that could be used to improve the SEO of the website further./n/n
95
+
96
+ Third text block of the report./n
97
+ Describe, if available, IN A SINGLE SENTENCE the {technologies} that the site appears to be using and what they do./n/n
98
+
99
+ THE OUTPUT MUST USE THE FOLLOWING TEMPLATE:/n
100
+ "first": "First text block with schema classes in <i>italic</i>",
101
+ "second": "Second text block with entities in <b>bold</b>",
102
+ "third": "Third text block with technologies in <i>italic</i>"
103
+ """
104
+ prompt = PromptTemplate(template=template, input_variables=[
105
+ "advice", "items", "topics", "technologies"])
106
+ run_statement = {"advice": _advice, "items": _items,
107
+ "topics": _topics, "technologies": _technologies}
108
+
109
+ # Create the prompt template and the run statement when there ARE NOT schema classes
110
+ elif not _items:
111
+ template = """
112
+ First text block of the report./n
113
+ The website homepage doesn't seem to feature any schema class./n/n
114
+
115
+ Second text block of the report./n
116
+ The website's homepage also references the following entities: {topics} that can be used to improve the SEO of the website./n/n
117
+
118
+ Third text block of the report./n
119
+ Describe, if available, IN A SINGLE SENTENCE the {technologies} that the site appears to be using and what they do./n/n
120
+
121
+ THE OUTPUT MUST USE THE FOLLOWING TEMPLATE:/n
122
+ "first": "First text block",
123
+ "second": "Second text block with entities in <b>bold</b>"
124
+ "third": "Third text block with technologies in <i>italic</i>"
125
+ """
126
+ prompt = PromptTemplate(template=template, input_variables=[
127
+ "topics", "technologies"])
128
+ run_statement = {"topics": _topics, "technologies": _technologies}
129
+
130
+ # Create the prompt template and the run statement when there ARE issues
131
+ else:
132
+ template = """
133
+ First text block of the report./n
134
+ Analyze the: {advice}, consider that the site features the following schema classes: {items}./n/n
135
+
136
+ Second text block of the report. /n
137
+ Describe the following issues with the markup: {issues} and indicate how to fix them./n/n
138
+
139
+ Third text block of the report./n
140
+ The website's homepage also references the following entities: {topics} that could be used to improve the SEO of the website further./n/n
141
+
142
+ Fourth text block of the report./n
143
+ Describe, if available, IN A SINGLE SENTENCE the {technologies} that the site appears to be using and what they do./n/n
144
+
145
+ THE OUTPUT MUST USE THE FOLLOWING TEMPLATE:/n
146
+ "first": "First text block with schema classes in <i>italic</i>",
147
+ "second": "Second text block with issues in <u>underline</u>",
148
+ "third": "Third text block with entities in <b>bold</b>"
149
+ "fourth": "Fourth text block with technologies in <i>italic</i>"
150
+ """
151
+ prompt = PromptTemplate(template=template, input_variables=[
152
+ "advice", "items", "topics", "issues", "technologies"])
153
+ run_statement = {"advice": _advice, "items": _items,
154
+ "topics": _topics, "issues": _issues, "technologies": _technologies}
155
+
156
+ # Create the LLMChain
157
+ llm_chain = LLMChain(prompt=prompt, llm=llm)
158
+
159
+ # If there are no issues, remove the issues from the prompt
160
+ prompt_text = prompt.format(**run_statement)
161
+
162
+ # Run the LLMChain and return the output
163
+ out = llm_chain.run(**run_statement)
164
+
165
+ return out
166
+
167
+ # Call WooRank API to get the data (cached)
168
+
169
+
170
+ @st.cache_data
171
+ def get_woorank_data(url):
172
+ """
173
+ It takes a URL as input, and returns a dictionary of the data from the Woorank API
174
+
175
+ :param url: The URL of the website you want to get data for
176
+ """
177
+ # Extract the domain from the URL
178
+
179
+ extracted = tldextract.extract(url)
180
+ url = f"{extracted.domain}.{extracted.suffix}"
181
+
182
+ # Build the API URL
183
+ api_url = f"{API_ENDPOINT}?url={url}"
184
+
185
+ # Set the API key in the headers
186
+ headers = {"x-api-key": "456b66d0ed4e3c9a2d7b559e40ce9034",
187
+ "Accept": "application/json"}
188
+
189
+ # Call the API using HTTP GET and parse the JSON response to extract what we need
190
+ response = requests.get(api_url, headers=headers)
191
+ data = response.json()
192
+ result = data.get("criteria", {}).get("schema_org", {})
193
+ advice = result.get("advice", {})
194
+ items = result.get("data", {}).get("counts", {})
195
+ issues = result.get("data", {}).get("issues", {})
196
+ topics_raw = data.get("criteria", {}).get("topics", {}).get("data", {})
197
+ technologies_raw = data.get("criteria", {}).get(
198
+ "technologies", {}).get("data", {}).get("technologies", {})
199
+
200
+ # extract the unique English labels into a list
201
+ topics = list(
202
+ set([label for item in topics_raw for label in item['dbpediaLabelsEn']]))
203
+
204
+ # extract the technologies that are related to seo and search-engines
205
+ technologies = []
206
+ for item in technologies_raw:
207
+ if "seo" in item["categories"] or "search-engines" in item["categories"]:
208
+ technologies.append(item["app"])
209
+
210
+ # Return now all the items we need
211
+ return result, advice, items, issues, topics, technologies
212
+
213
+ # Here capture the output of the function and write it to the Streamlit app for debugging purposes
214
+
215
+
216
+ def capture_output(func):
217
+ """Capture output from running a function and write using streamlit."""
218
+
219
+ @wraps(func)
220
+ def wrapper(*args, **kwargs):
221
+ # Redirect output to string buffers
222
+ stdout, stderr = StringIO(), StringIO()
223
+ try:
224
+ with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):
225
+ return func(*args, **kwargs)
226
+ except Exception as err:
227
+ print(f"Failure while executing: {err}")
228
+ finally:
229
+ if _stdout := stdout.getvalue():
230
+ print("Execution stdout:")
231
+ print(_stdout)
232
+ if _stderr := stderr.getvalue():
233
+ print("Execution stderr:")
234
+ print(_stderr)
235
+
236
+ return wrapper
237
+
238
+ # ---------------------------------------------------------------------------- #
239
+ # Main Function
240
+ # ---------------------------------------------------------------------------- #
241
+
242
+
243
+ def main():
244
+
245
+ # Set up the Streamlit app
246
+ # Adding the input for the URL
247
+ url = st.text_input("Enter a URL to analyze")
248
+
249
+ if st.button("RUN THE STRUCTURED DATA AUDIT"):
250
+ # Call the Woorank API
251
+ schema_org, advice, items, issues, topics, technologies = get_woorank_data(
252
+ url)
253
+ msg = analyze_data(advice, items, topics, issues, technologies)
254
+ # Display the results when the button is clicked and the data is available
255
+ if schema_org:
256
+ st.write("##### Your Findings 📈")
257
+ try:
258
+ data_out = json.loads(msg)
259
+ # here is the first block of text with the advice
260
+ first_block_text = data_out['first']
261
+ # here is the second block of text (opportunities if there are no issues, issues if there are)
262
+ second_block_text = data_out['second']
263
+
264
+ # here we create the HTML string for the first block of text (advice)
265
+ htmlstr1 = f"""<div class="success">{first_block_text}</div>"""
266
+ st.markdown(htmlstr1, unsafe_allow_html=True)
267
+ # adding a disclosure message
268
+ st.markdown(
269
+ """<div class="disclosure">*These findings are based on the analysis of your website as seen from the "eyes" of a crawler.</div>""", unsafe_allow_html=True)
270
+
271
+ # if there are no issues, we only have three blocks of text (advice, opportunities, technologies)
272
+ if not issues:
273
+ # here we get the third block of text with the technologies
274
+ third_block_text = data_out['third']
275
+ # here we create the HTML string for the second block of text (opportunities)
276
+ htmlstr2 = f"""<p class="opportunity">ℹ️ <b>Opportunities</b></br>{second_block_text}</p>"""
277
+ st.markdown(htmlstr2, unsafe_allow_html=True)
278
+ # here we create the HTML string for the third block of text (technologies)
279
+ htmlstr3 = f"""<p class="technology">👩🏽‍💻 <b>Technologies</b></br>{third_block_text}</p>"""
280
+ st.markdown(htmlstr3, unsafe_allow_html=True)
281
+ # if there are issues, we have four blocks of text (advice, issues, opportunities, technologies)
282
+ else:
283
+ # here we get the third block of text with the opportunities
284
+ third_block_text = data_out['third']
285
+ # here we get the fourth block of text with the technologies
286
+ fourth_block_text = data_out['fourth']
287
+ # here we create the HTML string for the second block of text (issues)
288
+ htmlstr2 = f"""<p class="warning">⚠️ <b>Warnings</b></br>{second_block_text}</p>"""
289
+ st.markdown(htmlstr2, unsafe_allow_html=True)
290
+ # here we create the HTML string for the third block of text (opportunities)
291
+ htmlstr3 = f"""<p class="opportunity">ℹ️ <b>Opportunities</b></br>{third_block_text}</p>"""
292
+ st.markdown(htmlstr3, unsafe_allow_html=True)
293
+ # here we create the HTML string for the fourth block of text (technologies)
294
+ htmlstr4 = f"""<p class="technology">👩🏽‍💻 <b>Technologies</b></br>{fourth_block_text}</p>"""
295
+ st.markdown(htmlstr4, unsafe_allow_html=True)
296
+ except Exception as e:
297
+ st.warning(
298
+ "Sorry, something went wrong. Please try again later.", icon="⚠️")
299
+ # Adding debug info
300
+ stprint = capture_output(print)
301
+ stprint(e)
302
+ stprint(msg)
303
+
304
+ st.write("---")
305
+
306
+ # Adding an expandable section to display the full response
307
+ with st.expander("INSPECT THE REPORT"):
308
+ # st.write("#### Advice")
309
+ # st.markdown(advice, unsafe_allow_html=True)
310
+ st.write("##### Items")
311
+ st.write(items)
312
+ if not issues:
313
+ st.write("No issues found on the structured data")
314
+ else:
315
+ st.write("#### Issues")
316
+ st.write(issues)
317
+ st.write("##### Entities")
318
+ st.write(topics)
319
+ st.write("##### Technologies")
320
+ st.write(technologies)
321
+ st.write("##### Full response")
322
+ st.write(schema_org)
323
+ # If the API call fails, display an error message
324
+ else:
325
+ if len(url) == 0:
326
+ st.warning("Please enter a URL to analyze")
327
+ else:
328
+ st.warning("Whoops, sorry, our bot didn't find any data. It might be that the URL is not accessible (a firewall is in place, for example), or the website does not have structured data.", icon="⚠️")
329
+
330
+
331
+ if __name__ == "__main__":
332
+ main()