File size: 17,526 Bytes
900df0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
"""
HandwrittenOCR - ู†ุธุงู… ุงู„ุชุณุฌูŠู„ ุงู„ู…ูุตู‘ู„ v7.0
=============================================
ูŠุณุฌู‘ู„ ูƒู„ ู…ุง ูŠุญุฏุซ ููŠ ุงู„ุชุทุจูŠู‚ ุจุงู„ุชูุตูŠู„:
- ูƒู„ ุฎุทูˆุฉ ู…ุนุงู„ุฌุฉ ู…ุน ุงู„ูˆู‚ุช ูˆุงู„ู…ูƒุงู†
- ุงู„ุฃุฎุทุงุก ู…ุน traceback ูƒุงู…ู„
- ุฃุญุฏุงุซ ู…ู†ุธู…ุฉ (JSON) ู„ุณู‡ูˆู„ุฉ ุงู„ุชุญู„ูŠู„
- ุชู‚ุฑูŠุฑ HTML ุชู„ู‚ุงุฆูŠ
- ุงู„ุฐุงูƒุฑุฉ ูˆุงู„ุฃุฏุงุก
"""

import logging
import os
import sys
import json
import traceback
import time
import functools
from datetime import datetime
from logging.handlers import RotatingFileHandler
from pathlib import Path


# ===================== ุงู„ููˆุฑู…ุชุฑ ุงู„ู…ูุตู‘ู„ =====================

class DetailedFormatter(logging.Formatter):
    """ููˆุฑู…ุชุฑ ู…ูุตู‘ู„ ูŠุชุถู…ู†: ุงู„ูˆู‚ุชุŒ ุงู„ู…ุณุชูˆู‰ุŒ ุงู„ู…ู„ูุŒ ุงู„ุฏุงู„ุฉุŒ ุงู„ุณุทุฑุŒ ุงู„ุฑุณุงู„ุฉ."""

    COLORS = {
        "DEBUG": "\033[36m",     # ุณู…ุงูˆูŠ
        "INFO": "\033[32m",      # ุฃุฎุถุฑ
        "WARNING": "\033[33m",   # ุฃุตูุฑ
        "ERROR": "\033[31m",     # ุฃุญู…ุฑ
        "CRITICAL": "\033[1;31m", # ุฃุญู…ุฑ ุนุฑูŠุถ
    }
    RESET = "\033[0m"

    def __init__(self, colorize=False):
        super().__init__()
        self.colorize = colorize

    def format(self, record):
        # ุฅุถุงูุฉ traceback ูƒุงู…ู„ ู„ู„ุฃุฎุทุงุก
        if record.exc_info and record.exc_info[0] is not None:
            record.exc_text = self.format_exception(record.exc_info)

        # ุงู„ุจู†ูŠุฉ: 2026-05-01 12:34:56 | INFO     | module:function:42 | ุฑุณุงู„ุฉ
        module = record.module or "unknown"
        func = record.funcName or "?"
        line = record.lineno or 0
        location = f"{module}:{func}:{line}"

        timestamp = datetime.fromtimestamp(record.created).strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]

        # ุงู„ู„ูˆู† (ู„ู„ุดุงุดุฉ ูู‚ุท)
        level = record.levelname
        if self.colorize and level in self.COLORS:
            level_str = f"{self.COLORS[level]}{level:<8}{self.RESET}"
        else:
            level_str = f"{level:<8}"

        msg = record.getMessage()

        # ุชู†ุณูŠู‚ ุงู„ุฑุณุงู„ุฉ ุงู„ู†ู‡ุงุฆูŠ
        result = f"{timestamp} | {level_str} | {location} | {msg}"

        # ุฅู„ุญุงู‚ ุงู„ู€ traceback
        if hasattr(record, 'exc_text') and record.exc_text:
            result += "\n" + record.exc_text

        # ุฅู„ุญุงู‚ ู…ุนู„ูˆู…ุงุช ุฅุถุงููŠุฉ
        if hasattr(record, 'extra_data') and record.extra_data:
            result += f"\n    [ุชูุงุตูŠู„] {json.dumps(record.extra_data, ensure_ascii=False, default=str)}"

        return result

    def format_exception(self, exc_info):
        """ุชู†ุณูŠู‚ traceback ูƒุงู…ู„ ูˆู…ูุตู‘ู„."""
        lines = []
        lines.append("    โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•")
        lines.append("    โ•‘                     ุชุชุจุน ุงู„ุฎุทุฃ ุงู„ูƒุงู…ู„                      ")
        lines.append("    โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•")
        tb_lines = traceback.format_exception(*exc_info)
        for line in tb_lines:
            for sub in line.rstrip("\n").split("\n"):
                lines.append(f"    โ•‘ {sub}")
        lines.append("    โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•")
        return "\n".join(lines)


