[METHOD] Make Your Own PAA Site With OpenAI - Complete Tutorial + FREE Python Script

Yes, it's possible to get longer content (700-1200) words using a single prompt. The token count doesn't work like you think. Although restricting the number of tokens can result in shorter content, increasing the number of tokens doesn't increase the length of the output beyond a certain point.

For example, let's take a simple prompt: write a blog introduction paragraph for the topic XYZ.

Whether you set the tokens to 250 or 3500, it won't make any difference. You'll still get one paragraph.

Similarly, the number of tokens is not what's restricting your output. It's the prompt.

It takes approximately 1000 tokens to generate 750 words. But just setting 1000 as the number of tokens does not generate 750 words.

I know that it's not intuitive but that's how it works. Even with the best prompts ever, it'll be hard to generate 2000+ words using a single prompt. Once again, this is not because you run out of tokens.
Thanks: the reason why I thought it was token limited is that if you prototype prompts in the OpenAI playground, you can run out tokens quickly: OpenAI tells you you've used too many in the question and answer. So I guess I'm not really understanding this.
 
Technically, what is the difference between a PAA website and a normal blog? Does PAA use HTML tags in a specific order?

Technically, not much. Some sites include multiple PAA questions and answers on one page. Some sites have 1 article dedicated to 1 PAA question. It depends on what you feel like doing.

Thanks: the reason why I thought it was token limited is that if you prototype prompts in the OpenAI playground, you can run out tokens quickly: OpenAI tells you you've used too many in the question and answer. So I guess I'm not really understanding this.

Yes, on the lower end, the number of tokens can restrict your output. But after a certain point, the number of tokens doesn't matter and the length of your output will be similar regardless of the number of tokens you select.

I hope that makes sense.
 
Yes, it's possible to get longer content (700-1200) words using a single prompt. The token count doesn't work like you think. Although restricting the number of tokens can result in shorter content, increasing the number of tokens doesn't increase the length of the output beyond a certain point.

For example, let's take a simple prompt: write a blog introduction paragraph for the topic XYZ.

Whether you set the tokens to 250 or 3500, it won't make any difference. You'll still get one paragraph.

Similarly, the number of tokens is not what's restricting your output. It's the prompt.

It takes approximately 1000 tokens to generate 750 words. But just setting 1000 as the number of tokens does not generate 750 words.

I know that it's not intuitive but that's how it works. Even with the best prompts ever, it'll be hard to generate 2000+ words using a single prompt. Once again, this is not because you run out of tokens.
can anyone here give an example of a single prompt that will yield over 750 words?
 
No need to waste money on buying PAA sites. You can make your own PAA site with hundreds of posts in a few hours.

Here's an easy tutorial and python script to make your own PAA site.

I don't like combining multiple PAA questions in one post so tutorial will show you how to create an article for each PAA question.

The only thing you'll need to refine is the prompt you use to create the content with OpenAI. I've included a very basic prompt. The output with this prompt is not going to be great. The output may even be too short to be usable.

You'll need to come up with your own prompts that are tailored for your niche.

DO NOT skip this step.

Prompts are the most important part of the entire process. Take some time and come up with a great prompt that'll produce high quality content.




Step 1: Select a niche

I recommend selecting a sub-niche within a broader niche. Working with smaller niches is much easier and you can build topical authority and rank quickly. For this tutorial, I'm going to use "Yerba Mate" as an example.

If this is your first time, I recommend selecting a super small niche like the one in the example.

Step 2: SEO Minion

Step 2 is straight forward. Use a VPN server in your target country, Google the main head term and scrape the PAA using the SEO Minion Chrome extension. You can use as many levels as you like. I'm using 8 levels for this example.

Step 3: Remove Duplicates

Use Excel/Numbers/Google Sheets to remove the duplicate PAAs. SEO Minion doesn't remove the duplicates so it has to be done manually. Also, make sure that all the PAA's are related to the topic. Sometimes, the PAA's have no relation to the topic. I suggest taking the time and manually going through the questions. Remove anything that isn't relevant.

