-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdata_processing.py
151 lines (129 loc) · 4.86 KB
/
data_processing.py
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
from langchain_community.document_loaders import PyPDFDirectoryLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
import os
import sys
from dotenv import load_dotenv
from pinecone import Pinecone
from langchain_pinecone import PineconeVectorStore
#from langchain_community.embeddings import GooglePalmEmbeddings
import os
#from langchain_community.llms import GooglePalm
from langchain_google_genai import GoogleGenerativeAIEmbeddings
from langchain_google_genai import GoogleGenerativeAI
from langchain.chains import RetrievalQA
from langchain.chains import create_retrieval_chain
from langchain.chains.combine_documents import create_stuff_documents_chain
from langchain.prompts import PromptTemplate
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationalRetrievalChain
import logging
logging.basicConfig(level=logging.INFO)
from langchain_core.prompts import ChatPromptTemplate
from langchain_groq import ChatGroq
from langchain_mistralai import MistralAIEmbeddings
from langchain_core.prompts import PromptTemplate
from langchain.prompts import (
ChatPromptTemplate,
HumanMessagePromptTemplate,
SystemMessagePromptTemplate,
)
#os.environ['HF_TOKEN'] =os.getenv("HF_TOKEN")
load_dotenv(override=True)
#print("HF_TOKEN:",os.getenv("HF_TOKEN"))
def pdf_processing(UPLOAD_DIR):
try:
loader=PyPDFDirectoryLoader(UPLOAD_DIR)
data=loader.load()
text_splitter=RecursiveCharacterTextSplitter(
chunk_size=500,
chunk_overlap=20,
)
text_chunks = text_splitter.split_documents(data)
return text_chunks
except:
return ValueError
def del_vectors(model,session_id):
if(model=="GOOGLE"):
index_name='rag-cpdf'
else:
index_name='rag-mis'
pc = Pinecone(
api_key=os.getenv("PINECONE_API_KEY")
)
index=pc.Index(index_name)
index_stats=index.describe_index_stats()
if session_id in index_stats['namespaces'].keys():
index.delete(delete_all=True,namespace=session_id)
print("VECTOR FOUND:DELETED")
else:
print("NO VECTORSTORE")
def vectorise(text_chunks,model,session_id):
if(model=="GOOGLE"):
embeddings=GoogleGenerativeAIEmbeddings(model="models/embedding-001")
index_name='rag-cpdf'
else:
load_dotenv(override=True)
embeddings = MistralAIEmbeddings(model = "mistral-embed",api_key=os.getenv("MINSTRAL_AI_API_KEY"))
index_name='rag-mis'
pc = Pinecone(
api_key=os.getenv("PINECONE_API_KEY")
)
# index=pc.Index(index_name)
# index_stats=index.describe_index_stats()
# if "current" in index_stats['namespaces'].keys():
# index.delete(delete_all=True,namespace='current')
#logging.info("**** CLEARED SPACE ****")
vectorstore = PineconeVectorStore.from_documents(
text_chunks,
index_name=index_name,
embedding=embeddings,
namespace=session_id
)
return vectorstore
#Depricated
# print(index)
#index.delete(delete_all=True,namespace='real')
#pc_info=index.describe_index_stats(namespace="real")
# for i, t in zip(range(len(text_chunks)), text_chunks):
# query_result = embeddings.embed_query(t.page_content)
# index.upsert(
# vectors=[
# {
# "id": str(i),
# "values": query_result,
# "metadata": {"text":str(text_chunks[i].page_content)}
# }
# ],
# namespace="real"
# )
def create_conversation(vectorstore,model):
try:
if(model=="GOOGLE"):
llm = GoogleGenerativeAI(model="gemini-1.5-flash", temperature=0.1)
else:
llm = ChatGroq(temperature=0.3, model_name="mixtral-8x7b-32768")
# system_message_prompt = SystemMessagePromptTemplate.from_template(
# "You have to answer the asked questined , if you dont know the answers, say I apologise I'm now able to answer that. The context you need is:{context}"
# )
# human_message_prompt = HumanMessagePromptTemplate.from_template(
# "{question}"
# )
# messages = [
# system_message_prompt,
# human_message_prompt
# ]
# qa_prompt = ChatPromptTemplate.from_messages( messages )
memory=ConversationBufferMemory(
memory_key='chat_history',return_messages=True)
conversation_chain=ConversationalRetrievalChain.from_llm(
llm=llm,
retriever=vectorstore.as_retriever(),
memory=memory,
)
return conversation_chain
except Exception as e:
return KeyError
def chat(conversation,question):
response=conversation({'question':question})
print(response)
return response