taaha3244 commited on
Commit
61d1032
1 Parent(s): 8999dd1

Upload main.py

Browse files
Files changed (1) hide show
  1. main.py +155 -0
main.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+ from langchain_community.document_loaders import PyPDFLoader
4
+ from langchain_community.llms import OpenAI
5
+ from langchain.chains.summarize import load_summarize_chain
6
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
7
+ from langchain import hub
8
+ from langchain_community.vectorstores import Qdrant
9
+ from qdrant_client import QdrantClient
10
+ from langchain_openai import OpenAIEmbeddings
11
+ from langchain_openai import ChatOpenAI
12
+ from langchain_core.output_parsers import StrOutputParser
13
+ from langchain_core.runnables import RunnablePassthrough
14
+ from langchain.prompts import PromptTemplate
15
+
16
+ load_dotenv()
17
+
18
+ def summarize_pdf_document(file_path, openai_api_key):
19
+ # Load PDF document
20
+ loader = PyPDFLoader(file_path)
21
+ documents = loader.load()
22
+
23
+ # Split text from documents
24
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=2000, chunk_overlap=500)
25
+ docs = text_splitter.split_documents(documents)
26
+
27
+ # Set up OpenAI client
28
+ llm = OpenAI(temperature=0, openai_api_key=openai_api_key)
29
+
30
+ # Load the summarization chain process
31
+ summary_chain = load_summarize_chain(llm=llm, chain_type='map_reduce')
32
+
33
+ # Invoke the summarization process
34
+ output = summary_chain.run(docs)
35
+
36
+ return output
37
+
38
+ def embed_document_data(documents):
39
+ """Load, process, and embed a PDF file into a vector store.
40
+
41
+ Args:
42
+ file_path (str): Path to the PDF file to be processed and embedded.
43
+ """
44
+
45
+
46
+ # Split text from documents into smaller chunks
47
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=2000, chunk_overlap=400)
48
+ texts = text_splitter.split_documents(documents)
49
+
50
+ # Set up embeddings model with OpenAI
51
+ openai_api_key = os.getenv("OPENAI_API_KEY")
52
+ embeddings_model = OpenAIEmbeddings(model='text-embedding-3-small', openai_api_key=openai_api_key)
53
+
54
+ # Configure Qdrant client
55
+ qdrant_url = os.getenv("QDRANT_URL")
56
+ qdrant_api_key = os.getenv("QDRANT_API_KEY")
57
+ client = QdrantClient(location=qdrant_url, api_key=qdrant_api_key)
58
+
59
+ # Initialize Qdrant storage with the client and embedding model
60
+ qdrant = Qdrant(client=client, collection_name="Lex-v1", embeddings=embeddings_model)
61
+
62
+ # Add documents to the Qdrant collection
63
+ qdrant.add_documents(texts)
64
+
65
+
66
+ def retrieve_documents(query: str):
67
+ """
68
+ Takes a user query as input and returns a response using a Retrieval-Augmented Generation (RAG) flow
69
+ incorporating langchain, Qdrant, and OpenAI.
70
+
71
+ Args:
72
+ query (str): The user's question to be answered.
73
+
74
+ """
75
+ try:
76
+ # Setup
77
+ qdrant_url = os.getenv('QDRANT_URL')
78
+ qdrant_api_key = os.getenv("QDRANT_API_KEY")
79
+ openai_api_key=os.getenv('OPENAI_API_KEY')
80
+
81
+ embeddings_model = OpenAIEmbeddings(model='text-embedding-3-small', openai_api_key=openai_api_key)
82
+ qdrant_client = QdrantClient(url=qdrant_url, api_key=qdrant_api_key)
83
+ qdrant = Qdrant(client=qdrant_client, collection_name="Lex-v1",
84
+ embeddings=embeddings_model)
85
+ retriever = qdrant.as_retriever(search_kwargs={"k": 5})
86
+
87
+
88
+ prompt=PromptTemplate(
89
+
90
+ template="""
91
+ # Your role
92
+ You are a brilliant expert at understanding the intent of the questioner and the crux of the question, and providing the most optimal answer from the docs to the questioner's needs from the documents you are given.
93
+
94
+
95
+ # Instruction
96
+ Your task is to answer the question using the following pieces of retrieved context delimited by XML tags.
97
+
98
+
99
+ Retrieved Context:
100
+ {context}
101
+
102
+
103
+
104
+ # Constraint
105
+ 1. Think deeply and multiple times about the user's question\nUser's question:\n{question}\nYou must understand the intent of their question and provide the most appropriate answer.
106
+ - Ask yourself why to understand the context of the question and why the questioner asked it, reflect on it, and provide an appropriate response based on what you understand.
107
+ 2. Choose the most relevant content(the key content that directly relates to the question) from the retrieved context and use it to generate an answer.
108
+ 3. Generate a concise, logical answer. When generating the answer, Do Not just list your selections, But rearrange them in context so that they become paragraphs with a natural flow.
109
+ 4. When you don't have retrieved context for the question or If you have a retrieved documents, but their content is irrelevant to the question, you should answer 'I can't find the answer to that question in the material I have'.
110
+ 5. Use five sentences maximum. Keep the answer concise but logical/natural/in-depth.
111
+ 6. At the end of the response provide metadata provided in the relevant docs , For example:"Metadata: page: 19, source: /content/OCR_RSCA/Analyse docs JVB + mails et convention FOOT INNOVATION.pdf'. Return Just the page and source
112
+
113
+
114
+ # Question:
115
+ {question}""",
116
+ input_variables=["context","question"]
117
+ )
118
+ llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0,openai_api_key=openai_api_key)
119
+
120
+
121
+ def format_docs(docs):
122
+ formatted_docs = []
123
+ for doc in docs:
124
+ # Format the metadata into a string
125
+ metadata_str = ', '.join(f"{key}: {value}" for key, value in doc.metadata.items())
126
+
127
+ # Combine page content with its metadata
128
+ doc_str = f"{doc.page_content}\nMetadata: {metadata_str}"
129
+
130
+ # Append to the list of formatted documents
131
+ formatted_docs.append(doc_str)
132
+
133
+ # Join all formatted documents with double newlines
134
+ return "\n\n".join(formatted_docs)
135
+
136
+
137
+ rag_chain = (
138
+ {"context": retriever | format_docs, "question": RunnablePassthrough()}
139
+ | prompt
140
+ | llm
141
+ | StrOutputParser()
142
+ )
143
+
144
+ result = rag_chain.invoke(query)
145
+ return result
146
+ except Exception as e:
147
+ print(f"Error processing the query: {e}")
148
+ return None
149
+
150
+ def is_document_embedded(filename):
151
+ """Check if a document has already been embedded based on its filename."""
152
+ # This function needs to query your backend or check a local database/file.
153
+ # For simplicity, here's a placeholder that always returns False.
154
+ # Replace this with actual logic.
155
+ return False