- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi.py
More file actions
Latest commit
executable file
·508 lines (398 loc) · 15.7 KB
/
Copy pathapi.py
File metadata and controls
executable file
·508 lines (398 loc) · 15.7 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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
"""
FastAPI Backend for Knowledge Graph System
Provides REST API endpoints for graph creation and querying
"""
fromfastapiimportFastAPI, UploadFile, File, HTTPException, BackgroundTasks
fromfastapi.responsesimportJSONResponse, FileResponse
fromfastapi.middleware.corsimportCORSMiddleware
frompydanticimportBaseModel
fromtypingimportOptional, List, Dict
importos
importshutil
fromdatetimeimportdatetime
importuuid
importjson
fromdocument_processorimportDocumentProcessor
fromtext_preprocessorimportTextPreprocessor
fromentity_extractorimportEntityExtractor
fromrelation_extractorimportRelationExtractor
fromgraph_builderimportKnowledgeGraphBuilder
fromgraph_visualizerimportGraphVisualizer
fromgraph_querierimportKnowledgeGraphQuerier
fromsemantic_retrieverimportSemanticRetriever
fromconfigimportOPENAI_API_KEY
# Initialize FastAPI app
app=FastAPI(
title="Knowledge Graph API",
description="API for creating and querying knowledge graphs from documents",
version="1.0.0"
)
# Add CORS middleware for Streamlit
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Global storage for active knowledge graphs
active_graphs: Dict[str, Dict] = {}
# Global storage for chat history
chat_history: Dict[str, List[Dict]] = {}
# Pydantic models for request/response
classGraphCreationResponse(BaseModel):
graph_id: str
message: str
entities_count: int
relations_count: int
statistics: Dict
output_dir: str
classSemanticSearchRequest(BaseModel):
graph_id: str
query: str
top_k: int=5
classQuestionAnswerRequest(BaseModel):
graph_id: str
question: str
classEntityRelationsRequest(BaseModel):
graph_id: str
entity_name: str
classSPARQLQueryRequest(BaseModel):
graph_id: str
query: str
classChatMessage(BaseModel):
role: str
content: str
timestamp: str
facts: Optional[List[str]] =None
classSaveChatRequest(BaseModel):
graph_id: str
messages: List[ChatMessage]
@app.get("/")
asyncdefroot():
"""Root endpoint"""
return {
"message": "Knowledge Graph API",
"version": "1.0.0",
"endpoints": {
"health": "/health",
"upload": "/upload",
"graphs": "/graphs",
"semantic_search": "/semantic_search",
"question_answer": "/question_answer",
"entity_relations": "/entity_relations",
"sparql_query": "/sparql_query",
"visualization": "/visualization/{graph_id}",
"download_graph": "/download_graph/{graph_id}"
}
}
@app.get("/health")
asyncdefhealth_check():
"""Health check endpoint"""
return {
"status": "healthy",
"active_graphs": len(active_graphs),
"openai_configured": bool(OPENAI_API_KEY)
}
@app.post("/upload", response_model=GraphCreationResponse)
asyncdefupload_document(
file: UploadFile=File(...),
background_tasks: BackgroundTasks=None
):
"""
Upload a document and create a knowledge graph
Supports PDF, TXT, and DOCX files
"""
# Validate file type
allowed_extensions= {'.pdf', '.txt', '.docx', '.doc'}
file_ext=os.path.splitext(file.filename)[1].lower()
iffile_extnotinallowed_extensions:
raiseHTTPException(
status_code=400,
detail=f"Unsupported file type: {file_ext}. Allowed: {allowed_extensions}"
)
# Generate unique ID
timestamp=datetime.now().strftime("%Y%m%d_%H%M%S")
graph_id=f"{timestamp}_{uuid.uuid4().hex[:8]}"
output_dir=f"output/kg_{graph_id}"
os.makedirs(output_dir, exist_ok=True)
# Save uploaded file temporarily
temp_file_path=f"{output_dir}/uploaded_{file.filename}"
try:
withopen(temp_file_path, "wb") asbuffer:
shutil.copyfileobj(file.file, buffer)
# Process document
doc_processor=DocumentProcessor()
text=doc_processor.load_document(temp_file_path)
upload_progress[graph_id].update({
'progress': 20,
'message': 'Document loaded, preprocessing text...',
'logs': upload_progress[graph_id]['logs'] + [f"✓ Loaded document from {temp_file_path}"]
})
# Preprocess
preprocessor=TextPreprocessor()
preprocessed=preprocessor.preprocess(text)
# Extract entities
entity_extractor=EntityExtractor(openai_api_key=OPENAI_API_KEY)
spacy_entities=entity_extractor.extract_entities_spacy(preprocessed['cleaned'])
upload_progress[graph_id].update({
'progress': 40,
'message': f'Extracted {len(spacy_entities)} entities with spaCy, using LLM...',
'logs': upload_progress[graph_id]['logs'] + [f"✓ Extracted {len(spacy_entities)} entities using spaCy"]
})
llm_entities=entity_extractor.extract_entities_llm(preprocessed['cleaned'])
upload_progress[graph_id].update({
'progress': 50,
'message': 'Merging entities...',
'logs': upload_progress[graph_id]['logs'] + [f"✓ Extracted {len(llm_entities)} entities using LLM"]
})
entities=entity_extractor.merge_entities(spacy_entities, llm_entities)
upload_progress[graph_id].update({
'progress': 60,
'message': 'Extracting relations...',
'logs': upload_progress[graph_id]['logs'] + [f"✓ Merged into {len(entities)} unique entities"]
})
# Extract relations
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)
# Build knowledge graph
kg_builder=KnowledgeGraphBuilder()
kg_builder.build_from_extractions(entities, relations)
upload_progress[graph_id].update({
'progress': 85,
'message': 'Saving graph...',
'logs': upload_progress[graph_id]['logs'] + ["✓ Knowledge graph built"]
})
# Save graph
kg_builder.save_rdf(f"{output_dir}/knowledge_graph.ttl")
upload_progress[graph_id].update({
'progress': 90,
'message': 'Creating visualization...',
'logs': upload_progress[graph_id]['logs'] + ["✓ Graph saved as RDF"]
})
# Create visualization
visualizer=GraphVisualizer(kg_builder)
visualizer.visualize(f"{output_dir}/knowledge_graph.png")
upload_progress[graph_id].update({
'progress': 95,
'message': 'Indexing for search...',
'logs': upload_progress[graph_id]['logs'] + ["✓ Visualization created"]
})
# Initialize semantic retriever
retriever=SemanticRetriever(kg_builder)
retriever.index_graph()
# Initialize querier
querier=KnowledgeGraphQuerier(kg_builder)
# Get statistics
stats=kg_builder.get_statistics()
# Store in memory
active_graphs[graph_id] = {
'kg_builder': kg_builder,
'retriever': retriever,
'querier': querier,
'entities': entities,
'relations': relations,
'output_dir': output_dir,
'filename': file.filename,
'created_at': datetime.now().isoformat(),
'statistics': stats
}
# Save metadata
metadata= {
'graph_id': graph_id,
'filename': file.filename,
'created_at': datetime.now().isoformat(),
'entities_count': len(entities),
'relations_count': len(relations),
'statistics': stats
}
withopen(f"{output_dir}/metadata.json", 'w') asf:
json.dump(metadata, f, indent=2)
returnGraphCreationResponse(
graph_id=graph_id,
message="Knowledge graph created successfully",
entities_count=len(entities),
relations_count=len(relations),
statistics=stats,
output_dir=output_dir
)
exceptExceptionase:
# Cleanup on error
ifos.path.exists(output_dir):
shutil.rmtree(output_dir)
raiseHTTPException(status_code=500, detail=str(e))
finally:
# Close uploaded file
awaitfile.close()
@app.get("/graphs")
asyncdeflist_graphs():
"""List all active knowledge graphs"""
graphs_info= []
forgraph_id, datainactive_graphs.items():
graphs_info.append({
'graph_id': graph_id,
'filename': data.get('filename', 'Unknown'),
'created_at': data['created_at'],
'entities_count': len(data['entities']),
'relations_count': len(data['relations']),
'statistics': data['statistics']
})
return {"graphs": graphs_info, "total": len(graphs_info)}
@app.get("/chat_history/{graph_id}")
asyncdefget_chat_history(graph_id: str):
"""Get chat history for a specific graph"""
ifgraph_idnotinactive_graphs:
raiseHTTPException(status_code=404, detail="Graph not found")
return {
"graph_id": graph_id,
"messages": chat_history.get(graph_id, []),
"count": len(chat_history.get(graph_id, []))
}
@app.post("/chat_history/{graph_id}")
asyncdefsave_chat_message(graph_id: str, message: ChatMessage):
"""Save a chat message to history"""
ifgraph_idnotinactive_graphs:
raiseHTTPException(status_code=404, detail="Graph not found")
ifgraph_idnotinchat_history:
chat_history[graph_id] = []
chat_history[graph_id].append(message.dict())
return {
"message": "Chat message saved",
"total_messages": len(chat_history[graph_id])
}
@app.delete("/chat_history/{graph_id}")
asyncdefclear_chat_history(graph_id: str):
"""Clear chat history for a specific graph"""
ifgraph_idnotinactive_graphs:
raiseHTTPException(status_code=404, detail="Graph not found")
ifgraph_idinchat_history:
delchat_history[graph_id]
return {"message": "Chat history cleared"}
@app.get("/graph/{graph_id}")
asyncdefget_graph_info(graph_id: str):
"""Get information about a specific graph"""
ifgraph_idnotinactive_graphs:
raiseHTTPException(status_code=404, detail="Graph not found")
data=active_graphs[graph_id]
return {
'graph_id': graph_id,
'filename': data['filename'],
'created_at': data['created_at'],
'entities_count': len(data['entities']),
'relations_count': len(data['relations']),
'statistics': data['statistics'],
'sample_entities': [e['text'] foreindata['entities'][:10]]
}
@app.post("/semantic_search")
asyncdefsemantic_search(request: SemanticSearchRequest):
"""Perform semantic search on knowledge graph"""
ifrequest.graph_idnotinactive_graphs:
raiseHTTPException(status_code=404, detail="Graph not found")
retriever=active_graphs[request.graph_id]['retriever']
try:
results=retriever.search(request.query, top_k=request.top_k)
return {"results": results, "query": request.query}
exceptExceptionase:
raiseHTTPException(status_code=500, detail=str(e))
@app.post("/question_answer")
asyncdefquestion_answer(request: QuestionAnswerRequest):
"""Answer questions using LLM and knowledge graph"""
ifrequest.graph_idnotinactive_graphs:
raiseHTTPException(status_code=404, detail="Graph not found")
ifnotOPENAI_API_KEY:
raiseHTTPException(
status_code=400,
detail="OpenAI API key not configured"
)
retriever=active_graphs[request.graph_id]['retriever']
try:
answer=retriever.answer_question_llm(request.question, OPENAI_API_KEY)
# Also get relevant facts
relevant_facts=retriever.search(request.question, top_k=5)
return {
"question": request.question,
"answer": answer,
"relevant_facts": relevant_facts
}
exceptExceptionase:
raiseHTTPException(status_code=500, detail=str(e))
@app.post("/entity_relations")
asyncdefentity_relations(request: EntityRelationsRequest):
"""Find all relations for a specific entity"""
ifrequest.graph_idnotinactive_graphs:
raiseHTTPException(status_code=404, detail="Graph not found")
querier=active_graphs[request.graph_id]['querier']
try:
results=querier.find_entity_relations(request.entity_name)
return {
"entity": request.entity_name,
"relations": results,
"count": len(results)
}
exceptExceptionase:
raiseHTTPException(status_code=500, detail=str(e))
@app.post("/sparql_query")
asyncdefsparql_query(request: SPARQLQueryRequest):
"""Execute custom SPARQL query"""
ifrequest.graph_idnotinactive_graphs:
raiseHTTPException(status_code=404, detail="Graph not found")
querier=active_graphs[request.graph_id]['querier']
try:
results=querier.query(request.query)
return {
"results": results,
"count": len(results)
}
exceptExceptionase:
raiseHTTPException(status_code=500, detail=f"Query execution failed: {str(e)}")
@app.get("/visualization/{graph_id}")
asyncdefget_visualization(graph_id: str):
"""Get the knowledge graph visualization image"""
ifgraph_idnotinactive_graphs:
raiseHTTPException(status_code=404, detail="Graph not found")
output_dir=active_graphs[graph_id]['output_dir']
image_path=f"{output_dir}/knowledge_graph.png"
ifnotos.path.exists(image_path):
raiseHTTPException(status_code=404, detail="Visualization not found")
returnFileResponse(image_path, media_type="image/png")
@app.get("/download_graph/{graph_id}")
asyncdefdownload_graph(graph_id: str):
"""Download the RDF knowledge graph file"""
ifgraph_idnotinactive_graphs:
raiseHTTPException(status_code=404, detail="Graph not found")
output_dir=active_graphs[graph_id]['output_dir']
graph_path=f"{output_dir}/knowledge_graph.ttl"
ifnotos.path.exists(graph_path):
raiseHTTPException(status_code=404, detail="Graph file not found")
returnFileResponse(
graph_path,
media_type="text/turtle",
filename=f"knowledge_graph_{graph_id}.ttl"
)
@app.get("/entities/{graph_id}")
asyncdefget_entities(graph_id: str):
"""Get all entities from a graph"""
ifgraph_idnotinactive_graphs:
raiseHTTPException(status_code=404, detail="Graph not found")
entities=active_graphs[graph_id]['entities']
return {
"entities": entities,
"count": len(entities)
}
@app.delete("/graph/{graph_id}")
asyncdefdelete_graph(graph_id: str):
"""Delete a knowledge graph from memory"""
ifgraph_idnotinactive_graphs:
raiseHTTPException(status_code=404, detail="Graph not found")
# Remove from memory
delactive_graphs[graph_id]
return {"message": f"Graph {graph_id} deleted successfully"}
if__name__=="__main__":
importuvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)