VectorV17 commited on
Commit
9f59c2f
Β·
verified Β·
1 Parent(s): 5f2c2b0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -136
app.py CHANGED
@@ -1,154 +1,104 @@
1
- import os
2
  import gradio as gr
3
- from huggingface_hub import InferenceClient
4
- from database import db
 
 
 
5
 
6
- # Initialize HF Serverless Inference Client
7
- HF_TOKEN = os.getenv("HF_TOKEN", None)
8
- client = InferenceClient("Qwen/Qwen2.5-7B-Instruct", token=HF_TOKEN)
9
 
10
- def format_graph_context(records):
11
- """Formats retrieved graph records into readable LLM context and UI HTML."""
12
- if not records:
13
- return "No matching nodes found in Knowledge Graph.", ""
14
 
15
- context_str = "RELEVANT KNOWLEDGE GRAPH NEIGHBORHOOD:\n"
16
- formatted_html = "<div style='font-size: 13px; line-height: 1.6;'>"
17
 
18
- for r in records:
19
- context_str += f"- Article: {r['title']}\n"
20
- context_str += f" Content: {r['content']}\n"
21
- if r.get('category'):
22
- context_str += f" Category: {r['category']}\n"
23
- if r.get('errorCode'):
24
- context_str += f" Resolves Error: {r['errorCode']} ({r.get('issueDetail', '')})\n"
25
-
26
- # Multi-hop prerequisites
27
- prereqs = [p['title'] for p in r.get('prerequisites', []) if p.get('title')]
28
- if prereqs:
29
- context_str += f" Prerequisite Action Required: {', '.join(prereqs)}\n"
30
- context_str += "\n"
31
-
32
- # UI Visual Debugger Content
33
- formatted_html += f"<b>πŸ“„ Article:</b> {r['title']}<br/>"
34
- formatted_html += f"<b>πŸ“‚ Category:</b> {r.get('category', 'N/A')}<br/>"
35
- if prereqs:
36
- formatted_html += f"<b>πŸ”— 2-Hop Prerequisite:</b> <span style='color: #d97706;'>{', '.join(prereqs)}</span><br/>"
37
- formatted_html += "<hr style='margin: 8px 0; border-color: #eee;'/>"
38
-
39
- formatted_html += "</div>"
40
- return context_str, formatted_html
41
-
42
- def bot_respond(user_message, history):
43
- """Processes user input, queries CognoDB, and streams LLM response."""
44
- if history is None:
45
- history = []
46
 
47
- if not user_message.strip():
48
- yield history, "<i>No query entered.</i>"
49
- return
50
 
51
- # Step 1: Multi-Hop Cypher Traversal on CognoDB
52
- records, db_error = db.query_graph_neighborhood(user_message)
53
-
54
- if db_error:
55
- graph_context = f"Database Alert: {db_error}"
56
- ui_debug = f"<span style='color:red;'>⚠️ {db_error}</span>"
57
- else:
58
- graph_context, ui_debug = format_graph_context(records)
59
-
60
- # Step 2: Construct Prompt with Graph Context Injection
61
- system_prompt = (
62
- "You are the Wexa Knowledge Graph Assistant. "
63
- "Answer the user's question accurately and concisely using ONLY the retrieved Graph Context below. "
64
- "If prerequisites are mentioned in the context, explicitly state them to the user.\n\n"
65
- f"{graph_context}"
66
- )
67
-
68
- messages = [{"role": "system", "content": system_prompt}]
69
-
70
- # Reconstruct conversation history
71
- for msg in history:
72
- messages.append(msg)
73
- messages.append({"role": "user", "content": user_message})
74
-
75
- # Update chatbot UI state
76
- history.append({"role": "user", "content": user_message})
77
- history.append({"role": "assistant", "content": ""})
78
- yield history, ui_debug
79
-
80
- # Step 3: Stream Response from Hugging Face Inference API
81
- try:
82
- accumulated_text = ""
83
- for chunk in client.chat_completion(messages, max_tokens=512, stream=True, temperature=0.3):
84
- token = chunk.choices[0].delta.content
85
- if token:
86
- accumulated_text += token
87
- history[-1]["content"] = accumulated_text
88
- yield history, ui_debug
89
- except Exception as e:
90
- history[-1]["content"] = f"An error occurred while generating the response: {str(e)}"
91
- yield history, ui_debug
92
 
