
    Wi%                         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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)Llama)MappingListTupleAny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i ddddfdeeef   dedz  dedz  deeef   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)LlamaCPPa  A llama.cpp implementation to use as a representation model.

    Arguments:
        model: Either a string pointing towards a local LLM or a
                `llama_cpp.Llama` object.
        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.
        pipeline_kwargs: Kwargs that you can pass to the `llama_cpp.Llama`
                         when it is called such as `max_tokens` to be generated.
        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 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 llama.cpp, first download the LLM:

    ```bash
    wget https://huggingface.co/TheBloke/zephyr-7B-alpha-GGUF/resolve/main/zephyr-7b-alpha.Q4_K_M.gguf
    ```

    Then, we can now use the model the model with BERTopic in just a couple of lines:

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

    # Use llama.cpp to load in a 4-bit quantized version of Zephyr 7B Alpha
    representation_model = LlamaCPP("zephyr-7b-alpha.Q4_K_M.gguf")

    # Create our BERTopic model
    topic_model = BERTopic(representation_model=representation_model, verbose=True)
    ```

    If you want to have more control over the LLMs parameters, you can run it like so:

    ```python
    from bertopic import BERTopic
    from bertopic.representation import LlamaCPP
    from llama_cpp import Llama

    # Use llama.cpp to load in a 4-bit quantized version of Zephyr 7B Alpha
    llm = Llama(model_path="zephyr-7b-alpha.Q4_K_M.gguf", n_gpu_layers=-1, n_ctx=4096, stop="Q:")
    representation_model = LlamaCPP(llm)

    # Create our BERTopic model
    topic_model = BERTopic(representation_model=representation_model, verbose=True)
    ```
    N   modelpromptsystem_promptpipeline_kwargsnr_docs	diversity
doc_length	tokenizerc	                    t        |t              rt        |ddd      | _        n#t        |t              r|| _        nt	        d      ||nt
        | _        ||nt        | _        t
        | _	        t        | _
        || _        || _        || _        || _        || _        t!        | j                  | j                         g | _        y )N
ChatML)
model_pathn_gpu_layersstopchat_formatzpMake sure that the model that youpass is either a string referring to alocal LLM or a ` llama_cpp.Llama` object.)
isinstancestrr   r   
ValueError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   s	            m/home/sietch6/trending-topics-pipeline/venv/lib/python3.12/site-packages/bertopic/representation/_llamacpp.py__init__zLlamaCPP.__init__s   s     eS!%btYabDJu%DJ< 
 !' 2f.;.G]Mb-&;#."$"-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                  j                  ddd| j                  dd|dgi| j                  }|d   d   d	   d
   j!                         }|dfgt#        d      D cg c]  }d c}z   ||<    |S 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
        i  )disablemessagessystem)rolecontentuserchoicesr   messager7      	   ) r    )_extract_representative_docsr   r   r   itemsverboser   r   r   _create_promptr)   appendr   create_chat_completionr   r   striprange)r*   topic_modelr.   r/   r0   repr_docs_mappings_updated_topicstopicdocsdoctruncated_docsr   topic_descriptionlabels                  r+   extract_topicszLlamaCPP.extract_topics   s[   & '2&N&NidllDNN'
#Aq!  2 8 8 :H[H[D[\ 	OKE4nrsgj/T__dnn^absNs((GFMM  ( !B

 A A !#+8J8JKV\ioMpq!&&! &i03I>yIOOQE&+QZLU1X3NG3N$NN5!	O  t 4Os   ")D7"	D<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*   rL   rK   r0   keywordsr   s         r+   rB   zLlamaCPP._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 )Nr=   z- r   rS   )rV   )r   rL   
to_replacerM   s       r+   rX   zLlamaCPP._replace_documents   s=    
 	'CBse2,&J	'z:r-   )__name__
__module____qualname____doc__r
   r#   r   r   r	   intfloatr   r,   pd	DataFramer   r   r   rQ   rB   staticmethodrX   r>   r-   r+   r   r   )   s   GX "$(-/"&!%15 S%Z   d
  Tz	 
 !c*    4<  $J  h'$. D' <<' 	'
 T%U
"3445' 
d5e,--	.'R&  r-   r   )pandasrb   r   scipy.sparser   	llama_cppr   typingr   r   r   r	   r
   r   bertopic.representation._baser   bertopic.representation._utilsr   r   r%   r&   r   r>   r-   r+   <module>rk      s<      #  = = < c8 [ n! nr-   