-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstate.py
More file actions
154 lines (132 loc) · 5.79 KB
/
Copy pathstate.py
File metadata and controls
154 lines (132 loc) · 5.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
"""全局状态容器 — 单例模式,所有模块通过它读写数据"""
import json
import os
from models import Concept, Relation, QuizQuestion, QuizRecord
from datetime import date
STATE_FILE = os.path.join(os.path.dirname(__file__), "data", "state.json")
class AppState:
"""应用全局状态,单例"""
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance._init()
return cls._instance
def _init(self):
self.concepts: dict[str, Concept] = {} # id → Concept
self.relations: list[Relation] = []
self.questions: dict[str, QuizQuestion] = {} # id → QuizQuestion
self.records: list[QuizRecord] = []
# ─── 写入 ───
def add_concept(self, c: Concept):
existing = self.concepts.get(c.id)
if existing:
existing.description = existing.description or c.description
existing.category = existing.category or c.category
existing.difficulty = c.difficulty or existing.difficulty
existing.related_ids = list(set(existing.related_ids + c.related_ids))
else:
self.concepts[c.id] = c
def add_relation(self, r: Relation):
if not any(x.src_id == r.src_id and x.dst_id == r.dst_id and x.rel_type == r.rel_type for x in self.relations):
self.relations.append(r)
src = self.concepts.get(r.src_id)
dst = self.concepts.get(r.dst_id)
if src and r.dst_id not in src.related_ids:
src.related_ids.append(r.dst_id)
if dst and r.src_id not in dst.related_ids:
dst.related_ids.append(r.src_id)
def add_question(self, q: QuizQuestion):
self.questions[q.id] = q
def add_record(self, r: QuizRecord):
r.reviewed_at = date.today().isoformat()
self.records.append(r)
# ─── 查询 ───
def get_concept_by_id(self, cid: str) -> Concept | None:
return self.concepts.get(cid)
def get_concept_by_name(self, name: str) -> Concept | None:
for c in self.concepts.values():
if c.name == name:
return c
return None
def get_weak_concepts(self, top_n: int = 10) -> list[tuple[Concept, float]]:
"""返回正确率最低的概念 (concept, rate)"""
stats: dict[str, list[bool]] = {}
for r in self.records:
for cid in r.concept_ids:
stats.setdefault(cid, []).append(r.is_correct)
result = []
for cid, results in stats.items():
concept = self.concepts.get(cid)
if concept:
rate = sum(results) / len(results)
result.append((concept, rate))
result.sort(key=lambda x: x[1])
return result[:top_n]
def get_due_reviews(self, target_date: str = "") -> list[tuple[QuizRecord, QuizQuestion]]:
"""获取到期待复习的题目"""
if not target_date:
target_date = date.today().isoformat()
due = []
for r in self.records:
if r.next_review <= target_date and not r.is_correct:
q = self.questions.get(r.question_id)
if q:
due.append((r, q))
return due
def get_graph_data(self) -> dict:
"""返回 PyVis 格式的图数据"""
nodes = []
for c in self.concepts.values():
nodes.append({
"id": c.id, "label": c.name, "title": c.description,
"group": c.category, "value": max(1, len(c.related_ids)),
"difficulty": c.difficulty
})
edges = []
for r in self.relations:
edges.append({
"from": r.src_id, "to": r.dst_id,
"label": r.rel_type, "title": r.description
})
return {"nodes": nodes, "edges": edges}
def get_stats(self) -> dict:
"""返回统计信息"""
correct = sum(1 for r in self.records if r.is_correct)
total = len(self.records)
return {
"concepts": len(self.concepts),
"relations": len(self.relations),
"questions": len(self.questions),
"records": total,
"accuracy": f"{correct/total*100:.1f}%" if total > 0 else "N/A"
}
# ─── 持久化 ───
def save(self):
data = {
"concepts": [c.__dict__ for c in self.concepts.values()],
"relations": [r.__dict__ for r in self.relations],
"questions": [q.__dict__ for q in self.questions.values()],
"records": [r.__dict__ for r in self.records],
}
os.makedirs(os.path.dirname(STATE_FILE), exist_ok=True)
with open(STATE_FILE, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
def load(self):
if not os.path.exists(STATE_FILE):
return
with open(STATE_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
self._init()
for d in data.get("concepts", []):
c = Concept(d["name"], d.get("description",""), d.get("category",""), d.get("source_file",""), d.get("difficulty",3), d.get("related_ids",[]))
self.concepts[c.id] = c
for d in data.get("relations", []):
self.relations.append(Relation(d["src_id"], d["dst_id"], d.get("rel_type",""), d.get("description","")))
for d in data.get("questions", []):
q = QuizQuestion(d["question"], d["correct_answer"], d.get("explanation",""), d.get("concept_ids",[]), d.get("q_type","choice"), d.get("options",[]), d.get("difficulty",3))
self.questions[q.id] = q
for d in data.get("records", []):
self.records.append(QuizRecord(**d))
def clear(self):
self._init()