File size: 13,914 Bytes
a3acd70
 
 
b43f4c5
a3acd70
 
 
 
 
 
 
b43f4c5
a3acd70
 
 
 
 
 
 
 
 
 
 
 
 
b43f4c5
a3acd70
 
b43f4c5
a3acd70
 
05908c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b43f4c5
05908c3
a3acd70
b43f4c5
a3acd70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b43f4c5
a3acd70
 
 
 
 
b43f4c5
a3acd70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b43f4c5
a3acd70
 
 
 
 
 
7b35dcd
a3acd70
 
 
 
 
 
7b35dcd
 
 
 
 
 
 
a3acd70
 
 
 
 
 
 
 
7b35dcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a3acd70
 
7b35dcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a3acd70
 
 
b43f4c5
a3acd70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da60d2c
a3acd70
 
 
 
 
 
 
 
 
 
 
 
 
da60d2c
a3acd70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05908c3
a3acd70
05908c3
a3acd70
7b35dcd
a3acd70
 
 
 
 
 
7b35dcd
05908c3
7b35dcd
 
05908c3
 
 
 
a3acd70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da60d2c
 
05908c3
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
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
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

# تخصيص المظهر
st.set_page_config(layout="wide", page_title="محلل المواقع المتقدم")

# تحميل الأنيميشن
def load_lottieurl(url):
    try:
        r = requests.get(url)
        r.raise_for_status()
        return r.json()
    except Exception as e:
        # Fallback to a basic loading animation JSON
        return {
            "v": "5.5.7",
            "fr": 29.9700012207031,
            "ip": 0,
            "op": 180.00000733155,
            "w": 500,
            "h": 500,
            "nm": "Loading",
            "ddd": 0,
            "assets": [],
            "layers": [
                {
                    "ddd": 0,
                    "ind": 1,
                    "ty": 4,
                    "nm": "Loading Circle",
                    "sr": 1,
                    "ks": {
                        "o": {"a": 0, "k": 100, "ix": 11},
                        "r": {"a": 1, "k": [{"i": {"x": [0.833], "y": [0.833]}, "o": {"x": [0.167], "y": [0.167]}, "t": 0, "s": [0], "e": [360]}, {"t": 180.00000733155}], "ix": 10}
                    }
                }
            ]
        }

# تحميل الأنيميشن الافتراضي
lottie_analyzing = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_qpwbqki6.json")

# تصميم CSS مخصص
st.markdown("""
<style>
    .main {
        background-color: #f0f2f6;
    }
    .stButton>button {
        color: white;
        background-color: #ff4b4b;
        border-radius: 10px;
        padding: 15px 25px;
        border: none;
    }
    .stButton>button:hover {
        background-color: #ff6b6b;
        border: none;
    }
    .metric-card {
        background-color: white;
        border-radius: 10px;
        padding: 20px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    }
</style>
""", unsafe_allow_html=True)

class WebsiteAnalyzer:
    def __init__(self):
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }

    async def analyze_performance(self, url):
        try:
            start_time = time.time()
            async with httpx.AsyncClient() as client:
                response = await client.get(url)
                load_time = time.time() - start_time
                page_size = len(response.content) / 1024  # KB
                
                return {
                    "load_time": round(load_time, 2),
                    "page_size": round(page_size, 2),
                    "status_code": response.status_code
                }
        except Exception as e:
            return {"error": str(e)}

    async def analyze_seo(self, url):
        try:
            async with httpx.AsyncClient() as client:
                response = await client.get(url)
                soup = BeautifulSoup(response.text, 'html.parser')
                
                # تحليل العناوين مع تقييم
                headings = {
                    'h1': len(soup.find_all('h1')),
                    'h2': len(soup.find_all('h2')),
                    'h3': len(soup.find_all('h3'))
                }
                
                # تقييم العناوين
                heading_score = 0
                if headings['h1'] > 0:
                    heading_score += 20  # تأكد من وجود H1
                heading_score += min(headings['h2'], 3) * 5  # حتى 3 عناوين H2
                heading_score += min(headings['h3'], 3) * 3  # حتى 3 عناوين H3
                
                # تحليل الروابط
                links = soup.find_all('a')
                internal_links = len([link for link in links if urlparse(link.get('href', '')).netloc == urlparse(url).netloc])
                external_links = len(links) - internal_links
                
                # تحليل الصور
                images = soup.find_all('img')
                images_without_alt = len([img for img in images if not img.get('alt')])
                images_alt_score = max(0, 100 - (images_without_alt * 5))  # خصم 5 نقاط لكل صورة بدون Alt
                
                # تحليل العنوان والوصف
                title = soup.title.string if soup.title else "لا يوجد عنوان"
                meta_description = soup.find("meta", {"name": "description"}) or soup.find("meta", {"property": "og:description"})
                description_text = meta_description.get("content") if meta_description else "لا يوجد وصف"
                
                # حساب نقاط العنوان والوصف
                title_score = 0
                if title and len(title) > 10 and len(title) <= 60:
                    title_score = 20
                
                description_score = 0
                if description_text != "لا يوجد وصف" and 70 <= len(description_text) <= 160:
                    description_score = 20
                
                # حساب النقاط الإجمالية
                total_seo_score = heading_score + images_alt_score + title_score + description_score
                
                return {
                    "title": {
                        "text": title,
                        "score": title_score,
                        "recommendation": "يجب أن يكون العنوان بين 10-60 حرفًا" if title_score == 0 else "العنوان مثالي"
                    },
                    "meta_description": {
                        "text": description_text,
                        "score": description_score,
                        "recommendation": "يجب أن يكون الوصف بين 70-160 حرفًا" if description_score == 0 else "الوصف مثالي"
                    },
                    "headings": {
                        "details": headings,
                        "score": heading_score,
                        "recommendation": "تأكد من وجود عنوان H1 واستخدم العناوين الفرعية بشكل هرمي"
                    },
                    "internal_links": {
                        "count": internal_links,
                        "score": min(internal_links, 20),
                        "recommendation": "الروابط الداخلية جيدة للتنقل وتحسين SEO"
                    },
                    "external_links": {
                        "count": external_links,
                        "recommendation": "استخدم الروابط الخارجية بحكمة للمصداقية"
                    },
                    "images": {
                        "total": len(images),
                        "without_alt": images_without_alt,
                        "alt_score": images_alt_score,
                        "recommendation": f"أضف نص بديل لـ {images_without_alt} صورة"
                    },
                    "total_seo_score": {
                        "score": total_seo_score,
                        "max_score": 100,
                        "grade": (
                            "ممتاز" if total_seo_score >= 80 else
                            "جيد" if total_seo_score >= 60 else
                            "متوسط" if total_seo_score >= 40 else
                            "ضعيف"
                        )
                    }
                }
        except Exception as e:
            return {"error": str(e)}

    def analyze_security(self, url):
        try:
            domain = urlparse(url).netloc
            
            # فحص SSL
            ctx = ssl.create_default_context()
            with ctx.wrap_socket(socket.socket(), server_hostname=domain) as s:
                s.connect((domain, 443))
                cert = s.getpeercert()
            
            # فحص DNS
            dns_records = {
                'A': [str(r) for r in dns.resolver.resolve(domain, 'A')],
                'MX': [str(r) for r in dns.resolver.resolve(domain, 'MX')],
                'TXT': [str(r) for r in dns.resolver.resolve(domain, 'TXT')]
            }
            
            # معلومات WHOIS
            domain_info = whois.whois(domain)
            
            return {
                "ssl_valid": True,
                "ssl_expiry": cert['notAfter'],
                "dns_records": dns_records,
                "domain_info": {
                    "registrar": domain_info.registrar,
                    "creation_date": domain_info.creation_date,
                    "expiration_date": domain_info.expiration_date
                }
            }
        except Exception as e:
            return {"error": str(e)}

    async def take_screenshot(self, url):
        try:
            chrome_options = Options()
            chrome_options.add_argument('--headless')
            chrome_options.add_argument('--no-sandbox')
            chrome_options.add_argument('--disable-dev-shm-usage')
            
            driver = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options)
            driver.get(url)
            driver.set_window_size(1920, 1080)
            
            screenshot = driver.get_screenshot_as_png()
            driver.quit()
            
            return Image.open(io.BytesIO(screenshot))
        except Exception as e:
            return None

