|
import openai |
|
import requests |
|
from gpiozero import Button |
|
from time import sleep |
|
import os |
|
|
|
# Replace with your OpenAI API key |
|
openai.api_key = 'your_openai_api_key' |
|
|
|
# Define GPIO pins |
|
START_BUTTON_PIN = 17 |
|
CLEAR_BUTTON_PIN = 27 |
|
|
|
# Initialize buttons |
|
start_button = Button(START_BUTTON_PIN) |
|
clear_button = Button(CLEAR_BUTTON_PIN) |
|
|
|
conversation_history = [] |
|
current_author = "" |
|
|
|
# Project Gutenberg search function |
|
def get_author_works(author_name): |
|
search_url = f'http://gutendex.com/search/?title={author_name}&languages=en' |
|
response = requests.get(search_url) |
|
results = response.json() |
|
if results['results']: |
|
# Example: get the first work for simplicity |
|
work_url = results['results'][0]['url'] |
|
return work_url |
|
return None |
|
|
|
def download_work(work_url): |
|
response = requests.get(work_url) |
|
if response.status_code == 200: |
|
with open('author_work.txt', 'w') as file: |
|
file.write(response.text) |
|
else: |
|
print("Failed to download work.") |
|
|
|
# Function to send a message to ChatGPT |
|
def send_to_chatgpt(message): |
|
global conversation_history |
|
conversation_history.append(message) |
|
response = openai.ChatCompletion.create( |
|
model="gpt-3.5-turbo", |
|
messages=[{"role": "user", "content": msg} for msg in conversation_history] |
|
) |
|
reply = response.choices[0].message['content'] |
|
conversation_history.append(reply) |
|
return reply |
|
|
|
# Button press handlers |
|
def start_conversation(): |
|
global conversation_history |
|
conversation_history = [] |
|
global current_author |
|
if current_author: |
|
author_work_url = get_author_works(current_author) |
|
if author_work_url: |
|
download_work(author_work_url) |
|
with open('author_work.txt', 'r') as file: |
|
context = file.read() |
|
prompt = f"Act like {current_author}. Here is some context: {context}" |
|
else: |
|
prompt = f"Act like {current_author}. I don't have specific works to provide." |
|
else: |
|
prompt = "Please provide the author's name to start." |
|
print("ChatGPT:", send_to_chatgpt(prompt)) |
|
|
|
def clear_conversation(): |
|
global conversation_history |
|
conversation_history = [] |
|
print("Conversation cleared.") |
|
|
|
# Attach button event handlers |
|
start_button.when_pressed = start_conversation |
|
clear_button.when_pressed = clear_conversation |
|
|
|
print("Press the buttons to interact with ChatGPT.") |
|
while True: |
|
sleep(1) |