demoPOC commited on
Commit
a4a901b
·
1 Parent(s): 05c0b3f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +207 -109
app.py CHANGED
@@ -1,144 +1,242 @@
1
  import openai
2
- import numpy as np
3
- import pandas as pd
4
- import os
5
- from langchain.embeddings.openai import OpenAIEmbeddings
6
- from langchain.embeddings.huggingface import HuggingFaceEmbeddings
7
- from langchain import HuggingFaceHub
8
- from langchain.vectorstores import Chroma
9
- from langchain.text_splitter import RecursiveCharacterTextSplitter
10
- from langchain.llms import OpenAI
11
- from langchain.chains import RetrievalQA
12
- from langchain.chains import VectorDBQA
13
- from langchain.document_loaders import TextLoader, WebBaseLoader, SeleniumURLLoader
14
- from langchain.document_loaders import UnstructuredFileLoader
15
  from flask import Flask, jsonify, render_template, request
 
 
 
 
 
 
 
16
  from werkzeug.utils import secure_filename
17
- from werkzeug.datastructures import FileStorage
 
18
  import nltk
19
- nltk.download("punkt")
20
- import warnings
21
- warnings.filterwarnings("ignore")
22
 
 
23
 
 
 
24
 
25
- openai.api_key=os.getenv("OPENAI_API_KEY")
 
26
 
 
27
 
28
- import flask
29
- import os
30
- from dotenv import load_dotenv
31
- load_dotenv()
 
 
 
 
 
 
32
 
33
- loader = UnstructuredFileLoader('Jio.txt', mode='elements')
34
- documents= loader.load()
 
35
 
36
- text_splitter = RecursiveCharacterTextSplitter(chunk_size=1500, chunk_overlap=150)
37
- texts = text_splitter.split_documents(documents)
38
- embeddings = OpenAIEmbeddings()
39
- vectordb = Chroma.from_documents(texts,embeddings)
40
- chain = RetrievalQA.from_chain_type(llm=OpenAI(temperature=0.0),chain_type="stuff", retriever=vectordb.as_retriever(search_type="mmr"),return_source_documents=True)
41
 
 
42
 
43
  app = flask.Flask(__name__, template_folder="./")
 
44
  # Create a directory in a known location to save files to.
45
  uploads_dir = os.path.join(app.root_path,'static', 'uploads')
 
46
  os.makedirs(uploads_dir, exist_ok=True)
47
 
 
 
 
 
 
 
 
 
 
48
 
49
- @app.route('/Home')
50
- def index():
51
- return flask.render_template('index.html')
52
 
53
- @app.route('/post_json', methods=['POST'])
54
  def process_json():
 
 
55
  content_type = request.headers.get('Content-Type')
56
  if (content_type == 'application/json'):
