From 6203717f7824d74c53f2cd9bbd74f1bb22d58771 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Mon, 20 Oct 2025 11:46:46 +0000 Subject: [PATCH 1/5] Initial plan From 31037771d9150f83b4bca4be0955fbc2a7e3739e Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Mon, 20 Oct 2025 11:55:03 +0000 Subject: [PATCH 2/5] Add comprehensive AI system audit tool with bilingual support Co-authored-by: wasalstor-web <230709381+wasalstor-web@users.noreply.github.com> --- .gitignore | 2 + README.md | 24 +- SYSTEM_AUDIT_GUIDE.md | 498 +++++++++++++++++++++++++ run-system-audit.sh | 86 +++++ system_audit.py | 730 +++++++++++++++++++++++++++++++++++++ tests/test_system_audit.py | 198 ++++++++++ 6 files changed, 1537 insertions(+), 1 deletion(-) create mode 100644 SYSTEM_AUDIT_GUIDE.md create mode 100755 run-system-audit.sh create mode 100755 system_audit.py create mode 100644 tests/test_system_audit.py diff --git a/.gitignore b/.gitignore index a6b37da..7cfd063 100644 --- a/.gitignore +++ b/.gitignore @@ -72,6 +72,8 @@ Desktop.ini # Project specific ai-agent-platform-archive-* finalization_report*.txt +system_audit_report.txt +system_audit_report.json # VPS Configuration (sensitive) .env diff --git a/README.md b/README.md index 04cd8c3..c29684f 100644 --- a/README.md +++ b/README.md @@ -19,11 +19,33 @@ The platform now includes DL+, a complete Arabic-first AI system that integrates 📖 **Key Documentation:** - **[Complete DL+ Documentation](DLPLUS_README.md)** -- **[Hostinger Command Execution Guide](HOSTINGER_COMMAND_EXECUTION.md)** ⭐ NEW! +- **[System Audit Guide](SYSTEM_AUDIT_GUIDE.md)** 🔍 NEW! +- **[Hostinger Command Execution Guide](HOSTINGER_COMMAND_EXECUTION.md)** - **[Command Examples](examples/hostinger_command_examples.py)** --- +## 🔍 NEW: Full System Audit Tool + +**نظام الفحص الشامل للذكاء الاصطناعي** + +Comprehensive system auditing tool that provides detailed reports on: +- ✅ System status and resource usage (CPU, RAM, Disk) +- 🧠 Active AI models (LLaMA, Qwen, GPT-4, Claude, etc.) +- 🌐 Connected websites and SSL certificates +- 🔗 API/ABI/Webhook status +- 📄 Pages and forms validation +- 🔌 External integrations (GitHub, Hostinger, Cloudflare) + +**Quick Audit:** +```bash +./run-system-audit.sh +``` + +**[Read the Complete Audit Guide →](SYSTEM_AUDIT_GUIDE.md)** + +--- + ## 🚀 Quick Start **The platform is live and accessible at:** diff --git a/SYSTEM_AUDIT_GUIDE.md b/SYSTEM_AUDIT_GUIDE.md new file mode 100644 index 0000000..5e3a929 --- /dev/null +++ b/SYSTEM_AUDIT_GUIDE.md @@ -0,0 +1,498 @@ +# 🔍 نظام الفحص الشامل للذكاء الاصطناعي +# Full AI System Audit Tool Documentation + +## نظرة عامة / Overview + +أداة فحص شاملة لنظام الذكاء الاصطناعي تقوم بفحص وتوثيق جميع جوانب النظام بما في ذلك: + +A comprehensive audit tool for the AI Agent Platform that checks and documents all aspects of the system including: + +- ✅ **حالة النظام المبرمج** / System Status - Server uptime, CPU, RAM, Disk usage +- 🧠 **أدوات الذكاء الاصطناعي** / Active AI Models - LLaMA, Qwen, Mistral, DeepSeek, GPT-4, Claude, etc. +- 🌐 **المواقع والأنظمة المرتبطة** / Connected Websites - GitHub Pages, domains, SSL certificates +- 🔗 **واجهات البرمجة** / API/ABI/Webhooks - FastAPI endpoints, webhook handlers +- 📄 **الصفحات والنماذج** / Pages and Forms - Frontend files, HTML forms +- 🔌 **الارتباطات الخارجية** / External Integrations - GitHub, Hostinger, Cloudflare, Telegram + +--- + +## 🚀 التشغيل السريع / Quick Start + +### الطريقة الأولى: استخدام السكريبت (مستحسن) + +**Method 1: Using Shell Script (Recommended)** + +```bash +# تشغيل الفحص الشامل +# Run comprehensive audit +./run-system-audit.sh +``` + +السكريبت سيقوم تلقائياً بـ: +- ✅ التحقق من Python وpip +- ✅ تثبيت المتطلبات المفقودة +- ✅ تشغيل الفحص +- ✅ عرض التقرير + +The script will automatically: +- ✅ Check for Python and pip +- ✅ Install missing requirements +- ✅ Run the audit +- ✅ Display the report + +### الطريقة الثانية: استخدام Python مباشرة + +**Method 2: Using Python Directly** + +```bash +# تثبيت المتطلبات +# Install requirements +pip3 install psutil httpx aiohttp + +# تشغيل الفحص +# Run audit +python3 system_audit.py +``` + +--- + +## 📋 المتطلبات / Requirements + +### البرمجيات الأساسية / Core Software +- Python 3.8 أو أحدث / Python 3.8+ +- pip (مدير الحزم) / pip (package manager) + +### المكتبات المطلوبة / Required Libraries +```bash +psutil>=5.9.0 # معلومات النظام / System info +httpx>=0.25.0 # طلبات HTTP / HTTP requests +aiohttp>=3.9.0 # طلبات HTTP غير متزامنة / Async HTTP +``` + +--- + +## 📊 التقارير المنتجة / Generated Reports + +يقوم النظام بإنشاء تقريرين: + +The system generates two reports: + +### 1. تقرير نصي / Text Report +**الملف / File:** `system_audit_report.txt` + +تقرير تفصيلي سهل القراءة بالعربية والإنجليزية يحتوي على: + +A detailed, human-readable report in Arabic and English containing: +- معلومات النظام الأساسية / Basic system information +- حالة الموارد / Resource status +- قائمة النماذج / Model listings +- حالة الاتصالات / Connection status +- ملخص شامل / Comprehensive summary + +### 2. تقرير JSON / JSON Report +**الملف / File:** `system_audit_report.json` + +تقرير بصيغة JSON للمعالجة البرمجية يحتوي على جميع البيانات المنظمة. + +A JSON-formatted report for programmatic processing containing all structured data. + +--- + +## 🔍 مكونات الفحص / Audit Components + +### 1️⃣ حالة النظام المبرمج / System Status + +**ماذا يتم فحصه؟ / What is checked?** + +- 🖥️ معلومات المنصة (نظام التشغيل، الإصدار) / Platform info (OS, version) +- ⏱️ وقت التشغيل / Uptime +- 💻 استخدام CPU (النسبة والأنوية) / CPU usage (percentage and cores) +- 🧠 استهلاك الذاكرة (الإجمالي، المستخدم، المتاح) / Memory usage (total, used, available) +- 💾 مساحة القرص (الإجمالي، المستخدم، المتاح) / Disk space (total, used, free) +- 🌐 معلومات الشبكة (اسم المضيف، IP المحلي) / Network info (hostname, local IP) + +**مثال على النتيجة / Example Output:** + +``` +🖥️ المنصة / Platform: Linux 6.14.0 +🐍 Python: 3.12.3 +⏱️ وقت التشغيل / Uptime: 1:23:45 + +💻 CPU: + - عدد الأنوية / Cores: 4 + - الاستخدام / Usage: 15.5% + +🧠 الذاكرة / Memory: + - الإجمالي / Total: 16.00 GB + - المستخدم / Used: 4.50 GB + - المتاح / Available: 11.50 GB + - النسبة / Percentage: 28.1% + +💾 القرص / Disk: + - الإجمالي / Total: 100.00 GB + - المستخدم / Used: 45.00 GB + - المتاح / Free: 55.00 GB + - النسبة / Percentage: 45.0% +``` + +--- + +### 2️⃣ أدوات الذكاء الاصطناعي المفعّلة / Active AI Models + +**ماذا يتم فحصه؟ / What is checked?** + +- 🧠 النماذج المكتشفة في الوثائق والتكوين / Models detected in docs and config +- ⚙️ حالة DL+ API (منفذ 8000) / DL+ API status (port 8000) +- 💬 حالة OpenWebUI (منفذ 3000) / OpenWebUI status (port 3000) +- ✅ استجابة النماذج / Model responsiveness + +**النماذج المدعومة / Supported Models:** + +- LLaMA / لاما +- Qwen +- Mistral +- DeepSeek +- GPT-4 +- Claude +- AraBERT / عربرت +- Gemini + +**مثال على النتيجة / Example Output:** + +``` +🧠 النماذج المكتشفة / Detected Models: + ✓ LLaMA + ✓ Qwen + ✓ GPT-4 + ✓ Claude + ✓ AraBERT + +⚙️ حالة الخدمات / Services Status: + - dlplus_api: ✅ نشط / Active + - openwebui: ✅ نشط / Active +``` + +--- + +### 3️⃣ المواقع والأنظمة المرتبطة / Connected Websites + +**ماذا يتم فحصه؟ / What is checked?** + +- 🌐 GitHub Pages (الرابط والوصول) / GitHub Pages (URL and accessibility) +- 🔒 شهادات SSL / SSL certificates +- 🔗 النطاقات المكتشفة في التكوين / Domains discovered in config +- 🔌 النقاط النهائية المحلية / Local endpoints + +**مثال على النتيجة / Example Output:** + +``` +🌐 GitHub Pages: + - الرابط / URL: https://wasalstor-web.github.io/AI-Agent-Platform/ + - الحالة / Status: ✅ متاح / Accessible + - SSL: ✅ HTTPS نشط / HTTPS Active + +🔗 النطاقات المكتشفة / Discovered Domains: + - github.com + - wasalstor-web.github.io + - your-domain.com + +🔌 النقاط النهائية المحلية / Local Endpoints: + - DL+ API: ✅ نشط / Active + - OpenWebUI: ✅ نشط / Active +``` + +--- + +### 4️⃣ الـ API / ABI / Webhooks + +**ماذا يتم فحصه؟ / What is checked?** + +- 🔗 نقاط FastAPI (/health, /api/status, /docs, etc.) / FastAPI endpoints +- 🪝 معالجات Webhooks / Webhook handlers +- 📡 حالة الاستجابة / Response status +- ⚙️ ملفات الخادم / Server files + +**النقاط المفحوصة / Checked Endpoints:** + +- `/health` - فحص الصحة / Health check +- `/api/status` - حالة API / API status +- `/api/models` - قائمة النماذج / Models list +- `/docs` - توثيق Swagger / Swagger docs +- `/openapi.json` - مواصفات OpenAPI / OpenAPI specs + +**مثال على النتيجة / Example Output:** + +``` +🔗 واجهات البرمجة / API Endpoints: + - /health: ✅ نشط / Active + - /api/status: ✅ نشط / Active + - /docs: ✅ نشط / Active + +🪝 Webhooks: + - github-webhook-handler.py: ✅ موجود / Present + - github-commander.py: ✅ موجود / Present +``` + +--- + +### 5️⃣ الصفحات والنماذج / Pages and Forms + +**ماذا يتم فحصه؟ / What is checked?** + +- 📄 ملفات HTML الرئيسية / Main HTML files +- 📝 عدد النماذج والحقول / Form and input counts +- 📊 أحجام الملفات / File sizes +- ✅ وجود الملفات / File existence + +**مثال على النتيجة / Example Output:** + +``` +📄 الواجهة الأمامية / Frontend: + - الملف / File: index.html + - الحجم / Size: 54.37 KB + - الحالة / Status: ✅ موجود / Present + +📝 النماذج / Forms: + - index.html: 3 نموذج / forms, 12 حقل / inputs +``` + +--- + +### 6️⃣ الارتباطات والربط الخارجي / External Integrations + +**ماذا يتم فحصه؟ / What is checked?** + +- 🐙 **GitHub:** ملفات المستودع، workflows، webhooks / Repository files, workflows, webhooks +- 🌐 **Hostinger:** سكريبتات النشر والإدارة / Deployment and management scripts +- ☁️ **Cloudflare:** الإشارات في التكوين / References in config +- 📱 **Telegram:** ملفات البوتات / Bot files + +**مثال على النتيجة / Example Output:** + +``` +🐙 GitHub: + - المستودع / Repository: wasalstor-web/AI-Agent-Platform + - الحالة / Status: ✅ نشط / Active + - الملفات / Files: 4 موجود / present + +🌐 Hostinger: + - الحالة / Status: ✅ مدمج / Integrated + - الملفات / Files: 4 موجود / present + +☁️ Cloudflare: + - الحالة / Status: ❌ غير مذكور / Not mentioned + +📱 Telegram: + - الحالة / Status: ❌ غير موجود / Not found +``` + +--- + +## 🧪 الاختبارات / Testing + +### تشغيل الاختبارات / Running Tests + +```bash +# تثبيت متطلبات الاختبار +# Install test requirements +pip3 install pytest pytest-asyncio + +# تشغيل جميع الاختبارات +# Run all tests +python3 -m pytest tests/test_system_audit.py -v + +# تشغيل اختبار محدد +# Run specific test +python3 -m pytest tests/test_system_audit.py::test_check_system_status -v +``` + +### الاختبارات المتاحة / Available Tests + +1. ✅ `test_system_audit_initialization` - تهيئة الأداة / Tool initialization +2. ✅ `test_check_system_status` - فحص حالة النظام / System status check +3. ✅ `test_check_ai_models` - كشف النماذج / Model detection +4. ✅ `test_check_websites` - فحص المواقع / Website check +5. ✅ `test_check_apis` - فحص APIs / API check +6. ✅ `test_check_pages` - فحص الصفحات / Page check +7. ✅ `test_check_integrations` - فحص الارتباطات / Integration check +8. ✅ `test_run_full_audit` - تشغيل فحص كامل / Full audit run +9. ✅ `test_generate_report` - توليد التقرير / Report generation +10. ✅ `test_save_report` - حفظ التقرير / Report saving + +--- + +## 📁 الملفات / Files + +``` +AI-Agent-Platform/ +├── system_audit.py # الأداة الرئيسية / Main audit tool +├── run-system-audit.sh # سكريبت التشغيل / Execution script +├── tests/ +│ └── test_system_audit.py # ملف الاختبارات / Test file +├── SYSTEM_AUDIT_GUIDE.md # هذا الدليل / This guide +├── system_audit_report.txt # تقرير نصي (مُنشأ) / Text report (generated) +└── system_audit_report.json # تقرير JSON (مُنشأ) / JSON report (generated) +``` + +--- + +## 🔧 الاستخدام البرمجي / Programmatic Usage + +### استيراد واستخدام الأداة في Python + +**Import and use in Python:** + +```python +import asyncio +from system_audit import SystemAudit + +async def run_audit(): + # إنشاء كائن الفحص + # Create audit instance + audit = SystemAudit() + + # تشغيل الفحص الكامل + # Run full audit + results = await audit.run_full_audit() + + # توليد التقرير + # Generate report + report = audit.generate_report() + print(report) + + # حفظ التقارير + # Save reports + txt_path, json_path = audit.save_report() + print(f"Reports saved: {txt_path}, {json_path}") + + # الوصول إلى البيانات + # Access data + print(f"Detected models: {results['ai_models']['detected_models']}") + print(f"CPU usage: {results['system_status']['cpu']['usage_percent']}%") + +# تشغيل +# Run +asyncio.run(run_audit()) +``` + +### فحص مكونات محددة / Check Specific Components + +```python +async def check_specific(): + audit = SystemAudit() + + # فحص النظام فقط + # Check system only + system_status = await audit.check_system_status() + print(f"CPU: {system_status['cpu']['usage_percent']}%") + + # فحص النماذج فقط + # Check models only + models = await audit.check_ai_models() + print(f"Models: {models['detected_models']}") + + # فحص المواقع فقط + # Check websites only + websites = await audit.check_websites() + print(f"GitHub Pages: {websites['github_pages']}") + +asyncio.run(check_specific()) +``` + +--- + +## 🔒 الأمان / Security + +### المعلومات الحساسة / Sensitive Information + +الأداة **لا تجمع أو تعرض**: + +The tool **does NOT collect or display**: +- ❌ كلمات المرور / Passwords +- ❌ مفاتيح API / API keys +- ❌ معلومات اعتماد / Credentials +- ❌ بيانات شخصية / Personal data + +### التقارير / Reports + +- ✅ التقارير المُنشأة تحتوي فقط على معلومات النظام العامة / Reports contain only general system info +- ✅ يتم تجاهل ملفات .env تلقائياً / .env files are automatically ignored +- ✅ التقارير مستبعدة من Git (.gitignore) / Reports excluded from Git (.gitignore) + +--- + +## 🛠️ استكشاف الأخطاء / Troubleshooting + +### المشكلة: الفحص لا يعمل + +**Problem: Audit not running** + +```bash +# تحقق من Python +# Check Python +python3 --version + +# تحقق من pip +# Check pip +pip3 --version + +# أعد تثبيت المتطلبات +# Reinstall requirements +pip3 install --upgrade psutil httpx aiohttp +``` + +### المشكلة: النماذج غير مكتشفة + +**Problem: Models not detected** + +- تأكد من وجود ملفات README.md و DLPLUS_README.md / Ensure README files exist +- تحقق من ملفات التكوين في dlplus/config / Check config files in dlplus/config +- راجع محتوى index.html / Review index.html content + +### المشكلة: APIs غير متوفرة + +**Problem: APIs not available** + +```bash +# تحقق من تشغيل DL+ API +# Check if DL+ API is running +curl http://localhost:8000/health + +# تحقق من OpenWebUI +# Check OpenWebUI +curl http://localhost:3000 + +# شغل الخدمات +# Start services +./start-dlplus.sh +``` + +--- + +## 📚 مراجع إضافية / Additional References + +- **[README.md](README.md)** - نظرة عامة على المشروع / Project overview +- **[DLPLUS_README.md](DLPLUS_README.md)** - دليل نظام DL+ / DL+ system guide +- **[STATUS.md](STATUS.md)** - حالة المشروع / Project status +- **[DEPLOYMENT.md](DEPLOYMENT.md)** - دليل النشر / Deployment guide + +--- + +## 🎯 الخلاصة / Summary + +أداة الفحص الشامل توفر: + +The comprehensive audit tool provides: + +✅ **فحص كامل للنظام** / Complete system inspection +✅ **تقارير تفصيلية** / Detailed reports +✅ **دعم ثنائي اللغة** / Bilingual support +✅ **سهولة الاستخدام** / Easy to use +✅ **اختبارات شاملة** / Comprehensive tests +✅ **توثيق واضح** / Clear documentation + +--- + +**آخر تحديث / Last Updated:** 2025-10-20 +**الإصدار / Version:** 1.0.0 +**الحالة / Status:** ✅ مكتمل / Complete diff --git a/run-system-audit.sh b/run-system-audit.sh new file mode 100755 index 0000000..5e2ef49 --- /dev/null +++ b/run-system-audit.sh @@ -0,0 +1,86 @@ +#!/bin/bash + +# نظام فحص شامل للذكاء الاصطناعي +# Full AI System Audit Tool + +# الألوان +GREEN="\033[0;32m" +BLUE="\033[0;34m" +YELLOW="\033[1;33m" +RED="\033[0;31m" +NC="\033[0m" # لا لون + +echo -e "${BLUE}================================================${NC}" +echo -e "${BLUE}🔍 نظام فحص شامل للذكاء الاصطناعي${NC}" +echo -e "${BLUE}🔍 Full AI System Audit Tool${NC}" +echo -e "${BLUE}================================================${NC}" +echo "" + +# التحقق من Python +if ! command -v python3 &> /dev/null; then + echo -e "${RED}❌ Python 3 غير مثبت / Python 3 not installed${NC}" + exit 1 +fi + +echo -e "${GREEN}✓ Python 3 موجود / Python 3 found${NC}" + +# التحقق من pip +if ! command -v pip3 &> /dev/null && ! command -v pip &> /dev/null; then + echo -e "${RED}❌ pip غير مثبت / pip not installed${NC}" + exit 1 +fi + +echo -e "${GREEN}✓ pip موجود / pip found${NC}" + +# تثبيت المتطلبات إذا لزم الأمر +echo -e "\n${YELLOW}📦 التحقق من المتطلبات / Checking requirements...${NC}" + +# قائمة المكتبات المطلوبة +REQUIRED_PACKAGES=( + "psutil" + "httpx" + "aiohttp" +) + +MISSING_PACKAGES=() + +for package in "${REQUIRED_PACKAGES[@]}"; do + if ! python3 -c "import $package" &> /dev/null; then + MISSING_PACKAGES+=("$package") + fi +done + +if [ ${#MISSING_PACKAGES[@]} -gt 0 ]; then + echo -e "${YELLOW}⚠️ بعض المكتبات مفقودة / Some packages are missing${NC}" + echo -e "${YELLOW}📥 جاري التثبيت / Installing: ${MISSING_PACKAGES[*]}${NC}" + + if command -v pip3 &> /dev/null; then + pip3 install ${MISSING_PACKAGES[@]} --quiet + else + pip install ${MISSING_PACKAGES[@]} --quiet + fi + + if [ $? -eq 0 ]; then + echo -e "${GREEN}✓ تم تثبيت المكتبات بنجاح / Packages installed successfully${NC}" + else + echo -e "${RED}❌ فشل تثبيت المكتبات / Failed to install packages${NC}" + echo -e "${YELLOW}⚠️ سيتم محاولة تشغيل الفحص على أي حال...${NC}" + fi +else + echo -e "${GREEN}✓ جميع المكتبات موجودة / All packages present${NC}" +fi + +# تشغيل الفحص +echo -e "\n${BLUE}🚀 بدء الفحص الشامل / Starting audit...${NC}\n" + +python3 system_audit.py + +EXIT_CODE=$? + +if [ $EXIT_CODE -eq 0 ]; then + echo -e "\n${GREEN}✅ الفحص اكتمل بنجاح / Audit completed successfully${NC}" +else + echo -e "\n${RED}❌ حدث خطأ في الفحص / Audit failed with error code: $EXIT_CODE${NC}" +fi + +exit $EXIT_CODE diff --git a/system_audit.py b/system_audit.py new file mode 100755 index 0000000..1ecdca5 --- /dev/null +++ b/system_audit.py @@ -0,0 +1,730 @@ +#!/usr/bin/env python3 +""" +نظام فحص شامل للذكاء الاصطناعي +Full AI System Audit Tool + +This tool performs a comprehensive audit of the AI Agent Platform including: +- System status and resource usage +- Active AI models and their responsiveness +- Connected websites and endpoints +- API/ABI/Webhook status +- Pages and forms validation +- External integrations mapping +""" + +import asyncio +import json +import os +import platform +import psutil +import socket +import subprocess +import sys +import time +from datetime import datetime +from pathlib import Path +from typing import Dict, List, Any, Optional +import httpx +import aiohttp +import ssl +import re + +class SystemAudit: + """Comprehensive system audit tool""" + + def __init__(self): + self.results = { + 'timestamp': datetime.now().isoformat(), + 'system_status': {}, + 'ai_models': {}, + 'websites': {}, + 'apis': {}, + 'pages': {}, + 'integrations': {} + } + self.project_root = Path(__file__).parent + + async def run_full_audit(self) -> Dict[str, Any]: + """Run complete system audit""" + print("🔍 بدء الفحص الشامل للنظام...") + print("🔍 Starting comprehensive system audit...\n") + + # 1. System Status + print("1️⃣ فحص حالة النظام...") + print("1️⃣ Checking system status...") + self.results['system_status'] = await self.check_system_status() + + # 2. AI Models + print("\n2️⃣ فحص نماذج الذكاء الاصطناعي...") + print("2️⃣ Checking AI models...") + self.results['ai_models'] = await self.check_ai_models() + + # 3. Websites and Endpoints + print("\n3️⃣ فحص المواقع والنقاط النهائية...") + print("3️⃣ Checking websites and endpoints...") + self.results['websites'] = await self.check_websites() + + # 4. APIs and Webhooks + print("\n4️⃣ فحص واجهات البرمجة...") + print("4️⃣ Checking APIs and webhooks...") + self.results['apis'] = await self.check_apis() + + # 5. Pages and Forms + print("\n5️⃣ فحص الصفحات والنماذج...") + print("5️⃣ Checking pages and forms...") + self.results['pages'] = await self.check_pages() + + # 6. External Integrations + print("\n6️⃣ فحص الارتباطات الخارجية...") + print("6️⃣ Checking external integrations...") + self.results['integrations'] = await self.check_integrations() + + return self.results + + async def check_system_status(self) -> Dict[str, Any]: + """Check system status and resource usage""" + status = {} + + try: + # Basic system info + status['platform'] = { + 'system': platform.system(), + 'release': platform.release(), + 'version': platform.version(), + 'machine': platform.machine(), + 'processor': platform.processor(), + 'python_version': sys.version + } + + # Uptime + try: + boot_time = datetime.fromtimestamp(psutil.boot_time()) + uptime = datetime.now() - boot_time + status['uptime'] = { + 'boot_time': boot_time.isoformat(), + 'uptime_seconds': uptime.total_seconds(), + 'uptime_human': str(uptime) + } + except Exception as e: + status['uptime'] = {'error': str(e)} + + # CPU + try: + status['cpu'] = { + 'count': psutil.cpu_count(), + 'usage_percent': psutil.cpu_percent(interval=1), + 'per_cpu': psutil.cpu_percent(interval=1, percpu=True) + } + except Exception as e: + status['cpu'] = {'error': str(e)} + + # Memory + try: + mem = psutil.virtual_memory() + status['memory'] = { + 'total_gb': round(mem.total / (1024**3), 2), + 'available_gb': round(mem.available / (1024**3), 2), + 'used_gb': round(mem.used / (1024**3), 2), + 'percent': mem.percent + } + except Exception as e: + status['memory'] = {'error': str(e)} + + # Disk + try: + disk = psutil.disk_usage('/') + status['disk'] = { + 'total_gb': round(disk.total / (1024**3), 2), + 'used_gb': round(disk.used / (1024**3), 2), + 'free_gb': round(disk.free / (1024**3), 2), + 'percent': disk.percent + } + except Exception as e: + status['disk'] = {'error': str(e)} + + # Network + try: + hostname = socket.gethostname() + local_ip = socket.gethostbyname(hostname) + status['network'] = { + 'hostname': hostname, + 'local_ip': local_ip + } + except Exception as e: + status['network'] = {'error': str(e)} + + status['status'] = '✅ نشط / Active' + + except Exception as e: + status['error'] = str(e) + status['status'] = '❌ خطأ / Error' + + return status + + async def check_ai_models(self) -> Dict[str, Any]: + """Check active AI models""" + models = { + 'detected_models': [], + 'dlplus_models': [], + 'openwebui_models': [], + 'status': {} + } + + try: + # Check DL+ models from config + dlplus_config = self.project_root / 'dlplus' / 'config' + if dlplus_config.exists(): + config_files = list(dlplus_config.glob('*.yaml')) + list(dlplus_config.glob('*.yml')) + for config_file in config_files: + try: + with open(config_file, 'r', encoding='utf-8') as f: + content = f.read() + # Extract model references + if 'llama' in content.lower(): + models['dlplus_models'].append('LLaMA') + if 'qwen' in content.lower(): + models['dlplus_models'].append('Qwen') + if 'mistral' in content.lower(): + models['dlplus_models'].append('Mistral') + if 'deepseek' in content.lower(): + models['dlplus_models'].append('DeepSeek') + except Exception as e: + pass + + # Check README and documentation for model references + doc_files = [ + 'README.md', + 'DLPLUS_README.md', + 'OPENWEBUI.md', + 'index.html' + ] + + all_models = set() + for doc_file in doc_files: + doc_path = self.project_root / doc_file + if doc_path.exists(): + try: + with open(doc_path, 'r', encoding='utf-8') as f: + content = f.read().lower() + + # Model detection patterns + model_patterns = { + 'LLaMA': r'llama|لاما', + 'Qwen': r'qwen', + 'Mistral': r'mistral', + 'DeepSeek': r'deepseek', + 'GPT-4': r'gpt-?4', + 'Claude': r'claude', + 'AraBERT': r'arabert|عربرت', + 'Gemini': r'gemini' + } + + for model_name, pattern in model_patterns.items(): + if re.search(pattern, content): + all_models.add(model_name) + except Exception: + pass + + models['detected_models'] = sorted(list(all_models)) + + # Check if DL+ system is running + try: + async with aiohttp.ClientSession() as session: + async with session.get('http://localhost:8000/health', timeout=aiohttp.ClientTimeout(total=5)) as resp: + if resp.status == 200: + models['status']['dlplus_api'] = '✅ نشط / Active' + else: + models['status']['dlplus_api'] = f'⚠️ استجابة غير متوقعة / Unexpected response: {resp.status}' + except Exception as e: + models['status']['dlplus_api'] = f'❌ غير متاح / Not available: {str(e)}' + + # Check OpenWebUI + try: + async with aiohttp.ClientSession() as session: + async with session.get('http://localhost:3000', timeout=aiohttp.ClientTimeout(total=5)) as resp: + if resp.status in [200, 301, 302, 404]: + models['status']['openwebui'] = '✅ نشط / Active' + else: + models['status']['openwebui'] = f'⚠️ استجابة غير متوقعة / Unexpected response: {resp.status}' + except Exception as e: + models['status']['openwebui'] = f'❌ غير متاح / Not available: {str(e)}' + + except Exception as e: + models['error'] = str(e) + + return models + + async def check_websites(self) -> Dict[str, Any]: + """Check connected websites and endpoints""" + websites = { + 'github_pages': {}, + 'domains': [], + 'ssl_status': {}, + 'endpoints': [] + } + + try: + # GitHub Pages + github_url = 'https://wasalstor-web.github.io/AI-Agent-Platform/' + try: + async with aiohttp.ClientSession() as session: + async with session.get(github_url, timeout=aiohttp.ClientTimeout(total=10)) as resp: + websites['github_pages'] = { + 'url': github_url, + 'status': resp.status, + 'ssl': '✅ HTTPS نشط / HTTPS Active', + 'accessible': '✅ متاح / Accessible' if resp.status == 200 else '❌ غير متاح / Not accessible' + } + except Exception as e: + websites['github_pages'] = { + 'url': github_url, + 'error': str(e), + 'accessible': '❌ غير متاح / Not accessible' + } + + # Check for domain references in config files + config_files = ['.env', '.env.example', 'README.md', 'STATUS.md'] + for config_file in config_files: + config_path = self.project_root / config_file + if config_path.exists(): + try: + with open(config_path, 'r', encoding='utf-8') as f: + content = f.read() + # Extract domain patterns + domain_patterns = [ + r'https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', + r'[a-zA-Z0-9.-]+\.space', + r'[a-zA-Z0-9.-]+\.com', + r'[a-zA-Z0-9.-]+\.io' + ] + for pattern in domain_patterns: + matches = re.findall(pattern, content) + for match in matches: + if match not in websites['domains']: + websites['domains'].append(match) + except Exception: + pass + + # Local endpoints + local_endpoints = [ + ('http://localhost:8000', 'DL+ API'), + ('http://localhost:3000', 'OpenWebUI'), + ('http://localhost:8080', 'Alternative Port'), + ('http://127.0.0.1:8000', 'DL+ API (localhost)') + ] + + for url, name in local_endpoints: + try: + async with aiohttp.ClientSession() as session: + async with session.get(url, timeout=aiohttp.ClientTimeout(total=2)) as resp: + websites['endpoints'].append({ + 'name': name, + 'url': url, + 'status': resp.status, + 'accessible': '✅ نشط / Active' + }) + except Exception as e: + websites['endpoints'].append({ + 'name': name, + 'url': url, + 'error': str(e), + 'accessible': '❌ غير نشط / Inactive' + }) + + except Exception as e: + websites['error'] = str(e) + + return websites + + async def check_apis(self) -> Dict[str, Any]: + """Check API/ABI/Webhook status""" + apis = { + 'fastapi': {}, + 'webhooks': [], + 'endpoints': [] + } + + try: + # Check FastAPI + fastapi_endpoints = [ + '/health', + '/api/status', + '/api/models', + '/docs', + '/openapi.json' + ] + + base_url = 'http://localhost:8000' + for endpoint in fastapi_endpoints: + try: + async with aiohttp.ClientSession() as session: + async with session.get(f'{base_url}{endpoint}', timeout=aiohttp.ClientTimeout(total=5)) as resp: + apis['endpoints'].append({ + 'endpoint': endpoint, + 'url': f'{base_url}{endpoint}', + 'status': resp.status, + 'accessible': '✅ نشط / Active' if resp.status in [200, 404] else '⚠️ تحذير / Warning' + }) + except Exception as e: + apis['endpoints'].append({ + 'endpoint': endpoint, + 'url': f'{base_url}{endpoint}', + 'error': str(e), + 'accessible': '❌ غير متاح / Not available' + }) + + # Check for webhook configurations + webhook_files = ['github-webhook-handler.py', 'github-commander.py'] + for webhook_file in webhook_files: + webhook_path = self.project_root / webhook_file + if webhook_path.exists(): + apis['webhooks'].append({ + 'file': webhook_file, + 'exists': True, + 'status': '✅ موجود / Present' + }) + + # Check API server file + api_server = self.project_root / 'api' / 'server.py' + if api_server.exists(): + apis['fastapi'] = { + 'server_file': 'api/server.py', + 'exists': True, + 'status': '✅ موجود / Present' + } + + except Exception as e: + apis['error'] = str(e) + + return apis + + async def check_pages(self) -> Dict[str, Any]: + """Check pages and forms""" + pages = { + 'frontend': {}, + 'forms': [], + 'files': [] + } + + try: + # Check main HTML file + index_html = self.project_root / 'index.html' + if index_html.exists(): + try: + with open(index_html, 'r', encoding='utf-8') as f: + content = f.read() + pages['frontend'] = { + 'file': 'index.html', + 'size_kb': round(len(content) / 1024, 2), + 'exists': True, + 'status': '✅ موجود / Present' + } + + # Check for forms + form_count = content.count('