File size: 20,136 Bytes
5b422be
 
 
 
 
 
 
 
 
 
 
2d2ce75
5b422be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a2a88bfa",
   "metadata": {},
   "source": [
    "# 测试脚本\n",
    "\n",
    "使用此脚本需要打开 RWKV Runner,通过调用 API 接口进行批量测试。\n",
    "\n",
    "使用该脚本时,被测试的 jsonl 文件需要是和训练集相同的单轮问答对话;\n",
    "\n",
    "测试时,会同时生成一个‘测试结果’和‘正确答案’的对比到指定 jsonl 中。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ae91c93a",
   "metadata": {},
   "source": [
    "## 测试整个文件夹中的全部 jsonl"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "43660c81",
   "metadata": {},
   "outputs": [],
   "source": [
    "# %% [markdown]\n",
    "# # 模型测试脚本 (批量处理文件夹中的jsonl文件)\n",
    "#\n",
    "# 请按以下步骤操作:\n",
    "# **1.**  **修改配置部分**: 找到下面的 `--- 配置 ---` 部分,并更新 `INPUT_FOLDER_PATH`, `OUTPUT_FOLDER_PATH`, `API_URL`, `HEADERS`。`REQUEST_PARAMS` 已根据您的要求更新。\n",
    "# **2.**  **检查 API 响应解析**: 在 `get_model_completion` 函数内部,找到标记为 `!!! 重要 !!!` 的部分,确保代码能正确解析你的模型 API 返回的 JSON 数据以提取文本输出。\n",
    "# **3.**  **运行此单元格**: 执行这个单元格开始测试。结果将逐文件写入输出文件夹。\n",
    "\n",
    "# %%\n",
    "import requests\n",
    "import json\n",
    "import sys\n",
    "import os\n",
    "import csv # 导入csv模块\n",
    "from tqdm.notebook import tqdm # 使用 notebook 版本的 tqdm\n",
    "from datetime import datetime # 用于添加时间戳\n",
    "from IPython import get_ipython # 用于在 Jupyter Notebook 中检测环境\n",
    "\n",
    "# --- 配置 ---\n",
    "# vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv\n",
    "# vvvvvvvvvvvvvvvvv 请在这里修改你的配置 vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv\n",
    "\n",
    "INPUT_FOLDER_PATH = \"./Test\"                            # 输入路径 \n",
    "OUTPUT_FOLDER_PATH = \"./Test/Results/20250526/new\"       # 输出路径 \n",
    "API_URL = \"http://192.168.0.103:8022/v1/completions\"    # API 地址\n",
    "\n",
    "HEADERS = {\n",
    "    'Content-Type': 'application/json',\n",
    "}\n",
    "\n",
    "REQUEST_PARAMS = {\n",
    "    \"max_tokens\": 100,\n",
    "    \"temperature\": 0.4,\n",
    "    \"top_p\": 0,\n",
    "    \"presence_penalty\": 0,\n",
    "    \"frequency_penalty\": 0,\n",
    "    \"stop\": [\"\\n\", \"User:\"]\n",
    "}\n",
    "# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
    "# ^^^^^^^^^^^^^^^^^^^^^^^^^ 配置结束 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
    "# --- 配置结束 ---\n",
    "\n",
    "print(\"--- 配置加载 ---\")\n",
    "print(f\"输入文件夹路径: {INPUT_FOLDER_PATH}\")\n",
    "print(f\"输出文件夹路径: {OUTPUT_FOLDER_PATH}\")\n",
    "print(f\"API 地址: {API_URL}\")\n",
    "print(f\"请求参数 (已更新): {REQUEST_PARAMS}\")\n",
    "print(\"-\" * 30)\n",
    "\n",
    "# --- 辅助函数 ---\n",
    "def process_jsonl_line(line):\n",
    "    try:\n",
    "        data = json.loads(line)\n",
    "        full_text = data.get(\"text\")\n",
    "        if not full_text: return None, None\n",
    "        parts = full_text.split(\"\\n\\nAssistant:\", 1)\n",
    "        if len(parts) != 2: return None, None\n",
    "        prompt = parts[0] + \"\\n\\nAssistant:\"\n",
    "        expected_answer = parts[1].strip()\n",
    "        return prompt, expected_answer\n",
    "    except: return None, None\n",
    "\n",
    "def get_model_completion(prompt):\n",
    "    payload = {\"prompt\": prompt, **REQUEST_PARAMS}\n",
    "    try:\n",
    "        response = requests.post(API_URL, headers=HEADERS, json=payload, timeout=60)\n",
    "        response.raise_for_status()\n",
    "        response_data = response.json()\n",
    "        # !!! 重要: 这里需要根据你的 API 返回的具体格式来调整 !!!\n",
    "        model_output = response_data.get('choices', [{}])[0].get('text', '').strip()\n",
    "        return model_output if model_output is not None else \"\"\n",
    "    except (requests.exceptions.RequestException, json.JSONDecodeError, KeyError, IndexError, AttributeError, TypeError) as e:\n",
    "        # print(f\"API请求或解析错误: {e}\") # 可以取消注释以调试API问题\n",
    "        return None\n",
    "\n",
    "def process_single_file(input_file_path, output_file_path):\n",
    "    total_count, correct_count, lines_processed, invalid_format_count, api_errors = 0, 0, 0, 0, 0\n",
    "    print(f\"\\n开始处理文件: {input_file_path}\")\n",
    "    print(f\"详细结果将写入: {output_file_path}\")\n",
    "    # print(\"-\" * 30) # 减少重复打印分隔线\n",
    "    try:\n",
    "        with open(output_file_path, 'w', encoding='utf-8') as outfile:\n",
    "            try:\n",
    "                 with open(input_file_path, 'r', encoding='utf-8') as f_count: num_lines = sum(1 for _ in f_count)\n",
    "            except: num_lines = None\n",
    "\n",
    "            with open(input_file_path, 'r', encoding='utf-8') as infile:\n",
    "                # tqdm的bar_format可以保持简洁一些\n",
    "                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",
    "                for line in file_iterator:\n",
    "                    lines_processed += 1\n",
    "                    line = line.strip()\n",
    "                    if not line: continue\n",
    "                    prompt, expected_answer = process_jsonl_line(line)\n",
    "                    if prompt is None or expected_answer is None:\n",
    "                        invalid_format_count += 1\n",
    "                    else:\n",
    "                        model_output = get_model_completion(prompt)\n",
    "                        if model_output is not None:\n",
    "                            total_count += 1 # 有效的API响应和测试对\n",
    "                            is_correct = (model_output == expected_answer)\n",
    "                            if is_correct: correct_count += 1\n",
    "                            result_data = {\"expected_answer\": expected_answer, \"model_output\": model_output, \"is_correct\": is_correct}\n",
    "                            outfile.write(json.dumps(result_data, ensure_ascii=False) + '\\n')\n",
    "                        else:\n",
    "                            api_errors += 1\n",
    "                    # 更新进度条后缀\n",
    "                    accuracy = (correct_count / total_count * 100) if total_count > 0 else 0.0\n",
    "                    file_iterator.set_postfix_str(f\"正确:{correct_count}/{total_count} ({accuracy:.1f}%) APIErr:{api_errors} FormatErr:{invalid_format_count}\")\n",
    "                outfile.flush()\n",
    "    except FileNotFoundError:\n",
    "         print(f\"错误:处理期间未找到输入文件 '{input_file_path}'。\")\n",
    "         return None\n",
    "    except IOError as e:\n",
    "         print(f\"错误: 读写文件 '{output_file_path}' 时发生错误: {e}\")\n",
    "         return None\n",
    "    except Exception as e:\n",
    "        print(f\"\\n处理文件 '{os.path.basename(input_file_path)}' 时发生意外错误: {e}\")\n",
    "        import traceback; traceback.print_exc()\n",
    "        return None\n",
    "    \n",
    "    final_accuracy = (correct_count / total_count * 100) if total_count > 0 else 0.0\n",
    "    # 确保返回的字典键名清晰\n",
    "    return {\n",
    "        \"filename\": os.path.basename(input_file_path), # 文件全名\n",
    "        \"lines_processed\": lines_processed,\n",
    "        \"invalid_format_count\": invalid_format_count,\n",
    "        \"api_errors\": api_errors,\n",
    "        \"total_valid_tests\": total_count, # 测试数据条数\n",
    "        \"correct_predictions\": correct_count, # 正确条数\n",
    "        \"accuracy_percent\": final_accuracy # 正确率\n",
    "    }\n",
    "\n",
    "# --- 主处理逻辑 ---\n",
    "def main():\n",
    "    os.makedirs(OUTPUT_FOLDER_PATH, exist_ok=True)\n",
    "    today_date = datetime.now().strftime(\"%Y%m%d\")\n",
    "    \n",
    "    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",
    "    \n",
    "    if not input_files_paths:\n",
    "        print(f\"错误:在输入文件夹 '{INPUT_FOLDER_PATH}' 中未找到任何jsonl文件。\")\n",
    "        return\n",
    "    \n",
    "    print(f\"\\n找到 {len(input_files_paths)} 个jsonl文件待处理:\")\n",
    "    for file_path_item in input_files_paths: print(f\"  - {os.path.basename(file_path_item)}\")\n",
    "    \n",
    "    all_stats_collected = []\n",
    "    \n",
    "    summary_txt_filename = f\"accuracy_summary_{today_date}.txt\"\n",
    "    summary_txt_filepath = os.path.join(OUTPUT_FOLDER_PATH, summary_txt_filename)\n",
    "    \n",
    "    summary_csv_filename = f\"accuracy_summary_{today_date}.csv\"\n",
    "    summary_csv_filepath = os.path.join(OUTPUT_FOLDER_PATH, summary_csv_filename)\n",
    "\n",
    "    try:\n",
    "        with open(summary_txt_filepath, 'w', encoding='utf-8') as summary_txt_file, \\\n",
    "             open(summary_csv_filepath, 'w', encoding='utf-8', newline='') as summary_csv_file:\n",
    "            \n",
    "            csv_writer = csv.writer(summary_csv_file)\n",
    "\n",
    "            # 写入TXT文件头 (保持不变)\n",
    "            summary_txt_file.write(f\"测试日期: {today_date}\\n\")\n",
    "            summary_txt_file.write(\"=\"*40 + \"\\n\")\n",
    "            summary_txt_file.write(f\"{'文件名':<30} | {'正确率':>7}\\n\")\n",
    "            summary_txt_file.write(\"=\"*40 + \"\\n\")\n",
    "            summary_txt_file.flush()\n",
    "\n",
    "            # --- 修改CSV文件头 ---\n",
    "            csv_header = ['文件名', '测试数据条数', '正确条数', '正确率 (%)']\n",
    "            csv_writer.writerow(csv_header)\n",
    "            summary_csv_file.flush()\n",
    "\n",
    "            for current_input_file_path in input_files_paths:\n",
    "                base_name = os.path.basename(current_input_file_path)\n",
    "                name_without_ext = os.path.splitext(base_name)[0]\n",
    "                output_jsonl_file = os.path.join(OUTPUT_FOLDER_PATH, f\"{name_without_ext}_{today_date}.jsonl\")\n",
    "                \n",
    "                stats_data = process_single_file(current_input_file_path, output_jsonl_file)\n",
    "                \n",
    "                if stats_data:\n",
    "                    all_stats_collected.append(stats_data)\n",
    "                    \n",
    "                    # 写入TXT文件 (文件名缩短逻辑保持)\n",
    "                    filename_display_txt = stats_data['filename']\n",
    "                    if len(filename_display_txt) > 28: filename_display_txt = filename_display_txt[:25] + \"...\"\n",
    "                    summary_txt_file.write(f\"{filename_display_txt:<30} | {stats_data['accuracy_percent']:>6.2f}%\\n\")\n",
    "                    summary_txt_file.flush()\n",
    "\n",
    "                    # --- 修改写入CSV文件的数据行 ---\n",
    "                    csv_row = [\n",
    "                        stats_data['filename'],  # 文件全名\n",
    "                        stats_data['total_valid_tests'],\n",
    "                        stats_data['correct_predictions'],\n",
    "                        f\"{stats_data['accuracy_percent']:.2f}%\" # 格式化正确率\n",
    "                    ]\n",
    "                    csv_writer.writerow(csv_row)\n",
    "                    summary_csv_file.flush()\n",
    "            \n",
    "            # 所有文件处理完毕后,写入总体统计\n",
    "            if all_stats_collected:\n",
    "                # 使用 process_single_file 返回的键名\n",
    "                grand_total_lines = sum(s[\"lines_processed\"] for s in all_stats_collected)\n",
    "                grand_total_tests = sum(s[\"total_valid_tests\"] for s in all_stats_collected)\n",
    "                grand_total_correct = sum(s[\"correct_predictions\"] for s in all_stats_collected)\n",
    "                overall_accuracy_percent = (grand_total_correct / grand_total_tests * 100) if grand_total_tests > 0 else 0.0\n",
    "                \n",
    "                # 写入TXT总体统计 (保持不变)\n",
    "                summary_txt_file.write(\"=\"*40 + \"\\n\")\n",
    "                summary_txt_file.write(f\"{'总体准确率':<30} | {overall_accuracy_percent:>6.2f}%\\n\")\n",
    "                summary_txt_file.write(\"=\"*40 + \"\\n\")\n",
    "                summary_txt_file.flush()\n",
    "\n",
    "                # --- 修改写入CSV的总体统计行 ---\n",
    "                csv_writer.writerow([]) # 可选:写入一个空行作为分隔\n",
    "                overall_csv_row = [\n",
    "                    'TOTAL / OVERALL',\n",
    "                    grand_total_tests,\n",
    "                    grand_total_correct,\n",
    "                    f\"{overall_accuracy_percent:.2f}%\"\n",
    "                ]\n",
    "                csv_writer.writerow(overall_csv_row)\n",
    "                summary_csv_file.flush()\n",
    "                \n",
    "                # 控制台打印总结信息\n",
    "                print(\"\\n\" + \"=\" * 50 + \"\\n所有文件处理完成!\\n\" + \"=\" * 50)\n",
    "                print(f\"\\n总计处理了 {len(all_stats_collected)} 个文件,{grand_total_lines} 行输入\")\n",
    "                print(f\"总计 {grand_total_tests} 个有效测试,{grand_total_correct} 个正确预测\")\n",
    "                print(f\"总体准确率: {overall_accuracy_percent:.2f}%\")\n",
    "                \n",
    "                print(\"\\n各文件详细统计 (控制台):\")\n",
    "                for s_item in all_stats_collected:\n",
    "                    print(f\"\\n文件: {s_item['filename']}\")\n",
    "                    print(f\"  处理行数: {s_item['lines_processed']}\")\n",
    "                    print(f\"  格式错误行数: {s_item['invalid_format_count']}\")\n",
    "                    print(f\"  API错误数: {s_item['api_errors']}\")\n",
    "                    print(f\"  有效测试数 (total_valid_tests): {s_item['total_valid_tests']}\")\n",
    "                    print(f\"  正确预测数 (correct_predictions): {s_item['correct_predictions']}\")\n",
    "                    print(f\"  准确率 (accuracy_percent): {s_item['accuracy_percent']:.2f}%\")\n",
    "                \n",
    "                print(f\"\\n已将准确率摘要写入到 TXT: {summary_txt_filepath}\")\n",
    "                print(f\"已将准确率摘要写入到 CSV: {summary_csv_filepath}\")\n",
    "            \n",
    "            else: \n",
    "                message = \"所有文件的处理均未成功生成统计数据。\"\n",
    "                summary_txt_file.write(\"=\"*40 + \"\\n\" + f\"{message}\\n\")\n",
    "                # CSV中也可以记录此信息\n",
    "                csv_writer.writerow([message, 'N/A', 'N/A', 'N/A'])\n",
    "                summary_csv_file.flush()\n",
    "                print(f\"\\n{message} 摘要文件已更新。\")\n",
    "                                \n",
    "    except IOError as e:\n",
    "        print(f\"\\n错误:处理摘要文件时发生IO错误: {e}\")\n",
    "        if all_stats_collected: # 尝试打印已收集的数据\n",
    "            print(\"\\n注意:摘要文件写入可能存在问题,但以下是控制台的统计信息。\")\n",
    "            # (可以复用上面的控制台打印逻辑,但为了简洁此处省略)\n",
    "            print(\"请检查控制台输出获取部分结果。\")\n",
    "\n",
    "    if not all_stats_collected and input_files_paths:\n",
    "        print(\"\\n所有文件的处理均未成功生成统计数据(未在摘要文件中记录此信息,若摘要文件创建失败)。\")\n",
    "\n",
    "# 执行主函数\n",
    "if __name__ == \"__main__\":\n",
    "    try:\n",
    "        shell = get_ipython().__class__.__name__\n",
    "        if shell != 'ZMQInteractiveShell': raise NameError\n",
    "    except NameError:\n",
    "        try:\n",
    "            from tqdm import tqdm as std_tqdm\n",
    "            globals()['tqdm'] = std_tqdm \n",
    "            print(\"信息:非Jupyter Notebook环境,使用标准tqdm。\")\n",
    "        except ImportError:\n",
    "            print(\"警告:标准tqdm库未安装。进度条可能无法正常显示或仅简单打印。\")\n",
    "            class dummy_tqdm: # 改进的dummy_tqdm\n",
    "                def __init__(self, iterable=None, desc=\"\", total=None, unit=\"\", bar_format=None, **kwargs):\n",
    "                    self.iterable, self.desc, self.total, self.current, self.unit = iterable, desc, total, 0, unit\n",
    "                    self.postfix_text = \"\"\n",
    "                    if self.total:\n",
    "                        print(f\"{self.desc}: 开始处理 {self.total} {self.unit}...\")\n",
    "                    else:\n",
    "                        print(f\"{self.desc}: 开始处理...\")\n",
    "\n",
    "                def __iter__(self):\n",
    "                    for i, obj in enumerate(self.iterable):\n",
    "                        yield obj\n",
    "                        self.update(1)\n",
    "                        if self.total and (i + 1) % (self.total // 10 if self.total >=10 else 1) == 0: # 每10%或每项打印\n",
    "                             self.print_status()\n",
    "                        elif not self.total and (i+1) % 50 == 0: # 如果没有total,每50项打印\n",
    "                             self.print_status()\n",
    "\n",
    "\n",
    "                def set_postfix_str(self, s):\n",
    "                    self.postfix_text = s\n",
    "                    # 不立即打印,由 __iter__ 中的逻辑控制打印频率\n",
    "\n",
    "                def print_status(self):\n",
    "                    total_str = str(self.total) if self.total else \"?\"\n",
    "                    sys.stdout.write(f\"\\r{self.desc}: {self.current}/{total_str} {self.unit} | {self.postfix_text}      \")\n",
    "                    sys.stdout.flush()\n",
    "\n",
    "                def update(self, n=1):\n",
    "                    self.current += n\n",
    "\n",
    "                def close(self):\n",
    "                    self.print_status() # 确保最后的状态被打印\n",
    "                    sys.stdout.write(f\"\\n{self.desc}: 处理完成 {self.current} {self.unit}。\\n\")\n",
    "                    sys.stdout.flush()\n",
    "            globals()['tqdm'] = dummy_tqdm\n",
    "    main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "55187222",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "torch",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}