Jean Noรซl
Published ยฉ CC BY-SA

ProseCode - Sticky Shapes

โ€œ๐˜๐—ต๐—ฒ ๐—ฑ๐—ฒ๐˜€๐—ฐ๐—ฟ๐—ถ๐—ฝ๐˜๐—ถ๐—ผ๐—ป ๐˜„๐—ถ๐—น๐—น ๐—ฏ๐—ฒ ๐˜๐—ต๐—ฒ ๐—ฝ๐—ฟ๐—ผ๐—ด๐—ฟ๐—ฎ๐—บโ€ A proof of concept ProseCode - Sticky Shapes (powered by chatGPT)

IntermediateFull instructions provided1 hour412
ProseCode - Sticky Shapes

Things used in this project

Software apps and online services

Python 3
chatGPT

Story

Read more

Schematics

IDE screenshot

a screenshot of the Pycharm IDE

Code

ProseCodeStickyShapes_03.py

Python
# -*- coding: utf-8 -*-
#https://levelup.gitconnected.com/interfacing-chatgpt-with-python-824be63dfa2f
#https://sharegpt.com/c/IldH7z0
#https://ancient-rest-469.notion.site/Osez-les-4-Jours-de-L-cole-LDLC-atelier-Python-Chat-GPT-ad408254451f49979381dba7c44e9871

from tkinter import *
import threading
import openai
import openai.error
from queue import Queue
import time
import math
import random

Keyfile = open("api_key.txt", "r")
openai.api_key = Keyfile.readline()
Keyfile.close()

#modele="gpt-3.5-turbo-16k"
modele="gpt-4"
temperature = 0.2

print("checking openai API connexion ...")
modellist = openai.Model.list()
#for i in modellist.data:
    #print(i.id)
print("****************************")
print("ProseCode Stickers: ready!")
print("I can draw sticky shapes on the drawing canva")

f = open("session_log.txt", "w")
f.write("ProseCode_Stickers LOG\n")
f.close()

script = open("script.txt", "w")
script.write("#saved script")
script.close()

queue = Queue()
error = False
stop= False
tempscript=" "
codeGPT=""

def script_extract():
    #print("EXTRACTION")
    flag = False
    global codeGPT
    tempscript1 = open("temp.txt", "w")
    tempscript1.write(codeGPT)
    tempscript1.close()
    codeGPT=""
    tempscript2 = open("temp.txt", "r")
    line = "***"
    while line != "":
        line = tempscript2.readline()
        if line.startswith("#ProseCode"):
            flag = True
        if line.startswith("#EndProse"):
            flag = False
            codeGPT = codeGPT + line
            break
        if(flag == True):
            #print("OK>" + line)
            codeGPT = codeGPT + line
    tempscript3 = open("tempGPT.txt", "w")
    tempscript3.write(codeGPT)
    tempscript3.close()
    tempscript2.close()

def refresh():
    fen.quit()
    vp_start_gui()
    #my_draw()

def vp_start_gui():
    global fen
    global canva
    fen = Tk()
    fen.title("ProseCode sticky shapes")
    fen.geometry("800x950")
    canva = Canvas(fen, width=800, height=800, bg='#e3e3dc')
    canva.pack()

    def stop_button_clicked():
        global stop
        stop = True

    def erase_button_clicked():
        global stop
        stop = True
        canva.delete("all")

    # Cration des boutons STOP, PLAY, ERASE et RESTART
    button_frame = Frame(fen)
    button_frame.pack()

    stop_button = Button(button_frame, text="STOP", command=stop_button_clicked, width=10, height=2)
    stop_button.grid(row=0, column=0, padx=5, pady=5)
    erase_button = Button(button_frame, text="ERASE", command=erase_button_clicked, width=10, height=2)
    erase_button.grid(row=0, column=2, padx=5, pady=5)


def Log(string):
    f = open("session_log.txt", "a")
    f.write(string)
    f.close()

