OK much
This commit is contained in:
204
Html/db/user.py
204
Html/db/user.py
@@ -1,116 +1,116 @@
|
||||
from datetime import date
|
||||
from tinydb import TinyDB, Query
|
||||
import os
|
||||
# Example usage:
|
||||
import json
|
||||
from datetime import datetime
|
||||
|
||||
LOCAL_USER_DATA_DIR = "data/user/" # only use locally, not for other .py files
|
||||
|
||||
class User:
|
||||
def __init__(self, db_file='user_data.json'):
|
||||
"""初始化用户管理,自动打开并加载 JSON 数据文件。"""
|
||||
self.db_file = db_file
|
||||
self.db = TinyDB(self.db_file)
|
||||
self.user_query = Query()
|
||||
def __init__(self, user_id, select_course, head_icon, course_process_dict, save_path):
|
||||
self.user_id = user_id # User ID
|
||||
self.select_course = select_course # List of selected courses
|
||||
self.head_icon = head_icon # URL of the user's head icon
|
||||
self.course_process_dict = course_process_dict # Dictionary of courses with their progress
|
||||
self.save_path = save_path
|
||||
|
||||
def add_user(self, user_data):
|
||||
"""添加新的用户"""
|
||||
if not self.db.search(self.user_query.user_id == user_data['user_id']):
|
||||
self.db.insert(user_data)
|
||||
else:
|
||||
print(f"User with ID {user_data['user_id']} already exists.")
|
||||
def save_chapter_memory(self, course_id, lesson_id, subchapter_title, mem_list, score, is_rebuttal):
|
||||
'''
|
||||
Save the memory of a chapter
|
||||
'''
|
||||
try:
|
||||
if(course_id not in self.course_process_dict):
|
||||
self.course_process_dict[course_id] = {'lesson_processs':[], 'course_put_in_date':'', 'course_last_study_date':'', 'course_total_study_time':0}
|
||||
self.course_process_dict[course_id]['course_last_study_date'] = datetime.now().strftime('%Y-%m-%d')
|
||||
for _ in range(len(self.course_process_dict[course_id]['lesson_processs'])):
|
||||
lesson_process, lid = self.course_process_dict[course_id]['lesson_processs'][_]
|
||||
if lid == lesson_id:
|
||||
saveed = False
|
||||
for i in range(len(lesson_process)):
|
||||
chapter_info = lesson_process[i]
|
||||
if chapter_info['title'] == subchapter_title:
|
||||
chapter_info['dialog'] = mem_list
|
||||
if is_rebuttal:
|
||||
chapter_info['rebuttal_score'] = score
|
||||
else:
|
||||
chapter_info['score'] = score
|
||||
chapter_info['is_rebuttal'] = is_rebuttal
|
||||
saveed = True
|
||||
break
|
||||
if not saveed:
|
||||
lesson_process.append({
|
||||
'title': subchapter_title,
|
||||
'dialog': mem_list,
|
||||
'score': score,
|
||||
'is_rebuttal': is_rebuttal,
|
||||
'rebuttal_score': score if is_rebuttal else 0,
|
||||
})
|
||||
break
|
||||
self.save_to_file()
|
||||
except Exception as e:
|
||||
print("=-=-=-=-=-=")
|
||||
print(e)
|
||||
def get_course_progress(self):
|
||||
for course_name, course_data in self.course_process_dict.items():
|
||||
print(f"Course: {course_name}")
|
||||
for lessons,lesson_id in course_data["lesson_processs"]:
|
||||
print(f" Lesson ID: {lesson_id}")
|
||||
for chapter in lessons:
|
||||
chapter_info = chapter
|
||||
print(f" Chapter Dialog: {chapter_info['dialog']}")
|
||||
print(f" Chapter Score: {chapter_info['score']}")
|
||||
print(f" Rebuttal: {'Yes' if chapter_info['is_rebuttal'] else 'No'}")
|
||||
if chapter_info['is_rebuttal']:
|
||||
print(f" Rebuttal Score: {chapter_info['rebuttal_score']}")
|
||||
|
||||
def get_user(self, user_id):
|
||||
"""根据 user_id 获取用户信息"""
|
||||
result = self.db.search(self.user_query.user_id == user_id)
|
||||
return result[0] if result else None
|
||||
def select_new_course(self, course_id, course):
|
||||
self.select_course.append(course_id)
|
||||
|
||||
def update_user(self, user_id, updated_data):
|
||||
"""更新用户信息"""
|
||||
self.db.update(updated_data, self.user_query.user_id == user_id)
|
||||
|
||||
def delete_user(self, user_id):
|
||||
"""删除用户"""
|
||||
self.db.remove(self.user_query.user_id == user_id)
|
||||
|
||||
def get_all_users(self):
|
||||
"""获取所有用户"""
|
||||
return self.db.all()
|
||||
self.course_process_dict[course_id] = {'lesson_processs':[], 'course_put_in_date':'', 'course_last_study_date':'','course_total_study_time':0}
|
||||
self.course_process_dict[course_id]['lesson_processs']
|
||||
for lesson in course.lessons:
|
||||
self.course_process_dict[course_id]['lesson_processs'].append(([], lesson['lesson_id']))
|
||||
|
||||
|
||||
# 用户数据结构示例
|
||||
# user_data = {
|
||||
# 'user_id': 'user123',
|
||||
# 'select_course': ['course1', 'course2'],
|
||||
# 'course_process_dict': {
|
||||
# 'course1': {
|
||||
# 'course_process': {
|
||||
# 'lesson_processs': [
|
||||
# {
|
||||
# 'lesson_process': [
|
||||
# {
|
||||
# 'chapter_info': {
|
||||
# 'dialog': ['This is chapter 1 dialog'],
|
||||
# 'score': 85,
|
||||
# 'is_rebuttal': True,
|
||||
# 'rebuttal_score': 90
|
||||
# }
|
||||
# },
|
||||
# {
|
||||
# 'chapter_info': {
|
||||
# 'dialog': ['This is chapter 2 dialog'],
|
||||
# 'score': 75,
|
||||
# 'is_rebuttal': False,
|
||||
# 'rebuttal_score': 0
|
||||
# }
|
||||
# }
|
||||
# ]
|
||||
# }
|
||||
# ],
|
||||
# 'course_put_in_date': date(2024, 1, 1),
|
||||
# 'course_last_study_date': date(2024, 12, 25),
|
||||
# 'course_total_study_time': 120 # 总学习时间:分钟
|
||||
# }
|
||||
# },
|
||||
# 'course2': {
|
||||
# 'course_process': {
|
||||
# 'lesson_processs': [
|
||||
# {
|
||||
# 'lesson_process': [
|
||||
# {
|
||||
# 'chapter_info': {
|
||||
# 'dialog': ['This is course2 chapter 1 dialog'],
|
||||
# 'score': 88,
|
||||
# 'is_rebuttal': False,
|
||||
# 'rebuttal_score': 0
|
||||
# }
|
||||
# }
|
||||
# ]
|
||||
# }
|
||||
# ],
|
||||
# 'course_put_in_date': date(2024, 2, 1),
|
||||
# 'course_last_study_date': date(2024, 12, 24),
|
||||
# 'course_total_study_time': 90
|
||||
# }
|
||||
# }
|
||||
# }
|
||||
# }
|
||||
with open(self.save_path, 'w') as f:
|
||||
json.dump(self.__json__(), f, indent=4)
|
||||
|
||||
# updated_user_data = {
|
||||
# 'select_course': ['course1', 'course3']
|
||||
# }
|
||||
def save_to_file(self):
|
||||
print(f"saved at {self.save_path}")
|
||||
self.get_course_progress()
|
||||
with open(self.save_path, 'w') as f:
|
||||
json.dump(self.__json__(), f, indent=4)
|
||||
|
||||
# # 创建 User 实例
|
||||
# user_list = User()
|
||||
def __json__(self):
|
||||
return {
|
||||
'user_id': self.user_id,
|
||||
'select_course': self.select_course,
|
||||
'head_icon': self.head_icon,
|
||||
'course_process_dict': self.course_process_dict
|
||||
}
|
||||
|
||||
# # 添加用户
|
||||
# user_list.add_user(user_data)
|
||||
def to_json(self):
|
||||
return json.dumps(self.__json__(), indent=4)
|
||||
|
||||
# # 获取用户信息
|
||||
# user = user_list.get_user('user123')
|
||||
# print(user)
|
||||
def load_user_from_json(user_id, user_data_dir = None)-> User:
|
||||
USER_DATA_DIR = user_data_dir if user_data_dir else LOCAL_USER_DATA_DIR
|
||||
with open(os.path.join(USER_DATA_DIR, f'{user_id}.json'), "r") as f:
|
||||
raw_json = f.read()
|
||||
user_data = json.loads(raw_json)
|
||||
return User(save_path = os.path.join(USER_DATA_DIR, f'{user_id}.json'), **user_data)
|
||||
|
||||
# # 更新用户选择的课程
|
||||
# user_list.update_user('user123', updated_user_data)
|
||||
def create_user_json(user_id, user_data_dir = None):
|
||||
USER_DATA_DIR = user_data_dir if user_data_dir else LOCAL_USER_DATA_DIR
|
||||
with open(os.path.join(USER_DATA_DIR, f'{user_id}.json'), "w") as f:
|
||||
f.write(json.dumps({
|
||||
'user_id': user_id,
|
||||
'select_course': [],
|
||||
'head_icon': '',
|
||||
'course_process_dict': {}
|
||||
}))
|
||||
|
||||
# # 获取所有用户
|
||||
# all_users = user_list.get_all_users()
|
||||
# print(all_users)
|
||||
if(__name__ == "__main__"):
|
||||
|
||||
# # 删除用户
|
||||
# user_list.delete_user('user123')
|
||||
user = load_user_from_json('cake')
|
||||
|
||||
|
||||
user.get_course_progress()
|
||||
|
||||
Reference in New Issue
Block a user