Step 4: Prepare The CSV

We need to prepare the CSV for the script. It's pretty easy to do.

This is the output from SEO Minion:

View attachment 239045


Delete all the columns except PAA Title and Text. Rename PAA title to topic. Rename Text to context.

This is how the final CSV should look:

View attachment 239046

Rename the file as "input.csv".

Step 5: Use OpenAI to Generate Content

You're now ready to generate content using the OpenAI API. You'll need to use your OpenAI API key.

Here's the Python code you need to use:

Code:
import openai
import pandas as pd

df = pd.read_csv("input.csv")

# Set OpenAI API key
openai.api_key = "YOUR_API_KEY"

results = []

for index, row in df.iterrows():
 
    prompt = f"Please write a detailed article about {row['topic']}. Use this information to write the article: {row['context']}"
    response = openai.Completion.create(engine="text-davinci-003", prompt=prompt, temperature=0.7,max_tokens=2048,top_p=0.5)
    results.append([row['topic'], response.choices[0].text])

output_df = pd.DataFrame(results, columns = ['Topic', 'Generated Text'])

output_df.to_csv('output.csv', index=False)

In its basic form, the prompt will use the PAA answer as context to write the article. Assuming that the PAA answer that Google shows is accurate, the output generated using that as context should generate more accurate content.

Once again, YOU NEED TO CHANGE THE PROMPT. Please don't use this prompt because the output will be pathetic and short. The variable for the topic is {row['topic']} and the context is {row['context']}. Use these in your own prompt any way you see fit.

You need to customize your prompts for your specific niche. Ideally, you'd want custom prompts for each article but that takes too long when you're creating bulk content.

The output will be saved as a CSV.

Step 6: Use WP All Import

Use the WP All Import plugin to upload the content to your site. There are several tutorials that go over how you can do that. You can use some plugins for images etc.




That's pretty much it. It's super easy to get started. There are several ways to improve the output you get from OpenAI but I'm not going to get into that here.

You can also use this script for other types of content or for inserting researched data into a prompt.
Google doesnt detect that texts from ChatGPT as plagiarism if you dont pass them through a text spinner??
 
Google doesnt detect that texts from ChatGPT as plagiarism if you dont pass them through a text spinner??

I don't think I said that. Maybe you misinterpreted something from the original post.
 
can anyone here give an example of a single prompt that will yield over 750 words?
As warriorsam53 has implied, I'm not sure I understand the way tokens work, so I thought the only way to find out would be to conduct experiments in the OpenAI playground. I created a prompt based on what was initially suggested by the OP, with input gleaned by SEO Minion . I then changed variables one by one and did three runs every time and took the average word count.
What I discovered was:
  • Reducing Top P reduces the word count - in all my tests after this discovery, I set it to 1.
  • Increasing T increasing variability and also average word count. In subsequent experiments I set it at 1. Note that this may impact the quality of the answer but this wasn't my interest - I wanted to understand the efffect of settings on word count.
  • Surprisingly (for me but confirmed by something the OP said in the thread), increasing the max token parameter beyond a threshold did not increase the word count - and on average sometimes led to decreased word count. (But this may be due to sampling error: just taking 3 samples per setting. If this were a proper science project, I'd be taking 10 samples per setting.)
  • By threshold I mean that if the max token setting was too low, OpenAI did not complete the answer: it stalled in mid sentence. A way to fix this is to type "continue", but I felt this would make the script too complicated, so preferred to find settings that produced no stalls.
  • When the prompt included wording to the effect that the answer must include over 400 words, the word count in the answer increased for all settings and often, but not always, over 400 words. The threshold in this instance was around 500 tokens, or around 1.4 tokens per word.
  • When the prompt was changed to say the answer must include over 800 words, the number of words in the output increased, but not to 800.
That's as far as I've got. The point of this post is to help people understand how to adjust the prompt. I think this is by far the most difficult aspect of the technique because the OpenAI interface is a bit non-intuitive, and if you Google this, you'll find all kinds of nonsense alongside the good stuff. I asked ChatGPT to help, but it hasn't produced much in the way of insight so far!

++++++++++++++++++++++++++++
Edit: I think one way forward is to specify the structure of the answer: start with an executive summary, finish with a comprehensive conclusion - that kind of thing. Hope that helps :)
 
