awacke1 commited on
Commit
d8b9f2a
·
1 Parent(s): c5fdec2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +169 -37
app.py CHANGED
@@ -3,11 +3,63 @@ 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
@@ -91,51 +143,127 @@ def predict(inputs, top_p, temperature, chat_counter, chatbot=[], history=[]):
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)",)
@@ -143,9 +271,13 @@ with gr.Blocks(css = """#col_container {width: 1000px; margin-left: auto; margin
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)
 
3
  import json
4
  import requests
5
 
6
+
7
+ #Chatbot2
8
+ from transformers import BlenderbotTokenizer, BlenderbotForConditionalGeneration
9
+ import torch
10
+ from datasets import load_dataset
11
+ # PersistDataset -----
12
+ import os
13
+ import csv
14
+ from gradio import inputs, outputs
15
+ import huggingface_hub
16
+ from huggingface_hub import Repository, hf_hub_download, upload_file
17
+ from datetime import datetime
18
+ import fastapi
19
+ from typing import List, Dict
20
+ import httpx
21
+ import pandas as pd
22
+ import datasets as ds
23
+
24
+ #Chatbot2 constants
25
+ title = """<h1 align="center">💬ChatGPT ChatBack🧠💾</h1>"""
26
+ #description = """Chatbot With persistent memory dataset allowing multiagent system AI to access a shared dataset as memory pool with stored interactions. """
27
+ UseMemory=True
28
+ HF_TOKEN=os.environ.get("HF_TOKEN")
29
+
30
+ #ChatGPT info
31
  API_URL = "https://api.openai.com/v1/chat/completions" #os.getenv("API_URL") + "/generate_stream"
32
  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.
33
  # Keys for Open AI ChatGPT API usage are created from here: https://platform.openai.com/account/api-keys
34
+ description = """
35
+
36
+ Chatbot With persistent memory dataset allowing multiagent system AI to access a shared dataset as memory pool with stored interactions.
37
+
38
+
39
+ ## ChatGPT Datasets 📚
40
+ - WebText
41
+ - Common Crawl
42
+ - BooksCorpus
43
+ - English Wikipedia
44
+ - Toronto Books Corpus
45
+ - OpenWebText
46
+
47
+ ## ChatGPT Datasets - Details 📚
48
+ - **WebText:** A dataset of web pages crawled from domains on the Alexa top 5,000 list. This dataset was used to pretrain GPT-2.
49
+ - [WebText: A Large-Scale Unsupervised Text Corpus by Radford et al.](https://paperswithcode.com/dataset/webtext)
50
+ - **Common Crawl:** A dataset of web pages from a variety of domains, which is updated regularly. This dataset was used to pretrain GPT-3.
51
+ - [Language Models are Few-Shot Learners](https://paperswithcode.com/dataset/common-crawl) by Brown et al.
52
+ - **BooksCorpus:** A dataset of over 11,000 books from a variety of genres.
53
+ - [Scalable Methods for 8 Billion Token Language Modeling](https://paperswithcode.com/dataset/bookcorpus) by Zhu et al.
54
+ - **English Wikipedia:** A dump of the English-language Wikipedia as of 2018, with articles from 2001-2017.
55
+ - [Improving Language Understanding by Generative Pre-Training](https://huggingface.co/spaces/awacke1/WikipediaUltimateAISearch?logs=build) Space for Wikipedia Search
56
+ - **Toronto Books Corpus:** A dataset of over 7,000 books from a variety of genres, collected by the University of Toronto.
57
+ - [Massively Multilingual Sentence Embeddings for Zero-Shot Cross-Lingual Transfer and Beyond](https://paperswithcode.com/dataset/bookcorpus) by Schwenk and Douze.
58
+ - **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.
59
+ - [Language Models are Few-Shot Learners](https://paperswithcode.com/dataset/openwebtext) by Brown et al.
60
+ """
61
 
62
+ #ChatGPT predict
63
  def predict(inputs, top_p, temperature, chat_counter, chatbot=[], history=[]): #repetition_penalty, top_k
64
 
65
  # 1. Set up a payload
 
143
  chat = [(history[i], history[i + 1]) for i in range(0, len(history) - 1, 2) ] # convert to tuples of list
144
  token_counter+=1
145
  yield chat, history, chat_counter # resembles {chatbot: chat, state: history}
 
146
 
147
+ def take_last_tokens(inputs, note_history, history):
148
+ if inputs['input_ids'].shape[1] > 128:
149
+ inputs['input_ids'] = torch.tensor([inputs['input_ids'][0][-128:].tolist()])
150
+ inputs['attention_mask'] = torch.tensor([inputs['attention_mask'][0][-128:].tolist()])
151
+ note_history = ['</s> <s>'.join(note_history[0].split('</s> <s>')[2:])]
152
+ history = history[1:]
153
+ return inputs, note_history, history
154
+
155
+ def add_note_to_history(note, note_history):# good example of non async since we wait around til we know it went okay.
156
+ note_history.append(note)
157
+ note_history = '</s> <s>'.join(note_history)
158
+ return [note_history]
159
+
160
+ # ChatGPT clear
161
  def reset_textbox():
162
  return gr.update(value='')
163
 
164
+ #Chatbot2 Save Results
165
+ def SaveResult(text, outputfileName):
166
+ basedir = os.path.dirname(__file__)
167
+ savePath = outputfileName
168
+ print("Saving: " + text + " to " + savePath)
169
+ from os.path import exists
170
+ file_exists = exists(savePath)
171
+ if file_exists:
172
+ with open(outputfileName, "a") as f: #append
173
+ f.write(str(text.replace("\n"," ")))
174
+ f.write('\n')
175
+ else:
176
+ with open(outputfileName, "w") as f: #write
177
+ f.write(str("time, message, text\n")) # one time only to get column headers for CSV file
178
+ f.write(str(text.replace("\n"," ")))
179
+ f.write('\n')
180
+ return
181
 
182
+ #Chatbot2 Store Message
183
+ def store_message(name: str, message: str, outputfileName: str):
184
+ basedir = os.path.dirname(__file__)
185
+ savePath = outputfileName
186
+
187
+ # if file doesnt exist, create it with labels
188
+ from os.path import exists
189
+ file_exists = exists(savePath)
190
+
191
+ if (file_exists==False):
192
+ with open(savePath, "w") as f: #write
193
+ f.write(str("time, message, text\n")) # one time only to get column headers for CSV file
194
+ if name and message:
195
+ writer = csv.DictWriter(f, fieldnames=["time", "message", "name"])
196
+ writer.writerow(
197
+ {"time": str(datetime.now()), "message": message.strip(), "name": name.strip() }
198
+ )
199
+ df = pd.read_csv(savePath)
200
+ df = df.sort_values(df.columns[0],ascending=False)
201
+ else:
202
+ if name and message:
203
+ with open(savePath, "a") as csvfile:
204
+ writer = csv.DictWriter(csvfile, fieldnames=[ "time", "message", "name", ])
205
+ writer.writerow(
206
+ {"time": str(datetime.now()), "message": message.strip(), "name": name.strip() }
207
+ )
208
+ df = pd.read_csv(savePath)
209
+ df = df.sort_values(df.columns[0],ascending=False)
210
+ return df
211
 
212
+ #Chatbot2 get base directory of saves
213
+ def get_base(filename):
214
+ basedir = os.path.dirname(__file__)
215
+ print(basedir)
216
+ loadPath = basedir + filename
217
+ print(loadPath)
218
+ return loadPath
 
 
 
 
 
 
 
 
219
 
220
+ #Chatbot2 - History
221
+ def chat(message, history):
222
+ history = history or []
223
+ if history:
224
+ history_useful = ['</s> <s>'.join([str(a[0])+'</s> <s>'+str(a[1]) for a in history])]
225
+ else:
226
+ history_useful = []
227
+ history_useful = add_note_to_history(message, history_useful)
228
+ inputs = tokenizer(history_useful, return_tensors="pt")
229
+ inputs, history_useful, history = take_last_tokens(inputs, history_useful, history)
230
+ reply_ids = model.generate(**inputs)
231
+ response = tokenizer.batch_decode(reply_ids, skip_special_tokens=True)[0]
232
+ history_useful = add_note_to_history(response, history_useful)
233
+ list_history = history_useful[0].split('</s> <s>')
234
+ history.append((list_history[-2], list_history[-1]))
235
+ df=pd.DataFrame()
236
+ if UseMemory:
237
+ outputfileName = 'ChatbotMemory3.csv' # Test first time file create
238
+ df = store_message(message, response, outputfileName) # Save to dataset
239
+ basedir = get_base(outputfileName)
240
+ return history, df, basedir
241
 
242
+
243
+ # 6. Use Gradio to pull it all together
244
+ with gr.Blocks(css = """#col_container {width: 1000px; margin-left: auto; margin-right: auto;} #chatbot {height: 520px; overflow: auto;}""") as demo:
245
+
246
  gr.HTML(title)
247
 
248
+ # Chat bot memory - dataframe
249
+ gr.Markdown("<h1><center>🍰Gradio chatbot backed by dataframe CSV memory🎨</center></h1>")
250
+ with gr.Row():
251
+ t1 = gr.Textbox(lines=1, default="", label="Chat Text:")
252
+ b1 = gr.Button("🍰 Respond and Retrieve Messages")
253
+ with gr.Row(): # inputs and buttons
254
+ s1 = gr.State([])
255
+ df1 = gr.Dataframe(wrap=True, max_rows=1000, overflow_row_behaviour= "paginate")
256
+ with gr.Row(): # inputs and buttons
257
+ file = gr.File(label="File")
258
+ s2 = gr.Markdown()
259
+ b1.click(fn=chat, inputs=[t1, s1], outputs=[s1, df1, file])
260
+
261
 
262
  with gr.Column(elem_id = "col_container"):
263
+ chatbot = gr.Chatbot(elem_id='chatbot')
264
+ inputs = gr.Textbox(placeholder= "There is only one real true reward in life and this is existence or nonexistence. Everything else is a corollary.", label= "Type an input and press Enter") #t
265
+ state = gr.State([])
266
+ gpt = gr.Button()
267
 
268
  with gr.Accordion("Parameters", open=False):
269
  top_p = gr.Slider( minimum=-0, maximum=1.0, value=1.0, step=0.05, interactive=True, label="Top-p (nucleus sampling)",)
 
271
  chat_counter = gr.Number(value=0, visible=False, precision=0)
272
 
273
  inputs.submit( predict, [inputs, top_p, temperature,chat_counter, chatbot, state], [chatbot, state, chat_counter],)
 
 
 
274
 
275
+ gpt.click(predict, [inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter],)
276
+ gpt.click(reset_textbox, [], [inputs])
277
+ inputs.submit(reset_textbox, [], [inputs])
278
+
279
+ # Show ChatGPT Datasets information
280
  gr.Markdown(description)
281
+
282
+ # Kickoff
283
  demo.queue().launch(debug=True)