93
  # --- Gradio UI Layout ---
94
- custom_css = """
95
- #header { text-align: center; margin-bottom: 10px; }
96
- #status-badge { padding: 8px 12px; border-radius: 6px; font-weight: bold; margin-bottom: 10px; }
97
- .online { background-color: #dcfce7; color: #15803d; border: 1px solid #86efac; }
98
- .offline { background-color: #fee2e2; color: #b91c1c; border: 1px solid #fca5a5; }
99
- """
100
 
101
- with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:
102
- gr.Markdown("# πŸ•ΈοΈ GraphRAG FAQ AI Agent", elem_id="header")
103
- gr.Markdown("An intelligent support assistant powered by **CognoDB Cloud (Graph Database)** and **Qwen2.5-7B**.")
104
-
105
- # Live Database Status Indicator
106
- is_online = db.is_connected()
107
- status_class = "online" if is_online else "offline"
108
- status_text = "🟒 CognoDB Cloud: Connected & Ready" if is_online else "πŸ”΄ CognoDB Cloud: Unreachable (Fallback Mode)"
109
 
110
- gr.HTML(f"<div id='status-badge' class='{status_class}'>{status_text}</div>")
111
-
112
- with gr.Row():
113
- with gr.Column(scale=3):
114
- # FIXED: Removed type="messages" for Gradio 5/6 compatibility
115
- chatbot = gr.Chatbot(height=420)
116
- msg_input = gr.Textbox(
117
- placeholder="Ask a question (e.g., 'How do I fix 401 unauthorized errors?')...",
118
- show_label=False
119
- )
120
 
121
  with gr.Row():
122
- send_btn = gr.Button("Submit Query", variant="primary")
123
- clear_btn = gr.Button("Clear Chat")
124
 
125
- gr.Examples(
126
- examples=[
127
- "How do I fix 401 unauthorized errors?",
128
- "How can I rotate my API keys?",
129
- "How does graph context optimize token economics?"
130
- ],
131
- inputs=msg_input
132
  )
133
 
134
- with gr.Column(scale=2):
135
- gr.Markdown("### πŸ” Live Graph Retrieval Inspector")
136
- graph_inspector = gr.HTML("<i>Submit a query to inspect live Cypher 2-hop traversal context...</i>")
137
-
138
- # Event Wiring
139
- send_btn.click(
140
- bot_respond,
141
- inputs=[msg_input, chatbot],
142
- outputs=[chatbot, graph_inspector]
143
- ).then(lambda: "", None, msg_input)
144
-
145
- msg_input.submit(
146
- bot_respond,
147
- inputs=[msg_input, chatbot],
148
- outputs=[chatbot, graph_inspector]
149
- ).then(lambda: "", None, msg_input)
150
-
151
- clear_btn.click(lambda: ([], "<i>Chat cleared.</i>"), None, [chatbot, graph_inspector])
152
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  if __name__ == "__main__":
154
- demo.launch()
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import pandas as pd
3
+ from database import (
4
+ init_sqlite, get_relational_stats, seed_graph_database,
5
+ get_schedule_conflicts, get_prerequisites, find_ensembles
6
+ )
7
 
8
+ # Initialize Relational SQLite DB on startup
9
+ init_sqlite()
 
10
 
11
+ # --- Wrapper Functions for Gradio UI ---
12
+ def refresh_dashboard():
13
+ df_c, df_s = get_relational_stats()
14
+ return df_c, df_s, f"Total Courses: {len(df_c)}", f"Total Students: {len(df_s)}"
15
 
16
+ def trigger_graph_seed():
17
+ return seed_graph_database()
18
 
19
+ def trigger_conflict_check():
20
+ return get_schedule_conflicts()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
+ def trigger_prereq_check(course_id):
23
+ if not course_id: course_id = "C103"
24
+ return get_prerequisites(course_id)
25
 
26
+ def trigger_ensemble_finder():
27
+ return find_ensembles()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
  # --- Gradio UI Layout ---
30
+ theme = gr.themes.Soft(primary_hue="indigo", secondary_hue="blue")
 
 
 
 
 
31
 
