Search code examples
pythonflaskopenai-api

I'm trying to turn this python script into a web app with flask


I am trying to turn my script into a web app, it uses wordpress and chatgpt to generate articles based on keywords and what you type in the input boxes and allows the user to instantly upload to drafts on their wordpress site.. I am running into an issue:

updated

# app.py
from flask import Flask, render_template, request, flash
from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, SubmitField
from wtforms.validators import InputRequired
import openai
import requests
import random

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'

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


class InputForm(FlaskForm):
    api_key = StringField('OpenAI API Key', validators=[InputRequired()])
    input_text = TextAreaField('Input Text', validators=[InputRequired()])
    keywords = TextAreaField('Keywords (comma-separated)', validators=[InputRequired()])
    wp_base_url = StringField('WordPress Base URL', validators=[InputRequired()])
    wp_username = StringField('WordPress Username', validators=[InputRequired()])
    wp_password = StringField('WordPress Password', validators=[InputRequired()])
    submit = SubmitField('Submit')


# Array holding wordpress author IDs
authorList = ["1", "2"]

# You can call the "gpt-3.5-turbo" model
modelEngine = "gpt-3.5-turbo"

# WordPress information
wp_base_url = ""
wp_username = ""
wp_password = ""


# Post creator function
def create_post(inputTitleSent, outputText):
    randomAuthor = random.choice(authorList)

    post_status = "draft"
    headers = {
        "Content-Type": "application/x-www-form-urlencoded"
    }
    post = {
        "title": inputTitleSent,
        "content": outputText,
        "status": post_status,
        "author": randomAuthor,
        "categories:": "6"
    }
    url = wp_base_url + "/wp-json/wp/v2/posts"
    response = requests.post(url, data=post, headers=headers, auth=(wp_username, wp_password))
    return response


# Post title creator function
def create_title(outputText):
    response = openai.ChatCompletion.create(
        model=modelEngine,
        messages=[{"role": "user", "content": f"Write a title for this article:\n\n {outputText}"}],
        n=1
    )
    create_title = response.choices[0].message.content
    create_title = create_title.replace('"', '')
    return create_title


@app.route('/', methods=['GET', 'POST'])
def index():
    global wp_base_url, wp_username, wp_password  # Move the global declaration here

    form = InputForm()

    if form.validate_on_submit():
        # Get user input from the form
        data = request.get_json()
        api_key = data.get('api_key')
        input_text = data.get('input_text')
        keywords = data.get('keywords')
        wp_base_url = data.get('wp_base_url')
        wp_username = data.get('wp_username')
        wp_password = data.get('wp_password')

        try:
            response = openai.ChatCompletion.create(
                model=modelEngine,
                messages=[{"role": "user", "content": "Testing API Key"}],
                n=1
            )

            if 'choices' not in response or not response['choices']:
                flash("Invalid API Key. Please check and try again.", "error")
                return render_template('index.html', form=form, data=None)

            # ... (rest of the code remains the same)
        except requests.exceptions.RequestException as e:
            flash("Error occurred while connecting to the OpenAI API. Please check your internet connection and try again.", "error")
            return render_template('index.html', form=form, data=None)

        except Exception as e:
            flash("An unexpected error occurred. Please try again later.", "error")
            return render_template('index.html', form=form, data=None)

    return render_template('index.html', form=form, data=None)


if __name__ == '__main__':
    app.run(debug=True)

the requests are getting sent to the server on debug but it doesn't run the script when pressing submit and the inputs doesn't render, how can I fix this?

index.html (updated):

<!DOCTYPE html>
<html>
<head>
    <title>OpenAI WordPress Web App</title>
