JiheonJeong commited on
Commit
22108e0
·
1 Parent(s): dda1cd6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -105
app.py CHANGED
@@ -15,6 +15,8 @@ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
15
  NUM_THREADS = int(16)
16
  TOTAL_K = 5
17
  SAMPLE_IDX = []
 
 
18
 
19
  print (NUM_THREADS)
20
 
@@ -42,89 +44,90 @@ def parse_codeblock(text):
42
  lines[i] = "<br/>" + line.replace("<", "&lt;").replace(">", "&gt;")
43
  return "".join(lines)
44
 
45
- def predict(inputs, top_p, temperature, chat_counter, chatbot, history, request:gr.Request):
46
- payload = {
47
- "model": MODEL,
48
- "messages": [{"role": "user", "content": f"{inputs}"}],
49
- "temperature" : 1.0,
50
- "top_p":1.0,
51
- "n" : 1,
52
- "stream": True,
53
- "presence_penalty":0,
54
- "frequency_penalty":0,
55
- }
56
-
57
- headers = {
58
- "Content-Type": "application/json",
59
- "Authorization": f"Bearer {OPENAI_API_KEY}",
60
- "Headers": f"{request.kwargs['headers']}"
61
- }
62
-
63
- # print(f"chat_counter - {chat_counter}")
64
- if chat_counter != 0 :
65
- messages = []
66
- for i, data in enumerate(history):
67
- if i % 2 == 0:
68
- role = 'user'
69
- else:
70
- role = 'assistant'
71
- message = {}
72
- message["role"] = role
73
- message["content"] = data
74
- messages.append(message)
 
75
 
76
- message = {}
77
- message["role"] = "user"
78
- message["content"] = inputs
79
- messages.append(message)
80
- payload = {
81
- "model": MODEL,
82
- "messages": messages,
83
- "temperature" : temperature,
84
- "top_p": top_p,
85
- "n" : 1,
86
- "stream": True,
87
- "presence_penalty":0,
88
- "frequency_penalty":0,
89
- }
90
-
91
- chat_counter += 1
92
-
93
- history.append(inputs)
94
- token_counter = 0
95
- partial_words = ""
96
- counter = 0
97
-
98
- try:
99
- # make a POST request to the API endpoint using the requests.post method, passing in stream=True
100
- response = requests.post(API_URL, headers=headers, json=payload, stream=True)
101
- response_code = f"{response}"
102
- #if response_code.strip() != "<Response [200]>":
103
- # #print(f"response code - {response}")
104
- # raise Exception(f"Sorry, hitting rate limit. Please try again later. {response}")
105
 
106
- for chunk in response.iter_lines():
107
- #Skipping first chunk
108
- if counter == 0:
109
- counter += 1
110
- continue
111
- #counter+=1
112
- # check whether each line is non-empty
113
- if chunk.decode() :
114
- chunk = chunk.decode()
115
- # decode each line as response data is in bytes
116
- if len(chunk) > 12 and "content" in json.loads(chunk[6:])['choices'][0]['delta']:
117
- partial_words = partial_words + json.loads(chunk[6:])['choices'][0]["delta"]["content"]
118
- if token_counter == 0:
119
- history.append(" " + partial_words)
120
- else:
121
- history[-1] = partial_words
122
- token_counter += 1
123
- yield [(parse_codeblock(history[i]), parse_codeblock(history[i + 1])) for i in range(0, len(history) - 1, 2) ], history, chat_counter, response, gr.update(interactive=False), gr.update(interactive=False) # resembles {chatbot: chat, state: history}
124
- except Exception as e:
125
- print (f'error found: {e}')
126
- yield [(parse_codeblock(history[i]), parse_codeblock(history[i + 1])) for i in range(0, len(history) - 1, 2) ], history, chat_counter, response, gr.update(interactive=True), gr.update(interactive=True)
127
- print(json.dumps({"chat_counter": chat_counter, "payload": payload, "partial_words": partial_words, "token_counter": token_counter, "counter": counter}))
128
 
