
    .h;                     \   d dl Z d dlZd dlZd dlZd dlZd dlZd dlmZ d dlmZ d dl	m
Z
mZ d dlmZ  ed      Zedv r"ej                         rej!                  d	        G d
 d      Z G d d      Zedk(  r ed        ed        e       Z	 	 ej-                         Z edd        eded   dd        eded   dd        eded   d   dd        eded   d    d!d        ed"ed   d#   dd$        ed%ed&   d'   d(d        ed)ed&   d*   d(d       ed+   rL ed,       ed+   j1                         D ]-  \  ZZ ed-e d.ed/   d0d1ed2   dd3ed4   d5d6ed7   d0d8       / n ed9        ej6                  d:       y# e$ r  ed;       Y yw xY w)<    N)datetime)Path)MACOSRANK)check_requirementsz	train.log>   r   T)
missing_okc                   x    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
 G d	 d
      Z G d dej                        Zy)ConsoleLoggera  
    Console output capture with API/file streaming and deduplication.

    Captures stdout/stderr output and streams it to either an API endpoint or local file, with intelligent
    deduplication to reduce noise from repetitive console output.

    Attributes:
        destination (str | Path): Target destination for streaming (URL or Path object).
        is_api (bool): Whether destination is an API endpoint (True) or local file (False).
        original_stdout: Reference to original sys.stdout for restoration.
        original_stderr: Reference to original sys.stderr for restoration.
        log_queue (queue.Queue): Thread-safe queue for buffering log messages.
        active (bool): Whether console capture is currently active.
        worker_thread (threading.Thread): Background thread for processing log queue.
        last_line (str): Last processed line for deduplication.
        last_time (float): Timestamp of last processed line.
        last_progress_line (str): Last progress bar line for progress deduplication.
        last_was_progress (bool): Whether the last line was a progress bar.

    Examples:
        Basic file logging:
        >>> logger = ConsoleLogger("training.log")
        >>> logger.start_capture()
        >>> print("This will be logged")
        >>> logger.stop_capture()

        API streaming:
        >>> logger = ConsoleLogger("https://api.example.com/logs")
        >>> logger.start_capture()
        >>> # All output streams to API
        >>> logger.stop_capture()
    c                 x   || _         t        |t              xr |j                  d      | _        | j                  st        |      | _         t        j                  | _        t        j                  | _
        t        j                  d      | _        d| _        d| _        d| _        d| _        d| _        d| _        y)z
        Initialize with API endpoint or local file path.

        Args:
            destination (str | Path): API endpoint URL (http/https) or local file path for streaming output.
        )zhttp://zhttps://  )maxsizeFN g        )destination
isinstancestr
startswithis_apir   sysstdoutoriginal_stdoutstderroriginal_stderrqueueQueue	log_queueactiveworker_thread	last_line	last_timelast_progress_linelast_was_progress)selfr   s     V/var/www/html/ai-service/venv/lib/python3.12/site-packages/ultralytics/utils/logger.py__init__zConsoleLogger.__init__7   s     ' c2f{7M7MNe7f{{#K0D  #zz"zzT2! "$!&    c                    | j                   ryd| _         | j                  | j                  | j                        t        _        | j                  | j                  | j                        t        _        	 | j                  | j                        }t        j                  d      j                  |       t        j                  | j                  d      | _        | j                   j#                          y# t        $ r Y Lw xY w)zTStart capturing console output and redirect stdout/stderr to custom capture objects.NTultralytics)targetdaemon)r   _ConsoleCapturer   
_queue_logr   r   r   r   _LogHandlerlogging	getLogger
addHandler	Exception	threadingThread_stream_workerr   start)r#   handlers     r$   start_capturezConsoleLogger.start_captureP   s    ;;))$*>*>P
))$*>*>P
	&&t7Gm,77@ '--T5H5HQUV  "	  		s   4?C4 4	D ?D c                     | j                   syd| _         | j                  t        _        | j                  t        _        | j                  j                  d       y)zAStop capturing console output and restore original stdout/stderr.NF)r   r   r   r   r   r   r   putr#   s    r$   stop_capturezConsoleLogger.stop_capturec   s?    {{))
))
4 r&   c                    | j                   syt        j                         }d|v r|j                  d      d   }|j                  d      }|r|d   dk(  r|j                          |D ]  }|j	                         }d|v rd|v rM|j                  d      d   j                         }|| j                  k(  r| j                  r[|| _        d	| _        n|s| j                  rd
| _        d
| _        || j                  k(  r|| j                  z
  dk  r|| _        || _	        |j                  d      s+t        j                         j                  d      }d| d| }| j                  | d      r	 y)z?Queue console text with deduplication and timestamp processing.Nr   
