import pandas as pd
import requests
import os
import base64
from tqdm import tqdm
import concurrent.futures
import threading
import google.generativeai as genai
from tenacity import (
retry,
stop_after_attempt,
wait_random_exponential,
) # for exponential backoff
# WordPress site URL
WP_URL = "https://jakgainbed.com/"
# WordPress username and password
USERNAME = "xxx"
PASSWORD = "xxx"
API_KEY = "xxxx"
genai.configure(api_key=API_KEY)
model = genai.GenerativeModel("gemini-1.5-flash")
output_df = pd.DataFrame(
columns=["URL Slug", "Meta Title", "Description", "Blog Content", "Featured Image"]
)
output_lock = threading.Lock()
@retry(
wait=wait_random_exponential(multiplier=1, min=4, max=10),
stop=stop_after_attempt(5),
)
def generate_blog_post(row):
try:
url_slug = row["URL Slug"]
meta_title = row["Meta Title"]
description = row["Description of Page"]
featured_image = row["Featured Image"]
product_data = row["Product Data"]
response = model.generate_content(
f"xxxxxxxx"
)
blog_content = response.text
tqdm.write(f"Generated blog content for URL Slug {url_slug}")
tqdm.write(f"Generated featured image for URL Slug {url_slug}")
result = {
"URL Slug": url_slug,
"Meta Title": meta_title,
"Description": description,
"Blog Content": blog_content,
"Featured Image": featured_image,
}
with output_lock:
global output_df
output_df = pd.concat(
[output_df, pd.DataFrame([result])], ignore_index=True
)
output_df.to_csv("output.csv", index=False)
tqdm.write(f"Saved blog post for URL Slug {url_slug} to output.csv")
# Open the image file in binary mode
with open(result["Featured Image"], "rb") as img:
# Prepare the headers for the REST API request
headers = {
"Content-Disposition": f'attachment; filename={os.path.basename(result["Featured Image"])}',
"Content-Type": "image/png", # Adjust this if your images are not PNGs
"Authorization": "Basic "
+ base64.b64encode(f"{USERNAME}:{PASSWORD}".encode("utf-8")).decode(
"utf-8"
),
}
# Send the POST request to the WordPress REST API
response = requests.post(
f"{WP_URL}/wp-json/wp/v2/media", headers=headers, data=img
)
# If the request was successful, the image ID will be in the response
if response.status_code == 201:
image_id = response.json()["id"]
else:
print(f"Error uploading image: {response.content}")
# Create a blog post in WordPress
post = {
"title": result["Meta Title"],
"content": result["Blog Content"],
"status": "publish",
"excerpt": result["Description"],
"slug": result["URL Slug"],
"meta": {},
"featured_media": image_id,
}
# Send the POST request to create the post
response = requests.post(
f"{WP_URL}/wp-json/wp/v2/posts",
headers={
"Authorization": "Basic "
+ base64.b64encode(f"{USERNAME}:{PASSWORD}".encode("utf-8")).decode(
"utf-8"
)
},
json=post,
)
if response.status_code != 201:
print(f"Error creating post: {response.content}")
else:
print(f"Successfully created post with ID: {response.json()['id']}")
except Exception as e:
tqdm.write(f"Error generating blog post for URL Slug {url_slug}: {e}")
return None
df = pd.read_excel("input.xlsx")
rows = df.to_dict("records")
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
results = list(tqdm(executor.map(generate_blog_post, rows), total=len(rows)))
when I put my freinds’ WordPress acccount and url in WP_URL,USERNAME, PASSWORD, It works very well
But when I put my new WP account, the result is
Generated blog content for URL Slug A
Generated featured image for URL Slug A
Saved blog post for URL Slug A to output.csv
Error generating blog post for URL Slug A: HTTPSConnectionPool(host='jakgainbed.com', port=443): Max retries exceeded with url: /wp-json/wp/v2/media (Caused by SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:2406)')))
Although I diligently searched Google for the error code, I couldn’t find a solution. I installed WordPress using Vultr hosting and the CyberPanel app, and I’m wondering if the issue lies with these or if I need to install a specific WP plugin.