Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import os
|
| 3 |
+
import re
|
| 4 |
+
import streamlit as st
|
| 5 |
+
import time
|
| 6 |
+
|
| 7 |
+
sys.path.append(os.path.abspath("."))
|
| 8 |
+
from langchain.chains import ConversationalRetrievalChain
|
| 9 |
+
from langchain.memory import ConversationBufferMemory
|
| 10 |
+
from langchain.llms import OpenAI
|
| 11 |
+
from langchain.document_loaders import UnstructuredPDFLoader
|
| 12 |
+
from langchain.vectorstores import Chroma
|
| 13 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
| 14 |
+
from langchain.text_splitter import NLTKTextSplitter
|
| 15 |
+
from patent_downloader import PatentDownloader
|
| 16 |
+
|
| 17 |
+
PERSISTED_DIRECTORY = "."
|
| 18 |
+
|
| 19 |
+
# Fetch API key securely from the environment
|
| 20 |
+
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 21 |
+
if not OPENAI_API_KEY:
|
| 22 |
+
st.error("Critical Error: OpenAI API key not found in the environment variables. Please configure it.")
|
| 23 |
+
st.stop()
|
| 24 |
+
|
| 25 |
+
def load_docs(document_path):
|
| 26 |
+
loader = UnstructuredPDFLoader(document_path)
|
| 27 |
+
documents = loader.load()
|
| 28 |
+
text_splitter = NLTKTextSplitter(chunk_size=1000)
|
| 29 |
+
return text_splitter.split_documents(documents)
|
| 30 |
+
|
| 31 |
+
def already_indexed(vectordb, file_name):
|
| 32 |
+
indexed_sources = set(
|
| 33 |
+
x["source"] for x in vectordb.get(include=["metadatas"])["metadatas"]
|
| 34 |
+
)
|
| 35 |
+
return file_name in indexed_sources
|
| 36 |
+
|
| 37 |
+
def load_chain(file_name=None):
|
| 38 |
+
loaded_patent = st.session_state.get("LOADED_PATENT")
|
| 39 |
+
|
| 40 |
+
vectordb = Chroma(
|
| 41 |
+
persist_directory=PERSISTED_DIRECTORY,
|
| 42 |
+
embedding_function=HuggingFaceEmbeddings(),
|
| 43 |
+
)
|
| 44 |
+
if loaded_patent == file_name or already_indexed(vectordb, file_name):
|
| 45 |
+
st.write("Already indexed")
|
| 46 |
+
else:
|
| 47 |
+
vectordb.delete_collection()
|
| 48 |
+
docs = load_docs(file_name)
|
| 49 |
+
st.write("Length: ", len(docs))
|
| 50 |
+
|
| 51 |
+
vectordb = Chroma.from_documents(
|
| 52 |
+
docs, HuggingFaceEmbeddings(), persist_directory=PERSISTED_DIRECTORY
|
| 53 |
+
)
|
| 54 |
+
vectordb.persist()
|
| 55 |
+
st.session_state["LOADED_PATENT"] = file_name
|
| 56 |
+
|
| 57 |
+
memory = ConversationBufferMemory(
|
| 58 |
+
memory_key="chat_history",
|
| 59 |
+
return_messages=True,
|
| 60 |
+
input_key="question",
|
| 61 |
+
output_key="answer",
|
| 62 |
+
)
|
| 63 |
+
return ConversationalRetrievalChain.from_llm(
|
| 64 |
+
OpenAI(temperature=0, openai_api_key=OPENAI_API_KEY),
|
| 65 |
+
vectordb.as_retriever(search_kwargs={"k": 3}),
|
| 66 |
+
return_source_documents=False,
|
| 67 |
+
memory=memory,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
def extract_patent_number(url):
|
| 71 |
+
pattern = r"/patent/([A-Z]{2}\d+)"
|
| 72 |
+
match = re.search(pattern, url)
|
| 73 |
+
return match.group(1) if match else None
|
| 74 |
+
|
| 75 |
+
def download_pdf(patent_number):
|
| 76 |
+
patent_downloader = PatentDownloader()
|
| 77 |
+
patent_downloader.download(patent=patent_number)
|
| 78 |
+
return f"{patent_number}.pdf"
|
| 79 |
+
|
| 80 |
+
if __name__ == "__main__":
|
| 81 |
+
st.set_page_config(
|
| 82 |
+
page_title="Patent Chat: Google Patents Chat Demo",
|
| 83 |
+
page_icon="π",
|
| 84 |
+
layout="wide",
|
| 85 |
+
initial_sidebar_state="expanded",
|
| 86 |
+
)
|
| 87 |
+
st.header("π Patent Chat: Google Patents Chat Demo")
|
| 88 |
+
|
| 89 |
+
# Allow user to input the Google patent link
|
| 90 |
+
patent_link = st.text_input("Enter Google Patent Link:", key="PATENT_LINK")
|
| 91 |
+
|
| 92 |
+
if not patent_link:
|
| 93 |
+
st.warning("Please enter a Google patent link to proceed.")
|
| 94 |
+
st.stop()
|
| 95 |
+
else:
|
| 96 |
+
st.session_state["patent_link_configured"] = True
|
| 97 |
+
|
| 98 |
+
patent_number = extract_patent_number(patent_link)
|
| 99 |
+
if not patent_number:
|
| 100 |
+
st.error("Invalid patent link format. Please provide a valid Google patent link.")
|
| 101 |
+
st.stop()
|
| 102 |
+
|
| 103 |
+
st.write("Patent number: ", patent_number)
|
| 104 |
+
|
| 105 |
+
pdf_path = f"{patent_number}.pdf"
|
| 106 |
+
if os.path.isfile(pdf_path):
|
| 107 |
+
st.write("File already downloaded.")
|
| 108 |
+
else:
|
| 109 |
+
st.write("Downloading patent file...")
|
| 110 |
+
pdf_path = download_pdf(patent_number)
|
| 111 |
+
st.write("File downloaded.")
|
| 112 |
+
|
| 113 |
+
chain = load_chain(pdf_path)
|
| 114 |
+
|
| 115 |
+
if "messages" not in st.session_state:
|
| 116 |
+
st.session_state["messages"] = [
|
| 117 |
+
{"role": "assistant", "content": "How can I help you?"}
|
| 118 |
+
]
|
| 119 |
+
|
| 120 |
+
for message in st.session_state.messages:
|
| 121 |
+
with st.chat_message(message["role"]):
|
| 122 |
+
st.markdown(message["content"])
|
| 123 |
+
|
| 124 |
+
if user_input := st.chat_input("What is your question?"):
|
| 125 |
+
st.session_state.messages.append({"role": "user", "content": user_input})
|
| 126 |
+
with st.chat_message("user"):
|
| 127 |
+
st.markdown(user_input)
|
| 128 |
+
|
| 129 |
+
with st.chat_message("assistant"):
|
| 130 |
+
message_placeholder = st.empty()
|
| 131 |
+
full_response = ""
|
| 132 |
+
|
| 133 |
+
with st.spinner("CHAT-BOT is at Work ..."):
|
| 134 |
+
assistant_response = chain({"question": user_input})
|
| 135 |
+
for chunk in assistant_response["answer"].split():
|
| 136 |
+
full_response += chunk + " "
|
| 137 |
+
time.sleep(0.05)
|
| 138 |
+
message_placeholder.markdown(full_response + "β")
|
| 139 |
+
st.session_state.messages.append(
|
| 140 |
+
{"role": "assistant", "content": full_response}
|
| 141 |
+
)
|