import numpy as np import os import gradio as gr import openai import gspread from oauth2client.service_account import ServiceAccountCredentials # Define the credentials to access the Google Sheets API SCOPE = ["https://www.googleapis.com/auth/drive"] SERVICE_ACCOUNT_FILE = "./check" os.environ['GOOGLE_SHEETS_TOKEN'] # os.environ['GOOGLE_SHEETS_TOKEN'] creds = ServiceAccountCredentials.from_json_keyfile_name(SERVICE_ACCOUNT_FILE, SCOPE) client = gspread.authorize(creds) sheet = client.open("Feedback").sheet1 def continueStory(blank, messageHistory): openai.api_key = os.environ['OPENAI_KEY'] messageHistory.append({"role": "user", "content": blank + "\n\nGenerate the next paragraph with a blank in the last line for me to fill. There should only be one and only one blank in the paragraph. The blank should be at the end of the last line of the paragraph. It is very importat that there is only one blank and that it is at the end!"}) response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages = messageHistory ) story = response["choices"][0]["message"]["content"] messageHistory.append(response["choices"][0]["message"]) return story, messageHistory with gr.Blocks(css=''' .gradio-container { display: flex; flex-direction: column; justify-content: center; align-items: center; background-image: url('file=https://cdn.discordapp.com/attachments/941582479117127680/1080730421425344542/rodotcom_colorful_abstract_illustration_for_the_background_of_c_f1b331d7-6493-4a33-9063-345d31a66ddb.png'); } h1 { font-size: 3rem; font-weight: 700; margin-top: 1rem; margin-bottom: 1rem; color: white; } p { font-size: 1.25rem; margin-bottom: 2rem; color: white; } label { font-size: 1.25rem; font-weight: 500; margin-bottom: 0.5rem; } input[type="text"], textarea { font-size: 1.25rem; padding: 0.5rem; border: 2px solid #ccc; border-radius: 5px; width: 100%; } .gradio-button { background-color: #2196f3; color: #fff; font-size: 1.25rem; font-weight: 500; padding: 0.75rem 1.5rem; border-radius: 5px; cursor: pointer; transition: all 0.2s ease-in-out; } .gradio-button:hover { background-color: #0c7cd5; } ''') as demo: title = gr.HTML('''

Infinite Stories

Let's see where your imagination can take you!