# ===================== ู…ูุณุฌู‘ู„ ุงู„ุฃุญุฏุงุซ ุงู„ู…ู†ุธู…ุฉ (JSON) =====================

class EventLogger:
    """ูŠุณุฌู‘ู„ ุงู„ุฃุญุฏุงุซ ุจุชู†ุณูŠู‚ JSON ู…ู†ุธู‘ู… ููŠ ู…ู„ู ู…ู†ูุตู„."""

    def __init__(self, events_log_path: str):
        self.events_log_path = events_log_path
        os.makedirs(os.path.dirname(events_log_path), exist_ok=True)

    def log_event(self, event_type: str, data: dict = None, status: str = "ok"):
        """ุชุณุฌูŠู„ ุญุฏุซ."""
        entry = {
            "timestamp": datetime.now().isoformat(),
            "event": event_type,
            "status": status,
            "data": data or {},
        }
        try:
            with open(self.events_log_path, "a", encoding="utf-8") as f:
                f.write(json.dumps(entry, ensure_ascii=False, default=str) + "\n")
        except Exception:
            pass


# ===================== ุฅุนุฏุงุฏ ุงู„ู„ูˆุบ =====================

_event_logger = None


def setup_logging(config=None, log_dir=None, log_level="DEBUG"):
    """
    ุฅุนุฏุงุฏ ู†ุธุงู… ุงู„ุชุณุฌูŠู„ ุงู„ู…ูุตู‘ู„.

    Parameters:
        config: ูƒุงุฆู† ุงู„ุฅุนุฏุงุฏุงุช (ุงุฎุชูŠุงุฑูŠ)
        log_dir: ู…ุณุงุฑ ู…ุฌู„ุฏ ุงู„ู„ูˆู‚ (ุงุฎุชูŠุงุฑูŠ โ€” ูŠูุณุชุฎุฏู… ุจุฏู„ุงู‹ ู…ู† config)
        log_level: ู…ุณุชูˆู‰ ุงู„ุชุณุฌูŠู„ (ุงูุชุฑุงุถูŠ DEBUG)

    Returns:
        logging.Logger: ูƒุงุฆู† ุงู„ู„ูˆุบ ุงู„ุฑุฆูŠุณูŠ
    """
    global _event_logger

    if config:
        config.ensure_dirs()
        logs_dir = config.logs_dir
        log_file = config.log_file
        events_file = config.events_jsonl
        level = getattr(logging, config.log_level.upper(), logging.DEBUG)
    else:
        logs_dir = log_dir or "/app/data/logs"
        os.makedirs(logs_dir, exist_ok=True)
        ts = datetime.now().strftime("%Y%m%d_%H%M%S")
        log_file = os.path.join(logs_dir, f"ocr_{ts}.log")
        events_file = os.path.join(logs_dir, f"ocr_events_{ts}.jsonl")
        level = getattr(logging, log_level.upper(), logging.DEBUG)

    # ุงู„ู„ูˆุบ ุงู„ุฑุฆูŠุณูŠ
    logger = logging.getLogger("HandwrittenOCR")
    logger.setLevel(level)
    logger.handlers.clear()

    # === Handler 1: ู…ู„ู ู…ูุตู‘ู„ (ูƒู„ ุดูŠุก) ===
    detailed_handler = RotatingFileHandler(
        log_file,
        maxBytes=5_000_000,  # 5 MB
        backupCount=10,
        encoding="utf-8",
    )
    detailed_handler.setLevel(logging.DEBUG)
    detailed_handler.setFormatter(DetailedFormatter(colorize=False))
    logger.addHandler(detailed_handler)

    # === Handler 2: ู…ู„ู ุงู„ุฃุฎุทุงุก ูู‚ุท ===
    errors_file = log_file.replace(".log", "_errors.log")
    error_handler = RotatingFileHandler(
        errors_file,
        maxBytes=5_000_000,
        backupCount=5,
        encoding="utf-8",
    )
    error_handler.setLevel(logging.ERROR)
    error_handler.setFormatter(DetailedFormatter(colorize=False))
    logger.addHandler(error_handler)

    # === Handler 3: ุงู„ุดุงุดุฉ (ู…ุฎุชุตุฑ) ===
    stream_handler = logging.StreamHandler(sys.stdout)
    stream_handler.setLevel(logging.INFO)
    stream_handler.setFormatter(DetailedFormatter(colorize=True))
    logger.addHandler(stream_handler)

    # === ู…ุณุฌู‘ู„ ุงู„ุฃุญุฏุงุซ ===
    _event_logger = EventLogger(events_file)

    # ุชุณุฌูŠู„ ุงู„ุจุฏุงูŠุฉ
    logger.info("=" * 65)
    logger.info("ุจุฏุก ุชุดุบูŠู„ HandwrittenOCR โ€” ู†ุธุงู… ุงู„ุชุณุฌูŠู„ ุงู„ู…ูุตู‘ู„ v7.0")
    logger.info(f"ู…ู„ู ุงู„ู„ูˆู‚:   {log_file}")
    logger.info(f"ู…ู„ู ุงู„ุฃุฎุทุงุก:  {errors_file}")
    logger.info(f"ู…ู„ู ุงู„ุฃุญุฏุงุซ:  {events_file}")
    logger.info(f"ู…ุณุชูˆู‰ ุงู„ุชุณุฌูŠู„: {logging.getLevelName(level)}")
    logger.info("=" * 65)

    return logger