129
 
130
  def reset_textbox():
@@ -134,12 +137,11 @@ def random_sample():
134
  SAMPLE_IDX = random.choices(range(25), k=TOTAL_K)
135
  image = np.array(Image.open(os.path.join(os.path.dirname(__file__), "data/Court.jpeg")))
136
  random_characters = [Image.open(os.path.join(os.path.dirname(__file__), f'data/characters_{idx:02}.png')).resize((64, 64)) for idx in SAMPLE_IDX]
137
- random_position = [(145 + 200 * i + 400 * (i//2), j * 110 + 900) for i in range(4) for j in range(4) ]
138
- random_position = random.choices(random_position, k = TOTAL_K)
139
  new_image = Image.fromarray(image).convert('RGBA')
140
  for k in range(TOTAL_K):
141
- new_image.paste(random_characters[k], random_position[k], random_characters[k])
142
- return np.array(new_image)
143
 
144
  def reset_sample():
145
  image = np.array(Image.open(os.path.join(os.path.dirname(__file__), "data/Court.jpeg")))
@@ -160,6 +162,9 @@ Assistant: <utterance>
160
  In this app, you can explore the outputs of a gpt-3.5 LLM.
161
  """
162
 
 
 
 
163
  theme = gr.themes.Default(primary_hue="green")
164
  agents = []
165
  with gr.Blocks(css = """#col_container { margin-left: auto; margin-right: auto;}
@@ -170,14 +175,7 @@ with gr.Blocks(css = """#col_container { margin-left: auto; margin-right: auto;}
170
 
171
  #gr.HTML('''<center><a href="https://huggingface.co/spaces/yuntian-deng/ChatGPT?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>Duplicate the Space and run securely with your OpenAI API Key</center>''')
172
  with gr.Column(elem_id = "col_container", visible=False) as main_block:
173
- #API Key is provided by OpenAI
174
- #openai_api_key = gr.Textbox(type='password', label="Enter only your OpenAI API key here")
175
- # gr.HTML(f"""
176
- # <a href="https://huggingface.co/spaces/JiheonJeong/Temp2/resolve/main/data/Court.jpeg" target="_blank">
177
- # <img class="image-container" src="https://huggingface.co/spaces/JiheonJeong/Temp2/resolve/main/data/Court.jpeg" alt="이미지">
178
-
179
- # </a>
180
- # """)
181
  with gr.Row():
182
  with gr.Column(scale=7):
183
  image = gr.Image(os.path.join(os.path.dirname(__file__), "data/Court.jpeg"), height = 800, width = 1600)
@@ -185,19 +183,14 @@ with gr.Blocks(css = """#col_container { margin-left: auto; margin-right: auto;}
185
  for idx in range(TOTAL_K):
186
  text = gr.Textbox(label=f"Random Sample - {idx+1}")
187
  agents.append(text)
188
-
189
- # text1 = gr.Textbox(label="Random Sample - 1")
190
- # text2 = gr.Textbox(label="Random Sample - 2")
191
- # text3 = gr.Textbox(label="Random Sample - 3")
192
 
193
  # chatbot = gr.Chatbot(elem_id='chatbot') #c
194
- inputs = gr.Textbox(placeholder= "Hi there!", label= "Type an input and press Enter") #t
195
- # state = gr.State([]) #s
196
- # with gr.Row():
197
- # with gr.Column(scale=7):
198
- # b1 = gr.Button("Submission", visible=not DISABLED)
199
- # with gr.Column(scale=3):
200
- # server_status_code = gr.Textbox(label="Status code from OpenAI server", )
201
  with gr.Row():
202
  with gr.Column(scale=7):
203
  b0 = gr.Button('Random Sample', visible=not DISABLED)
@@ -238,7 +231,7 @@ with gr.Blocks(css = """#col_container { margin-left: auto; margin-right: auto;}
238
  accept_button.click(None, None, accept_checkbox, _js=js, queue=False)
239
  accept_checkbox.change(fn=enable_inputs, inputs=[], outputs=[user_consent_block, main_block], queue=False)
240
 
241
- b0.click(random_sample, inputs = [], outputs = [image])
242
  b2.click(reset_sample, inputs = [], outputs = [image])
243
 
244
  # inputs.submit(reset_textbox, [], [inputs, b1], queue=False)
 
15
  NUM_THREADS = int(16)
16
  TOTAL_K = 5
17
  SAMPLE_IDX = []
18
+ RANDOM_POSITION = [(145 + 200 * i + 400 * (i//2), j * 110 + 900) for i in range(4) for j in range(4) ]
19
+ CURRENT_POSITION = []
20
 
21
  print (NUM_THREADS)
22
 
 
44
  lines[i] = "<br/>" + line.replace("<", "&lt;").replace(">", "&gt;")
45
  return "".join(lines)
46
 
47
+
48
+ # def predict(inputs, top_p, temperature, chat_counter, chatbot, history, request:gr.Request):
49
+ # payload = {
50
+ # "model": MODEL,
51
+ # "messages": [{"role": "user", "content": f"{inputs}"}],
52
+ # "temperature" : 1.0,
53
+ # "top_p":1.0,
54
+ # "n" : 1,
55
+ # "stream": True,
56
+ # "presence_penalty":0,
57
+ # "frequency_penalty":0,
58
+ # }
59
+
60
+ # headers = {
61
+ # "Content-Type": "application/json",
62
+ # "Authorization": f"Bearer {OPENAI_API_KEY}",
63
+ # "Headers": f"{request.kwargs['headers']}"
64
+ # }
65
+
66
+ # # print(f"chat_counter - {chat_counter}")
67
+ # if chat_counter != 0 :
68
+ # messages = []
69
+ # for i, data in enumerate(history):
70
+ # if i % 2 == 0:
71
+ # role = 'user'
72
+ # else:
73
+ # role = 'assistant'
74
+ # message = {}
75
+ # message["role"] = role
76
+ # message["content"] = data
77
+ # messages.append(message)
78
 
79
+ # message = {}
80
+ # message["role"] = "user"
81
+ # message["content"] = inputs
82
+ # messages.append(message)
83
+ # payload = {
84
+ # "model": MODEL,
85
+ # "messages": messages,
86
+ # "temperature" : temperature,
87
+ # "top_p": top_p,
88
+ # "n" : 1,
89
+ # "stream": True,
90
+ # "presence_penalty":0,
91
+ # "frequency_penalty":0,
92
+ # }
93
+
94
+ # chat_counter += 1
95
+
96
+ # history.append(inputs)
97
+ # token_counter = 0
98
+ # partial_words = ""
99
+ # counter = 0
100
+
101
+ # try:
102
+ # # make a POST request to the API endpoint using the requests.post method, passing in stream=True
103
+ # response = requests.post(API_URL, headers=headers, json=payload, stream=True)
104
+ # response_code = f"{response}"
105
+ # #if response_code.strip() != "<Response [200]>":
106
+ # # #print(f"response code - {response}")
107
+ # # raise Exception(f"Sorry, hitting rate limit. Please try again later. {response}")
108
 
109
+ # for chunk in response.iter_lines():
110
+ # #Skipping first chunk
111
+ # if counter == 0:
112
+ # counter += 1
113
+ # continue
114
+ # #counter+=1
115
+ # # check whether each line is non-empty
116
+ # if chunk.decode() :
117
+ # chunk = chunk.decode()
118
+ # # decode each line as response data is in bytes
119
+ # if len(chunk) > 12 and "content" in json.loads(chunk[6:])['choices'][0]['delta']:
120
+ # partial_words = partial_words + json.loads(chunk[6:])['choices'][0]["delta"]["content"]
121
+ # if token_counter == 0:
122
+ # history.append(" " + partial_words)
123
+ # else:
124
+ # history[-1] = partial_words
125
+ # token_counter += 1
126
+ # yield [(parse_codeblock(history[i]), parse_codeblock(history[i + 1])) for i in range(0, len(history) - 1, 2) ], history, chat_counter, response, gr.update(interactive=False), gr.update(interactive=False) # resembles {chatbot: chat, state: history}
127
+ # except Exception as e:
128
+ # print (f'error found: {e}')
129
+ # yield [(parse_codeblock(history[i]), parse_codeblock(history[i + 1])) for i in range(0, len(history) - 1, 2) ], history, chat_counter, response, gr.update(interactive=True), gr.update(interactive=True)
130
+ # print(json.dumps({"chat_counter": chat_counter, "payload": payload, "partial_words": partial_words, "token_counter": token_counter, "counter": counter}))
131
 
132
 
133
  def reset_textbox():
 
137
  SAMPLE_IDX = random.choices(range(25), k=TOTAL_K)
138
  image = np.array(Image.open(os.path.join(os.path.dirname(__file__), "data/Court.jpeg")))
139
  random_characters = [Image.open(os.path.join(os.path.dirname(__file__), f'data/characters_{idx:02}.png')).resize((64, 64)) for idx in SAMPLE_IDX]
140
+ current_position = random.choices(RANDOM_POSITION, k = TOTAL_K)
 
141
  new_image = Image.fromarray(image).convert('RGBA')
142
  for k in range(TOTAL_K):
143
+ new_image.paste(random_characters[k], current_position[k], random_characters[k])
144
+ return np.array(new_image), current_position
145
 
146
  def reset_sample():
147
  image = np.array(Image.open(os.path.join(os.path.dirname(__file__), "data/Court.jpeg")))
 
162
  In this app, you can explore the outputs of a gpt-3.5 LLM.
163
  """
164
 
165
+ def sumbit(image):
166
+
167
+
168
  theme = gr.themes.Default(primary_hue="green")
169
  agents = []
170
  with gr.Blocks(css = """#col_container { margin-left: auto; margin-right: auto;}
 
175
 
176
  #gr.HTML('''<center><a href="https://huggingface.co/spaces/yuntian-deng/ChatGPT?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>Duplicate the Space and run securely with your OpenAI API Key</center>''')
177
  with gr.Column(elem_id = "col_container", visible=False) as main_block:
178
+
 
 
 
 
 
 
 
179
  with gr.Row():
180
  with gr.Column(scale=7):
181
  image = gr.Image(os.path.join(os.path.dirname(__file__), "data/Court.jpeg"), height = 800, width = 1600)
 
183
  for idx in range(TOTAL_K):
184
  text = gr.Textbox(label=f"Random Sample - {idx+1}")
185
  agents.append(text)
 
 
 
 
186
 
187
  # chatbot = gr.Chatbot(elem_id='chatbot') #c
188
+ with gr.Row():
189
+ with gr.Column(scale=7):
190
+ inputs = gr.Textbox(placeholder= "Hi there!", label= "Type an input and press Enter") #t
191
+ with gr.Column(scale=3):
192
+ b1 = gr.Button('Submit', visible=not DISABLED)
193
+
 
194
  with gr.Row():
195
  with gr.Column(scale=7):
196
  b0 = gr.Button('Random Sample', visible=not DISABLED)
 
231
  accept_button.click(None, None, accept_checkbox, _js=js, queue=False)
232
  accept_checkbox.change(fn=enable_inputs, inputs=[], outputs=[user_consent_block, main_block], queue=False)
233
 
234
+ b0.click(random_sample, inputs = [], outputs = [image, CURRENT_POSITION])
235
  b2.click(reset_sample, inputs = [], outputs = [image])
236
 
237
  # inputs.submit(reset_textbox, [], [inputs, b1], queue=False)