
    WiK"                         d dl Z d dlZd dlmZ d dlmZ d dlmZmZm	Z	m
Z
mZ d dlmZ d dlmZmZ dZdZ G d	 d
e      Zy)    N)tqdm)
csr_matrix)MappingListTupleUnionCallable)BaseRepresentation)truncate_document%validate_truncate_document_parametersa  
This is a list of texts where each collection of texts describe a topic. After each collection of texts, the name of the topic they represent is mentioned as a short-highly-descriptive title
---
Topic:
Sample texts from this topic:
- Traditional diets in most cultures were primarily plant-based with a little meat on top, but with the rise of industrial style meat production and factory farming, meat has become a staple food.
- Meat, but especially beef, is the word food in terms of emissions.
- Eating meat doesn't make you a bad person, not eating meat doesn't make you a good one.

Keywords: meat beef eat eating emissions steak food health processed chicken
Topic name: Environmental impacts of eating meat
---
Topic:
Sample texts from this topic:
- I have ordered the product weeks ago but it still has not arrived!
- The website mentions that it only takes a couple of days to deliver but I still have not received mine.
- I got a message stating that I received the monitor but that is not true!
- It took a month longer to deliver than was advised...

Keywords: deliver weeks product shipping long delivery received arrived arrive week
Topic name: Shipping and delivery issues
---
Topic:
Sample texts from this topic:
[DOCUMENTS]
Keywords: [KEYWORDS]
Topic name:z@You are an assistant that extracts high-level topics from texts.c                       e Zd ZdZ	 	 	 	 	 	 	 	 ddededz  dedz  dedz  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ed        Zy)Cohereav  Use the Cohere API to generate topic labels based on their
    generative model.

    Find more about their models here:
    https://docs.cohere.ai/docs

    Arguments:
        client: A `cohere.Client`
        model: Model to use within Cohere, defaults to `"xlarge"`.
        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.
        system_prompt: The system prompt to be used in the model. If no system prompt is given,
                       `self.default_system_prompt_` is used instead.
        delay_in_seconds: The delay in seconds between consecutive prompts
                                in order to prevent RateLimitErrors.
        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 this, you will need to install cohere first:

    `pip install cohere`

    Then, get yourself an API key and use Cohere's API as follows:

    ```python
    import cohere
    from bertopic.representation import Cohere
    from bertopic import BERTopic

    # Create your representation model
    co = cohere.Client(my_api_key)
    representation_model = Cohere(co)

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

    You can also use a custom prompt:

    ```python
    prompt = "I have the following documents: [DOCUMENTS]. What topic do they contain?"
    representation_model = Cohere(co, prompt=prompt)
    ```
    Nmodelpromptsystem_promptdelay_in_secondsnr_docs	diversity
doc_length	tokenizerc
                    || _         || _        ||nt        | _        ||nt        | _        t        | _        t        | _        || _        || _	        || _
        || _        |	| _        t        | j                  | j                         g | _        y )N)clientr   DEFAULT_PROMPTr   DEFAULT_SYSTEM_PROMPTr   default_prompt_default_system_prompt_r   r   r   r   r   r   prompts_)
selfr   r   r   r   r   r   r   r   r   s
             k/home/sietch6/trending-topics-pipeline/venv/lib/python3.12/site-packages/bertopic/representation/_cohere.py__init__zCohere.__init__o   s}     
 & 2f.;.G]Mb-&;# 0"$"-dnndooN    	documentsc_tf_idftopicsreturnc           
         |j                  |||d| j                  | j                        \  }}}}i }t        |j	                         |j
                         D ]  \  }}	|	D 
cg c]$  }
t        || j                  | j                  |
      & }}
| j                  |||      }| j                  j                  |       | j                  rt        j                  | j                         | j                  j!                  | j"                  | j$                  |ddg      }|j&                  j)                         }|dfgt+        d      D cg c]  }d c}z   ||<    |S c c}
w c c}w )	a  Extract topics.

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

        Returns:
            updated_topics: Updated topic representations
        i  )disable2   
)r   preamblemessage
max_tokensstop_sequences   	   ) r   )_extract_representative_docsr   r   r   itemsverboser   r   r   _create_promptr   appendr   timesleepr   chatr   r   textstriprange)r   topic_modelr"   r#   r$   repr_docs_mappings_updated_topicstopicdocsdoctruncated_docsr   requestlabels                  r   extract_topicszCohere.extract_topics   sU   & '2&N&NidllDNN'
#Aq!
  2 8 8 :H[H[D[\ 	OKE4nrsgj/T__dnn^absNs((GFMM  ( $$

4001kk&&jj++ $v ' G LL&&(E&+QZLU1X3NG3N$NN5!#	O& % t  4Os   ")E	E!c                 `   t        t        ||          }| j                  t        k(  r?| j                  j	                  ddj                  |            }| j                  ||      }|S | j                  }d|v r!|j	                  ddj                  |            }d|v r| j                  ||      }|S )Nz
[KEYWORDS]z, [DOCUMENTS])nextzipr   r   replacejoin_replace_documents)r   rA   r@   r$   keywordsr   s         r   r4   zCohere._create_prompt   s    VE]+, ;;.([[((tyy7JKF,,VT:F  [[Fv%dii6IJ&00>r!   c                 N    d}|D ]  }|d| dz  } | j                  d|      } | S )Nr0   z- r)   rH   )rK   )r   rA   
to_replacerB   s       r   rM   zCohere._replace_documents   s=    
 	'CBse2,&J	'z:r!   )z	command-rNNN   NNN)__name__
__module____qualname____doc__strfloatintr   r	   r    pd	DataFramer   r   r   r   rF   r4   staticmethodrM    r!   r   r   r   )   s   CP !!$()-"&!%15  d
	
 Tz  $,  4< $J h'$.6, <<, 	,
 T%U
"3445, 
d5e,--	.,\&  r!   r   )r6   pandasrY   r   scipy.sparser   typingr   r   r   r   r	   bertopic.representation._baser
   bertopic.representation._utilsr   r   r   r   r   r\   r!   r   <module>rb      s<       # 8 8 < c8 [ h hr!   