Yaswanth123 commited on
Commit
fd80499
·
verified ·
1 Parent(s): 08172e3

Update app.py With Proper UI Enhancements

Browse files
Files changed (1) hide show
  1. app.py +460 -163
app.py CHANGED
@@ -1,196 +1,493 @@
1
-
 
2
 
3
  import gradio as gr
4
- import logging
5
  import os
6
- from typing import List, Dict, Any, Optional
 
 
7
 
8
- # --- 1. CONFIGURATION FIRST ---
9
- from config import initialize_dspy
10
- custom_lm = initialize_dspy()
11
 
12
- # --- 2. Now Import Other Modules ---
13
  from config import (
14
- API_KEY, STATE_STAGE, STATE_HISTORY, STAGE_START, STAGE_EXPLAINING,
15
- STATE_EXPLAINER_PROMPT
 
 
16
  )
 
17
  from resource_processor import process_uploaded_files
18
- from orchestrator import process_chat_message
19
 
20
- # Setup basic logging
21
- logging.basicConfig(level=logging.INFO, format='{levelname} {asctime} [%(name)s]: {message}', style='{')
22
  logger = logging.getLogger(__name__)
23
 
24
- def respond(
25
- user_message: str, # The content from the textbox
26
- chat_history_ui: List[Dict[str, str]],
27
- app_state: Dict[str, Any],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  uploaded_files: Optional[List[Any]],
29
- explainer_prompt_display: str
 
 
 
30
  ):
31
  """
32
- Core backend function. Receives UI state, calls orchestrator, and returns updated UI state.
33
- This version also handles clearing the input textbox directly.
34
  """
35
- # Guard clause: If user sends an empty message, do nothing.
36
- if not user_message.strip():
37
- # Return all components unchanged, including the uncleared textbox
38
- return chat_history_ui, app_state, gr.update(), gr.update(), gr.update(), user_message
39
-
40
- # Guard clause: If the API key is missing, the app won't work.
41
- if not custom_lm:
42
- error_msg = "FATAL ERROR: AI Backend is not configured. Please check your .env file for a valid GOOGLE_API_KEY."
43
- chat_history_ui.append({"role": "user", "content": user_message})
44
- chat_history_ui.append({"role": "assistant", "content": error_msg})
45
- # Keep file uploader visible on error, but clear the textbox.
46
- yield chat_history_ui, app_state, gr.update(visible=True), gr.update(), gr.update(), ""
47
- return
48
 
49
- # --- Step 1: Update UI and State with User's Message ---
50
- chat_history_ui.append({"role": "user", "content": user_message})
51
- app_state[STATE_HISTORY].append({'role': 'user', 'parts': [{'text': user_message}]})
52
- chat_history_ui.append({"role": "assistant", "content": ""}) # Placeholder for bot response
53
 
54
- # First yield for immediate UI update. Hide file uploader, but don't clear textbox yet.
55
- yield chat_history_ui, app_state, gr.update(visible=False), gr.update(), gr.update(), user_message
 
 
 
 
 
 
 
 
56
 
57
- # --- Step 2: Handle File Uploads ---
58
- processed_file_data = None
59
- if app_state.get(STATE_STAGE) == STAGE_START and uploaded_files:
60
- logger.info(f"Processing {len(uploaded_files)} files for new chat session.")
61
- processed_file_data = process_uploaded_files(uploaded_files)
 
 
 
 
 
 
 
 
62
 
63
- # --- Step 3: Call the Main Agent Logic (The Orchestrator) ---
 
 
 
 
 
 
 
 
 
 
64
  try:
65
- final_user_facing_reply, new_state = process_chat_message(
66
- user_message_text=user_message,
67
- current_session_state=app_state,
68
- uploaded_resource_data=processed_file_data,
69
- modified_explainer_prompt=explainer_prompt_display
70
- )
71
- app_state = new_state
 
 
 
 
 
 
 
 
 
 
 
72
  except Exception as e:
