
    Wii&                         d dl Zd dlZd dlmZ d dlmZm	Z	 	 	 	 	 	 	 	 	 	 	 ddee
   dee   dz  dej                  dej                  dedz  ded	ed
e	ee
f   de
dedefdZy)    N)ListUniondocstopics
embeddingsreduced_embeddingssamplehide_annotationshide_document_hovercustom_labelstitlewidthheightc                 @   | j                   }||dkD  rd}g }t        |      D ]  }t        j                  t        j                  |      |k(        d   }t        |      dk  rt        |      nt        t        |      |z        }|j                  t        j                  j                  ||d              t        j                  |      }t        j                  dt        j                  |      |   i      }|D cg c]  }||   	 c}|d<   |D cg c]  }||   	 c}|d<   |3|.|,| j                  |j                  j                         d	
      }n:|}n7|||   }n/|-|+| j                  |j                  j                         d	
      }|/	 ddlm}  |dddd      j#                        }|j$                  }n||||   }n|||}t        |      }||}dddf   |d<   |dddf   |d<   t+        |t,              r|D cg c]#  }t-        |      dgg| j.                  |   |   z   % }}|D cg c]'  }dj1                  |dd D cg c]  }|d   	 c}      ) }}}|D cg c]  }t        |      dk  r|n|dd dz    }}n| j2                  ,|r*|D cg c]  }| j2                  || j4                  z        }}nM|D cg c]>  }| ddj1                  | j7                  |      D cg c]  \  }}|	 c}}dd       z   @ }}}}t9        j:                         }t        |      j=                  |      }t        |      dk(  rdg}|j>                  |j@                  jC                  |      ddf   }d|d<   dd|jD                  jG                         |jH                  jG                         dg|j>                  t        |      ddf<   |jK                  t9        jL                  |jD                  |jH                  |s|j                  ndddddtO        d d!d"#      $             tQ        ||      D ]  \  } }||v s|dk7  s|j>                  |j@                  |k(  ddf   }d|d<   |sQdd|jD                  jG                         |jH                  jG                         | g|j>                  t        |      ddf<   |jK                  t9        jL                  |jD                  |jH                  |s|j                  ndd|jR                  d| tO        d%&      tO        d!d"'      (	              |jD                  jU                         tW        |jD                  jU                         d)z        z
  |jD                  jY                         tW        |jD                  jY                         d)z        z   f}!|jH                  jU                         tW        |jH                  jU                         d)z        z
  |jH                  jY                         tW        |jH                  jY                         d)z        z   f}"|j[                  d*t]        |!      dz  |"d   t]        |!      dz  |"d   tO        d d+      ,       |j[                  d*|!d   t]        |"      dz  |!d   t]        |"      dz  tO        d-d+      ,       |j_                  |!d   t]        |"      dz  d.dd/       |j_                  |"d   t]        |!      dz  d0dd1       |ja                  d2|	 d"d3d4tO        d5d67      d8|