''') with gr.Row(elem_id='row'): character = gr.Textbox(label='Who will be the main character?', elem_id = 'theme', placeholder="i.e. Diego, an 11-year-old pirate") messageHistory = gr.State() beginBtn = gr.Button("Start!", elem_id="generate-btn") story_output = gr.Textbox(label='Story') blank = gr.Textbox(label='How will you fill the blank?', elem_id = 'blank') with gr.Column(visible=True) as continueStoryCol: continueBtn = gr.Button("Continue Story", elem_id="continue-btn") with gr.Column(visible=False) as newStoryCol: newStoryBtn = gr.Button("Create New Story", elem_id="new-story-btn") with gr.Column(visible=True) as finishCol: finishBtn = gr.Button("Finish Story", elem_id="finish-btn") provideFeedbackBtn = gr.Button("Provide Feedback", elem_id="feedback-btn") with gr.Column(visible=False) as feedbackForm: ratingRadio = gr.Radio(["1", "2", "3", "4", "5"], label="How would you rate the story") feedback_text = gr.Textbox(label='Any other comments?') submitFeedbackBtn = gr.Button("Submit Feedback", elem_id="submit-feedback-btn") with gr.Column(visible=False) as thankyou: feedback_thankyou = gr.HTML("

Thanks for your feeback!

") with gr.Column(visible=False) as mesHistoryCol: messageHistoryTextBox = gr.Textbox(label='How will you fill the blank?', elem_id = 'blank', value=messageHistory) # the submit feedback btn needs to: send the feedback, # hide the elements and provide a message saying thanks for your feedback def show_feedback_text(): return {feedbackForm: gr.update(visible=True)} def submitFeedback(comment, rating, character, messageHistory): readableHistory = '' for m in messageHistory: readableHistory += m['content'] readableHistory += '\n\n' row = [comment, rating, character, readableHistory] sheet.append_row(row) return {thankyou: gr.update(visible=True), feedbackForm: gr.update(visible=False)} def generateStory(character): openai.api_key = openai.api_key = os.environ['OPENAI_KEY'] messageHistory=[ {"role": "system", "content": "You are a helpful assistant for storytelling-driven games that writes in the style of Doctor Seuss and Julia Donaldson."}, {"role": "system", "name":"example_user", "content": "We are going to engage in a collaborative storytelling game. You are going to generate a paragraph but you are going to leave a blank in the last word, that I will have to complete in order to generate the next paragraph. We will do this for every paragraph. Please generate the first paragraph. The story is about a {}. Write in the style of Julia Donaldson and Doctor Seuss. Remember, just write one paragraph! After this one paragraph is generated, I will tell you the word that I want to use to fill the blank, and then you can generate the next. For more context, the game works as follows. 1. You generate one, and only one paragraph, with a blank somewhere in the last line of the paragraph. 2. I tell you how I want to fill the blank. 3. You generate the next paragraph based on my response to continue the story, this next paragraph also has a blank somewhere in the last line of the paragraph. 4. I tell you how to fill the blank. And so on."}, {"role": "system", "name": "example_assistant", "content": "In a land of green hills and blue sky,\n Lived a boy named Jack, oh my oh my!\n He loved to explore and roam,\n From the woods to the sea foam.\n He'd climb up trees and run down hills,\n Watch the water flow and the flowers spill.\n But his favorite place, as you can see,\n Was the forest where he felt so free.\n One day, Jack set out to _____."}, {"role": "system", "name":"example_user", "content": "{A cave} Write the next paragraph and leave a blank at the end for me to fill!"}, {"role": "system", "name": "example_assistant", "content": "Jack had heard about a cave,\n Where treasure was hidden like in a rave.\n He packed some food and a flashlight,\n And set off, with all his might.\n The forest was thick and the way was rough,\n But Jack kept going, feeling tough.\n He crossed a stream and climbed a hill,\n Until he saw the cave, so still.\n The entrance was dark, but Jack was brave,\n He took a deep breath and entered the cave.\n Deep inside, he saw something ____."}, {"role": "user", "content": f"We are going to engage in a collaborative storytelling game. You are going to generate a paragraph but you are going to leave a blank in the last word, that I will have to complete in order to generate the next paragraph. We will do this for every paragraph. Please generate the first paragraph. The story is about {character}. Write in the style of Julia Donaldson and Doctor Seuss. Remember, just write one paragraph! After this one paragraph is generated, I will tell you the word that I want to use to fill the blank, and then you can generate the next. For more context, the game works as follows. 1. You generate one, and only one paragraph, with a blank somewhere in the last line of the paragraph. 2. I tell you how I want to fill the blank. 3. You generate the next paragraph based on my response to continue the story, this next paragraph also has a blank somewhere in the last line of the paragraph. 4. I tell you how to fill the blank. And so on."} ] response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages = messageHistory ) # check response and generate until you get desired behavior s = response["choices"][0]["message"]["content"] if (s.endswith("_.") or s.endswith("_")) and ("_" not in s[:-2].rstrip("_")): story = s else: response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages = messageHistory ) s = response["choices"][0]["message"]["content"] if (s.endswith("_.") or s.endswith("_")) and ("_" not in s[:-2].rstrip("_")): story = s else: response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages = messageHistory ) story = response["choices"][0]["message"]["content"] messageHistory.append(response["choices"][0]["message"]) return story, messageHistory def finishStory(blank, messageHistory): openai.api_key = openai.api_key = os.environ['OPENAI_KEY'] messageHistory.append({"role": "user", "content": blank + "\n\nNow bring the story to a close. Write the necessary paragraphs to make it have a happy or funny ending. No need to leave a blank anymore."}) response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages = messageHistory ) story = response["choices"][0]["message"]["content"] messageHistory.append(response["choices"][0]["message"]) return story, messageHistory def createNewStory(): return {character: gr.update(value=""), story_output: gr.update(value=""), blank: gr.update(value=""), continueStoryCol: gr.update(visible=True), finishCol: gr.update(visible=True), newStoryCol: gr.update(visible=False) } def hideContinueBtn(): return {continueStoryCol: gr.update(visible=False), newStoryCol: gr.update(visible=True), finishCol: gr.update(visible=False)} beginBtn.click(generateStory, inputs=[character], outputs=[story_output, messageHistory]) continueBtn.click(continueStory, inputs=[blank, messageHistory], outputs=[story_output, messageHistory]) finishBtn.click(finishStory, inputs=[blank, messageHistory], outputs=[story_output, messageHistory]) finishBtn.click(hideContinueBtn, [], [continueStoryCol, newStoryCol, finishCol]) provideFeedbackBtn.click(show_feedback_text, [], [feedbackForm]) submitFeedbackBtn.click(submitFeedback, [feedback_text, ratingRadio, character, messageHistory], [thankyou, feedbackForm]) newStoryBtn.click(createNewStory, [], [character, story_output, blank, continueStoryCol, finishCol, newStoryCol]) demo.launch(share=False)