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