Pseudo Code Generator

Flask Application for OpenAI-Powered Data Generation

This Flask app generates random data based on user scenarios using OpenAI's code generation capabilities. It handles HTTP requests, executes generated Python code, and can return data in CSV format for download.


Empty image or helper icon

Prompt

from flask import Flask, render_template, request, send_file, jsonify, session import csv import io from io import BytesIO from io import StringIO import random import openai import os import traceback import logging import faker

app = Flask(name)

Set your OpenAI API key

openai.api_key = os.environ['OPENAIDEMO'] openai.api_key = os.getenv('OPENAIDEMO') if not openai.api_key: raise ValueError("OPENAIDEMO environment variable is not set. Please set it in the Secrets tab.")

print(f"API Key set: {'Yes' if openai.api_key else 'No'}") print(f"API Key length: {len(openai.api_key) if openai.api_key else 0}")

def extract_python_code(response): lines = response.split('\n') code_lines = [] in_code_block = False for line in lines: if line.strip().startswith('python'): in_code_block = True continue elif line.strip() == '' and in_code_block: in_code_block = False continue if in_code_block: code_lines.append(line) return '\n'.join(code_lines)

def generate_python_code(scenario, num_columns): prompt = f""" Create a Python function named 'generate_random_data' that generates random data for the following business scenario: {scenario}

The function should:
1. Take a 'num_rows' parameter
2. Generate exactly {num_columns} columns of data
3. Return a list of dictionaries, where each dictionary represents a row of data
4. Include appropriate field names and data types for the scenario
5. Use the random module to generate data

Provide ONLY the Python code for the function, enclosed in triple backticks, without any additional explanation.
"""
try:
    response = openai.chat.completions.create(
        model="gpt-4o",
        messages=[
            {"role": "system", "content": "You are a Python code generator. Respond only with the requested Python code, enclosed in triple backticks."},
            {"role": "user", "content": prompt}
        ]
    )
    full_response = response.choices[0].message.content
    return extract_python_code(full_response)
except Exception as e:
    logging.error(f"Error in generating code: {str(e)}")
    return None

logging.basicConfig(level=logging.DEBUG)

@app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': logging.info(f"Received POST request with scenario: {request.form['scenario']}") try: scenario = request.form['scenario'] num_rows = int(request.form['num_rows']) num_columns = int(request.form['num_columns']) logging.info(f"Received request: scenario='{scenario}', num_rows={num_rows}") generated_code = generate_python_code(scenario, num_columns) logging.debug(f"Generated code: {generated_code}") if generated_code and isinstance(generated_code, str): try: exec(generated_code, globals()) if 'generate_random_data' not in globals(): raise NameError("The function 'generate_random_data' was not defined.") # Check if this is a preview request if 'preview' in request.form: preview_data = globals().get('generate_random_data', lambda num_rows: [])(5) # Generate 5 rows for preview return jsonify({'success': True, 'preview': preview_data}) # If not a preview, generate full data set data = globals().get('generate_random_data', lambda num_rows: [])(num_rows) logging.info(f"Generated {len(data)} rows of data") output = StringIO() writer = csv.DictWriter(output, fieldnames=data[0].keys()) writer.writeheader() writer.writerows(data) output.seek(0) return send_file(io.BytesIO(output.getvalue().encode()), mimetype='text/csv', as_attachment=True, download_name='data_scenario.csv') except Exception as e: logging.error(f"Error in executing generated code: {str(e)}") logging.error(traceback.format_exc()) return jsonify({'error': f'Error in executing generated code: {str(e)}'}), 500 else: logging.error("Failed to generate code") return jsonify({'error': 'Failed to generate code'}), 500 except Exception as e: logging.error(f"Unexpected error: {str(e)}") logging.error(traceback.format_exc()) return jsonify({'error': f'Unexpected error: {str(e)}'}), 500 else: # For GET requests, retrieve the selected scenario from the session selected_scenario = session.get('selected_scenario', '') return render_template('index.html', scenario=selected_scenario)

@app.route('/scenario-browser') def scenario_browser(): return render_template('scenario_browser.html') @app.route('/set-scenario', methods=['POST']) def set_scenario(): data = request.json scenario = data.get('scenario') # Store the scenario in session session['selected_scenario'] = scenario return jsonify({"success": True})

