Spaces:
Sleeping
Sleeping
File size: 9,054 Bytes
d028a9b 0f5564a 22108e0 d028a9b 5963935 f159474 3bd97c2 d028a9b 9484ce7 f159474 d028a9b 9484ce7 703ce39 d028a9b cebdace d028a9b cebdace d028a9b 8d3a5ca 5963935 21c05be 66ba57f 18384f9 cff0d7a 66ba57f cff0d7a 66ba57f cff0d7a 22108e0 d56be10 d028a9b 22108e0 c67c3ba 4ae55cf d56be10 dda1cd6 c67c3ba 4ae55cf 22108e0 d028a9b eefa63e d028a9b 9484ce7 5457a5d 5963935 5c7093e d028a9b 0fae765 3337e70 d028a9b | 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 | import gradio as gr
import os
import sys
import json
import requests
import glob
from PIL import Image
from io import BytesIO
import random
import numpy as np
MODEL = "gpt-3.5-turbo"
API_URL = os.getenv("API_URL")
DISABLED = os.getenv("DISABLED") == 'True'
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
NUM_THREADS = int(16)
TOTAL_K = 5
SAMPLE_IDX = []
RANDOM_POSITION = [[145 + 200 * i + 400 * (i//2), j * 110 + 900] for i in range(4) for j in range(4) ]
CURRENT_POSITION = []
print (NUM_THREADS)
def exception_handler(exception_type, exception, traceback):
print("%s: %s" % (exception_type.__name__, exception))
sys.excepthook = exception_handler
sys.tracebacklimit = 0
def show_image_from_link(image_link):
response = requests.get(image_link)
img = Image.open(BytesIO(response.content))
return img
#https://github.com/gradio-app/gradio/issues/3531#issuecomment-1484029099
def parse_codeblock(text):
lines = text.split("\n")
for i, line in enumerate(lines):
if "```" in line:
if line != "```":
lines[i] = f'<pre><code class="{lines[i][3:]}">'
else:
lines[i] = '</code></pre>'
else:
if i > 0:
lines[i] = "<br/>" + line.replace("<", "<").replace(">", ">")
return "".join(lines)
def random_sample():
global SAMPLE_IDX
# SAMPLE_IDX = get_random_sample(range(25), TOTAL_K)
SAMPLE_IDX = list(np.random.choice(range(25), TOTAL_K, replace = False))
# SAMPLE_IDX = random.choices(range(25), k=TOTAL_K)
image = np.array(Image.open(os.path.join(os.path.dirname(__file__), "data/Court.jpeg")))
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]
global CURRENT_POSITION
# CURRENT_POSITION = get_random_sample(RANDOM_POSITION, TOTAL_K)
CURRENT_POSITION = [ RANDOM_POSITION[k] for k in list(np.random.choice(range(len(RANDOM_POSITION)), TOTAL_K, replace = False))]
# CURRENT_POSITION = random.choices(range(len(RANDOM_POSITION)), k = TOTAL_K)
new_image = Image.fromarray(image).convert('RGBA')
for k in range(TOTAL_K):
new_image.paste(random_characters[k], CURRENT_POSITION[k], random_characters[k])
print(CURRENT_POSITION)
return np.array(new_image)
def reset_sample(*agents):
image = np.array(Image.open(os.path.join(os.path.dirname(__file__), "data/Court.jpeg")))
new_agents = []
for k in range(TOTAL_K):
new_agents.append('')
return image, *[gr.Textbox.update(value=answer) for answer in new_agents]
title = """<h1 align="center">Courtroom with AI juries</h1>"""
if DISABLED:
title = """<h1 align="center" style="color:red">This app has reached OpenAI's usage limit. We are currently requesting an increase in our quota. Please check back in a few days.</h1>"""
description = """Language models can be conditioned to act like dialogue agents through a conversational prompt that typically takes the form:
```
User: <utterance>
Assistant: <utterance>
User: <utterance>
Assistant: <utterance>
...
```
In this app, you can explore the outputs of a gpt-3.5 LLM.
"""
def submit(image, *agents):
global CURRENT_POSITION
balloon = Image.open(os.path.join(os.path.dirname(__file__), 'data/balloon.png')).resize((64, 64))
new_image = Image.fromarray(image).convert('RGBA')
for k in range(TOTAL_K):
new_image.paste(balloon, [CURRENT_POSITION[k][0], CURRENT_POSITION[k][1] - 64], balloon)
Answer = 'X'
new_agents = []
for k in range(TOTAL_K):
new_agents.append(Answer)
return np.array(new_image), *[gr.Textbox.update(value=answer) for answer in new_agents]
theme = gr.themes.Default(primary_hue="green")
agents = []
with gr.Blocks(css = """#col_container { margin-left: auto; margin-right: auto;}
#chatbot {height: 520px; overflow: auto;}""",
theme=theme) as demo:
gr.HTML(title)
#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>''')
with gr.Column(elem_id = "col_container", visible=False) as main_block:
with gr.Row():
with gr.Column(scale=7):
image = gr.Image(os.path.join(os.path.dirname(__file__), "data/Court.jpeg"), height = 800, width = 1600)
with gr.Column(scale=3):
for idx in range(TOTAL_K):
text = gr.Textbox(label=f"Random Sample - {idx+1}")
agents.append(text)
# chatbot = gr.Chatbot(elem_id='chatbot') #c
with gr.Row():
with gr.Column(scale=7):
inputs = gr.Textbox(placeholder= "Hi there!", label= "Type an input and press Enter") #t
with gr.Column(scale=3):
b1 = gr.Button('Submit', visible=not DISABLED)
with gr.Row():
with gr.Column(scale=7):
b0 = gr.Button('Random Sample', visible=not DISABLED)
with gr.Column(scale=3):
b2 = gr.Button('Reset', visible=not DISABLED)
#inputs, top_p, temperature, top_k, repetition_penalty
with gr.Accordion("Parameters", open=False):
top_p = gr.Slider( minimum=-0, maximum=1.0, value=1.0, step=0.05, interactive=True, label="Top-p (nucleus sampling)",)
temperature = gr.Slider( minimum=-0, maximum=5.0, value=1.0, step=0.1, interactive=True, label="Temperature",)
#top_k = gr.Slider( minimum=1, maximum=50, value=4, step=1, interactive=True, label="Top-k",)
#repetition_penalty = gr.Slider( minimum=0.1, maximum=3.0, value=1.03, step=0.01, interactive=True, label="Repetition Penalty", )
chat_counter = gr.Number(value=0, visible=False, precision=0)
with gr.Column(elem_id = "user_consent_container") as user_consent_block:
# Get user consent
accept_checkbox = gr.Checkbox(visible=False)
js = "(x) => confirm('By clicking \"OK\", I agree that my data may be published or shared.')"
with gr.Accordion("User Consent for Data Collection, Use, and Sharing", open=True):
gr.HTML("""
<div>
<p>By using our app, which is powered by OpenAI's API, you acknowledge and agree to the following terms regarding the data you provide:</p>
<ol>
<li><strong>Collection:</strong> We may collect information, including the inputs you type into our app, the outputs generated by OpenAI's API, and certain technical details about your device and connection (such as browser type, operating system, and IP address) provided by your device's request headers.</li>
<li><strong>Use:</strong> We may use the collected data for research purposes, to improve our services, and to develop new products or services, including commercial applications, and for security purposes, such as protecting against unauthorized access and attacks.</li>
<li><strong>Sharing and Publication:</strong> Your data, including the technical details collected from your device's request headers, may be published, shared with third parties, or used for analysis and reporting purposes.</li>
<li><strong>Data Retention:</strong> We may retain your data, including the technical details collected from your device's request headers, for as long as necessary.</li>
</ol>
<p>By continuing to use our app, you provide your explicit consent to the collection, use, and potential sharing of your data as described above. If you do not agree with our data collection, use, and sharing practices, please do not use our app.</p>
</div>
""")
accept_button = gr.Button("I Agree")
def enable_inputs():
return user_consent_block.update(visible=False), main_block.update(visible=True)
accept_button.click(None, None, accept_checkbox, _js=js, queue=False)
accept_checkbox.change(fn=enable_inputs, inputs=[], outputs=[user_consent_block, main_block], queue=False)
b0.click(random_sample, inputs = [], outputs = [image])
b2.click(reset_sample, inputs = [], outputs = [image, *agents])
b1.click(submit, inputs = [image, *agents], outputs = [image, *agents])
# inputs.submit(reset_textbox, [], [inputs, b1], queue=False)
# inputs.submit(predict, [inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter, server_status_code, inputs, b1],) #openai_api_key
# b1.click(reset_textbox, [], [inputs, b1], queue=False)
# b1.click(predict, [inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter, server_status_code, inputs, b1],) #openai_api_key
demo.queue(max_size=20, concurrency_count=NUM_THREADS, api_open=False).launch(share=False) |