Last edited:
I don't think I said that. Maybe you misinterpreted something from the original post.
1. I know you didnt talk about this, but i have read a few articles saying ChatGPT contains plagiarism. Is this True?

2. If not, maybe it would also be a good idea to spin it? Because if Google ever manages to detect texts made by ChatGPT then it will launch a new update and the website will go down. What do you think

Pd: When i talk about ChatGPT api, im talking about the OpenAI api
 
Last edited:
1. I know you didnt talk about this, but i have read a few articles saying ChatGPT contains plagiarism. Is this True?

2. If not, maybe it would also be a good idea to spin it? Because if Google ever manages to detect texts made by ChatGPT then it will launch a new update and the website will go down. What do you think

Pd: When i talk about ChatGPT api, im talking about the OpenAI api

Essentially, all AI content is plagiarised since it’s just reworded content from multiple sources. Sometimes it makes stuff up too but most of the time, if the answer is accurate, it’s probably sourced from somewhere.

Spinning the content won’t really change much since it’s just an additional step where you’re rewording the content once again. The content generated by AI is already “spun”’in a way.

As far as penalising AI content goes, Google may decide to penalise it at any time. I’m not sure if spinning content can avoid such a penalty.

Even human written content is plagiarised a lot of the time. A lot of writers will just google your keyword and use the results on page 1 for their “research”. It’s not very different from what OpenAI does.

Whether a writer uses a website, a YT video or Reddit for their research, it’s still someone else’s ideas being rephrased.

One way to avoid this could be to add some unique research and insights to your prompt while using OpenAI.
 
Ваш входной файл соответствует реальности? Есть ли в нем забавные персонажи?

Как уже говорили другие, это была большая доля.
Некоторые люди, кажется, борются с Python, поэтому я использовал pyinstaller, чтобы создать исполняемую версию скрипта, которая работает на платформах Windows.
Загрузите файл здесь:
[СПОЙЛЕР="Скрыть"]
https://www.mediafire.com/file/gmamp1v5kguq283/BHW+Script.zip/file[/СПОЙЛЕР]

Это zip-файл с тремя компонентами:
- openai_scraper_v1.exe - исполняемый файл Windows -
- input.csv - пример входного файла
- openai_key.txt

ИНСТРУКЦИИ

Загрузите и распакуйте на свой компьютер с Windows — я рекомендую вам использовать песочницу, пока вы не почувствуете, что это безопасно (!)
Отредактируйте входной файл .csv со своими запросами.
Отредактируйте текстовый файл и используйте свой ключ openAI, а не пример в файле.

Дважды щелкните, чтобы запустить, и подождите — ничего особенного не произойдет, пока запуск не будет завершен, и вы получите файл output.csv. Я думаю, что Таблицы — лучший способ манипулировать файлами .csv — вы можете выполнить очистку одним щелчком мыши, чтобы удалить лишние пробелы в тексте (Данные > очистка данных)

Никаких гарантий и гарантий. Спасибо OP @warriorsam53, написавшему оригинальный сценарий.

Я проверил исполняемый файл с помощью Virustotal. Я понятия не имею, почему он показывает 3 положительных результата из 67 — как я уже сказал, используйте на свой страх и риск.

https://www.virustotal.com/gui/file/a52b212848794e8514cb9aca5757c60ec7420ebd22b84cd6cadc7cd3cfa715f3?nocache=1
I did like that, but I don't understand where output.csv should be saved?
 
Hello thank you very much! Can you share it as a code please ( With tabs ) ?
Code:
# Importuj biblioteki
import openai
import pandas as pd
import pickle
from tqdm import tqdm

# Wczytaj plik CSV
df = pd.read_csv("input.csv")

# Ustaw klucz API OpenAI
openai.api_key = "apikey"