</head>
<body>
    <h1>Input your information:</h1>
    <form id="inputForm" method="POST">
        {{ form.csrf_token }}
        {{ form.api_key.label }} {{ form.api_key(id='api_key', size=60) }}<br>
        {{ form.input_text.label }} {{ form.input_text(id='input_text', rows=10, cols=60) }}<br>
        {{ form.keywords.label }} {{ form.keywords(id='keywords', rows=3, cols=60) }}<br>
        {{ form.wp_base_url.label }} {{ form.wp_base_url(id='wp_base_url', size=60) }}<br>
        {{ form.wp_username.label }} {{ form.wp_username(id='wp_username', size=60) }}<br>
        {{ form.wp_password.label }} {{ form.wp_password(id='wp_password', size=60) }}<br>
        {{ form.submit() }}
    </form>

    {% if data %}
        <h1>Generated Posts:</h1>
        {% for post in data %}
            <h2>{{ post.title }}</h2>
            <p>{{ post.content }}</p>
            <hr>
        {% endfor %}
    {% endif %}

    <script>
        document.getElementById('inputForm').addEventListener('submit', function (event) {
            event.preventDefault(); // Prevent the form from submitting normally
            var api_key = document.getElementById('api_key').value;
            var input_text = document.getElementById('input_text').value;
            var keywords = document.getElementById('keywords').value;
            var wp_base_url = document.getElementById('wp_base_url').value;
            var wp_username = document.getElementById('wp_username').value;
            var wp_password = document.getElementById('wp_password').value;

            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/');
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.onreadystatechange = function () {
                if (xhr.readyState === XMLHttpRequest.DONE) {
                    if (xhr.status === 200) {
                        // Request successful, update the page if necessary
                        var response = JSON.parse(xhr.responseText);
                        if (response.error) {
                            alert('Error: ' + response.error);
                        } else {
                            alert('Data processed successfully!');
                            // Optionally, you can update the page with the generated posts here
                        }
                    } else {
                        // Handle error here
                        alert('Error occurred. Please try again later.');
                    }
                }
            };

            var data = JSON.stringify({
                api_key: api_key,
                input_text: input_text,
                keywords: keywords,
                wp_base_url: wp_base_url,
                wp_username: wp_username,
                wp_password: wp_password
            });

            xhr.send(data);
        });
    </script>
</body>
</html>

Solution

  • edir your index.html :

        <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>OpenAI WordPress Web App</title>
    </head>
    <body>
        <h1>Input your information:</h1>
        <form id="inputForm" method="POST" action="{{ url_for('index') }}">
            {{ form.csrf_token }}
            {{ form.api_key.label }} {{ form.api_key(id='api_key', size=60) }}<br>
            {{ form.input_text.label }} {{ form.input_text(id='input_text', rows=10, cols=60) }}<br>
            {{ form.keywords.label }} {{ form.keywords(id='keywords', rows=3, cols=60) }}<br>
            {{ form.wp_base_url.label }} {{ form.wp_base_url(id='wp_base_url', size=60) }}<br>
            {{ form.wp_username.label }} {{ form.wp_username(id='wp_username', size=60) }}<br>
            {{ form.wp_password.label }} {{ form.wp_password(id='wp_password', size=60) }}<br>
            {{ form.submit() }}
        </form>
    
        {% if data %}
            <h1>Generated Posts:</h1>
            {% for post in data %}
                <h2>{{ post.title }}</h2>
                <p>{{ post.content }}</p>
                <hr>
            {% endfor %}
        {% endif %}
    
    
    </body>
    </html>
    

    and it will be you flask wtf form :

    from flask_wtf import FlaskForm
    from wtforms import StringField, TextAreaField, SubmitField
    from wtforms.validators import  DataRequired
    
    class InputForm(FlaskForm):
        api_key = StringField('OpenAI API Key', validators=[DataRequired()])
        input_text = TextAreaField('Input Text', validators=[DataRequired()])
        keywords = TextAreaField('Keywords (comma-separated)', validators=[DataRequired()])
        wp_base_url = StringField('WordPress Base URL', validators=[DataRequired()])
        wp_username = StringField('WordPress Username', validators=[DataRequired()])
        wp_password = StringField('WordPress Password', validators=[DataRequired()])
        submit = SubmitField('Submit')
    

    and tour index route will be you can just add you rest of your code problem was getting information right ?

    @app.route('/', methods=['GET', 'POST'])
    def index():
        print(request.method) # testing request method coming from your index.html form
        form = InputForm()
        if request.method == 'POST' and form.validate_on_submit():
        # Get user input from the for
            api_key = form.api_key.data
            input_text = form.input_text.data
            keywords = form.keywords.data
            wp_base_url = form.wp_base_url.data
            wp_username = form.wp_username.data
            wp_password = form.wp_password.data
            for item in form: # for testing your results
                print(item.data)
            # rest of your code 
    
    return render_template('index.html', form=form, data=None)