Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -3,143 +3,11 @@ import os
|
|
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, 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 |
-
|
29 |
-
#ChatGPT info
|
30 |
API_URL = "https://api.openai.com/v1/chat/completions" #os.getenv("API_URL") + "/generate_stream"
|
31 |
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.
|
32 |
# Keys for Open AI ChatGPT API usage are created from here: https://platform.openai.com/account/api-keys
|
33 |
-
description = """
|
34 |
-
|
35 |
-
Chatbot With persistent memory dataset allowing multiagent system AI to access a shared dataset as memory pool with stored interactions.
|
36 |
-
|
37 |
-
|
38 |
-
## ChatGPT Datasets 📚
|
39 |
-
- WebText
|
40 |
-
- Common Crawl
|
41 |
-
- BooksCorpus
|
42 |
-
- English Wikipedia
|
43 |
-
- Toronto Books Corpus
|
44 |
-
- OpenWebText
|
45 |
-
|
46 |
-
## ChatGPT Datasets - Details 📚
|
47 |
-
- **WebText:** A dataset of web pages crawled from domains on the Alexa top 5,000 list. This dataset was used to pretrain GPT-2.
|
48 |
-
- [WebText: A Large-Scale Unsupervised Text Corpus by Radford et al.](https://paperswithcode.com/dataset/webtext)
|
49 |
-
- **Common Crawl:** A dataset of web pages from a variety of domains, which is updated regularly. This dataset was used to pretrain GPT-3.
|
50 |
-
- [Language Models are Few-Shot Learners](https://paperswithcode.com/dataset/common-crawl) by Brown et al.
|
51 |
-
- **BooksCorpus:** A dataset of over 11,000 books from a variety of genres.
|
52 |
-
- [Scalable Methods for 8 Billion Token Language Modeling](https://paperswithcode.com/dataset/bookcorpus) by Zhu et al.
|
53 |
-
- **English Wikipedia:** A dump of the English-language Wikipedia as of 2018, with articles from 2001-2017.
|
54 |
-
- [Improving Language Understanding by Generative Pre-Training](https://huggingface.co/spaces/awacke1/WikipediaUltimateAISearch?logs=build) Space for Wikipedia Search
|
55 |
-
- **Toronto Books Corpus:** A dataset of over 7,000 books from a variety of genres, collected by the University of Toronto.
|
56 |
-
- [Massively Multilingual Sentence Embeddings for Zero-Shot Cross-Lingual Transfer and Beyond](https://paperswithcode.com/dataset/bookcorpus) by Schwenk and Douze.
|
57 |
-
- **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.
|
58 |
-
- [Language Models are Few-Shot Learners](https://paperswithcode.com/dataset/openwebtext) by Brown et al.
|
59 |
-
"""
|
60 |
-
|
61 |
|
62 |
-
#Chatbot2 Save Results
|
63 |
-
def SaveResult(text, outputfileName):
|
64 |
-
basedir = os.path.dirname(__file__)
|
65 |
-
savePath = outputfileName
|
66 |
-
print("Saving: " + text + " to " + savePath)
|
67 |
-
from os.path import exists
|
68 |
-
file_exists = exists(savePath)
|
69 |
-
if file_exists:
|
70 |
-
with open(outputfileName, "a") as f: #append
|
71 |
-
f.write(str(text.replace("\n"," ")))
|
72 |
-
f.write('\n')
|
73 |
-
else:
|
74 |
-
with open(outputfileName, "w") as f: #write
|
75 |
-
f.write(str("time, message, text\n")) # one time only to get column headers for CSV file
|
76 |
-
f.write(str(text.replace("\n"," ")))
|
77 |
-
f.write('\n')
|
78 |
-
return
|
79 |
-
|
80 |
-
#Chatbot2 Store Message
|
81 |
-
def store_message(name: str, message: str, outputfileName: str):
|
82 |
-
basedir = os.path.dirname(__file__)
|
83 |
-
savePath = outputfileName
|
84 |
-
|
85 |
-
# if file doesnt exist, create it with labels
|
86 |
-
from os.path import exists
|
87 |
-
file_exists = exists(savePath)
|
88 |
-
|
89 |
-
if (file_exists==False):
|
90 |
-
with open(savePath, "w") as f: #write
|
91 |
-
f.write(str("time, message, text\n")) # one time only to get column headers for CSV file
|
92 |
-
if name and message:
|
93 |
-
writer = csv.DictWriter(f, fieldnames=["time", "message", "name"])
|
94 |
-
writer.writerow(
|
95 |
-
{"time": str(datetime.now()), "message": message.strip(), "name": name.strip() }
|
96 |
-
)
|
97 |
-
df = pd.read_csv(savePath)
|
98 |
-
df = df.sort_values(df.columns[0],ascending=False)
|
99 |
-
else:
|
100 |
-
if name and message:
|
101 |
-
with open(savePath, "a") as csvfile:
|
102 |
-
writer = csv.DictWriter(csvfile, fieldnames=[ "time", "message", "name", ])
|
103 |
-
writer.writerow(
|
104 |
-
{"time": str(datetime.now()), "message": message.strip(), "name": name.strip() }
|
105 |
-
)
|
106 |
-
df = pd.read_csv(savePath)
|
107 |
-
df = df.sort_values(df.columns[0],ascending=False)
|
108 |
-
return df
|
109 |
-
|
110 |
-
#Chatbot2 get base directory of saves
|
111 |
-
def get_base(filename):
|
112 |
-
basedir = os.path.dirname(__file__)
|
113 |
-
print(basedir)
|
114 |
-
loadPath = basedir + filename
|
115 |
-
print(loadPath)
|
116 |
-
return loadPath
|
117 |
-
|
118 |
-
#Chatbot2 - History
|
119 |
-
def chat(message, history):
|
120 |
-
history = history or []
|
121 |
-
if history:
|
122 |
-
history_useful = ['</s> <s>'.join([str(a[0])+'</s> <s>'+str(a[1]) for a in history])]
|
123 |
-
else:
|
124 |
-
history_useful = []
|
125 |
-
history_useful = add_note_to_history(message, history_useful)
|
126 |
-
inputs = tokenizer(history_useful, return_tensors="pt")
|
127 |
-
inputs, history_useful, history = take_last_tokens(inputs, history_useful, history)
|
128 |
-
reply_ids = model.generate(**inputs)
|
129 |
-
response = tokenizer.batch_decode(reply_ids, skip_special_tokens=True)[0]
|
130 |
-
history_useful = add_note_to_history(response, history_useful)
|
131 |
-
list_history = history_useful[0].split('</s> <s>')
|
132 |
-
history.append((list_history[-2], list_history[-1]))
|
133 |
-
df=pd.DataFrame()
|
134 |
-
if UseMemory:
|
135 |
-
outputfileName = 'ChatbotMemory3.csv' # Test first time file create
|
136 |
-
df = store_message(message, response, outputfileName) # Save to dataset
|
137 |
-
basedir = get_base(outputfileName)
|
138 |
-
return history, df, basedir
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
#ChatGPT predict
|
143 |
def predict(inputs, top_p, temperature, chat_counter, chatbot=[], history=[]): #repetition_penalty, top_k
|
144 |
|
145 |
# 1. Set up a payload
|
@@ -203,17 +71,18 @@ def predict(inputs, top_p, temperature, chat_counter, chatbot=[], history=[]):
|
|
203 |
# TODO - make this parse out markdown so we can have similar interface
|
204 |
counter=0
|
205 |
for chunk in response.iter_lines():
|
206 |
-
|
207 |
if counter == 0:
|
208 |
counter+=1
|
209 |
continue
|
210 |
-
|
|
|
211 |
if chunk.decode() :
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
partial_words = partial_words + json.loads(chunk[6:])['choices'][0]["delta"]["content"]
|
218 |
if token_counter == 0:
|
219 |
history.append(" " + partial_words)
|
@@ -221,61 +90,50 @@ def predict(inputs, top_p, temperature, chat_counter, chatbot=[], history=[]):
|
|
221 |
history[-1] = partial_words
|
222 |
chat = [(history[i], history[i + 1]) for i in range(0, len(history) - 1, 2) ] # convert to tuples of list
|
223 |
token_counter+=1
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
df=pd.DataFrame()
|
228 |
-
if UseMemory:
|
229 |
-
outputfileName = 'ChatGPT-RLHF-Memory.csv' # Test first time file create
|
230 |
-
df = store_message(chat, history, outputfileName) # Save to dataset
|
231 |
-
basedir = get_base(outputfileName)
|
232 |
-
#return history, df, basedir
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
yield chat, history, chat_counter # resembles {chatbot: chat, state: history}
|
|
|
237 |
|
238 |
-
def take_last_tokens(inputs, note_history, history):
|
239 |
-
if inputs['input_ids'].shape[1] > 128:
|
240 |
-
inputs['input_ids'] = torch.tensor([inputs['input_ids'][0][-128:].tolist()])
|
241 |
-
inputs['attention_mask'] = torch.tensor([inputs['attention_mask'][0][-128:].tolist()])
|
242 |
-
note_history = ['</s> <s>'.join(note_history[0].split('</s> <s>')[2:])]
|
243 |
-
history = history[1:]
|
244 |
-
return inputs, note_history, history
|
245 |
-
|
246 |
-
def add_note_to_history(note, note_history):# good example of non async since we wait around til we know it went okay.
|
247 |
-
note_history.append(note)
|
248 |
-
note_history = '</s> <s>'.join(note_history)
|
249 |
-
return [note_history]
|
250 |
-
|
251 |
-
# ChatGPT clear
|
252 |
def reset_textbox():
|
253 |
return gr.update(value='')
|
254 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
255 |
# 6. Use Gradio to pull it all together
|
256 |
-
with gr.Blocks(css = """#col_container {width: 1000px; margin-left: auto; margin-right: auto;}
|
257 |
-
|
258 |
-
gr.HTML(title)
|
259 |
|
260 |
-
|
261 |
-
gr.
|
262 |
-
with gr.Row():
|
263 |
-
t1 = gr.Textbox(lines=1, default="", label="Chat Text:")
|
264 |
-
b1 = gr.Button("🍰 Respond and Retrieve Messages")
|
265 |
-
with gr.Row(): # inputs and buttons
|
266 |
-
s1 = gr.State([])
|
267 |
-
df1 = gr.Dataframe(wrap=True, max_rows=1000, overflow_row_behaviour= "paginate")
|
268 |
-
with gr.Row(): # inputs and buttons
|
269 |
-
file = gr.File(label="File")
|
270 |
-
s2 = gr.Markdown()
|
271 |
-
#b1.click(fn=chat, inputs=[t1, s1], outputs=[s1, df1, file])
|
272 |
|
273 |
|
274 |
with gr.Column(elem_id = "col_container"):
|
275 |
-
chatbot = gr.Chatbot(elem_id='chatbot')
|
276 |
-
inputs = gr.Textbox(placeholder= "
|
277 |
-
state = gr.State([])
|
278 |
-
|
279 |
|
280 |
with gr.Accordion("Parameters", open=False):
|
281 |
top_p = gr.Slider( minimum=-0, maximum=1.0, value=1.0, step=0.05, interactive=True, label="Top-p (nucleus sampling)",)
|
@@ -283,13 +141,9 @@ with gr.Blocks(css = """#col_container {width: 1000px; margin-left: auto; margin
|
|
283 |
chat_counter = gr.Number(value=0, visible=False, precision=0)
|
284 |
|
285 |
inputs.submit( predict, [inputs, top_p, temperature,chat_counter, chatbot, state], [chatbot, state, chat_counter],)
|
286 |
-
|
287 |
-
|
288 |
-
gpt.click(reset_textbox, [], [inputs])
|
289 |
inputs.submit(reset_textbox, [], [inputs])
|
290 |
-
|
291 |
-
# Show ChatGPT Datasets information
|
292 |
gr.Markdown(description)
|
293 |
-
|
294 |
-
# Kickoff
|
295 |
demo.queue().launch(debug=True)
|
|
|
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
|
|
|
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)
|
|
|
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 |
+
## ChatGPT Datasets 📚
|
102 |
+
- WebText
|
103 |
+
- Common Crawl
|
104 |
+
- BooksCorpus
|
105 |
+
- English Wikipedia
|
106 |
+
- Toronto Books Corpus
|
107 |
+
- OpenWebText
|
108 |
+
## ChatGPT Datasets - Details 📚
|
109 |
+
- **WebText:** A dataset of web pages crawled from domains on the Alexa top 5,000 list. This dataset was used to pretrain GPT-2.
|
110 |
+
- [WebText: A Large-Scale Unsupervised Text Corpus by Radford et al.](https://paperswithcode.com/dataset/webtext)
|
111 |
+
- **Common Crawl:** A dataset of web pages from a variety of domains, which is updated regularly. This dataset was used to pretrain GPT-3.
|
112 |
+
- [Language Models are Few-Shot Learners](https://paperswithcode.com/dataset/common-crawl) by Brown et al.
|
113 |
+
- **BooksCorpus:** A dataset of over 11,000 books from a variety of genres.
|
114 |
+
- [Scalable Methods for 8 Billion Token Language Modeling](https://paperswithcode.com/dataset/bookcorpus) by Zhu et al.
|
115 |
+
- **English Wikipedia:** A dump of the English-language Wikipedia as of 2018, with articles from 2001-2017.
|
116 |
+
- [Improving Language Understanding by Generative Pre-Training](https://huggingface.co/spaces/awacke1/WikipediaUltimateAISearch?logs=build) Space for Wikipedia Search
|
117 |
+
- **Toronto Books Corpus:** A dataset of over 7,000 books from a variety of genres, collected by the University of Toronto.
|
118 |
+
- [Massively Multilingual Sentence Embeddings for Zero-Shot Cross-Lingual Transfer and Beyond](https://paperswithcode.com/dataset/bookcorpus) by Schwenk and Douze.
|
119 |
+
- **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.
|
120 |
+
- [Language Models are Few-Shot Learners](https://paperswithcode.com/dataset/openwebtext) by Brown et al.
|
121 |
+
|
122 |
+
"""
|
123 |
+
|
124 |
# 6. Use Gradio to pull it all together
|
125 |
+
with gr.Blocks(css = """#col_container {width: 1000px; margin-left: auto; margin-right: auto;}
|
126 |
+
#chatbot {height: 520px; overflow: auto;}""") as demo:
|
|
|
127 |
|
128 |
+
|
129 |
+
gr.HTML(title)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
130 |
|
131 |
|
132 |
with gr.Column(elem_id = "col_container"):
|
133 |
+
chatbot = gr.Chatbot(elem_id='chatbot') #c
|
134 |
+
inputs = gr.Textbox(placeholder= "Hi there!", label= "Type an input and press Enter") #t
|
135 |
+
state = gr.State([]) #s
|
136 |
+
b1 = gr.Button()
|
137 |
|
138 |
with gr.Accordion("Parameters", open=False):
|
139 |
top_p = gr.Slider( minimum=-0, maximum=1.0, value=1.0, step=0.05, interactive=True, label="Top-p (nucleus sampling)",)
|
|
|
141 |
chat_counter = gr.Number(value=0, visible=False, precision=0)
|
142 |
|
143 |
inputs.submit( predict, [inputs, top_p, temperature,chat_counter, chatbot, state], [chatbot, state, chat_counter],)
|
144 |
+
b1.click( predict, [inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter],)
|
145 |
+
b1.click(reset_textbox, [], [inputs])
|
|
|
146 |
inputs.submit(reset_textbox, [], [inputs])
|
147 |
+
|
|
|
148 |
gr.Markdown(description)
|
|
|
|
|
149 |
demo.queue().launch(debug=True)
|