def get_event_logger() -> EventLogger:
    """ุงู„ุญุตูˆู„ ุนู„ู‰ ู…ุณุฌู‘ู„ ุงู„ุฃุญุฏุงุซ."""
    return _event_logger


# ===================== ุฃุฏูˆุงุช ู…ุณุงุนุฏุฉ =====================

def log_function_entry_exit(logger):
    """ุฏูŠูƒูˆุฑุงุชูˆุฑ ูŠุณุฌู‘ู„ ุฏุฎูˆู„ ูˆุฎุฑูˆุฌ ุงู„ุฏุงู„ุฉ ู…ุน ุงู„ูˆู‚ุช ูˆุงู„ู…ุนุงู…ู„ุงุช."""
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            func_name = func.__name__
            args_str = [repr(a)[:100] for a in args]
            kwargs_str = [f"{k}={repr(v)[:100]}" for k, v in kwargs.items()]
            all_params = ", ".join(args_str + kwargs_str)
            if len(all_params) > 300:
                all_params = all_params[:300] + "..."

            logger.debug(f"ENTER {func_name}({all_params})")
            start = time.time()

            try:
                result = func(*args, **kwargs)
                elapsed = time.time() - start
                logger.debug(f"EXIT  {func_name} โ€” ู†ุฌุญ ููŠ {elapsed:.3f}s")
                return result
            except Exception as e:
                elapsed = time.time() - start
                logger.error(
                    f"FAIL  {func_name} โ€” ูุดู„ ุจุนุฏ {elapsed:.3f}s โ€” {type(e).__name__}: {e}",
                    exc_info=True,
                )
                raise
        return wrapper
    return decorator


def log_step(logger, step_name: str, details: dict = None):
    """ุชุณุฌูŠู„ ุฎุทูˆุฉ ู…ุนุงู„ุฌุฉ ู…ุน ุงู„ุชูุงุตูŠู„."""
    logger.info(f"STEP  [{step_name}]")
    if details:
        for key, value in details.items():
            logger.info(f"      {key}: {value}")

    # ุชุณุฌูŠู„ ูƒุญุฏุซ JSON
    evt = get_event_logger()
    if evt:
        evt.log_event(f"step:{step_name}", data=details)


def log_error_full(logger, context: str, error: Exception, extra: dict = None):
    """ุชุณุฌูŠู„ ุฎุทุฃ ุจุงู„ุชูุตูŠู„ ู…ุน ุงู„ุณูŠุงู‚ ูˆ traceback ูƒุงู…ู„."""
    logger.error(
        f"ERROR [{context}] {type(error).__name__}: {error}",
        exc_info=True,
        extra=extra or {},
    )

    # ุชุณุฌูŠู„ ูƒุญุฏุซ JSON
    evt = get_event_logger()
    if evt:
        evt.log_event(
            f"error:{context}",
            data={
                "error_type": type(error).__name__,
                "error_message": str(error),
                "traceback": traceback.format_exc(),
                **(extra or {}),
            },
            status="error",
        )


