-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
122 lines (103 loc) · 3.81 KB
/
Copy pathapp.py
File metadata and controls
122 lines (103 loc) · 3.81 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
#!/usr/bin/env python3
"""
Graph RAG System Web Interface
Simple Flask frontend for easy querying
"""
from flask import Flask, render_template, request, jsonify
import os
import json
from dotenv import load_dotenv
from graph_rag_system import GraphRAGSystem
# Load environment variables from .env file
load_dotenv()
app = Flask(__name__)
# Global variable to store the RAG system
rag_system = None
def initialize_system():
"""Initialize the Graph RAG system"""
global rag_system
if rag_system is None:
print("🔧 Initializing Graph RAG System...")
api_key = os.getenv("ANTHROPIC_API_KEY")
use_ai = bool(api_key)
rag_system = GraphRAGSystem(api_key, use_ai=use_ai)
# Build using directories so any files you add are ingested automatically
rag_system.build_system("data/excel", "data")
print("✅ System initialized successfully!")
@app.route('/api/reload', methods=['POST'])
def reload_system():
"""Rebuild the Graph RAG system (use when new PDFs are added)"""
try:
global rag_system
print("🔄 Reloading Graph RAG System...")
api_key = os.getenv("ANTHROPIC_API_KEY")
use_ai = bool(api_key)
# Recreate the system to ensure a clean rebuild
rag_system = GraphRAGSystem(api_key, use_ai=use_ai)
rag_system.build_system("data/excel", "data")
print("✅ Reload completed!")
return jsonify({"success": True}), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/clear-cache', methods=['POST'])
def clear_cache():
"""Clear all cached data"""
try:
global rag_system
if rag_system is None:
# Initialize system if not already done
initialize_system()
result = rag_system.clear_cache()
if result.get("success"):
print("🗑️ Cache cleared successfully!")
return jsonify({"success": True, "message": "Cache cleared successfully"}), 200
else:
return jsonify({"success": False, "error": result.get("error", "Unknown error")}), 500
except Exception as e:
return jsonify({'error': str(e)}), 500
# Initialize system on startup
print("🚀 Starting Graph RAG Web Interface...")
initialize_system()
@app.route('/')
def index():
"""Main page"""
return render_template('index.html')
@app.route('/api/query', methods=['POST'])
def query():
"""Handle query requests"""
try:
data = request.get_json()
query_text = data.get('query', '')
if not query_text:
return jsonify({'error': 'No query provided'}), 400
# Initialize system if not already done
initialize_system()
# Process query
result = rag_system.search_and_answer(query_text)
return jsonify({
'success': True,
'query': query_text,
'answer': result['answer'],
'num_results': result['num_results'],
'num_relationships': result['num_relationships'],
'related_documents': result['related_documents'][:10] # Limit to 10
})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/stats')
def stats():
"""Get system statistics"""
try:
initialize_system()
stats = rag_system.get_system_statistics()
return jsonify(stats)
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/health')
def health():
"""Health check endpoint"""
return jsonify({'status': 'healthy', 'message': 'Graph RAG System is running'})
if __name__ == '__main__':
print("🚀 Starting Graph RAG Web Interface...")
print("📱 Open your browser and go to: http://localhost:5001")
app.run(debug=True, host='0.0.0.0', port=5001)