-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·449 lines (343 loc) · 14.8 KB
/
main.py
File metadata and controls
executable file
·449 lines (343 loc) · 14.8 KB
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
"""
Main Pipeline - Complete Knowledge Graph Creation Example
"""
import os
from document_processor import DocumentProcessor
from text_preprocessor import TextPreprocessor
from entity_extractor import EntityExtractor
from relation_extractor import RelationExtractor
from graph_builder import KnowledgeGraphBuilder
from graph_visualizer import GraphVisualizer
from graph_querier import KnowledgeGraphQuerier
from semantic_retriever import SemanticRetriever
from config import OPENAI_API_KEY
from datetime import datetime
import uuid
def interactive_query_interface(kg_builder: KnowledgeGraphBuilder, entities: list):
"""Interactive interface for querying the knowledge graph"""
# Initialize querying tools
print("\n" + "="*70)
print("INITIALIZING QUERY INTERFACE")
print("="*70)
querier = KnowledgeGraphQuerier(kg_builder)
retriever = SemanticRetriever(kg_builder)
retriever.index_graph()
print("✓ Query interface ready!")
while True:
print("\n" + "="*70)
print("KNOWLEDGE GRAPH QUERY MENU")
print("="*70)
print("\nAvailable Options:")
print(" 1. Semantic Search - Find relevant information using natural language")
print(" 2. Question Answering - Ask questions and get AI-generated answers")
print(" 3. SPARQL Query - Find all relations for a specific entity")
print(" 4. Custom SPARQL Query - Execute your own SPARQL query")
print(" 5. View Graph Statistics")
print(" 6. Exit")
choice = input("\nSelect an option (1-6): ").strip()
if choice == '1':
semantic_search_interface(retriever)
elif choice == '2':
question_answering_interface(retriever)
elif choice == '3':
sparql_entity_relations_interface(querier, entities)
elif choice == '4':
custom_sparql_interface(querier, kg_builder)
elif choice == '5':
show_graph_statistics(kg_builder)
elif choice == '6':
print("\n👋 Exiting query interface. Goodbye!")
break
else:
print("\n❌ Invalid option. Please select 1-6.")
def semantic_search_interface(retriever: SemanticRetriever):
"""Interactive semantic search interface"""
print("\n" + "-"*70)
print("SEMANTIC SEARCH")
print("-"*70)
print("Search the knowledge graph using natural language.")
while True:
query = input("\nEnter search query (or 'back' to return): ").strip()
if query.lower() in ['back', 'exit', 'quit']:
break
if not query:
print("❌ Please enter a search query.")
continue
print(f"\n🔍 Searching for: '{query}'")
top_k = input("Number of results to show (default 5): ").strip()
top_k = int(top_k) if top_k.isdigit() else 5
results = retriever.search(query, top_k=top_k)
if not results:
print("No results found.")
continue
print(f"\n📊 Top {len(results)} Results:")
for i, result in enumerate(results, 1):
print(f"\n {i}. {result['subject']} → {result['predicate']} → {result['object']}")
print(f" Similarity Score: {result['similarity']:.3f}")
another = input("\nSearch again? (y/n): ").strip().lower()
if another != 'y':
break
def question_answering_interface(retriever: SemanticRetriever):
"""Interactive question answering interface"""
print("\n" + "-"*70)
print("QUESTION ANSWERING (AI-Powered)")
print("-"*70)
if not OPENAI_API_KEY:
print("❌ Question answering requires an OpenAI API key.")
print("Please set OPENAI_API_KEY in your .env file.")
input("\nPress Enter to continue...")
return
print("Ask questions about the knowledge graph and get AI-generated answers.")
print("Example: 'What did Einstein work on?', 'Where was Marie Curie born?'")
while True:
question = input("\nEnter your question (or 'back' to return): ").strip()
if question.lower() in ['back', 'exit', 'quit']:
break
if not question:
print("❌ Please enter a question.")
continue
print(f"\n💭 Thinking about: '{question}'")
print("⏳ Retrieving relevant facts and generating answer...")
answer = retriever.answer_question_llm(question, OPENAI_API_KEY)
print(f"\n✨ Answer:\n{answer}")
another = input("\n\nAsk another question? (y/n): ").strip().lower()
if another != 'y':
break
def sparql_entity_relations_interface(querier: KnowledgeGraphQuerier, entities: list):
"""Interactive interface for finding entity relations"""
print("\n" + "-"*70)
print("ENTITY RELATIONS FINDER")
print("-"*70)
print("Find all relationships for a specific entity in the graph.")
if not entities:
print("❌ No entities found in the knowledge graph.")
input("\nPress Enter to continue...")
return
while True:
print("\n📋 Available Entities:")
# Show first 20 entities
display_entities = entities[:20]
for i, entity in enumerate(display_entities, 1):
print(f" {i}. {entity['text']} ({entity['type']})")
if len(entities) > 20:
print(f" ... and {len(entities) - 20} more")
print("\nOptions:")
print(" - Enter entity name directly")
print(" - Enter number to select from list")
print(" - Type 'back' to return")
user_input = input("\nSelect entity: ").strip()
if user_input.lower() in ['back', 'exit', 'quit']:
break
if not user_input:
print("❌ Please enter an entity name or number.")
continue
# Check if input is a number
if user_input.isdigit():
idx = int(user_input) - 1
if 0 <= idx < len(display_entities):
entity_name = display_entities[idx]['text']
else:
print("❌ Invalid number. Please try again.")
continue
else:
entity_name = user_input
print(f"\n🔍 Finding relations for: {entity_name}")
results = querier.find_entity_relations(entity_name)
if not results:
print(f"❌ No relations found for '{entity_name}'")
print(" This entity might not exist in the graph or has no connections.")
continue
print(f"\n📊 Found {len(results)} relations:")
for i, result in enumerate(results, 1):
predicate = result.get('predicate', 'N/A')
obj = result.get('object', 'N/A')
obj_label = result.get('objLabel', 'None')
# Extract readable predicate name
if '/' in predicate:
predicate_name = predicate.split('/')[-1].replace('_', ' ')
elif '#' in predicate:
predicate_name = predicate.split('#')[-1].replace('_', ' ')
else:
predicate_name = predicate
# Extract readable object name
if obj_label and obj_label != 'None':
object_name = obj_label
elif '/' in obj:
object_name = obj.split('/')[-1].replace('_', ' ')
elif '#' in obj:
object_name = obj.split('#')[-1].replace('_', ' ')
else:
object_name = obj
print(f" {i}. {entity_name} → {predicate_name} → {object_name}")
another = input("\n\nLookup another entity? (y/n): ").strip().lower()
if another != 'y':
break
def custom_sparql_interface(querier: KnowledgeGraphQuerier, kg_builder: KnowledgeGraphBuilder):
"""Interactive interface for custom SPARQL queries"""
print("\n" + "-"*70)
print("CUSTOM SPARQL QUERY")
print("-"*70)
print("Execute custom SPARQL queries on the knowledge graph.")
example_query = f"""PREFIX kg: <{kg_builder.ns}>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?subject ?predicate ?object
WHERE {{
?subject ?predicate ?object .
}}
LIMIT 10"""
print("\nExample Query:")
print(example_query)
while True:
print("\n" + "-"*70)
print("Enter your SPARQL query (type 'END' on a new line when done):")
print("Type 'example' to use the example query above")
print("Type 'back' to return to menu")
user_input = input("\n> ").strip()
if user_input.lower() in ['back', 'exit', 'quit']:
break
if user_input.lower() == 'example':
sparql_query = example_query
else:
# Multi-line input
query_lines = [user_input]
while True:
line = input()
if line.strip().upper() == 'END':
break
query_lines.append(line)
sparql_query = '\n'.join(query_lines)
if not sparql_query.strip():
print("❌ Empty query. Please try again.")
continue
print("\n⏳ Executing query...")
try:
results = querier.query(sparql_query)
if not results:
print("✓ Query executed successfully. No results returned.")
continue
print(f"\n✓ Query returned {len(results)} results:")
print("\n" + "-"*70)
# Display results
for i, result in enumerate(results, 1):
print(f"\nResult {i}:")
for key, value in result.items():
print(f" {key}: {value}")
except Exception as e:
print(f"\n❌ Query execution failed: {e}")
print("Please check your SPARQL syntax and try again.")
another = input("\n\nExecute another query? (y/n): ").strip().lower()
if another != 'y':
break
def show_graph_statistics(kg_builder: KnowledgeGraphBuilder):
"""Display knowledge graph statistics"""
print("\n" + "-"*70)
print("KNOWLEDGE GRAPH STATISTICS")
print("-"*70)
stats = kg_builder.get_statistics()
print("\n📊 Graph Overview:")
for key, value in stats.items():
formatted_key = key.replace('_', ' ').title()
print(f" {formatted_key}: {value}")
input("\nPress Enter to continue...")
def main(input_file=None):
"""Run the complete knowledge graph creation pipeline
Args:
input_file: Path to input document (PDF, TXT, or DOCX). If None, uses sample.
"""
print("\n" + "="*70)
print("KNOWLEDGE GRAPH CREATION PIPELINE")
print("="*70 + "\n")# Generate unique ID for this run
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
unique_id = f"{timestamp}_{uuid.uuid4().hex[:8]}"
output_dir = f"output/kg_{unique_id}"
print("\n" + "="*70)
print("KNOWLEDGE GRAPH CREATION PIPELINE")
print(f"Run ID: {unique_id}")
print("="*70 + "\n")
# Step 1: Load Document
print("STEP 1: Document Loading")
print("-" * 70)
doc_processor = DocumentProcessor()
if input_file:
text = doc_processor.load_document(input_file)
else:
text = doc_processor.create_sample_document()
# Step 2: Preprocess Text
print("\nSTEP 2: Text Preprocessing")
print("-" * 70)
preprocessor = TextPreprocessor()
preprocessed = preprocessor.preprocess(text)
# Step 3: Extract Entities
print("\nSTEP 3: Entity Extraction")
print("-" * 70)
entity_extractor = EntityExtractor(openai_api_key=OPENAI_API_KEY)
spacy_entities = entity_extractor.extract_entities_spacy(preprocessed['cleaned'])
llm_entities = entity_extractor.extract_entities_llm(preprocessed['cleaned'])
entities = entity_extractor.merge_entities(spacy_entities, llm_entities)
print(f"\nExtracted {len(entities)} unique entities")
if entities:
print(f"Sample entities: {[e['text'] for e in entities[:5]]}")
# Step 4: Extract Relations
print("\nSTEP 4: Relation Extraction")
print("-" * 70)
relation_extractor = RelationExtractor(openai_api_key=OPENAI_API_KEY)
pattern_relations = relation_extractor.extract_relations_pattern(
preprocessed['cleaned'], entities
)
llm_relations = relation_extractor.extract_relations_llm(
preprocessed['cleaned'], entities
)
relations = relation_extractor.merge_relations(pattern_relations, llm_relations)
print(f"\nExtracted {len(relations)} unique relations")
if relations:
print(f"Sample relations:")
for rel in relations[:3]:
print(f" - {rel['subject']} → {rel['predicate']} → {rel['object']}")
# Step 5: Build Knowledge Graph
print("\nSTEP 5: Knowledge Graph Construction")
print("-" * 70)
kg_builder = KnowledgeGraphBuilder()
kg_builder.build_from_extractions(entities, relations)
# Get statistics
stats = kg_builder.get_statistics()
print(f"\nGraph Statistics:")
for key, value in stats.items():
print(f" {key}: {value}")
# Save graph
os.makedirs(output_dir, exist_ok=True)
kg_builder.save_rdf(f"{output_dir}/knowledge_graph.ttl")
# Step 6: Visualize Graph
print("\nSTEP 6: Graph Visualization")
print("-" * 70)
visualizer = GraphVisualizer(kg_builder)
visualizer.visualize(f"{output_dir}/knowledge_graph.png")
print("\n" + "="*70)
print("KNOWLEDGE GRAPH CONSTRUCTION COMPLETED!")
print("="*70)
print(f"\n✓ Output files saved in '{output_dir}/' directory:")
print(f" - knowledge_graph.ttl (RDF graph)")
print(f" - knowledge_graph.png (visualization)")
# Launch interactive query interface
print("\n" + "="*70)
print("LAUNCHING INTERACTIVE QUERY INTERFACE")
print("="*70)
input("\nPress Enter to start querying the knowledge graph...")
interactive_query_interface(kg_builder, entities)
print("\n" + "="*70)
print("SESSION COMPLETED!")
print("="*70 + "\n")
if __name__ == "__main__":
import sys
# Check if file path provided as command line argument
if len(sys.argv) > 1:
input_file = sys.argv[1]
if not os.path.exists(input_file):
print(f"Error: File '{input_file}' not found!")
sys.exit(1)
main(input_file)
else:
# Run with sample document
print("No input file provided. Using sample document.")
print("Usage: python main.py <path_to_pdf_or_document>")
print()
main()