
    Wi[#                     r   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
 d dlmZmZmZmZ  G d d      Zd Zd	 Zd
 Z G d d      Zd Zddej,                  dej,                  fdZ	 	 	 	 ddeeej0                  ef      deeej0                  ef      dededeej0                  ef   f
dZ G d d      Zy)    N)Iterable)
csr_matrix)
squareform)OptionalUnionTupleAnyc                   0    e Zd Zd Zd Zd Zd Zd Zd Zy)MyLoggerc                 8    t        j                  d      | _        y )NBERTopic)logging	getLoggerlogger)selfs    [/home/sietch6/trending-topics-pipeline/venv/lib/python3.12/site-packages/bertopic/_utils.py__init__zMyLogger.__init__   s    ''
3    c                 h    | j                  |       | j                          d| j                  _        y )NF)	set_level_add_handlerr   	propagate)r   levels     r   	configurezMyLogger.configure   s&    u %r   c                 <    | j                   j                  |        y N)r   infor   messages     r   r   zMyLogger.info   s    G9&r   c                 @    | j                   j                  d|        y )Nz	WARNING: )r   warningr   s     r   r!   zMyLogger.warning   s    iy12r   c                 L    g d}||v r| j                   j                  |       y y )N)DEBUGINFOWARNINGERRORCRITICAL)r   setLevel)r   r   levelss      r   r   zMyLogger.set_level   s%    BF?KK  ' r   c                 B   t        j                         }|j                  t        j                  d             | j                  j                  |       t        | j                  j                        dkD  r*| j                  j                  d   g| j                  _        y y )Nz$%(asctime)s - %(name)s - %(message)s   r   )r   StreamHandlersetFormatter	Formatterr   
addHandlerlenhandlers)r   shs     r   r   zMyLogger._add_handler   sv    ""$
))*PQRr" t{{##$q($(KK$8$8$;#<DKK  )r   N)	__name__
__module____qualname__r   r   r   r!   r   r    r   r   r   r   
   s     4&
'3(
=r   r   c           	         t        | t        j                        rt        d      t        | t              rCt        | t
              s3t        | D cg c]  }t        |t
               c}      st        d      yt        d      c c}w )z?Check whether the input documents are indeed a list of strings.z7Make sure to supply a list of strings, not a dataframe.z2Make sure that the iterable only contains strings.zMMake sure that the documents variable is an iterable containing strings only.N)
isinstancepd	DataFrame	TypeErrorr   strany)	documentsdocs     r   check_documents_typer@   (   sn    )R\\*QRR	Ix	(Is1KI>SJsC(>?PQQ @ ghh ?s   Bc                     | et        t        | t        j                        t        | t              g      st        d      | j                  d   t        |      k7  rt        d      yy)z/Check if the embeddings have the correct shape.NzOMake sure to input embeddings as a numpy array or scipy.sparse.csr.csr_matrix. r   zMake sure that the embeddings are a numpy array with shape: (len(docs), vector_dim) where vector_dim is the dimensionality of the vector embeddings. )r=   r8   npndarrayr   
ValueErrorshaper0   )
embeddingsdocss     r   check_embeddings_shaperH   3   sf    Jz2::6
:z8Z[\noo"c$i/ 1  0	 r   c                 f    d}| j                   #t        |dt        |       j                  iz        y)a  Checks if the model was fitted by verifying the presence of self.matches.

    Arguments:
        topic_model: BERTopic instance for which the check is performed.

    Returns:
        None

    Raises:
        ValueError: If the matches were not found.
    zlThis %(name)s instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.Nname)topics_rD   typer3   )topic_modelmsgs     r   check_is_fittedrO   A   s;     yC"[(9(B(BCCDD #r   c                   $    e Zd ZdZddZd Zd Zy)NotInstalledzThis object is used to notify the user that additional dependencies need to be
    installed in order to use the string matching model.
    Nc                     || _         || _        d| j                    d}|||z  }|| _        y |d| j                   dz  }|| _        y )NzIn order to use z  you will need to install via;

