
    WiF,                         d dl Z 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mZ d dlmZ d dlmZmZmZ dZdZ G d	 d
e      Zd Zy)    N)tqdm)
csr_matrix)MappingListTupleAnyUnionCallable)BaseRepresentation)retry_with_exponential_backofftruncate_document%validate_truncate_document_parametersa+  You will extract a short topic label from given documents and keywords.
Here are two examples of topics you created before:

# Example 1
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 worst 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: Environmental impacts of eating meat

# Example 2
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: Shipping and delivery issues

# Your task
Sample texts from this topic:
[DOCUMENTS]

Keywords: [KEYWORDS]

Based on the information above, extract a short topic label (three words at most) in the following format:
topic: <topic_label>
z@You are an assistant that extracts high-level topics from texts.c                      e Zd ZdZdddi ddddddf
dededz  dedz  d	eeef   d
edz  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ed        Zy)OpenAIa}  Using the OpenAI API to generate topic labels based
    on one of their Completion of ChatCompletion models.

    For an overview see:
    https://platform.openai.com/docs/models

    Arguments:
        client: A `openai.OpenAI` client
        model: Model to use within OpenAI, defaults to `"gpt-4o-mini"`.
        generator_kwargs: Kwargs passed to `openai.Completion.create`
                          for fine-tuning the output.
        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.
        exponential_backoff: Retry requests with a random exponential backoff.
                             A short sleep is used when a rate limit error is hit,
                             then the requests is retried. Increase the sleep length
                             if errors are hit until 10 unsuccessful requests.
                             If True, overrides `delay_in_seconds`.
        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 the openai package first:

    `pip install openai`

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

    ```python
    import openai
    from bertopic.representation import OpenAI
    from bertopic import BERTopic

    # Create your representation model
    client = openai.OpenAI(api_key=MY_API_KEY)
    representation_model = OpenAI(client, delay_in_seconds=5)

    # 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] \nThese documents are about the following topic: '"
    representation_model = OpenAI(client, prompt=prompt, delay_in_seconds=5)
    ```

    To choose a model:

    ```python
    representation_model = OpenAI(client, model="gpt-4o-mini", delay_in_seconds=10)
    ```
    zgpt-4o-miniNF   modelpromptsystem_promptgenerator_kwargsdelay_in_secondsexponential_backoffnr_docs	diversity
doc_length	tokenizerc                 r   || _         || _        |t        | _        n|| _        |t        | _        n|| _        t        | _        t        | _        || _        || _	        || _
        |	| _        |
| _        || _        t        | j                  | j                         g | _        || _        | j                   j#                  d      r#|j#                  d      | _        | j                   d= | j                   j#                  d      r| j                   d= | j                   j#                  d      sd| j                   d<   y y )Nr   r   stop
)clientr   DEFAULT_CHAT_PROMPTr   DEFAULT_SYSTEM_PROMPTr   default_prompt_default_system_prompt_r   r   r   r   r   r   r   prompts_r   get)selfr   r   r   r   r   r   r   r   r   r   r   kwargss                k/home/sietch6/trending-topics-pipeline/venv/lib/python3.12/site-packages/bertopic/representation/_openai.py__init__zOpenAI.__init__   s    
>-DK DK !6D!.D2&;# 0#6 "$"-dnndooN 0  $$W-)--g6DJ%%g.  $$X.%%h/$$((0,0D!!&) 1    	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                         d| j                  dd|dg}| j                   |d| j"                  }| j$                  rt'        | j(                  fi |}n0 | j(                  j*                  j,                  j.                  di |}|ret1        |j2                  d   j4                  d      rB|j2                  d   j4                  j6                  j9                         j;                  d	d
      }nd}|dfg||<    |S c c}
w )aJ  Extract topics.

        Arguments:
            topic_model: A BERTopic model
            documents: All input documents
            c_tf_idf: The topic c-TF-IDF representation
            topics: The candidate topics as calculated with c-TF-IDF

        Returns:
            updated_topics: Updated topic representations
        i  )disablesystem)rolecontentuser)r   messagesr   r3   ztopic:  zNo label returned    )_extract_representative_docsr   r   r   itemsverboser   r   r   _create_promptr$   appendr   timesleepr   r   r   r   chat_completions_with_backoffr   chatcompletionscreatehasattrchoicesmessager3   stripreplace)r&   topic_modelr+   r,   r-   repr_docs_mappings_updated_topicstopicdocsdoctruncated_docsr   r5   r'   responselabels                    r(   extract_topicszOpenAI.extract_topics   s   & '2&N&NidllDNN'
#Aq!
  2 8 8 :H[H[D[\ 	1KE4nrsgj/T__dnn^absNs((GFMM  ( $$

4001 "d.@.@AF3H
 $ ''F
 ''8OO>4;;++77>>HH
 GH$4$4Q$7$?$?K ((+33;;AACKKIWYZ+&+QZLN5!?	1B A ts   #)G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    rH   join_replace_documents)r&   rN   rM   r-   keywordsr   s         r(   r<   zOpenAI._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 )Nr6   z- r   rU   )rH   )r   rN   
to_replacerO   s       r(   rY   zOpenAI._replace_documents  s=    
 	'CBse2,&J	'z:r*   )__name__
__module____qualname____doc__strr   r   floatboolintr	   r
   r)   pd	DataFramer   r   r   rS   r<   staticmethodrY   r8   r*   r(   r   r   2   s9   Pj #!$(.0)-$)"&!%15/1 /1 d
	/1
 Tz/1 "#s(+/1  $,/1 "/1 /1 4</1 $J/1 h'$./1b: <<: 	:
 T%U
"3445: 
d5e,--	.:x&  r*   r   c                      t        | j                  j                  j                  t        j
                  f      di |S )N)errorsr8   )r   rA   rB   rC   openaiRateLimitError)r   r'   s     r(   r@   r@     sB    )&&%%'  	 r*   )r>   rj   pandasre   r   scipy.sparser   typingr   r   r   r   r	   r
   bertopic.representation._baser   bertopic.representation._utilsr   r   r   r    r!   r   r@   r8   r*   r(   <module>rq      sN        # = = <  @ [ Y Yxr*   