r   u   ─u    ━━r   TFg?z[20z%Y-%m-%d %H:%M:%S[z] )r   timesplitpoprstripstripr!   r"   r   r    r   r   nowstrftime	_safe_put)r#   textcurrent_timelineslineprogress_core	timestamps          r$   r,   zConsoleLogger._queue_logm   sj   {{yy{ 4<::d#B'D

4 U2Y"_IIK #	D;;=D } D  $

9 5a 8 > > @ D$;$;;@V@V*7')-&  6 6-2D*).& t~~%,*G#*M!DN)DN ??5)$LLN334GH	9+Rv. >>TF"+.G#	r&   c                    	 | j                   j                  |       y# t        j                  $ rS 	 | j                   j	                          | j                   j                  |       Y y# t        j
                  $ r Y Y yw xY ww xY w)z0Safely put item in queue with overflow handling.TF)r   
put_nowaitr   Full
get_nowaitEmpty)r#   items     r$   rG   zConsoleLogger._safe_put   so    		NN%%d+zz 	))+))$/;; 	s&    B5A))B <B?B  Bc                     | j                   r?	 | j                  j                  d      }|y| j                  |       | j                   r>yy# t        j
                  $ r Y aw xY w)z4Background worker for streaming logs to destination.   )timeoutN)r   r   get
_write_logr   rR   )r#   log_texts     r$   r4   zConsoleLogger._stream_worker   s[    kk>>--a-8#) kk ;; s   A A A#"A#c                    	 | j                   r_ddl}t        j                         j	                         |j                         d}|j                  t        | j                        |d       y| j                  j                  j                  dd       | j                  j                  dd	
      5 }|j                  |       ddd       y# 1 sw Y   yxY w# t        $ r$}t        d| | j                         Y d}~yd}~ww xY w)z4Write log to API endpoint or local file destination.r   N)rM   message   )jsonrV   T)parentsexist_okazutf-8)encodingzPlatform logging error: )file)r   requestsr   rE   	isoformatrD   postr   r   parentmkdiropenwriter1   printr   )r#   rH   rc   payloadfes         r$   rX   zConsoleLogger._write_log   s    	M{{(0(@(@(Btzz|\c$"2"23'1M  ''--dT-J%%**3*A "QGGDM" " " 	M,QC0t7K7KLL	Ms=   A*C -AC 1CC CC C 	D!D  Dc                   &    e Zd ZdZdZd Zd Zd Zy)ConsoleLogger._ConsoleCapturez"Lightweight stdout/stderr capture.originalcallbackc                      || _         || _        y Nrp   )r#   rq   rr   s      r$   r%   z&ConsoleLogger._ConsoleCapture.__init__   s    $DM$DMr&   c                 \    | j                   j                  |       | j                  |       y rt   )rq   ri   rr   )r#   rH   s     r$   ri   z#ConsoleLogger._ConsoleCapture.write   s     MM%MM$r&   c                 8    | j                   j                          y rt   )rq   flushr:   s    r$   rw   z#ConsoleLogger._ConsoleCapture.flush   s    MM!r&   N)__name__