# Utwórz pustą listę na wyniki
results = []

# Próbuj wczytać wyniki z pliku cache, jeśli istnieje
try:
    with open("results_cache.pkl", "rb") as f:
        results = pickle.load(f)
        print("Wczytano dane z cache.")
except (FileNotFoundError, EOFError):
        print("Brak danych w cache.")
pass

# Pobierz indeks ostatnio pobranego wiersza
last_index = -1
if len(results) > 0:
    last_index = results[-1][0]

# Implementacja pętli for i paska postępu
for index, row in tqdm(df[last_index+1:].iterrows(), total=len(df[last_index+1:])):
    try:
# Określ tekst zapytania dla OpenAI
        prompt = f"Please write a detailed article about {row['topic']} Use this information to write the article: {row['context']}."

# Wywołaj usługę OpenAI
        response = openai.Completion.create(engine="text-davinci-003", prompt=prompt, temperature=1, max_tokens=2048, top_p=1)

# Dodaj odpowiedź do listy wyników
        results.append([index, row['topic'], response.choices[0].text])

# Zapisz wyniki do pliku cache co kilka wierszy
        if index % 5 == 0:
            with open("results_cache.pkl", "wb") as f:
                pickle.dump(results, f)
    except Exception as e:
        print("Wystąpił błąd:", e)
    break

# Utwórz DataFrame z wynikami
output_df = pd.DataFrame(results, columns = ['Index', 'Topic', 'Generated Text'])

# Zapisz wyniki do pliku CSV
output_df.to_csv('output.csv', index=False)
I did it with trial and error method but it generates only one article. Maybe server is busy but no errors at all. I don't know how to repair this code.
/edit it generated two articles. so maybe its about overloaded server. I'll try in the evening to use it because progress bar may be very useful.

c496ChI
 
Last edited:
As warriorsam53 has implied, I'm not sure I understand the way tokens work, so I thought the only way to find out would be to conduct experiments in the OpenAI playground. I created a prompt based on what was initially suggested by the OP, with input gleaned by SEO Minion . I then changed variables one by one and did three runs every time and took the average word count.
What I discovered was:
  • Reducing Top P reduces the word count - in all my tests after this discovery, I set it to 1.
  • Increasing T increasing variability and also average word count. In subsequent experiments I set it at 1. Note that this may impact the quality of the answer but this wasn't my interest - I wanted to understand the efffect of settings on word count.
  • Surprisingly (for me but confirmed by something the OP said in the thread), increasing the max token parameter beyond a threshold did not increase the word count - and on average sometimes led to decreased word count. (But this may be due to sampling error: just taking 3 samples per setting. If this were a proper science project, I'd be taking 10 samples per setting.)
  • By threshold I mean that if the max token setting was too low, OpenAI did not complete the answer: it stalled in mid sentence. A way to fix this is to type "continue", but I felt this would make the script too complicated, so preferred to find settings that produced no stalls.
  • When the prompt included wording to the effect that the answer must include over 400 words, the word count in the answer increased for all settings and often, but not always, over 400 words. The threshold in this instance was around 500 tokens, or around 1.4 tokens per word.
  • When the prompt was changed to say the answer must include over 800 words, the number of words in the output increased, but not to 800.
That's as far as I've got. The point of this post is to help people understand how to adjust the prompt. I think this is by far the most difficult aspect of the technique because the OpenAI interface is a bit non-intuitive, and if you Google this, you'll find all kinds of nonsense alongside the good stuff. I asked ChatGPT to help, but it hasn't produced much in the way of insight so far!

++++++++++++++++++++++++++++
Edit: I think one way forward is to specify the structure of the answer: start with an executive summary, finish with a comprehensive conclusion - that kind of thing. Hope that helps :)
Nice tips... The reason I asked was that Mr. Warrior implied that it was possible in a single prompt. I have tried so many prompts, not even 1 post with over 800 words.
 
Code:
# Importuj biblioteki
import openai
import pandas as pd
import pickle
from tqdm import tqdm

