ankitv42 commited on
Commit
925e68e
·
verified ·
1 Parent(s): 745dbba

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +144 -0
app.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+
3
+ import os
4
+ import gradio as gr
5
+
6
+ from langchain_community.vectorstores.neo4j_vector import remove_lucene_chars
7
+ from langchain_community.graphs import Neo4jGraph
8
+ from langchain_experimental.graph_transformers import LLMGraphTransformer
9
+ from langchain.document_loaders import PyPDFLoader
10
+ from langchain.embeddings import HuggingFaceEmbeddings
11
+ from langchain.vectorstores import Neo4jVector
12
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
13
+ from langchain_groq import ChatGroq
14
+ from langchain_core.prompts import ChatPromptTemplate
15
+ from langchain_core.output_parsers import StrOutputParser
16
+ from langchain_core.runnables import RunnableParallel, RunnableLambda
17
+ from langchain_core.pydantic_v1 import BaseModel, Field
18
+
19
+ # --- API & DB Setup ---
20
+ os.environ["GROQ_API_KEY"] = "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"
21
+ NEO4J_URI = "neo4j+s://491b8299.databases.neo4j.io"
22
+ NEO4J_USERNAME = "neo4j"
23
+ NEO4J_PASSWORD = "W3i8UiePw9QyaSJxK9l_apbzUnzh10YWxZQtnpSS02I"
24
+
25
+ graph = Neo4jGraph(url=NEO4J_URI, username=NEO4J_USERNAME, password=NEO4J_PASSWORD)
26
+ llm = ChatGroq(model="llama3-8b-8192")
27
+ embedding_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
28
+ llm_transformer = LLMGraphTransformer(llm=llm)
29
+
30
+ # --- Entity Extraction Schema ---
31
+ class Entities(BaseModel):
32
+ names: list[str] = Field(..., description="All person, org, or business names")
33
+
34
+ entity_prompt = ChatPromptTemplate.from_messages([
35
+ ("system", "you are extracting organization and person entities from the text"),
36
+ ("human", "Use the given format to extract entities:\ninput: {question}")
37
+ ])
38
+ entity_chain = entity_prompt | llm.with_structured_output(Entities)
39
+
40
+ # --- Helpers ---
41
+ def generate_full_text_query(input: str) -> str:
42
+ words = [el for el in remove_lucene_chars(input).split() if el]
43
+ return " AND ".join([f"{word}~2" for word in words])
44
+
45
+ def structured_retriever(question: str) -> str:
46
+ entities = entity_chain.invoke({"question": question})
47
+ result = ""
48
+ for entity in entities.names:
49
+ cypher = """
50
+ CALL db.index.fulltext.queryNodes('entity', $query, {limit:2})
51
+ YIELD node,score
52
+ CALL {
53
+ WITH node
54
+ MATCH (node)-[r:!MENTIONS]->(neighbor)
55
+ RETURN node.id + '-' + type(r) + '->' + neighbor.id AS output
56
+ UNION ALL
57
+ WITH node
58
+ MATCH (node)<-[r:!MENTIONS]-(neighbor)
59
+ RETURN neighbor.id + '-' + type(r) + '->' + node.id AS output
60
+ }
61
+ RETURN output LIMIT 50
62
+ """
63
+ response = graph.query(cypher, {"query": generate_full_text_query(entity)})
64
+ result += "\n".join([el['output'] for el in response])
65
+ return result
66
+
67
+ def retriever(question: str) -> str:
68
+ structured = structured_retriever(question)
69
+ unstructured = [el.page_content for el in vector_index.similarity_search(question)]
70
+ return f"Structured Data:\n{structured}\n\nUnstructured Data:\n" + "\n---\n".join(unstructured)
71
+
72
+ # --- RAG Chain ---
73
+ template = """Answer the question based only on the context:
74
+ {context}
75
+
76
+ Question: {question}
77
+ Use natural language and be concise.
78
+ Answer:"""
79
+
80
+ qa_prompt = ChatPromptTemplate.from_template(template)
81
+
82
+ chain = (
83
+ RunnableParallel({
84
+ "context": RunnableLambda(lambda x: retriever(x["question"])),
85
+ "question": RunnableLambda(lambda x: x["question"]),
86
+ })
87
+ | qa_prompt
88
+ | llm
89
+ | StrOutputParser()
90
+ )
91
+
92
+ # --- Gradio Pipeline ---
93
+ vector_index = None
94
+
95
+ def process_pdf(pdf_file):
96
+ global vector_index
97
+ loader = PyPDFLoader(pdf_file.name)
98
+ docs = loader.load()
99
+
100
+ splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
101
+ docs_split = splitter.split_documents(docs)
102
+
103
+ graph_docs = []
104
+ for i in range(0, len(docs_split), 2):
105
+ try:
106
+ graph_docs.extend(llm_transformer.convert_to_graph_documents(docs_split[i:i+2]))
107
+ except Exception as e:
108
+ print(f"Error: {e}")
109
+
110
+ graph.add_graph_documents(graph_docs, baseEntityLabel=True, include_source=True)
111
+ graph.query("CREATE FULLTEXT INDEX entity IF NOT EXISTS FOR (e:__Entity__) ON EACH [e.id]")
112
+
113
+ vector_index = Neo4jVector.from_existing_graph(
114
+ embedding_model,
115
+ search_type="hybrid",
116
+ graph=graph,
117
+ node_label="Document",
118
+ embedding_node_property="embedding",
119
+ text_node_properties=["text"]
120
+ )
121
+ return "PDF uploaded and processed successfully!"
122
+
123
+ def chat_with_doc(question):
124
+ if vector_index is None:
125
+ return "Please upload and process a PDF first."
126
+ return chain.invoke({"question": question})
127
+
128
+ # --- Gradio UI ---
129
+ with gr.Blocks() as demo:
130
+ gr.Markdown("## 🧠 Graph RAG PDF Q&A")
131
+ with gr.Row():
132
+ pdf_input = gr.File(label="Upload PDF")
133
+ upload_btn = gr.Button("Process PDF")
134
+ output_info = gr.Textbox(label="Status", interactive=False)
135
+
136
+ with gr.Row():
137
+ question_input = gr.Textbox(label="Ask a Question")
138
+ ask_btn = gr.Button("Get Answer")
139
+ answer_output = gr.Textbox(label="Answer")
140
+
141
+ upload_btn.click(process_pdf, inputs=[pdf_input], outputs=[output_info])
142
+ ask_btn.click(chat_with_doc, inputs=[question_input], outputs=[answer_output])
143
+
144
+ demo.launch()