32
+ with gr.Blocks(theme=theme, title="Music Academy Graph System") as demo:
33
+ gr.Markdown("# 🎡 Music Academy Management System (Polyglot Architecture)")
34
+ gr.Markdown("Combining local Relational records with powerful remote Graph database logic (CognoDB).")
 
 
 
 
 
35
 
36
+ with gr.Tabs():
37
+
38
+ # TAB 1: Relational Dashboard (Legacy / Standard CRUD)
39
+ with gr.Tab("πŸ“‹ Relational Catalog (SQLite)"):
40
+ gr.Markdown("### Standard Tabular Records")
41
+ with gr.Row():
42
+ stat_courses = gr.Textbox(label="Courses Metric", interactive=False)
43
+ stat_students = gr.Textbox(label="Students Metric", interactive=False)
 
 
44
 
45
  with gr.Row():
46
+ table_courses = gr.Dataframe(label="Courses Table", interactive=False)
47
+ table_students = gr.Dataframe(label="Students Table", interactive=False)
48
 
49
+ refresh_btn = gr.Button("πŸ”„ Refresh Relational Data", variant="primary")
50
+ refresh_btn.click(
51
+ fn=refresh_dashboard,
52
+ outputs=[table_courses, table_students, stat_courses, stat_students]
 
 
 
53
  )
54
 
55
+ # TAB 2: Graph Intelligence (CognoDB)
56
+ with gr.Tab("πŸ•ΈοΈ Graph Intelligence (CognoDB)"):
57
+ gr.Markdown("### Graph-Aware Operations")
58
+ gr.Markdown("> *These operations utilize Cypher traversals in Neo4j to solve problems that are heavily taxing or awkward in traditional SQL databases.*")
59
+
60
+ with gr.Row():
61
+ seed_btn = gr.Button("🌱 1. Seed Graph Database (Run First)", variant="secondary")
62
+ seed_status = gr.Textbox(label="Seed Status", interactive=False)
63
+ seed_btn.click(fn=trigger_graph_seed, outputs=seed_status)
 
 
 
 
 
 
 
 
 
64
 
65
+ gr.Divider()
66
+
67
+ with gr.Row():
68
+ with gr.Column():
69
+ gr.Markdown("#### βš”οΈ Schedule Conflict Engine")
70
+ gr.Markdown("Detects overlapping course schedules in rooms using a multi-node traversal.")
71
+ conflict_btn = gr.Button("Run Conflict Detector", variant="primary")
72
+ conflict_table = gr.Dataframe(label="Conflict Results")
73
+ conflict_btn.click(fn=trigger_conflict_check, outputs=conflict_table)
74
+
75
+ with gr.Column():
76
+ gr.Markdown("#### 🎸 Ensemble Matchmaker")
77
+ gr.Markdown("Finds students with complementary instruments available during the same time slot.")
78
+ ensemble_btn = gr.Button("Run Matchmaker", variant="primary")
79
+ ensemble_table = gr.Dataframe(label="Matchmaker Results")
80
+ ensemble_btn.click(fn=trigger_ensemble_finder, outputs=ensemble_table)
81
+
82
+ gr.Divider()
83
+
84
+ with gr.Row():
85
+ with gr.Column(scale=1):
86
+ gr.Markdown("#### πŸ“š Prerequisite Pathway Tracker")
87
+ gr.Markdown("Executes a multi-hop traversal (`*1..5`) to map the entire learning path.")
88
+ course_input = gr.Textbox(label="Enter Course ID (e.g., C103)", value="C103")
89
+ prereq_btn = gr.Button("Map Pathway", variant="primary")
90
+ with gr.Column(scale=2):
91
+ prereq_table = gr.Dataframe(label="Pathway Results")
92
+ prereq_btn.click(fn=trigger_prereq_check, inputs=course_input, outputs=prereq_table)
93
+
94
+ # Load relational data on app startup
95
+ demo.load(fn=refresh_dashboard, outputs=[table_courses, table_students, stat_courses, stat_students])
96
+
97
+ # Launch app with native Gradio Authentication
98
  if __name__ == "__main__":
99
+ demo.launch(
100
+ server_name="0.0.0.0",
101
+ server_port=7860,
102
+ auth=("admin", "admin123"), # Simple login security
103
+ auth_message="Welcome to Music Academy Mgmt. Please login (admin / admin123)"
104
+ )