File size: 8,755 Bytes
3e3d3de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Quick setup script for Hugging Face tokens
سكريپت إعداد سريع لرموز Hugging Face

This script loads tokens from environment variables only.
No hardcoded tokens are included for security.
"""

import os
import sys
from pathlib import Path

# Add src to path
sys.path.insert(0, str(Path(__file__).parent / "src"))

def setup_tokens():
    """Setup tokens from environment variables"""
    
    print("🔑 إعداد رموز Hugging Face")
    print("=" * 50)
    print("📝 ملاحظة: يجب إضافة الرموز في متغيرات البيئة:")
    print("   - HF_TOKEN_READ: رمز القراءة")
    print("   - HF_TOKEN_WRITE: رمز الكتابة") 
    print("   - HF_TOKEN_FINE_GRAINED: رمز مخصص")
    print("=" * 50)
    
    try:
        from src.core.token_manager import TokenManager
        
        # Initialize token manager
        token_manager = TokenManager()
        
        # Token definitions from environment variables
        tokens = {
            'read_token': {
                'token': os.getenv('HF_TOKEN_READ'),
                'type': 'read',
                'description': 'رمز القراءة - للتطوير والتعلم والوصول للنماذج العامة',
                'is_default': True
            },
            'write_token': {
                'token': os.getenv('HF_TOKEN_WRITE'),
                'type': 'write',
                'description': 'رمز الكتابة - لرفع ومشاركة النماذج مع المجتمع',
                'is_default': False
            },
            'fine_grained_token': {
                'token': os.getenv('HF_TOKEN_FINE_GRAINED'),
                'type': 'fine_grained',
                'description': 'رمز مخصص - للمشاريع التجارية والبيانات الطبية الحساسة',
                'is_default': False
            }
        }
        
        # Save tokens
        tokens_found = 0
        for name, token_info in tokens.items():
            token = token_info['token']
            
            if not token:
                print(f"⚠️ تخطي {name} - لم يتم العثور على الرمز في متغيرات البيئة")
                continue
                
            success = token_manager.save_token(
                name=name,
                token=token,
                token_type=token_info['type'],
                description=token_info['description'],
                is_default=token_info['is_default']
            )
            
            if success:
                tokens_found += 1
                print(f"✅ تم حفظ {name} ({token_info['type']})")
                
                # Validate token
                validation = token_manager.validate_token(token)
                if validation['valid']:
                    print(f"   ✓ الرمز صحيح - المستخدم: {validation.get('username', 'غير معروف')}")
                else:
                    print(f"   ⚠️ تحذير: {validation.get('message', 'فشل التحقق')}")
            else:
                print(f"❌ فشل في حفظ {name}")
        
        if tokens_found == 0:
            print("\n❌ لم يتم العثور على أي رموز في متغيرات البيئة!")
            print("💡 يرجى إضافة الرموز في إعدادات Hugging Face Spaces:")
            print("   1. اذهب إلى Settings > Variables")
            print("   2. أضف HF_TOKEN_READ, HF_TOKEN_WRITE, HF_TOKEN_FINE_GRAINED")
            print("   3. أعد تشغيل Space")
            return False
        
        print(f"\n📊 ملخص الرموز المحفوظة: {tokens_found}/3")
        tokens_list = token_manager.list_tokens()
        
        for token in tokens_list:
            status = "🟢 افتراضي" if token['is_default'] else "🔵 متاح"
            print(f"  {status} {token['name']} ({token['type']}) - {token['usage_count']} استخدام")
        
        print("\n🎯 تخصيص الرموز للمهام:")
        task_mappings = {
            'read': 'قراءة النماذج العامة',
            'download': 'تحميل النماذج',
            'medical': 'البيانات الطبية الحساسة',
            'private': 'النماذج الخاصة والمحدودة',
            'write': 'رفع النماذج الجديدة',
            'upload': 'مشاركة المحتوى',
            'commercial': 'المشاريع التجارية',
            'enterprise': 'الاستخدام المؤسسي'
        }
        
        for task, description in task_mappings.items():
            token = token_manager.get_token_for_task(task)
            if token:
                # Find token name
                token_name = "غير معروف"
                for t in tokens_list:
                    test_token = token_manager.get_token(t['name'])
                    if test_token == token:
                        token_name = t['name']
                        break
                print(f"  📋 {task}: {description}{token_name}")
            else:
                print(f"  ❌ {task}: {description} → لا يوجد رمز مناسب")
        
        print("\n✅ تم إعداد جميع الرموز بنجاح!")
        print("\n🌐 يمكنك الآن:")
        print("  • تشغيل التطبيق: python run_optimized.py")
        print("  • إدارة الرموز: http://localhost:8000/tokens")
        print("  • الوصول للبيانات الطبية: http://localhost:8000/medical-datasets")
        
        return True
        
    except ImportError as e:
        print(f"❌ خطأ في الاستيراد: {e}")
        print("💡 تأكد من تثبيت التبعيات: pip install -r requirements.txt")
        return False
    except Exception as e:
        print(f"❌ خطأ في إعداد الرموز: {e}")
        return False

def test_tokens():
    """Test token functionality"""
    
    print("\n🧪 اختبار وظائف الرموز")
    print("=" * 30)
    
    try:
        from src.core.token_manager import TokenManager
        
        token_manager = TokenManager()
        
        # Test different task types
        test_tasks = ['read', 'medical', 'write', 'private']
        
        for task in test_tasks:
            token = token_manager.get_token_for_task(task)
            if token:
                print(f"✅ {task}: رمز متوفر")
            else:
                print(f"❌ {task}: لا يوجد رمز")
        
        return True
        
    except Exception as e:
        print(f"❌ خطأ في الاختبار: {e}")
        return False

def show_usage_examples():
    """Show usage examples"""
    
    print("\n📚 أمثلة الاستخدام")
    print("=" * 30)
    
    examples = [
        {
            'task': 'تحميل نموذج عام',
            'code': 'curl http://localhost:8000/api/tokens/for-task/read',
            'description': 'للحصول على رمز القراءة للنماذج العامة'
        },
        {
            'task': 'تحميل بيانات طبية',
            'code': 'curl http://localhost:8000/api/tokens/for-task/medical',
            'description': 'للحصول على رمز مخصص للبيانات الطبية'
        },
        {
            'task': 'رفع نموذج جديد',
            'code': 'curl http://localhost:8000/api/tokens/for-task/write',
            'description': 'للحصول على رمز الكتابة لرفع النماذج'
        }
    ]
    
    for example in examples:
        print(f"\n📋 {example['task']}:")
        print(f"   الكود: {example['code']}")
        print(f"   الوصف: {example['description']}")

def main():
    """Main function"""
    
    print("🚀 مرحباً بك في إعداد رموز Hugging Face")
    print("Welcome to Hugging Face Tokens Setup")
    print("=" * 60)
    
    # Check if .env file exists
    if not Path('.env').exists():
        print("⚠️ ملف .env غير موجود")
        print("💡 تأكد من نسخ .env.example إلى .env أو إضافة الرموز في متغيرات البيئة")
    
    # Setup tokens
    if setup_tokens():
        # Test tokens
        test_tokens()
        
        # Show examples
        show_usage_examples()
        
        print("\n🎉 تم الإعداد بنجاح!")
        return 0
    else:
        print("\n❌ فشل في الإعداد")
        print("📖 راجع SECURITY_SETUP.md للحصول على تعليمات مفصلة")
        return 1

if __name__ == "__main__":
    sys.exit(main())