File size: 10,899 Bytes
a3acd70
81169a3
a3acd70
b43f4c5
a3acd70
 
45a9528
 
a3acd70
 
45a9528
b43f4c5
45a9528
 
 
 
3a8824c
45a9528
 
 
 
 
a3acd70
 
 
45a9528
 
 
 
 
 
3a8824c
 
 
 
b43f4c5
45a9528
 
 
 
b43f4c5
81169a3
a3acd70
45a9528
 
 
 
 
 
 
 
 
 
a3acd70
13cd273
45a9528
 
 
 
 
 
 
 
 
 
 
 
7e9a98f
 
45a9528
 
 
 
 
 
 
3a8824c
 
 
 
 
 
 
45a9528
 
3a8824c
 
 
 
 
 
 
 
 
45a9528
 
 
 
 
 
 
 
 
3a8824c
45a9528
3a8824c
 
45a9528
 
 
3a8824c
 
 
 
 
 
 
 
 
45a9528
7e9a98f
45a9528
 
3a8824c
 
 
 
 
 
 
 
 
 
45a9528
3a8824c
 
 
 
 
 
 
 
 
6887cab
3a8824c
 
7e9a98f
3a8824c
 
45a9528
3a8824c
 
 
 
 
 
 
45a9528
 
3a8824c
 
45a9528
7e9a98f
3a8824c
45a9528
3a8824c
 
 
45a9528
3a8824c
 
 
 
 
 
 
 
45a9528
 
3a8824c
 
 
 
 
 
 
 
 
45a9528
7e9a98f
3a8824c
 
81169a3
3a8824c
45a9528
3a8824c
 
45a9528
3a8824c
 
45a9528
13cd273
3a8824c
 
 
 
 
45a9528
81169a3
 
3a8824c
45a9528
3a8824c
 
45a9528
3a8824c
 
 
 
 
45a9528
 
3a8824c
5c78dbd
3a8824c
 
 
 
 
9275131
45a9528
 
3a8824c
45a9528
3a8824c
 
45a9528
3a8824c
 
 
 
 
 
 
 
 
45a9528
3a8824c
 
45a9528
3a8824c
e2afe1c
3a8824c
 
 
 
 
 
5c78dbd
 
3a8824c
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
from streamlit_lottie import st_lottie
from streamlit_option_menu import option_menu
import requests
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime
import httpx
import asyncio
import aiohttp
from bs4 import BeautifulSoup
import whois
import ssl
import socket
import dns.resolver
from urllib.parse import urlparse, urljoin
import json
import numpy as np
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from PIL import Image
import io
import time
import tldextract
import requests_html
from fake_useragent import UserAgent
from concurrent.futures import ThreadPoolExecutor
import re
from urllib.robotparser import RobotFileParser
import random
from textblob import TextBlob
from collections import Counter
import networkx as nx

# تهيئة المتغيرات العامة
TIMEOUT = 10
MAX_RETRIES = 3
COMMON_CRAWL_INDEX = 'https://index.commoncrawl.org/CC-MAIN-2023-50-index'

