PyaeSoneK commited on
Commit
0567750
·
1 Parent(s): 8e2430c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +112 -50
app.py CHANGED
@@ -1,5 +1,3 @@
1
- #This version includes the memory and custom prompt, representing the final version
2
-
3
  import streamlit as st
4
  from streamlit_chat import message as st_message
5
  import pandas as pd
@@ -36,6 +34,7 @@ from langchain.chains.conversational_retrieval.prompts import CONDENSE_QUESTION_
36
 
37
 
38
  prompt_template = """
 
39
  You are the chatbot and the advanced legal assitant that can give answers to all the legal questions a common citizen would have . Your job is to give answers when questions about General legal information, Family law, Employment law, Consumer rights, Housing and tenancy, Personal injury, Wills and estates, Criminal law are asked.
40
  Your job is to answer questions only and only related to Legal aspect. Anything unrelated should be responded with the fact that your main job is solely to provide assistance regarding Legality.
41
  MUST only use the following pieces of context to answer the question at the end. If the answers are not in the context or you are not sure of the answer, just say that you don't know, don't try to make up an answer.
@@ -44,6 +43,64 @@ Question: {question}
44
  When encountering abusive, offensive, or harmful language, such as fuck, bitch,etc, just politely ask the users to maintain appropriate behaviours.
45
  Always make sure to elaborate your response and use vibrant, positive tone to represent good branding of the school.
46
  Never answer with any unfinished response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  Answer:
48
  """
49
  PROMPT = PromptTemplate(
@@ -57,52 +114,44 @@ st.set_page_config(
57
  page_icon = '🕵')
58
 
59
 
60
- from transformers import AutoModel
61
- import torch
62
- import transformers
63
- from transformers import AutoTokenizer, AutoModelForCausalLM
64
 
65
- from transformers import pipeline
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
  @st.cache_resource
68
- def load_llm_model():
69
- # llm = LlamaForConditionalGeneration.from_pretrained(model_id= 'PyaeSoneK/LlamaV2LegalFineTuned',
70
- # task= 'text2text-generation',
71
- # model_kwargs={ "device_map": "auto",
72
- # "load_in_8bit": True,"max_length": 256, "temperature": 0,
73
- # "repetition_penalty": 1.5})
74
-
75
- #token = st.secrets['hf_access_token']
76
- #llm = AutoModelForCausalLM.from_pretrained(model_id = 'PyaeSoneK/LlamaV2LegalFineTuned',
77
- # task = 'text2text-generation',
78
- # device_map='auto',
79
- # torch_dtype=torch.float16,
80
- # use_auth_token= st.secrets['hf_access_token'],
81
-
82
- #return llm
83
- model = AutoModelForCausalLM.from_pretrained("PyaeSoneK/LlamaV2LegalFineTuned",
84
- device_map='auto',
85
- torch_dtype=torch.float16,
86
- use_auth_token= st.secrets['hf_access_token'],)
87
- # load_in_4bit=True
88
-
89
- tokenizer = AutoTokenizer.from_pretrained("PyaeSoneK/LlamaV2LegalFineTuned",
90
- use_auth_token=True,)
91
-
92
- pipe = pipeline("text-generation",
93
- model=model,
94
- tokenizer= tokenizer,
95
- torch_dtype=torch.bfloat16,
96
- device_map="auto",
97
- max_new_tokens = 512,
98
- do_sample=True,
99
- top_k=30,
100
- num_return_sequences=1,
101
- eos_token_id=tokenizer.eos_token_id
102
- )
103
-
104
- return model
105
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
107
 
108
  @st.cache_resource
@@ -123,9 +172,16 @@ def load_conversational_qa_memory_retriever():
123
  get_chat_history=lambda h :h)
124
  return conversational_qa_memory_retriever, question_generator
125
 
 
 
 
 
126
 
 
127
 
128
-
 
 
129
 
130
 
131
 
@@ -222,8 +278,12 @@ worksheet_comment = workbook.worksheet("Sheet2")
222
  datetime_format= "%Y-%m-%d %H:%M:%S"
