Världens Godaste Kycklinggryta

from internal_juicer import read_csv_file, AUTH, WEBSITE # Import functions and variables from internal_juicer.py

import openai # OpenAI API library for interacting with GPT models

import json # Library to handle JSON data

import os # Library to interact with the operating system

from internal_juicer_writer import rewriter, scrape_and_summarize # Import functions from internal_juicer_writer.py

from internal_juicer import OPENAI_API_KEY # Import the OpenAI API key from internal_juicer.py

from internal_juicer_writer import summarization_and_urls # Import additional functions

openai.api_key = OPENAI_API_KEY # Set the OpenAI API key

def update_wordpress_post(post_id, updated_content):

"""

Updates the content of a WordPress post using its REST API.



:param post_id: ID of the post to update.

:param updated_content: New content to set for the post.

:return: HTTP status code of the update request.

"""

url = f"{WEBSITE}/wp-json/wp/v2/posts/{post_id}"  # Construct API endpoint URL

headers = {

    'Content-Type': 'application/json',  # Specify the content type as JSON

}

data = {

    'content': updated_content  # Define the updated content payload

}

try:

    response = requests.post(url, headers=headers, json=data, auth=AUTH)  # Make POST request to update the post

    response.raise_for_status()  # Raise exception for HTTP errors

    return response.status_code  # Return the HTTP status code of the response

except requests.RequestException as e:

    print(f"Error updating post {post_id}: {e}")  # Print error message

    return None  # Return None on failure

import csv # Library to handle CSV files

def main():

"""

Main function that orchestrates reading posts from a CSV, processing each post, updating them, and logging the results.

"""

posts = []  # Initialize an empty list to store posts

try:

    with open('posts.csv', 'r', encoding='utf-8') as f:

        reader = csv.DictReader(f)  # Initialize CSV DictReader

        posts = list(reader)  # Convert reader to list and store in posts

except FileNotFoundError:

    print("posts.csv file not found.")

    return



done_posts = []  # Initialize a list to keep track of successfully updated posts



for post in posts:

    post_id = post.get('Post ID')

    post_url = post.get('URL')



    if not post_id or not post_url:

        print(f"Invalid post entry: {post}")

        continue  # Skip invalid entries



    retries = 2  # Number of retries allowed for processing the post

    while retries >= 0:

        try:

            print(f"Processing Post ID: {post_id}, URL: {post_url}")  # Debugging information



            # Obtain summaries, URLs, and article content using summarization_and_urls function

            my_summaries, my_urls, article = summarization_and_urls(post_id, post_url)

            if not my_urls:

                print(f"No relevant URLs found for Post ID {post_id}. Skipping update.")

                post['Updated'] = 'NO_URLS'

                break



            # Rewrite the article with the obtained URLs and summaries

            cleaned_article = rewriter(my_urls, my_summaries, article)

            if not cleaned_article:

                print(f"Failed to rewrite article for Post ID {post_id}.")

                post['Updated'] = 'FAILED_REWRITE'

                break



            # Update the WordPress post with the rewritten content

            response_code = update_wordpress_post(post_id, cleaned_article)



            if response_code == 200:

                print(f"Post {post_id} updated successfully.")  # Inform about successful update

                post['Updated'] = 'UPDATED'  # Mark the post as updated

                done_posts.append(post)  # Add to the list of done posts

                break  # Exit the retry loop

            else:

                print(f"Failed to update post {post_id}. Response code: {response_code}")  # Inform about failure

                post['Updated'] = 'FAILED_UPDATE'

                break  # Exit the retry loop



        except json.decoder.JSONDecodeError as e:

            print(f"JSON decoding error for Post ID {post_id}: {e}. Retrying...")

            retries -= 1



        except Exception as e:

            print(f"Unexpected error for Post ID {post_id}: {e}. Retrying...")

            retries -= 1



        if retries < 0:

            print(f"Failed to process Post ID {post_id} after retries.")

            post['Updated'] = 'FAILED_RETRIES'



# Write the updated posts back to 'posts.csv'

try:

    with open('posts.csv', 'w', newline='', encoding='utf-8') as f:

        if posts:

            fieldnames = posts.keys()  # Get the CSV header from the first post

            writer = csv.DictWriter(f, fieldnames=fieldnames)  # Initialize DictWriter with fieldnames

            writer.writeheader()  # Write the header to the CSV

            writer.writerows(posts)  # Write all post rows to the CSV

except Exception as e:

    print(f"Error writing to posts.csv: {e}")



# Write successfully updated posts to 'done.csv'

try:

    with open('done.csv', 'w', newline='', encoding='utf-8') as f:

        if done_posts:

            fieldnames = done_posts.keys()  # Get the CSV header from the first done post

            writer = csv.DictWriter(f, fieldnames=fieldnames)  # Initialize DictWriter with fieldnames

            writer.writeheader()  # Write the header to the CSV

            writer.writerows(done_posts)  # Write all done post rows to the CSV

except Exception as e:

    print(f"Error writing to done.csv: {e}")

if name == “main“:

main()  # Execute the main function when the script is run