class WebsiteAnalyzer:
    def __init__(self):
        self.ua = UserAgent()
        self.session = requests.Session()
        self.cache = {}
        
    def _get_headers(self):
        return {
            'User-Agent': self.ua.random,
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Language': 'en-US,en;q=0.5',
            'Connection': 'keep-alive',
        }

    async def _fetch_with_retry(self, url, retries=MAX_RETRIES):
        for i in range(retries):
            try:
                async with httpx.AsyncClient(timeout=TIMEOUT) as client:
                    response = await client.get(url, headers=self._get_headers())
                    response.raise_for_status()
                    return response
            except Exception as e:
                if i == retries - 1:
                    raise e
                await asyncio.sleep(1)

    async def analyze_performance(self, url):
        try:
            performance_metrics = {
                'dns_lookup': [],
                'tcp_handshake': [],
                'ttfb': [],
                'content_download': []
            }

            # تحليل الأداء على أجهزة مختلفة
            devices = ['desktop', 'mobile', 'tablet']
            device_metrics = {}
            
            for device in devices:
                chrome_options = Options()
                chrome_options.add_argument(f"--user-agent={self._get_device_user_agent(device)}")
                start_time = time.time()
                
                # قياس الأداء لكل جهاز
                device_metrics[device] = {
                    'load_time': time.time() - start_time,
                    'render_time': self._measure_render_time(url, chrome_options)
                }

            # تحليل عام للأداء
            for _ in range(3):
                start_time = time.time()
                domain = urlparse(url).netloc
                dns_start = time.time()
                socket.gethostbyname(domain)
                performance_metrics['dns_lookup'].append(time.time() - dns_start)

                response = await self._fetch_with_retry(url)
                performance_metrics['ttfb'].append(response.elapsed.total_seconds())
                performance_metrics['content_download'].append(time.time() - start_time - response.elapsed.total_seconds())

            # تحليل الموارد والتحسينات
            soup = BeautifulSoup(response.text, 'html.parser')
            resource_analysis = self._analyze_resources(soup, response.content)
            optimization_suggestions = self._generate_optimization_suggestions(resource_analysis)

            return {
                "أداء الموقع": {
                    "تحليل الأجهزة": {
                        device: {
                            "زمن التحميل": f"{metrics['load_time']:.2f} ثانية",
                            "زمن العرض": f"{metrics['render_time']:.2f} ثانية"
                        } for device, metrics in device_metrics.items()
                    },
                    "تحليل الموارد": resource_analysis,
                    "اقتراحات التحسين": optimization_suggestions
                }
            }
        except Exception as e:
            return {"error": f"حدث خطأ أثناء تحليل الأداء: {str(e)}"}

    def _analyze_resources(self, soup, content):
        """تحليل موارد الصفحة وتحديد فرص التحسين"""
        resources = {
            'images': self._analyze_images(soup),
            'scripts': self._analyze_scripts(soup),
            'styles': self._analyze_styles(soup),
            'fonts': self._analyze_fonts(soup),
            'total_size': len(content) / 1024
        }
        return resources

    def _analyze_images(self, soup):
        """تحليل تفصيلي للصور"""
        images = soup.find_all('img')
        return {
            'count': len(images),
            'without_alt': len([img for img in images if not img.get('alt')]),
            'large_images': len([img for img in images if self._is_large_image(img)]),
            'optimization_needed': self._check_image_optimization(images)
        }

    def _analyze_competitors(self, url):
        """تحليل المنافسين والمقارنة معهم"""
        try:
            competitors = self._find_competitors(url)
            comparison = {}
            
            for competitor in competitors:
                comparison[competitor] = {
                    'traffic': self._estimate_traffic(competitor),
                    'keywords': self._analyze_keywords(competitor),
                    'backlinks': self._analyze_backlinks(competitor),
                    'social_presence': self._analyze_social_presence(competitor)
                }
            
            return {
                'المنافسون الرئيسيون': comparison,
                'تحليل مقارن': self._generate_competitive_analysis(comparison)
            }
        except Exception as e:
            return {"error": f"خطأ في تحليل المنافسين: {str(e)}"}

    def _analyze_content_quality(self, soup):
        """تحليل جودة المحتوى"""
        text_content = soup.get_text()
        
        # تحليل لغوي
        blob = TextBlob(text_content)
        
        # تحليل القراءة
        readability = self._calculate_readability(text_content)
        
        # تحليل الكلمات المفتاحية
        keywords = self._extract_keywords(text_content)
        
        return {
            "تحليل المحتوى": {
                "مستوى القراءة": readability,
                "تنوع المفردات": self._calculate_lexical_diversity(text_content),
                "الكلمات المفتاحية الرئيسية": keywords[:10],
                "العاطفة": {
                    "إيجابية": blob.sentiment.polarity,
                    "موضوعية": blob.sentiment.subjectivity
                }
            }
        }

    def _analyze_backlinks(self, url):
        """تحليل الروابط الخلفية"""
        try:
            backlinks = self._fetch_backlinks(url)
            
            # تحليل جودة الروابط
            quality_metrics = self._analyze_backlink_quality(backlinks)
            
            # تحليل تنوع المصادر
            diversity = self._analyze_source_diversity(backlinks)
            
            return {
                "تحليل الروابط الخلفية": {
                    "العدد الإجمالي": len(backlinks),
                    "جودة الروابط": quality_metrics,
                    "تنوع المصادر": diversity,
                    "أهم المصادر": self._get_top_referring_domains(backlinks)
                }
            }
        except Exception as e:
            return {"error": f"خطأ في تحليل الروابط الخلفية: {str(e)}"}

    def _analyze_social_signals(self, url):
        """تحليل الإشارات الاجتماعية"""
        try:
            social_metrics = {
                'facebook': self._get_facebook_shares(url),
                'twitter': self._get_twitter_shares(url),
                'linkedin': self._get_linkedin_shares(url),
                'pinterest': self._get_pinterest_shares(url)
            }
            
            engagement_analysis = self._analyze_social_engagement(social_metrics)
            
            return {
                "التواجد الاجتماعي": {
                    "إحصائيات المشاركة": social_metrics,
                    "تحليل التفاعل": engagement_analysis,
                    "توصيات": self._generate_social_recommendations(engagement_analysis)
                }
            }
        except Exception as e:
            return {"error": f"خطأ في تحليل الإشارات الاجتماعية: {str(e)}"}

    def _generate_comprehensive_report(self, url):
        """توليد تقرير شامل"""
        try:
            report = {
                "تحليل الأداء": self.analyze_performance(url),
                "تحليل SEO": self.analyze_seo(url),
                "تحليل الأمان": self.analyze_security(url),
                "تحليل المنافسين": self._analyze_competitors(url),
                "تحليل المحتوى": self._analyze_content_quality(BeautifulSoup(requests.get(url).text, 'html.parser')),
                "تحليل الروابط": self._analyze_backlinks(url),
                "التواجد الاجتماعي": self._analyze_social_signals(url),
                "التوصيات": self._generate_recommendations()
            }
            
            return report
        except Exception as e:
            return {"error": f"خطأ في توليد التقرير الشامل: {str(e)}"}

    def _generate_recommendations(self):
        """توليد توصيات مخصصة"""
        recommendations = {
            "تحسينات عاجلة": [],
            "تحسينات متوسطة الأولوية": [],
            "تحسينات طويلة المدى": []
        }
        
        # إضافة التوصيات بناءً على نتائج التحليل
        return recommendations

# مثال للاستخدام
async def main():
    analyzer = WebsiteAnalyzer()
    url = "https://example.com"
    report = await analyzer._generate_comprehensive_report(url)
    print(json.dumps(report, ensure_ascii=False, indent=2))

if __name__ == "__main__":
    asyncio.run(main())