Spaces:
Runtime error

File size: 5,521 Bytes
8d7cec1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import logging
import hashlib
import secrets
from datetime import datetime, timedelta
from typing import Optional, Dict, Any, List
import bcrypt
import json
from config import config

# إعداد التسجيل
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('logs/app.log'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

def generate_secure_token(length: int = 32) -> str:
    """توليد رمز أمني عشوائي"""
    return secrets.token_urlsafe(length)

def hash_password(password: str) -> str:
    """تشفير كلمة المرور"""
    return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')

def verify_password(password: str, hashed: str) -> bool:
    """التحقق من كلمة المرور"""
    return bcrypt.checkpw(password.encode('utf-8'), hashed.encode('utf-8'))

def validate_file_extension(filename: str) -> bool:
    """التحقق من نوع الملف المسموح به"""
    allowed_extensions = config.ALLOWED_EXTENSIONS
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in allowed_extensions

def sanitize_filename(filename: str) -> str:
    """تنظيف اسم الملف"""
    # إزالة الأحرف غير المسموح بها
    import re
    return re.sub(r'[^\w\-_\.]', '_', filename)

def create_backup_path() -> str:
    """إنشاء مسار النسخ الاحتياطي"""
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    backup_dir = os.path.join(config.BACKUP_PATH, f"backup_{timestamp}")
    os.makedirs(backup_dir, exist_ok=True)
    return backup_dir

def calculate_file_hash(filepath: str) -> str:
    """حساب تجزئة الملف"""
    hash_sha256 = hashlib.sha256()
    with open(filepath, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_sha256.update(chunk)
    return hash_sha256.hexdigest()

def setup_logging():
    """إعداد نظام التسجيل"""
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=[
            logging.FileHandler('logs/app.log'),
            logging.StreamHandler()
        ]
    )
    return logging.getLogger(__name__)

def get_current_timestamp() -> str:
    """الحصول على الطابع الزمني الحالي"""
    return datetime.now().isoformat()

def extract_risk_indicators(text: str) -> Dict[str, Any]:
    """استخراج مؤشرات المخاطر من النص"""
    indicators = {
        'attack_words': [],
        'security_keywords': [],
        'financial_indicators': [],
        'time_indicators': []
    }
    
    attack_terms = ['attack', 'war', 'conflict', 'battle', 'combat', 'military', 'force', 'threat', 'danger']
    security_terms = ['security', 'safety', 'protection', 'threat', 'risk', 'danger', 'secure', 'protected']
    
    text_lower = text.lower()
    
    for term in attack_terms:
        if term in text_lower:
            indicators['attack_words'].append(term)
    
    for term in security_terms:
        if term in text_lower:
            indicators['security_keywords'].append(term)
    
    return indicators

def safe_file_operation(func):
    """ديكورات لحماية عمليات الملفات"""
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            logger.error(f"Error in file operation: {str(e)}")
            raise
    return wrapper

def validate_input_data(data: Dict[str, Any]) -> bool:
    """التحقق من صحة بيانات الإدخال"""
    try:
        # التحقق من الحقول المطلوبة
        required_fields = ['input_type', 'input_content']
        for field in required_fields:
            if field not in data or not data[field]:
                return False
        
        # التحقق من نوع المدخل
        allowed_types = ['text', 'image', 'audio', 'video']
        if data.get('input_type') not in allowed_types:
            return False
        
        # التحقق من حجم المحتوى
        if len(str(data.get('input_content', ''))) > 100000:  # 100KB
            return False
            
        return True
    except Exception as e:
        logger.error(f"Error validating input  {str(e)}")
        return False

def format_response(success: bool, message: str, data: Optional[Dict] = None) -> Dict[str, Any]:
    """تنسيق الاستجابة"""
    response = {
        "success": success,
        "message": message
    }
    if 
        response["data"] = data
    return response

def get_system_health() -> Dict[str, Any]:
    """الحصول على حالة النظام"""
    try:
        import psutil
        import platform
        
        # معلومات النظام
        cpu_percent = psutil.cpu_percent(interval=1)
        memory = psutil.virtual_memory()
        disk = psutil.disk_usage('/')
        
        return {
            "system": platform.system(),
            "cpu_percent": cpu_percent,
            "memory_percent": memory.percent,
            "disk_percent": (disk.used / disk.total) * 100,
            "timestamp": datetime.now().isoformat()
        }
    except Exception as e:
        logger.error(f"Error getting system health: {str(e)}")
        return {"error": "Unable to get system health"}