Charreau Bell, Ph.D commited on
Commit
2a6090d
β€’
1 Parent(s): 1956c42

Fixed hf destination path in gh actions for auto deployment

Browse files
Files changed (2) hide show
  1. app.py +358 -0
  2. requirements.txt +15 -0
app.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/gradio_application.ipynb.
2
+
3
+ # %% auto 0
4
+ __all__ = ['save_pdf', 'save_json', 'save_txt', 'save_csv', 'num_sources', 'css', 'save_chatbot_dialogue',
5
+ 'SlightlyDelusionalTutor', 'embed_key', 'create_reference_store', 'prompt_select', 'add_user_message',
6
+ 'get_tutor_reply', 'disable_until_done']
7
+
8
+ # %% ../nbs/gradio_application.ipynb 9
9
+ import gradio as gr
10
+ from functools import partial
11
+ import pandas as pd
12
+ import os
13
+
14
+ from .PromptInteractionBase import *
15
+ from .IOHelperUtilities import *
16
+ from .SelfStudyPrompts import *
17
+ from .MediaVectorStores import *
18
+
19
+ # %% ../nbs/gradio_application.ipynb 13
20
+ def save_chatbot_dialogue(chat_tutor, save_type):
21
+
22
+ formatted_convo = pd.DataFrame(chat_tutor.conversation_memory, columns=['user', 'chatbot'])
23
+
24
+ output_fname = f'tutoring_conversation.{save_type}'
25
+
26
+ if save_type == 'csv':
27
+ formatted_convo.to_csv(output_fname, index=False)
28
+ elif save_type == 'json':
29
+ formatted_convo.to_json(output_fname, orient='records')
30
+ elif save_type == 'txt':
31
+ temp = formatted_convo.apply(lambda x: 'User: {0}\nAI: {1}'.format(x[0], x[1]), axis=1)
32
+ temp = '\n\n'.join(temp.tolist())
33
+ with open(output_fname, 'w') as f:
34
+ f.write(temp)
35
+ else:
36
+ gr.update(value=None, visible=False)
37
+
38
+ return gr.update(value=output_fname, visible=True)
39
+
40
+ save_pdf = partial(save_chatbot_dialogue, save_type='pdf')
41
+ save_json = partial(save_chatbot_dialogue, save_type='json')
42
+ save_txt = partial(save_chatbot_dialogue, save_type='txt')
43
+ save_csv = partial(save_chatbot_dialogue, save_type='csv')
44
+
45
+
46
+ # %% ../nbs/gradio_application.ipynb 16
47
+ class SlightlyDelusionalTutor:
48
+ # create basic initialization function
49
+ def __init__(self, model_name = None):
50
+
51
+ # create default model name
52
+ if model_name is None:
53
+ self.model_name = 'gpt-3.5-turbo-16k'
54
+
55
+ self.chat_llm = None
56
+ self.tutor_chain = None
57
+ self.vector_store = None
58
+ self.vs_retriever = None
59
+ self.conversation_memory = []
60
+ self.sources_memory = []
61
+ self.flattened_conversation = ''
62
+ self.api_key_valid = False
63
+ self.learning_objectives = None
64
+ self.openai_auth = ''
65
+
66
+ def initialize_llm(self):
67
+
68
+ if self.openai_auth:
69
+ try:
70
+ self.chat_llm = create_model(self.model_name, openai_api_key = self.openai_auth)
71
+ self.api_key_valid = True
72
+ except Exception as e:
73
+ print(e)
74
+ self.api_key_valid = False
75
+ else:
76
+ print("Please provide an OpenAI API key and press Enter.")
77
+
78
+ def add_user_message(self, user_message):
79
+ self.conversation_memory.append([user_message, None])
80
+ self.flattened_conversation = self.flattened_conversation + '\n\n' + 'User: ' + user_message
81
+
82
+ def get_tutor_reply(self, **input_kwargs):
83
+
84
+ if not self.conversation_memory:
85
+ return "Please type something to start the conversation."
86
+
87
+ # we want to have a different vector comparison for reference lookup after the topic is first used
88
+ if len(self.conversation_memory) > 1:
89
+ if 'question' in input_kwargs.keys():
90
+ if input_kwargs['question']:
91
+ input_kwargs['question'] = self.conversation_memory[-1][0] + ' keeping in mind I want to learn about ' + input_kwargs['question']
92
+ else:
93
+ input_kwargs['question'] = self.conversation_memory[-1][0]
94
+
95
+ # get tutor message
96
+ tutor_message = get_tutoring_answer(None,
97
+ self.tutor_chain,
98
+ assessment_request = self.flattened_conversation + 'First, please provide your feedback on my previous answer if I was answering a question, otherwise, respond appropriately to my statement. Then, help me with the following:' + self.conversation_memory[-1][0],
99
+ learning_objectives = self.learning_objectives,
100
+ return_dict=True,
101
+ **input_kwargs)
102
+
103
+ # add tutor message to conversation memory
104
+ self.conversation_memory[-1][1] = tutor_message['answer']
105
+ self.flattened_conversation = self.flattened_conversation + '\nAI: ' + tutor_message['answer']
106
+ self.sources_memory.append(tutor_message['source_documents'])
107
+ #print(self.flattened_conversation, '\n\n')
108
+ print(tutor_message['source_documents'])
109
+
110
+ def get_sources_memory(self):
111
+ # retrieve last source
112
+ last_sources = self.sources_memory[-1]
113
+
114
+ # get page_content keyword from last_sources
115
+ doc_contents = ['Source ' + str(ind+1) + '\n"' + doc.page_content + '"\n\n' for ind, doc in enumerate(last_sources)]
116
+ doc_contents = ''.join(doc_contents)
117
+
118
+ return doc_contents
119
+
120
+ def forget_conversation(self):
121
+ self.conversation_memory = []
122
+ self.sources_memory = []
123
+ self.flattened_conversation = ''
124
+
125
+ # %% ../nbs/gradio_application.ipynb 18
126
+ def embed_key(openai_api_key, chat_tutor):
127
+ if not openai_api_key:
128
+ return chat_tutor
129
+
130
+ # Otherwise, update key
131
+ os.environ["OPENAI_API_KEY"] = openai_api_key
132
+
133
+ #update tutor
134
+ chat_tutor.openai_auth = openai_api_key
135
+
136
+ if not chat_tutor.api_key_valid:
137
+ chat_tutor.initialize_llm()
138
+
139
+ return chat_tutor
140
+
141
+ # %% ../nbs/gradio_application.ipynb 20
142
+ def create_reference_store(chat_tutor, vs_button, text_cp, upload_files, reference_vs, openai_auth, learning_objs):
143
+
144
+ text_segs = []
145
+ upload_segs = []
146
+
147
+ if reference_vs:
148
+ raise NotImplementedError("Reference Vector Stores are not yet implemented")
149
+
150
+ if text_cp.strip():
151
+ text_segs = get_document_segments(text_cp, 'text', chunk_size=700, chunk_overlap=100)
152
+ [doc.metadata.update({'source':'text box'}) for doc in text_segs];
153
+
154
+ if upload_files:
155
+ print(upload_files)
156
+ upload_fnames = [f.name for f in upload_files]
157
+ upload_segs = get_document_segments(upload_fnames, 'file', chunk_size=700, chunk_overlap=100)
158
+
159
+ # get the full list of everything
160
+ all_segs = text_segs + upload_segs
161
+ print(all_segs)
162
+
163
+ # create the vector store and update tutor
164
+ vs_db, vs_retriever = create_local_vector_store(all_segs, search_kwargs={"k": 2})
165
+ chat_tutor.vector_store = vs_db
166
+ chat_tutor.vs_retriever = vs_retriever
167
+
168
+ # create the tutor chain
169
+ if not chat_tutor.api_key_valid or not chat_tutor.openai_auth:
170
+ chat_tutor = embed_key(openai_auth, chat_tutor)
171
+ qa_chain = create_tutor_mdl_chain(kind="retrieval_qa", mdl=chat_tutor.chat_llm, retriever = chat_tutor.vs_retriever, return_source_documents=True)
172
+ chat_tutor.tutor_chain = qa_chain
173
+
174
+ # store learning objectives
175
+ chat_tutor.learning_objectives = learning_objs
176
+
177
+ # return the story
178
+ return chat_tutor, gr.update(interactive=True, value='Tutor Initialized!')
179
+
180
+ # %% ../nbs/gradio_application.ipynb 22
181
+ ### Gradio Called Functions ###
182
+
183
+ def prompt_select(selection, number, length):
184
+ if selection == "Random":
185
+ prompt = f"Please design a {number} question quiz based on the context provided and the inputted learning objectives (if applicable). The types of questions should be randomized (including multiple choice, short answer, true/false, short answer, etc.). Provide one question at a time, and wait for my response before providing me with feedback. Again, while the quiz may ask for multiple questions, you should only provide 1 question in you initial response. Do not include the answer in your response. If I get an answer wrong, provide me with an explanation of why it was incorrect, and then give me additional chances to respond until I get the correct choice. Explain why the correct choice is right."
186
+ elif selection == "Fill in the Blank":
187
+ prompt = f"Create a {number} question fill in the blank quiz refrencing the context provided. The quiz should reflect the learning objectives (if inputted). The 'blank' part of the question should appear as '________'. The answers should reflect what word(s) should go in the blank an accurate statement. An example is the follow: 'The author of the article is ______.' The question should be a statement. Provide one question at a time, and wait for my response before providing me with feedback. Again, while the quiz may ask for multiple questions, you should only provide ONE question in you initial response. Do not include the answer in your response. If I get an answer wrong, provide me with an explanation of why it was incorrect,and then give me additional chances to respond until I get the correct choice. Explain why the correct choice is right."
188
+ elif selection == "Short Answer":
189
+ prompt = f"Please design a {number} question quiz about which reflects the learning objectives (if inputted). The questions should be short answer. Expect the correct answers to be {length} sentences long. Provide one question at a time, and wait for my response before providing me with feedback. Again, while the quiz may ask for multiple questions, you should only provide ONE question in you initial response. Do not include the answer in your response. If I get an answer wrong, provide me with an explanation of why it was incorrect, and then give me additional chances to respond until I get the correct choice. Explain why the correct answer is right."
190
+ else:
191
+ prompt = f"Please design a {number} question {selection.lower()} quiz based on the context provided and the inputted learning objectives (if applicable). Provide one question at a time, and wait for my response before providing me with feedback. Again, while the quiz may ask for multiple questions, you should only provide 1 question in you initial response. Do not include the answer in your response. If I get an answer wrong, provide me with an explanation of why it was incorrect, and then give me additional chances to respond until I get the correct choice. Explain why the correct choice is right."
192
+ return prompt, prompt
193
+
194
+
195
+ # %% ../nbs/gradio_application.ipynb 24
196
+ ### Chatbot Functions ###
197
+
198
+ def add_user_message(user_message, chat_tutor):
199
+ """Display user message and update chat history to include it.
200
+ Also disables user text input until bot is finished (call to reenable_chat())
201
+ See https://gradio.app/creating-a-chatbot/"""
202
+ chat_tutor.add_user_message(user_message)
203
+ return gr.update(value="", interactive=False), chat_tutor.conversation_memory, chat_tutor
204
+
205
+ def get_tutor_reply(learning_topic, chat_tutor):
206
+ chat_tutor.get_tutor_reply(input_kwargs={'question':learning_topic})
207
+ return gr.update(value="", interactive=True), gr.update(visible=True, value=chat_tutor.get_sources_memory()), chat_tutor.conversation_memory, chat_tutor
208
+
209
+ num_sources = 2
210
+
211
+ # %% ../nbs/gradio_application.ipynb 25
212
+ def disable_until_done(obj_in):
213
+ return gr.update(interactive=False)
214
+
215
+ # %% ../nbs/gradio_application.ipynb 27
216
+ # See https://gradio.app/custom-CSS-and-JS/
217
+ css="""
218
+ #sources-container {
219
+ overflow: scroll !important; /* Needs to override default formatting */
220
+ /*max-height: 20em; */ /* Arbitrary value */
221
+ }
222
+ #sources-container > div { padding-bottom: 1em !important; /* Arbitrary value */ }
223
+ .short-height > * > * { min-height: 0 !important; }
224
+ .translucent { opacity: 0.5; }
225
+ .textbox_label { padding-bottom: .5em; }
226
+ """
227
+ #srcs = [] # Reset sources (db and qa are kept the same for ease of testing)
228
+
229
+ with gr.Blocks(css=css, analytics_enabled=False) as demo:
230
+
231
+ #initialize tutor (with state)
232
+ study_tutor = gr.State(SlightlyDelusionalTutor())
233
+
234
+ # Title
235
+ gr.Markdown("# Studying with a Slightly Delusional Tutor")
236
+
237
+ # API Authentication functionality
238
+ with gr.Box():
239
+ gr.Markdown("### OpenAI API Key ")
240
+ gr.HTML("""<span>Embed your OpenAI API key below; if you haven't created one already, visit
241
+ <a href="https://platform.openai.com/account/api-keys">platform.openai.com/account/api-keys</a>
242
+ to sign up for an account and get your personal API key</span>""",
243
+ elem_classes="textbox_label")
244
+ api_input = gr.Textbox(show_label=False, type="password", container=False, autofocus=True,
245
+ placeholder="●●●●●●●●●●●●●●●●●", value='')
246
+ api_input.submit(fn=embed_key, inputs=[api_input, study_tutor], outputs=study_tutor)
247
+ api_input.blur(fn=embed_key, inputs=[api_input, study_tutor], outputs=study_tutor)
248
+
249
+ # Reference document functionality (building vector stores)
250
+ with gr.Box():
251
+ gr.Markdown("### Add Reference Documents")
252
+ # TODO Add entry for path to vector store (should be disabled for now)
253
+ with gr.Row(equal_height=True):
254
+ text_input = gr.TextArea(label='Copy and paste your text below',
255
+ lines=2)
256
+
257
+ file_input = gr.Files(label="Load a .txt or .pdf file",
258
+ file_types=['.pdf', '.txt'], type="file",
259
+ elem_classes="short-height")
260
+
261
+ instructor_input = gr.TextArea(label='Enter vector store URL, if given by instructor (WIP)', value='',
262
+ lines=2, interactive=False, elem_classes="translucent")
263
+
264
+ # Adding the learning objectives
265
+ with gr.Box():
266
+ gr.Markdown("### Optional: Enter Your Learning Objectives")
267
+ learning_objectives = gr.Textbox(label='If provided by your instructor, please input your learning objectives for this session', value='')
268
+
269
+ # Adding the button to submit all of the settings and create the Chat Tutor Chain.
270
+ with gr.Row():
271
+ vs_build_button = gr.Button(value = 'Start Studying with Your Tutor!', scale=1)
272
+ vs_build_button.click(disable_until_done, vs_build_button, vs_build_button) \
273
+ .then(create_reference_store, [study_tutor, vs_build_button, text_input, file_input, instructor_input, api_input, learning_objectives],
274
+ [study_tutor, vs_build_button])
275
+
276
+
277
+
278
+ # Premade question prompts
279
+ with gr.Box():
280
+ gr.Markdown("""
281
+ ## Generate a Premade Prompt
282
+ Select your type and number of desired questions. Click "Generate Prompt" to get your premade prompt,
283
+ and then "Insert Prompt into Chat" to copy the text into the chat interface below. \
284
+ You can also copy the prompt using the icon in the upper right corner and paste directly into the input box when interacting with the model.
285
+ """)
286
+ with gr.Row():
287
+ with gr.Column():
288
+ question_type = gr.Dropdown(["Multiple Choice", "True or False", "Short Answer", "Fill in the Blank", "Random"], label="Question Type")
289
+ number_of_questions = gr.Textbox(label="Enter desired number of questions")
290
+ sa_desired_length = gr.Dropdown(["1-2", "3-4", "5-6", "6 or more"], label = "For short answer questions only, choose the desired sentence length for answers. The default value is 1-2 sentences.")
291
+ with gr.Column():
292
+ prompt_button = gr.Button("Generate Prompt")
293
+ premade_prompt_output = gr.Textbox(label="Generated prompt (save or copy)", show_copy_button=True)
294
+
295
+
296
+ # Chatbot interface
297
+ gr.Markdown("## Chat with the Model")
298
+ topic_input = gr.Textbox(label="What topic or concept are you trying to learn more about?")
299
+ with gr.Row(equal_height=True):
300
+ with gr.Column(scale=2):
301
+ chatbot = gr.Chatbot()
302
+ with gr.Row():
303
+ user_chat_input = gr.Textbox(label="User input", scale=9)
304
+ user_chat_submit = gr.Button("Ask/answer model", scale=1)
305
+
306
+ # sources
307
+ with gr.Box(elem_id="sources-container", scale=1):
308
+ # TODO: Display document sources in a nicer format?
309
+ gr.HTML(value="<h3 id='sources'>Referenced Sources</h3>")
310
+ sources_output = gr.Textbox(value='', interactive=False, visible=False, show_label=False)
311
+ #sources_output = []
312
+ #for i in range(num_sources):
313
+ # source_elem = gr.HTML(visible=False)
314
+ # sources_output.append(source_elem)
315
+
316
+ #define the behavior of prompt button later since it depends on user_chat_input
317
+ prompt_button.click(prompt_select,
318
+ inputs=[question_type, number_of_questions, sa_desired_length],
319
+ outputs=[premade_prompt_output, user_chat_input])
320
+
321
+ # Display input and output in three-ish parts
322
+ # (using asynchronous functions):
323
+ # First show user input, then show model output when complete
324
+ # Then wait until the bot provides response and return the result
325
+ # Finally, allow the user to ask a new question by reenabling input
326
+ async_response = user_chat_submit.click(add_user_message,
327
+ [user_chat_input, study_tutor],
328
+ [user_chat_input, chatbot, study_tutor], queue=False) \
329
+ .then(get_tutor_reply, [topic_input, study_tutor], [user_chat_input, sources_output, chatbot, study_tutor], queue=True)
330
+
331
+ async_response_b = user_chat_input.submit(add_user_message,
332
+ [user_chat_input, study_tutor],
333
+ [user_chat_input, chatbot, study_tutor], queue=False) \
334
+ .then(get_tutor_reply, [topic_input, study_tutor], [user_chat_input, sources_output, chatbot, study_tutor], queue=True)
335
+
336
+ with gr.Blocks():
337
+ gr.Markdown("""
338
+ ## Export Your Chat History
339
+ Export your chat history as a .json, PDF file, .txt, or .csv file
340
+ """)
341
+ with gr.Row():
342
+ export_dialogue_button_json = gr.Button("JSON")
343
+ export_dialogue_button_pdf = gr.Button("PDF")
344
+ export_dialogue_button_txt = gr.Button("TXT")
345
+ export_dialogue_button_csv = gr.Button("CSV")
346
+
347
+ file_download = gr.Files(label="Download here",
348
+ file_types=['.pdf', '.txt', '.csv', '.json'], type="file", visible=False)
349
+
350
+ export_dialogue_button_json.click(save_json, study_tutor, file_download, show_progress=True)
351
+ export_dialogue_button_pdf.click(save_pdf, study_tutor, file_download, show_progress=True)
352
+ export_dialogue_button_txt.click(save_txt, study_tutor, file_download, show_progress=True)
353
+ export_dialogue_button_csv.click(save_csv, study_tutor, file_download, show_progress=True)
354
+
355
+ demo.queue()
356
+ demo.launch(debug=True)
357
+ #demo.launch()
358
+ #gr.close_all()
requirements.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ langchain
2
+ pandas
3
+ numpy
4
+ openai
5
+ gradio
6
+ chromadb
7
+ tiktoken
8
+ unstructured
9
+ pdf2image
10
+ yt_dlp
11
+ libmagic
12
+ chromadb
13
+ librosa
14
+ deeplake
15
+ ipyfilechooser