223
 
224
 
225
- llm_model = load_llm_model()
226
 
 
 
 
 
 
227
  conversational_qa_memory_retriever, question_generator = load_conversational_qa_memory_retriever()
228
  print("all load done")
229
 
@@ -238,12 +298,12 @@ if st.session_state.chat_history == []:
238
 
239
 
240
 
241
- st.write("# 🦜Legal QA For Dummies 🔗 ")
242
  st.markdown("""
243
  ####This Legal QA is designed for normal people trying to get the legal answers orbiting around in their life.
244
- The goal of this chatbot is to provide answers and advice quick access information about Legality : Law and Regulations and What Ca
245
  """)
246
- st.write(' ⚠️ Please expect to wait **~ 10 - 20 seconds per question** as thi app is running on CPU against 3-billion-parameter LLM')
247
 
248
  st.markdown("---")
249
  st.write(" ")
@@ -289,4 +349,6 @@ feedback_input = st.text_area(label= 'please leave your feedback or any ideas to
289
  feedback_button = st.button(label = 'Submit feedback!')
290
 
291
  if feedback_button:
292
- update_worksheet_comment()
 
 
 
 
 
1
  import streamlit as st
2
  from streamlit_chat import message as st_message
3
  import pandas as pd
 
34
 
35
 
36
  prompt_template = """
37
+
38
  You are the chatbot and the advanced legal assitant that can give answers to all the legal questions a common citizen would have . Your job is to give answers when questions about General legal information, Family law, Employment law, Consumer rights, Housing and tenancy, Personal injury, Wills and estates, Criminal law are asked.
39
  Your job is to answer questions only and only related to Legal aspect. Anything unrelated should be responded with the fact that your main job is solely to provide assistance regarding Legality.
40
  MUST only use the following pieces of context to answer the question at the end. If the answers are not in the context or you are not sure of the answer, just say that you don't know, don't try to make up an answer.
 
43
  When encountering abusive, offensive, or harmful language, such as fuck, bitch,etc, just politely ask the users to maintain appropriate behaviours.
44
  Always make sure to elaborate your response and use vibrant, positive tone to represent good branding of the school.
45
  Never answer with any unfinished response
46
+ Answer:
47
+ """
48
+
49
+ PROMPT = PromptTemplate(
50
+ template=prompt_template, input_variables=["context", "question"]
51
+ )
52
+ chain_type_kwargs = {"prompt": PROMPT}
53
+
54
+
55
+ #This version includes the memory and custom prompt, representing the final version
56
+
57
+ import streamlit as st
58
+ from streamlit_chat import message as st_message
59
+ import pandas as pd
60
+ import numpy as np
61
+ import datetime
62
+ import gspread
63
+ import pickle
64
+ import os
65
+ import csv
66
+ import json
67
+ import torch
68
+ from tqdm.auto import tqdm
69
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
70
+
71
+
72
+ # from langchain.vectorstores import Chroma
73
+ from langchain.vectorstores import FAISS
74
+ from langchain.embeddings import HuggingFaceInstructEmbeddings
75
+
76
+
77
+ from langchain import HuggingFacePipeline
78
+ from langchain.chains import RetrievalQA
79
+ from langchain.prompts import PromptTemplate
80
+ from langchain.memory import ConversationBufferWindowMemory
81
+
82
+
83
+ from langchain.chains import LLMChain
84
+ from langchain.chains import ConversationalRetrievalChain
85
+ from langchain.chains.question_answering import load_qa_chain
86
+ from langchain.chains.conversational_retrieval.prompts import CONDENSE_QUESTION_PROMPT
87
+
88
+
89
+
90
+ prompt_template = """
91
+
92
+ You are the chatbot and the face of Asian Institute of Technology (AIT). Your job is to give answers to prospective and current students about the school.
93
+ Your job is to answer questions only and only related to the AIT. Anything unrelated should be responded with the fact that your main job is solely to provide assistance regarding AIT.
94
+ MUST only use the following pieces of context to answer the question at the end. If the answers are not in the context or you are not sure of the answer, just say that you don't know, don't try to make up an answer.
95
+
96
+
97
+ {context}
98
+ Question: {question}
99
+
100
+ When encountering abusive, offensive, or harmful language, such as fuck, bitch,etc, just politely ask the users to maintain appropriate behaviours.
101
+ Always make sure to elaborate your response and use vibrant, positive tone to represent good branding of the school.
102
+ Never answer with any unfinished response
103
+
104
  Answer:
105
  """
106
  PROMPT = PromptTemplate(
 
114
  page_icon = '🕵')
115
 
116
 
 
 
 
 
117
 
118
+
119
+ @st.cache_data
120
+ def load_scraped_web_info():
121
+ with open("Banksandbanking", "rb") as fp:
122
+ banksandbanking_web_documents = pickle.load(fp)
123
+
124
+
125
+ text_splitter = RecursiveCharacterTextSplitter(
126
+ # Set a really small chunk size, just to show.
127
+ chunk_size = 500,
128
+ chunk_overlap = 100,
129
+ length_function = len,
130
+ )
131
+
132
+ chunked_text = text_splitter.create_documents([doc for doc in tqdm(banksandbanking_web_documents)])
133
+
134
 
135
  @st.cache_resource
136
+ def load_embedding_model():
137
+ embedding_model = HuggingFaceInstructEmbeddings(model_name='hkunlp/instructor-base',
138
+ model_kwargs = {'device': torch.device('cuda' if torch.cuda.is_available() else 'cpu')})
139
+ return embedding_model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
 
141
+ @st.cache_data
142
+ def load_faiss_index():
143
+ vector_database = FAISS.load_local("faiss_index_web_and_curri_new", embedding_model) #CHANGE THIS FAISS EMBEDDED KNOWLEDGE
144
+ return vector_database
145
+
146
+ @st.cache_resource
147
+ def load_llm_model():
148
+ llm = HuggingFacePipeline.from_model_id(model_id= 'PyaeSoneK/pythia_70m_legalQA',
149
+ task= 'text2text-generation',
150
+
151
+ model_kwargs={ "max_length": 256, "temperature": 0,
152
+ "torch_dtype":torch.float32,
153
+ "repetition_penalty": 1.3})
154
+ return llm
155
 
156
 
157
  @st.cache_resource
 
172
  get_chat_history=lambda h :h)
