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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"id": "a2a88bfa",
|
| 6 |
+
"metadata": {},
|
| 7 |
+
"source": [
|
| 8 |
+
"# 测试脚本\n",
|
| 9 |
+
"\n",
|
| 10 |
+
"使用此脚本需要打开 RWKV Runner,通过调用 API 接口进行批量测试。\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"使用该脚本时,被测试的 jsonl 文件需要是和训练集相同的单论问答对话;\n",
|
| 13 |
+
"\n",
|
| 14 |
+
"测试时,会同时生成一个‘测试结果’和‘正确答案’的对比到指定 jsonl 中。"
|
| 15 |
+
]
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "markdown",
|
| 19 |
+
"id": "ae91c93a",
|
| 20 |
+
"metadata": {},
|
| 21 |
+
"source": [
|
| 22 |
+
"## 测试整个文件夹中的全部 jsonl"
|
| 23 |
+
]
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
"cell_type": "code",
|
| 27 |
+
"execution_count": null,
|
| 28 |
+
"id": "43660c81",
|
| 29 |
+
"metadata": {},
|
| 30 |
+
"outputs": [],
|
| 31 |
+
"source": [
|
| 32 |
+
"# %% [markdown]\n",
|
| 33 |
+
"# # 模型测试脚本 (批量处理文件夹中的jsonl文件)\n",
|
| 34 |
+
"#\n",
|
| 35 |
+
"# 请按以下步骤操作:\n",
|
| 36 |
+
"# **1.** **修改配置部分**: 找到下面的 `--- 配置 ---` 部分,并更新 `INPUT_FOLDER_PATH`, `OUTPUT_FOLDER_PATH`, `API_URL`, `HEADERS`。`REQUEST_PARAMS` 已根据您的要求更新。\n",
|
| 37 |
+
"# **2.** **检查 API 响应解析**: 在 `get_model_completion` 函数内部,找到标记为 `!!! 重要 !!!` 的部分,确保代码能正确解析你的模型 API 返回的 JSON 数据以提取文本输出。\n",
|
| 38 |
+
"# **3.** **运行此单元格**: 执行这个单元格开始测试。结果将逐文件写入输出文件夹。\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"# %%\n",
|
| 41 |
+
"import requests\n",
|
| 42 |
+
"import json\n",
|
| 43 |
+
"import sys\n",
|
| 44 |
+
"import os\n",
|
| 45 |
+
"import csv # 导入csv模块\n",
|
| 46 |
+
"from tqdm.notebook import tqdm # 使用 notebook 版本的 tqdm\n",
|
| 47 |
+
"from datetime import datetime # 用于添加时间戳\n",
|
| 48 |
+
"from IPython import get_ipython # 用于在 Jupyter Notebook 中检测环境\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"# --- 配置 ---\n",
|
| 51 |
+
"# vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv\n",
|
| 52 |
+
"# vvvvvvvvvvvvvvvvv 请在这里修改你的配置 vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv\n",
|
| 53 |
+
"\n",
|
| 54 |
+
"INPUT_FOLDER_PATH = \"./Test\" # 输入路径 \n",
|
| 55 |
+
"OUTPUT_FOLDER_PATH = \"./Test/Results/20250526/new\" # 输出路径 \n",
|
| 56 |
+
"API_URL = \"http://192.168.0.103:8022/v1/completions\" # API 地址\n",
|
| 57 |
+
"\n",
|
| 58 |
+
"HEADERS = {\n",
|
| 59 |
+
" 'Content-Type': 'application/json',\n",
|
| 60 |
+
"}\n",
|
| 61 |
+
"\n",
|
| 62 |
+
"REQUEST_PARAMS = {\n",
|
| 63 |
+
" \"max_tokens\": 100,\n",
|
| 64 |
+
" \"temperature\": 0.4,\n",
|
| 65 |
+
" \"top_p\": 0,\n",
|
| 66 |
+
" \"presence_penalty\": 0,\n",
|
| 67 |
+
" \"frequency_penalty\": 0,\n",
|
| 68 |
+
" \"stop\": [\"\\n\", \"User:\"]\n",
|
| 69 |
+
"}\n",
|
| 70 |
+
"# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
|
| 71 |
+
"# ^^^^^^^^^^^^^^^^^^^^^^^^^ 配置结束 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
|
| 72 |
+
"# --- 配置结束 ---\n",
|
| 73 |
+
"\n",
|
| 74 |
+
"print(\"--- 配置加载 ---\")\n",
|
| 75 |
+
"print(f\"输入文件夹路径: {INPUT_FOLDER_PATH}\")\n",
|
| 76 |
+
"print(f\"输出文件夹路径: {OUTPUT_FOLDER_PATH}\")\n",
|
| 77 |
+
"print(f\"API 地址: {API_URL}\")\n",
|
| 78 |
+
"print(f\"请求参数 (已更新): {REQUEST_PARAMS}\")\n",
|
| 79 |
+
"print(\"-\" * 30)\n",
|
| 80 |
+
"\n",
|
| 81 |
+
"# --- 辅助函数 ---\n",
|
| 82 |
+
"def process_jsonl_line(line):\n",
|
| 83 |
+
" try:\n",
|
| 84 |
+
" data = json.loads(line)\n",
|
| 85 |
+
" full_text = data.get(\"text\")\n",
|
| 86 |
+
" if not full_text: return None, None\n",
|
| 87 |
+
" parts = full_text.split(\"\\n\\nAssistant:\", 1)\n",
|
| 88 |
+
" if len(parts) != 2: return None, None\n",
|
| 89 |
+
" prompt = parts[0] + \"\\n\\nAssistant:\"\n",
|
| 90 |
+
" expected_answer = parts[1].strip()\n",
|
| 91 |
+
" return prompt, expected_answer\n",
|
| 92 |
+
" except: return None, None\n",
|
| 93 |
+
"\n",
|
| 94 |
+
"def get_model_completion(prompt):\n",
|
| 95 |
+
" payload = {\"prompt\": prompt, **REQUEST_PARAMS}\n",
|
| 96 |
+
" try:\n",
|
| 97 |
+
" response = requests.post(API_URL, headers=HEADERS, json=payload, timeout=60)\n",
|
| 98 |
+
" response.raise_for_status()\n",
|
| 99 |
+
" response_data = response.json()\n",
|
| 100 |
+
" # !!! 重要: 这里需要根据你的 API 返回的具体格式来调整 !!!\n",
|
| 101 |
+
" model_output = response_data.get('choices', [{}])[0].get('text', '').strip()\n",
|
| 102 |
+
" return model_output if model_output is not None else \"\"\n",
|
| 103 |
+
" except (requests.exceptions.RequestException, json.JSONDecodeError, KeyError, IndexError, AttributeError, TypeError) as e:\n",
|
| 104 |
+
" # print(f\"API请求或解析错误: {e}\") # 可以取消注释以调试API问题\n",
|
| 105 |
+
" return None\n",
|
| 106 |
+
"\n",
|
| 107 |
+
"def process_single_file(input_file_path, output_file_path):\n",
|
| 108 |
+
" total_count, correct_count, lines_processed, invalid_format_count, api_errors = 0, 0, 0, 0, 0\n",
|
| 109 |
+
" print(f\"\\n开始处理文件: {input_file_path}\")\n",
|
| 110 |
+
" print(f\"详细结果将写入: {output_file_path}\")\n",
|
| 111 |
+
" # print(\"-\" * 30) # 减少重复打印分隔线\n",
|
| 112 |
+
" try:\n",
|
| 113 |
+
" with open(output_file_path, 'w', encoding='utf-8') as outfile:\n",
|
| 114 |
+
" try:\n",
|
| 115 |
+
" with open(input_file_path, 'r', encoding='utf-8') as f_count: num_lines = sum(1 for _ in f_count)\n",
|
| 116 |
+
" except: num_lines = None\n",
|
| 117 |
+
"\n",
|
| 118 |
+
" with open(input_file_path, 'r', encoding='utf-8') as infile:\n",
|
| 119 |
+
" # tqdm的bar_format可以保持简洁一些\n",
|
| 120 |
+
" file_iterator = tqdm(infile, total=num_lines, desc=f\"测试 {os.path.basename(input_file_path)}\", unit=\" 行\", bar_format='{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]')\n",
|
| 121 |
+
" for line in file_iterator:\n",
|
| 122 |
+
" lines_processed += 1\n",
|
| 123 |
+
" line = line.strip()\n",
|
| 124 |
+
" if not line: continue\n",
|
| 125 |
+
" prompt, expected_answer = process_jsonl_line(line)\n",
|
| 126 |
+
" if prompt is None or expected_answer is None:\n",
|
| 127 |
+
" invalid_format_count += 1\n",
|
| 128 |
+
" else:\n",
|
| 129 |
+
" model_output = get_model_completion(prompt)\n",
|
| 130 |
+
" if model_output is not None:\n",
|
| 131 |
+
" total_count += 1 # 有效的API响应和测试对\n",
|
| 132 |
+
" is_correct = (model_output == expected_answer)\n",
|
| 133 |
+
" if is_correct: correct_count += 1\n",
|
| 134 |
+
" result_data = {\"expected_answer\": expected_answer, \"model_output\": model_output, \"is_correct\": is_correct}\n",
|
| 135 |
+
" outfile.write(json.dumps(result_data, ensure_ascii=False) + '\\n')\n",
|
| 136 |
+
" else:\n",
|
| 137 |
+
" api_errors += 1\n",
|
| 138 |
+
" # 更新进度条后缀\n",
|
| 139 |
+
" accuracy = (correct_count / total_count * 100) if total_count > 0 else 0.0\n",
|
| 140 |
+
" file_iterator.set_postfix_str(f\"正确:{correct_count}/{total_count} ({accuracy:.1f}%) APIErr:{api_errors} FormatErr:{invalid_format_count}\")\n",
|
| 141 |
+
" outfile.flush()\n",
|
| 142 |
+
" except FileNotFoundError:\n",
|
| 143 |
+
" print(f\"错误:处理期间未找到输入文件 '{input_file_path}'。\")\n",
|
| 144 |
+
" return None\n",
|
| 145 |
+
" except IOError as e:\n",
|
| 146 |
+
" print(f\"错误: 读写文件 '{output_file_path}' 时发生错误: {e}\")\n",
|
| 147 |
+
" return None\n",
|
| 148 |
+
" except Exception as e:\n",
|
| 149 |
+
" print(f\"\\n处理文件 '{os.path.basename(input_file_path)}' 时发生意外错误: {e}\")\n",
|
| 150 |
+
" import traceback; traceback.print_exc()\n",
|
| 151 |
+
" return None\n",
|
| 152 |
+
" \n",
|
| 153 |
+
" final_accuracy = (correct_count / total_count * 100) if total_count > 0 else 0.0\n",
|
| 154 |
+
" # 确保返回的字典键名清晰\n",
|
| 155 |
+
" return {\n",
|
| 156 |
+
" \"filename\": os.path.basename(input_file_path), # 文件全名\n",
|
| 157 |
+
" \"lines_processed\": lines_processed,\n",
|
| 158 |
+
" \"invalid_format_count\": invalid_format_count,\n",
|
| 159 |
+
" \"api_errors\": api_errors,\n",
|
| 160 |
+
" \"total_valid_tests\": total_count, # 测试数据条数\n",
|
| 161 |
+
" \"correct_predictions\": correct_count, # 正确条数\n",
|
| 162 |
+
" \"accuracy_percent\": final_accuracy # 正确率\n",
|
| 163 |
+
" }\n",
|
| 164 |
+
"\n",
|
| 165 |
+
"# --- 主处理逻辑 ---\n",
|
| 166 |
+
"def main():\n",
|
| 167 |
+
" os.makedirs(OUTPUT_FOLDER_PATH, exist_ok=True)\n",
|
| 168 |
+
" today_date = datetime.now().strftime(\"%Y%m%d\")\n",
|
| 169 |
+
" \n",
|
| 170 |
+
" input_files_paths = [os.path.join(INPUT_FOLDER_PATH, item) for item in os.listdir(INPUT_FOLDER_PATH) if item.endswith('.jsonl') and os.path.isfile(os.path.join(INPUT_FOLDER_PATH, item))]\n",
|
| 171 |
+
" \n",
|
| 172 |
+
" if not input_files_paths:\n",
|
| 173 |
+
" print(f\"错误:在输入文件夹 '{INPUT_FOLDER_PATH}' 中未找到任何jsonl文件。\")\n",
|
| 174 |
+
" return\n",
|
| 175 |
+
" \n",
|
| 176 |
+
" print(f\"\\n找到 {len(input_files_paths)} 个jsonl文件待处理:\")\n",
|
| 177 |
+
" for file_path_item in input_files_paths: print(f\" - {os.path.basename(file_path_item)}\")\n",
|
| 178 |
+
" \n",
|
| 179 |
+
" all_stats_collected = []\n",
|
| 180 |
+
" \n",
|
| 181 |
+
" summary_txt_filename = f\"accuracy_summary_{today_date}.txt\"\n",
|
| 182 |
+
" summary_txt_filepath = os.path.join(OUTPUT_FOLDER_PATH, summary_txt_filename)\n",
|
| 183 |
+
" \n",
|
| 184 |
+
" summary_csv_filename = f\"accuracy_summary_{today_date}.csv\"\n",
|
| 185 |
+
" summary_csv_filepath = os.path.join(OUTPUT_FOLDER_PATH, summary_csv_filename)\n",
|
| 186 |
+
"\n",
|
| 187 |
+
" try:\n",
|
| 188 |
+
" with open(summary_txt_filepath, 'w', encoding='utf-8') as summary_txt_file, \\\n",
|
| 189 |
+
" open(summary_csv_filepath, 'w', encoding='utf-8', newline='') as summary_csv_file:\n",
|
| 190 |
+
" \n",
|
| 191 |
+
" csv_writer = csv.writer(summary_csv_file)\n",
|
| 192 |
+
"\n",
|
| 193 |
+
" # 写入TXT文件头 (保持不变)\n",
|
| 194 |
+
" summary_txt_file.write(f\"测试日期: {today_date}\\n\")\n",
|
| 195 |
+
" summary_txt_file.write(\"=\"*40 + \"\\n\")\n",
|
| 196 |
+
" summary_txt_file.write(f\"{'文件名':<30} | {'正确率':>7}\\n\")\n",
|
| 197 |
+
" summary_txt_file.write(\"=\"*40 + \"\\n\")\n",
|
| 198 |
+
" summary_txt_file.flush()\n",
|
| 199 |
+
"\n",
|
| 200 |
+
" # --- 修改CSV文件头 ---\n",
|
| 201 |
+
" csv_header = ['文件名', '测试数据条数', '正确条数', '正确率 (%)']\n",
|
| 202 |
+
" csv_writer.writerow(csv_header)\n",
|
| 203 |
+
" summary_csv_file.flush()\n",
|
| 204 |
+
"\n",
|
| 205 |
+
" for current_input_file_path in input_files_paths:\n",
|
| 206 |
+
" base_name = os.path.basename(current_input_file_path)\n",
|
| 207 |
+
" name_without_ext = os.path.splitext(base_name)[0]\n",
|
| 208 |
+
" output_jsonl_file = os.path.join(OUTPUT_FOLDER_PATH, f\"{name_without_ext}_{today_date}.jsonl\")\n",
|
| 209 |
+
" \n",
|
| 210 |
+
" stats_data = process_single_file(current_input_file_path, output_jsonl_file)\n",
|
| 211 |
+
" \n",
|
| 212 |
+
" if stats_data:\n",
|
| 213 |
+
" all_stats_collected.append(stats_data)\n",
|
| 214 |
+
" \n",
|
| 215 |
+
" # 写入TXT文件 (文件名缩短逻辑保持)\n",
|
| 216 |
+
" filename_display_txt = stats_data['filename']\n",
|
| 217 |
+
" if len(filename_display_txt) > 28: filename_display_txt = filename_display_txt[:25] + \"...\"\n",
|
| 218 |
+
" summary_txt_file.write(f\"{filename_display_txt:<30} | {stats_data['accuracy_percent']:>6.2f}%\\n\")\n",
|
| 219 |
+
" summary_txt_file.flush()\n",
|
| 220 |
+
"\n",
|
| 221 |
+
" # --- 修改写入CSV文件的数据行 ---\n",
|
| 222 |
+
" csv_row = [\n",
|
| 223 |
+
" stats_data['filename'], # 文件全名\n",
|
| 224 |
+
" stats_data['total_valid_tests'],\n",
|
| 225 |
+
" stats_data['correct_predictions'],\n",
|
| 226 |
+
" f\"{stats_data['accuracy_percent']:.2f}%\" # 格式化正确率\n",
|
| 227 |
+
" ]\n",
|
| 228 |
+
" csv_writer.writerow(csv_row)\n",
|
| 229 |
+
" summary_csv_file.flush()\n",
|
| 230 |
+
" \n",
|
| 231 |
+
" # 所有文件处理完毕后,写入总体统计\n",
|
| 232 |
+
" if all_stats_collected:\n",
|
| 233 |
+
" # 使用 process_single_file 返回的键名\n",
|
| 234 |
+
" grand_total_lines = sum(s[\"lines_processed\"] for s in all_stats_collected)\n",
|
| 235 |
+
" grand_total_tests = sum(s[\"total_valid_tests\"] for s in all_stats_collected)\n",
|
| 236 |
+
" grand_total_correct = sum(s[\"correct_predictions\"] for s in all_stats_collected)\n",
|
| 237 |
+
" overall_accuracy_percent = (grand_total_correct / grand_total_tests * 100) if grand_total_tests > 0 else 0.0\n",
|
| 238 |
+
" \n",
|
| 239 |
+
" # 写入TXT总体统计 (保持不变)\n",
|
| 240 |
+
" summary_txt_file.write(\"=\"*40 + \"\\n\")\n",
|
| 241 |
+
" summary_txt_file.write(f\"{'总体准确率':<30} | {overall_accuracy_percent:>6.2f}%\\n\")\n",
|
| 242 |
+
" summary_txt_file.write(\"=\"*40 + \"\\n\")\n",
|
| 243 |
+
" summary_txt_file.flush()\n",
|
| 244 |
+
"\n",
|
| 245 |
+
" # --- 修改写入CSV的总体统计行 ---\n",
|
| 246 |
+
" csv_writer.writerow([]) # 可选:写入一个空行作为分隔\n",
|
| 247 |
+
" overall_csv_row = [\n",
|
| 248 |
+
" 'TOTAL / OVERALL',\n",
|
| 249 |
+
" grand_total_tests,\n",
|
| 250 |
+
" grand_total_correct,\n",
|
| 251 |
+
" f\"{overall_accuracy_percent:.2f}%\"\n",
|
| 252 |
+
" ]\n",
|
| 253 |
+
" csv_writer.writerow(overall_csv_row)\n",
|
| 254 |
+
" summary_csv_file.flush()\n",
|
| 255 |
+
" \n",
|
| 256 |
+
" # 控制台打印总结信息\n",
|
| 257 |
+
" print(\"\\n\" + \"=\" * 50 + \"\\n所有文件处理完成!\\n\" + \"=\" * 50)\n",
|
| 258 |
+
" print(f\"\\n总计处理了 {len(all_stats_collected)} 个文件,{grand_total_lines} 行输入\")\n",
|
| 259 |
+
" print(f\"总计 {grand_total_tests} 个有效测试,{grand_total_correct} 个正确预测\")\n",
|
| 260 |
+
" print(f\"总体准确率: {overall_accuracy_percent:.2f}%\")\n",
|
| 261 |
+
" \n",
|
| 262 |
+
" print(\"\\n各文件详细统计 (控制台):\")\n",
|
| 263 |
+
" for s_item in all_stats_collected:\n",
|
| 264 |
+
" print(f\"\\n文件: {s_item['filename']}\")\n",
|
| 265 |
+
" print(f\" 处理行数: {s_item['lines_processed']}\")\n",
|
| 266 |
+
" print(f\" 格式错误行数: {s_item['invalid_format_count']}\")\n",
|
| 267 |
+
" print(f\" API错误数: {s_item['api_errors']}\")\n",
|
| 268 |
+
" print(f\" 有效测试数 (total_valid_tests): {s_item['total_valid_tests']}\")\n",
|
| 269 |
+
" print(f\" 正确预测数 (correct_predictions): {s_item['correct_predictions']}\")\n",
|
| 270 |
+
" print(f\" 准确率 (accuracy_percent): {s_item['accuracy_percent']:.2f}%\")\n",
|
| 271 |
+
" \n",
|
| 272 |
+
" print(f\"\\n已将准确率摘要写入到 TXT: {summary_txt_filepath}\")\n",
|
| 273 |
+
" print(f\"已将准确率摘要写入到 CSV: {summary_csv_filepath}\")\n",
|
| 274 |
+
" \n",
|
| 275 |
+
" else: \n",
|
| 276 |
+
" message = \"所有文件的处理均未成功生成统计数据。\"\n",
|
| 277 |
+
" summary_txt_file.write(\"=\"*40 + \"\\n\" + f\"{message}\\n\")\n",
|
| 278 |
+
" # CSV中也可以记录此信息\n",
|
| 279 |
+
" csv_writer.writerow([message, 'N/A', 'N/A', 'N/A'])\n",
|
| 280 |
+
" summary_csv_file.flush()\n",
|
| 281 |
+
" print(f\"\\n{message} 摘要文件已更新。\")\n",
|
| 282 |
+
" \n",
|
| 283 |
+
" except IOError as e:\n",
|
| 284 |
+
" print(f\"\\n错误:处理摘要文件时发生IO错误: {e}\")\n",
|
| 285 |
+
" if all_stats_collected: # 尝试打印已收集的数据\n",
|
| 286 |
+
" print(\"\\n注意:摘要文件写入可能存在问题,但以下是控制台的统计信息。\")\n",
|
| 287 |
+
" # (可以复用上面的控制台打印逻辑,但为了简洁此处省略)\n",
|
| 288 |
+
" print(\"请检查控制台输出获取部分结果。\")\n",
|
| 289 |
+
"\n",
|
| 290 |
+
" if not all_stats_collected and input_files_paths:\n",
|
| 291 |
+
" print(\"\\n所有文件的处理均未成功生成统计数据(未在摘要文件中记录此信息,若摘要文件创建失败)。\")\n",
|
| 292 |
+
"\n",
|
| 293 |
+
"# 执行主函数\n",
|
| 294 |
+
"if __name__ == \"__main__\":\n",
|
| 295 |
+
" try:\n",
|
| 296 |
+
" shell = get_ipython().__class__.__name__\n",
|
| 297 |
+
" if shell != 'ZMQInteractiveShell': raise NameError\n",
|
| 298 |
+
" except NameError:\n",
|
| 299 |
+
" try:\n",
|
| 300 |
+
" from tqdm import tqdm as std_tqdm\n",
|
| 301 |
+
" globals()['tqdm'] = std_tqdm \n",
|
| 302 |
+
" print(\"信息:非Jupyter Notebook环境,使用标准tqdm。\")\n",
|
| 303 |
+
" except ImportError:\n",
|
| 304 |
+
" print(\"警告:标准tqdm库未安装。进度条可能无法正常显示或仅简单打印。\")\n",
|
| 305 |
+
" class dummy_tqdm: # 改进的dummy_tqdm\n",
|
| 306 |
+
" def __init__(self, iterable=None, desc=\"\", total=None, unit=\"\", bar_format=None, **kwargs):\n",
|
| 307 |
+
" self.iterable, self.desc, self.total, self.current, self.unit = iterable, desc, total, 0, unit\n",
|
| 308 |
+
" self.postfix_text = \"\"\n",
|
| 309 |
+
" if self.total:\n",
|
| 310 |
+
" print(f\"{self.desc}: 开始处理 {self.total} {self.unit}...\")\n",
|
| 311 |
+
" else:\n",
|
| 312 |
+
" print(f\"{self.desc}: 开始处理...\")\n",
|
| 313 |
+
"\n",
|
| 314 |
+
" def __iter__(self):\n",
|
| 315 |
+
" for i, obj in enumerate(self.iterable):\n",
|
| 316 |
+
" yield obj\n",
|
| 317 |
+
" self.update(1)\n",
|
| 318 |
+
" if self.total and (i + 1) % (self.total // 10 if self.total >=10 else 1) == 0: # 每10%或每项打印\n",
|
| 319 |
+
" self.print_status()\n",
|
| 320 |
+
" elif not self.total and (i+1) % 50 == 0: # 如果没有total,每50项打印\n",
|
| 321 |
+
" self.print_status()\n",
|
| 322 |
+
"\n",
|
| 323 |
+
"\n",
|
| 324 |
+
" def set_postfix_str(self, s):\n",
|
| 325 |
+
" self.postfix_text = s\n",
|
| 326 |
+
" # 不立即打印,由 __iter__ 中的逻辑控制打印频率\n",
|
| 327 |
+
"\n",
|
| 328 |
+
" def print_status(self):\n",
|
| 329 |
+
" total_str = str(self.total) if self.total else \"?\"\n",
|
| 330 |
+
" sys.stdout.write(f\"\\r{self.desc}: {self.current}/{total_str} {self.unit} | {self.postfix_text} \")\n",
|
| 331 |
+
" sys.stdout.flush()\n",
|
| 332 |
+
"\n",
|
| 333 |
+
" def update(self, n=1):\n",
|
| 334 |
+
" self.current += n\n",
|
| 335 |
+
"\n",
|
| 336 |
+
" def close(self):\n",
|
| 337 |
+
" self.print_status() # 确保最后的状态被打印\n",
|
| 338 |
+
" sys.stdout.write(f\"\\n{self.desc}: 处理完成 {self.current} {self.unit}。\\n\")\n",
|
| 339 |
+
" sys.stdout.flush()\n",
|
| 340 |
+
" globals()['tqdm'] = dummy_tqdm\n",
|
| 341 |
+
" main()"
|
| 342 |
+
]
|
| 343 |
+
},
|
| 344 |
+
{
|
| 345 |
+
"cell_type": "code",
|
| 346 |
+
"execution_count": null,
|
| 347 |
+
"id": "55187222",
|
| 348 |
+
"metadata": {},
|
| 349 |
+
"outputs": [],
|
| 350 |
+
"source": []
|
| 351 |
+
}
|
| 352 |
+
],
|
| 353 |
+
"metadata": {
|
| 354 |
+
"kernelspec": {
|
| 355 |
+
"display_name": "torch",
|
| 356 |
+
"language": "python",
|
| 357 |
+
"name": "python3"
|
| 358 |
+
},
|
| 359 |
+
"language_info": {
|
| 360 |
+
"codemirror_mode": {
|
| 361 |
+
"name": "ipython",
|
| 362 |
+
"version": 3
|
| 363 |
+
},
|
| 364 |
+
"file_extension": ".py",
|
| 365 |
+
"mimetype": "text/x-python",
|
| 366 |
+
"name": "python",
|
| 367 |
+
"nbconvert_exporter": "python",
|
| 368 |
+
"pygments_lexer": "ipython3",
|
| 369 |
+
"version": "3.12.7"
|
| 370 |
+
}
|
| 371 |
+
},
|
| 372 |
+
"nbformat": 4,
|
| 373 |
+
"nbformat_minor": 5
|
| 374 |
+
}
|