57
-
58
- userQuery = request.get_json()['query']
59
- responseJSON=chain({"query":userQuery});
60
- print("Retrieved Document List START ***********************\n\n")
61
- pretty_print_docs(responseJSON['source_documents'])
62
- print("Retrieved Document List END ***********************\n\n")
63
- print("Ques:>>>>"+userQuery+"\n Ans:>>>"+responseJSON["result"])
64
- return jsonify(botMessage=responseJSON["result"]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  else:
66
  return 'Content-Type not supported!'
67
 
68
-
69
- @app.route('/file_upload',methods=['POST'])
70
  def file_Upload():
71
-
72
- fileprovided=not request.files.getlist('files[]')[0].filename==''
73
- urlProvided=not request.form.getlist('weburl')[0]==''
74
- print("*******")
75
- print("File Provided:"+str(fileprovided))
76
- print("URL Provided:"+str(urlProvided))
77
- print("*******")
78
- print(not ('documents' in vars() or 'documents' in globals()))
79
- # if not ('documents' in vars() or 'documents' in globals()):
80
- documents = []
81
- if fileprovided:
82
-
83
- #Delete Files
84
- for filename in os.listdir(uploads_dir):
85
- file_path = os.path.join(uploads_dir, filename)
86
- print("Clearing Doc Directory. Trying to delete"+file_path)
87
- try:
88
- if os.path.isfile(file_path) or os.path.islink(file_path):
89
- os.unlink(file_path)
90
- elif os.path.isdir(file_path):
91
- shutil.rmtree(file_path)
92
- except Exception as e:
93
- print('Failed to delete %s. Reason: %s' % (file_path, e))
94
- #Read and Embed New Files provided
95
- for file in request.files.getlist('files[]'):
96
- print(file.filename)
97
- file.save(os.path.join(uploads_dir, secure_filename(file.filename)))
98
- loader = UnstructuredFileLoader(os.path.join(uploads_dir, secure_filename(file.filename)), mode='elements')
99
- documents.extend(loader.load())
100
- else:
101
- loader = UnstructuredFileLoader('Jio.txt', mode='elements')
102
- documents.extend(loader.load())
103
-
104
- if urlProvided:
105
- weburl=request.form.getlist('weburl')
106
- print(weburl)
107
- urlList=weburl[0].split(';')
108
- print(urlList)
109
- urlLoader=SeleniumURLLoader(urlList)
110
- documents.extend(urlLoader.load())
111
-
112
-
113
-
114
- print(uploads_dir)
115
- global chain;
116
-
117
- text_splitter = RecursiveCharacterTextSplitter(chunk_size=1500, chunk_overlap=150)
118
- texts = text_splitter.split_documents(documents)
119
-
120
- print("All chunk List START ***********************\n\n")
121
- pretty_print_docs(texts)
122
- print("All chunk List END ***********************\n\n")
123
-
124
- embeddings = OpenAIEmbeddings()
125
- vectordb = Chroma.from_documents(texts,embeddings)
126
- chain = RetrievalQA.from_chain_type(llm=OpenAI(temperature=0.0),chain_type="stuff", retriever=vectordb.as_retriever(search_type="mmr"),return_source_documents=True)
127
-
128
- return render_template("index.html")
129
-
130
- @app.route('/')
131
- def KBUpload():
132
- return render_template("KBTrain.html")
133
 
134
- @app.route('/aiassist')
135
- def aiassist():
136
- return render_template("index.html")
137
 
138
  def pretty_print_docs(docs):
139
- print(f"\n{'-' * 100}\n".join([f"Document {i+1}:\n\n" + "Document Source>>> "+d.metadata['source']+"\n\nContent>>> "+d.page_content for i, d in enumerate(docs)]))
 
 
140
 
141
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
 
143
  if __name__ == '__main__':
144
  app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 7860)))
 
 
1
  import openai
2
+
3
+ openai.api_key=os.getenv("OPENAI_API_KEY")
4
+
5
+ from dotenv import load_dotenv
6
+ load_dotenv()
7
+
 
 
 
 
 
 
 
8
  from flask import Flask, jsonify, render_template, request
9
+ import requests, json
10
+
11
+ # import nltk
12
+ # nltk.download("punkt")
13
+
14
+ import os
15
+ import shutil
16
  from werkzeug.utils import secure_filename
17
+ from werkzeug.datastructures import FileStorage
18
+
19
  import nltk
 
 
 
20
 
21
+ from datetime import datetime
22
 
23
+ import openai
24
+ from langchain.llms import OpenAI
25
 
26
+ from langchain.embeddings.openai import OpenAIEmbeddings
27
+ from langchain.embeddings.sentence_transformer import SentenceTransformerEmbeddings
28
 
29
+ from langchain.document_loaders import SeleniumURLLoader, PyPDFLoader
30
 
31
+ from langchain.vectorstores import Chroma
32
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
33
+
34
+ from langchain.chains import VectorDBQA
35
+
36
+ from langchain.document_loaders import UnstructuredFileLoader
37
+ from langchain import PromptTemplate
38
+
39
+ from langchain.chains import RetrievalQA
40
+ from langchain.memory import ConversationBufferWindowMemory
41
 
42
+ import warnings
43
+
44
+ warnings.filterwarnings("ignore")
45
 
 
 
 
 
 
46
 
47
+ #app = Flask(__name__)
48
 
49
  app = flask.Flask(__name__, template_folder="./")
50
+
51
  # Create a directory in a known location to save files to.
52
  uploads_dir = os.path.join(app.root_path,'static', 'uploads')
53
+
54
  os.makedirs(uploads_dir, exist_ok=True)
55
 