73
- logger.error(f"Critical error in orchestrator call: {e}", exc_info=True)
74
- final_user_facing_reply = f"[SYSTEM ERROR: An exception occurred in the agent's logic. Please check the logs. Details: {e}]"
75
-
76
- # --- Step 4: Update the UI with the AI's Final Response ---
77
- syllabus_flag_data = app_state.get("display_syllabus_flag")
78
- if syllabus_flag_data:
79
- syllabus_content = syllabus_flag_data.get("content", "Error displaying syllabus.")
80
- chat_history_ui[-1] = {"role": "assistant", "content": syllabus_content}
81
- chat_history_ui.append({"role": "assistant", "content": final_user_facing_reply})
82
- app_state.pop("display_syllabus_flag", None)
83
- else:
84
- chat_history_ui[-1]['content'] = final_user_facing_reply
85
-
86
- # --- Step 5: Determine visibility of explainer prompt box for the final return ---
87
- prompt_update = gr.update(visible=False)
88
- header_update = gr.update(visible=False)
89
- if new_state.get(STATE_STAGE) == STAGE_EXPLAINING:
90
- prompt_value = explainer_prompt_display if explainer_prompt_display else new_state.get(STATE_EXPLAINER_PROMPT)
91
- prompt_update = gr.update(value=prompt_value, visible=True)
92
- header_update = gr.update(visible=True)
93
-
94
- # Final yield: return all component states AND an empty string to clear the textbox.
95
- yield chat_history_ui, app_state, gr.update(visible=False), header_update, prompt_update, ""
96
-
97
- def start_new_session():
98
- """ Resets the chat history, internal state, and all UI components for a new conversation. """
99
- logger.info("UI action: Starting new session.")
100
- initial_state = {
101
- STATE_STAGE: STAGE_START,
102
- STATE_HISTORY: [{'role': 'model', 'parts': [{'text': 'Hello! What would you like to learn about today?'}]}]
103
- }
104
- initial_chat_history_ui = [{"role": "assistant", "content": "Hello! What would you like to learn about today?"}]
105
-
106
- return (
107
- initial_chat_history_ui,
108
- initial_state,
109
- gr.update(value=[], visible=True), # File uploader
110
- gr.update(visible=False), # Prompt header
111
- gr.update(value="", visible=False), # Prompt textbox
112
- "" # Clear the main textbox
 
 
 
 
 
 
 
 
 
 
 
113
  )
 
 
 
 
 
 
 
114
 