173
  return conversational_qa_memory_retriever, question_generator
174
 
175
+ def load_retriever(llm, db):
176
+ qa_retriever = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff",
177
+ retriever=db.as_retriever(),
178
+ chain_type_kwargs= chain_type_kwargs)
179
 
180
+ return qa_retriever
181
 
182
+ def retrieve_document(query_input):
183
+ related_doc = vector_database.similarity_search(query_input)
184
+ return related_doc
185
 
186
 
187
 
 
278
  datetime_format= "%Y-%m-%d %H:%M:%S"
279
 
280
 
 
281
 
282
+ load_scraped_web_info()
283
+ embedding_model = load_embedding_model()
284
+ vector_database = load_faiss_index()
285
+ llm_model = load_llm_model()
286
+ qa_retriever = load_retriever(llm= llm_model, db= vector_database)
287
  conversational_qa_memory_retriever, question_generator = load_conversational_qa_memory_retriever()
288
  print("all load done")
289
 
 
298
 
299
 
300
 
301
+ st.write("🦜Seon's Legal QA For Dummies 🔗 ")
302
  st.markdown("""
303
  ####This Legal QA is designed for normal people trying to get the legal answers orbiting around in their life.
304
+ The goal of this chatbot is to provide answers and advice with quick access information on Legality : Law and Regulations: what's right or wrong in general!
305
  """)
306
+ st.write(' ⚠️ Please expect to wait **~ 5-10 seconds per question** as thi app is running on CPU against 70-million-parameter LLM')
307
 
308
  st.markdown("---")
309
  st.write(" ")
 
349
  feedback_button = st.button(label = 'Submit feedback!')
350
 
351
  if feedback_button:
352
+ update_worksheet_comment()
353
+
354
+