Harnessing ChatGPT to Populate Your Entire Website with Fresh Content: Part 8:
08_Get_Excerpt_for_Article
This script is used to generate a short synopsis or excerpt for each article using OpenAI. This excerpt can then be used as a summary or preview of the article on the website.
First, we import the necessary modules and set up the credentials for OpenAI and WordPress.
import jso
import pandas as pd
import openai
import sqlite3
from models import Trend, session
import base64
import requests
from sqlalchemy import and_
# OpenAI credentials
openai.api_key = "your_openai_api_key_here"
# WordPress credentials
username = "your_wordpress_username_here"
api_base_url = "https://www.your_wordpress_site_here.com/wp-json/wp/v2/"
application_password = "your_wordpress_application_password_here"n
We then retrieve all trends from the database that have a non-null `article_id`, non-empty `article`, and non-null `article_tags`. For each trend, the script generates a two-sentence synopsis of the article using OpenAI's completion API:
all_trends = session.query(Trend).filter(and_(Trend.article_id != None, Trend.article != '', Trend.article_tags != None)).all(
for idx, trend in enumerate(all_trends):
??try:
????response = openai.Completion.create(
??????engine="text-davinci-003",
??????prompt=f"Write a two sentence synopsis of [{trend.title}].",
??????max_tokens=50,
??????n=1,
??????stop=None,
??????temperature=0.7)
????only_choice = response.choices[0].text.strip()
????trend.article_excerpt = only_choice
????session.commit()
??except Exception as e:
????print(e)
????break
If the synopsis is generated successfully, it's added to the `article_excerpt` field of the `Trend` instance and the changes are committed to the database.
Finally, the database session is closed:
session.Close()
With this script, we now have a short synopsis for each article that can be displayed on the website as a preview of the content.