zpip install bertopic[z]

)tooldeprN   )r   rS   rT   
custom_msgrN   s        r   r   zNotInstalled.__init__X   s]    	 +MN!:C  *488*E::Cr   c                 ,    t        | j                        r   ModuleNotFoundErrorrN   r   argskwargss      r   __getattr__zNotInstalled.__getattr__c       !$((++r   c                 ,    t        | j                        r   rW   rY   s      r   __call__zNotInstalled.__call__f   r]   r   r   )r3   r4   r5   __doc__r   r\   r_   r6   r   r   rQ   rQ   S   s    	,,r   rQ   c                    | j                   }t        |      dk(  r|d   }|||dz
  z  dz  k7  rmt        d      t        |      dk(  r=|d   |k7  s|d   |k7  rt        d      t        j                  | d       t        |       } nt        dt        |      z        t        j                  | dk        rt        d      | S )a_  Validate the distance matrix and convert it to a condensed distance matrix
    if necessary.

    A valid distance matrix is either a square matrix of shape (n_samples, n_samples)
    with zeros on the diagonal and non-negative values or condensed distance matrix
    of shape (n_samples * (n_samples - 1) / 2,) containing the upper triangular of the
    distance matrix.

    Arguments:
        X: Distance matrix to validate.
        n_samples: Number of samples in the dataset.

    Returns:
        X: Validated distance matrix.

    Raises:
        ValueError: If the distance matrix is not valid.
    r+   r      z;The condensed distance matrix must have shape (n*(n-1)/2,).zMThe distance matrix must be of shape (n, n) where n is the number of samples.zThe distance matrix must be either a 1-D condensed distance matrix of shape (n*(n-1)/2,) or a 2-D square distance matrix of shape (n, n).where n is the number of documents.Got a distance matrix of shape %sz/Distance matrix cannot contain negative values.)rE   r0   rD   rB   fill_diagonalr   r<   r=   )X	n_samplessns       r   validate_distance_matrixrh   j   s    ( 	
A
1v{aDi!m,q01Z[[	Q1aDI1Q49#4lmm
AqM0 36a&	9
 	
 
vva!e}JKKHr   distsreturnc                 \     j                         }t         j                  d   dz
        D ]{       dz      k(  st         fd dz   d D            |z         }t	        |||   z
        }t
        j                  j                  |   |dz  z   |   |z         |dz   <   } |S )a  Check if the consecutive elements in the distance array are the same. If so, a small noise
    is added to one of the elements to make sure that the array does not contain duplicates.

    Arguments:
        dists: distance array sorted in the increasing order.
        noise_max: the maximal magnitude of noise to be added.

    Returns:
         Unique distances sorted in the preserved increasing order.
    r   r+   c              3   4   K   | ]  }|   k7  s|  y wr   r6   ).0dri   is     r   	<genexpr>z'get_unique_distances.<locals>.<genexpr>   s     $P1!uQx-Q$Ps   Nrb   )lowhigh)copyrangerE   nextminrB   randomuniform)ri   	noise_maxdists_cpnext_unique_distcurr_max_noisero   s   `    @r   get_unique_distancesr}      s     zz|H5;;q>A%& y8uQU|##$Pa!eg$PRWXYRZ]fRfg !,<x{,JKN ii//HQK.STBT4T[cde[fiw[w/xHQUOy Or   ctfidf_embeddingsrF   
use_ctfidfoutput_ndarrayc                    dt         t        j                  t        f   dt        j                  fd}t	               }|r| |j                  d       |d}}n!| d}}n||j                  d       | d}}n|d}}|r
 ||      |fS ||fS )a  Select the topic representation.

    Arguments:
        ctfidf_embeddings: The c-TF-IDF embedding matrix
        embeddings: The topic embedding matrix
        use_ctfidf: Whether to use the c-TF-IDF representation. If False, topics embedding representation is used, if it
                    exists. Default is True.
        output_ndarray: Whether to convert the selected representation into ndarray
    Raises
        ValueError:
            - If no topic representation was found
            - If c-TF-IDF embeddings are not a numpy array or a scipy.sparse.csr_matrix

    Returns:
        The selected topic representation and a boolean indicating whether it is c-TF-IDF.
    arrayrj   c                 F    t        | t              r| j                         S | S r   )r8   r   toarray)r   s    r   
to_ndarrayz/select_topic_representation.<locals>.to_ndarray   s    eZ(==?"r   zyNo c-TF-IDF matrix was found despite it is supposed to be used (`use_ctfidf` is True). Defaulting to semantic embeddings.FTzNo topic embeddings were found despite they are supposed to be used (`use_ctfidf` is False). Defaulting to c-TF-IDF representation.)r   rB   rC   r   r   r!   )r~   rF   r   r   r   r   repr_ctfidf_useds           r   select_topic_representationr      s    .%

J 67 BJJ 
 ZF$NN5 ",U;E!2D;ENN9 "3D;E!+U;E .:e;FFE;FFr   c                        e Zd ZdZdedefdZy)MockPlotlyModulezBMock module that raises an error when plotly functions are called.rJ   rj   c                     fd}|S )Nc                  "    t        d d      )NzPlotly is required to use 'z('. Install it with uv pip install plotly)ImportError)rZ   r[   rJ   s     r   mock_functionz3MockPlotlyModule.__getattr__.<locals>.mock_function   s     ;D6Aijkkr   r6   )r   rJ   r   s    ` r   r\   zMockPlotlyModule.__getattr__   s    	l r   N)r3   r4   r5   r`   r<   r	   r\   r6   r   r   r   r      s    L  r   r   )gHz>)NNTF)numpyrB   pandasr9   r   collections.abcr   scipy.sparser   scipy.spatial.distancer   typingr   r   r   r	   r   r@   rH   rO   rQ   rh   r   r}   rC   boolr   r   r6   r   r   <module>r      s       $ # - . .= =<iE$, ,..b RXX 2 BF:> 	1Gbjj*&< =>1Grzz:5671G 1G 	1G
 2::t1Gh r   