import openai
import os
openai.api_key = "your_open_ai_api_key"
def upload_image(filename,your_site,your_user,your_password):
import requests, json
api_url_image = your_site+'/wp-json/wp/v2/media'
the_pic = open(filename, 'rb').read()
fnm = os.path.basename(filename)
result = requests.post(
url=api_url_image,
data=the_pic,
headers={ 'Content-Type': 'image/jpg','Content-Disposition' : 'attachment; filename=%s'% fnm},
auth=(your_user, your_password)
)
response =result.json()
the_image_id = response.get('id')
the_image_url = response.get('guid').get("rendered")
return (the_image_id, the_image_url)
def make_post(the_title,the_text,your_user,your_password,your_site,wordpress_category,the_image_id):
import requests
import base64
your_credentials = your_user + ":" + your_password
your_token = base64.b64encode(your_credentials.encode())
your_header = {'Authorization': 'Basic ' + your_token.decode('utf-8')}
api_url = your_site+'/wp-json/wp/v2/posts'
if the_image_id>0:
if not wordpress_category == "":
data = {
'title' : the_title,
'status': 'publish',
'content': the_text,
'categories': 3,
'featured_media': the_image_id
##'slug' : 'example-post',
}
else:
data = {
'title' : the_title,
'status': 'publish',
'content': the_text,
'featured_media': the_image_id
##'slug' : 'example-post',
}
else:
if not wordpress_category == "":
data = {
'title' : the_title,
'status': 'publish',
'content': the_text,
'categories': 3,
}
else:
data = {
'title' : the_title,
'status': 'publish',
'content': the_text,
}
response = requests.post(api_url,headers=your_header, json=data)
return response.json()
def gpt_chat(all_params):
the_keyword,the_prefix,the_temperature,the_max_tokens = all_params
the_text = the_prefix + the_keyword + ":"
#the_text = the_prefix + the_text
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": the_text}],
temperature=the_temperature,
max_tokens=the_max_tokens
)
the_result = response["choices"][0]["message"]["content"]
return the_result
def fix_ahrefs_keywords(file_with_keywords):
#remove empty lines and non keyword lines from output of https://ahrefs.com/keyword-generator
with open(file_with_keywords, 'r') as fyl:
lines = fyl.readlines()
good_lines = []
for aline in lines:
aline = aline.strip()
if (not any(str.isdigit(x) for x in aline) or len(aline.split())>3) and not aline.strip()=="" and not "Sign up" in aline and not "N/A" in aline:
good_lines.append(aline)
with open(file_with_keywords, 'w') as f:
for line in good_lines:
f.write(f"{line}\n")
#load file with your keywords
file_with_keywords = "sample_data/keywords.txt"
#this step fixes the file with keywords from https://ahrefs.com/keyword-generator
fix_ahrefs_keywords(file_with_keywords)