Rahulad3 commited on
Commit
911653a
·
1 Parent(s): 0768767

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -327
app.py DELETED
@@ -1,327 +0,0 @@
1
- import fitz
2
- import PyPDF2
3
- import numpy as np
4
- import gradio as gr
5
- import json
6
- import socket
7
- import os
8
- from datetime import datetime
9
- import pandas as pd
10
- from langchain.chains import RetrievalQA
11
- from langchain.llms import OpenAI
12
- from langchain.document_loaders import TextLoader
13
- from langchain.document_loaders import PyPDFLoader
14
- from langchain.indexes import VectorstoreIndexCreator
15
- from langchain.text_splitter import CharacterTextSplitter
16
- from langchain.embeddings import OpenAIEmbeddings
17
- from langchain.vectorstores import Chroma
18
- from langchain.chains import ConversationalRetrievalChain
19
- import shutil
20
- demo = gr.Blocks()
21
- options_org=[]
22
- options_bot=['','','']
23
-
24
-
25
- isExist = os.path.exists("Organizations")
26
- if(isExist==False):
27
- os.mkdir("Organizations")
28
-
29
- if(os.path.isfile('Organizationdetails.json')):
30
- #Getting organization name
31
- f = open('Organizationdetails.json', encoding='utf-8', errors='ignore')
32
- data = json.load(f,strict=False)
33
- for p_id, p_info in data.items():
34
- options_org.append(p_id)
35
- f.close()
36
-
37
-
38
- if(os.path.isfile('Botdetails.json')):
39
- #Getting organization name
40
- f1 = open('Botdetails.json')
41
- data = json.load(f1)
42
- for p_id, p_info in data.items():
43
- options_bot.append(p_id)
44
- f1.close()
45
-
46
-
47
- def Create_Organization(org_name, org_handle):
48
-
49
- o=org_handle
50
- path = o
51
- isExist = os.path.exists(path)
52
- hostname=socket.gethostname()
53
- now = datetime.now()
54
- tim=now.strftime("%d/%m/%Y %H:%M:%S")
55
- Organizationdetails={}
56
- Organization_required_details = ["Organizationame","OrganizationHandle" "Created_by", "Created_Time"]
57
- Organizationdetails[org_handle] = {}
58
- Organizationdetails[org_handle]['Organizationame']=org_name
59
- Organizationdetails[org_handle]['OrganizationHandle']=org_handle
60
- Organizationdetails[org_handle]['Created_by']=hostname
61
- Organizationdetails[org_handle]['Created_Time']=tim
62
- isfileE = os.path.isfile("Organizationdetails.json")
63
- if isfileE: #If file present "rb" and w
64
- with open('Organizationdetails.json', 'rb') as txtfile:
65
- d=json.load(txtfile)
66
- d.update(Organizationdetails)
67
- for p_id, p_info in d.items():
68
- options_org.append(p_id)
69
- with open('Organizationdetails.json', 'w') as txtfile:
70
- json.dump(d, txtfile)
71
- if not isExist: #create folder for working
72
- os.makedirs(os.path.join('Organizations', org_handle))
73
- else: #if file not present then create with 'w'
74
- with open('Organizationdetails.json', 'w') as txtfile:
75
- json.dump(Organizationdetails, txtfile)
76
- if not isExist: #create folder for working
77
- os.makedirs(os.path.join('Organizations', org_handle))
78
- return "Organization Created : "+ o
79
-
80
- def clear():
81
- return None, None, None
82
-
83
- def Create_Bot(Organizationame,Bot_Name,Bot_Handle_Name,Bot_Image,Tools,OpenAI_API_key,
84
- Initial_Message,Intro_Message,Rules):
85
-
86
- botim =Bot_Image.name
87
- print(Bot_Name)
88
- b=Bot_Handle_Name
89
- bo=Organizationame
90
- hostname=socket.gethostname()
91
- now = datetime.now()
92
- tim=now.strftime("%d/%m/%Y %H:%M:%S")
93
- Botdetails = { }
94
- Bot_required_details = ["Bot_Name", "Organizationame", "Created_by", "Created_Time","Bot_Handle_Name","Bot_Image","Tools","OpenAI_API_key",
95
- "Initial_Message","Intro_Message","Rules"]
96
- Botdetails[Bot_Handle_Name] = {}
97
- Botdetails[Bot_Handle_Name]['Bot_Name']=Bot_Name
98
- Botdetails[Bot_Handle_Name]['Organizationame']=Organizationame
99
- Botdetails[Bot_Handle_Name]['Created_by']=hostname
100
- Botdetails[Bot_Handle_Name]['Created_Time']=tim
101
- Botdetails[Bot_Handle_Name]['Bot_Handle_Name']=Bot_Handle_Name
102
- Botdetails[Bot_Handle_Name]['Bot_Image']=botim
103
- Botdetails[Bot_Handle_Name]['Tools']=Tools
104
- Botdetails[Bot_Handle_Name]['OpenAI_API_key']=OpenAI_API_key
105
- Botdetails[Bot_Handle_Name]['Initial_Message']=Initial_Message
106
- Botdetails[Bot_Handle_Name]['Intro_Message']=Intro_Message
107
- Botdetails[Bot_Handle_Name]['Rules']=Rules
108
- path = os.path.join(os.getcwd()+'\\Organizations\\', Organizationame,Bot_Name)
109
- Inputpath = os.path.join(os.getcwd()+'\\Organizations\\', Organizationame,Bot_Name,'Inputs')
110
- Outputpath = os.path.join(os.getcwd()+'\\Organizations\\', Organizationame,Bot_Name,'Outputs')
111
-
112
- isExist = os.path.exists(path)
113
-
114
- pp=os.path.join('Organizations',Organizationame+'\\Botdetails.json')
115
-
116
- isfileE = os.path.isfile(pp)
117
- if isfileE: #If file present "rb" and 'w'
118
- with open(pp, 'rb') as txtfile:
119
- d=json.load(txtfile)
120
- d.update(Botdetails)
121
- with open(pp, 'w') as txtfile:
122
- json.dump(d, txtfile)
123
- if not isExist:
124
- os.makedirs(path)
125
- os.makedirs(Inputpath)
126
- os.makedirs(Outputpath)
127
- else: #if file not present then create with 'w'
128
- with open(pp, 'w') as txtfile:
129
- json.dump(Botdetails, txtfile)
130
- if not isExist:
131
- os.makedirs(path)
132
- os.makedirs(Inputpath)
133
- os.makedirs(Outputpath)
134
- return "Bot Created : " + b +" in "+bo +" Organization "
135
-
136
-
137
-
138
-
139
- def loadbotdata(SelectOrganizationame):
140
- new=[]
141
- if(os.path.isfile(os.getcwd()+'\\Organizations\\'+SelectOrganizationame+'\\Botdetails.json')):
142
- fd = open(os.getcwd()+'\\Organizations\\'+SelectOrganizationame+'\\Botdetails.json')
143
- data = json.load(fd)
144
- for p_id, p_info in data.items():
145
- new.append(p_id)
146
- #return new
147
- return gr.update(choices=new, value=new[0])
148
-
149
-
150
- def loadbotdataasdf(SelectOrganizationame):
151
- df=[]
152
- new=[]
153
- if(os.path.isfile(os.getcwd()+'\\Organizations\\'+SelectOrganizationame+'\\Botdetails.json')):
154
- fl = open(os.getcwd()+'\\Organizations\\'+SelectOrganizationame+'\\Botdetails.json')
155
- data = json.load(fl)
156
- df = pd.DataFrame.from_dict(data, orient='columns')
157
- print (df)
158
- for p_id, p_info in data.items():
159
- new.append(p_id)
160
- return df,gr.update(choices=new, value=new[0])
161
-
162
- def upload_file(org, bot , files):
163
- file_paths = [file.name for file in files]
164
- allfiles=file_paths
165
- path = os.path.join(os.getcwd()+'\\Organizations\\', org,bot,'Inputs')
166
- os.makedirs(path, exist_ok=True)
167
-
168
- for file_path in file_paths:
169
- shutil.copy(file_path, path)
170
- return file_paths
171
-
172
-
173
- def train(files):
174
- for file in files:
175
- print(file.name)
176
- if file.name.endswith(".pdf"):
177
- pdf_document = fitz.open(file.name)
178
- documents = []
179
- for page_num in range(pdf_document.page_count):
180
- page = pdf_document.load_page(page_num)
181
- text = page.get_text()
182
- documents.append(text)
183
-
184
-
185
- output_folder = "Output"
186
- os.makedirs(output_folder, exist_ok=True)
187
- output_file_name = os.path.splitext(os.path.basename(file.name))[0]
188
- output_file_path = os.path.join(output_folder, f"{output_file_name}_page_{page_num + 1}.txt")
189
-
190
- with open(output_file_path, "w", encoding="utf-8") as output_file:
191
- for text in documents:
192
- output_file.write(text)
193
-
194
- return "Training Done"
195
- chat_history = []
196
-
197
-
198
- def construct_index(directory_path):
199
- file_paths=[]
200
- for root, directories, files in os.walk(directory_path):
201
- for file_name in files:
202
- file_path = os.path.join(root, file_name)
203
- file_paths.append(file_path)
204
-
205
-
206
-
207
- for file in file_paths:
208
- if file.endswith(".pdf"):
209
- loader = PyPDFLoader(file)
210
- documents = loader.load()
211
- return documents
212
-
213
- def chatbot(input_text):
214
- global chat_history
215
-
216
- query = input_text
217
- text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
218
- texts = text_splitter.split_documents(documents)
219
- embeddings = OpenAIEmbeddings()
220
- db = Chroma.from_documents(texts, embeddings)
221
- retriever = db.as_retriever(search_type="similarity", search_kwargs={"k":2})
222
- vectordbkwargs = {"search_distance": 0.9}
223
- qa = ConversationalRetrievalChain.from_llm(OpenAI(), retriever,return_source_documents=True)
224
- print(chat_history)
225
- if chat_history==[]:
226
- result = qa({"question": query,"chat_history": chat_history, "vectordbkwargs": {"search_distance": 0.9}})
227
- else:
228
- result = qa({"question": query, "chat_history": chat_history, "vectordbkwargs": {"search_distance": 0.9}})
229
- chat_history = [(query, result["answer"])]
230
- return result["answer"]
231
-
232
-
233
- with demo:
234
- gr.Markdown("BotRite")
235
-
236
- with gr.Tabs() :
237
- with gr.TabItem("ChatBot"):
238
- with gr.Row():
239
- SelectOrg = gr.Dropdown(options_org ,label="Select Organization" )
240
-
241
- with gr.Row():
242
- Selectbot = gr.Dropdown( label="Select Bot" ,choices=options_bot,
243
- value=options_bot[0], interactive=True)
244
- # Selectbot = gr.Radio(options_bot ,label="Select Bot")
245
-
246
- with gr.Column():
247
- query_input = gr.Textbox(lines=7, label="Enter your text")
248
- ask_button = gr.Button("Ask")
249
- text_output = gr.Text(label="Your Bot Answer")
250
- ask_button.click(fn=lambda btn: [text_output.update(chatbot(query_input.value)), chat_history.append(query_input.value)], inputs=[query_input], outputs=text_output)
251
-
252
- with gr.TabItem("Settings"):
253
- with gr.Tabs():
254
-
255
- with gr.TabItem("Create Organization:"):
256
- with gr.Row():
257
- org_name = gr.Textbox(label="Name",info="Your name / Nickname",placeholder="Enter you organization full name")
258
- org_handle = gr.Textbox(label="Handle Name",info="Your unique organization name", placeholder="Enter Organization handle name")
259
- output_org =gr.Textbox(label='Status')
260
- with gr.Row():
261
- Createorg_button = gr.Button("Create Organization")
262
- Clearorg_button = gr.Button("Clear", variant="stop")
263
-
264
- with gr.TabItem("Bot Details"):
265
- SelectOrganizationame = gr.Dropdown(options_org, label="Select Organization")
266
- with gr.Tabs():
267
- with gr.TabItem("Your Bots:"):
268
- with gr.Row():
269
- with gr.Column():
270
- #SelectOrganizationame = gr.components.Dropdown(options_org, label="Select Organization")
271
- botdf=gr.Dataframe(headers=["Bot_Name", "Organizationame", "Created_by", "Created_Time","Bot_Handle_Name","Bot_Image","Tools","OpenAI_API_key",
272
- "Initial_Message","Intro_Message","Rules"], label="Bot Details")
273
-
274
- with gr.TabItem("Create Bot:"):
275
-
276
- Organizationame =SelectOrganizationame
277
- botname = gr.Textbox(label="Bot Name",info="Your bot name / Nickname", placeholder="Enter bot full name")
278
- bothandle = gr.Textbox(label="Bot Handle Name",info="Your unique bot name" ,placeholder="Enter bot handle name")
279
- image_button = gr.File(label="Select bot image")
280
- botllm = gr.components.CheckboxGroup(['OpenAI', 'Dolly', 'Q&A Model'],label="Tools")
281
- # model = gr.components.Dropdown(Options1, label="Model")
282
- openai_key = gr.Textbox(label="You OpenAI API key", type="password" , info="Add your OpenAi Key click the link to create new or copy exsisting key from your openai account https://platform.openai.com/account/api-keys")
283
- initailsmsg = gr.Textbox(label="Initial Message", placeholder="This message will be shared by bot as intro​" , info="This message will be shared by bot as intro​")
284
- intromsg = gr.Textbox(label="Intro Message", placeholder="This message will be sent to bot as prefix to first message​", info="This message will be sent to bot as prefix to first message​")
285
- rules = gr.Textbox(label="Rules", placeholder="These rules will be sent to bot as prefix to first message (after introduction)​", info="These rules will be sent to bot as prefix to first message (after introduction)​")
286
- output_bot =gr.Textbox(label='Status')
287
- Createbot_button = gr.Button("Create Bot")
288
- with gr.TabItem("Bot Configuration"):
289
- Selectbotconfig = gr.Dropdown(label="Select Bot",choices=options_bot,
290
- value=options_bot[0], interactive=True)
291
- with gr.TabItem("Load Data"):
292
- with gr.Row():
293
- with gr.Column():
294
- Train_Fileselect_button = gr.UploadButton("Upload PDF Files", file_types=[".pdf"], file_count="multiple")
295
- file_output = gr.File()
296
- with gr.Column():
297
- Train_button = gr.Button("Train Data")
298
- Train_output =gr.Textbox(label='Status')
299
-
300
- with gr.TabItem("Chat with your bot"):
301
- with gr.Row():
302
- with gr.Column():
303
- query_input = gr.Textbox(lines=7, label="Enter your text")
304
- ask_button = gr.Button("Ask")
305
- with gr.Column():
306
- text_output=gr.Text(label="Your Bot Answer")
307
- with gr.TabItem("Deploy"):
308
- with gr.Row():
309
- archive_button = gr.Button("Archive")
310
- publish_button = gr.Button("Publish")
311
- with gr.TabItem("Logs"):
312
- with gr.Column():
313
- Selectlog = gr.Dropdown( label="Select Log")
314
- logview = gr.Text(label="Log")
315
- #def Dropdown_Org(x):
316
-
317
- SelectOrg.change(fn=loadbotdata, inputs=SelectOrg,outputs=Selectbot )
318
- SelectOrganizationame.change(fn=loadbotdataasdf, inputs=SelectOrganizationame,outputs=[botdf,Selectbotconfig])
319
- Createorg_button.click(fn=Create_Organization,inputs=[org_name, org_handle], outputs=output_org)
320
-
321
- Clearorg_button.click(lambda : [None,None,None], inputs=None, outputs=[org_name,org_handle,output_org])
322
- Createbot_button.click(fn=Create_Bot,inputs=[Organizationame, botname, bothandle,image_button,botllm,openai_key,initailsmsg,intromsg,rules], outputs=output_bot)
323
-
324
- Train_Fileselect_button.upload(upload_file,inputs=[SelectOrganizationame, Selectbotconfig,Train_Fileselect_button], outputs=[file_output])
325
- Train_button.click(fn=train,inputs=Train_Fileselect_button, outputs=Train_output)
326
-
327
- demo.launch()