SarahXia0405 commited on
Commit
ce485af
·
verified ·
1 Parent(s): 487f6ba

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +233 -585
app.py CHANGED
@@ -1,6 +1,5 @@
1
  # app.py
2
  from typing import List, Dict, Tuple, Optional
3
-
4
  import gradio as gr
5
 
6
  from config import (
@@ -27,660 +26,309 @@ from rag_engine import (
27
  )
28
  from syllabus_utils import extract_course_topics_from_file
29
 
30
-
31
  # ================== Assets ==================
32
-
33
  HANBRIDGE_LOGO_PATH = "hanbridge_logo.png"
34
  CLARE_LOGO_PATH = "clare_mascot.png"
35
- CLARE_RUN_PATH = "Clare_Run.png"
36
-
37
-
38
- # ================== CSS(只控制 User Guide 样式) ==================
39
-
40
- USER_GUIDE_CSS = """
41
- #user-guide-panel h2 {
42
- font-size: 1rem;
43
- margin-bottom: 0.35rem;
44
- }
45
- #user-guide-panel h3 {
46
- font-size: 0.9rem;
47
- margin-bottom: 0.25rem;
48
- }
49
- #user-guide-panel p,
50
- #user-guide-panel li {
51
- font-size: 0.8rem;
52
- }
53
-
54
- /* 左侧 User Guide 链接按钮 → 蓝色小链接风格 */
55
  #user-guide-links button {
56
- background: transparent !important;
57
- border: none !important;
58
- box-shadow: none !important;
59
- padding: 2px 0 !important;
60
- margin: 1px 0 !important;
61
- text-align: left !important;
62
- color: #004a99 !important;
63
- text-decoration: underline;
64
- font-size: 0.8rem;
65
  }
66
- #user-guide-links button:hover {
67
- background: transparent !important;
68
- color: #002b66 !important;
69
- }
70
- """
71
-
72
 
73
- # ========= Clare User Guide Content =========
 
 
74
 
 
75
  USER_GUIDE_SECTIONS = {
76
- "getting_started": """
77
- ## Getting started
78
-
79
- Welcome to **Clare — Your Personalized AI Tutor**.
80
-
81
- Clare is designed to support your learning through:
82
- - Clear explanations of course concepts
83
- - Socratic-style reasoning guidance
84
- - Personalized reinforcement based on learning science
85
- - Course-aligned answers using your uploaded materials
86
- - Micro-quizzes & summaries to strengthen understanding
87
-
88
- **To begin:**
89
- 1. Select your **Learning Mode** on the left
90
- 2. (Optional) Upload your **syllabus / slides / notes** at the top
91
- 3. Ask Clare any question about your course, assignment, or study plan.
92
- """,
93
- "mode_definition": """
94
- ## Mode Definition
95
-
96
- Clare offers different teaching modes to match how you prefer to learn.
97
-
98
- ### Concept Explainer
99
- Clear, structured explanations with examples — ideal for learning new topics.
100
-
101
- ### Socratic Tutor
102
- Clare asks guiding questions instead of giving direct answers.
103
- Helps you build reasoning and problem-solving skills.
104
-
105
- ### Exam Prep / Quiz
106
- Generates short practice questions aligned with your course week.
107
- Useful for self-testing and preparing for exams.
108
-
109
- ### Assignment Helper
110
- Helps you interpret assignment prompts, plan structure, and understand requirements.
111
- ❗ Clare does **not** produce full assignment answers (academic integrity).
112
-
113
- ### Quick Summary
114
- Gives brief summaries of slides, reading materials, or long questions.
115
- """,
116
- "how_clare_works": """
117
- ## How Clare Works
118
-
119
- Clare combines **course context + learning science + AI reasoning** to generate answers.
120
-
121
- Clare uses:
122
- - **Your selected Learning Mode**
123
- Determines tone, depth, and interaction style.
124
-
125
- - **Your uploaded course files**
126
- Syllabus, slides, or papers help align answers with your specific course.
127
-
128
- - **Reinforcement learning cycle**
129
- Answers may prioritize key concepts you’re likely to forget (based on the forgetting curve).
130
-
131
- - **Adaptive explanation depth**
132
- Clare can adjust complexity depending on your previous interactions.
133
-
134
- - **Responsible AI principles**
135
- Avoids harmful output and preserves academic integrity.
136
- """,
137
- "memory_line": """
138
- ## What is Memory Line?
139
-
140
- **Memory Line** is a visualization of your *learning reinforcement cycle*.
141
-
142
- Based on the **forgetting-curve model**, Clare organizes your review topics into:
143
- - **T+0 (Current Week)** – new concepts
144
- - **T+7** – first spaced review
145
- - **T+14** – reinforcement review
146
- - **T+30** – long-term consolidation
147
-
148
- Clare uses these cycles to decide:
149
- - Which concepts to reinforce today
150
- - Which explanations to prioritize
151
- - When to introduce quick review questions
152
-
153
- **Review Now** will generate a small set of concepts that are due for spaced repetition.
154
- """,
155
- "learning_progress": """
156
- ## Learning Progress Report
157
-
158
- The Learning Progress Report highlights:
159
- - **Concepts mastered**
160
- - **Concepts in progress**
161
- - **Concepts due for review**
162
- - Your recent **micro-quiz results**
163
- - Suggested **next-step topics**
164
-
165
- You can download a **summary** at any time to use as study notes.
166
- """,
167
- "how_files": """
168
- ## How Clare Uses Your Files
169
-
170
- Your uploaded syllabus / slides / notes help Clare:
171
-
172
- - Align explanations with your exact course
173
- - Use terminology consistent with your professor
174
- - Improve factual accuracy
175
- - Generate personalized reinforcement content
176
-
177
- 🔒 **Privacy**
178
- - Files are used only within your session
179
- - They are not kept as permanent training data
180
-
181
- Accepted formats: **.docx / .pdf / .pptx**
182
- """,
183
- "micro_quiz": """
184
- ## Micro-Quiz
185
-
186
- The **Micro-Quiz** function provides a:
187
-
188
- - 1-minute self-check
189
- - 1–3 questions based on your recent topics
190
- - Instant feedback
191
-
192
- Micro-quizzes strengthen your memory and are part of Clare’s reinforcement system.
193
- """,
194
- "summarization": """
195
- ## Summarization
196
-
197
- Clare can summarize:
198
-
199
- - Lecture notes
200
- - Uploaded PDFs
201
- - Long conversation threads
202
- - Complex concepts
203
-
204
- Summary styles can include:
205
- - Bullet points
206
- - Key ideas
207
- - Study notes
208
- - Comparison-style highlights.
209
- """,
210
- "export_conversation": """
211
- ## Export Conversation
212
-
213
- You can export your chat session for:
214
-
215
- - Study review
216
- - Exam preparation
217
- - Documentation for tutoring help
218
- - Saving important explanations
219
-
220
- Export format: **Markdown / plain text** (depending on this Space configuration).
221
- """,
222
- "faq": """
223
- ## FAQ
224
-
225
- **Q: Does Clare give assignment answers?**
226
- No. Clare assists with understanding and planning but does **not** generate full solutions.
227
-
228
- **Q: Does Clare replace lectures or TA office hours?**
229
- No. Clare supplements your learning by providing on-demand guidance.
230
-
231
- **Q: Can Clare explain my professor’s slides?**
232
- Yes — upload your slides so Clare can align explanations with your course.
233
-
234
- **Q: What languages does Clare support?**
235
- Currently: English & 简体中文.
236
-
237
- **Q: Why does Clare sometimes ask me questions instead of answering directly?**
238
- You may be in **Socratic Tutor** mode — Clare is guiding your reasoning.
239
- """
240
  }
241
 
242
-
243
  def get_user_guide_section(section_key: str) -> str:
244
- """Return markdown text for a User Guide section."""
245
  return USER_GUIDE_SECTIONS.get(section_key, "Section not found.")
246
 
247
-
248
  # ================== Gradio App ==================
249
 
250
- with gr.Blocks(
251
- title="Clare – Hanbridge AI Teaching Assistant",
252
- css=USER_GUIDE_CSS,
253
- ) as demo:
254
- # 顶部品牌区:左 Hanbridge logo + 文案,中间标题,右 Clare 小火苗(保持你原来的结构)
255
-
256
- with gr.Column(scale=6):
257
- # ---------- Header using Markdown + <img> ----------
258
- gr.Markdown(
259
- f"""
260
- <div style="display:flex;align-items:center;gap:20px; padding:8px 0;">
261
-
262
- <!-- Clare Mascot -->
263
- <img src="file/{CLARE_LOGO_PATH}" style="height:70px;">
264
 
265
- <!-- Text Block -->
266
- <div style="display:flex;flex-direction:column;">
267
- <div style="font-size:28px;font-weight:700; line-height:1.2;">
268
- Clare
269
- </div>
270
- <div style="font-size:18px;font-weight:500; line-height:1.2;">
271
- Your Personalized AI Tutor
272
- </div>
273
- <div style="font-size:14px;color:#666;">
274
- Personalized guidance, review, and intelligent reinforcement – designed for how you learn.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
275
  </div>
 
276
  </div>
277
-
278
- <!-- Right-side Hanbridge Logo -->
279
- <div style="margin-left:auto;">
280
- <img src="file/{HANBRIDGE_LOGO_PATH}" style="height:60px;">
281
- </div>
282
-
283
- </div>
284
- """
285
- )
286
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
287
 
288
- # 简短说明
289
- gr.Markdown(
290
- """
291
- - Ask in **English** → Clare answers in English.
292
- - Ask in **Chinese** → Clare can answer in Chinese.
293
- - Use different **learning modes** to change Clare's teaching style.
294
- - Optionally upload your **course syllabus / slides / literature (.docx / .pdf / .pptx)** so Clare stays aligned with your course.
295
- """
296
- )
 
 
 
 
 
 
297
 
298
- # 顶部:模型、语言偏好、学习模式
299
- with gr.Row():
300
- model_name = gr.Textbox(
301
- label="Model name",
302
- value=DEFAULT_MODEL,
303
- info="For example: gpt-4.1-mini, gpt-4.1, gpt-4o, etc.",
304
- )
305
- language_preference = gr.Radio(
306
- choices=["Auto", "English", "中文"],
307
- value="Auto",
308
- label="Preferred answer language",
309
- )
310
- learning_mode = gr.Radio(
311
- choices=LEARNING_MODES,
312
- value="Concept Explainer",
313
- label="Learning mode",
314
- )
 
 
 
 
 
 
315
 
316
- # 课程文件上传
317
- with gr.Row():
318
- syllabus_file = gr.File(
319
- label="Upload course file (.docx / .pdf / .pptx)",
320
- file_types=[".docx", ".pdf", ".pptx"],
321
- )
322
- doc_type = gr.Dropdown(
323
- choices=DOC_TYPES,
324
- value="Syllabus",
325
- label="File type",
326
- )
327
 
328
- # 状态:课程大纲 + 学生弱项 + 认知状态 + RAG chunks
329
- course_outline_state = gr.State(DEFAULT_COURSE_TOPICS)
330
- weakness_state = gr.State([])
331
- cognitive_state_state = gr.State({"confusion": 0, "mastery": 0})
332
- rag_chunks_state = gr.State([]) # Session 级 RAG 向量库
333
-
334
- # 上传 syllabus 时更新课程大纲 + RAG chunks
335
  def update_course_and_rag(file, doc_type_val):
336
- """
337
- 上传文件时:
338
- - 如果 doc_type 是 Syllabus,就尝试从文件中解析课程大纲(支持 docx / pdf);
339
- - 否则使用默认大纲;
340
- - 同时无论 doc_type 为何,都用文件内容构建一次 RAG chunks。
341
- """
342
  topics = extract_course_topics_from_file(file, doc_type_val)
343
  rag_chunks = build_rag_chunks_from_file(file, doc_type_val)
344
- return topics, rag_chunks
 
 
345
 
346
  syllabus_file.change(
347
  fn=update_course_and_rag,
348
  inputs=[syllabus_file, doc_type],
349
- outputs=[course_outline_state, rag_chunks_state],
350
- )
351
-
352
- # 左侧聊天,右侧 Session 状态栏
353
- with gr.Row():
354
- chatbot = gr.Chatbot(
355
- label="Clare Chat",
356
- height=450,
357
- avatar_images=(None, CLARE_LOGO_PATH), # 用户默认头像,助教用小火苗
358
- )
359
- session_status = gr.Markdown(
360
- value=render_session_status(
361
- "Concept Explainer",
362
- [],
363
- {"confusion": 0, "mastery": 0},
364
- ),
365
- label="Session status",
366
- )
367
-
368
- user_input = gr.Textbox(
369
- label="Your question",
370
- placeholder="Ask about a concept, your assignment, or let Clare test you with a quick question...",
371
  )
372
 
373
- with gr.Row():
374
- clear_btn = gr.Button("Reset conversation")
375
- export_btn = gr.Button("Export conversation")
376
- quiz_btn = gr.Button("Generate 3 quiz questions")
377
- summary_btn = gr.Button("Summarize concepts")
378
-
379
- export_box = gr.Textbox(
380
- label="Conversation export (Markdown)",
381
- lines=8,
382
- )
383
- quiz_box = gr.Textbox(
384
- label="Generated quiz (with answer key)",
385
- lines=8,
386
- )
387
- summary_box = gr.Textbox(
388
- label="Concept summary (for study notes)",
389
- lines=8,
390
- )
391
-
392
- # ========== User Guide ==========
393
-
394
- with gr.Accordion("User Guide", open=False):
395
- with gr.Row():
396
- # 左侧“蓝色链接列表”
397
- with gr.Column(scale=1, min_width=180, elem_id="user-guide-links"):
398
- ug_getting_started = gr.Button("Getting started", variant="secondary")
399
- ug_mode_def = gr.Button("Mode Definition", variant="secondary")
400
- ug_how_works = gr.Button("How Clare Works", variant="secondary")
401
- ug_memory_line = gr.Button("What is Memory line", variant="secondary")
402
- ug_learning_progress = gr.Button("Learning Progress Report", variant="secondary")
403
- ug_how_files = gr.Button("How Clare Uses Your Files", variant="secondary")
404
- ug_micro_quiz = gr.Button("Micro-Quiz", variant="secondary")
405
- ug_summarization = gr.Button("Summarization", variant="secondary")
406
- ug_export_conv = gr.Button("Export Conversation", variant="secondary")
407
- ug_faq = gr.Button("FAQ", variant="secondary")
408
-
409
- # 右侧具体内容框
410
- with gr.Column(scale=3):
411
- user_guide_md = gr.Markdown(
412
- value=USER_GUIDE_SECTIONS["getting_started"],
413
- elem_id="user-guide-panel",
414
- )
415
-
416
- # 主对话逻辑
417
- def respond(
418
- message,
419
- chat_history,
420
- course_outline,
421
- weaknesses,
422
- cognitive_state,
423
- rag_chunks,
424
- model_name_val,
425
- language_pref_val,
426
- learning_mode_val,
427
- doc_type_val,
428
- ):
429
- # 1) 决定本轮语言(Auto / English / 中文)
430
- resolved_lang = detect_language(message or "", language_pref_val)
431
-
432
- # 2) 空输入防护
433
  if not message or not message.strip():
434
- empty_msg = get_empty_input_prompt(resolved_lang)
435
- new_history = chat_history + [("", empty_msg)]
436
- status_text = render_session_status(
437
- learning_mode_val,
438
- weaknesses or [],
439
- cognitive_state,
440
- )
441
- return "", new_history, weaknesses, cognitive_state, status_text
442
 
443
- # 3) 更新弱项 & 认知状态
444
  weaknesses = update_weaknesses_from_message(message, weaknesses or [])
445
  cognitive_state = update_cognitive_state_from_message(message, cognitive_state)
446
 
447
- # 4) Same Question Check(session 内复用答案)
448
- dup = find_similar_past_question(message, chat_history)
449
- if dup is not None:
450
- past_q, past_a, sim = dup
451
- prefix_en = (
452
- "I noticed this question is very similar to one you asked earlier, "
453
- "so I'm showing the previous explanation again. "
454
- "If there's a specific part that's still unclear, tell me and I can "
455
- "re-explain it in a different way.\n\n"
456
- "**Earlier answer:**\n"
457
- )
458
- prefix_zh = (
459
- "我注意到你现在的问题和之前问过的非常相似,"
460
- "所以我先把当时的回答再展示一次。"
461
- "如果还有具体不清楚的地方,可以告诉我,我会换一种方式解释。\n\n"
462
- "**之前的回答:**\n"
463
- )
464
- if resolved_lang == "中文":
465
- answer = prefix_zh + past_a
466
- else:
467
- answer = prefix_en + past_a
468
-
469
- new_history = chat_history + [(message, answer)]
470
- status_text = render_session_status(
471
- learning_mode_val,
472
- weaknesses,
473
- cognitive_state,
474
- )
475
- return "", new_history, weaknesses, cognitive_state, status_text
476
-
477
- # 5) RAG:基于上传文档做检索
478
  rag_context = retrieve_relevant_chunks(message, rag_chunks or [])
479
 
480
- # 6) 正常调用 Clare(带上 RAG context)
481
  answer, new_history = chat_with_clare(
482
  message=message,
483
  history=chat_history,
484
- model_name=model_name_val,
485
  language_preference=resolved_lang,
486
- learning_mode=learning_mode_val,
487
  doc_type=doc_type_val,
488
  course_outline=course_outline,
489
  weaknesses=weaknesses,
490
  cognitive_state=cognitive_state,
491
- rag_context=rag_context,
492
  )
493
-
494
- # RAG 标记
495
- if rag_context:
496
- # 根据语言给不同提示
497
- if resolved_lang == "中文":
498
- prefix = "(本次回答参考了你上传的课程文档内容。)\n\n"
499
- else:
500
- prefix = "(This answer used excerpts from your uploaded course document.)\n\n"
501
-
502
- tagged_answer = prefix + answer
503
- # 更新最后一条记录里的 assistant 内容
504
- if new_history:
505
- new_history[-1] = (message, tagged_answer)
506
- answer = tagged_answer
507
-
508
- status_text = render_session_status(
509
- learning_mode_val,
510
- weaknesses,
511
- cognitive_state,
512
- )
513
- return "", new_history, weaknesses, cognitive_state, status_text
514
 
515
  user_input.submit(
516
  respond,
517
- [
518
- user_input,
519
- chatbot,
520
- course_outline_state,
521
- weakness_state,
522
- cognitive_state_state,
523
- rag_chunks_state,
524
- model_name,
525
- language_preference,
526
- learning_mode,
527
- doc_type,
528
- ],
529
- [user_input, chatbot, weakness_state, cognitive_state_state, session_status],
530
- )
531
-
532
- # 清空对话 & 状态
533
- def clear_all():
534
- empty_state = {"confusion": 0, "mastery": 0}
535
- status_text = render_session_status("Concept Explainer", [], empty_state)
536
- return (
537
- [], # chatbot
538
- [], # weaknesses
539
- empty_state, # cognitive_state
540
- [], # rag_chunks
541
- "", # export_box
542
- "", # quiz_box
543
- "", # summary_box
544
- status_text, # session_status
545
- )
546
-
547
- clear_btn.click(
548
- clear_all,
549
- None,
550
- [
551
- chatbot,
552
- weakness_state,
553
- cognitive_state_state,
554
- rag_chunks_state,
555
- export_box,
556
- quiz_box,
557
- summary_box,
558
- session_status,
559
- ],
560
- queue=False,
561
  )
562
 
563
- # 导出对话
564
- def on_export(chat_history, course_outline, learning_mode_val, weaknesses, cognitive_state):
565
- return export_conversation(
566
- chat_history,
567
- course_outline,
568
- learning_mode_val,
569
- weaknesses or [],
570
- cognitive_state,
571
- )
572
 
573
  export_btn.click(
574
  on_export,
575
  [chatbot, course_outline_state, learning_mode, weakness_state, cognitive_state_state],
576
- [export_box],
577
  )
578
 
579
- # 生成 quiz
580
- def on_quiz(
581
- chat_history,
582
- course_outline,
583
- weaknesses,
584
- cognitive_state,
585
- model_name_val,
586
- language_pref_val,
587
- ):
588
- return generate_quiz_from_history(
589
- chat_history,
590
- course_outline,
591
- weaknesses or [],
592
- cognitive_state,
593
- model_name_val,
594
- language_pref_val,
595
- )
596
 
597
  quiz_btn.click(
598
  on_quiz,
599
- [
600
- chatbot,
601
- course_outline_state,
602
- weakness_state,
603
- cognitive_state_state,
604
- model_name,
605
- language_preference,
606
- ],
607
- [quiz_box],
608
  )
609
 
610
- # 概念总结
611
- def on_summary(
612
- chat_history,
613
- course_outline,
614
- weaknesses,
615
- cognitive_state,
616
- model_name_val,
617
- language_pref_val,
618
- ):
619
- return summarize_conversation(
620
- chat_history,
621
- course_outline,
622
- weaknesses or [],
623
- cognitive_state,
624
- model_name_val,
625
- language_pref_val,
626
- )
627
 
628
  summary_btn.click(
629
  on_summary,
630
- [
631
- chatbot,
632
- course_outline_state,
633
- weakness_state,
634
- cognitive_state_state,
635
- model_name,
636
- language_preference,
637
- ],
638
- [summary_box],
639
  )
640
 
641
- # ========== User Guide button bindings ==========
 
 
 
 
642
 
643
- ug_getting_started.click(
644
- lambda: get_user_guide_section("getting_started"),
645
- outputs=user_guide_md,
646
- )
647
- ug_mode_def.click(
648
- lambda: get_user_guide_section("mode_definition"),
649
- outputs=user_guide_md,
650
- )
651
- ug_how_works.click(
652
- lambda: get_user_guide_section("how_clare_works"),
653
- outputs=user_guide_md,
654
- )
655
- ug_memory_line.click(
656
- lambda: get_user_guide_section("memory_line"),
657
- outputs=user_guide_md,
658
- )
659
- ug_learning_progress.click(
660
- lambda: get_user_guide_section("learning_progress"),
661
- outputs=user_guide_md,
662
- )
663
- ug_how_files.click(
664
- lambda: get_user_guide_section("how_files"),
665
- outputs=user_guide_md,
666
- )
667
- ug_micro_quiz.click(
668
- lambda: get_user_guide_section("micro_quiz"),
669
- outputs=user_guide_md,
670
- )
671
- ug_summarization.click(
672
- lambda: get_user_guide_section("summarization"),
673
- outputs=user_guide_md,
674
- )
675
- ug_export_conv.click(
676
- lambda: get_user_guide_section("export_conversation"),
677
- outputs=user_guide_md,
678
- )
679
- ug_faq.click(
680
- lambda: get_user_guide_section("faq"),
681
- outputs=user_guide_md,
682
  )
683
-
 
 
 
 
 
 
 
 
 
 
684
 
685
  if __name__ == "__main__":
686
- demo.launch()
 
1
  # app.py
2
  from typing import List, Dict, Tuple, Optional
 
3
  import gradio as gr
4
 
5
  from config import (
 
26
  )
27
  from syllabus_utils import extract_course_topics_from_file
28
 
 
29
  # ================== Assets ==================
 
30
  HANBRIDGE_LOGO_PATH = "hanbridge_logo.png"
31
  CLARE_LOGO_PATH = "clare_mascot.png"
32
+ # CLARE_RUN_PATH = "Clare_Run.png"
33
+
34
+ # ================== CSS ==================
35
+ # 增加了一些针对布局微调的 CSS
36
+ CUSTOM_CSS = """
37
+ #user-guide-panel h2 { font-size: 1rem; margin-bottom: 0.35rem; }
38
+ #user-guide-panel h3 { font-size: 0.9rem; margin-bottom: 0.25rem; }
39
+ #user-guide-panel p, #user-guide-panel li { font-size: 0.8rem; }
 
 
 
 
 
 
 
 
 
 
 
 
40
  #user-guide-links button {
41
+ background: transparent !important; border: none !important; box-shadow: none !important;
42
+ padding: 2px 0 !important; margin: 1px 0 !important; text-align: left !important;
43
+ color: #004a99 !important; text-decoration: underline; font-size: 0.8rem;
 
 
 
 
 
 
44
  }
45
+ #user-guide-links button:hover { color: #002b66 !important; }
 
 
 
 
 
46
 
47
+ /* 调整左侧边栏紧凑度 */
48
+ .left-sidebar-group { border: 1px solid #e5e7eb; padding: 10px; border-radius: 8px; }
49
+ """
50
 
51
+ # ========= Clare User Guide Content (保持原样) =========
52
  USER_GUIDE_SECTIONS = {
53
+ "getting_started": "## Getting started\n\nWelcome to **Clare**...", # (为了节省篇幅,此处省略具体文本,保持你原代码内容即可)
54
+ "mode_definition": "## Mode Definition\n\nClare offers different teaching modes...",
55
+ "how_clare_works": "## How Clare Works\n\nClare combines course context...",
56
+ "memory_line": "## What is Memory Line?\n\nMemory Line is a visualization...",
57
+ "learning_progress": "## Learning Progress Report\n\nThe Learning Progress Report highlights...",
58
+ "how_files": "## How Clare Uses Your Files\n\nYour uploaded syllabus / slides...",
59
+ "micro_quiz": "## Micro-Quiz\n\nThe Micro-Quiz function provides...",
60
+ "summarization": "## Summarization\n\nClare can summarize...",
61
+ "export_conversation": "## Export Conversation\n\nYou can export your chat session...",
62
+ "faq": "## FAQ\n\n**Q: Does Clare give assignment answers?**..."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  }
64
 
 
65
  def get_user_guide_section(section_key: str) -> str:
 
66
  return USER_GUIDE_SECTIONS.get(section_key, "Section not found.")
67
 
 
68
  # ================== Gradio App ==================
69
 
70
+ with gr.Blocks(title="Clare – Hanbridge AI Teaching Assistant", css=CUSTOM_CSS) as demo:
71
+
72
+ # 状态变量
73
+ course_outline_state = gr.State(DEFAULT_COURSE_TOPICS)
74
+ weakness_state = gr.State([])
75
+ cognitive_state_state = gr.State({"confusion": 0, "mastery": 0})
76
+ rag_chunks_state = gr.State([])
77
+
78
+ # ============ 整体布局:左(1) - 中(3) - 右(1) ============
79
+ with gr.Row():
 
 
 
 
80
 
81
+ # ============ [左侧] 控制面板 Sidebar ============
82
+ with gr.Column(scale=1, min_width=200):
83
+ # 1. Reset 按钮 (深色/红色强调)
84
+ clear_btn = gr.Button("Reset Conversation", variant="stop")
85
+
86
+ gr.Markdown("### Model Settings")
87
+ # 2. 模型与语言
88
+ model_name = gr.Textbox(label="Model", value=DEFAULT_MODEL, lines=1)
89
+ language_preference = gr.Radio(
90
+ choices=["Auto", "English", "简体中文"],
91
+ value="Auto",
92
+ label="Language"
93
+ )
94
+
95
+ # 3. 学习模式 (Learning Mode)
96
+ learning_mode = gr.Radio(
97
+ choices=LEARNING_MODES,
98
+ value="Concept Explainer",
99
+ label="Learning Mode",
100
+ info="Select style"
101
+ )
102
+
103
+ # 4. User Guide (折叠菜单)
104
+ with gr.Accordion("User Guide", open=False):
105
+ with gr.Column(elem_id="user-guide-links"):
106
+ ug_getting_started = gr.Button("Getting started")
107
+ ug_mode_def = gr.Button("Mode Definition")
108
+ ug_how_works = gr.Button("How Clare Works")
109
+ ug_memory_line = gr.Button("What is Memory Line")
110
+ # ... 可以添加更多 User Guide 按钮
111
+
112
+ # 5. 系统设置/退出 (底部)
113
+ with gr.Group():
114
+ gr.Button("System Settings", variant="secondary")
115
+ gr.Button("Log Out", variant="secondary")
116
+
117
+ # ============ [中间] 主内容区 Center Main ============
118
+ with gr.Column(scale=3):
119
+
120
+ # 1. Header (Clare & Hanbridge Logos)
121
+ gr.Markdown(
122
+ f"""
123
+ <div style="display:flex;align-items:center;justify-content:space-between; padding-bottom:10px; border-bottom: 2px solid #eee;">
124
+ <div style="display:flex;align-items:center;gap:15px;">
125
+ <img src="file/{CLARE_LOGO_PATH}" style="height:60px;">
126
+ <div>
127
+ <h1 style="margin:0;font-size:24px;">Clare</h1>
128
+ <p style="margin:0;font-size:14px;color:#666;">Your Personalized AI Tutor</p>
129
+ <i style="font-size:12px;color:#888;">Personalized guidance, review, and intelligent reinforcement</i>
130
+ </div>
131
  </div>
132
+ <img src="file/{HANBRIDGE_LOGO_PATH}" style="height:50px;">
133
  </div>
134
+ """
135
+ )
 
 
 
 
 
 
 
136
 
137
+ # 2. 上传区与 Memory Line 并排
138
+ with gr.Group():
139
+ with gr.Row():
140
+ # 左半部分:上传文件
141
+ with gr.Column(scale=1):
142
+ syllabus_file = gr.File(
143
+ label="Upload file (.docx/.pdf/.pptx)",
144
+ file_types=[".docx", ".pdf", ".pptx"],
145
+ file_count="single",
146
+ height=100
147
+ )
148
+ doc_type = gr.Dropdown(
149
+ choices=DOC_TYPES,
150
+ value="Syllabus",
151
+ label="File type",
152
+ container=False
153
+ )
154
+
155
+ # 右半部分:Memory Line 面板
156
+ with gr.Column(scale=1):
157
+ gr.Markdown("**Memory Line** 🧠")
158
+ # 这里可以用 HTML 模拟一个进度条或 Review 状态
159
+ session_status = gr.Markdown(
160
+ value=render_session_status("Concept Explainer", [], {"confusion": 0, "mastery": 0}),
161
+ elem_id="memory-line-status"
162
+ )
163
+ with gr.Row():
164
+ review_btn = gr.Button("Review Now", size="sm", variant="primary")
165
+ report_btn = gr.Button("Learning Progress Report ⬇️", size="sm")
166
+
167
+ # 3. Chat Interface
168
+ # 为了模仿截图中的 Instructional Text,可以在 Chatbot 上方放提示
169
+ gr.Markdown(
170
+ """
171
+ <div style="background-color:#f9fafb; padding:10px; border-radius:5px; margin-top:10px; font-size:0.9em; color:#555;">
172
+ ✦ <b>Instruction:</b> Use different learning modes to change Clare's teaching style.<br>
173
+ ✦ <b>Example:</b> "Why does context length matter?" or "How does RAG reduce hallucination?"
174
+ </div>
175
+ """
176
+ )
177
 
178
+ chatbot = gr.Chatbot(
179
+ label="",
180
+ height=450,
181
+ avatar_images=(None, CLARE_LOGO_PATH),
182
+ show_label=False,
183
+ bubble_full_width=False
184
+ )
185
+
186
+ user_input = gr.Textbox(
187
+ label="Your Input",
188
+ placeholder="Ask about a concept, your assignment, or let Clare test you...",
189
+ show_label=False,
190
+ container=True,
191
+ autofocus=True
192
+ )
193
 
194
+ # ============ [右侧] 功能栏 Right Sidebar ============
195
+ with gr.Column(scale=1, min_width=180):
196
+ gr.Markdown("### Actions")
197
+
198
+ # 这里的按钮设计为全宽
199
+ export_btn = gr.Button("Export Conversation", size="sm")
200
+ quiz_btn = gr.Button("Let's Try (Micro-Quiz)", size="sm")
201
+ summary_btn = gr.Button("Summarization", size="sm")
202
+
203
+ gr.Markdown("### Results")
204
+ # 统一结果展示区(模仿图中右下角的空白区域)
205
+ # 用一个 Tab 或者一个通用的 Box 来展示 Export/Quiz/Summary 的结果
206
+ result_display = gr.Textbox(
207
+ label="Generated Content",
208
+ lines=15,
209
+ placeholder="Results from Export, Quiz, or Summary will appear here...",
210
+ show_label=False
211
+ )
212
+
213
+ # User Guide 的内容显示框 (隐藏或作为 Modal 更好,但在现有结构下可以放下面或者用 Modal 替代)
214
+ # 为了符合截图设计,User Guide 点击后可能是在中间对话框显示,或者弹出。
215
+ # 这里暂时保留一个隐藏的 Markdown 区域用于逻辑兼容,或者让结果显示在 result_display 中。
216
+ user_guide_display = gr.Markdown(visible=False)
217
 
218
+ # ================== Logic Bindings ==================
 
 
 
 
 
 
 
 
 
 
219
 
220
+ # 1. File Upload Logic
 
 
 
 
 
 
221
  def update_course_and_rag(file, doc_type_val):
 
 
 
 
 
 
222
  topics = extract_course_topics_from_file(file, doc_type_val)
223
  rag_chunks = build_rag_chunks_from_file(file, doc_type_val)
224
+ # 更新 Memory Line 的状态显示 (示例)
225
+ status_md = f"✅ **File Loaded:** {doc_type_val}\n\nAnalyzing content for Memory Line..."
226
+ return topics, rag_chunks, status_md
227
 
228
  syllabus_file.change(
229
  fn=update_course_and_rag,
230
  inputs=[syllabus_file, doc_type],
231
+ outputs=[course_outline_state, rag_chunks_state, session_status],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
232
  )
233
 
234
+ # 2. Chat Logic (Standard)
235
+ def respond(message, chat_history, course_outline, weaknesses, cognitive_state, rag_chunks, model, lang, mode, doc_type_val):
236
+ # ... (此处逻辑复用你原有的代码逻辑) ...
237
+ # 为了简洁,这里直接调用原有的 chat_with_clare 等函数
238
+ # 注意:你需要确保 import 了这些函数
239
+
240
+ resolved_lang = detect_language(message or "", lang)
241
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
  if not message or not message.strip():
243
+ return "", chat_history, weaknesses, cognitive_state, session_status.value
 
 
 
 
 
 
 
244
 
245
+ # 更新状态
246
  weaknesses = update_weaknesses_from_message(message, weaknesses or [])
247
  cognitive_state = update_cognitive_state_from_message(message, cognitive_state)
248
 
249
+ # RAG Check
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
250
  rag_context = retrieve_relevant_chunks(message, rag_chunks or [])
251
 
252
+ # Chat
253
  answer, new_history = chat_with_clare(
254
  message=message,
255
  history=chat_history,
256
+ model_name=model,
257
  language_preference=resolved_lang,
258
+ learning_mode=mode,
259
  doc_type=doc_type_val,
260
  course_outline=course_outline,
261
  weaknesses=weaknesses,
262
  cognitive_state=cognitive_state,
263
+ rag_context=rag_context
264
  )
265
+
266
+ # 更新 Memory Line 状态文本 (模拟)
267
+ new_status = render_session_status(mode, weaknesses, cognitive_state)
268
+
269
+ return "", new_history, weaknesses, cognitive_state, new_status
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270
 
271
  user_input.submit(
272
  respond,
273
+ [user_input, chatbot, course_outline_state, weakness_state, cognitive_state_state, rag_chunks_state, model_name, language_preference, learning_mode, doc_type],
274
+ [user_input, chatbot, weakness_state, cognitive_state_state, session_status]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
275
  )
276
 
277
+ # 3. Action Buttons (Right Sidebar) -> Output to `result_display`
278
+
279
+ # Export
280
+ def on_export(chat_history, course_outline, mode, weaknesses, cognitive_state):
281
+ return export_conversation(chat_history, course_outline, mode, weaknesses, cognitive_state)
 
 
 
 
282
 
283
  export_btn.click(
284
  on_export,
285
  [chatbot, course_outline_state, learning_mode, weakness_state, cognitive_state_state],
286
+ [result_display]
287
  )
288
 
289
+ # Quiz
290
+ def on_quiz(chat_history, course_outline, weaknesses, cognitive_state, model, lang):
291
+ return generate_quiz_from_history(chat_history, course_outline, weaknesses, cognitive_state, model, lang)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
292
 
293
  quiz_btn.click(
294
  on_quiz,
295
+ [chatbot, course_outline_state, weakness_state, cognitive_state_state, model_name, language_preference],
296
+ [result_display]
 
 
 
 
 
 
 
297
  )
298
 
299
+ # Summary
300
+ def on_summary(chat_history, course_outline, weaknesses, cognitive_state, model, lang):
301
+ return summarize_conversation(chat_history, course_outline, weaknesses, cognitive_state, model, lang)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
302
 
303
  summary_btn.click(
304
  on_summary,
305
+ [chatbot, course_outline_state, weakness_state, cognitive_state_state, model_name, language_preference],
306
+ [result_display]
 
 
 
 
 
 
 
307
  )
308
 
309
+ # 4. Reset Logic
310
+ def clear_all():
311
+ empty_state = {"confusion": 0, "mastery": 0}
312
+ default_status = render_session_status("Concept Explainer", [], empty_state)
313
+ return [], [], empty_state, [], "", default_status
314
 
315
+ clear_btn.click(
316
+ clear_all,
317
+ None,
318
+ [chatbot, weakness_state, cognitive_state_state, rag_chunks_state, result_display, session_status],
319
+ queue=False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320
  )
321
+
322
+ # 5. User Guide Links (Logic to show text in Result box or popup)
323
+ # 为了简化交互,点击 User Guide 按钮时,将内容显示在右侧 Result 框或者中间 Chat
324
+ # 这里示例显示在右侧 Result 框
325
+ def show_guide(section):
326
+ return get_user_guide_section(section)
327
+
328
+ ug_getting_started.click(lambda: show_guide("getting_started"), outputs=result_display)
329
+ ug_mode_def.click(lambda: show_guide("mode_definition"), outputs=result_display)
330
+ ug_how_works.click(lambda: show_guide("how_clare_works"), outputs=result_display)
331
+ ug_memory_line.click(lambda: show_guide("memory_line"), outputs=result_display)
332
 
333
  if __name__ == "__main__":
334
+ demo.launch()