File size: 15,436 Bytes
77565ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8728cb3
77565ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
"""

Diagnostics & Auto-Repair Service

----------------------------------

سرویس اشکال‌یابی خودکار و تعمیر مشکلات سیستم

"""

import asyncio
import logging
import os
import subprocess
import sys
from dataclasses import dataclass, asdict
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
import json
import importlib.util

logger = logging.getLogger(__name__)


@dataclass
class DiagnosticIssue:
    """یک مشکل شناسایی شده"""
    severity: str  # critical, warning, info
    category: str  # dependency, config, network, service, model
    title: str
    description: str
    fixable: bool
    fix_action: Optional[str] = None
    auto_fixed: bool = False
    timestamp: str = None

    def __post_init__(self):
        if self.timestamp is None:
            self.timestamp = datetime.now().isoformat()


@dataclass
class DiagnosticReport:
    """گزارش کامل اشکال‌یابی"""
    timestamp: str
    total_issues: int
    critical_issues: int
    warnings: int
    info_issues: int
    issues: List[DiagnosticIssue]
    fixed_issues: List[DiagnosticIssue]
    system_info: Dict[str, Any]
    duration_ms: float


class DiagnosticsService:
    """سرویس اشکال‌یابی و تعمیر خودکار"""

    def __init__(self, resource_manager=None, provider_manager=None, auto_discovery_service=None):
        self.resource_manager = resource_manager
        self.provider_manager = provider_manager
        self.auto_discovery_service = auto_discovery_service
        self.last_report: Optional[DiagnosticReport] = None

    async def run_full_diagnostics(self, auto_fix: bool = False) -> DiagnosticReport:
        """اجرای کامل اشکال‌یابی"""
        start_time = datetime.now()
        issues: List[DiagnosticIssue] = []
        fixed_issues: List[DiagnosticIssue] = []

        # بررسی وابستگی‌ها
        issues.extend(await self._check_dependencies())

        # بررسی تنظیمات
        issues.extend(await self._check_configuration())

        # بررسی شبکه
        issues.extend(await self._check_network())

        # بررسی سرویس‌ها
        issues.extend(await self._check_services())

        # بررسی مدل‌ها
        issues.extend(await self._check_models())

        # بررسی فایل‌ها و دایرکتوری‌ها
        issues.extend(await self._check_filesystem())

        # اجرای تعمیر خودکار
        if auto_fix:
            for issue in issues:
                if issue.fixable and issue.fix_action:
                    fixed = await self._apply_fix(issue)
                    if fixed:
                        issue.auto_fixed = True
                        fixed_issues.append(issue)

        # محاسبه آمار
        critical = sum(1 for i in issues if i.severity == 'critical')
        warnings = sum(1 for i in issues if i.severity == 'warning')
        info_count = sum(1 for i in issues if i.severity == 'info')

        duration_ms = (datetime.now() - start_time).total_seconds() * 1000

        report = DiagnosticReport(
            timestamp=datetime.now().isoformat(),
            total_issues=len(issues),
            critical_issues=critical,
            warnings=warnings,
            info_issues=info_count,
            issues=issues,
            fixed_issues=fixed_issues,
            system_info=await self._get_system_info(),
            duration_ms=duration_ms
        )

        self.last_report = report
        return report

    async def _check_dependencies(self) -> List[DiagnosticIssue]:
        """بررسی وابستگی‌های Python"""
        issues = []
        required_packages = {
            'fastapi': 'FastAPI',
            'uvicorn': 'Uvicorn',
            'httpx': 'HTTPX',
            'pydantic': 'Pydantic',
            'duckduckgo_search': 'DuckDuckGo Search',
            'huggingface_hub': 'HuggingFace Hub',
            'transformers': 'Transformers',
        }

        for package, name in required_packages.items():
            try:
                spec = importlib.util.find_spec(package)
                if spec is None:
                    issues.append(DiagnosticIssue(
                        severity='critical' if package in ['fastapi', 'uvicorn'] else 'warning',
                        category='dependency',
                        title=f'بسته {name} نصب نشده است',
                        description=f'بسته {package} مورد نیاز است اما نصب نشده است.',
                        fixable=True,
                        fix_action=f'pip install {package}'
                    ))
            except Exception as e:
                issues.append(DiagnosticIssue(
                    severity='warning',
                    category='dependency',
                    title=f'خطا در بررسی {name}',
                    description=f'خطا در بررسی بسته {package}: {str(e)}',
                    fixable=False
                ))

        return issues

    async def _check_configuration(self) -> List[DiagnosticIssue]:
        """بررسی تنظیمات"""
        issues = []

        # بررسی متغیرهای محیطی مهم
        important_env_vars = {
            'HF_API_TOKEN': ('warning', 'توکن HuggingFace برای استفاده از مدل‌ها'),
        }

        for var, (severity, desc) in important_env_vars.items():
            if not os.getenv(var):
                issues.append(DiagnosticIssue(
                    severity=severity,
                    category='config',
                    title=f'متغیر محیطی {var} تنظیم نشده',
                    description=desc,
                    fixable=False
                ))

        # بررسی فایل‌های پیکربندی
        config_files = ['resources.json', 'config.json']
        for config_file in config_files:
            if not os.path.exists(config_file):
                issues.append(DiagnosticIssue(
                    severity='info',
                    category='config',
                    title=f'فایل پیکربندی {config_file} وجود ندارد',
                    description=f'فایل {config_file} یافت نشد. ممکن است به صورت خودکار ساخته شود.',
                    fixable=False
                ))

        return issues

    async def _check_network(self) -> List[DiagnosticIssue]:
        """بررسی اتصال شبکه"""
        issues = []
        import httpx

        test_urls = [
            ('https://api.coingecko.com/api/v3/ping', 'CoinGecko API'),
            ('https://api.huggingface.co', 'HuggingFace API'),
        ]

        for url, name in test_urls:
            try:
                async with httpx.AsyncClient(timeout=5.0) as client:
                    response = await client.get(url)
                    if response.status_code >= 400:
                        issues.append(DiagnosticIssue(
                            severity='warning',
                            category='network',
                            title=f'مشکل در اتصال به {name}',
                            description=f'درخواست به {url} با کد {response.status_code} پاسخ داد.',
                            fixable=False
                        ))
            except Exception as e:
                issues.append(DiagnosticIssue(
                    severity='warning',
                    category='network',
                    title=f'عدم دسترسی به {name}',
                    description=f'خطا در اتصال به {url}: {str(e)}',
                    fixable=False
                ))

        return issues

    async def _check_services(self) -> List[DiagnosticIssue]:
        """بررسی سرویس‌ها"""
        issues = []

        # بررسی Auto-Discovery Service
        if self.auto_discovery_service:
            status = self.auto_discovery_service.get_status()
            if not status.get('enabled'):
                issues.append(DiagnosticIssue(
                    severity='info',
                    category='service',
                    title='سرویس Auto-Discovery غیرفعال است',
                    description='سرویس جستجوی خودکار منابع غیرفعال است.',
                    fixable=False
                ))
            elif not status.get('model'):
                issues.append(DiagnosticIssue(
                    severity='warning',
                    category='service',
                    title='مدل HuggingFace برای Auto-Discovery تنظیم نشده',
                    description='سرویس Auto-Discovery بدون مدل HuggingFace کار می‌کند.',
                    fixable=False
                ))

        # بررسی Provider Manager
        if self.provider_manager:
            stats = self.provider_manager.get_all_stats()
            summary = stats.get('summary', {})
            if summary.get('online', 0) == 0 and summary.get('total_providers', 0) > 0:
                issues.append(DiagnosticIssue(
                    severity='critical',
                    category='service',
                    title='هیچ Provider آنلاینی وجود ندارد',
                    description='تمام Provider‌ها آفلاین هستند.',
                    fixable=False
                ))

        return issues

    async def _check_models(self) -> List[DiagnosticIssue]:
        """بررسی وضعیت مدل‌های HuggingFace"""
        issues = []

        try:
            from huggingface_hub import InferenceClient, HfApi
            api = HfApi()

            # بررسی مدل‌های استفاده شده
            models_to_check = [
                'HuggingFaceH4/zephyr-7b-beta',
                'cardiffnlp/twitter-roberta-base-sentiment-latest',
            ]

            for model_id in models_to_check:
                try:
                    model_info = api.model_info(model_id, timeout=5.0)
                    if not model_info:
                        issues.append(DiagnosticIssue(
                            severity='warning',
                            category='model',
                            title=f'مدل {model_id} در دسترس نیست',
                            description=f'نمی‌توان به اطلاعات مدل {model_id} دسترسی پیدا کرد.',
                            fixable=False
                        ))
                except Exception as e:
                    issues.append(DiagnosticIssue(
                        severity='warning',
                        category='model',
                        title=f'خطا در بررسی مدل {model_id}',
                        description=f'خطا: {str(e)}',
                        fixable=False
                    ))
        except ImportError:
            issues.append(DiagnosticIssue(
                severity='info',
                category='model',
                title='بسته huggingface_hub نصب نشده',
                description='برای بررسی مدل‌ها نیاز به نصب huggingface_hub است.',
                fixable=True,
                fix_action='pip install huggingface_hub'
            ))

        return issues

    async def _check_filesystem(self) -> List[DiagnosticIssue]:
        """بررسی فایل سیستم"""
        issues = []

        # بررسی دایرکتوری‌های مهم
        important_dirs = ['static', 'static/css', 'static/js', 'backend', 'backend/services']
        for dir_path in important_dirs:
            if not os.path.exists(dir_path):
                issues.append(DiagnosticIssue(
                    severity='warning',
                    category='filesystem',
                    title=f'دایرکتوری {dir_path} وجود ندارد',
                    description=f'دایرکتوری {dir_path} یافت نشد.',
                    fixable=True,
                    fix_action=f'mkdir -p {dir_path}'
                ))

        # بررسی فایل‌های مهم
        important_files = [
            'api_server_extended.py',
            'unified_dashboard.html',
            'static/js/websocket-client.js',
            'static/css/connection-status.css',
        ]
        for file_path in important_files:
            if not os.path.exists(file_path):
                issues.append(DiagnosticIssue(
                    severity='critical' if 'api_server' in file_path else 'warning',
                    category='filesystem',
                    title=f'فایل {file_path} وجود ندارد',
                    description=f'فایل {file_path} یافت نشد.',
                    fixable=False
                ))

        return issues

    async def _apply_fix(self, issue: DiagnosticIssue) -> bool:
        """اعمال تعمیر خودکار"""
        if not issue.fixable or not issue.fix_action:
            return False

        try:
            if issue.fix_action.startswith('pip install'):
                # نصب بسته
                package = issue.fix_action.replace('pip install', '').strip()
                result = subprocess.run(
                    [sys.executable, '-m', 'pip', 'install', package],
                    capture_output=True,
                    text=True,
                    timeout=60
                )
                if result.returncode == 0:
                    logger.info(f'✅ بسته {package} با موفقیت نصب شد')
                    return True
                else:
                    logger.error(f'❌ خطا در نصب {package}: {result.stderr}')
                    return False

            elif issue.fix_action.startswith('mkdir'):
                # ساخت دایرکتوری
                dir_path = issue.fix_action.replace('mkdir -p', '').strip()
                os.makedirs(dir_path, exist_ok=True)
                logger.info(f'✅ دایرکتوری {dir_path} ساخته شد')
                return True

            else:
                logger.warning(f'⚠️ عمل تعمیر ناشناخته: {issue.fix_action}')
                return False

        except Exception as e:
            logger.error(f'❌ خطا در اعمال تعمیر: {e}')
            return False

    async def _get_system_info(self) -> Dict[str, Any]:
        """دریافت اطلاعات سیستم"""
        import platform
        return {
            'python_version': sys.version,
            'platform': platform.platform(),
            'architecture': platform.architecture(),
            'processor': platform.processor(),
            'cwd': os.getcwd(),
        }

    def get_last_report(self) -> Optional[Dict[str, Any]]:
        """دریافت آخرین گزارش"""
        if self.last_report:
            return asdict(self.last_report)
        return None