Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
@@ -1,199 +1,32 @@
|
|
1 |
import gradio as gr
|
2 |
-
import
|
3 |
-
import sys
|
4 |
-
import json
|
5 |
-
import requests
|
6 |
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
11 |
-
print (API_URL)
|
12 |
-
print (OPENAI_API_KEY)
|
13 |
-
NUM_THREADS = int(os.getenv("NUM_THREADS"))
|
14 |
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
print("%s: %s" % (exception_type.__name__, exception))
|
19 |
-
sys.excepthook = exception_handler
|
20 |
-
sys.tracebacklimit = 0
|
21 |
-
|
22 |
-
#https://github.com/gradio-app/gradio/issues/3531#issuecomment-1484029099
|
23 |
-
def parse_codeblock(text):
|
24 |
-
lines = text.split("\n")
|
25 |
-
for i, line in enumerate(lines):
|
26 |
-
if "```" in line:
|
27 |
-
if line != "```":
|
28 |
-
lines[i] = f'<pre><code class="{lines[i][3:]}">'
|
29 |
-
else:
|
30 |
-
lines[i] = '</code></pre>'
|
31 |
-
else:
|
32 |
-
if i > 0:
|
33 |
-
lines[i] = "<br/>" + line.replace("<", "<").replace(">", ">")
|
34 |
-
return "".join(lines)
|
35 |
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
"top_p":1.0,
|
42 |
-
"n" : 1,
|
43 |
-
"stream": True,
|
44 |
-
"presence_penalty":0,
|
45 |
-
"frequency_penalty":0,
|
46 |
-
}
|
47 |
-
|
48 |
-
headers = {
|
49 |
-
"Content-Type": "application/json",
|
50 |
-
"Authorization": f"Bearer {OPENAI_API_KEY}",
|
51 |
-
"Headers": f"{request.kwargs['headers']}"
|
52 |
-
}
|
53 |
-
|
54 |
-
# print(f"chat_counter - {chat_counter}")
|
55 |
-
if chat_counter != 0 :
|
56 |
-
messages = []
|
57 |
-
for i, data in enumerate(history):
|
58 |
-
if i % 2 == 0:
|
59 |
-
role = 'user'
|
60 |
-
else:
|
61 |
-
role = 'assistant'
|
62 |
-
message = {}
|
63 |
-
message["role"] = role
|
64 |
-
message["content"] = data
|
65 |
-
messages.append(message)
|
66 |
-
|
67 |
-
message = {}
|
68 |
-
message["role"] = "user"
|
69 |
-
message["content"] = inputs
|
70 |
-
messages.append(message)
|
71 |
-
payload = {
|
72 |
-
"model": MODEL,
|
73 |
-
"messages": messages,
|
74 |
-
"temperature" : temperature,
|
75 |
-
"top_p": top_p,
|
76 |
-
"n" : 1,
|
77 |
-
"stream": True,
|
78 |
-
"presence_penalty":0,
|
79 |
-
"frequency_penalty":0,
|
80 |
-
}
|
81 |
-
|
82 |
-
chat_counter += 1
|
83 |
-
|
84 |
-
history.append(inputs)
|
85 |
-
token_counter = 0
|
86 |
-
partial_words = ""
|
87 |
-
counter = 0
|
88 |
-
|
89 |
-
try:
|
90 |
-
# make a POST request to the API endpoint using the requests.post method, passing in stream=True
|
91 |
-
response = requests.post(API_URL, headers=headers, json=payload, stream=True)
|
92 |
-
response_code = f"{response}"
|
93 |
-
#if response_code.strip() != "<Response [200]>":
|
94 |
-
# #print(f"response code - {response}")
|
95 |
-
# raise Exception(f"Sorry, hitting rate limit. Please try again later. {response}")
|
96 |
-
|
97 |
-
for chunk in response.iter_lines():
|
98 |
-
#Skipping first chunk
|
99 |
-
if counter == 0:
|
100 |
-
counter += 1
|
101 |
-
continue
|
102 |
-
#counter+=1
|
103 |
-
# check whether each line is non-empty
|
104 |
-
if chunk.decode() :
|
105 |
-
chunk = chunk.decode()
|
106 |
-
# decode each line as response data is in bytes
|
107 |
-
if len(chunk) > 12 and "content" in json.loads(chunk[6:])['choices'][0]['delta']:
|
108 |
-
partial_words = partial_words + json.loads(chunk[6:])['choices'][0]["delta"]["content"]
|
109 |
-
if token_counter == 0:
|
110 |
-
history.append(" " + partial_words)
|
111 |
-
else:
|
112 |
-
history[-1] = partial_words
|
113 |
-
token_counter += 1
|
114 |
-
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}
|
115 |
-
except Exception as e:
|
116 |
-
print (f'error found: {e}')
|
117 |
-
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)
|
118 |
-
print(json.dumps({"chat_counter": chat_counter, "payload": payload, "partial_words": partial_words, "token_counter": token_counter, "counter": counter}))
|
119 |
-
|
120 |
-
|
121 |
-
def reset_textbox():
|
122 |
-
return gr.update(value='', interactive=False), gr.update(interactive=False)
|
123 |
-
|
124 |
-
title = """<h1 align="center">GPT-4 Turbo: Research Preview (128K token limit, Short-Term Availability)</h1>"""
|
125 |
-
if DISABLED:
|
126 |
-
title = """<h1 align="center" style="color:red">This app has reached OpenAI's usage limit. Please check back tomorrow.</h1>"""
|
127 |
-
description = """Language models can be conditioned to act like dialogue agents through a conversational prompt that typically takes the form:
|
128 |
-
```
|
129 |
-
User: <utterance>
|
130 |
-
Assistant: <utterance>
|
131 |
-
User: <utterance>
|
132 |
-
Assistant: <utterance>
|
133 |
-
...
|
134 |
-
```
|
135 |
-
In this app, you can explore the outputs of a gpt-4 turbo LLM.
|
136 |
-
"""
|
137 |
-
|
138 |
-
theme = gr.themes.Default(primary_hue="green")
|
139 |
-
|
140 |
-
with gr.Blocks(css = """#col_container { margin-left: auto; margin-right: auto;}
|
141 |
-
#chatbot {height: 520px; overflow: auto;}""",
|
142 |
-
theme=theme) as demo:
|
143 |
-
gr.HTML(title)
|
144 |
-
#gr.HTML("""<h3 align="center">This app provides you full access to GPT-4 Turbo (128K token limit). You don't need any OPENAI API key.</h1>""")
|
145 |
-
#gr.HTML("""<h3 align="center" style="color: red;">If this app is too busy, consider trying our GPT-3.5 app, which has a much shorter queue time. Visit it below:<br/><a href="https://huggingface.co/spaces/yuntian-deng/ChatGPT">https://huggingface.co/spaces/yuntian-deng/ChatGPT</a></h3>""")
|
146 |
-
gr.HTML("""<h3 align="center" style="color: red;">If this app doesn't respond, it's likely due to our API key hitting the daily limit of our organization. Consider trying our GPT-3.5 app:<br/><a href="https://huggingface.co/spaces/yuntian-deng/ChatGPT">https://huggingface.co/spaces/yuntian-deng/ChatGPT</a></h3>""")
|
147 |
-
|
148 |
-
#gr.HTML('''<center><a href="https://huggingface.co/spaces/ysharma/ChatGPT4?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>Duplicate the Space and run securely with your OpenAI API Key</center>''')
|
149 |
-
with gr.Column(elem_id = "col_container", visible=False) as main_block:
|
150 |
-
#GPT4 API Key is provided by Huggingface
|
151 |
-
#openai_api_key = gr.Textbox(type='password', label="Enter only your GPT4 OpenAI API key here")
|
152 |
-
chatbot = gr.Chatbot(elem_id='chatbot') #c
|
153 |
-
inputs = gr.Textbox(placeholder= "Hi there!", label= "Type an input and press Enter") #t
|
154 |
-
state = gr.State([]) #s
|
155 |
-
with gr.Row():
|
156 |
-
with gr.Column(scale=7):
|
157 |
-
b1 = gr.Button(visible=not DISABLED).style(full_width=True)
|
158 |
-
with gr.Column(scale=3):
|
159 |
-
server_status_code = gr.Textbox(label="Status code from OpenAI server", )
|
160 |
|
161 |
-
|
162 |
-
with gr.Accordion("Parameters", open=False):
|
163 |
-
top_p = gr.Slider( minimum=-0, maximum=1.0, value=1.0, step=0.05, interactive=True, label="Top-p (nucleus sampling)",)
|
164 |
-
temperature = gr.Slider( minimum=-0, maximum=5.0, value=1.0, step=0.1, interactive=True, label="Temperature",)
|
165 |
-
#top_k = gr.Slider( minimum=1, maximum=50, value=4, step=1, interactive=True, label="Top-k",)
|
166 |
-
#repetition_penalty = gr.Slider( minimum=0.1, maximum=3.0, value=1.03, step=0.01, interactive=True, label="Repetition Penalty", )
|
167 |
-
chat_counter = gr.Number(value=0, visible=False, precision=0)
|
168 |
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
</ol>
|
183 |
-
<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>
|
184 |
-
</div>
|
185 |
-
""")
|
186 |
-
accept_button = gr.Button("I Agree")
|
187 |
-
|
188 |
-
def enable_inputs():
|
189 |
-
return user_consent_block.update(visible=False), main_block.update(visible=True)
|
190 |
-
|
191 |
-
accept_button.click(None, None, accept_checkbox, _js=js, queue=False)
|
192 |
-
accept_checkbox.change(fn=enable_inputs, inputs=[], outputs=[user_consent_block, main_block], queue=False)
|
193 |
-
|
194 |
-
inputs.submit(reset_textbox, [], [inputs, b1], queue=False)
|
195 |
-
inputs.submit(predict, [inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter, server_status_code, inputs, b1],) #openai_api_key
|
196 |
-
b1.click(reset_textbox, [], [inputs, b1], queue=False)
|
197 |
-
b1.click(predict, [inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter, server_status_code, inputs, b1],) #openai_api_key
|
198 |
-
|
199 |
-
demo.queue(max_size=20, concurrency_count=NUM_THREADS, api_open=False).launch(share=False)
|
|
|
1 |
import gradio as gr
|
2 |
+
import json
|
|
|
|
|
|
|
3 |
|
4 |
+
# Load your validation set
|
5 |
+
#with open('validation_data.json', 'r') as file:
|
6 |
+
# validation_data = json.load(file)
|
|
|
|
|
|
|
|
|
7 |
|
8 |
+
def predict(title, authors, abstract):
|
9 |
+
# Your model prediction logic here
|
10 |
+
score = 0.5 #model_inference(title, authors, abstract) # Replace this with your actual model inference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
|
12 |
+
# Calculate precision for scores >= the predicted score
|
13 |
+
#selected = [d for d in validation_data if d['score'] >= score]
|
14 |
+
#true_positives = sum(1 for d in selected if d['label'] == 1)
|
15 |
+
#precision = true_positives / len(selected) if selected else 0
|
16 |
+
precision = 0.w
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
|
18 |
+
result = f"For papers with a score greater than or equal to {score:.2f}, approximately {precision * 100:.2f}% are selected by AK."
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
|
20 |
+
return {"Score": score, "Result": result}
|
21 |
+
|
22 |
+
iface = gr.Interface(
|
23 |
+
fn=predict,
|
24 |
+
inputs=["text", "text", "text_area"],
|
25 |
+
outputs=["label", "label"],
|
26 |
+
examples=[["WildChat: 1M ChatGPT Interaction Logs in the Wild", "Wenting Zhao, Xiang Ren, Jack Hessel, Claire Cardie, Yejin Choi, Yuntian Deng", "Chatbots such as GPT-4 and ChatGPT are now serving millions of users. Despite their widespread use, there remains a lack of public datasets showcasing how these tools are used by a population of users in practice. To bridge this gap, we offered free access to ChatGPT for online users in exchange for their affirmative, consensual opt-in to anonymously collect their chat transcripts and request headers. From this, we compiled WildChat, a corpus of 1 million user-ChatGPT conversations, which consists of over 2.5 million interaction turns. We compare WildChat with other popular user-chatbot interaction datasets, and find that our dataset offers the most diverse user prompts, contains the largest number of languages, and presents the richest variety of potentially toxic use-cases for researchers to study. In addition to timestamped chat transcripts, we enrich the dataset with demographic data, including state, country, and hashed IP addresses, alongside request headers. This augmentation allows for more detailed analysis of user behaviors across different geographical regions and temporal dimensions. Finally, because it captures a broad range of use cases, we demonstrate the dataset’s potential utility in fine-tuning instruction-following models. WildChat is released at https://wildchat.allen.ai under AI2 ImpACT Licenses."]],
|
27 |
+
title="Will your paper be selected by @_akhaliq?",
|
28 |
+
description="Enter the title, authors, and abstract of the paper to predict its score and see the estimated acceptance rate for similar or higher-scored papers.",
|
29 |
+
live=True
|
30 |
+
)
|
31 |
+
|
32 |
+
iface.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|