56
+ vectordb = createVectorDB(loadKB(False, False, uploads_dir, None))
57
+
58
+ @app.route('/', methods=['GET'])
59
+ def test():
60
+ return "Docker hello"
61
+
62
+ @app.route('/KBUploader')
63
+ def KBUpload():
64
+ return render_template("FileUpload.html")
65
 
66
+ @app.route('/aiassist')
67
+ def aiassist():
68
+ return render_template("AIAssist.html")
69
 
70
+ @app.route('/agent/chat/suggestion', methods=['POST'])
71
  def process_json():
72
+ print(f"\n{'*' * 100}\n")
73
+ print("Request Received >>>>>>>>>>>>>>>>>>", datetime.now().strftime("%H:%M:%S"))
74
  content_type = request.headers.get('Content-Type')
75
  if (content_type == 'application/json'):
76
+ requestQuery = request.get_json()
77
+ print(type(requestQuery))
78
+ custDetailsPresent=False
79
+ customerName=""
80
+ customerDistrict=""
81
+ if("custDetails" in requestQuery):
82
+ custDetailsPresent = True
83
+ customerName=requestQuery['custDetails']['cName']
84
+ customerDistrict=requestQuery['custDetails']['cDistrict']
85
+
86
+ print("chain initiation")
87
+ chainRAG=getRAGChain(customerName, customerDistrict, custDetailsPresent,vectordb)
88
+ print("chain created")
89
+ suggestionArray = []
90
+
91
+ for index, query in enumerate(requestQuery['message']):
92
+ #message = answering(query)
93
+ relevantDoc = vectordb.similarity_search_with_score(query)
94
+ for doc in relevantDoc:
95
+ print(f"\n{'-' * 100}\n")
96
+ print("Document Source>>>>>> " + doc[len(doc) - 2].metadata['source'] + "\n\n")
97
+ print("Page Content>>>>>> " + doc[len(doc) - 2].page_content + "\n\n")
98
+ print("Similarity Score>>>> " + str(doc[len(doc) - 1]))
99
+ print(f"\n{'-' * 100}\n")
100
+ message = chainRAG.run({"query": query})
101
+ print("query:",query)
102
+ print("Response:", message)
103
+ if "I don't know" in message:
104
+ message = "Dear Sir/ Ma'am, Could you please ask questions relevant to Jio?"
105
+ responseJSON={"message":message,"id":index}
106
+ suggestionArray.append(responseJSON)
107
+ return jsonify(suggestions=suggestionArray)
108
  else:
109
  return 'Content-Type not supported!'
110
 
111
+ @app.route('/file_upload', methods=['POST'])
 
112
  def file_Upload():
113
+ fileprovided = not request.files.getlist('files[]')[0].filename == ''
114
+ urlProvided = not request.form.getlist('weburl')[0] == ''
115
+ print("*******")
116
+ print("File Provided:" + str(fileprovided))
117
+ print("URL Provided:" + str(urlProvided))
118
+ print("*******")
119
+
120
+ print(uploads_dir)
121
+ documents = loadKB(fileprovided, urlProvided, uploads_dir, request)
122
+ vectordb=createVectorDB(documents)
123
+ return render_template("AIAssist.html")
124
+
125
+ def createPrompt(cName, cCity, custDetailsPresent):
126
+ cProfile = "Customer's Name is " + cName + "\nCustomer's lives in or customer's Resident State or Customer's place is " + cCity + "\n"
127
+ print(cProfile)
128
+
129
+ template1 = """You role is of a Professional Customer Support Executive and your name is Jio AIAssist.
130
+ You are talking to the below customer whose information is provided in block delimited by <cp></cp>.
131
+ Use the following customer related information (delimited by <cp></cp>) and context (delimited by <ctx></ctx>) to answer the question at the end by thinking step by step alongwith reaonsing steps:
132
+ If you don't know the answer, just say that you don't know, don't try to make up an answer.
133
+ Use the customer information to replace entities in the question before answering\n
134
+ \n"""
135
+
136
+ template2 = """
137
+ <ctx>
138
+ {context}
139
+ </ctx>
140
+ <hs>
141
+ {history}
142
+ </hs>
143
+ Question: {question}
144
+ Answer: """
145
+
146
+ prompt_template = template1 + "<cp>\n" + cProfile + "\n</cp>\n" + template2
147
+ PROMPT = PromptTemplate(template=prompt_template, input_variables=["history", "context", "question"])
148
+ return PROMPT
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
 
 
 
 
150
 