def log_result(logger, step_name: str, result: dict):
    """ุชุณุฌูŠู„ ู†ุชูŠุฌุฉ ุฎุทูˆุฉ."""
    summary = {k: v for k, v in result.items() if k != "error"}
    logger.info(f"RESULT [{step_name}] {json.dumps(summary, ensure_ascii=False, default=str)}")

    evt = get_event_logger()
    if evt:
        evt.log_event(f"result:{step_name}", data=result)


# ===================== ุชู‚ุฑูŠุฑ HTML ู…ู† ุงู„ู„ูˆู‚ =====================

def log_health_snapshot(logger, extra: dict = None) -> dict:
    """ุชุณุฌูŠู„ ู„ู‚ุทุฉ ุตุญุฉ ุงู„ู†ุธุงู… (Platform, CUDA, RAM, Python)."""
    import platform
    snapshot = {
        "timestamp": datetime.now().isoformat(),
        "python": platform.python_version(),
        "platform": platform.platform(),
    }
    # CUDA
    try:
        import torch
        snapshot["cuda_available"] = torch.cuda.is_available()
        if torch.cuda.is_available():
            props = torch.cuda.get_device_properties(0)
            snapshot["gpu_name"] = props.name
            snapshot["gpu_vram_gb"] = round(props.total_mem / 1e9, 1)
    except Exception:
        snapshot["cuda_available"] = False
    # RAM
    try:
        import psutil
        mem = psutil.virtual_memory()
        snapshot["ram_total_gb"] = round(mem.total / 1e9, 1)
        snapshot["ram_available_gb"] = round(mem.available / 1e9, 1)
    except Exception:
        pass
    # Disk
    try:
        import shutil
        usage = shutil.disk_usage("/")
        snapshot["disk_free_gb"] = round(usage.free / 1e9, 1)
    except Exception:
        pass
    if extra:
        snapshot.update(extra)

    log_step(logger, "ู„ู‚ุทุฉ ุตุญุฉ ุงู„ู†ุธุงู…", snapshot)
    return snapshot


