# =============================================================================
# Supplementary File S2
# Democratic LLM topic naming (Pipeline Stage 2)
#
# Archival transcription of Appendix 2 of the source dissertation:
# Thomas, J. E. (2025). Alcohol Marketing on Social Media During the COVID-19
# Pandemic: Historical Perspectives, Modern Evidence, and Future Regulation.
# The University of Texas at Austin.
#
# Environment of record: Python 3.9.12; openai==0.27.0 (legacy SDK).
# This file is preserved verbatim for archival transparency. A maintained
# implementation against the current OpenAI SDK is provided with the working
# pipeline that accompanies this paper (stage2_democratic_naming.py).
# =============================================================================

# Dependencies
### This script was written under previous OpenAI API versions. Before Running:
### pip install openai==0.27.0; after running: pip install --upgrade openai
import openai
import pandas as pd
from tqdm import tqdm
import time

# Set up OpenAI API key
openai.api_key = "********"  # Replace "api_key" with your actual OpenAI API key

# Load the dataset
df = pd.read_csv('topics_for_gpt.csv')
# Where topics_for_gpt.csv is a dataset with two columns:
# numeric topic number (value from BERTopic model),
# words (array of representative words from BERTopic model);
# rows iterated 5000 times

# Function to call GPT-4o and get a topic name with error handling
def get_topic_name(words, max_retries=5):
    prompt = (f"The following words represent a topic derived from tweets generated by alcohol companies "
              f"during the COVID-19 pandemic: {words}. "
              f"Please provide a concise, meaningful topic name that clearly summarizes these words. ")

    retries = 0
    while retries < max_retries:
        try:
            response = openai.ChatCompletion.create(
                model="gpt-4o",
                messages=[
                    {"role": "system", "content": "You are an expert at naming topics."},
                    {"role": "user", "content": prompt}
                ],
                max_tokens=15,
                temperature=0.5,
                n=1,
                stop=None
            )
            topic_name = response['choices'][0]['message']['content'].strip()
            return topic_name

        except openai.error.APIError as e:
            print(f"APIError: {e}. Retrying ({retries + 1}/{max_retries})...")
            retries += 1
            time.sleep(2 ** retries)  # Exponential backoff

        except openai.error.RateLimitError as e:
            print(f"RateLimitError: {e}. Retrying ({retries + 1}/{max_retries})...")
            retries += 1
            time.sleep(2 ** retries)  # Exponential backoff

        except openai.error.Timeout as e:
            print(f"TimeoutError: {e}. Retrying ({retries + 1}/{max_retries})...")
            retries += 1
            time.sleep(2 ** retries)  # Exponential backoff

        except Exception as e:
            print(f"Unexpected error: {e}. Retrying ({retries + 1}/{max_retries})...")
            retries += 1
            time.sleep(2 ** retries)  # Exponential backoff

    # If all retries fail, return a placeholder or handle it accordingly
    print(f"Failed to get a response after {max_retries} retries.")
    return "Error: Unable to generate topic name"

# Loop through each row and generate the topic name with a progress bar
tqdm.pandas()

df['GPT'] = df['Words'].progress_apply(lambda words: get_topic_name(words))

# Save the updated dataframe back to CSV
df.to_csv('topics_for_gpt_output.csv', index=False)

print("Completed!")
