keneonyeachonam commited on
Commit
d2cea93
·
1 Parent(s): ec270ef

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +151 -0
app.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import json
4
+ import requests
5
+
6
+ #Streaming endpoint
7
+ API_URL = "https://api.openai.com/v1/chat/completions" #os.getenv("API_URL") + "/generate_stream"
8
+ OPENAI_API_KEY= os.environ["HF_TOKEN"] # Add a token to this space . Then copy it to the repository secret in this spaces settings panel. os.environ reads from there.
9
+ # Keys for Open AI ChatGPT API usage are created from here: https://platform.openai.com/account/api-keys
10
+
11
+ def predict(inputs, top_p, temperature, chat_counter, chatbot=[], history=[]): #repetition_penalty, top_k
12
+
13
+ # 1. Set up a payload
14
+ payload = {
15
+ "model": "gpt-3.5-turbo",
16
+ "messages": [{"role": "user", "content": f"{inputs}"}],
17
+ "temperature" : 1.0,
18
+ "top_p":1.0,
19
+ "n" : 1,
20
+ "stream": True,
21
+ "presence_penalty":0,
22
+ "frequency_penalty":0,
23
+ }
24
+
25
+ # 2. Define your headers and add a key from https://platform.openai.com/account/api-keys
26
+ headers = {
27
+ "Content-Type": "application/json",
28
+ "Authorization": f"Bearer {OPENAI_API_KEY}"
29
+ }
30
+
31
+ # 3. Create a chat counter loop that feeds [Predict next best anything based on last input and attention with memory defined by introspective attention over time]
32
+ print(f"chat_counter - {chat_counter}")
33
+ if chat_counter != 0 :
34
+ messages=[]
35
+ for data in chatbot:
36
+ temp1 = {}
37
+ temp1["role"] = "user"
38
+ temp1["content"] = data[0]
39
+ temp2 = {}
40
+ temp2["role"] = "assistant"
41
+ temp2["content"] = data[1]
42
+ messages.append(temp1)
43
+ messages.append(temp2)
44
+ temp3 = {}
45
+ temp3["role"] = "user"
46
+ temp3["content"] = inputs
47
+ messages.append(temp3)
48
+ #messages
49
+ payload = {
50
+ "model": "gpt-3.5-turbo",
51
+ "messages": messages, #[{"role": "user", "content": f"{inputs}"}],
52
+ "temperature" : temperature, #1.0,
53
+ "top_p": top_p, #1.0,
54
+ "n" : 1,
55
+ "stream": True,
56
+ "presence_penalty":0,
57
+ "frequency_penalty":0,
58
+ }
59
+ chat_counter+=1
60
+
61
+ # 4. POST it to OPENAI API
62
+ history.append(inputs)
63
+ print(f"payload is - {payload}")
64
+ # make a POST request to the API endpoint using the requests.post method, passing in stream=True
65
+ response = requests.post(API_URL, headers=headers, json=payload, stream=True)
66
+ #response = requests.post(API_URL, headers=headers, json=payload, stream=True)
67
+ token_counter = 0
68
+ partial_words = ""
69
+
70
+ # 5. Iterate through response lines and structure readable response
71
+ # TODO - make this parse out markdown so we can have similar interface
72
+ counter=0
73
+ for chunk in response.iter_lines():
74
+ #Skipping first chunk
75
+ if counter == 0:
76
+ counter+=1
77
+ continue
78
+ #counter+=1
79
+ # check whether each line is non-empty
80
+ if chunk.decode() :
81
+ chunk = chunk.decode()
82
+ # decode each line as response data is in bytes
83
+ if len(chunk) > 12 and "content" in json.loads(chunk[6:])['choices'][0]['delta']:
84
+ #if len(json.loads(chunk.decode()[6:])['choices'][0]["delta"]) == 0:
85
+ # break
86
+ partial_words = partial_words + json.loads(chunk[6:])['choices'][0]["delta"]["content"]
87
+ if token_counter == 0:
88
+ history.append(" " + partial_words)
89
+ else:
90
+ history[-1] = partial_words
91
+ chat = [(history[i], history[i + 1]) for i in range(0, len(history) - 1, 2) ] # convert to tuples of list
92
+ token_counter+=1
93
+ yield chat, history, chat_counter # resembles {chatbot: chat, state: history}
94
+
95
+
96
+ def reset_textbox():
97
+ return gr.update(value='')
98
+
99
+ title = """<h1 align="center">Memory Chat Story Generator ChatGPT</h1>"""
100
+ description = """
101
+
102
+ ## ChatGPT Datasets 📚
103
+ - WebText
104
+ - Common Crawl
105
+ - BooksCorpus
106
+ - English Wikipedia
107
+ - Toronto Books Corpus
108
+ - OpenWebText
109
+
110
+ ## ChatGPT Datasets - Details 📚
111
+ - **WebText:** A dataset of web pages crawled from domains on the Alexa top 5,000 list. This dataset was used to pretrain GPT-2.
112
+ - [WebText: A Large-Scale Unsupervised Text Corpus by Radford et al.](https://paperswithcode.com/dataset/webtext)
113
+ - **Common Crawl:** A dataset of web pages from a variety of domains, which is updated regularly. This dataset was used to pretrain GPT-3.
114
+ - [Language Models are Few-Shot Learners](https://paperswithcode.com/dataset/common-crawl) by Brown et al.
115
+ - **BooksCorpus:** A dataset of over 11,000 books from a variety of genres.
116
+ - [Scalable Methods for 8 Billion Token Language Modeling](https://paperswithcode.com/dataset/bookcorpus) by Zhu et al.
117
+ - **English Wikipedia:** A dump of the English-language Wikipedia as of 2018, with articles from 2001-2017.
118
+ - [Improving Language Understanding by Generative Pre-Training](https://huggingface.co/spaces/awacke1/WikipediaUltimateAISearch?logs=build) Space for Wikipedia Search
119
+ - **Toronto Books Corpus:** A dataset of over 7,000 books from a variety of genres, collected by the University of Toronto.
120
+ - [Massively Multilingual Sentence Embeddings for Zero-Shot Cross-Lingual Transfer and Beyond](https://paperswithcode.com/dataset/bookcorpus) by Schwenk and Douze.
121
+ - **OpenWebText:** A dataset of web pages that were filtered to remove content that was likely to be low-quality or spammy. This dataset was used to pretrain GPT-3.
122
+ - [Language Models are Few-Shot Learners](https://paperswithcode.com/dataset/openwebtext) by Brown et al.
123
+
124
+ """
125
+
126
+ # 6. Use Gradio to pull it all together
127
+ with gr.Blocks(css = """#col_container {width: 1000px; margin-left: auto; margin-right: auto;}
128
+ #chatbot {height: 520px; overflow: auto;}""") as demo:
129
+
130
+
131
+ gr.HTML(title)
132
+
133
+
134
+ with gr.Column(elem_id = "col_container"):
135
+ chatbot = gr.Chatbot(elem_id='chatbot') #c
136
+ inputs = gr.Textbox(placeholder= "Hi there!", label= "Type an input and press Enter") #t
137
+ state = gr.State([]) #s
138
+ b1 = gr.Button()
139
+
140
+ with gr.Accordion("Parameters", open=False):
141
+ top_p = gr.Slider( minimum=-0, maximum=1.0, value=1.0, step=0.05, interactive=True, label="Top-p (nucleus sampling)",)
142
+ temperature = gr.Slider( minimum=-0, maximum=5.0, value=1.0, step=0.1, interactive=True, label="Temperature",)
143
+ chat_counter = gr.Number(value=0, visible=False, precision=0)
144
+
145
+ inputs.submit( predict, [inputs, top_p, temperature,chat_counter, chatbot, state], [chatbot, state, chat_counter],)
146
+ b1.click( predict, [inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter],)
147
+ b1.click(reset_textbox, [], [inputs])
148
+ inputs.submit(reset_textbox, [], [inputs])
149
+
150
+ gr.Markdown(description)
151
+ demo.queue().launch(debug=True)