VectorV17 commited on
Commit
ef752ac
·
verified ·
1 Parent(s): 9a354ad

Delete database.py

Browse files
Files changed (1) hide show
  1. database.py +0 -185
database.py DELETED
@@ -1,185 +0,0 @@
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("COGNODB_URI", "bolt://localhost:7687")
63
- self.user = os.environ.get("COGNODB_USER", "neo4j")
64
- self.password = os.environ.get("COGNODB_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)