聊天机器人羲和的代码04
进一步完善和优化聊天机器人GUI,使其更加丰富和美观,采取了以下措施:
添加图标:为应用程序添加一个图标。
调整布局:进一步优化布局,使其更加美观。
增加样式:使用更多的样式和主题来提升视觉效果。
添加动画:增加加载动画以提高用户体验。
优化控件:使用更现代的控件和布局方式。
以下是具体实现:
-
添加图标
首先,确保您有一个图标文件(例如 icon.ico),然后将其添加到您的项目中。 -
调整布局
使用 ttk.Frame 和 ttk.LabelFrame 来更好地组织控件。 -
增加样式
使用 ttkbootstrap 的样式和主题来提升视觉效果。 -
增加动画
使用 ttk.Progressbar 来显示加载进度。 -
优化控件
使用 ttk.LabelFrame 来分组相关控件,使其更加清晰。
完整代码
import os
import json
import jsonlines
import torch
from torch.utils.data import Dataset, DataLoader
from transformers import BertModel, BertTokenizer
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
import logging
from difflib import SequenceMatcher
from datetime import datetime
import speech_recognition as sr# 获取项目根目录
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))# 配置日志
LOGS_DIR = os.path.join(PROJECT_ROOT, 'logs')
os.makedirs(LOGS_DIR, exist_ok=True)def setup_logging():log_file = os.path.join(LOGS_DIR, datetime.now().strftime('%Y-%m-%d/%H-%M-%S/羲和.txt'))os.makedirs(os.path.dirname(log_file), exist_ok=True)logging.basicConfig(level=logging.INFO,format='%(asctime)s - %(levelname)s - %(message)s',handlers=[logging.FileHandler(log_file),logging.StreamHandler()])setup_logging()# 数据集类
class XihuaDataset(Dataset):def __init__(self, file_path, tokenizer, max_length=128):self.tokenizer = tokenizerself.max_length = max_lengthself.data = self.load_data(file_path)def load_data(self, file_path):data = []if file_path.endswith('.jsonl'):with jsonlines.open(file_path) as reader:for i, item in enumerate(reader):try:if self.validate_item(item):data.append(item)except jsonlines.jsonlines.InvalidLineError as e:logging.warning(f"跳过无效行 {i + 1}: {e}")elif file_path.endswith('.json'):with open(file_path, 'r') as f:try:data = [item for item in json.load(f) if self.validate_item(item)]except json.JSONDecodeError as e:logging.warning(f"跳过无效文件 {file_path}: {e}")return datadef validate_item(self, item):required_keys = ['question', 'human_answers', 'chatgpt_answers']if all(key in item for key in required_keys):return Truelogging.warning(f"跳过无效项: 缺少必要键 {required_keys}")return Falsedef __len__(self):return len(self.data)def __getitem__(self, idx):item = self.data[idx]question = item['question']human_answer = item[