__module____qualname____doc__	__slots__r%   ri   rw    r&   r$   r+   ro      s    0,		%	 	"r&   r+   c                   ,     e Zd ZdZdZ fdZd Z xZS )ConsoleLogger._LogHandlerzLightweight logging handler.)rr   c                 0    t         |           || _        y rt   )superr%   rr   )r#   rr   	__class__s     r$   r%   z"ConsoleLogger._LogHandler.__init__   s    G$DMr&   c                 J    | j                  | j                  |      dz          y )Nr>   )rr   format)r#   records     r$   emitzConsoleLogger._LogHandler.emit   s    MM$++f-45r&   )rx   ry   rz   r{   r|   r%   r   __classcell__)r   s   @r$   r-   r      s    *!		%	6r&   r-   N)rx   ry   rz   r{   r%   r7   r;   r,   rG   r4   rX   r+   r.   Handlerr-   r}   r&   r$   r   r      sG    B'2#&!2h	M" " 
6goo 
6r&   r   c                   (    e Zd ZdZd Zd Zd Zd Zy)SystemLoggeru  
    Log dynamic system metrics for training monitoring.

    Captures real-time system metrics including CPU, RAM, disk I/O, network I/O, and NVIDIA GPU statistics for
    training performance monitoring and analysis.

    Attributes:
        pynvml: NVIDIA pynvml module instance if successfully imported, None otherwise.
        nvidia_initialized (bool): Whether NVIDIA GPU monitoring is available and initialized.
        net_start: Initial network I/O counters for calculating cumulative usage.
        disk_start: Initial disk I/O counters for calculating cumulative usage.

    Examples:
        Basic usage:
        >>> logger = SystemLogger()
        >>> metrics = logger.get_metrics()
        >>> print(f"CPU: {metrics['cpu']}%, RAM: {metrics['ram']}%")
        >>> if metrics["gpus"]:
        ...     gpu0 = metrics["gpus"]["0"]
        ...     print(f"GPU0: {gpu0['usage']}% usage, {gpu0['temp']}°C")

        Training loop integration:
        >>> system_logger = SystemLogger()
        >>> for epoch in range(epochs):
        ...     # Training code here
        ...     metrics = system_logger.get_metrics()
        ...     # Log to database/file
    c                     ddl }d| _        | j                         | _        |j	                         | _        |j                         | _        y)zInitialize the system logger.r   N)psutilpynvml_init_nvidianvidia_initializednet_io_counters	net_startdisk_io_counters
disk_start)r#   r   s     r$   r%   zSystemLogger.__init__  s=    "&"3"3"5//1 113r&   c                     	 t         rJ t        d       t        d      | _        | j                  j	                          y# t
        $ r Y yw xY w)z-Initialize NVIDIA GPU monitoring with pynvml.znvidia-ml-py>=12.0.0r   TF)r   r   
__import__r   nvmlInitr1   r:   s    r$   r   zSystemLogger._init_nvidia  sI    	956$X.DKKK  " 		s   =A   	AAc                    ddl }|j                         }|j                         }|j                         }t	        j
                  d      }t        |j                         d      t        |j                  d      t        |j                  | j                  j                  z
  dz  d      t        |j                  | j                  j                  z
  dz  d      t        |j                  dz  d      dt        |j                  | j                  j                  z
  dz  d      t        |j                  | j                  j                  z
  dz  d      di d	}| j                   r"|d
   j#                  | j%                                |S )a  
        Get current system metrics.

        Collects comprehensive system metrics including CPU usage, RAM usage, disk I/O statistics,
        network I/O statistics, and GPU metrics (if available). Example output:

        ```python
        metrics = {
            "cpu": 45.2,
            "ram": 78.9,
            "disk": {"read_mb": 156.7, "write_mb": 89.3, "used_gb": 256.8},
            "network": {"recv_mb": 157.2, "sent_mb": 89.1},
            "gpus": {
                0: {"usage": 95.6, "memory": 85.4, "temp": 72, "power": 285},
                1: {"usage": 94.1, "memory": 82.7, "temp": 70, "power": 278},
            },
        }
        ```

        - cpu (float): CPU usage percentage (0-100%)
        - ram (float): RAM usage percentage (0-100%)
        - disk (dict):
            - read_mb (float): Cumulative disk read in MB since initialization
            - write_mb (float): Cumulative disk write in MB since initialization
            - used_gb (float): Total disk space used in GB
        - network (dict):
            - recv_mb (float): Cumulative network received in MB since initialization
            - sent_mb (float): Cumulative network sent in MB since initialization
        - gpus (dict): GPU metrics by device index (e.g., 0, 1) containing:
            - usage (int): GPU utilization percentage (0-100%)
            - memory (float): CUDA memory usage percentage (0-100%)
            - temp (int): GPU temperature in degrees Celsius
            - power (int): GPU power consumption in watts

        Returns:
            metrics (dict): System metrics containing 'cpu', 'ram', 'disk', 'network', 'gpus' with respective usage data.
        r   N/   i   i   @)read_mbwrite_mbused_gb)recv_mbsent_mb)cpuramdisknetworkgpusr   )r   r   r   virtual_memoryshutil
