awacke1 commited on
Commit
0dc382c
ยท
1 Parent(s): 56ad7af

Create backupapp.py

Browse files
Files changed (1) hide show
  1. backupapp.py +131 -0
backupapp.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ payload = {
49
+ "model": "gpt-3.5-turbo",
50
+ "messages": messages, #[{"role": "user", "content": f"{inputs}"}],
51
+ "temperature" : temperature, #1.0,
52
+ "top_p": top_p, #1.0,
53
+ "n" : 1,
54
+ "stream": True,
55
+ "presence_penalty":0,
56
+ "frequency_penalty":0,
57
+ }
58
+ chat_counter+=1
59
+
60
+ # 4. POST it to OPENAI API
61
+ history.append(inputs)
62
+ print(f"payload is - {payload}")
63
+ response = requests.post(API_URL, headers=headers, json=payload, stream=True)
64
+ token_counter = 0
65
+ partial_words = ""
66
+
67
+ # 5. Iterate through response lines and structure readable response
68
+ counter=0
69
+ for chunk in response.iter_lines():
70
+ if counter == 0:
71
+ counter+=1
72
+ continue
73
+ if chunk.decode() :
74
+ chunk = chunk.decode()
75
+ if len(chunk) > 12 and "content" in json.loads(chunk[6:])['choices'][0]['delta']:
76
+ partial_words = partial_words + json.loads(chunk[6:])['choices'][0]["delta"]["content"]
77
+ if token_counter == 0:
78
+ history.append(" " + partial_words)
79
+ else:
80
+ history[-1] = partial_words
81
+ chat = [(history[i], history[i + 1]) for i in range(0, len(history) - 1, 2) ] # convert to tuples of list
82
+ token_counter+=1
83
+ yield chat, history, chat_counter
84
+
85
+
86
+ def reset_textbox():
87
+ return gr.update(value='')
88
+
89
+ title = """<h1 align="center">Memory Chat Story Generator ChatGPT</h1>"""
90
+ description = """
91
+ ## ChatGPT Datasets ๐Ÿ“š
92
+ - WebText
93
+ - Common Crawl
94
+ - BooksCorpus
95
+ - English Wikipedia
96
+ - Toronto Books Corpus
97
+ - OpenWebText
98
+ ## ChatGPT Datasets - Details ๐Ÿ“š
99
+ - **WebText:** A dataset of web pages crawled from domains on the Alexa top 5,000 list. This dataset was used to pretrain GPT-2.
100
+ - [WebText: A Large-Scale Unsupervised Text Corpus by Radford et al.](https://paperswithcode.com/dataset/webtext)
101
+ - **Common Crawl:** A dataset of web pages from a variety of domains, which is updated regularly. This dataset was used to pretrain GPT-3.
102
+ - [Language Models are Few-Shot Learners](https://paperswithcode.com/dataset/common-crawl) by Brown et al.
103
+ - **BooksCorpus:** A dataset of over 11,000 books from a variety of genres.
104
+ - [Scalable Methods for 8 Billion Token Language Modeling](https://paperswithcode.com/dataset/bookcorpus) by Zhu et al.
105
+ - **English Wikipedia:** A dump of the English-language Wikipedia as of 2018, with articles from 2001-2017.
106
+ - [Improving Language Understanding by Generative Pre-Training](https://huggingface.co/spaces/awacke1/WikipediaUltimateAISearch?logs=build) Space for Wikipedia Search
107
+ - **Toronto Books Corpus:** A dataset of over 7,000 books from a variety of genres, collected by the University of Toronto.
108
+ - [Massively Multilingual Sentence Embeddings for Zero-Shot Cross-Lingual Transfer and Beyond](https://paperswithcode.com/dataset/bookcorpus) by Schwenk and Douze.
109
+ - **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.
110
+ - [Language Models are Few-Shot Learners](https://paperswithcode.com/dataset/openwebtext) by Brown et al.
111
+ """
112
+
113
+ # 6. Use Gradio to pull it all together
114
+ with gr.Blocks(css = """#col_container {width: 1000px; margin-left: auto; margin-right: auto;} #chatbot {height: 520px; overflow: auto;}""") as demo:
115
+ gr.HTML(title)
116
+ with gr.Column(elem_id = "col_container"):
117
+ inputs = gr.Textbox(placeholder= "Hi there!", label= "Type an input and press Enter")
118
+ chatbot = gr.Chatbot(elem_id='chatbot')
119
+ state = gr.State([])
120
+ b1 = gr.Button()
121
+ with gr.Accordion("Parameters", open=False):
122
+ top_p = gr.Slider( minimum=-0, maximum=1.0, value=1.0, step=0.05, interactive=True, label="Top-p (nucleus sampling)",)
123
+ temperature = gr.Slider( minimum=-0, maximum=5.0, value=1.0, step=0.1, interactive=True, label="Temperature",)
124
+ chat_counter = gr.Number(value=0, visible=False, precision=0)
125
+
126
+ inputs.submit(predict, [inputs, top_p, temperature,chat_counter, chatbot, state], [chatbot, state, chat_counter])
127
+ b1.click(predict, [inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter])
128
+ b1.click(reset_textbox, [], [inputs])
129
+ inputs.submit(reset_textbox, [], [inputs])
130
+ gr.Markdown(description)
131
+ demo.queue().launch(debug=True)