-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
291 lines (243 loc) · 9.28 KB
/
Copy pathapp.py
File metadata and controls
291 lines (243 loc) · 9.28 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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
#!/usr/bin/env python3
"""
学术成长记录系统 - Flask 后端服务
"""
from flask import Flask, render_template, jsonify, request, send_from_directory
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import uuid
import os
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///academic_growth.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['STATIC_FOLDER'] = 'static'
db = SQLAlchemy(app)
# ============================================
# 数据库模型
# ============================================
class Course(db.Model):
id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
name = db.Column(db.String(100), nullable=False)
credits = db.Column(db.Float, nullable=False)
score = db.Column(db.Float, nullable=False)
created_at = db.Column(db.DateTime, default=datetime.now)
class Record(db.Model):
id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
type = db.Column(db.String(20), nullable=False) # competition, internship, research
name = db.Column(db.String(100), nullable=False)
time = db.Column(db.String(20))
role = db.Column(db.String(50))
description = db.Column(db.Text)
created_at = db.Column(db.DateTime, default=datetime.now)
# ============================================
# 工具函数
# ============================================
def calc_gpa(score):
"""计算单门课程绩点 (百分制 → 4.0制)"""
if score is None or score < 0:
return 0
return max(0, min(4, score / 10 - 5))
def calc_total_gpa(courses):
"""计算加权平均 GPA"""
if not courses:
return None
total_weight = 0
total_credits = 0
for course in courses:
cr = float(course.credits)
if cr <= 0:
continue
total_weight += calc_gpa(float(course.score)) * cr
total_credits += cr
return None if total_credits == 0 else total_weight / total_credits
def calc_total_credits(courses):
"""计算总学分"""
return sum(float(c.credits) for c in courses) if courses else 0
def get_eval_tags(courses, records):
"""获取智能画像标签"""
tags = []
gpa = calc_total_gpa(courses)
practice_total = len([r for r in records if r.type in ['competition', 'internship', 'research']])
if gpa is not None and gpa > 3.8:
tags.append({'name': '学神', 'type': 'rose'})
elif gpa is not None and gpa > 3.0:
tags.append({'name': '学霸', 'type': 'sage'})
if practice_total > 3:
tags.append({'name': '实践达人', 'type': 'sage'})
research_count = len([r for r in records if r.type == 'research'])
if research_count >= 2:
tags.append({'name': '科研新星', 'type': 'rose'})
if gpa is not None and gpa > 3.0 and practice_total > 3:
tags.append({'name': '全面发展', 'type': 'warm'})
return tags
def generate_summary(courses, records):
"""生成评价文字"""
gpa = calc_total_gpa(courses)
gpa_str = f"{gpa:.2f}" if gpa is not None else '--'
course_count = len(courses)
record_count = len([r for r in records if r.type in ['competition', 'internship', 'research']])
if course_count == 0 and record_count == 0:
return ''
s = f"你目前共记录了 {course_count} 门课程"
if gpa is not None:
s += f", GPA {gpa_str}"
if record_count > 0:
s += f", 以及 {record_count} 项实践经历"
s += '。'
if gpa is not None and gpa > 3.8:
s += ' 学业表现卓越,堪称学神级别!'
elif gpa is not None and gpa > 3.0:
s += ' 学业成绩优异,继续保持!'
elif gpa is not None and gpa > 0:
s += ' 继续努力,未来可期!'
if record_count > 5:
s += ' 实践经历丰富,综合能力突出。'
elif record_count > 0:
s += ' 实践经历正在积累中,加油!'
return s
# ============================================
# API 路由
# ============================================
@app.route('/api/courses', methods=['GET'])
def get_courses():
"""获取所有课程"""
courses = Course.query.all()
return jsonify([{
'id': c.id,
'name': c.name,
'credits': c.credits,
'score': c.score
} for c in courses])
@app.route('/api/courses', methods=['POST'])
def add_course():
"""添加课程"""
data = request.json
course = Course(
name=data['name'],
credits=data['credits'],
score=data['score']
)
db.session.add(course)
db.session.commit()
return jsonify({'id': course.id, 'success': True})
@app.route('/api/courses/<course_id>', methods=['PUT'])
def update_course(course_id):
"""更新课程"""
course = Course.query.get(course_id)
if not course:
return jsonify({'error': '课程不存在'}), 404
data = request.json
course.name = data.get('name', course.name)
course.credits = data.get('credits', course.credits)
course.score = data.get('score', course.score)
db.session.commit()
return jsonify({'success': True})
@app.route('/api/courses/<course_id>', methods=['DELETE'])
def delete_course(course_id):
"""删除课程"""
course = Course.query.get(course_id)
if not course:
return jsonify({'error': '课程不存在'}), 404
db.session.delete(course)
db.session.commit()
return jsonify({'success': True})
@app.route('/api/records', methods=['GET'])
def get_records():
"""获取所有记录"""
records = Record.query.all()
result = {'competition': [], 'internship': [], 'research': []}
for r in records:
result[r.type].append({
'id': r.id,
'name': r.name,
'time': r.time,
'role': r.role,
'description': r.description
})
return jsonify(result)
@app.route('/api/records', methods=['POST'])
def add_record():
"""添加记录"""
data = request.json
record = Record(
type=data['type'],
name=data['name'],
time=data.get('time'),
role=data.get('role'),
description=data.get('description')
)
db.session.add(record)
db.session.commit()
return jsonify({'id': record.id, 'success': True})
@app.route('/api/records/<record_id>', methods=['DELETE'])
def delete_record(record_id):
"""删除记录"""
record = Record.query.get(record_id)
if not record:
return jsonify({'error': '记录不存在'}), 404
db.session.delete(record)
db.session.commit()
return jsonify({'success': True})
@app.route('/api/stats', methods=['GET'])
def get_stats():
"""获取统计数据"""
courses = Course.query.all()
records = Record.query.all()
gpa = calc_total_gpa(courses)
total_credits = calc_total_credits(courses)
comp_count = len([r for r in records if r.type == 'competition'])
intern_count = len([r for r in records if r.type == 'internship'])
research_count = len([r for r in records if r.type == 'research'])
return jsonify({
'gpa': f"{gpa:.2f}" if gpa is not None else '--',
'credits': f"{total_credits:.1f}",
'courseCount': len(courses),
'compCount': comp_count,
'internCount': intern_count,
'researchCount': research_count,
'totalRecords': comp_count + intern_count + research_count
})
@app.route('/api/eval', methods=['GET'])
def get_eval():
"""获取智能评价"""
courses = Course.query.all()
records = Record.query.all()
tags = get_eval_tags(courses, records)
summary = generate_summary(courses, records)
return jsonify({'tags': tags, 'summary': summary})
# ============================================
# 静态文件服务
# ============================================
@app.route('/')
def index():
return send_from_directory(app.config['STATIC_FOLDER'], 'index.html')
@app.route('/<path:path>')
def static_files(path):
return send_from_directory(app.config['STATIC_FOLDER'], path)
# ============================================
# 初始化数据库
# ============================================
def init_db():
with app.app_context():
db.create_all()
# 添加一些示例数据
if not Course.query.first():
sample_courses = [
{'name': '高等数学', 'credits': 4, 'score': 92},
{'name': '数据结构', 'credits': 3, 'score': 88},
{'name': '计算机网络', 'credits': 3, 'score': 90},
{'name': '操作系统', 'credits': 3, 'score': 85},
]
for c in sample_courses:
db.session.add(Course(name=c['name'], credits=c['credits'], score=c['score']))
sample_records = [
{'type': 'competition', 'name': '全国数学建模竞赛', 'time': '2024-08', 'role': '队长'},
{'type': 'internship', 'name': '腾讯科技有限公司', 'time': '2024-07', 'role': '前端开发实习生'},
{'type': 'research', 'name': '机器学习算法研究', 'time': '2024-05', 'role': '研究员'},
]
for r in sample_records:
db.session.add(Record(**r))
db.session.commit()
if __name__ == '__main__':
init_db()
app.run(debug=True, host='0.0.0.0', port=8080)