saswatdas123 commited on
Commit
fe5256f
·
verified ·
1 Parent(s): 1d087ef

Upload 6 files

Browse files
pages/ChatPDF_Ingestion.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File Selection Drop Down
2
+ import streamlit as st
3
+ import os
4
+ from langchain.document_loaders import PyPDFLoader
5
+ from langchain_community.document_loaders import UnstructuredFileLoader, DirectoryLoader
6
+ from langchain.text_splitter import CharacterTextSplitter
7
+ from langchain.embeddings import HuggingFaceEmbeddings
8
+ from langchain.llms import HuggingFaceHub
9
+ from langchain.vectorstores import Chroma
10
+ from langchain_community.vectorstores import Chroma
11
+ from langchain.chains import ConversationalRetrievalChain
12
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
13
+ import sys,yaml,Utilities as ut
14
+
15
+
16
+ st.set_page_config(page_title="ChatPDF Ingestion", page_icon="📈")
17
+
18
+ def load_pdf():
19
+
20
+ # Load the pdf file and split it into smaller chunks
21
+ initdict={}
22
+ initdict = ut.get_tokens()
23
+ hf_token = initdict["hf_token"]
24
+ embedding_model_id = initdict["embedding_model"]
25
+ chromadbpath = initdict["chatPDF_chroma_db"]
26
+
27
+ embeddings = HuggingFaceEmbeddings(model_name=embedding_model_id)
28
+
29
+ loader = DirectoryLoader('data/', glob="**/*.pdf", show_progress=True, loader_cls=UnstructuredFileLoader)
30
+
31
+ documents = loader.load()
32
+ #print (len(documents))
33
+
34
+ # Split the documents into smaller chunks
35
+
36
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=700, chunk_overlap=70)
37
+ texts = text_splitter.split_documents(documents)
38
+
39
+ #Using Chroma vector database to store and retrieve embeddings of our text
40
+ db = Chroma.from_documents(texts, embeddings, persist_directory=chromadbpath)
41
+ return db
42
+
43
+ st.title("PatentGuru - Document Ingestion ")
44
+ # Main chat form
45
+ with st.form("chat_form"):
46
+ #query = st.text_input("You: ")
47
+ submit_button = st.form_submit_button("Upload..")
48
+
49
+ if submit_button:
50
+ load_pdf()
51
+
52
+ st.write ("Uploaded successfully")
pages/ChatPDF_Reader.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # import required libraries
2
+ from langchain.document_loaders import PyPDFLoader
3
+ from langchain.text_splitter import CharacterTextSplitter
4
+ from langchain.embeddings import HuggingFaceEmbeddings
5
+ from langchain.llms import HuggingFaceHub
6
+ from langchain.vectorstores import Chroma
7
+ from langchain_community.vectorstores import Chroma
8
+ from langchain.chains import ConversationalRetrievalChain
9
+ #from langchain.text_splitter import NLTKTextSplitter
10
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
11
+
12
+ import streamlit as st
13
+ import sys,yaml,Utilities as ut
14
+
15
+ def get_data(query):
16
+ chat_history = []
17
+ initdict={}
18
+ initdict = ut.get_tokens()
19
+ hf_token = initdict["hf_token"]
20
+ embedding_model_id = initdict["embedding_model"]
21
+ chromadbpath = initdict["chatPDF_chroma_db"]
22
+ llm_repo_id = initdict["llm_repoid"]
23
+
24
+
25
+ # We will use HuggingFace embeddings
26
+ embeddings = HuggingFaceEmbeddings(model_name=embedding_model_id)
27
+
28
+ #retriever = db.as_retriever(search_type="mmr", search_kwargs={'k': 1})
29
+ # load from disk
30
+ db = Chroma(persist_directory=chromadbpath, embedding_function=embeddings)
31
+ retriever = db.as_retriever(search_type="mmr", search_kwargs={'k': 2})
32
+
33
+ llm = HuggingFaceHub(huggingfacehub_api_token=hf_token,
34
+ repo_id=llm_repo_id, model_kwargs={"temperature":0.2, "max_new_tokens":50})
35
+
36
+ # Create the Conversational Retrieval Chain
37
+ qa_chain = ConversationalRetrievalChain.from_llm(llm, retriever,return_source_documents=True)
38
+ result = qa_chain({'question': query, 'chat_history': chat_history})
39
+ chat_history.append(result)
40
+ print('Answer: ' + result['answer'] + '\n')
41
+ print (result)
42
+ return result['answer']
43
+
44
+ st.title("PatentGuru Document Reader")
45
+
46
+ # Main chat form
47
+ with st.form("chat_form"):
48
+ query = st.text_input("Chat with PDF: ")
49
+ clear_history = st.checkbox('Clear Chat History')
50
+ submit_button = st.form_submit_button("Send")
51
+
52
+ if submit_button:
53
+ if clear_history:
54
+ st.write("Cleared previous chat history")
55
+
56
+ response = get_data(query)
57
+ if len(response)>0:
58
+ response = str(response.partition("Answer: ")[-1])
59
+ else: response = "No results"
60
+
61
+ # write results
62
+ st.write (response)
63
+
64
+
pages/Intelligent Chatbot.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_community.llms import HuggingFaceEndpoint
2
+ import streamlit as st, Utilities as ut
3
+ from langchain import hub
4
+ from langchain.agents import AgentExecutor, create_react_agent, load_tools
5
+ from langchain_community.chat_models.huggingface import ChatHuggingFace
6
+ #from langchain_openai import OpenAI
7
+
8
+ from langchain_community.callbacks.streamlit import (
9
+ StreamlitCallbackHandler,
10
+ )
11
+
12
+ st_callback = StreamlitCallbackHandler(st.container())
13
+
14
+ initdict={}
15
+ initdict = ut.get_tokens()
16
+ hf_token = initdict["hf_token"]
17
+ reactstyle_prompt = initdict["reactstyle_prompt"]
18
+ serpapi_api_key = initdict["serpapi_api_key"]
19
+ llm_repoid = initdict["llm_repoid"]
20
+
21
+ llm = HuggingFaceEndpoint(repo_id=llm_repoid,huggingfacehub_api_token=hf_token,temperature=0.9,verbose=True)
22
+
23
+ tools = load_tools(["serpapi"],llm=llm,serpapi_api_key=serpapi_api_key)
24
+ prompt = hub.pull(reactstyle_prompt)
25
+ agent = create_react_agent(llm, tools, prompt)
26
+ agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True,handle_parsing_errors=True)
27
+
28
+ chat_model = ChatHuggingFace(llm=llm)
29
+ chat_model_with_stop = chat_model.bind(stop=["\nObservation"])
30
+
31
+ st.title("PatentGuru - Intelligent Chatbot")
32
+
33
+ if prompt := st.chat_input():
34
+ st.chat_message("user").write(prompt)
35
+ with st.chat_message("assistant"):
36
+ st_callback = StreamlitCallbackHandler(st.container())
37
+
38
+ response = agent_executor.invoke(
39
+ {"input": prompt}, {"callbacks": [st_callback], "handle_parsing_errors":True}
40
+ )
41
+ st.write(response["output"])
pages/Patent_Ingestion.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # import required libraries
2
+ from langchain.embeddings import HuggingFaceEmbeddings
3
+ from langchain.llms import HuggingFaceHub
4
+ #from langchain.vectorstores import Chroma
5
+ from langchain_community.vectorstores import Chroma
6
+ import tensorflow_datasets as tfds
7
+ from sentence_transformers import SentenceTransformer
8
+ from datasets import load_dataset
9
+ from transformers import BartForConditionalGeneration, BartTokenizer
10
+ import textwrap
11
+ import chromadb
12
+ import streamlit as st
13
+ import sys,yaml
14
+ import uuid
15
+ import Utilities as ut
16
+
17
+
18
+ def text_summarizer(text):
19
+ initdict = ut.get_tokens()
20
+ BART_Model_Name = initdict["BART_model"]
21
+ #model_name = "facebook/bart-large-cnn"
22
+ model = BartForConditionalGeneration.from_pretrained(BART_Model_Name)
23
+ tokenizer = BartTokenizer.from_pretrained(BART_Model_Name)
24
+
25
+ inputs = tokenizer.encode("summarize: " + text, return_tensors="pt", max_length=1024, truncation=True)
26
+ summary_ids = model.generate(inputs, max_length=150, min_length=50, length_penalty=2.0, num_beams=4, early_stopping=True)
27
+
28
+ summary = tokenizer.decode(summary_ids[0], skip_special_tokens=True)
29
+ formatted_summary = "\n".join(textwrap.wrap(summary, width=80))
30
+
31
+ return formatted_summary
32
+
33
+ def load_patentBIGdata():
34
+
35
+ initdict={}
36
+ initdict = ut.get_tokens()
37
+
38
+ embedding_model_id = initdict["embedding_model"]
39
+ chromadbpath = initdict["dataset_chroma_db"]
40
+ chromadbcollname = initdict["dataset_chroma_db_collection_name"]
41
+
42
+ embedding_model = SentenceTransformer(embedding_model_id)
43
+
44
+ chroma_client = chromadb.PersistentClient(path= chromadbpath)
45
+
46
+ collection = chroma_client.get_or_create_collection(name=chromadbcollname)
47
+
48
+
49
+ # Load the Big patent dataset
50
+ ds = load_dataset("big_patent", "a", split="validation[:1%]",trust_remote_code=True)
51
+
52
+ for record in ds.take(10):
53
+ abstract, desc = record ["abstract"], record["description"]
54
+ # Summarize to 150 words
55
+ abstract = text_summarizer(abstract)
56
+ textembeddings = embedding_model.encode(abstract).tolist()
57
+
58
+ genguid=str(uuid.uuid4())
59
+ #take 8 characters
60
+ uniqueid = genguid[:8]
61
+ # Now we will store the expert explanation field of first 10 questions from dataset into collection.
62
+ collection.add(
63
+ documents=[
64
+ abstract
65
+ ],
66
+ embeddings=[textembeddings],
67
+ ids=[uniqueid]
68
+ )
69
+ #print(abstract)
70
+
71
+ st.title("Patent Ingestion - BIG Patent")
72
+
73
+ # Main chat form
74
+ with st.form("chat_form"):
75
+
76
+ submit_button = st.form_submit_button("Upload BIG Patent data...")
77
+
78
+ if submit_button:
79
+ load_patentBIGdata()
80
+ response = "BIG Patent dataset was successfully loaded"
81
+
82
+ st.write (response)
83
+
84
+
pages/Patent_Search.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # import required libraries
2
+ from langchain.embeddings import HuggingFaceEmbeddings
3
+ from langchain.llms import HuggingFaceHub
4
+ from langchain_community.vectorstores import Chroma
5
+ from sentence_transformers import SentenceTransformer
6
+ from langchain_core.prompts import ChatPromptTemplate
7
+ from langchain import PromptTemplate
8
+
9
+ import streamlit as st
10
+ import sys,yaml
11
+ import chromadb
12
+ import Utilities as ut
13
+
14
+ hf_token=""
15
+ chromadbpath=""
16
+ chromadbcollname=""
17
+ embedding_model_id=""
18
+ llm_repo_id=""
19
+ #embeddings=None
20
+ #chroma_client=None
21
+
22
+
23
+ def filterdistance(distcoll):
24
+ myemptydict={}
25
+ if len(distcoll) < 0:myemptydict
26
+ for distances in distcoll['distances']:
27
+ for distance in distances:
28
+ if distance<50: return distcoll
29
+ else: return myemptydict
30
+
31
+ def get_collections(query):
32
+ #myemptydict={}
33
+ result=""
34
+ initdict={}
35
+ initdict = ut.get_tokens()
36
+ hf_token = initdict["hf_token"]
37
+ embedding_model_id = initdict["embedding_model"]
38
+ chromadbpath = initdict["dataset_chroma_db"]
39
+ chromadbcollname = initdict["dataset_chroma_db_collection_name"]
40
+ llm_repo_id = initdict["llm_repoid"]
41
+
42
+ embedding_model = SentenceTransformer(embedding_model_id)
43
+ #print(chromadbpath)
44
+ #print(chromadbcollname)
45
+ chroma_client = chromadb.PersistentClient(path = chromadbpath)
46
+ collection = chroma_client.get_collection(name = chromadbcollname)
47
+
48
+ #collection = chroma_client.get_or_create_collection(name=chromadbcollname)
49
+ query_vector = embedding_model.encode(query).tolist()
50
+ output = collection.query(
51
+ query_embeddings=[query_vector],
52
+ n_results=1,
53
+ #where={"distances": "is_less_than_1"},
54
+ include=['documents','distances'],
55
+
56
+ )
57
+ #Filter for distances
58
+ output = filterdistance(output)
59
+
60
+ if len(output)>0:
61
+ template = """
62
+ <s>[INST] <<SYS>>
63
+ Act as a patent assistant who is helping summarize and neatly format the results for better readability. Ensure the output is gramatically correct and easily understandable
64
+ <</SYS>>
65
+
66
+ {text} [/INST]
67
+ """
68
+ #Build the prompt template
69
+ prompt = PromptTemplate(
70
+ input_variables=["text"],
71
+ template=template,
72
+ )
73
+ text = output
74
+
75
+ llm = HuggingFaceHub(huggingfacehub_api_token=hf_token,
76
+ repo_id=llm_repo_id, model_kwargs={"temperature":0.2, "max_new_tokens":50})
77
+
78
+ result = llm.invoke(prompt.format(text=text))
79
+ print (result)
80
+ return result
81
+
82
+ return output
83
+ # extract and apply distance condition
84
+
85
+ st.title("BIG Patent Search")
86
+
87
+ # Main chat form
88
+ with st.form("chat_form"):
89
+ query = st.text_input("Enter the abstract search for similar patents: ")
90
+ #LLM_Summary = st.checkbox('Summarize results with LLM')
91
+ submit_button = st.form_submit_button("Send")
92
+
93
+ if submit_button:
94
+ st.write("Fetching results..\n")
95
+ results = get_collections(query)
96
+
97
+ if len(results)>0:
98
+ #docids = results["documents"]
99
+ response = "There are existing patents related to - "
100
+ substring = results.partition("[/ASSistant]")[-1]
101
+ if len(substring)>0:
102
+ response = response + str(substring)
103
+ else:
104
+ response = response + results.partition("[/INST]")[-1]
105
+
106
+ else: response = "No results"
107
+
108
+ st.write (response)
109
+
pages/Prompt_Engineer.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from langchain.callbacks.manager import CallbackManager
3
+ from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
4
+ from langchain import PromptTemplate
5
+ from langchain_community.llms import LlamaCpp
6
+ #from langchain.chains import RetrievalQA
7
+ #from langchain_community.embeddings import SentenceTransformerEmbeddings
8
+
9
+ from langchain_core.prompts import ChatPromptTemplate
10
+ from langchain.callbacks.base import BaseCallbackHandler
11
+
12
+ #from langchain.schema import HumanMessage
13
+
14
+ import os
15
+ import json,streamlit as st
16
+ from pathlib import Path
17
+
18
+ class StreamHandler(BaseCallbackHandler):
19
+ def __init__(self, container, initial_text=""):
20
+ self.container = container
21
+ self.text=initial_text
22
+ def on_llm_new_token(self, token: str, **kwargs) -> None:
23
+ # "/" is a marker to show difference
24
+ # you don't need it
25
+ #self.text+=token+"/"
26
+ self.text+=token
27
+ self.container.markdown(self.text)
28
+
29
+ st.title("Prompt Engineer")
30
+
31
+ # Main chat form
32
+ with st.form("chat_form"):
33
+ query = st.text_input("Enter the topic you want to generate prompt for?: ")
34
+ #LLM_Summary = st.checkbox('Summarize results with LLM')
35
+ submit_button = st.form_submit_button("Send")
36
+
37
+
38
+ template = """
39
+ <s>[INST] <<SYS>>
40
+ Act as a patent advisor by providing subject matter expertise on any topic. Provide detailed and elaborate answers
41
+ <</SYS>>
42
+
43
+ {text} [/INST]
44
+ """
45
+ response=""
46
+ prompt = PromptTemplate(
47
+ input_variables=["text"],
48
+ template=template,
49
+ )
50
+ text = "Help me create a good prompt for the following: Information that is needed to file a US patent application for " + query
51
+ #print(prompt.format(text=query))
52
+
53
+ # Callbacks support token-wise streaming
54
+ callback_manager = CallbackManager([StreamingStdOutCallbackHandler()])
55
+
56
+ #model_path = "C:\Rajesh\AI-ML-Training\LLM\llama-2-7b.Q4_K_M.gguf"\
57
+ model_path = "C:\Rajesh\AI-ML-Training\LLM\zephyr-7b-beta.Q5_K_S.gguf"
58
+ chat_box=st.empty()
59
+ stream_handler = StreamHandler(chat_box)
60
+
61
+ llm = LlamaCpp(
62
+ model_path=model_path,
63
+ temperature=0.8,
64
+ max_tokens=500,
65
+ top_p=1,
66
+ #streaming=True,
67
+ #callback_manager=callback_manager,
68
+ callback_manager = [stream_handler],
69
+ verbose=True, # Verbose is required to pass to the callback manager
70
+ )
71
+
72
+ if submit_button:
73
+ #st.write("Fetching results..\n")
74
+ output = llm.invoke(prompt.format(text=text))
75
+ #response = response+output
76
+ #st.write(response)
77
+ #response = output([HumanMessage(content=query)])
78
+ #llm_response = output.content
79
+ #st.markdown(output)
80
+
81
+
82
+
83
+
84
+
85
+