Spaces:
Build error
Build error
File size: 7,578 Bytes
c066b32 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 | import requests
from bs4 import BeautifulSoup
from transformers import pipeline
import gradio as gr
from keybert import KeyBERT
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import re
from urllib.parse import urlparse, urljoin
from time import sleep
nltk.download('punkt')
nltk.download('stopwords')
def scrape_multiple_pages(urls):
all_content = ""
for url in urls:
try:
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
paragraphs = soup.find_all('p')
content = ' '.join([para.get_text() for para in paragraphs])
all_content += " " + content
except requests.exceptions.RequestException as e:
print(f"Failed to scrape {url}: {e}")
return all_content
def is_valid_url(url):
parsed = urlparse(url)
return bool(parsed.netloc) and bool(parsed.scheme)
def extract_links(url, domain):
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
links = [a.get('href') for a in soup.find_all('a', href=True)]
full_links = [urljoin(domain, link) if not link.startswith('http') else link for link in links]
valid_links = [link for link in full_links if is_valid_url(link)]
return valid_links
summarizer = pipeline('summarization')
def summarize_content(content):
if len(content.strip()) == 0:
return "No content extracted or content is empty."
# Truncate content to fit within model's maximum input length
max_input_length = 1024
content = content[:max_input_length]
summary = summarizer(content, max_length=150, min_length=50, do_sample=False)
if len(summary) == 0 or 'summary_text' not in summary[0]:
return "Failed to generate summary."
return summary[0]['summary_text']
kw_model = KeyBERT()
def suggest_keywords_advanced(content):
# Initialize KeyBERT
kw_model = KeyBERT()
# Extract keywords with KeyBERT
keywords = kw_model.extract_keywords(content, keyphrase_ngram_range=(1, 2), stop_words='english', top_n=10)
keywords_list = [keyword[0] for keyword in keywords]
# Additional processing with NLTK
stop_words = set(stopwords.words('english'))
word_tokens = word_tokenize(content)
filtered_words = [w for w in word_tokens if w.lower() not in stop_words and w.isalnum()]
# Frequency distribution
freq_dist = nltk.FreqDist(filtered_words)
most_common = freq_dist.most_common(10)
# Combine results from KeyBERT and NLTK
combined_keywords = list(set(keywords_list + [word for word, freq in most_common]))
return ', '.join(combined_keywords)
def word_count(content):
words = content.split()
return len(words)
def readability_score(content):
sentences = content.split('.')
words = content.split()
syllables = sum([len(re.findall(r'[aeiouyAEIOUY]+', word)) for word in words])
if len(words) == 0 or len(sentences) == 0:
return 0
score = 206.835 - 1.015 * (len(words) / len(sentences)) - 84.6 * (syllables / len(words))
return score
sentiment_analyzer = pipeline('sentiment-analysis')
def analyze_sentiment(content):
sentiments = sentiment_analyzer(content[:512]) # Analyze only the first 512 tokens for simplicity
return sentiments[0]['label'], sentiments[0]['score']
def seo_tool(url):
# Simulating processing time with sleep
sleep(2)
domain = url.split("//")[-1].split("/")[0]
links = extract_links(url, f"http://{domain}")
content = scrape_multiple_pages(links)
summary = summarize_content(content)
keywords = suggest_keywords_advanced(content)
sentiment, score = analyze_sentiment(content)
word_count_val = word_count(content)
readability_val = readability_score(content)
return summary, keywords, f"Sentiment: {sentiment} (Score: {score:.2f})", f"Word Count: {word_count_val}", f"Readability Score: {readability_val:.2f}"
# Custom CSS
custom_css = """
body {
background-color: #f0f0f0;
font-family: 'Arial', sans-serif;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background: linear-gradient(135deg, #1e3c72, #2a5298);
}
.container {
max-width: 90%;
width: 600px;
background: white;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
overflow: hidden;
padding-bottom: 20px;
}
.header {
background-color: #1e3c72;
color: white;
padding: 20px 20px 10px;
text-align: center;
font-size: 24px;
font-weight: bold;
}
.logo {
width: 100px;
margin: 0 auto 20px;
display: block;
}
.textbox, .output-box {
padding: 20px;
margin: 10px 0;
}
.textbox input[type="text"], .output-box textarea {
width: 100%;
padding: 15px;
border: 1px solid #ccc;
border-radius: 5px;
box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
}
.textbox input[type="text"]:focus, .output-box textarea:focus {
border-color: #1e3c72;
outline: none;
}
.button {
background-color: #1e3c72;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
margin: 20px auto;
display: block;
width: 50%;
text-align: center;
}
.button:hover {
background-color: #16335b;
}
.tooltip {
position: relative;
display: inline-block;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 200px;
background-color: black;
color: #fff;
text-align: center;
border-radius: 5px;
padding: 5px;
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
margin-left: -100px;
opacity: 0;
transition: opacity 0.3s;
}
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
.loading-spinner {
border: 16px solid #f3f3f3;
border-top: 16px solid #3498db;
border-radius: 50%;
width: 120px;
height: 120px;
animation: spin 2s linear infinite;
display: none;
margin: 20px auto;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
@media (max-width: 600px) {
.container {
width: 100%;
}
.textbox input[type="text"], .output-box textarea {
padding: 10px;
}
.button {
width: 70%;
}
}
"""
# Interface definition
interface = gr.Interface(
fn=seo_tool,
inputs=[
gr.Textbox(label="Enter a URL", placeholder="http://example.com")
],
outputs=[
gr.Textbox(label="Summary of Content"),
gr.Textbox(label="Suggested Keywords"),
gr.Textbox(label="Sentiment Analysis"),
gr.Textbox(label="Word Count"),
gr.Textbox(label="Readability Score")
],
title="AMInsightIQ - SEO Tool",
description="""
<br>
<h3>AMTechInscribe-Crafting Tomorrow's Code,Today!</h3>
<div class="header">AMInsightIQ - SEO Tool</div>
<p>Enter a URL to get a summary, keyword suggestions, sentiment analysis, word count, and readability score.</p>
<div class="loading-spinner" id="spinner"></div>
<script>
function showSpinner() {
document.getElementById('spinner').style.display = 'block';
}
function hideSpinner() {
document.getElementById('spinner').style.display = 'none';
}
document.querySelector('button').addEventListener('click', showSpinner);
document.querySelector('form').addEventListener('submit', hideSpinner);
</script>
""",
css=custom_css
)
interface.launch(share=True, inline=False, show_error=True)
|