def my_draw():
    global stop
    global code_GPT
    global tempscript
    global error
    global canva
    if not(queue.empty()):
        if (error == False):
            code_GPT= queue.get()
        else:
            code_GPT =" ERROR  "
        try:
            #print("Execution:")
            #print(code_GPT)
            exec(code_GPT)
        except:
            print("")
            print("sorry i don't know how to make it :-(")
            Log("sorry i don't know how to make it :-(")
            canva.delete("all")
            exec(tempscript)
            tempscript=" "
            error = False
            print("please, ask me again: ")

        else:
            #savedscript= code_GPT
            script = open("script.txt", "a")
            script.write(code_GPT)
            script.close()
            script = open("script.txt", "r")
            lastscript= script.readlines()
            script.close()
            for i in lastscript:
                tempscript = tempscript + i

    canva.after(20, my_draw)

messages = []


Prompt1 =''' Complete le script Python pour dessiner ce que je vais demander avec Tkinter Canvas,
uniquement les objets du Canva.
 '''

Prompt2 =''' 
Respecte strictement toutes les consignes suivantes avant de repondre :
Donne moi uniquement le code ncessaire entre les commentaire #ProseCode et #EndProse dans le script de base. 
Uniquement des instructions Python Tkinter Canvas.
Si il y a une boucle While on doit en sortir si le bool stop (global) est True, n'initialise pas ce bool stop.
Les objets dessines doivent toujours rester l'interieur du canva,
attention au rafraichissement des objets pour les animations: utiliser fen.update() si necessaire,
n'oublies pas les commentaire #ProseCode et #EndProse qui encadreront ton code Python
n'ajoute pas de fen.mainloop() car il est deja prevu dans le script de base.
Si c'est trop difficile : essaye quand meme avec un modele simplifie de ma demande.
Decris moi toujours ton dessin en commentaire, explicite tes choix en detail, juste apres #ProseCode.
Si tu ne peux pas generer le dessin demande : pose moi des questions en commentaires entre #ProseCode et #EndProse dans ta reponse.
Si la demande est en Anglais : reponds en Anglais pour les commentaires, sinon en Francais.
'''

messageInitial = """voici le script Python de base:
from tkinter import *
import time
import math 
import random

fen = Tk()
fen.title("ProseCode Stickers")
fen.geometry("800x1000")
canva = Canvas(fen, width=800, height=800, bg='#e3e3dc')
canva.pack()
stop = False

#ProseCode

#EndProse

fen.mainloop()

Memorise ce code de base.
Attention: n'ajoute pas d'espace aux commentaires #ProseCode et #EndProse.
voici ce que je veux dessiner dans ce script :

"""

messages.append(
        {
            'role': 'assistant',
            'content': messageInitial
        })

import time
import openai.error

def ChatSession():
    global codeGPT
    global error
    global stop
    global messages  # declare messages as global if it needs to be accessed outside this function

    while True:
        prompt = input('\nWhat do you want me to draw?: ')
        Log('\nWhat do you want me to draw?: ')
        Log(prompt)
        print("OK, I'm preparing the sticky shapes, please wait... ")
        stop = True
        prompt_complet = Prompt1 + messageInitial + prompt + Prompt2
        messages.append(
                {
                    'role': 'user',
                    'content': prompt_complet
                })
        # Limit the number of messages
        max_messages = 10
        messages = messages[-max_messages:]

        try:
            completion = openai.ChatCompletion.create(
                    model=modele,
                    messages=messages,
                    temperature=temperature)

            answer = completion['choices'][0]['message']['content']
            codeGPT = answer.strip()
            script_extract()
            print("Here is the Python code for what you asked:")
            print(codeGPT)
            Log("\n")
            Log(answer)
            Log("\n")
            stop = False
            queue.put(codeGPT)

            print("********************************************")
            messages.append(
                    {
                        'role': 'assistant',
                        'content': answer
                    })

        except openai.error.APIConnectionError as e:
            print(f"Error communicating with OpenAI: {e}. Retrying after 5 seconds...")
            time.sleep(5)
            continue

        except openai.error.InvalidRequestError as e:
            print("Error: ", e)
            continue


if __name__ == "__main__":
    t1 = threading.Thread(target=ChatSession)
    t2 = threading.Thread(target=my_draw)


    vp_start_gui()
    t1.start()
    t2.start()
    fen.mainloop()

Credits

Jean Noรซl
13 projects โ€ข 36 followers
pedagogical director at L'รฉcole LDLC https://www.linkedin.com/in/jnlootsidebox/
Contact

Comments

Please log in or sign up to comment.