151
  def pretty_print_docs(docs):
152
+ print(f"\n{'-' * 100}\n".join([f"Document {i + 1}:\n\n" + "Document Length>>>" + str(
153
+ len(d.page_content)) + "\n\nDocument Source>>> " + d.metadata['source'] + "\n\nContent>>> " + d.page_content for
154
+ i, d in enumerate(docs)]))
155
 
156
 
157
+ def getEmbeddingModel(embeddingId):
158
+ if (embeddingId == 1):
159
+ embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
160
+ else:
161
+ embeddings = OpenAIEmbeddings()
162
+ return embeddings
163
+
164
+
165
+ def getLLMModel(LLMID):
166
+ llm = OpenAI(temperature=0.0)
167
+ return llm
168
+
169
+
170
+ def clearKBUploadDirectory(uploads_dir):
171
+ for filename in os.listdir(uploads_dir):
172
+ file_path = os.path.join(uploads_dir, filename)
173
+ print("Clearing Doc Directory. Trying to delete" + file_path)
174
+ try:
175
+ if os.path.isfile(file_path) or os.path.islink(file_path):
176
+ os.unlink(file_path)
177
+ elif os.path.isdir(file_path):
178
+ shutil.rmtree(file_path)
179
+ except Exception as e:
180
+ print('Failed to delete %s. Reason: %s' % (file_path, e))
181
+
182
+
183
+ def loadKB(fileprovided, urlProvided, uploads_dir, request):
184
+ documents = []
185
+ if fileprovided:
186
+ # Delete Files
187
+ clearKBUploadDirectory(uploads_dir)
188
+ # Read and Embed New Files provided
189
+ for file in request.files.getlist('files[]'):
190
+ print("File Received>>>" + file.filename)
191
+ file.save(os.path.join(uploads_dir, secure_filename(file.filename)))
192
+ loader = PyPDFLoader(os.path.join(uploads_dir, secure_filename(file.filename)))
193
+ documents.extend(loader.load())
194
+ else:
195
+ loader = PyPDFLoader('./KnowledgeBase/Jio.pdf')
196
+ documents.extend(loader.load())
197
+
198
+ if urlProvided:
199
+ weburl = request.form.getlist('weburl')
200
+ print(weburl)
201
+ urlList = weburl[0].split(';')
202
+ print(urlList)
203
+ print("Selenium Started", datetime.now().strftime("%H:%M:%S"))
204
+ # urlLoader=RecursiveUrlLoader(urlList[0])
205
+ urlLoader = SeleniumURLLoader(urlList)
206
+ print("Selenium Completed", datetime.now().strftime("%H:%M:%S"))
207
+ documents.extend(urlLoader.load())
208
+
209
+ return documents
210
+
211
+
212
+ def getRAGChain(customerName,customerDistrict, custDetailsPresent,vectordb):
213
+ chain = RetrievalQA.from_chain_type(
214
+ llm=getLLMModel(0),
215
+ chain_type='stuff',
216
+ retriever=vectordb.as_retriever(),
217
+ verbose=False,
218
+ chain_type_kwargs={
219
+ "verbose": False,
220
+ "prompt": createPrompt(customerName, customerDistrict, custDetailsPresent),
221
+ "memory": ConversationBufferWindowMemory(
222
+ k=3,
223
+ memory_key="history",
224
+ input_key="question"),
225
+ }
226
+ )
227
+ return chain
228
+
229
+ def createVectorDB(documents):
230
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1500, chunk_overlap=150)
231
+ texts = text_splitter.split_documents(documents)
232
+ print("All chunk List START ***********************\n\n")
233
+ pretty_print_docs(texts)
234
+ print("All chunk List END ***********************\n\n")
235
+ embeddings = getEmbeddingModel(0)
236
+ vectordb = Chroma.from_documents(texts, embeddings)
237
+ return vectordb
238
+
239
 
240
  if __name__ == '__main__':
241
  app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 7860)))
242
+