# Wczytaj plik CSV
df = pd.read_csv("input.csv")

# Ustaw klucz API OpenAI
openai.api_key = "apikey"

# Utwórz pustą listę na wyniki
results = []

# Próbuj wczytać wyniki z pliku cache, jeśli istnieje
try:
    with open("results_cache.pkl", "rb") as f:
        results = pickle.load(f)
        print("Wczytano dane z cache.")
except (FileNotFoundError, EOFError):
        print("Brak danych w cache.")
pass

# Pobierz indeks ostatnio pobranego wiersza
last_index = -1
if len(results) > 0:
    last_index = results[-1][0]

# Implementacja pętli for i paska postępu
for index, row in tqdm(df[last_index+1:].iterrows(), total=len(df[last_index+1:])):
    try:
# Określ tekst zapytania dla OpenAI
        prompt = f"Please write a detailed article about {row['topic']} Use this information to write the article: {row['context']}."

# Wywołaj usługę OpenAI
        response = openai.Completion.create(engine="text-davinci-003", prompt=prompt, temperature=1, max_tokens=2048, top_p=1)

# Dodaj odpowiedź do listy wyników
        results.append([index, row['topic'], response.choices[0].text])

# Zapisz wyniki do pliku cache co kilka wierszy
        if index % 5 == 0:
            with open("results_cache.pkl", "wb") as f:
                pickle.dump(results, f)
    except Exception as e:
        print("Wystąpił błąd:", e)
    break

# Utwórz DataFrame z wynikami
output_df = pd.DataFrame(results, columns = ['Index', 'Topic', 'Generated Text'])

# Zapisz wyniki do pliku CSV
output_df.to_csv('output.csv', index=False)
I did it with trial and error method but it generates only one article. Maybe server is busy but no errors at all. I don't know how to repair this code.
/edit it generated two articles. so maybe its about overloaded server. I'll try in the evening to use it because progress bar may be very useful.

c496ChI
Hello,

Here is update with auto cache, autoblogging on WP, with html and tags, u need to use plugin to create WP password.

Code:
# Import necessary libraries

import openai

import pandas as pd

import pickle

import requests

import json

import base64

import re

from tqdm import tqdm







# Load CSV file

df = pd.read_csv("input.csv")



# Set API key for OpenAI

openai.api_key = "API KEY"



# Initialize a list to store the results

results = []



# Try to load the results from cache file

try:

    with open("results_cache.pkl", "rb") as f:

        results = pickle.load(f)

        print("Data loaded from cache.")

except (FileNotFoundError, EOFError):

    print("No data in cache.")

    pass



# Get the index of the last row

last_index = -1

if len(results) > 0:

    last_index = results[-1][0]





# Loop through the rows and generate text

for index, row in tqdm(df[last_index+1:].iterrows(), total=len(df[last_index+1:])):

    try:

        # Define the query text for OpenAI

        headers = {

        "Content-Type": "text/html",

        }

        prompt = f"<!-- Create detailed article with html tags and headings and bolded keywords on title {row['topic']}.--!>"



        # Call the OpenAI API

        response = openai.Completion.create(engine="text-davinci-003", prompt=prompt, temperature=0.7, max_tokens=3600, top_p=0.5, headers=headers)



        # Add the response to the results list

        results.append([index, row['topic'], response.choices[0].text])



  

        # Save the results to the cache file

        if index % 5 == 0:

            with open("results_cache.pkl", "wb") as f:

                pickle.dump(results, f)

    except Exception as e:

        print("Error:", e)

        break



  # Generate HTML from generated text

def parse_and_generate_html(text):

    text = text.strip()

    lines = text.split("\n")

    html = ""

    for line in lines:

        if not line.strip():  # Skip empty lines

            continue

        if line.startswith("#"):

            if line.startswith("##"):

                line = line[2:]

                html += f"<h2>{line}</h2>\n"

            else:

                line = line[1:]

                html += f"<h1>{line}</h1>\n"

        else:

            html += f"<p>{line}</p>\n"

    return html



# Create a DataFrame from the results

