File size: 10,864 Bytes
1031360
d40162f
1031360
 
0802045
 
 
 
 
 
 
 
fd378ee
 
0802045
 
 
3a159e9
e6630ec
1ecf223
3a159e9
1ecf223
3a159e9
61f86b3
 
1ecf223
 
 
 
3a159e9
1ecf223
 
0802045
1ecf223
3a159e9
 
b2bd8fb
 
3a159e9
1ecf223
 
 
 
 
 
b2bd8fb
1ecf223
81ef9db
a1fd363
1ecf223
 
 
48d020e
1ecf223
 
 
fd378ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61f86b3
d40162f
 
1ecf223
 
61f86b3
d40162f
 
b2bd8fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0802045
 
 
b2bd8fb
 
 
0802045
b2bd8fb
 
 
 
 
61f86b3
b2bd8fb
 
 
14d2ae1
 
 
0802045
 
 
 
 
 
 
 
 
 
14d2ae1
 
 
 
d5c8a18
 
 
 
 
 
 
14d2ae1
 
 
 
 
d5c8a18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14d2ae1
 
 
 
 
 
b2bd8fb
14d2ae1
 
 
 
 
 
 
 
 
 
 
0802045
14d2ae1
 
 
fd378ee
14d2ae1
 
 
5dcee28
 
14d2ae1
c555193
14d2ae1
 
 
 
 
 
 
0802045
14d2ae1
fd378ee
61f86b3
b1aa375
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
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('''
        <div style="text-align: center;">
            <h1 style="color: white; font-size: 3rem; font-weight: 700; margin-bottom: 1rem; color: white;">Infinite Stories</h1>
            <p style="color: white; font-size: 1.25rem; margin-bottom: 2rem; color: white;">Let's see where your imagination can take you!</p>
        </div>
    ''')
    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("<h2>Thanks for your feeback!</h2>")

    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):
   
      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)