clayp commited on
Commit
5520791
·
1 Parent(s): 1139def

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -0
app.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import json
4
+ import requests
5
+
6
+ API_URL = "https://api.openai.com/v1/chat/completions"
7
+
8
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
9
+ hf_token = os.getenv("hf_token")
10
+ private_space_name = "clayp/reaction"
11
+
12
+ def get_system_txt():
13
+ headers = {
14
+ "Authorization": f"Bearer {hf_token}"
15
+ }
16
+ response = requests.get(f"https://huggingface.co/spaces/clayp/reaction-sys/system.txt", headers=headers)
17
+ if response.status_code == 200:
18
+ return response.text.strip()
19
+ else:
20
+ raise Exception("Failed to fetch system.txt from private Gradio space")
21
+
22
+ system_msg = get_system_txt()
23
+
24
+ def check_password(password):
25
+ if password == os.getenv("pw"):
26
+ return True
27
+ else:
28
+ return False
29
+
30
+ def predict(inputs, chat_counter, chatbot=[], history=[]):
31
+ headers = {
32
+ "Content-Type": "application/json",
33
+ "Authorization": f"Bearer {OPENAI_API_KEY}"
34
+ }
35
+
36
+ # Read system message from system.txt
37
+ with open("system.txt", "r") as file:
38
+ system_msg = file.read().strip()
39
+
40
+ top_p = 1.0
41
+ temperature = 0.0
42
+
43
+ messages = [{"role": "system", "content": system_msg},]
44
+ for data in chatbot:
45
+ user = {"role": "user", "content": data[0]}
46
+ assistant = {"role": "assistant", "content": data[1]}
47
+ messages.append(user)
48
+ messages.append(assistant)
49
+ temp = {"role": "user", "content": inputs}
50
+ messages.append(temp)
51
+
52
+ payload = {
53
+ "model": "gpt-4",
54
+ "messages": messages,
55
+ "temperature": temperature,
56
+ "top_p": top_p,
57
+ "n": 1,
58
+ "stream": True,
59
+ "presence_penalty": 0,
60
+ "frequency_penalty": 0,
61
+ }
62
+
63
+ chat_counter += 1
64
+ history.append(inputs)
65
+ response = requests.post(API_URL, headers=headers, json=payload, stream=True)
66
+ token_counter = 0
67
+ partial_words = ""
68
+
69
+ counter = 0
70
+ for chunk in response.iter_lines():
71
+ if counter == 0:
72
+ counter += 1
73
+ continue
74
+ if chunk.decode():
75
+ chunk = chunk.decode()
76
+ if len(chunk) > 12 and "content" in json.loads(chunk[6:])['choices'][0]['delta']:
77
+ partial_words = partial_words + json.loads(chunk[6:])['choices'][0]["delta"]["content"]
78
+ if token_counter == 0:
79
+ history.append(" " + partial_words)
80
+ else:
81
+ history[-1] = partial_words
82
+ chat = [(history[i], history[i + 1]) for i in range(0, len(history) - 1, 2)]
83
+ token_counter += 1
84
+ yield chat, history, chat_counter, response
85
+
86
+ def reset_textbox():
87
+ return gr.update(value='')
88
+
89
+ title = """<h1 align="center">Response simulator</h1>"""
90
+
91
+ with gr.Blocks() as demo:
92
+ gr.HTML(title)
93
+ with gr.Column(elem_id="col_container"):
94
+ password_input = gr.Password(label="Enter password to access the app")
95
+ if check_password(password_input):
96
+ chatbot = gr.Chatbot(label='GPT-4', elem_id="chatbot")
97
+ inputs = gr.Textbox(placeholder="", label="Type an input and press Enter")
98
+ state = gr.State([])
99
+ server_status_code = gr.Textbox(label="Status code from OpenAI server",)
100
+ chat_counter = gr.Number(value=0, visible=False, precision=0)
101
+
102
+ inputs.submit(predict, [inputs, chat_counter, chatbot, state], [chatbot, state, chat_counter, server_status_code],)
103
+ inputs.submit(reset_textbox, [], [inputs])
104
+ else:
105
+ gr.Text("Incorrect password. Please try again.")
106
+
107
+ demo.launch()