Download utils.py from killerwar/new1: direct link, hf CLI and curl.
- Browser
- Download file 5.52 kB
-
https://huggingface.co/spaces/killerwar/new1/resolve/main/utils.py
- Command line
-
hf download hf://spaces/killerwar/new1/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/killerwar/new1/resolve/main/utils.py
5.52 kB
| 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"} |