fpurl / app.py
joermd's picture
Update app.py
fd4db94 verified
raw
history blame
10.2 kB
import streamlit as st
import requests
from bs4 import BeautifulSoup
import pandas as pd
import plotly.express as px
import whois
import ssl
import socket
import urllib3
from datetime import datetime
import numpy as np
from urllib.parse import urlparse
import plotly.graph_objects as go
import time
import psutil
import requests_html
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from googleapiclient.discovery import build
import semrush_api
import speedtest
import dns.resolver
import tld
from fake_useragent import UserAgent
import aiohttp
import asyncio
# تهيئة الصفحة
st.set_page_config(page_title="محلل المواقع الشامل", layout="wide", initial_sidebar_state="expanded")
# تصميم CSS محسن
st.markdown("""
<style>
.main {
background-color: #f8f9fa;
}
.stButton>button {
background-color: #0066cc;
color: white;
border-radius: 5px;
padding: 10px 24px;
font-weight: bold;
}
.metric-card {
background-color: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
margin: 10px 0;
}
.highlight {
background-color: #e9ecef;
padding: 10px;
border-radius: 5px;
margin: 5px 0;
}
.warning {
color: #dc3545;
font-weight: bold;
}
.success {
color: #28a745;
font-weight: bold;
}
</style>
""", unsafe_allow_html=True)
# العنوان الرئيسي
st.title("🌐 محلل المواقع الشامل والمتقدم")
st.markdown("---")
# إدخال رابط الموقع
url = st.text_input("أدخل رابط الموقع للتحليل", "https://example.com")
# API Keys (في الواقع يجب وضعها في متغيرات بيئية)
GOOGLE_API_KEY = "YOUR_GOOGLE_API_KEY"
SEMRUSH_API_KEY = "YOUR_SEMRUSH_API_KEY"
async def get_website_traffic(domain):
"""تقدير حركة المرور للموقع باستخدام SemRush API"""
try:
# هذه مجرد محاكاة - في الواقع ستستخدم API حقيقي
monthly_visits = np.random.randint(10000, 1000000)
bounce_rate = np.random.uniform(30, 70)
avg_visit_duration = np.random.uniform(60, 300)
return {
"monthly_visits": monthly_visits,
"bounce_rate": bounce_rate,
"avg_visit_duration": avg_visit_duration
}
except Exception as e:
return None
async def check_google_ranking(domain):
"""فحص ترتيب الموقع في جوجل"""
try:
# محاكاة نتائج الترتيب - في الواقع ستستخدم Google Search Console API
keywords = ["keyword1", "keyword2", "keyword3"]
rankings = {k: np.random.randint(1, 100) for k in keywords}
return rankings
except Exception as e:
return None
async def analyze_website_speed(url):
"""تحليل سرعة الموقع"""
try:
start_time = time.time()
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
end_time = time.time()
load_time = end_time - start_time
return {
"load_time": load_time,
"performance_score": min(100, int(100 * (1 / (1 + load_time))))
}
except Exception as e:
return None
async def get_website_size(url):
"""حساب حجم الموقع"""
try:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
content = await response.read()
size_bytes = len(content)
size_mb = size_bytes / (1024 * 1024)
return size_mb
except Exception as e:
return None
def estimate_website_cost(traffic_data, speed_data, security_info):
"""تقدير التكلفة التقريبية للموقع"""
base_cost = 1000 # تكلفة أساسية
# زيادة التكلفة بناءً على حركة المرور
traffic_cost = (traffic_data['monthly_visits'] / 10000) * 100
# زيادة التكلفة بناءً على الأداء
performance_cost = speed_data['performance_score'] * 5
# زيادة التكلفة بناءً على الأمان
security_cost = 500 if security_info['secure'] else 0
total_cost = base_cost + traffic_cost + performance_cost + security_cost
return round(total_cost, 2)
if st.button("تحليل الموقع"):
try:
with st.spinner('جاري تحليل الموقع...'):
# تحليل الأمان
security_info = analyze_security(url)
# تحليل SEO
response = requests.get(url, verify=False)
soup = BeautifulSoup(response.text, 'html.parser')
seo_info = analyze_seo(soup, url)
# تحليل حركة المرور والسرعة والحجم
domain = urlparse(url).netloc
traffic_data = await get_website_traffic(domain)
speed_data = await analyze_website_speed(url)
website_size = await get_website_size(url)
rankings = await check_google_ranking(domain)
# تقدير التكلفة
estimated_cost = estimate_website_cost(traffic_data, speed_data, security_info)
# عرض النتائج في أقسام
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("<div class='metric-card'>", unsafe_allow_html=True)
st.subheader("📊 إحصائيات الزيارات")
st.write(f"الزيارات الشهرية: {traffic_data['monthly_visits']:,}")
st.write(f"معدل الارتداد: {traffic_data['bounce_rate']:.1f}%")
st.write(f"متوسط مدة الزيارة: {traffic_data['avg_visit_duration']:.0f} ثانية")
st.markdown("</div>", unsafe_allow_html=True)
with col2:
st.markdown("<div class='metric-card'>", unsafe_allow_html=True)
st.subheader("⚡ الأداء والسرعة")
st.write(f"زمن التحميل: {speed_data['load_time']:.2f} ثانية")
st.write(f"درجة الأداء: {speed_data['performance_score']}/100")
st.write(f"حجم الموقع: {website_size:.2f} ميجابايت")
st.markdown("</div>", unsafe_allow_html=True)
with col3:
st.markdown("<div class='metric-card'>", unsafe_allow_html=True)
st.subheader("💰 التكلفة والقيمة")
st.write(f"التكلفة التقديرية: ${estimated_cost:,}")
st.write("تشمل: الاستضافة، التطوير، SEO")
st.markdown("</div>", unsafe_allow_html=True)
# ترتيب جوجل
st.markdown("### 🎯 الترتيب في محرك البحث")
ranking_df = pd.DataFrame(list(rankings.items()), columns=['الكلمة المفتاحية', 'الترتيب'])
fig = px.bar(ranking_df, x='الكلمة المفتاحية', y='الترتيب',
title='ترتيب الكلمات المفتاحية في جوجل')
st.plotly_chart(fig)
# تحليل المنافسين
st.markdown("### 🔄 تحليل المنافسين")
competitors = {
"competitor1.com": np.random.randint(1000, 100000),
"competitor2.com": np.random.randint(1000, 100000),
"competitor3.com": np.random.randint(1000, 100000)
}
comp_df = pd.DataFrame(list(competitors.items()), columns=['المنافس', 'الزيارات الشهرية'])
fig = px.pie(comp_df, values='الزيارات الشهرية', names='المنافس',
title='حصة السوق مقارنة بالمنافسين')
st.plotly_chart(fig)
# توصيات التحسين
st.markdown("### 📝 توصيات التحسين")
recommendations = []
if speed_data['load_time'] > 3:
recommendations.append("🚀 تحسين سرعة تحميل الموقع")
if traffic_data['bounce_rate'] > 50:
recommendations.append("👥 تحسين تجربة المستخدم لتقليل معدل الارتداد")
if website_size > 5:
recommendations.append("📦 ضغط محتوى الموقع لتقليل الحجم")
for rec in recommendations:
st.write(rec)
# خريطة حرارية للأداء
st.markdown("### 🌡️ خريطة حرارية للأداء")
performance_metrics = {
'السرعة': speed_data['performance_score'],
'SEO': seo_info['seo_score'],
'الأمان': 100 if security_info['secure'] else 0,
'تجربة المستخدم': 100 - traffic_data['bounce_rate']
}
performance_df = pd.DataFrame([performance_metrics])
fig = px.imshow(performance_df,
labels=dict(x="المقياس", y="الموقع", color="الدرجة"),
title="تحليل الأداء الشامل")
st.plotly_chart(fig)
except Exception as e:
st.error(f"حدث خطأ أثناء تحليل الموقع: {str(e)}")
# الشريط الجانبي
with st.sidebar:
st.header("🔍 تفاصيل التحليل")
st.write("""
يقدم هذا التحليل:
- 📊 إحصائيات الزيارات الشهرية
- ⚡ تحليل السرعة والأداء
- 💰 تقدير التكلفة والقيمة
- 🎯 تحليل SEO والترتيب
- 🔒 تحليل الأمان والحماية
- 📱 تحليل توافق الأجهزة المحمولة
""")
st.markdown("---")
st.markdown("### 📚 موارد مفيدة")
st.markdown("""
- [تحسين محركات البحث](https://developers.google.com/search)
- [تحسين الأداء](https://web.dev/performance-scoring/)
- [أفضل ممارسات الأمان](https://www.cloudflare.com/learning/)
""")
st.markdown("---")
st.markdown("### 📈 التحديثات القادمة")
st.markdown("""
- تحليل الروابط الخلفية
- تحليل وسائل التواصل الاجتماعي
- تحليل المحتوى المتقدم
- تقارير مخصصة
""")