|9       |jc                  d:       |je                  d:       |S c c}w c c}w # t&        t(        f$ r t)        d      w xY wc c}w c c}w c c}}w c c}w c c}w c c}}w c c}}}w );a  Visualize documents and their topics in 2D.

    Arguments:
        topic_model: A fitted BERTopic instance.
        docs: The documents you used when calling either `fit` or `fit_transform`
        topics: A selection of topics to visualize.
                Not to be confused with the topics that you get from `.fit_transform`.
                For example, if you want to visualize only topics 1 through 5:
                `topics = [1, 2, 3, 4, 5]`.
        embeddings: The embeddings of all documents in `docs`.
        reduced_embeddings: The 2D reduced embeddings of all documents in `docs`.
        sample: The percentage of documents in each topic that you would like to keep.
                Value can be between 0 and 1. Setting this value to, for example,
                0.1 (10% of documents in each topic) makes it easier to visualize
                millions of documents as a subset is chosen.
        hide_annotations: Hide the names of the traces on top of each cluster.
        hide_document_hover: Hide the content of the documents when hovering over
                             specific points. Helps to speed up generation of visualization.
        custom_labels: If bool, whether to use custom topic labels that were defined using
                       `topic_model.set_topic_labels`.
                       If `str`, it uses labels from other aspects, e.g., "Aspect1".
        title: Title of the plot.
        width: The width of the figure.
        height: The height of the figure.

    Examples:
    To visualize the topics simply run:

    ```python
    topic_model.visualize_documents(docs)
    ```

    Do note that this re-calculates the embeddings and reduces them to 2D.
    The advised and preferred pipeline for using this function is as follows:

    ```python
    from sklearn.datasets import fetch_20newsgroups
    from sentence_transformers import SentenceTransformer
    from bertopic import BERTopic
    from umap import UMAP

    # Prepare embeddings
    docs = fetch_20newsgroups(subset='all',  remove=('headers', 'footers', 'quotes'))['data']
    sentence_model = SentenceTransformer("all-MiniLM-L6-v2")
    embeddings = sentence_model.encode(docs, show_progress_bar=False)

    # Train BERTopic
    topic_model = BERTopic().fit(docs, embeddings)

    # Reduce dimensionality of embeddings, this step is optional
    # reduced_embeddings = UMAP(n_neighbors=10, n_components=2, min_dist=0.0, metric='cosine').fit_transform(embeddings)

    # Run the visualization with the original embeddings
    topic_model.visualize_documents(docs, embeddings=embeddings)

    # Or, if you have reduced the original embeddings already:
    topic_model.visualize_documents(docs, reduced_embeddings=reduced_embeddings)
    ```

    Or if you want to save the resulting figure:

    ```python
    fig = topic_model.visualize_documents(docs, reduced_embeddings=reduced_embeddings)
    fig.write_html("path/to/file.html")
    ```

    <iframe src="../../getting_started/visualization/documents.html"
    style="width:1000px; height: 800px; border: 0px;""></iframe>
    N   r   d   F)sizereplacetopicdocdocument)method)UMAP
      g        cosine)n_neighborsn_componentsmin_distmetricz{UMAP is required if the embeddings are not yet reduced in dimensionality. Please install it using `pip install umap-learn`.xy_         z...    textzOther documentszmarkers+textotherz#CFD8DC   g      ?)colorr   opacity)r!   r"   	hovertext	hoverinfomodename
showlegendmarker   )r   )r   r.   )	r!   r"   r/   r0   r*   r1   r2   textfontr4   g333333?line)r-   r   )typex0y0x1y1r7   z#9E9E9ED1)r!   r"   r*   	showarrowyshiftD2)r"   r!   r*   r>   xshiftsimple_whitecentertop   Black)r   r-   )r*   r!   xanchoryanchorfont)templater   r   r   )visible)3topics_setnpwherearraylenintextendrandomchoicepd	DataFrame_extract_embeddingsr   to_listumapr   fit
embedding_ImportErrorModuleNotFoundError
isinstancestrtopic_aspects_joincustom_labels_	_outliers	get_topicgoFigure
differencelocr   isinr!   meanr"   	add_trace	Scattergldictzipr*   minabsmax	add_shapesumadd_annotationupdate_layoutupdate_xaxesupdate_yaxes)#topic_modelr   r   r   r   r	   r
   r   r   r   r   r   topic_per_docindicesr   sr   dfindexembeddings_to_reducer   
umap_modelembeddings_2dunique_topicsnameslabelslabelwordvaluefignon_selected_topics	selectionr2   x_rangey_ranges#                                      h/home/sietch6/trending-topics-pipeline/venv/lib/python3.12/site-packages/bertopic/plotting/_documents.pyvisualize_documentsr      sh   f  ''M ~!G]# FHHRXXm,56q9Q#s1v3s1v+?ryy''e'DEF hhwG	w 7 @A	BB*12e2BuI5<=E='=BwK ~"4"<#.#B#B266>>CS\f#B#g #- !#-g#6 $6$>#.#B#B266>>CS\f#B#g  !	!"1sS[\``auvJ&11M
 
	 2 >*73	.:*&M~ AqD!BsGAqD!BsG -%fst]b3u:t$%(B(B=(QRW(XXttLQR&<58<=RROTUe#e*r/uSbzE/AAUU		#	#	/MXefu++EK4I4I,IJff '
 
 gQK#((K<Q<QRW<X#Y[T5D#YZ\[\#]^^
 
 ))+C m,77?
1$!drxx}}%891<=IIf(IMM#i.!#$ MM
kkkk+>immDia=		
 5-0 eF?u{rxx50!34I "If#KK$$&KK$$&4	c)na/0 MMkkkk3FimmD$"'!  Q4@ 	
S"$$((*,--

S"$$((*,--G
 	
S"$$((*,--

S"$$((*,--G MMw<!1:w<!1:	+   MM1:w<!1:w<!	+   s7|a'7de\^_s7|a'7de\^_ gb0
    U#U#J} 3=* 01 	% N 	& u<RUf $Z
sZ   =]]-] (]9<^]>	^/^	##^(^7^^]6>^^)
NNNNFFFz<b>Documents and Topics</b>i  i  )numpyrN   pandasrV   plotly.graph_objectsgraph_objectsrf   typingr   r   r`   rR   ndarrayfloatboolr        r   <module>r      s      !   $!%)" %&+.
s) I 

	
 

 DL   s#   r   