def generate_log_report(log_file: str, output_html: str = None) -> str:
    """
    ุชูˆู„ูŠุฏ ุชู‚ุฑูŠุฑ HTML ู…ูุตู‘ู„ ู…ู† ู…ู„ู ุงู„ู„ูˆู‚.

    Parameters:
        log_file: ู…ุณุงุฑ ู…ู„ู ุงู„ู„ูˆู‚
        output_html: ู…ุณุงุฑ ู…ู„ู HTML ุงู„ู†ุงุชุฌ (ุงุฎุชูŠุงุฑูŠ)

    Returns:
        str: ู…ุณุงุฑ ู…ู„ู HTML
    """
    if not os.path.exists(log_file):
        return ""

    if output_html is None:
        output_html = log_file.replace(".log", "_report.html")

    # ู‚ุฑุงุกุฉ ุงู„ู„ูˆู‚
    lines = []
    try:
        with open(log_file, "r", encoding="utf-8") as f:
            lines = f.readlines()
    except Exception:
        return ""

    # ุชุญู„ูŠู„ ุงู„ู„ูˆู‚
    errors = []
    warnings = []
    steps = []
    info_lines = []

    for line in lines:
        stripped = line.strip()
        if not stripped:
            continue
        if "ERROR" in stripped or "FAIL" in stripped:
            errors.append(stripped)
        elif "WARNING" in stripped:
            warnings.append(stripped)
        elif "STEP" in stripped:
            steps.append(stripped)
        elif "RESULT" in stripped:
            info_lines.append(stripped)

    # ุฅู†ุดุงุก HTML
    html = f"""<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ุชู‚ุฑูŠุฑ ุงู„ู„ูˆู‚ โ€” HandwrittenOCR</title>
    <style>
        * {{ margin: 0; padding: 0; box-sizing: border-box; }}
        body {{ font-family: 'Segoe UI', Tahoma, sans-serif; background: #f5f5f5; padding: 20px; direction: rtl; }}
        .container {{ max-width: 1200px; margin: 0 auto; }}
        h1 {{ text-align: center; color: #333; margin-bottom: 20px; }}
        .stats {{ display: flex; gap: 15px; margin-bottom: 20px; flex-wrap: wrap; justify-content: center; }}
        .stat-card {{ background: white; border-radius: 10px; padding: 15px 25px; text-align: center; box-shadow: 0 2px 8px rgba(0,0,0,0.1); min-width: 150px; }}
        .stat-card .number {{ font-size: 2em; font-weight: bold; }}
        .stat-card .label {{ color: #666; font-size: 0.9em; }}
        .stat-errors .number {{ color: #e74c3c; }}
        .stat-warnings .number {{ color: #f39c12; }}
        .stat-steps .number {{ color: #3498db; }}
        .stat-results .number {{ color: #2ecc71; }}
        .section {{ background: white; border-radius: 10px; padding: 20px; margin-bottom: 15px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }}
        .section h2 {{ margin-bottom: 15px; padding-bottom: 10px; border-bottom: 2px solid #eee; }}
        .section.errors h2 {{ color: #e74c3c; }}
        .section.warnings h2 {{ color: #f39c12; }}
        .section.steps h2 {{ color: #3498db; }}
        pre {{ background: #2d2d2d; color: #f8f8f2; padding: 15px; border-radius: 8px; overflow-x: auto; font-size: 0.85em; line-height: 1.6; direction: ltr; text-align: left; white-space: pre-wrap; word-wrap: break-word; }}
        .error-line {{ color: #ff6b6b; }}
        .warning-line {{ color: #ffd93d; }}
        .step-line {{ color: #6bcbff; }}
        .result-line {{ color: #6bff6b; }}
        .meta {{ text-align: center; color: #999; font-size: 0.85em; margin-top: 20px; }}
    </style>
</head>
<body>
<div class="container">
    <h1>HandwrittenOCR โ€” ุชู‚ุฑูŠุฑ ุงู„ู„ูˆู‚ ุงู„ู…ูุตู‘ู„</h1>
    <div class="meta">ุชู… ุงู„ุฅู†ุดุงุก: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} | ู…ู„ู ุงู„ู„ูˆู‚: {os.path.basename(log_file)}</div>

    <div class="stats">
        <div class="stat-card stat-errors">
            <div class="number">{len(errors)}</div>
            <div class="label">ุฎุทุฃ</div>
        </div>
        <div class="stat-card stat-warnings">
            <div class="number">{len(warnings)}</div>
            <div class="label">ุชุญุฐูŠุฑ</div>
        </div>
        <div class="stat-card stat-steps">
            <div class="number">{len(steps)}</div>
            <div class="label">ุฎุทูˆุฉ ู…ุนุงู„ุฌุฉ</div>
        </div>
        <div class="stat-card stat-results">
            <div class="number">{len(info_lines)}</div>
            <div class="label">ู†ุชูŠุฌุฉ</div>
        </div>
    </div>
"""

    if errors:
        html += '<div class="section errors"><h2>ุงู„ุฃุฎุทุงุก ({})</h2><pre>'.format(len(errors))
        for e in errors:
            escaped = e.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
            html += f'<span class="error-line">{escaped}</span>\n'
        html += '</pre></div>'

    if warnings:
        html += '<div class="section warnings"><h2>ุงู„ุชุญุฐูŠุฑุงุช ({})</h2><pre>'.format(len(warnings))
        for w in warnings:
            escaped = w.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
            html += f'<span class="warning-line">{escaped}</span>\n'
        html += '</pre></div>'

    if steps:
        html += '<div class="section steps"><h2>ุฎุทูˆุงุช ุงู„ู…ุนุงู„ุฌุฉ ({})</h2><pre>'.format(len(steps))
        for s in steps:
            escaped = s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
            html += f'<span class="step-line">{escaped}</span>\n'
        html += '</pre></div>'

    html += '<div class="section"><h2>ุงู„ู†ุชุงุฆุฌ ({})</h2><pre>'.format(len(info_lines))
    for r in info_lines:
        escaped = r.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
        html += f'<span class="result-line">{escaped}</span>\n'
    html += '</pre></div>'

    html += """
    <div class="section">
        <h2>ุงู„ู„ูˆู‚ ุงู„ูƒุงู…ู„</h2>
        <pre>"""
    for line in lines:
        escaped = line.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
        html += escaped
    html += """</pre>
    </div>
</div>
</body>
</html>"""

    try:
        with open(output_html, "w", encoding="utf-8") as f:
            f.write(html)
    except Exception:
        pass

    return output_html