#Tweet Generation Code in Python
import serial
import openai
import cv2
#tweak how it needs you to close the image
openai.api_key = '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'
image = cv2.imread('example_post.png')
# Window name in which image is displayed
window_name = 'Image'
ser = serial.Serial()
ser.port = 'COM4'
ser.baudrate = 115200
ser.timeout=0.1
ser.open()
#make call to OpenAI
def generate_tweet(input):
completion = openai.ChatCompletion.create(model="gpt-3.5-turbo-0301", messages=[{"role": "user", "content": input}])
text = completion.choices[0].message.content
return text
#convert OpenAI output into multiple strings in an array in order to overlay onto image on seperate lines
def format_tweet(tweet):
text_arr = tweet.split()
text_arr_reformatted = []
current_line = ""
line_char_count = 0
for i in text_arr:
line_char_count = line_char_count + len(i)
if line_char_count > 42:
text_arr_reformatted.append(current_line)
line_char_count = len(i) + 1
current_line = i + " "
else:
current_line = current_line + i + " "
print(current_line)
line_char_count = line_char_count + 1
text_arr_reformatted.append(current_line)
return text_arr_reformatted
#turns set area of template white then writes formatted text over the white space
def edit_image(text_arr):
new_image = cv2.imread('example_post.png')
white = (255, 255, 255)
image[55:200] = white
# font
font = cv2.FONT_HERSHEY_SIMPLEX
# org (x, y)
org = (25, 80)
# fontScale
fontScale = 0.55
#Color in BGR
color = (0, 0, 0)
# Line thickness of 2 px
thickness = 1
y0, dy = 80, 15
for i, line in enumerate(text_arr):
y = y0 + i*dy
cv2.putText(image, line, (25, y ), font, fontScale, color, thickness)
return new_image
prompt = "Without using emojis, pick a random activity and make a tweet in the style of a robot about watching someone doing the activity"
#loops constantly checking for serial monitor output until ctrl+C in terminal
demo = True
while(demo):
output = ser.readline().decode('ASCII')
print(output)
if "Generate tweet" in output:
print(prompt)
tweet = generate_tweet(prompt)
print("New Tweet - " + tweet)
new_image = edit_image(format_tweet(tweet))
cv2.imwrite('new_tweet' + str(test) + ".png", image)
cv2.imshow('New Tweet', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
ser.close()
Click to Expand
Content Rating
Is this a good/useful/informative piece of content to include in the project? Have your say!
You must login before you can post a comment. .