Spaces:
Runtime error
Runtime error
File size: 6,310 Bytes
74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d b29437f 74f3f5d 2a75dcb 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 94d4a49 74f3f5d 6c64b74 |
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 |
import os
import openai
os.environ["TOKENIZERS_PARALLELISM"] = "false"
os.environ["OPENAI_API_KEY"]
def save_docs(docs):
import shutil
import os
output_dir = "/home/user/app/docs/"
if os.path.exists(output_dir):
shutil.rmtree(output_dir)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for doc in docs:
shutil.copy(doc.name, output_dir)
return "Successful!"
def process_docs():
from langchain.document_loaders import PyPDFLoader
from langchain.document_loaders import DirectoryLoader
from langchain.document_loaders import TextLoader
from langchain.document_loaders import Docx2txtLoader
from langchain.document_loaders.csv_loader import CSVLoader
from langchain.document_loaders import UnstructuredExcelLoader
from langchain.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings
from langchain.text_splitter import RecursiveCharacterTextSplitter
loader1 = DirectoryLoader(
"/home/user/app/docs/", glob="./*.pdf", loader_cls=PyPDFLoader
)
document1 = loader1.load()
loader2 = DirectoryLoader(
"/home/user/app/docs/", glob="./*.txt", loader_cls=TextLoader
)
document2 = loader2.load()
loader3 = DirectoryLoader(
"/home/user/app/docs/", glob="./*.docx", loader_cls=Docx2txtLoader
)
document3 = loader3.load()
loader4 = DirectoryLoader(
"/home/user/app/docs/", glob="./*.csv", loader_cls=CSVLoader
)
document4 = loader4.load()
loader5 = DirectoryLoader(
"/home/user/app/docs/", glob="./*.xlsx", loader_cls=UnstructuredExcelLoader
)
document5 = loader5.load()
document1.extend(document2)
document1.extend(document3)
document1.extend(document4)
document1.extend(document5)
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=1000, chunk_overlap=200, length_function=len
)
docs = text_splitter.split_documents(document1)
embeddings = OpenAIEmbeddings()
docs_db = FAISS.from_documents(docs, embeddings)
docs_db.save_local("/home/user/app/docs_db/")
return "Successful!"
global agent
def create_agent():
from langchain_openai import ChatOpenAI
from langchain.chains.conversation.memory import ConversationSummaryBufferMemory
from langchain.chains import ConversationChain
global agent
llm = ChatOpenAI(model_name="gpt-3.5-turbo-16k")
memory = ConversationSummaryBufferMemory(llm=llm, max_token_limit=1000)
agent = ConversationChain(llm=llm, memory=memory, verbose=True)
return "Successful!"
def formatted_response(docs, question, response, state):
formatted_output = response + "\n\nSources"
for i, doc in enumerate(docs):
source_info = doc.metadata.get("source", "Unknown source")
page_info = doc.metadata.get("page", None)
doc_name = source_info.split("/")[-1].strip()
if page_info is not None:
formatted_output += f"\n{doc_name}\tpage no {page_info}"
else:
formatted_output += f"\n{doc_name}"
state.append((question, formatted_output))
return state, state
def search_docs(prompt, question, state):
from langchain_openai import OpenAIEmbeddings
from langchain.vectorstores import FAISS
from langchain.callbacks import get_openai_callback
global agent
agent = agent
state = state or []
embeddings = OpenAIEmbeddings()
docs_db = FAISS.load_local(
"/home/user/app/docs_db/", embeddings, allow_dangerous_deserialization=True
)
docs = docs_db.similarity_search(question)
prompt += "\n\n"
prompt += question
prompt += "\n\n"
prompt += str(docs)
with get_openai_callback() as cb:
response = agent.predict(input=prompt)
print(cb)
return formatted_response(docs, question, response, state)
import gradio as gr
css = """
.col{
max-width: 75%;
margin: 0 auto;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
"""
with gr.Blocks(css=css) as demo:
gr.Markdown("## <center>Your AI Medical Assistant</center>")
with gr.Tab("Your AI Medical Assistant"):
with gr.Column(elem_classes="col"):
with gr.Tab("Upload and Process Documents"):
with gr.Column():
docs_upload_input = gr.Files(label="Upload File(s)")
docs_upload_button = gr.Button("Upload")
docs_upload_output = gr.Textbox(label="Output")
docs_process_button = gr.Button("Process")
docs_process_output = gr.Textbox(label="Output")
create_agent_button = gr.Button("Create Agent")
create_agent_output = gr.Textbox(label="Output")
gr.ClearButton(
[
docs_upload_input,
docs_upload_output,
docs_process_output,
create_agent_output,
]
)
with gr.Tab("Query Documents"):
with gr.Column():
docs_prompt_input = gr.Textbox(label="Custom Prompt")
docs_chatbot = gr.Chatbot(label="Chats")
docs_state = gr.State()
docs_search_input = gr.Textbox(label="Question")
docs_search_button = gr.Button("Search")
gr.ClearButton([docs_prompt_input, docs_search_input])
#########################################################################################################
docs_upload_button.click(
save_docs, inputs=docs_upload_input, outputs=docs_upload_output
)
docs_process_button.click(process_docs, inputs=None, outputs=docs_process_output)
create_agent_button.click(create_agent, inputs=None, outputs=create_agent_output)
docs_search_button.click(
search_docs,
inputs=[docs_prompt_input, docs_search_input, docs_state],
outputs=[docs_chatbot, docs_state],
)
#########################################################################################################
demo.queue()
demo.launch()
|