
    qi=                     P   d Z ddlZddlmZ ddlmZmZ ddlmZ ddl	m
Z
 ddlmZmZmZmZmZmZ ddlmZmZ dd	lmZ 	 ddlZdd
lmZ d Ze G d de             Z G d de      Z y# e$ r7Z ej8                  de         ej8                  d        ede       dZ[ww xY w)zMoondream vision service implementation.

This module provides integration with the Moondream vision-language model
for image analysis and description generation.
    N)	dataclass)AsyncGeneratorOptional)logger)Image)
ErrorFrameFrameUserImageRawFrameVisionFullResponseEndFrameVisionFullResponseStartFrameVisionTextFrame)VisionSettings_warn_deprecated_param)VisionService)AutoModelForCausalLMzException: zKIn order to use Moondream, you need to `pip install pipecat-ai[moondream]`.zMissing module(s): c                     	 ddl } t        j                  j                         r%t        j                  d      t        j
                  fS 	 t        j                  j                         r%t        j                  d      t        j                  fS t        j                  j                  j                         r%t        j                  d      t        j                  fS t        j                  d      t        j
                  fS # t        $ r Y w xY w)aM  Detect the appropriate device to run on.

    Detects available hardware acceleration and selects the best device
    and data type for optimal performance.

    Returns:
        tuple: A tuple containing (device, dtype) where device is a torch.device
               and dtype is the recommended torch data type for that device.
    r   Nxpucudampscpu)intel_extension_for_pytorchtorchr   is_availabledevicefloat32ImportErrorr   float16backendsr   )r   s    S/opt/pipecat/venv/lib/python3.12/site-packages/pipecat/services/moondream/vision.pydetect_devicer    (   s    *99!!#<<&55 $ zz ||F#U]]22				(	(	*||E"EMM11||E"EMM11  s   AC? ?	D
Dc                       e Zd ZdZy)MoondreamSettingszkSettings for the Moondream vision service.

    Parameters:
        model: Moondream model identifier.
    N)__name__
__module____qualname____doc__     r   r"   r"   A   s    r(   r"   c                   n     e Zd ZU dZeZeed<   ddddddee   dee   f fd	Z	d
e
deedf   fdZ xZS )MoondreamServicezMoondream vision-language model service.

    Provides image analysis and description generation using the Moondream
    vision-language model. Supports various hardware acceleration options
    including CUDA, MPS, and Intel XPU.
    	_settingsNz
2025-01-09F)modelrevisionuse_cpusettingsr,   r/   c                   t        d      }|t        dt         d       ||_        ||j                  |       t	        	|   dd|i| |st               \  }}n%t        j                  d      }t        j                  }t        j                  d       t        j                  | j                  j                  d|d	|i|
      j                         | _        t        j                  d       y)ae  Initialize the Moondream service.

        Args:
            model: Hugging Face model identifier for the Moondream model.

                .. deprecated:: 0.0.105
                    Use ``settings=MoondreamSettings(model=...)`` instead.

            revision: Specific model revision to use.
            use_cpu: Whether to force CPU usage instead of hardware acceleration.
            settings: Runtime-updatable settings. When provided alongside deprecated
                parameters, ``settings`` values take precedence.
            **kwargs: Additional arguments passed to the parent VisionService.
        zvikhyatk/moondream2)r,   Nr,   r/   r   zLoading Moondream model...T )trust_remote_coder-   
device_mapdtypezLoaded Moondream modelr'   )r"   r   r,   apply_updatesuper__init__r    r   r   r   r   debugr   from_pretrainedr+   eval_model)
selfr,   r-   r.   r/   kwargsdefault_settingsr   r4   	__class__s
            r   r7   zMoondreamService.__init__U   s    0 -3HI "7,=wG%*" ))(3="2=f=)OMFE\\%(FMME12*::NN  "F|
 $& 	 	-.r(   framereturnc                   K    j                   st        d       yt        j                  dt	        j
                         d       dt        dt        t           dt        f fd}t        j                  |j
                  j                         d{   }t                t        |	       t                y7 .w)
zsAnalyze an image and generate a description.

        Args:
            frame: The image frame to process.
        zMoondream model not availableNzAnalyzing image (bytes length: )image_bytestextrA   c                     t        j                  j                  j                  |       }j                  j                  |      }j                  j                  ||      d   }|S )Nanswer)r   	frombytesformatsizer;   encode_imagequery)rD   rE   imageimage_embedsdescriptionr@   r<   s        r   get_image_descriptionz:MoondreamService.run_vision.<locals>.get_image_description   sR    OOELL%**kJE;;33E:L++++L$?IKr(   )rE   )r;   r   r   r8   lenrM   bytesr   strasyncio	to_threadrE   r   r   r   )r<   r@   rP   rO   s   ``  r   
run_visionzMoondreamService.run_vision   s      {{<==6s5;;7G6HJK	u 	HSM 	c 	 $--.CU[[RWR\R\]]*,,;//(**	 ^s   BCC	/C)r#   r$   r%   r&   r"   Settings__annotations__r   rS   r7   r
   r   r	   rV   __classcell__)r?   s   @r   r*   r*   J   se     !H  
  $045/ }5/ ,-5/n+&7 +N5RV;<W +r(   r*   )!r&   rT   dataclassesr   typingr   r   logurur   PILr   pipecat.frames.framesr   r	   r
   r   r   r   pipecat.services.settingsr   r   pipecat.services.vision_servicer   r   transformersr   ModuleNotFoundErroreerror	Exceptionr    r"   r*   r'   r(   r   <module>rf      s     ! +    M 9/122   X+} X+Q  /FLL;qc"#FLL^_
)!-
../s    
A) )B%.2B  B%