115
- # --- 3. Gradio Interface Definition ---
116
- with gr.Blocks(theme=gr.themes.Soft(), title="Forge Guide AI Tutor") as demo:
117
- gr.Markdown("# Forge Guide: AI Syllabus Architect")
118
- gr.Markdown("Start a new conversation by describing what you want to learn. For new chats, you can also upload resources like PDFs or text files.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
 
120
- app_state = gr.State({
121
- STATE_STAGE: STAGE_START,
122
- STATE_HISTORY: [{'role': 'model', 'parts': [{'text': 'Hello! What would you like to learn about today?'}]}]
123
- })
124
-
125
- with gr.Row():
126
- with gr.Column(scale=4):
127
- chatbot = gr.Chatbot(
128
- [{"role": "assistant", "content": "Hello! What would you like to learn about today?"}],
129
- elem_id="chatbot",
130
- height=650,
131
- render_markdown=True,
132
- avatar_images=(None, "https://i.imgur.com/3pyR0Vf.png"),
133
- type='messages',
134
- latex_delimiters=[{"left": "$$", "right": "$$", "display": True}, {"left": "$", "right": "$", "display": False}]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  )
136
 
137
- with gr.Row():
138
- txt_input = gr.Textbox(
139
- scale=4,
140
- show_label=False,
141
- placeholder="e.g., 'I want to build a RAG pipeline from scratch'",
142
- container=False,
143
- )
144
- submit_btn = gr.Button("Send", variant="primary", scale=1, min_width=100)
145
-
146
- with gr.Column(scale=1):
147
- gr.Markdown("### Resources")
148
- file_uploader = gr.File(
149
- file_count="multiple",
150
- label="Upload for New Chat (Optional)",
151
- file_types=[".pdf", ".txt", ".docx"],
152
- visible=True,
153
- interactive=True,
154
- )
155
- new_session_btn = gr.Button("Start New Session", variant="secondary")
156
- tutor_prompt_header = gr.Markdown("### Tutor Persona Prompt", visible=False)
157
- explainer_prompt_display = gr.Textbox(
158
- label="You can modify the tutor's persona and instructions here:",
159
- lines=15,
160
- interactive=True,
161
- visible=False,
162
- )
163
 
164
- # --- 4. Event Listeners: Wiring the UI to the Backend ---
165
- submit_actions = [txt_input, chatbot, app_state, file_uploader, explainer_prompt_display]
166
- output_components = [chatbot, app_state, file_uploader, tutor_prompt_header, explainer_prompt_display, txt_input]
167
 
168
- submit_btn.click(
169
- fn=respond,
170
- inputs=submit_actions,
171
- outputs=output_components,
172
- )
 
 
 
173
 
174
- txt_input.submit(
175
- fn=respond,
176
- inputs=submit_actions,
177
- outputs=output_components,
178
- )
179
 
180
- new_session_btn.click(
181
- fn=start_new_session,
182
- inputs=[],
183
- outputs=output_components
184
- )
 
185
 
186
- # --- 5. Launch the App ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
  if __name__ == "__main__":
188
- if not API_KEY:
189
- print("\n" + "="*60)
190
- print("CRITICAL ERROR: Cannot launch Gradio app.")
191
- print("Your GOOGLE_API_KEY is not set in the .env file.")
192
- print("="*60 + "\n")
 
 
193
  else:
194
- print("Launching Gradio app...")
195
- demo.queue().launch(debug=True)
196
-
 
1
+ # FILE: app.py
2
+ # FINAL REFACTORED VERSION WITH ADVANCED UI/UX
3
 
4
  import gradio as gr
 
5
  import os
6
+ import logging
7
+ from typing import Dict, Any, List, Optional
8
+ from dotenv import load_dotenv
9
 
10
+ # --- Backend & Configuration Imports ---
11
+ load_dotenv()
 
12
 
13
+ import dspy
14
  from config import (
15
+ initialize_dspy, RateLimiter,
16
+ STATE_STAGE, STATE_HISTORY, STATE_CURRENT_TITLE, STATE_GENERATED_TITLE,
17
+ STATE_EXPLAINER_PROMPT, STATE_TRANSITION_EXPLAINER_FLAG, STAGE_START,
18
+ STATE_IS_FIRST_TURN, DEFAULT_CHAT_TITLE,
19
  )
20
+ from orchestrator import process_chat_message, initialize_orchestrator_modules
21
  from resource_processor import process_uploaded_files
 
22
 
23
+ # --- Setup Logging ---
24
+ logging.basicConfig(level=logging.INFO, format='{levelname} {asctime} {name}: {message}', style='{')
25
  logger = logging.getLogger(__name__)
26
 
27
+ # --- Application Mode & UI Configuration ---
28
+ APP_MODE = os.getenv("APP_MODE", "visitor").lower()
29
+ if APP_MODE not in ["admin", "visitor"]:
30
+ raise ValueError("APP_MODE environment variable must be 'admin' or 'visitor'")
31
+
32
+ UI_FEEDBACK_MAP = {
33
+ "PROCESSING_INPUT": "🧠 Thinking...",
34
+ "ANALYZING_RESOURCES_INITIAL": "📄 Analyzing your documents...",
35
+ "GENERATING_SYLLABUS": "✍️ Crafting syllabus...",
36
+ "EXPLAINER_RESPONSE": "💬 Tutor is responding...",
37
+ # NOTE: The UI will use these for more granular feedback in the future if needed.
38
+ # For now, we use a general "Thinking..." message for stability during backend processing.
39
+ }
40
+
41
+ # --- Helper & Core Functions ---
42
+
43
+ def initialize_session_state() -> Dict[str, Any]:
44
+ """Creates a fresh session state dictionary, including the initial greeting."""
45
+ initial_history = [{'role': 'model', 'parts': [{'text': "Hello! I'm ready to help build a personalized syllabus. What topic are you interested in learning about?"}]}]
46
+ return {
47
+ STATE_STAGE: STAGE_START,
48
+ STATE_HISTORY: initial_history,
49
+ STATE_CURRENT_TITLE: DEFAULT_CHAT_TITLE,
50
+ STATE_IS_FIRST_TURN: True,
51
+ }
52
+
53
+ def start_session(api_key: str, api_tier: str):
54
+ """
55
+ (Visitor Mode) Validates API, initializes backends, and transitions UI.
56
+ ADDED: Debugging print statements to trace the authentication flow.
57
+ """
58
+ # --- START OF DEBUG BLOCK ---
59
+ print("\n--- [start_session] Function Entered ---")
60
+ # Use slicing to avoid printing the full secret key in logs
61
+ print(f"[start_session] Received API Key ending in: '...{api_key[-4:] if len(api_key) > 4 else api_key}'")
62
+ print(f"[start_session] Received API Tier: {api_tier}")
63
+ # --- END OF DEBUG BLOCK ---
64
+
65
+ # --- Case 1: Empty API Key ---
66
+ if not api_key.strip():
67
+ print("[start_session] DEBUG: Condition MET - API Key is empty or whitespace.")
68
+ error_msg = "<p style='color:red;'>API Key cannot be empty. Please provide a valid key.</p>"
69
+ yield (gr.update(visible=True), gr.update(visible=False), None, gr.update(value=error_msg, visible=True))
70
+ print("--- [start_session] END ---\n")
71
+ return
72
+
73
+ # --- Case 2: Authentication with DSPy Fails ---
74
+ print("[start_session] DEBUG: Attempting to call initialize_dspy...")
75
+ # Store the result in a variable so we can print it
76
+ auth_result = initialize_dspy(api_key=api_key)
77
+ print(f"[start_session] DEBUG: Result from initialize_dspy is: '{auth_result}' (Type: {type(auth_result)})")
78
+
79
+ if not isinstance(auth_result, list) :
80
+ #
81
+ print("[start_session] DEBUG: Condition MET - `if not auth_result` is TRUE. Authentication failed.")
82
+ error_msg = "<p style='color:red;'>Authentication failed. The provided API key is invalid or has expired. Please check the key and try again.</p>"
83
+ yield (gr.update(visible=True), gr.update(visible=False), None, gr.update(value=error_msg, visible=True))
84
+ print("--- [start_session] END ---\n")
85
+ return
86
+
87
+ print("[start_session] DEBUG: Condition SKIPPED - `if not auth_result` is FALSE. Assuming auth succeeded.")
88
+
89
+ # --- Case 3: Backend Module Initialization Fails ---
90
+ print("[start_session] DEBUG: Attempting to call initialize_orchestrator_modules...")
91
+ modules_result = initialize_orchestrator_modules()
92
+ print(f"[start_session] DEBUG: Result from initialize_orchestrator_modules is: {modules_result}")
93
+
94
+ if not modules_result:
95
+ print("[start_session] DEBUG: Condition MET - Backend module initialization failed.")
96
+ error_msg = "<p style='color:red;'>Failed to initialize backend AI modules after authentication. Please contact support.</p>"
97
+ yield (gr.update(visible=True), gr.update(visible=False), None, gr.update(value=error_msg, visible=True))
98
+ print("--- [start_session] END ---\n")
99
+ return
100
+
101
+ # --- Case 4: Success ---
102
+ print("[start_session] DEBUG: All checks passed. Proceeding to success case.")
103
+ max_calls = 7 if "Free" in api_tier else 1000
104
+ limiter = RateLimiter(max_calls=max_calls, time_period=60)
105
+
106
+ yield (
107
+ gr.update(visible=False), # Hide API view
108
+ gr.update(visible=True), # Show chat view
109
+ limiter, # Set the rate limiter state
110
+ gr.update(visible=False), # Hide the error message
111
+ )
112
+ print("--- [start_session] END: UI transitioned successfully. ---\n")
113
+ # FILE: app.py
114
+ # REPLACE the existing function with this new "consumer" version.
115
+
116
+ def handle_user_interaction(
117
+ user_message: str,
118
  uploaded_files: Optional[List[Any]],
119
+ current_state: Dict[str, Any],
120
+ file_names_state: List[str],
121
+ limiter: Optional[RateLimiter],
122
+ modified_explainer_prompt: str
123
  ):
124
  """
125
+ Main generator function, refactored for cleaner history management and clarity
126
+ while consuming the stream of updates from the orchestrator.
127
  """
128
+ # --- 1. PREPARATION AND UI UPDATE (YIELD 1) ---
129
+
130
+ # Get the *current* UI-compatible history from the state for a clean start
131
+ # We will build on top of this for all UI updates
132
+ ui_history = []
133
+ for msg in current_state.get(STATE_HISTORY, []):
134
+ if msg.get('message_type') != "internal_resource_summary":
135
+ role = "assistant" if msg.get("role") == "model" else "user"
136
+ content = msg.get("content", "") or (msg.get("parts")[0].get("text", "") if msg.get("parts") else "")
137
+ ui_history.append({"role": role, "content": content})
 
 
 
138
 
139
+ # Add the new user message in the clean UI format
140
+ ui_history.append({"role": "user", "content": user_message})
141
+ # Add the initial placeholder for the bot's response/status
142
+ ui_history.append({"role": "assistant", "content": f"*{UI_FEEDBACK_MAP['PROCESSING_INPUT']}*"})
143
 
144
+ # Update the backend-formatted history in the state for the orchestrator
145
+ backend_history = current_state.get(STATE_HISTORY, [])
146
+ backend_history.append({'role': 'user', 'parts': [{'text': user_message}]})
147
+ current_state[STATE_HISTORY] = backend_history
148
+
149
+ # Handle file display logic (this part remains the same)
150
+ all_file_names = sorted(list(set(file_names_state + [f.name for f in uploaded_files or []])))
151
+ file_display_md = "#### Uploaded Resources:\n" + "\n".join([f"- `{os.path.basename(name)}`" for name in all_file_names]) if all_file_names else ""
152
+ file_uploader_visible = not bool(all_file_names)
153
+ file_display_visible = bool(all_file_names)
154
 
155
+ print("YIELD 1: Displaying user message and initial status.")
156
+ yield (
157
+ gr.update(value=ui_history), # Use the cleanly built UI history
158
+ gr.update(value=""),
159
+ current_state,
160
+ gr.update(visible=file_uploader_visible),
161
+ gr.update(interactive=False),
162
+ gr.update(), gr.update(),
163
+ gr.update(value=file_display_md, visible=file_display_visible),
164
+ all_file_names,
165
+ gr.update(visible=False),
166
+ gr.update(), gr.update()
167
+ )
168
 
169
+ # --- 2. BACKEND PROCESSING (CONSUMER LOOP) ---
170
+ orchestrator_kwargs = {
171
+ "user_message_text": user_message,
172
+ "current_session_state": current_state,
173
+ "modified_explainer_prompt": modified_explainer_prompt or None,
174
+ "uploaded_resource_data": process_uploaded_files(uploaded_files) if uploaded_files else None
175
+ }
176
+ current_state[STATE_IS_FIRST_TURN] = False
177
+ if limiter: limiter.wait_if_needed()
178
+
179
+ final_state = None
180
  try:
181
+ # This loop consumes the `yield`ed updates from the backend orchestrator
182
+ for update_type, payload in process_chat_message(**orchestrator_kwargs):
183
+ if update_type == "status":
184
+ status_message = UI_FEEDBACK_MAP.get(payload, "Processing...")
185
+ # Update the last message in the chat (our status placeholder)
186
+ ui_history[-1]['content'] = f"*{status_message}*"
187
+ print(f"YIELD (Status Update): {status_message}")
188
+ # Yield a UI update with the new status message
189
+ yield (
190
+ gr.update(value=ui_history),
191
+ gr.update(), gr.update(), gr.update(), gr.update(),
192
+ gr.update(), gr.update(), gr.update(), gr.update(),
193
+ gr.update(), gr.update(), gr.update()
194
+ )
195
+ elif update_type == "final_result":
196
+ final_state = payload
197
+ break
198
+
199
  except Exception as e:
200
+ logger.error(f"Orchestrator stream error: {e}", exc_info=True)
201
+ current_state[STATE_HISTORY].append({'role': 'model', 'parts': [{'text': "An error occurred during processing."}]})
202
+ final_state = current_state
203
+
204
+ # --- 3. FINAL UI UPDATE (YIELD 2) ---
205
+ if not final_state:
206
+ logger.error("Processing finished without a final state.")
207
+ current_state[STATE_HISTORY].append({'role': 'model', 'parts': [{'text': "A critical error occurred."}]})
208
+ final_state = current_state
209
+
210
+ # --- Final Robust Translator ---
211
+ final_ui_history = []
212
+ for message in final_state.get(STATE_HISTORY, []):
213
+ if message.get('message_type') == "internal_resource_summary": continue
214
+ role = "assistant" if message.get("role") == "model" else "user"
215
+ content = message.get('content', '') or (message.get("parts")[0].get("text", "") if message.get("parts") else "")
216
+ final_ui_history.append({"role": role, "content": content})
217
+
218
+ # Logic for Suggested Replies and Tab Switching
219
+ looks_good_btn_update = gr.update(visible=False)
220
+ if final_ui_history and "what are your thoughts?" in final_ui_history[-1]['content'].lower():
221
+ looks_good_btn_update = gr.update(visible=True)
222
+
223
+ explainer_accordion_update, explainer_box_update, app_tabs_update, documentation_update = (gr.update(),)*4
224
+ if final_state.get(STATE_TRANSITION_EXPLAINER_FLAG):
225
+ explainer_accordion_update = gr.update(visible=True, open=True)
226
+ explainer_prompt_value = final_state.get(STATE_EXPLAINER_PROMPT, "")
227
+ explainer_box_update = gr.update(value=explainer_prompt_value)
228
+ app_tabs_update = gr.update(selected="doc_tab")
229
+ full_documentation_text = f"""
230
+ # Generated Tutor Persona
231
+ *This document contains the complete system prompt, including the finalized syllabus, that defines the AI tutor's behavior, personality, and knowledge base. You can copy this for reference or use in other applications.*
232
+ ***
233
+ {explainer_prompt_value}
234
+ """
235
+ documentation_update = gr.update(value=full_documentation_text)
236
+
237
+ print("YIELD 2: Displaying final AI response.")
238
+ yield (
239
+ gr.update(value=final_ui_history),
240
+ gr.update(value=""),
241
+ final_state,
242
+ gr.update(visible=file_uploader_visible),
243
+ gr.update(interactive=True),
244
+ explainer_accordion_update,
245
+ explainer_box_update,
246
+ gr.update(value=file_display_md, visible=file_display_visible),
247
+ all_file_names,
248
+ looks_good_btn_update,
249
+ app_tabs_update,
250
+ documentation_update,
251
  )
252
+ custom_css = """
253
+ /* --- Overall Page & Theme --- */
254
+ .gradio-container {
255
+ background: #F9FAFB; /* Soft off-white/light gray background */
256
+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif !important;
257
+ padding-top: 0 !important; /* Remove top padding to let header be flush */
258
+ }
259
 
260
+ /* --- Hero Header Section --- */
261
+ #app-header-container {
262
+ background: white;
263
+ border-bottom: 1px solid #E5E7EB;
264
+ padding: 1.5rem 2rem !important;
265
+ margin-bottom: 1.5rem !important;
266
+ }
267
+ #app-header h1 {
268
+ text-align: center;
269
+ font-size: 2.25rem !important;
270
+ font-weight: 800 !important;
271
+ color: #1F2937; /* Very dark gray for high contrast */
272
+ margin-bottom: 0.5rem !important;
273
+ }
274
+ #app-header p {
275
+ text-align: center;
276
+ font-size: 1.1rem !important;
277
+ color: #4B5563; /* Softer gray for subtitle */
278
+ margin-bottom: 0 !important;
279
+ }
280
 
281
+ /* --- Main Application Tabs --- */
282
+ #app-tabs .tab-nav button {
283
+ font-size: 1.1rem !important;
284
+ font-weight: 600 !important;
285
+ border-radius: 8px 8px 0 0 !important;
286
+ border-bottom: 3px solid transparent !important;
287
+ transition: all 0.2s ease-in-out;
288
+ background: transparent !important;
289
+ }
290
+ #app-tabs .tab-nav button.selected {
291
+ border-bottom-color: #4F46E5 !important; /* A strong indigo accent color */
292
+ background: white !important;
293
+ color: #4F46E5 !important;
294
+ }
295
+
296
+ /* --- Compact & Styled Buttons --- */
297
+ .sm-button {
298
+ min-width: 0 !important;
299
+ padding: 0.2rem 0.6rem !important;
300
+ height: 34px !important;
301
+ line-height: 1 !important;
302
+ align-self: center !important;
303
+ margin: 0 !important;
304
+ border-radius: 8px !important;
305
+ border: 1px solid #D1D5DB !important;
306
+ background: white !important;
307
+ color: #4B5563 !important;
308
+ box-shadow: 0 1px 2px 0 rgba(0,0,0,0.05);
309
+ transition: background-color 0.2s ease;
310
+ }
311
+ .sm-button:hover { background: #F9FAFB !important; }
312
+
313
+ /* --- Chat Interface Polish --- */
314
+ .chat-input-row { margin-top: 10px; }
315
+ #chatbot {
316
+ min-height: 600px;
317
+ box-shadow: none !important;
318
+ border: 1px solid #E5E7EB !important;
319
+ background-color: white !important;
320
+ }
321
+ """
322
+ # --- Gradio UI Definition ---
323
+ # --- Gradio UI Definition ---
324
+ # --- Gradio UI Definition ---
325
+ with gr.Blocks(theme=gr.themes.Soft(), css=custom_css, title="AI Syllabus Architect") as demo:
326
+
327
+ # --- State Management ---
328
+ session_state = gr.State(value=initialize_session_state)
329
+ rate_limiter_state = gr.State(value=None)
330
+ uploaded_file_names_state = gr.State([])
331
+ header_visibility_state = gr.State(value=True)
332
+
333
+ # --- TOP LEVEL HEADER (Collapsible) ---
334
+ with gr.Column(visible=True) as header_view:
335
+ gr.Markdown(
336
+ """
337
+ # AI Syllabus Architect
338
+ *Your personal guide to creating structured learning paths from any resource.*
339
+ """,
340
+ elem_id="app-header"
341
+ )
342
+ toggle_header_btn = gr.Button("⬆️", elem_classes="sm-button")
343
+
344
+ # --- UI for Visitor Mode (API Key Entry) ---
345
+ with gr.Column(visible=(APP_MODE == 'visitor'), elem_id="api_setup_view") as api_setup_view:
346
+ gr.Markdown("### 🔑 Please enter your Google AI API Key below to begin. You can get your free key from [Google AI Studio](https://aistudio.google.com/app/apikey).")
347
+
348
+ api_key_input = gr.Textbox(label="Google API Key", placeholder="Enter your API key here...", type="password")
349
+ api_tier_radio = gr.Radio(["Free Tier (7 calls/min)", "Paid Tier (1000 calls/min)"], label="Select API Tier", value="Free Tier (7 calls/min)")
350
+ api_key_submit_button = gr.Button("Start Session", variant="primary")
351
+ api_error_output = gr.Markdown(visible=False)
352
+
353
+ # ===================================================================
354
+ # CORRECTED MAIN UI: Top-level tabs and proper nesting
355
+ # ===================================================================
356
+ with gr.Tabs(elem_id="app-tabs", visible=(APP_MODE == 'admin')) as app_tabs:
357
+
358
+ # --- TAB 1: The Main Chat Interface ---
359
+ with gr.Tab("Chat Interface", id="chat_tab"):
360
+ with gr.Row(equal_height=False):
361
+ # --- MAIN CHAT COLUMN ---
362
+ with gr.Column(scale=7) as chat_column:
363
+ open_sidebar_btn = gr.Button("Show Resources & Persona ➡️", elem_classes="sm-button", visible=False)
364
+ initial_chat_ui = [{"role": "assistant", "content": "Hello! I'm ready to help build a personalized syllabus. What topic are you interested in learning about?"}]
365
+ chatbot = gr.Chatbot(initial_chat_ui, elem_id="chatbot", type="messages", show_label=False, render_markdown=True, avatar_images=(None, "https://i.imgur.com/3pyR0Vf.png"), latex_delimiters=[{"left": "$$", "right": "$$", "display": True}, {"left": "$", "right": "$", "display": False}])
366
+ with gr.Row(elem_classes="chat-input-row"):
367
+ looks_good_btn = gr.Button("looks good", size="sm", visible=False)
368
+ with gr.Row():
369
+ user_input_textbox = gr.Textbox(scale=4, show_label=False, placeholder="Type your message or upload files and press Enter...", container=False)
370
+ send_button = gr.Button("Send", variant="primary", scale=1, min_width=150)
371
+
372
+ # --- TOOLS SIDEBAR COLUMN (Correctly nested inside the Chat Tab's Row) ---
373
+ with gr.Column(scale=3, visible=True) as tools_sidebar:
374
+ close_sidebar_btn = gr.Button("⬅️ Close Sidebar", elem_classes="sm-button")
375
+ with gr.Accordion("🛠️ Session Content", open=True):
376
+ gr.Markdown("### 📄 Resources")
377
+ file_uploader = gr.File(label="Upload Learning Materials (First Turn Only)", file_count="multiple", file_types=[".pdf", ".docx", ".txt"], interactive=True)
378
+ file_display = gr.Markdown(visible=False)
379
+ with gr.Accordion("View/Edit AI Tutor Persona", open=False, visible=False) as explainer_prompt_accordion:
380
+ explainer_prompt_box = gr.Textbox(label="Tutor Persona System Prompt", lines=15, interactive=True, show_copy_button=True, info="You can view and modify the AI Tutor's persona here.")
381
+
382
+ # --- TAB 2: How to Use Guide ---
383
+ with gr.Tab("How to Use"):
384
+ gr.Markdown(
385
+ """
386
+ ### Quick Start Guide
387
+
388
+ **1. Start a Conversation:**
389
+ Begin by telling the AI what you want to learn. Be specific!
390
+ *Example: "I want to learn about building a RAG pipeline from scratch using Python."*
391
+
392
+ **2. Upload Resources (Optional):**
393
+ For a more tailored syllabus, upload relevant documents (`.pdf`, `.txt`, `.docx`) in your first message. The AI will use these as context.
394
+
395
+ **3. Negotiate the Syllabus:**
396
+ The AI will propose a syllabus. You can ask for changes, additions, or removals.
397
+ *Example: "Can you add a section on vector databases?"*
398
+
399
+ **4. Finalize and Learn:**
400
+ Once you're happy with the syllabus, tell the AI to finalize it (e.g., "This looks good, let's finalize it."). This will generate the tutor's persona and move to the learning phase.
401
+
402
+ **5. Interact with the Tutor:**
403
+ You can edit the tutor's persona at any time in the "Session Content" section to change its teaching style.
404
+
405
+ ---
406
+
407
+ ### Pro-User Guide: For a More Advanced Session
408
+
409
+ This is for users who want to architect a superior learning experience. Your prompts are the blueprints.
410
+
411
+ **1. On Architecting the Syllabus**
412
+
413
+ To get a truly calibrated result, you need to be precise.
414
+
415
+ * **Pinpoint Everything:** The key is to **pinpoint to every thing**. The more extra information you give, the better the AI can calibrate the syllabus to your exact needs.
416
+ * **Request Specific comparison :** Don't be afraid to demand more. For instance, you can **ask it for "the advanced version that contrasts one concept with another."**
417
+ * *Example:* `"For the data analysis module, I want the advanced version that contrasts the performance of Pandas with Polars for datasets over 10GB."*
418
+
419
+ **2. On Commanding the Tutor Persona**
420
+
421
+ This is the most important part. A well-defined persona yields a far more convincing and effective tutor.
422
+
423
+ * **The Core Principle:** When handling the Persona, **just don't ask the AI what persona you need.** A power user doesn't ask for a persona, they command one. You must *instruct* the AI on who it needs to be.
424
+
425
+ * **Advanced Techniques for Persona Prompts:**
426
+ * **First-Principles Thinking:** To force deep, foundational understanding.
427
+ * *Prompt Example:* `"Adopt the persona of a modern-day Feynman who thinks from first principles. When I ask about 'RAG pipelines,' start from the fundamental problem: 'How does a machine retrieve relevant information from a vast text library?' and build up from there."`
428
+ * **The Socratic Method:** To challenge your own thinking.
429
+ * *Prompt Example:* `"Become a Socratic tutor. Never give me a direct answer. Instead, relentlessly question my assumptions to lead me to the answer myself. If I say 'A vector database is faster,' your first response should be 'What do you mean by 'faster,' and compared to what?'"`
430
+ * **Key Figures from History:** To get a unique and powerful perspective.
431
+ * *Prompt Example:* `"Teach me chess as if you are Bobby Fischer preparing me for a world championship. Your tone should be intense, obsessive, and focused on total dominance. We will analyze unorthodox openings, drill methods to exploit opponent weaknesses, and master endgame precision. Every lesson is a step toward crushing the competition."`
432
+
433
+ Once your syllabus is perfected, finalize it. The AI will then adopt the persona you've engineered, and your advanced learning session will begin.
434
+ """
435
  )
436
 
437
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
438
 
 
 
 
439
 
440
+ # --- TAB 3: Generated Persona Documentation ---
441
+ with gr.Tab("Explainer Persona Prompt", id="doc_tab"):
442
+ # This is the new, more descriptive placeholder.
443
+ brief_documentation_display = gr.Markdown(
444
+ """
445
+ ## Tutor Persona Prompt
446
+
447
+ This Prompt will be generated after you finalize the syllabus in the chat.
448
 
449
+ It will contain the complete persona and system prompt that guides the AI tutor's teaching style, personality, and knowledge base.
 
 
 
 
450
 
451
+ ---
452
+ *Waiting for syllabus to be finalized...*
453
+ """
454
+ )
455
+
456
+ api_key_submit_button.click(fn=start_session, inputs=[api_key_input, api_tier_radio], outputs=[api_setup_view, app_tabs, rate_limiter_state, api_error_output])
457
 
458
+ def toggle_header(current_visibility_state):
459
+ new_visibility = not current_visibility_state
460
+ new_button_icon = "⬇️ Show Header" if not new_visibility else "⬆️ Hide Header"
461
+ return new_visibility, gr.update(visible=new_visibility), gr.update(value=new_button_icon)
462
+ toggle_header_btn.click(toggle_header, inputs=[header_visibility_state], outputs=[header_visibility_state, header_view, toggle_header_btn])
463
+
464
+ def close_sidebar():
465
+ return {tools_sidebar: gr.update(visible=False), open_sidebar_btn: gr.update(visible=True), chat_column: gr.update(scale=10)}
466
+ def open_sidebar():
467
+ return {tools_sidebar: gr.update(visible=True), open_sidebar_btn: gr.update(visible=False), chat_column: gr.update(scale=7)}
468
+ close_sidebar_btn.click(close_sidebar, outputs=[tools_sidebar, open_sidebar_btn, chat_column])
469
+ open_sidebar_btn.click(open_sidebar, outputs=[tools_sidebar, open_sidebar_btn, chat_column])
470
+
471
+ chat_inputs = [user_input_textbox, file_uploader, session_state, uploaded_file_names_state, rate_limiter_state, explainer_prompt_box]
472
+ chat_outputs = [chatbot, user_input_textbox, session_state, file_uploader, send_button, explainer_prompt_accordion, explainer_prompt_box, file_display, uploaded_file_names_state, looks_good_btn, app_tabs, brief_documentation_display]
473
+
474
+ user_input_textbox.submit(fn=handle_user_interaction, inputs=chat_inputs, outputs=chat_outputs)
475
+ send_button.click(fn=handle_user_interaction, inputs=chat_inputs, outputs=chat_outputs)
476
+
477
+ looks_good_btn.click(lambda: "looks good", inputs=[], outputs=[user_input_textbox]).then(
478
+ fn=handle_user_interaction,
479
+ inputs=chat_inputs,
480
+ outputs=chat_outputs
481
+ )
482
  if __name__ == "__main__":
483
+ # This section remains unchanged
484
+ if APP_MODE == 'admin':
485
+ logger.info("Starting in ADMIN mode.")
486
+ if initialize_dspy() and initialize_orchestrator_modules():
487
+ logger.info("Admin mode ready.")
488
+ else:
489
+ logger.critical("FATAL: Could not initialize DSPy or orchestrator modules in Admin mode.")
490
  else:
491
+ logger.info("Starting in VISITOR mode. Waiting for user to provide API key.")
492
+ demo.queue().launch(debug=True)
493
+