output_df = pd.DataFrame(results, columns = ['Index', 'Topic', 'Generated Text'])



# Generate HTML and add it to the data frame

output_df['Generated HTML'] = output_df['Generated Text'].apply(parse_and_generate_html)



# Loop through the rows and post the HTML content to WordPress

for index, row in output_df.iterrows():

    try:

        # Prepare the data for the WordPress API

        data = {

            "title": row['Topic'],

            "content": row['Generated HTML'],

            "status": "draft"

        }



        # Add the required credentials to the headers

        headers = {

            "Authorization": "Basic " + base64.b64encode(b"wordpress_python:password").decode("utf-8"),

            "Content-Type": "application/json"

        }

        url = "domain.com/wp-json/wp/v2/posts"



        # Post the generated text to WordPress as a draft post

        response = requests.post(url, headers=headers, data=json.dumps(data))

    except Exception as e:

        print(e)



# Save the results to a CSV file

output_df.to_csv('output.csv', index=False)
 
I tried earlier versions but there were issues so I improved this one, This way you wont loose any content ,The script saves the generated text to the results list as soon as it receives it from the OpenAI API. This means that the generated text is being saved while the script is running and doesn't wait until all the articles have been generated before writing them to the output file.
The use of the results list also allows the script to recover any generated articles in case an error occurs during the generation of a subsequent article. In other words, if an error occurs while generating an article, the script can simply continue generating articles for the remaining rows in the input CSV file, and the already-generated articles will still be saved in the results list.
Once all the articles have been generated and stored in the results list, the script creates a new pandas DataFrame called output_df from the results list and saves it to a new CSV file called "output.csv". So, the generated articles are saved twice: once in the results list as they are generated, and then again in the output file once all the articles have been generated.


Python:
import openai
import pandas as pd
from tqdm import tqdm

df = pd.read_csv("input.csv")

# Set OpenAI API key
openai.api_key = "APIKEY"

results = []
errors = []

for index, row in tqdm(df.iterrows(), total=len(df)):
    prompt = f"Please write a detailed article about {row['topic']}. Use this information to write the article: {row['context']}"
    try:
        response = openai.Completion.create(engine="text-davinci-003", prompt=prompt, temperature=0.7, max_tokens=2048, top_p=0.5)
        results.append([row['topic'], response.choices[0].text])
    except Exception as e:
        errors.append([row['topic'], row['context'], str(e)])
        continue

output_df = pd.DataFrame(results, columns=['Topic', 'Generated Text'])

# Save output to CSV file
output_df.to_csv('output.csv', index=False)

if len(errors) > 0:
    # Log any errors that occurred during the script
    error_df = pd.DataFrame(errors, columns=['Topic', 'Context', 'Error'])
    error_df.to_csv('errors.csv', index=False)
 
Last edited:
Hello,

Here is update with auto cache, autoblogging on WP, with html and tags, u need to use plugin to create WP password.


Code:
# Import necessary libraries

import openai

import pandas as pd

import pickle

import requests

import json

import base64

import re

from tqdm import tqdm







# Load CSV file

df = pd.read_csv("input.csv")



# Set API key for OpenAI

openai.api_key = "API KEY"



# Initialize a list to store the results

results = []



# Try to load the results from cache file

try:

    with open("results_cache.pkl", "rb") as f:

        results = pickle.load(f)

        print("Data loaded from cache.")

except (FileNotFoundError, EOFError):

    print("No data in cache.")

    pass



# Get the index of the last row

last_index = -1

if len(results) > 0:

    last_index = results[-1][0]





# Loop through the rows and generate text

for index, row in tqdm(df[last_index+1:].iterrows(), total=len(df[last_index+1:])):

    try:

        # Define the query text for OpenAI

        headers = {

        "Content-Type": "text/html",

        }

        prompt = f"<!-- Create detailed article with html tags and headings and bolded keywords on title {row['topic']}.--!>"



        # Call the OpenAI API

        response = openai.Completion.create(engine="text-davinci-003", prompt=prompt, temperature=0.7, max_tokens=3600, top_p=0.5, headers=headers)



        # Add the response to the results list

        results.append([index, row['topic'], response.choices[0].text])



 

        # Save the results to the cache file

        if index % 5 == 0:

            with open("results_cache.pkl", "wb") as f:

                pickle.dump(results, f)

    except Exception as e:

        print("Error:", e)

        break



  # Generate HTML from generated text

