VectorV17 commited on
Commit
5f2c2b0
·
verified ·
1 Parent(s): 7c5abc3

Update database.py

Browse files
Files changed (1) hide show
  1. database.py +171 -73
database.py CHANGED
@@ -1,87 +1,185 @@
 
1
  import os
 
2
  from neo4j import GraphDatabase, exceptions
3
 
4
- # Connection secrets retrieved securely from Environment Variables (Assignment Req 5.3)
5
- COGNODB_URI = os.getenv("COGNODB_URI", "bolt+s://your-instance.databases.cognodb.cloud")
6
- COGNODB_USER = os.getenv("COGNODB_USER", "cognodb")
7
- COGNODB_PASSWORD = os.getenv("COGNODB_PASSWORD", "your-password")
8
 
9
- class GraphDatabaseManager:
10
- """Manages CognoDB connectivity and parameterised Cypher operations."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  def __init__(self):
 
 
 
 
12
  self.driver = None
13
- self._connect()
14
 
15
- def _connect(self):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  try:
17
- self.driver = GraphDatabase.driver(
18
- COGNODB_URI,
19
- auth=(COGNODB_USER, COGNODB_PASSWORD)
20
- )
21
- self.driver.verify_connectivity()
22
- print("Successfully connected to CognoDB Cloud!")
23
  except Exception as e:
24
- print(f"[Warning] CognoDB Cloud Unreachable: {e}")
25
- self.driver = None
26
 
27
- def is_connected(self) -> bool:
28
- """Verifies if live DB connection is available."""
29
- if not self.driver:
30
- return False
31
- try:
32
- self.driver.verify_connectivity()
33
- return True
34
- except Exception:
35
- return False
36
 
37
- def close(self):
38
- if self.driver:
39
- self.driver.close()
 
 
 
 
 
 
 
 
40
 
41
- def query_graph_neighborhood(self, search_term: str):
42
- """
43
- Executes parameterised Cypher with a 2-hop traversal:
44
- Hop 1: (:Article)-[:REQUIRES_PREREQUISITE]->(:Article)
45
- Hop 2: (:Article)-[:BELONGS_TO]->(:Category)
46
- Also retrieves resolved issues and mentioned systems.
47
- """
48
- if not self.is_connected():
49
- return None, "Database unreachable. System operating in General Fallback Mode."
50
 
51
- # Parameterised Cypher Query ($term) - Strictly no string concatenation (Req 5.1)
52
- cypher_query = """
53
- MATCH (a:Article)
54
- WHERE toLower(a.title) CONTAINS toLower($term)
55
- OR toLower(a.content) CONTAINS toLower($term)
56
-
57
- // Hop 1 & 2: Get category, resolved issues, systems, and prerequisite articles with their categories
58
- OPTIONAL MATCH (a)-[:BELONGS_TO]->(c:Category)
59
- OPTIONAL MATCH (a)-[:RESOLVES]->(i:Issue)
60
- OPTIONAL MATCH (a)-[:MENTIONS]->(sys:System)
61
- OPTIONAL MATCH (a)-[:REQUIRES_PREREQUISITE]->(prereq:Article)-[:BELONGS_TO]->(pCat:Category)
62
-
63
- RETURN a.id AS articleId,
64
- a.title AS title,
65
- a.content AS content,
66
- c.name AS category,
67
- i.code AS errorCode,
68
- i.description AS issueDetail,
69
- sys.name AS affectedSystem,
70
- collect(DISTINCT {
71
- title: prereq.title,
72
- category: pCat.name
73
- }) AS prerequisites
74
- LIMIT 3
75
- """
76
- try:
77
- with self.driver.session() as session:
78
- result = session.run(cypher_query, term=search_term)
79
- records = [record.data() for record in result]
80
- return records, None
81
- except exceptions.Neo4jError as err:
82
- return None, f"Cypher Query Error: {str(err)}"
83
- except Exception as e:
84
- return None, f"Unexpected DB Error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
- # Singleton database manager instance
87
- db = GraphDatabaseManager()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sqlite3
2
  import os
3
+ import pandas as pd
4
  from neo4j import GraphDatabase, exceptions
5
 
6
+ # ==========================================
7
+ # 1. RELATIONAL DATABASE (SQLite for HF CPU)
8
+ # ==========================================
9
+ DB_FILE = "music_academy.db"
10
 
11
+ def init_sqlite():
12
+ """Initializes the local SQLite database for legacy tabular records."""
13
+ conn = sqlite3.connect(DB_FILE)
14
+ cursor = conn.cursor()
15
+
16
+ cursor.execute('''
17
+ CREATE TABLE IF NOT EXISTS courses (
18
+ course_id TEXT PRIMARY KEY,
19
+ instrument TEXT NOT NULL,
20
+ faculty_name TEXT NOT NULL,
21
+ faculty_email TEXT,
22
+ monthly_fees REAL,
23
+ description TEXT
24
+ )
25
+ ''')
26
+ cursor.execute('''
27
+ CREATE TABLE IF NOT EXISTS students (
28
+ enrollment_no TEXT PRIMARY KEY,
29
+ student_name TEXT NOT NULL,
30
+ student_email TEXT,
31
+ course_id TEXT,
32
+ FOREIGN KEY (course_id) REFERENCES courses(course_id) ON DELETE CASCADE
33
+ )
34
+ ''')
35
+
36
+ # Seed initial Relational Data if empty
37
+ cursor.execute("SELECT COUNT(*) FROM courses")
38
+ if cursor.fetchone()[0] == 0:
39
+ cursor.execute("INSERT INTO courses VALUES ('C101', 'Guitar Basics', 'John Smith', 'john@music.com', 1500.0, 'Intro to acoustic')")
40
+ cursor.execute("INSERT INTO courses VALUES ('C102', 'Advanced Guitar', 'John Smith', 'john@music.com', 2200.0, 'Shredding techniques')")
41
+ cursor.execute("INSERT INTO courses VALUES ('C201', 'Drums & Rhythm', 'Elena Rostova', 'elena@music.com', 1800.0, 'Percussion basics')")
42
+
43
+ cursor.execute("INSERT INTO students VALUES ('S1001', 'Alice Cooper', 'alice@rock.com', 'C101')")
44
+ cursor.execute("INSERT INTO students VALUES ('S1002', 'Bob Dylan', 'bob@folk.com', 'C201')")
45
+
46
+ conn.commit()
47
+ conn.close()
48
+
49
+ def get_relational_stats():
50
+ conn = sqlite3.connect(DB_FILE)
51
+ df_courses = pd.read_sql_query("SELECT * FROM courses", conn)
52
+ df_students = pd.read_sql_query("SELECT * FROM students", conn)
53
+ conn.close()
54
+ return df_courses, df_students
55
+
56
+ # ==========================================
57
+ # 2. GRAPH DATABASE (CognoDB Cloud / Neo4j)
58
+ # ==========================================
59
+ class GraphDBManager:
60
  def __init__(self):
61
+ # Hugging Face Secrets mapping
62
+ self.uri = os.environ.get("NEO4J_URI", "bolt://localhost:7687")
63
+ self.user = os.environ.get("NEO4J_USER", "neo4j")
64
+ self.password = os.environ.get("NEO4J_PASSWORD", "password")
65
  self.driver = None
 
66
 
67
+ def get_driver(self):
68
+ if self.driver is None:
69
+ try:
70
+ self.driver = GraphDatabase.driver(self.uri, auth=(self.user, self.password))
71
+ self.driver.verify_connectivity()
72
+ except exceptions.ServiceUnavailable:
73
+ self.driver = None
74
+ except Exception as e:
75
+ self.driver = None
76
+ return self.driver
77
+
78
+ def execute_query(self, query, parameters=None):
79
+ """Executes parameterized Cypher query with graceful error handling."""
80
+ driver = self.get_driver()
81
+ if not driver:
82
+ return None, "❌ Database Unreachable: Check CognoDB URI and Credentials in HF Secrets."
83
+
84
  try:
85
+ with driver.session() as session:
86
+ result = session.run(query, parameters or {})
87
+ return [record.data() for record in result], None
88
+ except exceptions.AuthError:
89
+ return None, "❌ Authentication Error: Invalid CognoDB Credentials."
 
90
  except Exception as e:
91
+ return None, f"❌ Cypher Error: {str(e)}"
 
92
 
93
+ graph_db = GraphDBManager()
 
 
 
 
 
 
 
 
94
 
95
+ def seed_graph_database():
96
+ """Seeds the graph database with complex relationships."""
97
+ cypher = """
98
+ // Create Courses & Prerequisite Chain
99
+ MERGE (c1:Course {id: 'C101', instrument: 'Guitar Basics'})
100
+ MERGE (c2:Course {id: 'C102', instrument: 'Advanced Guitar'})
101
+ MERGE (c3:Course {id: 'C103', instrument: 'Masterclass Guitar'})
102
+ MERGE (c2)-[:REQUIRES_PREREQUISITE]->(c1)
103
+ MERGE (c3)-[:REQUIRES_PREREQUISITE]->(c2)
104
+
105
+ MERGE (d1:Course {id: 'C201', instrument: 'Drums & Rhythm'})
106
 
