
    WiQ                     8   d dl Zd dlZd dlmZmZ d dlmZ 	 d dl	Z	d dl
mZ dddddd	dd
ddddi i fdee   dz  dee   dz  dej                   dej                   deeef   dedeedf   dedededededededefdZy# e$ r  ed        G d de      ZY vw xY w)    N)ListUnion)warn)FigurezAData map plotting is unavailable unless datamapplot is installed.c                       e Zd Zy)r   N)__name__
__module____qualname__     f/home/sietch6/trending-topics-pipeline/venv/lib/python3.12/site-packages/bertopic/plotting/_datamap.pyr   r      s    r   r   FzDocuments and Topicsi  i  docstopics
embeddingsreduced_embeddingscustom_labelstitle	sub_titlewidthheightinteractiveenable_searchtopic_prefixdatamap_kwdsint_datamap_kwdsreturnc                 T   | j                   }t        j                  dt        j                  |      i      }||d<   ||d<   |.|,| j                  |j                  j                         d      }n|}|/	 ddlm	}  |dd	d
d      j                  |      }|j                  }n|}t        |      }t        |t               r|D cg c]#  }t!        |      dgg| j"                  |   |   z   % }}|D cg c]'  }dj%                  |dd D cg c]  }|d   	 c}      ) }}}|D cg c]  }t'        |      dk  r|n|dd dz    }}n| j(                  ,|r*|D cg c]  }| j(                  || j*                  z        }}n|rO|D cg c]?  }d| ddj%                  | j-                  |      D cg c]  \  }}|	 c}}dd       z   A }}}}nG|D cg c]8  }dj%                  | j-                  |      D cg c]  \  }}|	 c}}dd       : }}}}t/        ||      D ci c]  \  }}||
 }}}d|d<   |t        |      }|D ]  }||vsd||<    t        j0                  |      j3                  |      j4                  } |
rt7        j8                  || f||||	d|}!|!S t7        j:                  || f|dz  |	dz  fd||d|\  }!}"|!S # 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 c c}}w c c}}}w c c}}w )a  Visualize documents and their topics in 2D as a static plot for publication using
    DataMapPlot.

    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]`. Documents not in these topics will be shown
                as noise points.
        embeddings:  The embeddings of all documents in `docs`.
        reduced_embeddings:  The 2D reduced embeddings of all documents in `docs`.
        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.
        sub_title: Sub-title of the plot.
        width: The width of the figure.
        height: The height of the figure.
        interactive: Whether to create an interactive plot using DataMapPlot's `create_interactive_plot`.
        enable_search: Whether to enable search in the interactive plot. Only works if `interactive=True`.
        topic_prefix: Prefix to add to the topic number when displaying the topic name.
        datamap_kwds:  Keyword args be passed on to DataMapPlot's `create_plot` function
                       if you are not using the interactive version.
                       See the DataMapPlot documentation for more details.
        int_datamap_kwds:  Keyword args be passed on to DataMapPlot's `create_interactive_plot` function
                           if you are using the interactive version.
                           See the DataMapPlot documentation for more details.

    Returns:
        figure: A Matplotlib Figure object.

    Examples:
    To visualize the topics simply run:

    ```python
    topic_model.visualize_document_datamap(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_document_datamap(docs, embeddings=embeddings)

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

    Or if you want to save the resulting figure:

    ```python
    fig = topic_model.visualize_document_datamap(docs, reduced_embeddings=reduced_embeddings)
    fig.savefig("path/to/file.png", bbox_inches="tight")
    ```
    <img src="../../getting_started/visualization/datamapplot.png",
         alt="DataMapPlot of 20-Newsgroups", width=800, height=800></img>
    topicdocNdocument)methodr   )UMAP      g333333?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`.          z...zTopic-z:    
Unlabelled)
hover_textr   r   r   d   )figsizedpir   r   )topics_pd	DataFramenparray_extract_embeddingsr   to_listumapr"   fit
embedding_ImportErrorModuleNotFoundErrorset
isinstancestrtopic_aspects_joinlencustom_labels_	_outliers	get_topiczipSeriesmapvaluesdatamapplotcreate_interactive_plotcreate_plot)#topic_modelr   r   r   r   r   r   r   r   r   r   r   r   r   r   topic_per_docdfembeddings_to_reducer"   
umap_modelembeddings_2dunique_topicsr   nameslabelslabelwordvalue	topic_num
topic_nametopic_name_mappingselected_topicsnamed_topic_per_docfigure_s#                                      r   visualize_document_datamaprd      s   z  ''M	w 78	9BBuIBwK 08*>>rvv~~?OXb>c) !	!"1tT\]aabvwJ&11M +&M -%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 +  r"SXX{G\G\]bGc.det.degfg.h%iiE 
 huuu^cSXX{7L7LU7STetTUWVWXYuEuMPQ^`eMfg4IIz)Z/gg)r f++ 	=I/0<"9-	=
 ))M2667IJQQ44
 '
 
( M  ++
 S[&3,/
 
	 Mw 01 	% N 	 u<RUf /e
 Uugsl   6-K (K04K:K5	K:'L #L	)L2L
>L$L<LL(L$K-5K:
LL)numpyr8   pandasr6   typingr   r   warningsr   rN   matplotlib.figurer   r?   objectrC   intndarraybooldictrd   r   r   r   <module>ro      sC      ( "#!%)&+'"&k
s)d
k Ik 

	k
 

k s#k k S$Yk k k k k k k k  !k  	LM 	s   
A> >BB