def main():
    st.title("🔍 محلل المواقع المتقدم")
    
    # إضافة قائمة جانبية
    with st.sidebar:
        selected = option_menu(
            menu_title="القائمة الرئيسية",
            options=["تحليل جديد", "التقارير السابقة", "الإعدادات"],
            icons=["search", "file-text", "gear"],
            menu_icon="cast",
            default_index=0,
        )
    
    if selected == "تحليل جديد":
        col1, col2 = st.columns([2, 1])
        
        with col1:
            url = st.text_input("أدخل رابط الموقع", "https://example.com")
            if st.button("بدء التحليل"):
                with st.spinner("جاري التحليل..."):
                    st_lottie(lottie_analyzing, height=200)
                    
                    analyzer = WebsiteAnalyzer()
                    
                    # تحليل متزامن
                    loop = asyncio.new_event_loop()
                    asyncio.set_event_loop(loop)
                    performance_data = loop.run_until_complete(analyzer.analyze_performance(url))
                    seo_data = loop.run_until_complete(analyzer.analyze_seo(url))
                    security_data = analyzer.analyze_security(url)
                    screenshot = loop.run_until_complete(analyzer.take_screenshot(url))
                    
                    # عرض النتائج
                    st.success("تم اكتمال التحليل!")
                    
                    # عرض البطاقات الإحصائية
                    cols = st.columns(3)
                    with cols[0]:
                        st.metric("زمن التحميل", f"{performance_data.get('load_time', 'N/A')}s")
                    with cols[1]:
                        st.metric("حجم الصفحة", f"{performance_data.get('page_size', 'N/A')} KB")
                    with cols[2]:
                        st.metric("الروابط الداخلية", seo_data.get('internal_links', 'N/A')['count'])
                    
                    # عرض تحليل SEO
                    with st.expander("تحليل SEO", expanded=True):
                        st.json(seo_data)
                        
                        # رسم بياني للعناوين
                        if 'headings' in seo_data and 'details' in seo_data['headings']:
                            fig = px.bar(
                                x=list(seo_data['headings']['details'].keys()),
                                y=list(seo_data['headings']['details'].values()),
                                title="توزيع العناوين",
                                labels={'x': 'نوع العنوان', 'y': 'العدد'}
                            )
                            st.plotly_chart(fig)
                    
                    # عرض تحليل الأمان
                    with st.expander("تحليل الأمان", expanded=True):
                        st.json(security_data)
                    
                    # عرض لقطة الشاشة
                    if screenshot:
                        st.image(screenshot, caption="لقطة شاشة للموقع", use_column_width=True)
        
        with col2:
            st.subheader("آخر التحليلات")
            # هنا يمكن إضافة قائمة بآخر المواقع التي تم تحليلها
    
    elif selected == "التقارير السابقة":
        st.subheader("التقارير السابقة")
        # هنا يمكن إضافة عرض للتقارير السابقة
    
    elif selected == "الإعدادات":
        st.subheader("إعدادات التحليل")
        # هنا يمكن إضافة إعدادات التحليل

if __name__ == "__main__":
    main()