Seattle, WA. USA
MichaelRoyBean@gmail.com

OpenAI API Note Taking Application

Personal Portfoio

This is a current project I am working on to utilize OpenAI’s API to improve and expand on a note taking application. Use inputs their notes, the API then expands on those notes. The user can retrieve and delete notes, the application is in Python and is created to be as simple as possible for quick note taking.

import os
import datetime
from openai import OpenAI
from dotenv import load_dotenv
from termcolor import colored

# Load environment variables from .env file
load_dotenv()

# Set the OpenAI API key from the environment variable
client = OpenAI(api_key=os.environ.get('OPENAI_API_KEY'))

def correct_and_suggest(note):
    try:
        # Use the client instance for API calls
        # Updated method name for Edit
        response = client.edits.create(
            model="code-davinci-edit-001",
            input=note,
            instruction="Correct the grammar and spelling of the text."
        )
        corrected_note = response.choices[0].text.strip()

        # Updated method name for Completion
        suggestion_response = client.completions.create(
            model="text-davinci-003",
            prompt=f"Based on the note: '{corrected_note}', suggest additional notes:",
            max_tokens=50
        )
        suggestions = suggestion_response.choices[0].text.strip()

        return corrected_note, suggestions
    except Exception as e:
        print(colored(f"Error contacting OpenAI API: {e}", "red"))
        return note, ""
    
def clear_screen():
    os.system('cls' if os.name == 'nt' else 'clear')

def add_note():
    note = input("Enter your note: ")
    corrected_note, suggestions = correct_and_suggest(note)
    timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    with open("notes.txt", "a") as file:
        file.write(f"{timestamp}: {corrected_note}\n")
    print(colored("Note added successfully.", "green"))
    if suggestions:
        print(colored("Additional suggestions based on your note:", "cyan"))
        print(suggestions)

def view_notes():
    try:
        with open("notes.txt", "r") as file:
            notes = file.read()
        if notes:
            print(notes)
        else:
            print(colored("No notes found.", "yellow"))
    except FileNotFoundError:
        print(colored("No notes found.", "yellow"))

def delete_note():
    try:
        with open("notes.txt", "r") as file:
            lines = file.readlines()
        if not lines:
            print(colored("No notes to delete.", "yellow"))
            return
        print(colored("Select the note to delete:", "cyan"))
        for idx, line in enumerate(lines, start=1):
            print(f"{idx}. {line}", end='')
        choice = int(input("\nEnter the number of the note to delete: "))
        del lines[choice - 1]
        with open("notes.txt", "w") as file:
            file.writelines(lines)
        print(colored("Note deleted successfully.", "green"))
    except FileNotFoundError:
        print(colored("No notes found.", "yellow"))
    except IndexError:
        print(colored("Invalid selection.", "red"))
    except ValueError:
        print(colored("Please enter a valid number.", "red"))

def main_menu():
    clear_screen()
    print(colored("Note Taking Program", "blue", attrs=['bold']))
    print(colored("====================", "blue", attrs=['bold']))
    print(colored("1. Add Note", "magenta"))
    print(colored("2. View Notes", "magenta"))
    print(colored("3. Delete Note", "magenta"))
    print(colored("4. Clear Screen", "magenta"))
    print(colored("5. Exit", "magenta"))

def main():
    while True:
        main_menu()
        choice = input(colored("\nEnter your choice: ", "yellow"))
        if choice == "1":
            add_note()
        elif choice == "2":
            view_notes()
        elif choice == "3":
            delete_note()
        elif choice == "4":
            clear_screen()
        elif choice == "5":
            print(colored("Exiting program.", "green"))
            break
        else:
            print(colored("Invalid choice. Please enter a number between 1-5.", "red"))
        input(colored("\nPress Enter to continue...", "cyan"))

if __name__ == "__main__":
    main()