if name == 'main': app.run(host='0.0.0.0', port=8080, debug=True)

Answer

Pseudo Code for Flask Application with OpenAI Interaction

Overview

The objective is to describe the logic of a Flask web application that generates random data based on user-defined scenarios by leveraging OpenAI's code generation capabilities. The application includes features for handling HTTP requests, executing generated Python code, and returning CSV files.

Main Components

1. Application Initialization

  • Import necessary libraries
  • Initialize Flask application
  • Set up OpenAI API key from environment variables

2. Function: extract_python_code

  • Extracts Python code from OpenAI's response which is embedded within markdown code blocks.

3. Function: generate_python_code

  • Constructs a prompt to request Python code generation.
  • Interacts with OpenAI's API to generate the desired function.
  • Handles exceptions and logs errors.

4. Route Handlers

  • index: Main entry point for web interactions. Handles both GET and POST requests.

    • On POST:
      • Log the scenario and number of rows/columns.
      • Generate code and execute it dynamically.
      • Prepare and send CSV for download or preview based on user input.
    • On GET:
      • Render the index page for user interaction.
  • scenario_browser: Renders a different page for browsing scenarios.

  • set_scenario: Stores selected scenario in the session for later use.

5. Main Execution

  • Run the application with specified host and port settings.

Pseudo Code

START Application

IMPORT necessary libraries (Flask, render_template, request, send_file, jsonify, session, csv, io, random, openai, os, logging, traceback)

INITIALIZE Flask application

SET OPENAI API key from environment variable 'OPENAIDEMO'

FUNCTION extract_python_code(response):
    INITIALIZE empty list code_lines
    SET in_code_block to False
    SPLIT response by newline

    FOR each line IN lines:
        IF line starts with '```python':
            SET in_code_block to True
            CONTINUE
        ELSE IF line is '```' AND in_code_block:
            SET in_code_block to False
            CONTINUE
        IF in_code_block:
            APPEND line to code_lines
    RETURN joined code_lines with newline

FUNCTION generate_python_code(scenario, num_columns):
    CONSTRUCT prompt using scenario and num_columns
    TRY:
        CALL OpenAI API to get code response
        STORE response from OpenAI
        RETURN extract_python_code(full_response)
    EXCEPT Exception e:
        LOG error message
        RETURN None

SET logging configuration

DEFINE route '/' with methods GET, POST:
    IF method is POST:
        LOG received scenario and data
        TRY:
            GET scenario, num_rows, num_columns from request
            LOG received data
            generated_code = CALL generate_python_code(scenario, num_columns)
            LOG generated code
            IF generated_code is valid string:
                TRY:
                    EXECUTE generated_code using exec
                    IF 'generate_random_data' is not defined:
                        RAISE NameError
                    IF 'preview' is present in request:
                        preview_data = CALL generate_random_data with 5 rows
                        RETURN preview_data as JSON response
                    ELSE:
                        data = CALL generate_random_data with num_rows
                        LOG data generation
                        INITIALIZE CSV writer
                        WRITE header and data to CSV
                        RETURN CSV file for download
                EXCEPT Exception e:
                    LOG execution error
                    RETURN error message as JSON response
            ELSE:
                LOG code generation failure
                RETURN failure message as JSON response
        EXCEPT Exception e:
            LOG unexpected error
            RETURN unexpected error message as JSON response
    ELSE:
        SELECTED_SCENARIO from session or set to empty
        RENDER index.html with selected scenario

DEFINE route '/scenario-browser':
    RENDER scenario_browser.html

DEFINE route '/set-scenario' with method POST:
    GET scenario from request JSON
    STORE scenario in session
    RETURN success message as JSON response

IF main module:
    RUN application on host '0.0.0.0' and port 8080 with debug mode

END Application

Conclusion

The outlined pseudo code serves as a blueprint for implementing a Flask-based application that interacts with the OpenAI API for dynamic code generation and data handling. This structure ensures clarity and ease of understanding for future development and documentation purposes.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

This Flask app generates random data based on user scenarios using OpenAI's code generation capabilities. It handles HTTP requests, executes generated Python code, and can return data in CSV format for download.