107
+ // Create Faculty & Slots (Intentional Conflict setup for F01 & F02 in Room 101)
108
+ MERGE (f1:Faculty {id: 'F01', name: 'John Smith'})
109
+ MERGE (f2:Faculty {id: 'F02', name: 'Elena Rostova'})
110
+ MERGE (s1:SessionSlot {id: 'SLOT_MON_10', day: 'Monday', time: '10:00 AM'})
111
+ MERGE (r1:Room {room_number: '101'})
112
+
113
+ MERGE (s1)-[:HELD_IN_ROOM]->(r1)
114
+ MERGE (f1)-[:SCHEDULED_FOR]->(s1)<-[:OCCURS_AT]-(c1)
115
+ MERGE (f2)-[:SCHEDULED_FOR]->(s1)<-[:OCCURS_AT]-(d1)
116
 
117
+ // Create Students for Ensemble Matchmaker
118
+ MERGE (st1:Student {id: 'S1001', name: 'Alice'})
119
+ MERGE (st2:Student {id: 'S1002', name: 'Bob'})
120
+ MERGE (st1)-[:ENROLLED_IN]->(c1)
121
+ MERGE (st2)-[:ENROLLED_IN]->(d1)
122
+ MERGE (st1)-[:ATTENDS_SLOT]->(s1)
123
+ MERGE (st2)-[:ATTENDS_SLOT]->(s1)
124
+ """
125
+ res, err = graph_db.execute_query(cypher)
126
+ if err: return err
127
+ return "✅ Graph Database Seeded Successfully!"
128
+
129
+ def get_schedule_conflicts():
130
+ """Awkward RDBMS Query 1: Find double-booked rooms using Graph Traversal."""
131
+ cypher = """
132
+ MATCH (s:SessionSlot)-[:HELD_IN_ROOM]->(r:Room)
133
+ MATCH (f:Faculty)-[:SCHEDULED_FOR]->(s)<-[:OCCURS_AT]-(c:Course)
134
+ WITH r, s, collect(f.name + ' (' + c.instrument + ')') AS bookings
135
+ WHERE size(bookings) > 1
136
+ RETURN r.room_number AS Room, s.day AS Day, s.time AS Time,
137
+ apoc.text.join(bookings, ' AND ') AS Conflicting_Classes
138
+ """
139
+ # Note: If APOC is not available on free tier CognoDB, we format in python:
140
+ cypher_no_apoc = """
141
+ MATCH (s:SessionSlot)-[:HELD_IN_ROOM]->(r:Room)
142
+ MATCH (f:Faculty)-[:SCHEDULED_FOR]->(s)<-[:OCCURS_AT]-(c:Course)
143
+ WITH r, s, collect(f.name + ' teaching ' + c.instrument) AS bookings
144
+ WHERE size(bookings) > 1
145
+ RETURN r.room_number AS Room, s.day AS Day, s.time AS Time, bookings AS Conflicting_Classes
146
+ """
147
+ res, err = graph_db.execute_query(cypher_no_apoc)
148
+ if err: return pd.DataFrame([{"Error": err}])
149
+ if not res: return pd.DataFrame([{"Status": "No Conflicts Detected! All clear."}])
150
+
151
+ # Format list to string for Gradio dataframe
152
+ for r in res:
153
+ r['Conflicting_Classes'] = " ⚠️ VS ⚠️ ".join(r['Conflicting_Classes'])
154
+ return pd.DataFrame(res)
155
+
156
+ def get_prerequisites(course_id="C103"):
157
+ """Multi-hop traversal: Variable length path matching (*1..5)"""
158
+ cypher = """
159
+ MATCH path = (target:Course {id: $cid})-[:REQUIRES_PREREQUISITE*1..5]->(prereq:Course)
160
+ RETURN target.instrument AS Target_Course,
161
+ [c IN nodes(path) | c.instrument] AS Prerequisite_Path
162
+ """
163
+ res, err = graph_db.execute_query(cypher, {"cid": course_id})
164
+ if err: return pd.DataFrame([{"Error": err}])
165
+ if not res: return pd.DataFrame([{"Status": "No prerequisites found."}])
166
+
167
+ for r in res:
168
+ r['Prerequisite_Path'] = " ➔ ".join(r['Prerequisite_Path'])
169
+ return pd.DataFrame(res)
170
 
171
+ def find_ensembles():
172
+ """Awkward RDBMS Query 2: Matchmaker for complementary skills in same time slot."""
173
+ cypher = """
174
+ MATCH (s1:Student)-[:ATTENDS_SLOT]->(slot:SessionSlot)<-[:ATTENDS_SLOT]-(s2:Student)
175
+ MATCH (s1)-[:ENROLLED_IN]->(c1:Course)
176
+ MATCH (s2)-[:ENROLLED_IN]->(c2:Course)
177
+ WHERE s1.id < s2.id AND c1.instrument <> c2.instrument
178
+ RETURN slot.day + ' ' + slot.time AS Practice_Slot,
179
+ s1.name + ' (' + c1.instrument + ')' AS Musician_1,
180
+ s2.name + ' (' + c2.instrument + ')' AS Musician_2
181
+ """
182
+ res, err = graph_db.execute_query(cypher)
183
+ if err: return pd.DataFrame([{"Error": err}])
184
+ if not res: return pd.DataFrame([{"Status": "No ensemble matches found."}])
185
+ return pd.DataFrame(res)