def parse_and_generate_html(text):

    text = text.strip()

    lines = text.split("\n")

    html = ""

    for line in lines:

        if not line.strip():  # Skip empty lines

            continue

        if line.startswith("#"):

            if line.startswith("##"):

                line = line[2:]

                html += f"<h2>{line}</h2>\n"

            else:

                line = line[1:]

                html += f"<h1>{line}</h1>\n"

        else:

            html += f"<p>{line}</p>\n"

    return html



# Create a DataFrame from the results

output_df = pd.DataFrame(results, columns = ['Index', 'Topic', 'Generated Text'])



# Generate HTML and add it to the data frame

output_df['Generated HTML'] = output_df['Generated Text'].apply(parse_and_generate_html)



# Loop through the rows and post the HTML content to WordPress

for index, row in output_df.iterrows():

    try:

        # Prepare the data for the WordPress API

        data = {

            "title": row['Topic'],

            "content": row['Generated HTML'],

            "status": "draft"

        }



        # Add the required credentials to the headers

        headers = {

            "Authorization": "Basic " + base64.b64encode(b"wordpress_python:password").decode("utf-8"),

            "Content-Type": "application/json"

        }

        url = "domain.com/wp-json/wp/v2/posts"



        # Post the generated text to WordPress as a draft post

        response = requests.post(url, headers=headers, data=json.dumps(data))

    except Exception as e:

        print(e)



# Save the results to a CSV file

output_df.to_csv('output.csv', index=False)
wouldn't be easier to upload it with XML-RPC?, to def it and call it in the for loop so it's uploaded on the fly?

No idea, I'm super average in python
 
I tried earlier versions but there were issues so I improved this one, This way you wont loose any content ,The script saves the generated text to the results list as soon as it receives it from the OpenAI API. This means that the generated text is being saved while the script is running and doesn't wait until all the articles have been generated before writing them to the output file.
The use of the results list also allows the script to recover any generated articles in case an error occurs during the generation of a subsequent article. In other words, if an error occurs while generating an article, the script can simply continue generating articles for the remaining rows in the input CSV file, and the already-generated articles will still be saved in the results list.
Once all the articles have been generated and stored in the results list, the script creates a new pandas DataFrame called output_df from the results list and saves it to a new CSV file called "output.csv". So, the generated articles are saved twice: once in the results list as they are generated, and then again in the output file once all the articles have been generated.


Python:
import openai
import pandas as pd
from tqdm import tqdm

df = pd.read_csv("input.csv")

# Set OpenAI API key
openai.api_key = "APIKEY"

results = []
errors = []

for index, row in tqdm(df.iterrows(), total=len(df)):
    prompt = f"Please write a detailed article about {row['topic']}. Use this information to write the article: {row['context']}"
    try:
        response = openai.Completion.create(engine="text-davinci-003", prompt=prompt, temperature=0.7, max_tokens=2048, top_p=0.5)
        results.append([row['topic'], response.choices[0].text])
    except Exception as e:
        errors.append([row['topic'], row['context'], str(e)])
        continue

output_df = pd.DataFrame(results, columns=['Topic', 'Generated Text'])

# Save output to CSV file
output_df.to_csv('output.csv', index=False)

if len(errors) > 0:
    # Log any errors that occurred during the script
    error_df = pd.DataFrame(errors, columns=['Topic', 'Context', 'Error'])
    error_df.to_csv('errors.csv', index=False)
Hi, nice one. can you make it so that it does not try to pull content again from the ones already processed? Just in case you have to start over again to prevent duplicates.

Like

Check if row already has an output column

{ skip that topic.}

else this is a new topic
{process it}
 
Back
Top