disk_usageroundcpu_percentpercent
read_bytesr   write_bytesused
bytes_recvr   
bytes_sentr   update_get_nvidia_metrics)r#   r   netr   memoryr   metricss          r$   get_metricszSystemLogger.get_metrics  sM   L 	$$&&&(&&(&&s+
 ++-q1+ $//DOO4N4N"NSZ![]^_!4#3#3doo6Q6Q#QV]"^`ab G!<a@ !#..4>>3L3L"LQX!Y[\] #..4>>3L3L"LQX!Y[\] 
  ""FO""4#;#;#=>r&   c                    i }| j                   r| j                  s|S 	 | j                  j                         }t        |      D ]  }| j                  j	                  |      }| j                  j                  |      }| j                  j                  |      }| j                  j                  || j                  j                        }| j                  j                  |      dz  }t        |j                  d      t        |j                  |j                  z  dz  d      ||d|t        |      <    	 |S # t        $ r Y |S w xY w)zMGet NVIDIA GPU metrics including utilization, memory, temperature, and power.r   r   d   )usager   temppower)r   r   nvmlDeviceGetCountrangenvmlDeviceGetHandleByIndexnvmlDeviceGetUtilizationRatesnvmlDeviceGetMemoryInfonvmlDeviceGetTemperatureNVML_TEMPERATURE_GPUnvmlDeviceGetPowerUsager   gpur   totalr   r1   )	r#   r   device_countihandleutilr   r   r   s	            r$   r   z SystemLogger._get_nvidia_metricsY  s   &&dkkK	;;99;L<( ??B{{@@H<<VD{{;;FDKKDdDde;;FCtK #488Q/#V[[6<<%?3$FJ "	 SV   		s   DD5 5	EEN)rx   ry   rz   r{   r%   r   r   r   r}   r&   r$   r   r      s    :4	@Dr&   r   __main__z&SystemLogger Real-time Metrics MonitorzPress Ctrl+C to stop
z[H[Jr   )endzCPU: r   z5.1f%zRAM: r   zDisk Read: r   r   z8.1fz MBzDisk Write: r   z7.1fzDisk Used: r   z GBz
Net Recv: r   r   z9.1fz
Net Sent: r   r   z
GPU Metrics:z  GPU z: r   3z	% | Mem: r   z
% | Temp: r   2u   °C | Power: r   Wz
GPU: No NVIDIA GPUs detectedrU   z

Stopped monitoring.)r.   r   r   r   r2   r@   r   pathlibr   ultralytics.utilsr   r   ultralytics.utils.checksr   DEFAULT_LOG_PATHexistsunlinkr   r   rx   rj   loggerr   r   itemsgpu_idgpu_datasleepKeyboardInterruptr}   r&   r$   <module>r      sE      
     ) 7 $ 7?'..0t,M6 M6`J JZ z	
23	
"#^F )((*G .b) E'%..a01E'%..a01K	 :4@DEL!<T B#FGK	 :4@DEJwy1)<TB#FGJwy1)<TB#FG v&'(/(=(=(? $FH 8G+<Q*? @  ( 248 9!!)&!1! 4 5""*7"3A!6a9 67DJJqM9  J  )'()s   DF F+*F+