File size: 10,482 Bytes
a74b879 | 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 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 | """
Schema Generator
Automatically generates JSON-LD schema markup for websites
"""
import json
from typing import Dict, List
from datetime import datetime
def generate_organization_schema(audit: Dict) -> Dict:
"""Generate Organization schema from audit data"""
pages = audit.get('pages', [])
org_name = audit.get('org_name', 'Company')
url = audit.get('url', '')
# Extract contact info from pages
emails = []
phones = []
social_links = []
for page in pages:
text = page.get('text', '') + ' ' + str(page.get('paragraphs', ''))
# Extract emails
import re
found_emails = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', text)
emails.extend(found_emails)
# Extract phones
found_phones = re.findall(r'(\+?\d{1,3}[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}', text)
phones.extend(found_phones)
# Extract social links
links = page.get('links', [])
for link in links:
href = link.get('href', '') if isinstance(link, dict) else str(link)
if any(social in href.lower() for social in ['facebook', 'twitter', 'instagram', 'linkedin', 'youtube']):
social_links.append(href)
schema = {
"@context": "https://schema.org",
"@type": "Organization",
"name": org_name,
"url": url,
"logo": f"{url}/logo.png",
"description": f"{org_name} - خدمات متميزة"
}
if emails:
schema["email"] = emails[0]
if phones:
schema["telephone"] = phones[0]
if social_links:
schema["sameAs"] = list(set(social_links))[:5]
# Add contact point
if emails or phones:
schema["contactPoint"] = {
"@type": "ContactPoint",
"contactType": "customer service",
"email": emails[0] if emails else None,
"telephone": phones[0] if phones else None
}
return schema
def generate_faq_schema(faqs: List[Dict]) -> Dict:
"""Generate FAQPage schema from FAQ list"""
if not faqs:
return None
schema = {
"@context": "https://schema.org",
"@type": "FAQPage",
"mainEntity": []
}
for faq in faqs:
question = faq.get('question', faq.get('q', ''))
answer = faq.get('answer', faq.get('a', ''))
if question and answer:
schema["mainEntity"].append({
"@type": "Question",
"name": question,
"acceptedAnswer": {
"@type": "Answer",
"text": answer
}
})
return schema if schema["mainEntity"] else None
def generate_breadcrumb_schema(url: str) -> Dict:
"""Generate BreadcrumbList schema from URL structure"""
from urllib.parse import urlparse
parsed = urlparse(url)
path_parts = [p for p in parsed.path.split('/') if p]
schema = {
"@context": "https://schema.org",
"@type": "BreadcrumbList",
"itemListElement": []
}
# Add home
schema["itemListElement"].append({
"@type": "ListItem",
"position": 1,
"name": "الرئيسية",
"item": f"{parsed.scheme}://{parsed.netloc}"
})
# Add path parts
current_url = f"{parsed.scheme}://{parsed.netloc}"
for i, part in enumerate(path_parts, start=2):
current_url += f"/{part}"
schema["itemListElement"].append({
"@type": "ListItem",
"position": i,
"name": part.replace('-', ' ').replace('_', ' ').title(),
"item": current_url
})
return schema
def generate_website_schema(audit: Dict) -> Dict:
"""Generate WebSite schema with search action"""
org_name = audit.get('org_name', 'Company')
url = audit.get('url', '')
schema = {
"@context": "https://schema.org",
"@type": "WebSite",
"name": org_name,
"url": url,
"potentialAction": {
"@type": "SearchAction",
"target": {
"@type": "EntryPoint",
"urlTemplate": f"{url}/search?q={{search_term_string}}"
},
"query-input": "required name=search_term_string"
}
}
return schema
def generate_article_schema(page: Dict, org_name: str) -> Dict:
"""Generate Article schema for blog posts"""
title = page.get('title', '')
url = page.get('url', '')
# Try to extract publish date
text = page.get('text', '')
import re
date_match = re.search(r'(\d{4}-\d{2}-\d{2})', text)
publish_date = date_match.group(1) if date_match else datetime.now().strftime('%Y-%m-%d')
schema = {
"@context": "https://schema.org",
"@type": "Article",
"headline": title,
"url": url,
"datePublished": publish_date,
"dateModified": publish_date,
"author": {
"@type": "Organization",
"name": org_name
},
"publisher": {
"@type": "Organization",
"name": org_name
}
}
# Extract image if available
images = page.get('images', [])
if images:
first_image = images[0] if isinstance(images[0], str) else images[0].get('src', '')
if first_image:
schema["image"] = first_image
return schema
def generate_product_schema(page: Dict, org_name: str) -> Dict:
"""Generate Product schema for product pages"""
title = page.get('title', '')
url = page.get('url', '')
text = page.get('text', '')
# Try to extract price
import re
price_match = re.search(r'(\$|SAR|ريال)\s*(\d+(?:\.\d{2})?)', text)
price = price_match.group(2) if price_match else "0"
currency = "SAR" if "ريال" in text or "SAR" in text else "USD"
schema = {
"@context": "https://schema.org",
"@type": "Product",
"name": title,
"url": url,
"description": text[:200] if text else title,
"offers": {
"@type": "Offer",
"price": price,
"priceCurrency": currency,
"availability": "https://schema.org/InStock",
"seller": {
"@type": "Organization",
"name": org_name
}
}
}
# Extract image
images = page.get('images', [])
if images:
first_image = images[0] if isinstance(images[0], str) else images[0].get('src', '')
if first_image:
schema["image"] = first_image
return schema
def generate_local_business_schema(audit: Dict) -> Dict:
"""Generate LocalBusiness schema"""
pages = audit.get('pages', [])
org_name = audit.get('org_name', 'Company')
url = audit.get('url', '')
# Extract location info
addresses = []
for page in pages:
text = page.get('text', '')
# Look for Saudi cities
saudi_cities = ['الرياض', 'جدة', 'مكة', 'المدينة', 'الدمام', 'الخبر', 'تبوك', 'أبها']
for city in saudi_cities:
if city in text:
addresses.append(city)
break
schema = {
"@context": "https://schema.org",
"@type": "LocalBusiness",
"name": org_name,
"url": url,
"address": {
"@type": "PostalAddress",
"addressCountry": "SA",
"addressLocality": addresses[0] if addresses else "الرياض"
}
}
return schema
def generate_all_schemas(audit: Dict) -> List[Dict]:
"""Generate all applicable schemas for a website"""
schemas = []
# Always add Organization
org_schema = generate_organization_schema(audit)
schemas.append(org_schema)
# Add WebSite with search
website_schema = generate_website_schema(audit)
schemas.append(website_schema)
# Add LocalBusiness if applicable
local_schema = generate_local_business_schema(audit)
schemas.append(local_schema)
# Add Breadcrumb for main page
url = audit.get('url', '')
if url:
breadcrumb_schema = generate_breadcrumb_schema(url)
schemas.append(breadcrumb_schema)
return schemas
def format_schema_for_html(schemas: List[Dict]) -> str:
"""Format schemas as HTML script tags"""
html_parts = []
for schema in schemas:
if schema:
json_str = json.dumps(schema, ensure_ascii=False, indent=2)
html_parts.append(f'<script type="application/ld+json">\n{json_str}\n</script>')
return '\n\n'.join(html_parts)
def get_schema_recommendations(audit: Dict) -> List[Dict]:
"""Get recommendations for missing schemas"""
recommendations = []
pages = audit.get('pages', [])
# Check if Organization schema exists
has_org_schema = False
for page in pages:
html = page.get('html', '')
if '"@type":"Organization"' in html or '"@type": "Organization"' in html:
has_org_schema = True
break
if not has_org_schema:
recommendations.append({
'type': 'organization',
'priority': 'high',
'title': 'أضف Organization Schema',
'description': 'يساعد محركات البحث على فهم معلومات شركتك',
'code': json.dumps(generate_organization_schema(audit), ensure_ascii=False, indent=2)
})
# Check for FAQ schema
has_faq = any('faq' in page.get('url', '').lower() for page in pages)
if has_faq:
recommendations.append({
'type': 'faq',
'priority': 'medium',
'title': 'أضف FAQPage Schema',
'description': 'يظهر الأسئلة الشائعة مباشرة في نتائج البحث',
'code': 'استخدم generate_faq_schema() مع قائمة الأسئلة'
})
# Check for BreadcrumbList
recommendations.append({
'type': 'breadcrumb',
'priority': 'medium',
'title': 'أضف BreadcrumbList Schema',
'description': 'يحسن التنقل في نتائج البحث',
'code': json.dumps(generate_breadcrumb_schema(audit.get('url', '')), ensure_ascii=False, indent=2)
})
return recommendations
|