
    Wi                         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	 d dl
mZmZmZmZmZmZ d dlmZ d dlmZmZ d	Z G d
 de      Zy)    N)tqdm)
csr_matrix)pipelineset_seed)Pipeline)MappingListTupleAnyUnionCallable)BaseRepresentation)truncate_document%validate_truncate_document_parametersz\
I have a topic described by the following keywords: [KEYWORDS].
The name of this topic is:
c                       e Zd ZdZdi dddddfdeeef   dedz  deeef   de	d	e	d
e
dz  de	dz  deeef   dz  fdZdej                  dedeeeeee
f      f   deeeeee
f      f   fdZd Zy)TextGenerationaw  Text2Text or text generation with transformers.

    Arguments:
        model: A transformers pipeline that should be initialized as "text-generation"
               for gpt-like models or "text2text-generation" for T5-like models.
               For example, `pipeline('text-generation', model='gpt2')`. If a string
               is passed, "text-generation" will be selected by default.
        prompt: The prompt to be used in the model. If no prompt is given,
                `self.default_prompt_` is used instead.
                NOTE: Use `"[KEYWORDS]"` and `"[DOCUMENTS]"` in the prompt
                to decide where the keywords and documents need to be
                inserted.
        pipeline_kwargs: Kwargs that you can pass to the transformers.pipeline
                         when it is called.
        random_state: A random state to be passed to `transformers.set_seed`
        nr_docs: The number of documents to pass to OpenAI if a prompt
                 with the `["DOCUMENTS"]` tag is used.
        diversity: The diversity of documents to pass to OpenAI.
                   Accepts values between 0 and 1. A higher
                   values results in passing more diverse documents
                   whereas lower values passes more similar documents.
        doc_length: The maximum length of each document. If a document is longer,
                    it will be truncated. If None, the entire document is passed.
        tokenizer: The tokenizer used to calculate to split the document into segments
                   used to count the length of a document.
                       * If tokenizer is 'char', then the document is split up
                         into characters which are counted to adhere to `doc_length`
                       * If tokenizer is 'whitespace', the document is split up
                         into words separated by whitespaces. These words are counted
                         and truncated depending on `doc_length`
                       * If tokenizer is 'vectorizer', then the internal CountVectorizer
                         is used to tokenize the document. These tokens are counted
                         and truncated depending on `doc_length`
                       * If tokenizer is a callable, then that callable is used to tokenize
                         the document. These tokens are counted and truncated depending
                         on `doc_length`

    Usage:

    To use a gpt-like model:

    ```python
    from bertopic.representation import TextGeneration
    from bertopic import BERTopic

    # Create your representation model
    generator = pipeline('text-generation', model='gpt2')
    representation_model = TextGeneration(generator)

    # Use the representation model in BERTopic on top of the default pipeline
    topic_model = BERTo pic(representation_model=representation_model)
    ```

    You can use a custom prompt and decide where the keywords should
    be inserted by using the `[KEYWORDS]` or documents with thte `[DOCUMENTS]` tag:

    ```python
    from bertopic.representation import TextGeneration

    prompt = "I have a topic described by the following keywords: [KEYWORDS]. Based on the previous keywords, what is this topic about?""

    # Create your representation model
    generator = pipeline('text2text-generation', model='google/flan-t5-base')
    representation_model = TextGeneration(generator)
    ```
    N*      modelpromptpipeline_kwargsrandom_statenr_docs	diversity
doc_length	tokenizerc	                 |   || _         t        |       t        |t              rt	        d|      | _        n#t        |t              r|| _        nt        d      ||nt        | _	        t        | _
        || _        || _        || _        || _        || _        t!        | j                  | j                         g | _        y )Nztext-generation)r   zwMake sure that the HF model that youpass is either a string referring to aHF model or a `transformers.pipeline` object.)r   r   
isinstancestrr   r   r   
ValueErrorDEFAULT_PROMPTr   default_prompt_r   r   r   r   r   r   prompts_)	selfr   r   r   r   r   r   r   r   s	            s/home/sietch6/trending-topics-pipeline/venv/lib/python3.12/site-packages/bertopic/representation/_textgeneration.py__init__zTextGeneration.__init__U   s     )eS!!"35ADJx(DJ@ 
 !' 2f-."$"-dnndooN    	documentsc_tf_idftopicsreturnc           
      (   | j                   t        k7  r>d| j                   v r0|j                  |||d| j                  | j                        \  }}}}n|j                         D ci c]  }|d }}i }t        |j                         |j                         D ]  \  }}	|	0|	D 
cg c]$  }
t        || j                  | j                  |
      & c}
n|	}| j                  |||      }| j                  j                  |        | j                  |fi | j                   }|D cg c]  }|d   j#                  |d      df }}t%        |      dk  r(|t'        dt%        |      z
        D cg c]  }d	 c}z  }|||<    |S c c}w c c}
w c c}w c c}w )
aO  Extract topic representations and return a single label.

        Arguments:
            topic_model: A BERTopic model
            documents: Not used
            c_tf_idf: Not used
            topics: The candidate topics as calculated with c-TF-IDF

        Returns:
            updated_topics: Updated topic representations
        [DOCUMENTS]i  N)disablegenerated_text    
   )r0   r   )r   r!   _extract_representative_docsr   r   keysr   itemsverboser   r   r   _create_promptr#   appendr   r   replacelenrange)r$   topic_modelr(   r)   r*   repr_docs_mappings_topicupdated_topicsdocsdoctruncated_docsr   topic_descriptiondescriptions                  r%   extract_topicszTextGeneration.extract_topicsw   s   & ;;.(]dkk-I*5*R*R)VS$,,+'1a <B;;=!I%%+!I!I 2 8 8 :H[H[D[\ 	6KE4 # bffZ]";QTUf 
 ((GFMM  ( !+

6 JT5I5I JZk!KV-.66vrBAF! ! $%*!uR#FWBX=X7Y%Z!g%ZZ!$5N5!'	6* 1 "J g!
 &[s   $
F $)F!F
)	Fc                 B   dj                  t        t        ||                }| j                  t        k(  r| j                  j                  d|      }|S | j                  }d|v r|j                  d|      }d|v r$d}|D ]  }|d| dz  } |j                  d|      }|S )Nz, z
[KEYWORDS]r-   r0   z- 
)joinnextzipr   r!   r9   )r$   rA   r?   r*   keywordsr   
to_replacerB   s           r%   r7   zTextGeneration._create_prompt   s    99T#ve}"567 ;;.([[((x@F  [[Fv%h?&
 /CBse2,.J/zBr'   )__name__
__module____qualname____doc__r   r   r   r   r   intfloatr   r&   pd	DataFramer   r	   r
   rF   r7    r'   r%   r   r      s   AL "-/"&!%15 S(]#  d
  !c*	 
     4<  $J  h'$. D0 <<0 	0
 T%U
"34450 
d5e,--	.0dr'   r   )pandasrT   r   scipy.sparser   transformersr   r   transformers.pipelines.baser   typingr   r	   r
   r   r   r   bertopic.representation._baser   bertopic.representation._utilsr   r   r!   r   rV   r'   r%   <module>r^      s6      # + 0 = = < ck' kr'   