diff --git "a/make_data_v2.ipynb" "b/make_data_v2.ipynb" new file mode 100644--- /dev/null +++ "b/make_data_v2.ipynb" @@ -0,0 +1,12481 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "396471a8", + "metadata": {}, + "source": [ + "# 生成-999~999的所有两两组合,加到指定jsonl后面\n", + "\n", + "用于生成:\n", + "\n", + "训练集:ADD_base_8M\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7835b055", + "metadata": {}, + "outputs": [], + "source": [ + "# -*- coding: utf-8 -*-\n", + "import json\n", + "import time\n", + "import os\n", + "import traceback\n", + "\n", + "# ===============================================\n", + "# 配置参数区域\n", + "# ===============================================\n", + "# 要追加到的目标 JSONL 文件名 (请确保此文件存在或脚本有权限创建)\n", + "TARGET_JSONL_FILE = \"ADD_base_.jsonl\"\n", + "\n", + "# 数字范围 (包含边界)\n", + "MIN_NUMBER = -999\n", + "MAX_NUMBER = 999\n", + "\n", + "# 控制进度报告的频率 (每处理 N 对数字报告一次)\n", + "REPORT_INTERVAL = 50000\n", + "# ===============================================\n", + "\n", + "def generate_pairwise_arithmetic(filename: str, min_num: int, max_num: int):\n", + " \"\"\"\n", + " 生成指定范围内所有数字对的加减法算术题,并追加到指定文件。\n", + " 确保生成的 JSONL 文件中,由本脚本添加的内容不包含空行。\n", + "\n", + " Args:\n", + " filename (str): 要追加数据到的 JSONL 文件名。\n", + " min_num (int): 范围的最小值 (包含)。\n", + " max_num (int): 范围的最大值 (包含)。\n", + " \"\"\"\n", + " print(f\"--- 开始生成 {min_num} 到 {max_num} 范围内的全排列加减法 ---\")\n", + " print(f\"将追加数据到文件: {filename}\")\n", + "\n", + " if min_num > max_num:\n", + " print(\"错误: 最小值不能大于最大值。\")\n", + " return\n", + "\n", + " number_range = list(range(min_num, max_num + 1))\n", + " total_numbers = len(number_range)\n", + " total_pairs = total_numbers * total_numbers\n", + " total_lines_expected = total_pairs * 2\n", + "\n", + " print(f\"数字范围内的数字数量: {total_numbers:,}\")\n", + " print(f\"需要处理的数字对总数: {total_pairs:,}\")\n", + " print(f\"预计追加的总行数: {total_lines_expected:,}\")\n", + "\n", + " start_time = time.time()\n", + " lines_added = 0\n", + " pairs_processed = 0\n", + " generation_successful = False # 添加一个标志来跟踪是否成功生成\n", + "\n", + " try:\n", + " with open(filename, 'a', encoding='utf-8') as f:\n", + " for a in number_range:\n", + " for b in number_range:\n", + " # 1. 处理加法 a + b\n", + " try:\n", + " c_add = a + b\n", + " question_add = f\"{a} + {b} = ?\"\n", + " answer_add = str(c_add)\n", + " text_content_add = f\"User: {question_add}\\n\\nAssistant: {answer_add}\"\n", + " data_add = {\"text\": text_content_add}\n", + " json_line_add = json.dumps(data_add, ensure_ascii=False)\n", + " f.write(json_line_add + '\\n') # 标准JSONL写法\n", + " lines_added += 1\n", + " except Exception as e_add:\n", + " print(f\"\\n处理加法时出错: a={a}, b={b}. 错误: {e_add}\")\n", + "\n", + " # 2. 处理减法 a - b\n", + " try:\n", + " c_sub = a - b\n", + " question_sub = f\"{a} - {b} = ?\"\n", + " answer_sub = str(c_sub)\n", + " text_content_sub = f\"User: {question_sub}\\n\\nAssistant: {answer_sub}\"\n", + " data_sub = {\"text\": text_content_sub}\n", + " json_line_sub = json.dumps(data_sub, ensure_ascii=False)\n", + " f.write(json_line_sub + '\\n') # 标准JSONL写法\n", + " lines_added += 1\n", + " except Exception as e_sub:\n", + " print(f\"\\n处理减法时出错: a={a}, b={b}. 错误: {e_sub}\")\n", + "\n", + " pairs_processed += 1\n", + "\n", + " # --- 进度报告 ---\n", + " if pairs_processed % REPORT_INTERVAL == 0 or pairs_processed == total_pairs:\n", + " elapsed_time = time.time() - start_time\n", + " progress = pairs_processed / total_pairs if total_pairs > 0 else 0\n", + " pairs_per_sec = pairs_processed / elapsed_time if elapsed_time > 0 else 0\n", + " est_total_time = elapsed_time / progress if progress > 1e-6 else float('inf')\n", + " est_remaining_time = max(0, est_total_time - elapsed_time) if est_total_time != float('inf') else float('inf')\n", + " est_remaining_str = f\"{est_remaining_time:.1f}s\" if est_remaining_time != float('inf') else \"N/A\"\n", + "\n", + " print(f\"\\r进度: {pairs_processed:,}/{total_pairs:,} 对 ({progress:.2%}) | \"\n", + " f\"已添加行数: {lines_added:,} | \"\n", + " f\"速度: {pairs_per_sec:.1f} 对/秒 | \"\n", + " f\"耗时: {elapsed_time:.1f}s | \"\n", + " f\"预计剩余: {est_remaining_str}\", end=\"\")\n", + "\n", + " print() # 结束进度报告行后换行\n", + " generation_successful = True # 标记生成过程完成(即使有小的错误跳过)\n", + "\n", + " except IOError as e:\n", + " print(f\"\\n打开或写入文件 '{filename}' 时发生 IO 错误: {e}\")\n", + " traceback.print_exc()\n", + " except Exception as e:\n", + " print(f\"\\n生成过程中发生未知错误: {e}\")\n", + " traceback.print_exc()\n", + " finally:\n", + " end_time = time.time()\n", + " total_time = end_time - start_time\n", + " print(\"\\n--- 生成阶段完成 ---\") # 改为阶段完成\n", + " if generation_successful:\n", + " print(f\"成功处理数字对数量: {pairs_processed:,}\")\n", + " print(f\"成功追加到文件的总行数: {lines_added:,}\")\n", + " print(f\"生成耗时: {total_time:.2f} 秒\")\n", + " if lines_added != total_lines_expected:\n", + " print(f\"警告: 实际添加行数 ({lines_added:,}) 与预期行数 ({total_lines_expected:,}) 不符。\")\n", + " else:\n", + " print(\"生成过程因错误提前中止。\")\n", + "\n", + " # 返回生成是否基本成功以及添加的行数,用于主程序判断是否需要后处理\n", + " return generation_successful, lines_added\n", + "\n", + "\n", + "def remove_trailing_newline(filename: str):\n", + " \"\"\"\n", + " 如果文件存在且末尾是换行符,则移除它。\n", + "\n", + " Args:\n", + " filename (str): 要处理的文件名。\n", + " \"\"\"\n", + " if not os.path.exists(filename):\n", + " print(f\"文件 '{filename}' 不存在,无法移除末尾换行符。\")\n", + " return\n", + "\n", + " try:\n", + " # 使用二进制读写模式 ('rb+') 以精确操作字节\n", + " with open(filename, 'rb+') as f:\n", + " # 移动到文件末尾\n", + " f.seek(0, os.SEEK_END)\n", + "\n", + " # 检查文件是否为空\n", + " if f.tell() == 0:\n", + " # print(f\"文件 '{filename}' 为空,无需操作。\") # 可以取消注释以查看此信息\n", + " return\n", + "\n", + " # 移动到最后一个字节之前的位置\n", + " f.seek(-1, os.SEEK_END)\n", + " # 读取最后一个字节\n", + " last_byte = f.read(1)\n", + "\n", + " # 如果最后一个字节是换行符 (b'\\n')\n", + " if last_byte == b'\\n':\n", + " # 截断文件,移除最后一个字节\n", + " f.seek(-1, os.SEEK_END) # 定位到换行符的位置\n", + " f.truncate() # 从当前位置截断\n", + " print(f\"信息: 已移除文件 '{filename}' 末尾的换行符。\")\n", + " # else:\n", + " # print(f\"信息: 文件 '{filename}' 末尾不是换行符,未作修改。\") # 可以取消注释以查看此信息\n", + "\n", + " except IOError as e:\n", + " print(f\"\\n错误: 处理文件 '{filename}' 末尾时发生 IO 错误: {e}\")\n", + " traceback.print_exc()\n", + " except Exception as e:\n", + " print(f\"\\n错误: 处理文件 '{filename}' 末尾时发生未知错误: {e}\")\n", + " traceback.print_exc()\n", + "\n", + "# ===============================================\n", + "# 主程序入口\n", + "# ===============================================\n", + "if __name__ == \"__main__\":\n", + " script_start_time = time.time()\n", + " print(\"=\"*30)\n", + " print(\" 全排列加减法数据追加脚本 \")\n", + " print(\"=\"*30)\n", + "\n", + " initial_file_exists = os.path.exists(TARGET_JSONL_FILE)\n", + " initial_file_size = os.path.getsize(TARGET_JSONL_FILE) if initial_file_exists else 0\n", + "\n", + " if not initial_file_exists:\n", + " print(f\"信息: 目标文件 '{TARGET_JSONL_FILE}' 不存在,将创建新文件��\")\n", + " else:\n", + " print(f\"信息: 目标文件 '{TARGET_JSONL_FILE}' 已存在,将在其后追加数据。\")\n", + " # (之前的检查文件末尾空行的逻辑可以移除或保留,看你是否关心追加前的文件状态)\n", + "\n", + " # 执行生成过程\n", + " success, added_lines = generate_pairwise_arithmetic(\n", + " filename=TARGET_JSONL_FILE,\n", + " min_num=MIN_NUMBER,\n", + " max_num=MAX_NUMBER\n", + " )\n", + "\n", + " # --- 后处理:移除末尾换行符 ---\n", + " # 仅在生成过程成功且确实添加了内容 或 文件原本就存在且非空时执行\n", + " # 避免在一个空的或生成失败的文件上执行\n", + " current_file_exists = os.path.exists(TARGET_JSONL_FILE)\n", + " if current_file_exists and (added_lines > 0 or (initial_file_exists and initial_file_size > 0)):\n", + " if success: # 确保生成过程没有在中途崩溃\n", + " print(\"\\n--- 开始后处理:移除末尾换行符 ---\")\n", + " remove_trailing_newline(TARGET_JSONL_FILE)\n", + " else:\n", + " print(\"\\n--- 跳过后处理:生成过程未成功完成 ---\")\n", + " elif not current_file_exists:\n", + " print(\"\\n--- 跳过后处理:目标文件不存在 ---\")\n", + " else: # 文件存在但大小为0(可能是新创建的空文件或原有的空文件且未添加内容)\n", + " print(\"\\n--- 跳过后处理:目标文件为空 ---\")\n", + "\n", + "\n", + " script_end_time = time.time()\n", + " print(\"\\n\" + \"=\"*30)\n", + " print(f\"脚本执行完毕。总耗时: {script_end_time - script_start_time:.2f} 秒。\")\n", + " print(f\"请检查文件: {TARGET_JSONL_FILE}\")\n", + " print(\"=\"*30)" + ] + }, + { + "cell_type": "markdown", + "id": "6c83b542", + "metadata": {}, + "source": [ + "# 在指定范围内,随机生成指定数量\n", + "跟上面的类似,但是不是全部的两两组合\n", + "- 添加了选择是否仅生成不进/退位数据的功能\n", + "\n", + "用于生成:\n", + "\n", + "测试集:ADD_base_test" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "93a6f0e0", + "metadata": {}, + "outputs": [], + "source": [ + "# -*- coding: utf-8 -*-\n", + "# v2.0.1: Corrected BUFFER_WRITE_SIZE scoping issue.\n", + "# Generates a specified number of unique arithmetic problems (add/sub)\n", + "# within a range, using diverse English/Arabic number formats and random casing.\n", + "# Appends to a target JSONL file.\n", + "\n", + "import json\n", + "import time\n", + "import os\n", + "import traceback\n", + "import random\n", + "import math \n", + "from decimal import Decimal, getcontext, ROUND_DOWN, ROUND_HALF_UP, InvalidOperation\n", + "\n", + "# ===============================================\n", + "# 配置参数区域\n", + "# ===============================================\n", + "TARGET_JSONL_FILE = \"ADD_en_base_test.jsonl\" # Updated filename\n", + "NUM_SAMPLES_TO_GENERATE = 500 \n", + "BUFFER_WRITE_SIZE = 10000 # Defined at module level, will be passed as param\n", + "\n", + "MIN_NUMBER_VAL = -999 \n", + "MAX_NUMBER_VAL = 999 \n", + "\n", + "STANDARD_ARABIC_PROB_V2: float = 0.40 \n", + "FULL_WIDTH_ARABIC_PROB_V2: float = 0.20 \n", + "ENGLISH_WORDS_PROB_V2: float = 0.40 \n", + "_format_prob_sum_v2 = (STANDARD_ARABIC_PROB_V2 + FULL_WIDTH_ARABIC_PROB_V2 + ENGLISH_WORDS_PROB_V2)\n", + "if not math.isclose(_format_prob_sum_v2, 1.0):\n", + " raise ValueError(f\"数字格式概率总和必须为 1.0,当前为: {_format_prob_sum_v2}\")\n", + "\n", + "ENGLISH_NUMBER_ENTIRE_STRING_CASE_PROB_V2: float = 0.8 \n", + "SYMBOLIC_OPERATOR_WORD_PROB_V2: float = 0.5 \n", + "ZERO_SPACE_PROB_V2: float = 0.8\n", + "MAX_RANDOM_SPACES_V2: int = 1 \n", + "\n", + "ENGLISH_QUESTION_PROMPTS_V2: list[str] = [\n", + " \" = ?\", \" equals what?\", \", what is the result?\", \", solve this.\", \" = what?\"\n", + "]\n", + "REPORT_INTERVAL_V2 = 1000 \n", + "# ===============================================\n", + "\n", + "_ENGLISH_DIGITS_V2 = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"]\n", + "_ENGLISH_TEENS_V2 = [\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\n", + "_ENGLISH_TENS_V2 = [\"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\n", + "_ENGLISH_LARGE_UNITS_V2 = [\"\", \"thousand\", \"million\", \"billion\", \"trillion\"] \n", + "\n", + "def _num_to_english_chunk_v2(n: int) -> str: \n", + " if not 0 <= n <= 999: return \"\"\n", + " if n == 0: return \"\"\n", + " parts = []\n", + " if n >= 100:\n", + " parts.append(_ENGLISH_DIGITS_V2[n // 100])\n", + " parts.append(\"hundred\")\n", + " n %= 100\n", + " if n > 0:\n", + " if 0 < n < 10: parts.append(_ENGLISH_DIGITS_V2[n])\n", + " elif 10 <= n < 20: parts.append(_ENGLISH_TEENS_V2[n - 10])\n", + " else:\n", + " parts.append(_ENGLISH_TENS_V2[n // 10])\n", + " if n % 10 > 0: parts.append(_ENGLISH_DIGITS_V2[n % 10])\n", + " return \" \".join(parts)\n", + "\n", + "def integer_to_english_words_v2(num: int) -> str:\n", + " if num == 0: return _ENGLISH_DIGITS_V2[0]\n", + " if abs(num) > (10**(len(_ENGLISH_LARGE_UNITS_V2) * 3) -1) :\n", + " return str(num) \n", + " sign = \"minus \" if num < 0 else \"\" \n", + " num_abs = abs(num)\n", + " parts = []\n", + " chunk_index = 0\n", + " if num_abs == 0: return _ENGLISH_DIGITS_V2[0] \n", + " temp_num = num_abs\n", + " while temp_num > 0:\n", + " if temp_num % 1000 != 0:\n", + " chunk_words = _num_to_english_chunk_v2(temp_num % 1000)\n", + " unit_word = _ENGLISH_LARGE_UNITS_V2[chunk_index] if chunk_index > 0 else \"\"\n", + " if unit_word: parts.append(unit_word)\n", + " if chunk_words: parts.append(chunk_words) \n", + " temp_num //= 1000\n", + " chunk_index += 1\n", + " if chunk_index >= len(_ENGLISH_LARGE_UNITS_V2) and temp_num > 0:\n", + " return str(num_abs) \n", + " result_words = \" \".join(p for p in reversed(parts) if p).strip() \n", + " return (sign + result_words).strip()\n", + "\n", + "def _apply_random_word_case_style_v2(word: str) -> str:\n", + " if not word or not any(c.isalpha() for c in word): return word\n", + " style_choice = random.random()\n", + " if style_choice < 0.4: return word.lower()\n", + " elif style_choice < 0.8: return word.upper()\n", + " else: return word.capitalize()\n", + "\n", + "def _apply_independent_word_casing_v2(text: str) -> str:\n", + " if not text or not any(c.isalpha() for c in text): return text\n", + " words = text.split(' ')\n", + " cased_words = [_apply_random_word_case_style_v2(word) for word in words]\n", + " return \" \".join(cased_words)\n", + "\n", + "def _apply_random_case_char_by_char_v2(text: str) -> str:\n", + " if not text or not any(c.isalpha() for c in text): return text\n", + " return \"\".join(random.choice([char.lower(), char.upper()]) if char.isalpha() else char for char in text)\n", + "\n", + "def _apply_random_case_number_style_v2(text: str) -> str: \n", + " if not text or not any(c.isalpha() for c in text): return text\n", + " if random.random() < ENGLISH_NUMBER_ENTIRE_STRING_CASE_PROB_V2:\n", + " return _apply_independent_word_casing_v2(text) \n", + " else:\n", + " return _apply_random_case_char_by_char_v2(text)\n", + "\n", + "def _apply_random_case_operator_style_v2(text: str) -> str:\n", + " if not text or not any(c.isalpha() for c in text): return text\n", + " return _apply_independent_word_casing_v2(text) \n", + "\n", + "_half_to_full_map_v2 = str.maketrans(\"0123456789+-=\", \"0123456789+-=\") \n", + "def to_full_width_v2(text: str) -> str: return text.translate(_half_to_full_map_v2)\n", + "\n", + "def format_number_for_question_v2(num: int) -> str:\n", + " fmt_choice_roll = random.random()\n", + " s_num = str(num)\n", + " if fmt_choice_roll < STANDARD_ARABIC_PROB_V2:\n", + " return s_num\n", + " elif fmt_choice_roll < STANDARD_ARABIC_PROB_V2 + FULL_WIDTH_ARABIC_PROB_V2:\n", + " return to_full_width_v2(s_num)\n", + " else: \n", + " raw_english = integer_to_english_words_v2(num)\n", + " if raw_english == s_num: \n", + " return s_num \n", + " return _apply_random_case_number_style_v2(raw_english)\n", + "\n", + "def get_random_spacing_v2() -> str:\n", + " if random.random() < ZERO_SPACE_PROB_V2: return \"\"\n", + " else: return \" \" * random.randint(1, MAX_RANDOM_SPACES_V2)\n", + "\n", + "\n", + "def generate_random_arithmetic_v2(filename: str, num_samples: int, min_val: int, max_val: int, buffer_size: int): # Added buffer_size parameter\n", + " print(f\"--- Starting generation of {num_samples:,} random arithmetic problems ---\")\n", + " print(f\"Number range: [{min_val}, {max_val}]\")\n", + " print(f\"Outputting to: {filename}\")\n", + " print(f\"Buffer write size for this run: {buffer_size:,}\")\n", + "\n", + "\n", + " if min_val > max_val:\n", + " print(\"Error: Min value cannot be greater than max value.\")\n", + " return False, 0 # Indicate failure\n", + " if num_samples <= 0:\n", + " print(\"Error: Number of samples to generate must be positive.\")\n", + " return False, 0 # Indicate failure\n", + "\n", + " range_size = max_val - min_val + 1\n", + " max_unique_problems = range_size * range_size * 2 \n", + " if num_samples > max_unique_problems:\n", + " print(f\"Warning: Requested {num_samples:,} samples, but only {max_unique_problems:,} unique problems possible in this range.\")\n", + " print(f\"Will generate up to {max_unique_problems:,} unique problems.\")\n", + " num_samples = max_unique_problems\n", + " \n", + " generated_problems = set()\n", + " lines_to_write_buffer = [] \n", + " lines_added_session = 0\n", + " \n", + " start_time = time.time()\n", + " attempts = 0\n", + " max_attempts = num_samples * 20 # Increased max_attempts factor for smaller ranges or larger sample requests\n", + " if range_size < 100 and num_samples > max_unique_problems * 0.5: # If range is small and many samples needed\n", + " max_attempts = num_samples * 50 # Allow even more attempts\n", + "\n", + " while len(generated_problems) < num_samples and attempts < max_attempts:\n", + " attempts += 1\n", + " a = random.randint(min_val, max_val)\n", + " b = random.randint(min_val, max_val)\n", + " op_type = random.choice(['add', 'subtract'])\n", + " \n", + " problem_signature = (a, b, op_type)\n", + " if problem_signature in generated_problems:\n", + " continue \n", + "\n", + " fmt_a = format_number_for_question_v2(a)\n", + " fmt_b = format_number_for_question_v2(b)\n", + "\n", + " result = 0\n", + " op_symbol_display = \"\"\n", + " \n", + " if op_type == 'add':\n", + " result = a + b\n", + " if random.random() < SYMBOLIC_OPERATOR_WORD_PROB_V2:\n", + " op_symbol_display = _apply_random_case_operator_style_v2(random.choice([\"plus\", \"add\"]))\n", + " else:\n", + " op_symbol_display = \"+\"\n", + " else: \n", + " result = a - b\n", + " if random.random() < SYMBOLIC_OPERATOR_WORD_PROB_V2:\n", + " op_symbol_display = _apply_random_case_operator_style_v2(random.choice([\"minus\", \"subtract\"]))\n", + " else:\n", + " op_symbol_display = \"-\"\n", + " \n", + " equals_display = \"=\"\n", + " if random.random() < SYMBOLIC_OPERATOR_WORD_PROB_V2 * 0.5: \n", + " equals_display = _apply_random_case_operator_style_v2(\"equals\")\n", + "\n", + " s1 = get_random_spacing_v2(); s2 = get_random_spacing_v2(); s3 = get_random_spacing_v2()\n", + " \n", + " question_parts = [fmt_a, s1, op_symbol_display, s2, fmt_b]\n", + " \n", + " base_question_str = \"\".join(question_parts)\n", + " question_str = base_question_str # Default if no prompt\n", + " if ENGLISH_QUESTION_PROMPTS_V2:\n", + " raw_prompt = random.choice(ENGLISH_QUESTION_PROMPTS_V2)\n", + " cased_prompt_part = _apply_random_case_operator_style_v2(raw_prompt.replace('=', '').strip())\n", + " \n", + " # Construct prompt carefully with equals sign\n", + " if raw_prompt.strip().startswith(\"=\"): # Prompt is like \" = ?\"\n", + " final_prompt = equals_display + get_random_spacing_v2() + cased_prompt_part\n", + " else: # Prompt is like \", solve this\"\n", + " final_prompt = get_random_spacing_v2() + cased_prompt_part # Add space before comma\n", + " # Prepend equals if not already part of the question via word operator\n", + " if equals_display == \"=\" and \"=\" not in op_symbol_display: # if equals is symbol and op is symbol\n", + " final_prompt = s3 + equals_display + final_prompt\n", + " elif equals_display != \"=\": # if equals is a word, it should be there\n", + " final_prompt = s3 + equals_display + final_prompt\n", + "\n", + "\n", + " question_str = base_question_str + final_prompt\n", + " else: # No prompts, ensure equals is there\n", + " question_str = base_question_str + s3 + equals_display + get_random_spacing_v2() + \"?\"\n", + "\n", + "\n", + " answer_str = str(result) \n", + " text_content = f\"User: {question_str}\\n\\nAssistant: {answer_str}\"\n", + " \n", + " try:\n", + " data = {\"text\": text_content}\n", + " json_line = json.dumps(data, ensure_ascii=False)\n", + " lines_to_write_buffer.append(json_line)\n", + " generated_problems.add(problem_signature)\n", + " lines_added_session +=1\n", + "\n", + " if len(lines_to_write_buffer) >= buffer_size: # Use parameter here\n", + " with open(filename, 'a', encoding='utf-8') as f:\n", + " for line in lines_to_write_buffer:\n", + " f.write(line + '\\n')\n", + " lines_to_write_buffer = []\n", + "\n", + " except Exception as e_json:\n", + " print(f\"\\nError processing/writing problem: a={a}, b={b}, op={op_type}. Error: {e_json}\")\n", + " continue \n", + "\n", + " current_generated_count = len(generated_problems)\n", + " if current_generated_count % REPORT_INTERVAL_V2 == 0 or current_generated_count == num_samples:\n", + " elapsed_time = time.time() - start_time\n", + " progress = current_generated_count / num_samples if num_samples > 0 else 0\n", + " samples_per_sec = current_generated_count / elapsed_time if elapsed_time > 0 else 0\n", + " est_total_time = elapsed_time / progress if progress > 1e-6 else float('inf')\n", + " est_remaining_time = max(0, est_total_time - elapsed_time) if est_total_time != float('inf') else float('inf')\n", + " est_remaining_str = f\"{est_remaining_time:.1f}s\" if est_remaining_time != float('inf') else \"N/A\"\n", + "\n", + " print(f\"\\rGenerated: {current_generated_count:,}/{num_samples:,} ({progress:.1%}) | \"\n", + " f\"Speed: {samples_per_sec:.1f} samples/s | \"\n", + " f\"Elapsed: {elapsed_time:.1f}s | \"\n", + " f\"ETA: {est_remaining_str} | Attempts: {attempts:,}\", end=\"\")\n", + "\n", + " if lines_to_write_buffer:\n", + " with open(filename, 'a', encoding='utf-8') as f:\n", + " for line in lines_to_write_buffer:\n", + " f.write(line + '\\n')\n", + "\n", + " print() \n", + " end_time = time.time(); total_time = end_time - start_time\n", + " \n", + " print(\"\\n--- Generation Phase Complete ---\")\n", + " final_generated_count = len(generated_problems)\n", + " print(f\"Successfully generated and wrote {final_generated_count:,} unique problems.\")\n", + " print(f\"Total attempts: {attempts:,}\")\n", + " print(f\"Total lines added this session: {lines_added_session:,}\")\n", + " print(f\"Generation time: {total_time:.2f} seconds.\")\n", + " \n", + " if final_generated_count < num_samples:\n", + " print(f\"Warning: Could only generate {final_generated_count:,} unique problems out of {num_samples:,} requested (max attempts: {max_attempts:,}).\")\n", + " \n", + " return True, lines_added_session\n", + "\n", + "\n", + "def remove_trailing_newline(filename: str):\n", + " if not os.path.exists(filename): return\n", + " try:\n", + " with open(filename, 'rb+') as f:\n", + " f.seek(0, os.SEEK_END)\n", + " if f.tell() == 0: return\n", + " f.seek(-1, os.SEEK_END); last_byte = f.read(1)\n", + " if last_byte == b'\\n': f.seek(-1, os.SEEK_END); f.truncate() \n", + " except IOError as e: print(f\"\\nError (IO) processing end of file '{filename}': {e}\"); traceback.print_exc()\n", + " except Exception as e: print(f\"\\nError (Unknown) processing end of file '{filename}': {e}\"); traceback.print_exc()\n", + "\n", + "# ===============================================\n", + "# 主程序入口\n", + "# ===============================================\n", + "if __name__ == \"__main__\":\n", + " script_start_time = time.time()\n", + " print(\"=\"*30); print(\" Random Arithmetic Problem Generation Script (v2.0.1) \"); print(\"=\"*30)\n", + "\n", + " initial_file_exists = os.path.exists(TARGET_JSONL_FILE)\n", + " initial_file_size = os.path.getsize(TARGET_JSONL_FILE) if initial_file_exists else 0\n", + "\n", + " if not initial_file_exists: print(f\"Info: Target file '{TARGET_JSONL_FILE}' does not exist, will be created.\")\n", + " else: print(f\"Info: Target file '{TARGET_JSONL_FILE}' exists, appending data.\")\n", + "\n", + " success, added_lines_session = generate_random_arithmetic_v2(\n", + " filename=TARGET_JSONL_FILE,\n", + " num_samples=NUM_SAMPLES_TO_GENERATE,\n", + " min_val=MIN_NUMBER_VAL,\n", + " max_val=MAX_NUMBER_VAL,\n", + " buffer_size=BUFFER_WRITE_SIZE # Pass the global config as parameter\n", + " )\n", + "\n", + " current_file_exists = os.path.exists(TARGET_JSONL_FILE)\n", + " if current_file_exists and (added_lines_session > 0 or (initial_file_exists and initial_file_size > 0)):\n", + " if success: \n", + " print(\"\\n--- Post-processing: Removing trailing newline if present ---\")\n", + " remove_trailing_newline(TARGET_JSONL_FILE)\n", + " else: print(\"\\n--- Skipping post-processing: Generation was not fully successful ---\")\n", + " elif not current_file_exists: print(\"\\n--- Skipping post-processing: Target file does not exist ---\")\n", + " else: print(\"\\n--- Skipping post-processing: Target file is empty ---\")\n", + "\n", + " script_end_time = time.time()\n", + " print(\"\\n\" + \"=\"*30)\n", + " print(f\"Script finished. Total execution time: {script_end_time - script_start_time:.2f} seconds.\")\n", + " print(f\"Data file: {TARGET_JSONL_FILE}\")\n", + " print(\"=\"*30)" + ] + }, + { + "cell_type": "markdown", + "id": "cae1a4ea", + "metadata": {}, + "source": [ + "# 在指定范围内,随机生成指定数量\n", + "跟上面的类似,但是不是全部的两两组合\n", + "- 添加了选择是否仅生成不进/退位数据的功能\n", + "\n", + "用于生成:\n", + "\n", + "测试集:ADD_base_test" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b2d53f83", + "metadata": {}, + "outputs": [], + "source": [ + "# -*- coding: utf-8 -*-\n", + "import json\n", + "import time\n", + "import os\n", + "import traceback\n", + "import random\n", + "\n", + "# ===============================================\n", + "# 配置参数区域\n", + "# ===============================================\n", + "# 要追加到的目标 JSONL 文件名 (请确保此文件存在或脚本有权限创建)\n", + "TARGET_JSONL_FILE = \"ADD_base_test.jsonl\" # Example name\n", + "\n", + "# 数字范围 (包含边界)\n", + "MIN_NUMBER = 0 # 调整为 >= 0 以便 \"no carry/borrow\" 有意义\n", + "MAX_NUMBER = 2000\n", + "\n", + "# 要生成的唯一问题数量\n", + "NUM_QUESTIONS_TO_GENERATE = 500\n", + "\n", + "# 是否只生成不进位/不退位的问题?\n", + "# True: 仅生成 a+b (a,b>=0, 无进位) 和 a-b (a>=b>=0, 无退位)\n", + "# False: 生成范围内的所有随机加减法\n", + "ONLY_NO_CARRY_BORROW = True\n", + "\n", + "# 控制进度报告的频率 (每生成 N 个问题报告一次)\n", + "REPORT_INTERVAL = 100\n", + "# ===============================================\n", + "\n", + "# --- Helper Functions for Carry/Borrow Check ---\n", + "\n", + "def check_carry(n1: int, n2: int) -> bool:\n", + " \"\"\"\n", + " 检查两个非负整数相加是否产生进位。\n", + " Args:\n", + " n1: 第一个非负整数。\n", + " n2: 第二个非负整数。\n", + " Returns:\n", + " True 如果有进位,False 如果没有。\n", + " \"\"\"\n", + " if n1 < 0 or n2 < 0: # 仅适用于非负数\n", + " return False # 或者抛出错误,根据定义决定\n", + " carry = 0\n", + " while n1 > 0 or n2 > 0:\n", + " digit1 = n1 % 10\n", + " digit2 = n2 % 10\n", + " digit_sum = digit1 + digit2 + carry\n", + " if digit_sum >= 10:\n", + " return True # 发现进位,立即返回\n", + " carry = digit_sum // 10 # 在这个严格检查下 carry 总是0,但保留逻辑\n", + " n1 //= 10\n", + " n2 //= 10\n", + " return False # 循环结束都没有进位\n", + "\n", + "def check_borrow(n1: int, n2: int) -> bool:\n", + " \"\"\"\n", + " 检查 n1 - n2 (n1 >= n2 >= 0) 是否产生借位。\n", + " Args:\n", + " n1: 被减数 (非负)。\n", + " n2: 减数 (非负, n2 <= n1)。\n", + " Returns:\n", + " True 如果有借位,False 如果没有。\n", + " \"\"\"\n", + " if not (n1 >= n2 >= 0): # 仅适用于 n1 >= n2 >= 0\n", + " return False # 或者抛出错误\n", + " borrow = 0\n", + " while n1 > 0 or n2 > 0: # 继续直到两个数都处理完\n", + " digit1 = n1 % 10\n", + " digit2 = n2 % 10\n", + "\n", + " # 执行减法,考虑上一位的借位\n", + " current_digit1 = digit1 - borrow\n", + " borrow = 0 # 重置当前位的借位需求\n", + "\n", + " if current_digit1 < digit2:\n", + " return True # 需要向前借位,立即返回\n", + "\n", + " # 不需要借位,正常计算\n", + " # diff = current_digit1 - digit2 # 实际结果不需要,只需检查是否借位\n", + "\n", + " n1 //= 10\n", + " n2 //= 10\n", + "\n", + " # 检查最高位是否需要借位 (理论上如果 n1>=n2 不会发生)\n", + " return borrow > 0 # 如果最后还需要借位说明有问题,但也算借位\n", + "\n", + "\n", + "def is_no_carry_addition(a: int, b: int) -> bool:\n", + " \"\"\"检查 a + b 是否为无进位加法 (仅限 a, b >= 0)\"\"\"\n", + " return a >= 0 and b >= 0 and not check_carry(a, b)\n", + "\n", + "def is_no_borrow_subtraction(a: int, b: int) -> bool:\n", + " \"\"\"检查 a - b 是否为无借位减法 (仅限 a >= b >= 0)\"\"\"\n", + " return a >= b >= 0 and not check_borrow(a, b)\n", + "\n", + "# --- Main Generation Function ---\n", + "\n", + "def generate_random_arithmetic_qapairs(\n", + " filename: str,\n", + " min_num: int,\n", + " max_num: int,\n", + " num_questions: int,\n", + " only_no_carry_borrow: bool = False):\n", + " \"\"\"\n", + " 在指定范围内随机生成指定数量的、不重复的加减法算术题,并追加到指定文件。\n", + " 可选地,只生成不进位/不退位的题目。\n", + " 如果无法生成足够数量的唯一问题,则报告错误。\n", + "\n", + " Args:\n", + " filename (str): 要追加数据到的 JSONL 文件名。\n", + " min_num (int): 范围的最小值 (包含)。\n", + " max_num (int): 范围的最大值 (包含)。\n", + " num_questions (int): 要生成的唯一问题的数量。\n", + " only_no_carry_borrow (bool): 如果为 True,则只生成满足条件的\n", + " 无进位加法 (a>=0, b>=0) 和\n", + " 无退位减法 (a>=b>=0)。\n", + "\n", + " Returns:\n", + " tuple: (bool, int) 第一个元素表示是否成功生成指定数量的问题,\n", + " 第二个元素是实际添加到文件的行数。\n", + " \"\"\"\n", + " print(f\"--- 开始生成 {num_questions:,} 个随机唯一加减法问题 ---\")\n", + " print(f\"范围: {min_num} 到 {max_num}\")\n", + " if only_no_carry_borrow:\n", + " print(\"约束: 仅生成无进位加法 (a,b>=0) / 无退位减法 (a>=b>=0)\")\n", + " # 对于此模式,强制要求范围至少包含非负数才有意义\n", + " if max_num < 0:\n", + " print(\"警告: 范围全是负数,无法生成无进位/退位问题。\")\n", + " # 可以直接返回错误,或者让它尝试直到超时\n", + " elif min_num < 0:\n", + " print(\"警告: 范围包含负数,但无进位/退位模式只会使用非负数部分。\")\n", + " # 实际可用范围缩小为 max(0, min_num) 到 max_num\n", + " effective_min = 0\n", + " effective_max = max_num\n", + " else:\n", + " effective_min = min_num\n", + " effective_max = max_num\n", + " # 粗略估计可能的无进位/退位问题数量 (非常粗略)\n", + " # 实际值会少很多,这里只是个概念\n", + " num_vals = effective_max - effective_min + 1\n", + " # 估算比全排列少得多,但难以精确计算\n", + " max_possible_approx = num_vals * num_vals # 极其粗略的上界估计\n", + " print(f\"可用非负数数量: {num_vals:,}\")\n", + " print(f\"(注意:无进位/退位的最大问题数远小于全排列,难以精确计算)\")\n", + " else:\n", + " print(\"约束: 无特殊约束 (允许进位/退位, 允许负数)\")\n", + " number_of_values = max_num - min_num + 1\n", + " max_possible_questions = number_of_values * number_of_values * 2\n", + " print(f\"数字范围内的数字数量: {number_of_values:,}\")\n", + " print(f\"理论上最大可生成的唯一问题数: {max_possible_questions:,}\")\n", + " if num_questions > max_possible_questions:\n", + " print(f\"错误: 无法生成 {num_questions:,} 个唯一问题,因为范围内最多只能生成 {max_possible_questions:,} 个。\")\n", + " return False, 0\n", + "\n", + " print(f\"将追加数据到文件: {filename}\")\n", + "\n", + " if min_num > max_num:\n", + " print(\"错误: 最小值不能大于最大值。\")\n", + " return False, 0\n", + " if num_questions <= 0:\n", + " print(\"错误: 要生成的问题数量必须大于 0。\")\n", + " return False, 0\n", + "\n", + " start_time = time.time()\n", + " lines_added = 0\n", + " generated_problems = set() # 使用集合来跟踪已生成的问题,确保唯一性\n", + "\n", + " generation_successful = False\n", + "\n", + " try:\n", + " with open(filename, 'a', encoding='utf-8') as f:\n", + " # 增加尝试次数上限,特别是对于约束模式\n", + " # 可以根据 only_no_carry_borrow 调整倍数\n", + " multiplier = 20 if only_no_carry_borrow else 10\n", + " max_attempts = num_questions * multiplier + 100000\n", + " attempts = 0\n", + "\n", + " while lines_added < num_questions and attempts < max_attempts:\n", + " attempts += 1\n", + " a = random.randint(min_num, max_num)\n", + " b = random.randint(min_num, max_num)\n", + " op_choice = random.choice(['+', '-'])\n", + "\n", + " # --- 应用无进位/退位约束 (如果启用) ---\n", + " if only_no_carry_borrow:\n", + " valid_for_constraint = False\n", + " if op_choice == '+':\n", + " if is_no_carry_addition(a, b):\n", + " valid_for_constraint = True\n", + " elif op_choice == '-':\n", + " if is_no_borrow_subtraction(a, b):\n", + " valid_for_constraint = True\n", + "\n", + " if not valid_for_constraint:\n", + " # 如果不满足无进位/退位条件,跳过这个组合,尝试下一个\n", + " continue\n", + " # --- 约束检查结束 ---\n", + "\n", + " # 创建唯一标识符\n", + " problem_id = (a, b, op_choice)\n", + "\n", + " # 检查是否已生成过\n", + " if problem_id not in generated_problems:\n", + " generated_problems.add(problem_id)\n", + "\n", + " # 生成问题和答案\n", + " if op_choice == '+':\n", + " result = a + b\n", + " question = f\"{a} + {b} = ?\"\n", + " else: # op_choice == '-'\n", + " result = a - b\n", + " question = f\"{a} - {b} = ?\"\n", + "\n", + " answer = str(result)\n", + " text_content = f\"User: {question}\\n\\nAssistant: {answer}\"\n", + " data = {\"text\": text_content}\n", + " json_line = json.dumps(data, ensure_ascii=False)\n", + "\n", + " # 写入文件\n", + " f.write(json_line + '\\n')\n", + " lines_added += 1\n", + "\n", + " # --- 进度报告 ---\n", + " if lines_added % REPORT_INTERVAL == 0 or lines_added == num_questions:\n", + " elapsed_time = time.time() - start_time\n", + " progress = lines_added / num_questions\n", + " qps = lines_added / elapsed_time if elapsed_time > 0 else 0\n", + " # 预估剩余时间在约束模式下可能非常不准,因为找到有效项的难度会增加\n", + " est_total_time = elapsed_time / progress if progress > 1e-6 else float('inf')\n", + " est_remaining_time = max(0, est_total_time - elapsed_time) if est_total_time != float('inf') else float('inf')\n", + " est_remaining_str = f\"{est_remaining_time:.1f}s\" if est_total_time != float('inf') else \"N/A\"\n", + " if only_no_carry_borrow and progress < 0.9: # 早期预估不准\n", + " est_remaining_str = \"~? s (约束模式预估难)\"\n", + "\n", + " print(f\"\\r进度: {lines_added:,}/{num_questions:,} ({progress:.2%}) | \"\n", + " f\"尝试次数: {attempts:,} | \"\n", + " f\"速度: {qps:.1f} 问题/秒 | \"\n", + " f\"耗时: {elapsed_time:.1f}s | \"\n", + " f\"预计剩余: {est_remaining_str}\", end=\"\")\n", + "\n", + " print() # 结束进度报告行后换行\n", + "\n", + " if lines_added < num_questions:\n", + " print(f\"\\n警告: 已尝试 {attempts:,} 次,但只生成了 {lines_added:,} / {num_questions:,} 个唯一问题。\")\n", + " if only_no_carry_borrow:\n", + " print(\"原因可能包括:范围/数量组合下满足无进位/退位条件的题目太少,或已接近饱和。\")\n", + " else:\n", + " print(\"原因可能包括:请求的数量非常接近理论最大值,或已接近饱和。\")\n", + " generation_successful = False\n", + " else:\n", + " generation_successful = True\n", + "\n", + " except IOError as e:\n", + " print(f\"\\n打开或写入文件 '{filename}' 时发生 IO 错误: {e}\")\n", + " traceback.print_exc()\n", + " generation_successful = False\n", + " except Exception as e:\n", + " print(f\"\\n生成过程中发生未知错误: {e}\")\n", + " traceback.print_exc()\n", + " generation_successful = False\n", + " finally:\n", + " end_time = time.time()\n", + " total_time = end_time - start_time\n", + " print(\"\\n--- 生成阶段完成 ---\")\n", + " if lines_added > 0:\n", + " print(f\"成功生成并追加到文件的唯一问题数: {lines_added:,}\")\n", + " print(f\"生成耗时: {total_time:.2f} 秒\")\n", + " if generation_successful:\n", + " print(f\"已成功达到目标数量 {num_questions:,}。\")\n", + " elif lines_added < num_questions:\n", + " # 只有在理论上可能但未达到时才打印这个特定警告\n", + " print(f\"警告: 未能生成所需的 {num_questions:,} 个问题 (实际生成 {lines_added:,})。\")\n", + "\n", + " return generation_successful, lines_added\n", + "\n", + "\n", + "# remove_trailing_newline 函数保持不变\n", + "def remove_trailing_newline(filename: str):\n", + " \"\"\"\n", + " 如果文件存在且末尾是换行符,则移除它。\n", + " \"\"\"\n", + " if not os.path.exists(filename):\n", + " # print(f\"文件 '{filename}' 不存在,无法移除末尾换行符。\") # 可以减少冗余信息\n", + " return\n", + " try:\n", + " with open(filename, 'rb+') as f:\n", + " f.seek(0, os.SEEK_END)\n", + " if f.tell() == 0: return\n", + " f.seek(-1, os.SEEK_END)\n", + " last_byte = f.read(1)\n", + " if last_byte == b'\\n':\n", + " f.seek(-1, os.SEEK_END)\n", + " f.truncate()\n", + " print(f\"信息: 已移除文件 '{filename}' 末尾的多余换行符。\")\n", + " except IOError as e:\n", + " print(f\"\\n错误: 处理文件 '{filename}' 末尾时发生 IO 错误: {e}\")\n", + " except Exception as e:\n", + " print(f\"\\n错误: 处理文件 '{filename}' 末尾时发生未知错误: {e}\")\n", + "\n", + "\n", + "# ===============================================\n", + "# 主程序入口\n", + "# ===============================================\n", + "if __name__ == \"__main__\":\n", + " script_start_time = time.time()\n", + " print(\"=\"*30)\n", + " print(\" 随机唯一加减法数据追加脚本 \")\n", + " print(f\"模式: {'仅无进位/退位' if ONLY_NO_CARRY_BORROW else '无限制'}\")\n", + " print(\"=\"*30)\n", + "\n", + " # --- 合理性检查 ---\n", + " if ONLY_NO_CARRY_BORROW and max(MIN_NUMBER, MAX_NUMBER) < 0:\n", + " print(\"错误配置: '仅无进位/退位' 模式要求数字范围至少包含 0 或正数。\")\n", + " print(\"当前范围: MIN_NUMBER={}, MAX_NUMBER={}\".format(MIN_NUMBER, MAX_NUMBER))\n", + " exit(1) # 提前退出\n", + "\n", + " initial_file_exists = os.path.exists(TARGET_JSONL_FILE)\n", + " initial_file_size = os.path.getsize(TARGET_JSONL_FILE) if initial_file_exists else 0\n", + "\n", + " if not initial_file_exists:\n", + " print(f\"信息: 目标文件 '{TARGET_JSONL_FILE}' 不存在,将创建新文件。\")\n", + " else:\n", + " print(f\"信息: 目标文件 '{TARGET_JSONL_FILE}' 已存在 ({initial_file_size} bytes),将在其后追加数据。\")\n", + "\n", + " # 执行生成过程\n", + " success, added_lines = generate_random_arithmetic_qapairs(\n", + " filename=TARGET_JSONL_FILE,\n", + " min_num=MIN_NUMBER,\n", + " max_num=MAX_NUMBER,\n", + " num_questions=NUM_QUESTIONS_TO_GENERATE,\n", + " only_no_carry_borrow=ONLY_NO_CARRY_BORROW # 传递新参数\n", + " )\n", + "\n", + " # --- 后处理:移除末尾换行符 ---\n", + " current_file_exists = os.path.exists(TARGET_JSONL_FILE)\n", + " if current_file_exists:\n", + " current_size = os.path.getsize(TARGET_JSONL_FILE)\n", + " if current_size > 0 :\n", + " print(\"\\n--- 开始后处理:检查并移除末尾换行符 ---\")\n", + " remove_trailing_newline(TARGET_JSONL_FILE)\n", + " else:\n", + " print(\"\\n--- 跳过后处理:目标文件为空 ---\")\n", + " # else: 文件不存在的情况已包含在生成失败的报告中\n", + "\n", + " script_end_time = time.time()\n", + " print(\"\\n\" + \"=\"*30)\n", + " if success:\n", + " print(f\"脚本成功执行,已生成并添加 {added_lines:,} / {NUM_QUESTIONS_TO_GENERATE:,} 个问题。\")\n", + " else:\n", + " print(f\"脚本执行完成,但未能生成所有要求的 {NUM_QUESTIONS_TO_GENERATE:,} 个问题 (实际添加 {added_lines:,})。\")\n", + " if added_lines == 0 and NUM_QUESTIONS_TO_GENERATE > 0:\n", + " print(\"可能的原因:\")\n", + " if ONLY_NO_CARRY_BORROW:\n", + " print(\"- 范围内满足无进位/退位条件的组合过少。\")\n", + " else:\n", + " print(\"- 范围过小无法满足数量要求。\")\n", + " print(\"- 发生文件写入错误。\")\n", + " print(\"- 尝试次数达到上限(尤其是在约束模式下)。\")\n", + " print(f\"约束模式: {'是' if ONLY_NO_CARRY_BORROW else '否'}\")\n", + " print(f\"总耗时: {script_end_time - script_start_time:.2f} 秒。\")\n", + " print(f\"请检查文件: {TARGET_JSONL_FILE}\")\n", + " print(\"=\"*30)" + ] + }, + { + "cell_type": "markdown", + "id": "3558f6de", + "metadata": {}, + "source": [ + "# 生成至少包含目标个数进位的\n", + "\n", + "这版本是先生成,后筛选,在设置要求进位较多时,效率极低,后面会有更好的版本。\n", + "\n", + "训练集:ADD_2M 和 ADD_4M\n", + "\n", + "测试集:ADD_test\n", + "\n", + "ADD_n{}_m{}系列也可用该版本,但n和m较大时,效率会下降" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "e30326c0", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "==============================\n", + " 算术题生成脚本 (v9) \n", + "==============================\n", + "提示: 目标最大总进/借位数 (inf) > 最大可能 (18)。\n", + "提示: 目标最大连续进/借位数 (inf) > 最大可能 (18)。\n", + "--- 开始生成算术数据 (v9 - Range Filter & Cleaned) ---\n", + "输出文件: qa_add_random_4M.jsonl\n", + "目标样本数: 4,000,000\n", + "批处理大小: 10,000\n", + "数字限制: Max整数位=12, Max小数位=5\n", + "概率: 加法=50.0%, 小数=15.0%, 负数=5.0%\n", + "进/借位范围: 总数=[0, inf], 连续=[0, inf]\n", + "问题格式: 数字格式随机(标:70.0%, 全:10.0%, 简:10.0%, 繁:10.0%), NL操作符概率=30.0%, 间距随机\n", + "答案格式: 标准阿拉伯数字 (无科学计数法)\n", + "其他: 进/借位增强概率=70.0%\n", + "已初始化/清空输出文件: 'qa_add_random_4M.jsonl'\n", + "\n", + "开始生成 4,000,000 条满足条件的数据...\n", + "进度: 4,000,000/4,000,000 (100.0%) | 写: 4,000,000 | 尝试: 4,461,784 (1.1/样本) | 22068.8 有效样本/秒 | 耗时:181.3s | 剩余:~0.0s \n", + "生成循环结束。目标: 4,000,000, 实际生成: 4,000,000 (尝试 4,461,784 次).\n", + "无剩余数据需写入。\n", + "\n", + "生成与写入完毕。目标: 4,000,000 -> 生成: 4,000,000 -> 写入: 4,000,000\n", + "总尝试次数: 4,461,784 (平均 1.12 次/有效样本)\n", + "总耗时: 181.25 秒。循环/写入错误: 461,784.\n", + "\n", + "=============== 详细统计 (基于生成的有效样本) ===============\n", + "总有效样本: 4,000,000\n", + "--------------------------------------------------\n", + "1. 算术题类型:\n", + " - 加法: 2,074,073 (51.9%)\n", + " - 减法: 1,925,927 (48.1%)\n", + "--------------------------------------------------\n", + "2. 运算数类型:\n", + " - 纯整数运算*: 3,332,296 (83.3%)\n", + " - 含小数运算*: 667,704 (16.7%)\n", + " *注: 基于输入或输出是否含小数部分。\n", + "--------------------------------------------------\n", + "3. 问题格式 - 操作数 A (总计: 4,000,000):\n", + " - standard : 2,799,997 ( 70.0%)\n", + " - full_width : 399,239 ( 10.0%)\n", + " - simple_zh : 400,133 ( 10.0%)\n", + " - complex_zh : 400,631 ( 10.0%)\n", + "--------------------------------------------------\n", + "4. 问题格式 - 操作数 B (总计: 4,000,000):\n", + " - standard : 2,800,015 ( 70.0%)\n", + " - full_width : 400,346 ( 10.0%)\n", + " - simple_zh : 400,061 ( 10.0%)\n", + " - complex_zh : 399,578 ( 10.0%)\n", + "--------------------------------------------------\n", + "5. 问题格式 - 操作符 (总计: 4,000,000):\n", + " - 符号 (+/-) : 2,847,966 ( 71.2%)\n", + " - 自然语言 (加/减) : 1,152,034 ( 28.8%)\n", + "--------------------------------------------------\n", + "6. 其他:\n", + " - 进/借位增强尝试 (占总循环比例): 3,124,139 (70.0%)\n", + "==================================================\n", + "\n", + "==============================\n", + "脚本执行完毕。总耗时: 181.25 秒。\n", + "数据文件: qa_add_random_4M.jsonl\n", + "==============================\n" + ] + } + ], + "source": [ + "# -*- coding: utf-8 -*-\n", + "# 生成满足指定进/借位范围条件,且问题格式多样化的算术问题数据集脚本。\n", + "# 问题格式: 数字(标准/全角/简中/繁中),操作符(符号/中文),间距随机。\n", + "# 答案格式: 标准阿拉伯数字 (无科学计数法)。\n", + "# 输出格式: {\"text\": \"User: <问题>\\n\\nAssistant: <答案>\"}\n", + "# v9: Implemented range-based carry/borrow filtering and cleaned up comments.\n", + "\n", + "import json\n", + "import random\n", + "import time\n", + "import math\n", + "from typing import List, Tuple, Union, Dict, Optional\n", + "from decimal import Decimal, getcontext, ROUND_DOWN, ROUND_HALF_UP, InvalidOperation\n", + "import traceback\n", + "from collections import Counter\n", + "\n", + "# ===============================================\n", + "# 配置参数区域\n", + "# ===============================================\n", + "# --- 主要数量和文件名 ---\n", + "TOTAL_SAMPLES = 4000000\n", + "OUTPUT_FILENAME = f\"qa_add_random_4M.jsonl\"\n", + "ADD_PROBABILITY: float = 0.5\n", + "BATCH_SAVE_SIZE: int = 10000\n", + "\n", + "# --- 数字生成控制 ---\n", + "MAX_DIGITS: int = 12 # 整数部分最大位数\n", + "MAX_DECIMAL_PLACES: int = 5 # 小数部分最大位数\n", + "DECIMAL_PROBABILITY: float = 0.15 # 生成小数问题的概率\n", + "NEGATIVE_POOL_PROB: float = 0.05 # 操作数为负的概率\n", + "\n", + "# --- 进/借位条件范围 ---\n", + "# 设置所需的总进/借位数范围 [min, max]\n", + "TARGET_TOTAL_CARRIES_MIN: int = 0\n", + "TARGET_TOTAL_CARRIES_MAX: int = math.inf # 设置为 math.inf 可表示无上限 (即至少 MIN)\n", + "\n", + "# 设置所需的连续进/借位数范围 [min, max]\n", + "TARGET_CONSECUTIVE_CARRIES_MIN: int = 0\n", + "TARGET_CONSECUTIVE_CARRIES_MAX: int = math.inf # 设置为 math.inf 可表示无上限 (即至少 MIN)\n", + "\n", + "# --- 格式化控制 (问题部分) ---\n", + "# -- 数字表示法概率 (总和应为 1.0) --\n", + "STANDARD_ARABIC_PROB: float = 0.70\n", + "FULL_WIDTH_ARABIC_PROB: float = 0.10\n", + "SIMPLE_CHINESE_PROB: float = 0.10\n", + "COMPLEX_CHINESE_PROB: float = 0.10\n", + "_format_prob_sum = STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB + SIMPLE_CHINESE_PROB + COMPLEX_CHINESE_PROB\n", + "if not math.isclose(_format_prob_sum, 1.0):\n", + " raise ValueError(f\"数字格式概率总和必须为 1.0,当前为: {_format_prob_sum}\")\n", + "\n", + "# -- 操作符格式控制 --\n", + "NL_OPERATOR_PROBABILITY: float = 0.30 # 使用 '加'/'减' 替代 '+','-' 的概率\n", + "NL_OPERATORS = {'+': '加', '-': '减'}\n", + "\n", + "# --- 其他控制 ---\n", + "CARRY_BORROW_BOOST_PROB: float = 0.70 # 尝试生成带进位/借位算术题的概率,以提高命中率\n", + "MAX_ATTEMPTS_FACTOR = 5000\n", + "\n", + "# ===============================================\n", + "# 核心代码\n", + "# ===============================================\n", + "\n", + "# --- 设置 Decimal 精度 ---\n", + "getcontext().prec = MAX_DIGITS + MAX_DECIMAL_PLACES + 30\n", + "\n", + "# --- 中文数字转换常量 ---\n", + "digit_map_simple = {'0': '零', '1': '一', '2': '二', '3': '三', '4': '四', '5': '五', '6': '六', '7': '七', '8': '八', '9': '九'}\n", + "unit_map_section_simple = ['', '十', '百', '千']\n", + "unit_map_large_simple = ['', '万', '亿', '兆']\n", + "digit_map_complex = {'0': '零', '1': '壹', '2': '贰', '3': '叁', '4': '肆', '5': '伍', '6': '陆', '7': '柒', '8': '捌', '9': '玖'}\n", + "unit_map_section_complex = ['', '拾', '佰', '仟']\n", + "unit_map_large_complex = ['', '萬', '億', '兆']\n", + "\n", + "# --- 中文数字转换函数 ---\n", + "def _convert_section(section_str: str, complex_form: bool = False) -> str:\n", + " digit_map = digit_map_complex if complex_form else digit_map_simple\n", + " unit_map_section = unit_map_section_complex if complex_form else unit_map_section_simple\n", + " if not section_str: return \"\"\n", + " try: section_int = int(section_str)\n", + " except ValueError: return \"无效输入\"\n", + " if section_int == 0: return digit_map['0']\n", + " chinese_s = \"\"; length = len(section_str); need_zero = False\n", + " for i in range(length):\n", + " digit = section_str[i]; place = length - 1 - i\n", + " if digit == '0': need_zero = True\n", + " else:\n", + " if need_zero and chinese_s and not chinese_s.endswith(digit_map['0']): chinese_s += digit_map['0']\n", + " need_zero = False; current_digit_chinese = \"\"\n", + " use_liang = False\n", + " if not complex_form and digit == '2': # \"二\" vs \"两\" 的处理\n", + " is_leading_two_and_high_place = (i == 0 and place >= 2) # e.g., 200, 2000\n", + " is_leading_two_in_ten = (i == 0 and place == 1 and length > 1) # e.g., 20 but not just 2\n", + " if (is_leading_two_and_high_place or is_leading_two_in_ten) and random.random() < 0.7:\n", + " current_digit_chinese = '两'\n", + " else:\n", + " current_digit_chinese = digit_map['2']\n", + " else: current_digit_chinese = digit_map[digit]\n", + "\n", + " is_leading_one_in_ten_place = (not complex_form and digit == '1' and place == 1 and i == 0 and length > 1)\n", + "\n", + " if is_leading_one_in_ten_place: # 处理 \"一十\" vs \"十\"\n", + " if length == 2: # 10-19\n", + " chinese_s += unit_map_section[place]\n", + " else: # e.g., 110, 1500\n", + " chinese_s += current_digit_chinese + unit_map_section[place]\n", + " else:\n", + " chinese_s += current_digit_chinese + unit_map_section[place]\n", + "\n", + " # 移除末尾的\"零\" (如果不是单个\"零\")\n", + " if chinese_s.endswith(digit_map['0']) and len(chinese_s) > len(digit_map['0']):\n", + " chinese_s = chinese_s[:-len(digit_map['0'])]\n", + " return chinese_s\n", + "\n", + "def num_to_chinese(num: int, complex_form: bool = False) -> str:\n", + " \"\"\"将整数转换为中文表示\"\"\"\n", + " if not isinstance(num, int): return \"无效输入\"\n", + " digit_map = digit_map_complex if complex_form else digit_map_simple\n", + " unit_map_large = unit_map_large_complex if complex_form else unit_map_large_simple\n", + " if num == 0: return digit_map['0']\n", + " if num < 0: return (\"负\" if not complex_form else \"负\") + num_to_chinese(abs(num), complex_form)\n", + "\n", + " s_num = str(num)\n", + " # 限制输入大小防止超长输出或性能问题\n", + " if len(s_num) > 50: return \"数字过大无法转换\"\n", + "\n", + " result = \"\"; sections = []\n", + " while len(s_num) > 0: sections.append(s_num[-4:]); s_num = s_num[:-4]\n", + " zero_padding_needed = False; last_section_was_zero = True\n", + "\n", + " for i in range(len(sections) - 1, -1, -1):\n", + " section_str = sections[i]\n", + " try: section_int = int(section_str)\n", + " except ValueError: return \"无效输入\"\n", + "\n", + " if section_int == 0:\n", + " if not last_section_was_zero: zero_padding_needed = True # 需要补零,如果前一个节非零\n", + " last_section_was_zero = True\n", + " continue # 跳过全零的节\n", + "\n", + " # 处理节之间的零\n", + " if zero_padding_needed and not last_section_was_zero:\n", + " result += digit_map['0']\n", + " zero_padding_needed = False # 零已添加\n", + "\n", + " section_chinese = _convert_section(section_str, complex_form)\n", + " if not section_chinese or section_chinese == \"无效输入\": return \"无效输入\"\n", + "\n", + " result += section_chinese\n", + " last_section_was_zero = False\n", + "\n", + " # 添加大的单位 (万, 亿, 兆)\n", + " if i > 0 and section_int != 0: # 只有非零节才添加大单位\n", + " result += unit_map_large[i]\n", + "\n", + " # 特殊处理:\"一十\" 开头简化为 \"十\" (仅简写)\n", + " if not complex_form and result.startswith(digit_map['1'] + unit_map_section_simple[1]): # '一十'\n", + " result = result[1:]\n", + "\n", + " return result\n", + "\n", + "def decimal_to_chinese(num: Decimal, complex_form: bool = False) -> str:\n", + " \"\"\"将 Decimal 转换为中文表示,包括小数\"\"\"\n", + " if not isinstance(num, Decimal): return \"无效输入\"\n", + " if not num.is_finite(): return \"无效输入\" # 处理 NaN, Infinity\n", + "\n", + " digit_map = digit_map_complex if complex_form else digit_map_simple\n", + " point_word = \"点\"\n", + "\n", + " try:\n", + " # 检查是否为整数\n", + " is_integer = (num == num.to_integral_value(rounding=ROUND_DOWN))\n", + " except Exception:\n", + " is_integer = False # 如果检查出错,则认为不是整数\n", + "\n", + " if is_integer:\n", + " try:\n", + " int_val = num.to_integral_value(rounding=ROUND_DOWN)\n", + " # 对整数部分的大小进行限制\n", + " if abs(int_val).adjusted() >= 50: return \"数字过大无法转换\"\n", + " return num_to_chinese(int(int_val), complex_form)\n", + " except (ValueError, TypeError, OverflowError, InvalidOperation):\n", + " return \"无效输入或溢出\"\n", + "\n", + " # 处理负数\n", + " if num < 0:\n", + " return (\"负\" if not complex_form else \"负\") + decimal_to_chinese(abs(num), complex_form)\n", + "\n", + " try:\n", + " # 使用 {:f} 格式化以避免科学计数法,并 normalize 去除末尾0\n", + " s_num = \"{:f}\".format(num.normalize())\n", + " except Exception:\n", + " return \"无效输入\"\n", + "\n", + " # 分离整数和小数部分\n", + " if '.' not in s_num: # normalize 后可能变回整数形式\n", + " try:\n", + " int_val_dec = Decimal(s_num)\n", + " if abs(int_val_dec).adjusted() >= 50: return \"数字过大无法转换\"\n", + " return num_to_chinese(int(int_val_dec), complex_form)\n", + " except (ValueError, TypeError, OverflowError, InvalidOperation):\n", + " return \"无效输入或溢出\"\n", + "\n", + " integer_part_str, fractional_part_str = s_num.split('.')\n", + " if not integer_part_str: integer_part_str = '0' # 处理如 \".5\" 的情况\n", + "\n", + " # 转换整数部分\n", + " try:\n", + " int_val_dec = Decimal(integer_part_str)\n", + " if abs(int_val_dec).adjusted() >= 50: return \"数字过大无法转换\"\n", + " chinese_int = num_to_chinese(int(int_val_dec), complex_form)\n", + " if chinese_int == \"无效输入\": return \"无效输入\"\n", + " except (ValueError, TypeError, OverflowError, InvalidOperation):\n", + " return \"无效输入或溢出\"\n", + "\n", + " # 转换小数部分\n", + " chinese_frac = \"\".join(digit_map.get(digit, '?') for digit in fractional_part_str)\n", + "\n", + " # 组合结果\n", + " if chinese_int == digit_map['0'] and chinese_frac: # 例如 0.5 -> 零点五\n", + " return f\"{digit_map['0']}{point_word}{chinese_frac}\"\n", + " elif chinese_frac: # 例如 1.2 -> 一点二\n", + " return f\"{chinese_int}{point_word}{chinese_frac}\"\n", + " else: # 理论上已由 is_integer 处理,作为后备\n", + " return chinese_int\n", + "\n", + "# --- 全角转换 ---\n", + "half_to_full_map = str.maketrans(\"0123456789.-+\", \"0123456789.-+\")\n", + "def to_full_width(text: str) -> str:\n", + " return text.translate(half_to_full_map)\n", + "\n", + "# --- 格式化数字变体 ---\n", + "def format_number_variant(num: Union[int, Decimal]) -> Tuple[str, str]:\n", + " \"\"\"根据概率将数字格式化为不同变体,返回格式化后的字符串和使用的格式名称\"\"\"\n", + " fmt_choice = random.random()\n", + " try:\n", + " num_dec = Decimal(str(num)) if not isinstance(num, Decimal) else num\n", + " except InvalidOperation:\n", + " return str(num), 'standard' # 无法转换则返回标准格式\n", + "\n", + " target_format = 'complex_zh' # 默认,对应最后一个概率区间\n", + " if fmt_choice < STANDARD_ARABIC_PROB:\n", + " target_format = 'standard'\n", + " elif fmt_choice < STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB:\n", + " target_format = 'full_width'\n", + " elif fmt_choice < STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB + SIMPLE_CHINESE_PROB:\n", + " target_format = 'simple_zh'\n", + "\n", + " try:\n", + " if not num_dec.is_finite(): # 处理 NaN, Infinity\n", + " s_num = str(num_dec)\n", + " return (to_full_width(s_num), 'full_width') if target_format == 'full_width' else (s_num, 'standard')\n", + "\n", + " # 获取标准的非科学计数法字符串\n", + " s_formatted = format_decimal_or_int(num_dec)\n", + "\n", + " if target_format == 'standard':\n", + " return s_formatted, 'standard'\n", + " elif target_format == 'full_width':\n", + " return to_full_width(s_formatted), 'full_width'\n", + " elif target_format == 'simple_zh':\n", + " result = decimal_to_chinese(num_dec, complex_form=False)\n", + " if result in [\"无效输入\", \"无效输入或溢出\", \"数字过大无法转换\"]:\n", + " return s_formatted, 'standard' # 转换失败则回退\n", + " return result, 'simple_zh'\n", + " else: # complex_zh\n", + " result = decimal_to_chinese(num_dec, complex_form=True)\n", + " if result in [\"无效输入\", \"无效输入或溢出\", \"数字过大无法转换\"]:\n", + " return s_formatted, 'standard' # 转换失败则回退\n", + " return result, 'complex_zh'\n", + " except Exception:\n", + " # 捕获其他意外错误,回退到标准格式\n", + " try: fallback_str = format_decimal_or_int(num)\n", + " except: fallback_str = str(num)\n", + " return fallback_str, 'standard'\n", + "\n", + "# --- 获取随机间距 ---\n", + "def get_realistic_spacing() -> str:\n", + " \"\"\"模拟打字习惯,生成随机长度的空格\"\"\"\n", + " space_options = [(\"\", 98), (\" \", 1), (\" \", 0.5), (\" \", 0.5)]\n", + " values = [opt[0] for opt in space_options]; weights = [opt[1] for opt in space_options]\n", + " try: return random.choices(values, weights=weights, k=1)[0]\n", + " except: return \"\"\n", + "\n", + "# --- 检查是否包含阿拉伯数字 ---\n", + "def contains_arabic_numerals(s: str) -> bool:\n", + " return any(c in \"01234567890123456789\" for c in s)\n", + "\n", + "# --- 辅助函数: 格式化 Decimal 或 int 为字符串 (确保无科学计数法) ---\n", + "def format_decimal_or_int(num: Union[int, Decimal]) -> str:\n", + " \"\"\"将整数或 Decimal 格式化为标准字符串,确保答案无科学计数法\"\"\"\n", + " try:\n", + " if isinstance(num, int):\n", + " return str(num)\n", + " if isinstance(num, Decimal):\n", + " if not num.is_finite(): return str(num) # NaN, Infinity\n", + "\n", + " normalized_num = num.normalize() # 去除尾随零\n", + "\n", + " if normalized_num.as_tuple().exponent >= 0: # 是整数\n", + " return str(normalized_num.to_integral_value())\n", + " else: # 是小数\n", + " s = \"{:f}\".format(normalized_num) # 强制定点表示法\n", + " if '.' in s: s = s.rstrip('0').rstrip('.') # 移除多余的零和小数点\n", + " return s\n", + " return str(num) # 其他类型\n", + " except Exception:\n", + " return str(num) # 出错时回退\n", + "\n", + "# --- 辅助函数: 根据概率分布选择 ---\n", + "def get_distributed_count_from_probs(population: List[int], probabilities: List[float]) -> int:\n", + " \"\"\"根据提供的概率分布从总体中选择一个元素\"\"\"\n", + " if not population: return 1\n", + " if not probabilities or len(population) != len(probabilities) or not all(p >= 0 for p in probabilities):\n", + " return random.choice(population) # 无效概率则随机选\n", + "\n", + " prob_sum = sum(probabilities)\n", + " if prob_sum < 1e-9: return random.choice(population) # 概率和过小则随机选\n", + "\n", + " normalized_probabilities = probabilities\n", + " if not math.isclose(prob_sum, 1.0, abs_tol=1e-5): # 归一化概率\n", + " try: normalized_probabilities = [p / prob_sum for p in probabilities]\n", + " except ZeroDivisionError: return random.choice(population)\n", + "\n", + " try: return random.choices(population, weights=normalized_probabilities, k=1)[0]\n", + " except Exception: return random.choice(population) # 选择时出错则随机选\n", + "\n", + "# --- 辅助函数: 计算位数概率分布 ---\n", + "def calculate_digit_probabilities(max_digits: int) -> Dict[int, float]:\n", + " \"\"\"为整数位数生成一个倾向于较少位数的概率分布\"\"\"\n", + " if max_digits <= 0: return {1: 1.0}\n", + " raw_probs = {}; prob_sum = Decimal('0.0'); base_prob = Decimal('0.1'); decay_factor = Decimal('0.95'); increase_factor = Decimal('1.05')\n", + "\n", + " # 生成原始概率,位数越多概率越低 (大致)\n", + " for n in range(1, max_digits + 1):\n", + " prob = base_prob * (decay_factor**(n - 1)) * (increase_factor**(max_digits - n + 1)) # 调整因子使长短位数都有机会\n", + " prob = max(Decimal('0.01'), prob) # 保证最低概率\n", + " raw_probs[n] = prob\n", + " prob_sum += prob\n", + "\n", + " # 归一化概率\n", + " normalized_probs = {}\n", + " if prob_sum <= 0: # 容错处理\n", + " fallback_prob = 1.0 / max(1, max_digits)\n", + " normalized_probs = {n: fallback_prob for n in range(1, max_digits + 1)}\n", + " else:\n", + " normalized_probs = {n: float(p / prob_sum) for n, p in raw_probs.items()}\n", + "\n", + " # 再次检查并强制归一化 (处理浮点数精度问题)\n", + " final_sum = sum(normalized_probs.values())\n", + " if not math.isclose(final_sum, 1.0, abs_tol=1e-9):\n", + " renorm_factor = 1.0 / final_sum if final_sum != 0 else 1.0\n", + " total = 0.0; keys = sorted(normalized_probs.keys())\n", + " for i, n in enumerate(keys):\n", + " if i == len(keys) - 1: normalized_probs[n] = max(0.0, 1.0 - total) # 最后一个补齐\n", + " else: normalized_probs[n] = max(0.0, normalized_probs[n] * renorm_factor); total += normalized_probs[n]\n", + "\n", + " return normalized_probs\n", + "\n", + "# --- 辅助函数: 生成指定位数的正整数 ---\n", + "def _generate_positive_integer_with_digits(num_digits: int) -> int:\n", + " if num_digits <= 0: num_digits = 1\n", + " if num_digits == 1: min_val, max_val = 0, 9\n", + " else: min_val = 10**(num_digits - 1); max_val = 10**num_digits - 1\n", + " if min_val > max_val: return max_val # 理论上不应发生\n", + " try: return random.randint(min_val, max_val)\n", + " except ValueError: return max_val # 极端情况回退\n", + "\n", + "# --- 辅助函数: 生成一对数字 (考虑进位偏置) ---\n", + "def _generate_number_pair(target_digits_a: int, target_digits_b: int, sign_a: int, sign_b: int,\n", + " is_decimal: bool, max_decimal_places: int,\n", + " operation_type: str, use_bias: bool) -> Tuple[Union[int, Decimal], Union[int, Decimal]]:\n", + " \"\"\"生成一对数字,可选地偏向于产生进位/借位\"\"\"\n", + " int_digits_a = max(1, target_digits_a); int_digits_b = max(1, target_digits_b)\n", + " num_decimal_places = random.randint(1, max_decimal_places) if is_decimal and max_decimal_places > 0 else 0\n", + " a_int_val: Decimal; b_int_val: Decimal\n", + "\n", + " # 生成整数部分 (可选偏置)\n", + " if use_bias: # 尝试逐位生成以增加进/借位概率\n", + " a_int_str = \"\"; b_int_str = \"\"\n", + " max_len = max(int_digits_a, int_digits_b)\n", + " for i in range(max_len):\n", + " place_value = max_len - 1 - i\n", + " is_part_of_a = (i >= max_len - int_digits_a); is_part_of_b = (i >= max_len - int_digits_b)\n", + " is_leading_digit_a = (i == max_len - int_digits_a); is_leading_digit_b = (i == max_len - int_digits_b)\n", + " min_da = 1 if is_leading_digit_a and int_digits_a > 1 else 0; max_da = 9 if is_part_of_a else 0\n", + " min_db = 1 if is_leading_digit_b and int_digits_b > 1 else 0; max_db = 9 if is_part_of_b else 0\n", + " digit_a = 0; digit_b = 0\n", + "\n", + " # 对低位增加强制产生进/借位的尝试\n", + " force_carry_borrow = (place_value < 3 and random.random() < 0.8) and is_part_of_a and is_part_of_b\n", + " eff_op = operation_type # 判断实际运算是加还是减 (考虑符号)\n", + " if operation_type == 'add' and sign_a * sign_b < 0: eff_op = 'subtract'\n", + " elif operation_type == 'subtract' and sign_a * sign_b < 0: eff_op = 'add'\n", + "\n", + " if force_carry_borrow:\n", + " attempts = 0\n", + " while attempts < 10:\n", + " da = random.randint(min_da, max_da) if is_part_of_a else 0\n", + " db = random.randint(min_db, max_db) if is_part_of_b else 0\n", + " carry = (eff_op == 'add' and da + db >= 10)\n", + " borrow = (eff_op == 'subtract' and da < db)\n", + " if carry or borrow: digit_a, digit_b = da, db; break\n", + " attempts += 1\n", + " else: # 尝试失败则随机生成\n", + " digit_a = random.randint(min_da, max_da) if is_part_of_a else 0\n", + " digit_b = random.randint(min_db, max_db) if is_part_of_b else 0\n", + " else: # 不强制则随机生成\n", + " digit_a = random.randint(min_da, max_da) if is_part_of_a else 0\n", + " digit_b = random.randint(min_db, max_db) if is_part_of_b else 0\n", + " a_int_str += str(digit_a); b_int_str += str(digit_b)\n", + " a_int_val = Decimal(a_int_str.lstrip('0') or '0')\n", + " b_int_val = Decimal(b_int_str.lstrip('0') or '0')\n", + " else: # 不使用偏置,直接生成整数\n", + " a_int = _generate_positive_integer_with_digits(int_digits_a)\n", + " b_int = _generate_positive_integer_with_digits(int_digits_b)\n", + " a_int_val = Decimal(a_int); b_int_val = Decimal(b_int)\n", + "\n", + " a_val = a_int_val; b_val = b_int_val\n", + "\n", + " # 生成小数部分 (可选偏置)\n", + " if num_decimal_places > 0:\n", + " frac_a = Decimal('0'); frac_b = Decimal('0')\n", + " try:\n", + " frac_a_int = random.randint(0, 10**num_decimal_places - 1)\n", + " frac_b_int = random.randint(0, 10**num_decimal_places - 1)\n", + " max_frac_val = 10**num_decimal_places - 1\n", + "\n", + " # 对小数部分也尝试增加进/借位概率\n", + " if use_bias and random.random() < 0.5:\n", + " eff_op = operation_type # 同样考虑符号后的实际运算\n", + " if operation_type == 'add' and sign_a * sign_b < 0: eff_op = 'subtract'\n", + " elif operation_type == 'subtract' and sign_a * sign_b < 0: eff_op = 'add'\n", + "\n", + " if eff_op == 'add': # 尝试使 frac_a + frac_b >= 1\n", + " needed = 10**num_decimal_places - frac_a_int\n", + " if 0 < needed <= max_frac_val + 1: # 确保目标值在范围内\n", + " lower_bound_add = needed; upper_bound_add = max_frac_val\n", + " if lower_bound_add <= upper_bound_add:\n", + " try: frac_b_int = random.randint(lower_bound_add, upper_bound_add)\n", + " except ValueError: pass # 范围无效则忽略\n", + " elif eff_op == 'subtract': # 尝试使 frac_a < frac_b\n", + " lower_bound_sub = frac_a_int + 1; upper_bound_sub = max_frac_val\n", + " if lower_bound_sub <= upper_bound_sub:\n", + " try: frac_b_int = random.randint(lower_bound_sub, upper_bound_sub)\n", + " except ValueError: pass # 范围无效则忽略\n", + "\n", + " scale = Decimal(10)**(-num_decimal_places)\n", + " frac_a = Decimal(frac_a_int) * scale\n", + " frac_b = Decimal(frac_b_int) * scale\n", + " except OverflowError: # 小数位数过多可能导致溢出\n", + " num_decimal_places = 0\n", + " print(f\"Warning: Overflow generating decimal part with {num_decimal_places} places. Generating integers instead.\")\n", + " a_val += frac_a; b_val += frac_b\n", + "\n", + " # 应用符号\n", + " final_a = a_val * sign_a; final_b = b_val * sign_b\n", + "\n", + " # 对结果进行量化和标准化\n", + " if is_decimal and num_decimal_places > 0:\n", + " try:\n", + " quantizer = Decimal('1e-' + str(num_decimal_places))\n", + " # 使用 ROUND_HALF_UP 进行四舍五入到目标小数位数\n", + " final_a = final_a.quantize(quantizer, rounding=ROUND_HALF_UP).normalize()\n", + " final_b = final_b.quantize(quantizer, rounding=ROUND_HALF_UP).normalize()\n", + " except InvalidOperation: pass # 量化错误则忽略\n", + " # 标准化 -0 为 0\n", + " if final_a.is_zero() and final_a.is_signed(): final_a = Decimal('0')\n", + " if final_b.is_zero() and final_b.is_signed(): final_b = Decimal('0')\n", + " elif not is_decimal: # 如果目标是整数,则取整\n", + " try:\n", + " final_a = int(final_a.to_integral_value(rounding=ROUND_DOWN)) # 向下取整符合一般预期\n", + " final_b = int(final_b.to_integral_value(rounding=ROUND_DOWN))\n", + " except (InvalidOperation, OverflowError, ValueError): # 取整失败则用原始整数部分\n", + " final_a = int(a_int_val) * sign_a if a_int_val != 0 else 0\n", + " final_b = int(b_int_val) * sign_b if b_int_val != 0 else 0\n", + "\n", + " # 避免意外生成 (0, 0) 对,这通常意义不大且不满足进位条件\n", + " zero_a = (final_a == 0) if isinstance(final_a, int) else final_a.is_zero()\n", + " zero_b = (final_b == 0) if isinstance(final_b, int) else final_b.is_zero()\n", + " if zero_a and zero_b and (target_digits_a > 1 or target_digits_b > 1 or num_decimal_places > 0):\n", + " # 如果生成了 (0,0) 且原始位数或小数位数大于预期,重试一次(不使用偏置)\n", + " return _generate_number_pair(target_digits_a, target_digits_b, sign_a, sign_b,\n", + " is_decimal, max_decimal_places, operation_type, False)\n", + " return final_a, final_b\n", + "\n", + "# --- 辅助函数: 检查进位/借位 ---\n", + "def check_carries_borrows(num1: Decimal, num2: Decimal, operation: str) -> Tuple[int, int]:\n", + " \"\"\"计算加法或减法中的总进/借位数和最大连续进/借位数\"\"\"\n", + " total_cb = 0; max_consecutive_cb = 0; current_consecutive_cb = 0\n", + " try:\n", + " # 1. 确定实际执行的操作 (加法或减法) 和操作数 (取绝对值)\n", + " effective_op = operation; op1: Decimal; op2: Decimal\n", + " if operation == 'add':\n", + " if num1.is_signed() != num2.is_signed(): # 异号相加 = 大数绝对值减小数绝对值\n", + " effective_op = 'subtract'\n", + " if abs(num1) >= abs(num2): op1, op2 = abs(num1), abs(num2)\n", + " else: op1, op2 = abs(num2), abs(num1)\n", + " else: # 同号相加 = 绝对值相加\n", + " op1, op2 = abs(num1), abs(num2)\n", + " elif operation == 'subtract':\n", + " if num1.is_signed() != num2.is_signed(): # 异号相减 = 绝对值相加\n", + " effective_op = 'add'\n", + " op1, op2 = abs(num1), abs(num2)\n", + " else: # 同号相减 = 大数绝对值减小数绝对值\n", + " effective_op = 'subtract'\n", + " if abs(num1) >= abs(num2): op1, op2 = abs(num1), abs(num2)\n", + " else: op1, op2 = abs(num2), abs(num1)\n", + " else: return -1, -1 # 无效操作\n", + "\n", + " if op1.is_zero() and op2.is_zero(): return 0, 0 # 0+/-0 没有进借位\n", + "\n", + " # 2. 将操作数转换为字符串并对齐\n", + " s1 = format_decimal_or_int(op1); s2 = format_decimal_or_int(op2)\n", + " s1_int, s1_frac = s1.split('.') if '.' in s1 else (s1, '')\n", + " s2_int, s2_frac = s2.split('.') if '.' in s2 else (s2, '')\n", + "\n", + " max_frac_len = max(len(s1_frac), len(s2_frac))\n", + " s1_frac = s1_frac.ljust(max_frac_len, '0'); s2_frac = s2_frac.ljust(max_frac_len, '0')\n", + " max_int_len = max(len(s1_int), len(s2_int))\n", + " s1_int = s1_int.zfill(max_int_len); s2_int = s2_int.zfill(max_int_len)\n", + "\n", + " aligned_s1 = s1_int + s1_frac; aligned_s2 = s2_int + s2_frac\n", + " full_len = len(aligned_s1)\n", + " carry = 0; borrow = 0 # 初始化进位和借位标志\n", + "\n", + " # 3. 从最低位开始逐位模拟计算\n", + " for i in range(full_len - 1, -1, -1):\n", + " try: d1 = int(aligned_s1[i]); d2 = int(aligned_s2[i])\n", + " except (IndexError, ValueError): return -1, -1 # 对齐或转换失败\n", + "\n", + " cb_occurred = False # 本位是否发生进/借位\n", + " if effective_op == 'add':\n", + " current_sum = d1 + d2 + carry # 当前位和 + 低位进位\n", + " if current_sum >= 10: carry = 1; cb_occurred = True # 产生新的进位\n", + " else: carry = 0; cb_occurred = False\n", + " else: # subtract\n", + " current_diff = d1 - borrow - d2 # 当前位差 - 低位借位\n", + " if current_diff < 0: borrow = 1; cb_occurred = True # 产生新的借位\n", + " else: borrow = 0; cb_occurred = False\n", + "\n", + " # 更新统计\n", + " if cb_occurred:\n", + " total_cb += 1; current_consecutive_cb += 1\n", + " else:\n", + " max_consecutive_cb = max(max_consecutive_cb, current_consecutive_cb) # 连续中断\n", + " current_consecutive_cb = 0\n", + "\n", + " # 加法最高位可能还有进位\n", + " if effective_op == 'add' and carry > 0:\n", + " total_cb += 1; current_consecutive_cb += 1\n", + "\n", + " # 最终更新最大连续计数\n", + " max_consecutive_cb = max(max_consecutive_cb, current_consecutive_cb)\n", + " except Exception:\n", + " # print(f\"Error in check_carries_borrows({num1}, {num2}, {operation}): {e}\")\n", + " # traceback.print_exc()\n", + " return -1, -1 # 发生任何错误返回-1\n", + "\n", + " return total_cb, max_consecutive_cb\n", + "\n", + "# --- 批量写入函数 ---\n", + "def write_batch_to_jsonl(buffer: List[Dict], filename: str, mode: str = 'a') -> int:\n", + " \"\"\"将缓冲区数据以 JSONL 格式写入文件,确保每行一个 JSON 对象\"\"\"\n", + " if not buffer: return 0\n", + " lines_written = 0; json_lines_to_write = []; serialization_errors = 0\n", + " for item in buffer:\n", + " try:\n", + " if not item or not isinstance(item, dict) or not item.get(\"text\"): # 跳过无效项\n", + " serialization_errors += 1; continue\n", + " json_string = json.dumps(item, ensure_ascii=False)\n", + " if json_string and not json_string.isspace(): # 跳过空输出\n", + " json_lines_to_write.append(json_string)\n", + " else: serialization_errors += 1\n", + " except Exception: serialization_errors += 1\n", + "\n", + " if json_lines_to_write:\n", + " try:\n", + " with open(filename, mode, encoding='utf-8') as f:\n", + " # 使用 '\\n' 连接并在末尾加 '\\n',符合 JSONL 标准\n", + " output_string = '\\n'.join(json_lines_to_write) + '\\n'\n", + " f.write(output_string)\n", + " lines_written = len(json_lines_to_write)\n", + " except IOError as e:\n", + " print(f\"\\n写入文件 '{filename}' 时 IO 错误: {e}\"); return 0\n", + " except Exception as e:\n", + " print(f\"\\n写入文件时未知错误: {e}\"); return 0\n", + "\n", + " if serialization_errors > 0: print(f\"\\n警告: 写入批次时 {serialization_errors} 个项目处理失败。\")\n", + " return lines_written\n", + "\n", + "\n", + "# --- 主要生成函数 ---\n", + "def generate_filtered_arithmetic_diverse(\n", + " filename: str, total_samples: int, add_prob: float, decimal_prob: float,\n", + " max_digits_limit: int, max_decimal_places: int, negative_pool_prob: float,\n", + " carry_borrow_boost_prob: float,\n", + " target_total_cb_min: int, target_total_cb_max: Union[int, float], # 使用新范围参数\n", + " target_consecutive_cb_min: int, target_consecutive_cb_max: Union[int, float], # 使用新范围参数\n", + " nl_operator_prob: float,\n", + " max_attempts_factor: int,\n", + " batch_save_size: int):\n", + " \"\"\"生成满足指定进/借位范围条件且格式多样化的算术问题数据\"\"\"\n", + "\n", + " # --- 0. 参数验证和准备 ---\n", + " if total_samples <= 0: print(\"警告:total_samples 必须大于 0。\"); return\n", + " if target_total_cb_min < 0 or target_consecutive_cb_min < 0: raise ValueError(\"最小进/借位条件数不能为负。\")\n", + " # 检查范围有效性\n", + " if target_total_cb_max < target_total_cb_min: raise ValueError(f\"总进/借位范围无效: MAX({target_total_cb_max}) < MIN({target_total_cb_min})\")\n", + " if target_consecutive_cb_max < target_consecutive_cb_min: raise ValueError(f\"连续进/借位范围无效: MAX({target_consecutive_cb_max}) < MIN({target_consecutive_cb_min})\")\n", + "\n", + " if batch_save_size <= 0: batch_save_size = 10000\n", + "\n", + " max_possible_cb = max_digits_limit + max_decimal_places + 1 # 理论最大进/借位数\n", + " # 更新警告信息以反映范围\n", + " if target_total_cb_min > max_possible_cb: print(f\"警告: 目标最小总进/借位数 ({target_total_cb_min}) > 最大可能 ({max_possible_cb})。可能无法生成。\")\n", + " if target_consecutive_cb_min > max_possible_cb: print(f\"警告: 目标最小连续进/借位数 ({target_consecutive_cb_min}) > 最大可能 ({max_possible_cb})。可能无法生成。\")\n", + " # 如果上限也超出理论最大值,也给个提示 (但不一定是错误)\n", + " if target_total_cb_max > max_possible_cb: print(f\"提示: 目标最大总进/借位数 ({target_total_cb_max}) > 最大可能 ({max_possible_cb})。\")\n", + " if target_consecutive_cb_max > max_possible_cb: print(f\"提示: 目标最大连续进/借位数 ({target_consecutive_cb_max}) > 最大可能 ({max_possible_cb})。\")\n", + "\n", + "\n", + " # --- 打印配置信息 ---\n", + " print(f\"--- 开始生成算术数据 (v9 - Range Filter & Cleaned) ---\")\n", + " print(f\"输出文件: {filename}\")\n", + " print(f\"目标样本数: {total_samples:,}\")\n", + " print(f\"批处理大小: {batch_save_size:,}\")\n", + " print(f\"数字限制: Max整数位={max_digits_limit}, Max小数位={max_decimal_places}\")\n", + " print(f\"概率: 加法={add_prob:.1%}, 小数={decimal_prob:.1%}, 负数={negative_pool_prob:.1%}\")\n", + " # 打印范围条件\n", + " total_max_str = \"inf\" if target_total_cb_max == math.inf else str(target_total_cb_max)\n", + " consec_max_str = \"inf\" if target_consecutive_cb_max == math.inf else str(target_consecutive_cb_max)\n", + " print(f\"进/借位范围: 总数=[{target_total_cb_min}, {total_max_str}], 连续=[{target_consecutive_cb_min}, {consec_max_str}]\")\n", + " print(f\"问题格式: 数字格式随机(标:{STANDARD_ARABIC_PROB:.1%}, 全:{FULL_WIDTH_ARABIC_PROB:.1%}, 简:{SIMPLE_CHINESE_PROB:.1%}, 繁:{COMPLEX_CHINESE_PROB:.1%}), NL操作符概率={nl_operator_prob:.1%}, 间距随机\")\n", + " print(f\"答案格式: 标准阿拉伯数字 (无科学计数法)\")\n", + " print(f\"其他: 进/借位增强概率={carry_borrow_boost_prob:.1%}\")\n", + "\n", + " # --- 计算位数分布 ---\n", + " digit_pop: List[int] = []; digit_probs_list: List[float] = []\n", + " if max_digits_limit > 0:\n", + " digit_probabilities_dict = calculate_digit_probabilities(max_digits_limit)\n", + " digit_pop = list(range(1, max_digits_limit + 1)); digit_probs_list = [digit_probabilities_dict.get(n, 0.0) for n in digit_pop]\n", + " if not digit_probs_list: digit_pop = [1]; digit_probs_list = [1.0]\n", + " else: digit_pop = [1]; digit_probs_list = [1.0]\n", + "\n", + " # --- 初始化计数器 ---\n", + " generated_count = 0; total_attempts = 0; total_lines_written = 0\n", + " add_count = 0; subtract_count = 0\n", + " integer_op_count = 0; decimal_op_count = 0\n", + " format_counts = Counter() # 操作数格式统计\n", + " operator_format_counts = Counter() # 操作符格式统计\n", + " boosted_carry_borrow_attempts = 0; errors_in_loop = 0\n", + " max_total_attempts = total_samples * max(100, max_attempts_factor)\n", + " start_time_generate = time.time()\n", + " output_buffer = []\n", + " last_reported_count = -1\n", + " last_save_time = start_time_generate\n", + "\n", + " # --- 初始化输出文件 ---\n", + " try:\n", + " with open(filename, 'w', encoding='utf-8') as f: f.write(\"\")\n", + " print(f\"已初始化/清空输出文件: '{filename}'\")\n", + " except IOError as e: print(f\"\\n错误:无法初始化输出文件 '{filename}': {e}\"); return\n", + "\n", + " print(f\"\\n开始生成 {total_samples:,} 条满足条件的数据...\")\n", + "\n", + " # --- 主生成循环 ---\n", + " while generated_count < total_samples:\n", + " total_attempts += 1\n", + " if total_attempts > max_total_attempts:\n", + " print(f\"\\n\\n警告: 尝试次数达到上限 ({total_attempts:,})。\")\n", + " print(f\"当前已生成: {generated_count:,} 条,已写入: {total_lines_written:,} 条。\")\n", + " print(\"脚本提前终止。\")\n", + " break\n", + "\n", + " data = None\n", + " try:\n", + " # --- 生成核心数据 ---\n", + " digits_a = get_distributed_count_from_probs(digit_pop, digit_probs_list)\n", + " digits_b = get_distributed_count_from_probs(digit_pop, digit_probs_list)\n", + " sign_a = -1 if random.random() < negative_pool_prob else 1\n", + " sign_b = -1 if random.random() < negative_pool_prob else 1\n", + " is_dec_intent = random.random() < decimal_prob\n", + " op_type = 'add' if random.random() < add_prob else 'subtract'\n", + " op_sym = '+' if op_type == 'add' else '-'\n", + " a: Union[int, Decimal]; b: Union[int, Decimal]\n", + " gen_biased = random.random() < carry_borrow_boost_prob\n", + " if gen_biased: boosted_carry_borrow_attempts += 1\n", + " a, b = _generate_number_pair(digits_a, digits_b, sign_a, sign_b, is_dec_intent, max_decimal_places, op_type, gen_biased)\n", + "\n", + " # --- 计算结果 c ---\n", + " c_final: Union[int, Decimal]; answer_str = \"\"\n", + " try:\n", + " a_calc = Decimal(str(a)) if not isinstance(a, Decimal) else a\n", + " b_calc = Decimal(str(b)) if not isinstance(b, Decimal) else b\n", + " if not a_calc.is_finite() or not b_calc.is_finite(): errors_in_loop += 1; continue\n", + " c_calc = a_calc + b_calc if op_type == 'add' else a_calc - b_calc\n", + " if not c_calc.is_finite(): errors_in_loop += 1; continue\n", + "\n", + " result_decimal_places = 0 # 确定结果小数位数\n", + " for num_in in [a, b]:\n", + " if isinstance(num_in, Decimal):\n", + " exp = num_in.normalize().as_tuple().exponent\n", + " if isinstance(exp, int) and exp < 0:\n", + " result_decimal_places = max(result_decimal_places, abs(exp))\n", + " result_decimal_places = min(result_decimal_places, max_decimal_places)\n", + "\n", + " # 量化和标准化结果\n", + " if result_decimal_places > 0:\n", + " quantizer = Decimal('1e-' + str(result_decimal_places))\n", + " c_final_dec = c_calc.quantize(quantizer, rounding=ROUND_HALF_UP)\n", + " else:\n", + " c_final_dec = c_calc.to_integral_value(rounding=ROUND_HALF_UP)\n", + " c_final_dec = c_final_dec.normalize()\n", + " if c_final_dec.is_zero() and c_final_dec.is_signed(): c_final_dec = Decimal('0')\n", + " c_final = c_final_dec\n", + " answer_str = format_decimal_or_int(c_final) # 格式化答案\n", + "\n", + " except (InvalidOperation, OverflowError, ArithmeticError): errors_in_loop += 1; continue\n", + " except Exception: errors_in_loop += 1; continue\n", + " if not answer_str: errors_in_loop += 1; continue\n", + "\n", + " # --- 检查进/借位条件 ---\n", + " try:\n", + " a_dec_check = Decimal(str(a)) if not isinstance(a, Decimal) else a\n", + " b_dec_check = Decimal(str(b)) if not isinstance(b, Decimal) else b\n", + " if not a_dec_check.is_finite() or not b_dec_check.is_finite(): errors_in_loop += 1; continue\n", + " actual_total_cb, actual_max_consecutive_cb = check_carries_borrows(a_dec_check, b_dec_check, op_type)\n", + " if actual_total_cb == -1: errors_in_loop += 1; continue # 检查出错\n", + " except Exception: errors_in_loop += 1; continue\n", + "\n", + " # --- 应用范围过滤器 ---\n", + " total_cb_ok = (target_total_cb_min <= actual_total_cb <= target_total_cb_max)\n", + " consecutive_cb_ok = (target_consecutive_cb_min <= actual_max_consecutive_cb <= target_consecutive_cb_max)\n", + "\n", + " if total_cb_ok and consecutive_cb_ok:\n", + " # --- 条件满足,进行格式化和统计 ---\n", + " try:\n", + " fmt_a_str, fmt_a_type = format_number_variant(a)\n", + " final_op_sym = op_sym; fmt_b_str = \"\"; fmt_b_type = \"\"\n", + "\n", + " # 处理负数 b 和格式化\n", + " try:\n", + " b_dec_val = Decimal(str(b)) if not isinstance(b, Decimal) else b\n", + " if b_dec_val.is_signed() and b_dec_val < 0:\n", + " fmt_b_abs_str, fmt_b_abs_type = format_number_variant(abs(b_dec_val))\n", + " fmt_b_str = fmt_b_abs_str; fmt_b_type = fmt_b_abs_type\n", + " if op_sym == '+': final_op_sym = '-'\n", + " elif op_sym == '-': final_op_sym = '+'\n", + " else:\n", + " fmt_b_str, fmt_b_type = format_number_variant(b)\n", + " except (InvalidOperation, TypeError):\n", + " fmt_b_str, fmt_b_type = format_number_variant(b) # Fallback\n", + "\n", + " # 检查格式化是否成功\n", + " if fmt_a_type == 'error' or fmt_b_type == 'error' or \\\n", + " fmt_a_str in [\"无效输入\", \"无效输入或溢出\", \"数字过大无法转换\"] or \\\n", + " fmt_b_str in [\"无效输入\", \"无效输入或溢出\", \"数字过大无法转换\"]:\n", + " errors_in_loop += 1; continue\n", + "\n", + " # 更新格式统计\n", + " format_counts[f'a_{fmt_a_type}'] += 1\n", + " format_counts[f'b_{fmt_b_type}'] += 1\n", + "\n", + " # 确定操作符格式\n", + " chosen_op_symbol = final_op_sym\n", + " use_nl_operator = False\n", + " a_is_arabic = contains_arabic_numerals(fmt_a_str)\n", + " b_is_arabic = contains_arabic_numerals(fmt_b_str)\n", + " if (a_is_arabic or b_is_arabic) and random.random() < nl_operator_prob:\n", + " nl_op = NL_OPERATORS.get(final_op_sym)\n", + " if nl_op: chosen_op_symbol = nl_op; use_nl_operator = True\n", + "\n", + " # 更新操作符统计\n", + " operator_format_counts['natural_language' if use_nl_operator else 'symbol'] += 1\n", + "\n", + " # 构建问题和最终数据\n", + " s1 = get_realistic_spacing(); s2 = get_realistic_spacing()\n", + " question_str = f\"{fmt_a_str}{s1}{chosen_op_symbol}{s2}{fmt_b_str}\"\n", + " if not question_str or question_str.isspace(): errors_in_loop += 1; continue\n", + "\n", + " text_content = f\"User: {question_str}\\n\\nAssistant: {answer_str}\"\n", + " data = {\"text\": text_content}\n", + "\n", + " # 更新其他统计\n", + " generated_count += 1\n", + " if op_type == 'add': add_count += 1\n", + " else: subtract_count += 1\n", + " is_a_dec_final = isinstance(a, Decimal) and a != a.to_integral_value(rounding=ROUND_DOWN)\n", + " is_b_dec_final = isinstance(b, Decimal) and b != b.to_integral_value(rounding=ROUND_DOWN)\n", + " is_c_dec_final = c_final != c_final.to_integral_value(rounding=ROUND_DOWN)\n", + " if is_a_dec_final or is_b_dec_final or is_c_dec_final: decimal_op_count += 1\n", + " else: integer_op_count += 1\n", + "\n", + " output_buffer.append(data)\n", + "\n", + " # 批量保存逻辑\n", + " if generated_count % batch_save_size == 0 and output_buffer:\n", + " write_start_time = time.time()\n", + " written_count = write_batch_to_jsonl(output_buffer, filename, mode='a')\n", + " write_duration = time.time() - write_start_time\n", + " if written_count > 0:\n", + " total_lines_written += written_count\n", + " avg_save_speed = written_count / write_duration if write_duration > 0 else float('inf')\n", + " print(f\"\\r--- Saved batch {written_count:,} ({avg_save_speed:.1f}/s). Total written: {total_lines_written:,} / Gen: {generated_count:,} ---{' '*10}\", end=\"\")\n", + " output_buffer.clear()\n", + " last_save_time = time.time()\n", + " else:\n", + " print(f\"\\n警告: 写入批处理失败 (gen_count={generated_count:,})。 Buffer cleared.\")\n", + " errors_in_loop += len(output_buffer); output_buffer.clear()\n", + "\n", + " except Exception: errors_in_loop += 1; continue # 格式化阶段出错\n", + "\n", + " except KeyboardInterrupt: print(\"\\nInterrupted.\"); break\n", + " except Exception: errors_in_loop += 1; continue # 主循环内错误\n", + "\n", + " # --- 进度报告 ---\n", + " report_interval = max(1, total_samples // 200) if total_samples > 0 else 1\n", + " now = time.time()\n", + " time_since_last_event = now - max(last_save_time, start_time_generate)\n", + " if generated_count > 0 and (generated_count % report_interval == 0 or generated_count == total_samples or time_since_last_event > 15):\n", + " if last_reported_count != generated_count:\n", + " progress = generated_count / total_samples if total_samples > 0 else 0\n", + " elapsed_time = now - start_time_generate\n", + " samples_per_sec = generated_count / elapsed_time if elapsed_time > 0 else 0\n", + " attempts_per_sample = total_attempts / generated_count if generated_count > 0 else float('inf')\n", + " est_rem_str = \"N/A\"\n", + " if progress > 1e-6 and samples_per_sec > 0 and attempts_per_sample < float('inf'):\n", + " est_rem_gen = (total_samples - generated_count) / samples_per_sec if samples_per_sec > 0 else float('inf')\n", + " if est_rem_gen < 1e6 : est_rem_str = f\"{est_rem_gen:.1f}s\"\n", + "\n", + " print(f\"\\r进度: {generated_count:,}/{total_samples:,} ({progress:.1%}) | 写: {total_lines_written:,} | 尝试: {total_attempts:,} ({attempts_per_sample:.1f}/样本) | {samples_per_sec:.1f} 有效样本/秒 | 耗时:{elapsed_time:.1f}s | 剩余:~{est_rem_str} \", end=\"\")\n", + " last_reported_count = generated_count\n", + " if time_since_last_event > 15: last_save_time = now # Update last event time for timeout check\n", + "\n", + "\n", + " # --- 循环结束后 ---\n", + " print(\" \" * 150, end=\"\\r\") # 清除进度条\n", + " print(f\"\\n生成循环结束。目标: {total_samples:,}, 实际生成: {generated_count:,} (尝试 {total_attempts:,} 次).\")\n", + "\n", + " # --- 写入剩余数据 ---\n", + " if output_buffer:\n", + " print(f\"写入最后 {len(output_buffer):,} 条数据...\")\n", + " write_start = time.time()\n", + " final_written = write_batch_to_jsonl(output_buffer, filename, mode='a')\n", + " write_end = time.time()\n", + " if final_written > 0:\n", + " total_lines_written += final_written\n", + " print(f\"最终批次写入完成 ({final_written:,} 条). 耗时: {write_end - write_start:.2f}s.\")\n", + " else:\n", + " print(\"警告: 最终批次写入失败。\")\n", + " errors_in_loop += len(output_buffer)\n", + " output_buffer.clear()\n", + " else:\n", + " print(\"无剩余数据需写入。\")\n", + "\n", + " # --- 结束日志和统计 ---\n", + " end_generate = time.time(); total_gen_time = end_generate - start_time_generate\n", + " print(f\"\\n生成与写入完毕。目标: {total_samples:,} -> 生成: {generated_count:,} -> 写入: {total_lines_written:,}\")\n", + " if total_lines_written != generated_count and generated_count > 0:\n", + " print(f\"警告: 写入行数({total_lines_written:,}) 与 生成数({generated_count:,}) 不匹配!\")\n", + "\n", + " attempts_per_actual = total_attempts / max(1, generated_count) if generated_count > 0 else float('inf')\n", + " print(f\"总尝试次数: {total_attempts:,} (平均 {attempts_per_actual:.2f} 次/有效样本)\")\n", + " print(f\"总耗时: {total_gen_time:.2f} 秒。循环/写入错误: {errors_in_loop:,}.\")\n", + "\n", + " # --- 打印详细统计 ---\n", + " print(\"\\n\" + \"=\"*15 + \" 详细统计 (基于生成的有效样本) \" + \"=\"*15)\n", + " if generated_count > 0:\n", + " print(f\"总有效样本: {generated_count:,}\")\n", + " print(\"-\" * 50)\n", + " print(\"1. 算术题类型:\")\n", + " print(f\" - 加法: {add_count:,} ({add_count/generated_count:.1%})\")\n", + " print(f\" - 减法: {subtract_count:,} ({subtract_count/generated_count:.1%})\")\n", + " print(\"-\" * 50)\n", + " print(\"2. 运算数类型:\")\n", + " print(f\" - 纯整数运算*: {integer_op_count:,} ({integer_op_count/generated_count:.1%})\")\n", + " print(f\" - 含小数运算*: {decimal_op_count:,} ({decimal_op_count/generated_count:.1%})\")\n", + " print(\" *注: 基于输入或输出是否含小数部分。\")\n", + " print(\"-\" * 50)\n", + " total_a_counts = sum(format_counts[k] for k in format_counts if k.startswith('a_'))\n", + " print(f\"3. 问题格式 - 操作数 A (总计: {total_a_counts:,}):\")\n", + " a_order = ['a_standard', 'a_full_width', 'a_simple_zh', 'a_complex_zh']\n", + " for fmt_key in a_order:\n", + " count = format_counts[fmt_key]; percent = count / total_a_counts * 100 if total_a_counts > 0 else 0\n", + " print(f\" - {fmt_key[2:]: <15}: {count:>10,} ({percent:>6.1f}%)\")\n", + " print(\"-\" * 50)\n", + " total_b_counts = sum(format_counts[k] for k in format_counts if k.startswith('b_'))\n", + " print(f\"4. 问题格式 - 操作数 B (总计: {total_b_counts:,}):\")\n", + " b_order = ['b_standard', 'b_full_width', 'b_simple_zh', 'b_complex_zh']\n", + " for fmt_key in b_order:\n", + " count = format_counts[fmt_key]; percent = count / total_b_counts * 100 if total_b_counts > 0 else 0\n", + " print(f\" - {fmt_key[2:]: <15}: {count:>10,} ({percent:>6.1f}%)\")\n", + " print(\"-\" * 50)\n", + " total_op_counts = sum(operator_format_counts.values())\n", + " print(f\"5. 问题格式 - 操作符 (总计: {total_op_counts:,}):\")\n", + " op_order = ['symbol', 'natural_language']\n", + " for op_fmt in op_order:\n", + " count = operator_format_counts[op_fmt]; percent = count / total_op_counts * 100 if total_op_counts > 0 else 0\n", + " display_name = {'symbol': '符号 (+/-)', 'natural_language': '自然语言 (加/减)'}.get(op_fmt, op_fmt)\n", + " print(f\" - {display_name: <18}: {count:>10,} ({percent:>6.1f}%)\")\n", + " print(\"-\" * 50)\n", + " print(\"6. 其他:\")\n", + " print(f\" - 进/借位增强尝试 (占总循环比例): {boosted_carry_borrow_attempts:,} ({boosted_carry_borrow_attempts / max(1, total_attempts):.1%})\")\n", + " print(\"=\"*50)\n", + " else:\n", + " print(\"\\n--- 未生成有效样本,无详细统计 ---\")\n", + " print(\"=\"*50)\n", + "\n", + "\n", + "# ===============================================\n", + "# 主程序入口\n", + "# ===============================================\n", + "if __name__ == \"__main__\":\n", + " total_start_time = time.time()\n", + " print(\"=\"*30); print(\" 算术题生成脚本 (v9) \"); print(\"=\"*30)\n", + "\n", + " # 预检查条件 (使用新变量名)\n", + " if TARGET_CONSECUTIVE_CARRIES_MIN > TARGET_TOTAL_CARRIES_MIN and TARGET_TOTAL_CARRIES_MIN >= 0:\n", + " print(f\"\\n!!! 配置提示: 目标最小连续数({TARGET_CONSECUTIVE_CARRIES_MIN}) > 目标最小总数({TARGET_TOTAL_CARRIES_MIN})。\")\n", + " max_possible = MAX_DIGITS + MAX_DECIMAL_PLACES + 1\n", + " if TARGET_TOTAL_CARRIES_MIN > max_possible:\n", + " print(f\"\\n!!! 配置警告: 目标最小总数({TARGET_TOTAL_CARRIES_MIN}) > 最大可能位数({max_possible})。可能无法生成满足条件的样本。 !!!\")\n", + " if TARGET_CONSECUTIVE_CARRIES_MIN > max_possible:\n", + " print(f\"\\n!!! 配置警告: 目标最小连续数({TARGET_CONSECUTIVE_CARRIES_MIN}) > 最大可能位数({max_possible})。可能无法生成满足条件的样本。 !!!\")\n", + "\n", + "\n", + " try:\n", + " generate_filtered_arithmetic_diverse(\n", + " filename=OUTPUT_FILENAME,\n", + " total_samples=TOTAL_SAMPLES,\n", + " add_prob=ADD_PROBABILITY,\n", + " decimal_prob=DECIMAL_PROBABILITY,\n", + " max_digits_limit=MAX_DIGITS,\n", + " max_decimal_places=MAX_DECIMAL_PLACES,\n", + " negative_pool_prob=NEGATIVE_POOL_PROB,\n", + " carry_borrow_boost_prob=CARRY_BORROW_BOOST_PROB,\n", + " target_total_cb_min=TARGET_TOTAL_CARRIES_MIN, # 传递范围下限\n", + " target_total_cb_max=TARGET_TOTAL_CARRIES_MAX, # 传递范围上限\n", + " target_consecutive_cb_min=TARGET_CONSECUTIVE_CARRIES_MIN, # 传递范围下限\n", + " target_consecutive_cb_max=TARGET_CONSECUTIVE_CARRIES_MAX, # 传递范围上限\n", + " nl_operator_prob=NL_OPERATOR_PROBABILITY,\n", + " max_attempts_factor=MAX_ATTEMPTS_FACTOR,\n", + " batch_save_size=BATCH_SAVE_SIZE\n", + " )\n", + " except ValueError as ve: print(f\"\\n配置错误: {ve}\")\n", + " except Exception as main_e: print(f\"\\n主程序错误: {main_e}\"); traceback.print_exc()\n", + " finally: pass\n", + "\n", + " total_end_time = time.time()\n", + " print(\"\\n\" + \"=\"*30); print(f\"脚本执行完毕。总耗时: {total_end_time - total_start_time:.2f} 秒。\"); print(f\"数据文件: {OUTPUT_FILENAME}\"); print(\"=\"*30)" + ] + }, + { + "cell_type": "markdown", + "id": "31f82f01", + "metadata": {}, + "source": [ + "# 更好的版本\n", + "\n", + "这一版本加入条件判断,同时逐位生成两个数字,加快速度\n", + "\n", + "同样可以用于生成:\n", + "\n", + "训练集:ADD_2M 和 ADD_4M\n", + "\n", + "测试集:ADD_test\n", + "\n", + "ADD_n{}_m{}系列也适用该版本" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "29710155", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "==============================\n", + " 算术题生成脚本 (v10.6) \n", + "==============================\n", + "--- 开始生成算术数据 (v10.6 - Chinese Sci Notation) ---\n", + "已初始化/清空输出文件: 'qa_add_n0m0-test.jsonl'\n", + "\n", + "开始构造 500 条满足条件的数据...\n", + "生成: 500/500 (100.0%) | 写入: 0 | 尝试: 500 ( 1.0/样本) | 失败率: 0.0% | 18518.4 样本/秒 | 耗时: 0.0s | 剩余: ~0s \n", + "构造循环结束。目标: 500, 实际生成: 500 (尝试 500 次, 构造失败 0 次).\n", + "写入最后 500 条数据...\n", + "最终批次写入完成 (500 条). 耗时: 0.00s.\n", + "\n", + "生成与写入完毕。目标: 500 -> 生成: 500 -> 写入: 500\n", + "总尝试次数: 500 (平均 1.00 次/有效样本)\n", + "构造失败次数: 0 (失败率: 0.00%)\n", + "总耗时: 0.03 秒。格式化/计算/写入错误: 0.\n", + "\n", + "=============== 详细统计 (基于生成的有效样本) ===============\n", + "总有效样本: 500\n", + "--------------------------------------------------\n", + "1. 算术题类型:\n", + " - 加法: 257 (51.4%)\n", + " - 减法: 243 (48.6%)\n", + "--------------------------------------------------\n", + "2. 运算数类型:\n", + " - 纯整数运算*: 416 (83.2%)\n", + " - 含小数运算*: 84 (16.8%)\n", + " *注: 基于输入或输出是否含小数部分。\n", + "--------------------------------------------------\n", + "3. 问题格式 - 操作数 A (总计: 500):\n", + " - standard : 352 ( 70.4%)\n", + " - full_width : 46 ( 9.2%)\n", + " - simple_zh : 53 ( 10.6%)\n", + " - complex_zh : 49 ( 9.8%)\n", + "--------------------------------------------------\n", + "4. 问题格式 - 操作数 B (总计: 500):\n", + " - standard : 329 ( 65.8%)\n", + " - full_width : 53 ( 10.6%)\n", + " - simple_zh : 60 ( 12.0%)\n", + " - complex_zh : 58 ( 11.6%)\n", + "--------------------------------------------------\n", + "5. 问题格式 - 类型 (总计: 500):\n", + " - 符号格式 (+/-) : 353 ( 70.6%)\n", + " - 自然语言格式 (多样化) : 147 ( 29.4%)\n", + "--------------------------------------------------\n", + "6. 符号问题格式 - 等号后缀 (总计符号问题: 353):\n", + " - 添加 \" = ?/?\" : 167 ( 47.3%)\n", + " - 未添加后缀 : 186 ( 52.7%)\n", + "==================================================\n", + "\n", + "==============================\n", + "脚本执行完毕。总耗时: 0.03 秒。\n", + "数据文件: qa_add_n0m0-test.jsonl\n", + "==============================\n" + ] + } + ], + "source": [ + "# -*- coding: utf-8 -*-\n", + "# 生成满足指定进/借位范围条件,且问题格式多样化的算术问题数据集脚本。\n", + "# 采用反向逐位构造方法优化生成效率。\n", + "# v10.6: Convert large/small numbers to Chinese scientific notation when Chinese format is selected.\n", + "\n", + "import json\n", + "import random\n", + "import time\n", + "import math\n", + "from typing import List, Tuple, Union, Dict, Optional, Callable\n", + "from decimal import Decimal, getcontext, ROUND_DOWN, ROUND_HALF_UP, InvalidOperation\n", + "import traceback\n", + "from collections import Counter\n", + "\n", + "# ===============================================\n", + "# 配置参数区域\n", + "# ===============================================\n", + "# --- 主要数量和文件名 ---\n", + "TOTAL_SAMPLES = 500\n", + "OUTPUT_FILENAME = f\"qa_add_n0m0-test.jsonl\" # 更新文件名\n", + "ADD_PROBABILITY: float = 0.5\n", + "BATCH_SAVE_SIZE: int = 10000\n", + "\n", + "# --- 数字生成控制 ---\n", + "MAX_DIGITS: int = 12\n", + "MAX_DECIMAL_PLACES: int = 5\n", + "DECIMAL_PROBABILITY: float = 0.15\n", + "NEGATIVE_POOL_PROB: float = 0.05\n", + "# --- 新增: 定义中文科学计数法的阈值 ---\n", + "# 当数字的指数 >= SCI_THRESHOLD_POS 或 <= SCI_THRESHOLD_NEG 时,\n", + "# 且目标格式为中文时,使用科学计数法表示。\n", + "SCI_THRESHOLD_POS = 20\n", + "SCI_THRESHOLD_NEG = -10\n", + "\n", + "\n", + "# --- 进/借位条件范围 ---\n", + "TARGET_TOTAL_CARRIES_MIN: int = 0\n", + "TARGET_TOTAL_CARRIES_MAX: int = math.inf\n", + "TARGET_CONSECUTIVE_CARRIES_MIN: int = 0\n", + "TARGET_CONSECUTIVE_CARRIES_MAX: int = math.inf\n", + "\n", + "# --- 格式化控制 (问题部分) ---\n", + "STANDARD_ARABIC_PROB: float = 0.70\n", + "FULL_WIDTH_ARABIC_PROB: float = 0.10\n", + "SIMPLE_CHINESE_PROB: float = 0.10\n", + "COMPLEX_CHINESE_PROB: float = 0.10\n", + "_format_prob_sum = STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB + SIMPLE_CHINESE_PROB + COMPLEX_CHINESE_PROB\n", + "if not math.isclose(_format_prob_sum, 1.0):\n", + " raise ValueError(f\"数字格式概率总和必须为 1.0,当前为: {_format_prob_sum}\")\n", + "\n", + "# --- 自然语言概率控制 ---\n", + "NL_QUESTION_PROBABILITY: float = 0.30\n", + "\n", + "# --- 等号后缀概率控制 (仅符号问题) ---\n", + "SYMBOLIC_EQUALS_SUFFIX_PROB: float = 0.50\n", + "\n", + "# --- 其他控制 ---\n", + "MAX_ATTEMPTS_FACTOR = 5000\n", + "\n", + "# ===============================================\n", + "# 核心代码\n", + "# ===============================================\n", + "\n", + "getcontext().prec = MAX_DIGITS + MAX_DECIMAL_PLACES + 30\n", + "\n", + "# --- 中文数字转换等辅助函数 (省略实现细节 - 同 v10.4) ---\n", + "digit_map_simple = {'0': '零', '1': '一', '2': '二', '3': '三', '4': '四', '5': '五', '6': '六', '7': '七', '8': '八', '9': '九'}\n", + "unit_map_section_simple = ['', '十', '百', '千']\n", + "unit_map_large_simple = ['', '万', '亿', '兆']\n", + "digit_map_complex = {'0': '零', '1': '壹', '2': '贰', '3': '叁', '4': '肆', '5': '伍', '6': '陆', '7': '柒', '8': '捌', '9': '玖'}\n", + "unit_map_section_complex = ['', '拾', '佰', '仟']\n", + "unit_map_large_complex = ['', '萬', '億', '兆']\n", + "def _convert_section(section_str: str, complex_form: bool = False) -> str:\n", + " digit_map = digit_map_complex if complex_form else digit_map_simple; unit_map_section = unit_map_section_complex if complex_form else unit_map_section_simple\n", + " if not section_str: return \"\"\n", + " try: section_int = int(section_str)\n", + " except ValueError: return \"无效输入\"\n", + " if section_int == 0: return digit_map['0']\n", + " chinese_s = \"\"; length = len(section_str); need_zero = False\n", + " for i in range(length):\n", + " digit = section_str[i]; place = length - 1 - i\n", + " if digit == '0': need_zero = True\n", + " else:\n", + " if need_zero and chinese_s and not chinese_s.endswith(digit_map['0']): chinese_s += digit_map['0']\n", + " need_zero = False; current_digit_chinese = \"\"\n", + " if not complex_form and digit == '2':\n", + " is_leading_two_and_high_place = (i == 0 and place >= 2); is_leading_two_in_ten = (i == 0 and place == 1 and length > 1)\n", + " if (is_leading_two_and_high_place or is_leading_two_in_ten) and random.random() < 0.7: current_digit_chinese = '两'\n", + " else: current_digit_chinese = digit_map['2']\n", + " else: current_digit_chinese = digit_map[digit]\n", + " is_leading_one_in_ten_place = (not complex_form and digit == '1' and place == 1 and i == 0 and length > 1)\n", + " if is_leading_one_in_ten_place:\n", + " if length == 2: chinese_s += unit_map_section[place]\n", + " else: chinese_s += current_digit_chinese + unit_map_section[place]\n", + " else: chinese_s += current_digit_chinese + unit_map_section[place]\n", + " if chinese_s.endswith(digit_map['0']) and len(chinese_s) > len(digit_map['0']): chinese_s = chinese_s[:-len(digit_map['0'])]\n", + " if not complex_form and chinese_s.startswith(digit_map['1'] + unit_map_section_simple[1]): chinese_s = chinese_s[1:]\n", + " return chinese_s\n", + "def num_to_chinese(num: int, complex_form: bool = False) -> str:\n", + " if not isinstance(num, int): return \"无效输入\"\n", + " digit_map = digit_map_complex if complex_form else digit_map_simple; unit_map_large = unit_map_large_complex if complex_form else unit_map_large_simple\n", + " if num == 0: return digit_map['0']\n", + " if num < 0: return (\"负\" if not complex_form else \"负\") + num_to_chinese(abs(num), complex_form)\n", + " s_num = str(num);\n", + " if len(s_num) > 50: return \"数字过大无法转换\"\n", + " result = \"\"; sections = [];\n", + " while len(s_num) > 0: sections.append(s_num[-4:]); s_num = s_num[:-4]\n", + " zero_padding_needed = False; last_section_was_zero = True\n", + " for i in range(len(sections) - 1, -1, -1):\n", + " section_str = sections[i];\n", + " try: section_int = int(section_str)\n", + " except ValueError: return \"无效输入\"\n", + " if section_int == 0:\n", + " if not last_section_was_zero and i != 0:\n", + " if i > 0 and int(sections[i-1]) != 0: zero_padding_needed = True\n", + " last_section_was_zero = True; continue\n", + " if (not last_section_was_zero or zero_padding_needed) and result:\n", + " if not result.endswith(digit_map['0']):\n", + " if (section_int < 1000 and len(section_str.lstrip('0')) < 4) or \\\n", + " (len(section_str) == 4 and section_str.startswith('0') and section_int != 0): result += digit_map['0']\n", + " zero_padding_needed = False\n", + " section_chinese = _convert_section(section_str, complex_form)\n", + " if not section_chinese or section_chinese == \"无效输入\": return \"无效输入\"\n", + " result += section_chinese; last_section_was_zero = False\n", + " if i > 0: result += unit_map_large[i]\n", + " if not complex_form and result.startswith(digit_map['1'] + unit_map_section_simple[1]): result = result[1:]\n", + " return result\n", + "def decimal_to_chinese(num: Decimal, complex_form: bool = False) -> str:\n", + " \"\"\"将 Decimal 数字(包括小数)转换为中文表示(非科学计数法)。\"\"\"\n", + " if not isinstance(num, Decimal): return \"无效输入\"\n", + " if not num.is_finite(): return \"无效输入\"\n", + " digit_map = digit_map_complex if complex_form else digit_map_simple; point_word = \"点\"\n", + " if num.is_zero() and num.is_signed(): num = Decimal('0')\n", + " try:\n", + " int_val = num.to_integral_value(rounding=ROUND_DOWN)\n", + " if num == int_val:\n", + " if abs(num).adjusted() >= 50: return \"数字过大无法转换\" # 避免超大整数转换\n", + " return num_to_chinese(int(num), complex_form)\n", + " except (ValueError, TypeError, OverflowError, InvalidOperation): return \"无效输入或溢出\"\n", + " if num < 0: return (\"负\" if not complex_form else \"负\") + decimal_to_chinese(abs(num), complex_form)\n", + " # 使用能保证非科学计数法的格式化函数\n", + " try: s_num = format_decimal_or_int(num)\n", + " except Exception: return \"无效输入\"\n", + " if '.' not in s_num: # 理论上不会发生,因为上面处理了整数\n", + " try:\n", + " int_val_dec = Decimal(s_num);\n", + " if abs(int_val_dec).adjusted() >= 50: return \"数字过大无法转换\"\n", + " return num_to_chinese(int(int_val_dec), complex_form)\n", + " except (ValueError, TypeError, OverflowError, InvalidOperation): return \"无效输入或溢出\"\n", + " integer_part_str, fractional_part_str = s_num.split('.', 1)\n", + " if not integer_part_str: integer_part_str = '0'\n", + " try:\n", + " int_val_dec = Decimal(integer_part_str);\n", + " if abs(int_val_dec).adjusted() >= 50: return \"数字过大无法转换\"\n", + " chinese_int = num_to_chinese(int(int_val_dec), complex_form)\n", + " if chinese_int == \"无效输入\": return \"无效输入\"\n", + " except (ValueError, TypeError, OverflowError, InvalidOperation): return \"无效输入或溢出\"\n", + " chinese_frac = \"\".join(digit_map.get(digit, '?') for digit in fractional_part_str)\n", + " if not chinese_frac: return chinese_int # 小数部分为空 (e.g., \"12.\" -> \"12\")\n", + " else:\n", + " if chinese_int == digit_map['0']: return f\"{digit_map['0']}{point_word}{chinese_frac}\"\n", + " else: return f\"{chinese_int}{point_word}{chinese_frac}\"\n", + "\n", + "# --- 新增:中文科学计数法转换函数 ---\n", + "def _decimal_to_chinese_scientific(num: Decimal, complex_form: bool = False) -> str:\n", + " \"\"\"将 Decimal 转换为中文科学记数法表示。\"\"\"\n", + " if not isinstance(num, Decimal): return \"无效输入\"\n", + " if not num.is_finite(): return \"无效输入\"\n", + " if num.is_zero(): return digit_map_complex['0'] if complex_form else digit_map_simple['0']\n", + "\n", + " sign_prefix = \"\"\n", + " if num < 0:\n", + " sign_prefix = \"负\" if not complex_form else \"负\"\n", + " num = abs(num)\n", + "\n", + " try:\n", + " # 使用 Decimal 的 to_sci_string 方法获取科学记数法字符串\n", + " # context 控制精度,这里使用默认或当前上下文精度\n", + " # 或者可以先用 format %e 再解析\n", + " sci_str = \"{:e}\".format(num.normalize()) # 例如 '1.234568e+8'\n", + " parts = sci_str.lower().split('e')\n", + " if len(parts) != 2: return \"科学计数法解析失败\" # 格式错误\n", + "\n", + " coeff_str = parts[0]\n", + " exp_str = parts[1]\n", + "\n", + " coeff_dec = Decimal(coeff_str)\n", + " exp_int = int(exp_str)\n", + "\n", + " # 转换系数部分为中文小数\n", + " coeff_chinese = decimal_to_chinese(coeff_dec, complex_form)\n", + " if coeff_chinese in [\"无效输入\", \"无效输入或溢出\", \"数字过大无法转换\"]:\n", + " return coeff_chinese # 传递错误\n", + "\n", + " # 转换指数部分为中文整数\n", + " exp_chinese = num_to_chinese(exp_int, complex_form)\n", + " if exp_chinese in [\"无效输入\", \"无效输入或溢出\", \"数字过大无法转换\"]:\n", + " return exp_chinese # 传递错误\n", + "\n", + " # 组合结果\n", + " return f\"{sign_prefix}{coeff_chinese}乘以十的{exp_chinese}次方\"\n", + "\n", + " except (ValueError, IndexError, Exception) as e:\n", + " # print(f\"转换为中文科学计数法时出错: {e}, num={num}\") # 调试\n", + " return \"转换科学计数法出错\"\n", + "\n", + "# --- 其他辅助函数 ---\n", + "half_to_full_map = str.maketrans(\"0123456789.-+\", \"0123456789.-+\")\n", + "def to_full_width(text: str) -> str: return text.translate(half_to_full_map)\n", + "def format_decimal_or_int(num: Union[int, Decimal]) -> str:\n", + " \"\"\"(v10.5 Refined) 将 int 或 Decimal 格式化为标准字符串表示, 保证无科学计数法和不必要的前导/尾随零。\"\"\"\n", + " try:\n", + " if isinstance(num, int): return str(num)\n", + " if isinstance(num, Decimal):\n", + " if not num.is_finite(): return str(num)\n", + " s = num.to_eng_string() # 强制非科学计数法\n", + " if '.' in s: s = s.rstrip('0').rstrip('.')\n", + " if '.' not in s and len(s) > 1 and s[0] == '0': s = s.lstrip('0'); s = s if s else '0'\n", + " return s if s else \"0\"\n", + " return str(num)\n", + " except Exception:\n", + " try: normalized_num = Decimal(str(num)).normalize(); temp_s = \"{:f}\".format(normalized_num); temp_s = temp_s.rstrip('0').rstrip('.') if '.' in temp_s else temp_s; return temp_s if temp_s else \"0\"\n", + " except: return str(num)\n", + "def format_number_variant(num: Union[int, Decimal]) -> Tuple[str, str]:\n", + " \"\"\"(v10.6) 根据概率将数字格式化为不同变体, 对中文格式增加科学计数法处理。\"\"\"\n", + " fmt_choice = random.random();\n", + " try: num_dec = Decimal(str(num)) if not isinstance(num, Decimal) else num\n", + " except InvalidOperation: return str(num), 'standard'\n", + " target_format = 'complex_zh'\n", + " if fmt_choice < STANDARD_ARABIC_PROB: target_format = 'standard'\n", + " elif fmt_choice < STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB: target_format = 'full_width'\n", + " elif fmt_choice < STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB + SIMPLE_CHINESE_PROB: target_format = 'simple_zh'\n", + " try:\n", + " if not num_dec.is_finite(): s_num = str(num_dec); return (to_full_width(s_num), 'full_width') if target_format == 'full_width' else (s_num, 'standard')\n", + "\n", + " s_formatted = format_decimal_or_int(num_dec) # 获取标准格式\n", + "\n", + " if target_format == 'standard': return s_formatted, 'standard'\n", + " elif target_format == 'full_width': return to_full_width(s_formatted), 'full_width'\n", + " else: # simple_zh or complex_zh\n", + " is_complex = (target_format == 'complex_zh')\n", + " result = \"\"\n", + " try:\n", + " # --- 修改: 检查是否需要使用中文科学计数法 ---\n", + " exponent = num_dec.normalize().adjusted()\n", + " use_sci_chinese = (exponent >= SCI_THRESHOLD_POS or exponent <= SCI_THRESHOLD_NEG)\n", + "\n", + " if use_sci_chinese:\n", + " result = _decimal_to_chinese_scientific(num_dec, complex_form=is_complex)\n", + " else:\n", + " result = decimal_to_chinese(num_dec, complex_form=is_complex)\n", + " # --- 结束修改 ---\n", + "\n", + " # 检查转换结果\n", + " if result in [\"无效输入\", \"无效输入或溢出\", \"数字过大无法转换\", \"科学计数法解析失败\", \"转换科学计数法出错\"]:\n", + " return s_formatted, 'standard' # 转换失败则回退\n", + " else:\n", + " return result, target_format # 返回中文格式\n", + " except Exception as e: # 捕获中文转换中的其他潜在错误\n", + " # print(f\"中文转换时出错: {e}, num={num_dec}\") # 调试\n", + " return s_formatted, 'standard' # 出错则回退\n", + "\n", + " except Exception: # 捕获 format_number_variant 中的其他错误\n", + " try: fallback_str = format_decimal_or_int(num)\n", + " except: fallback_str = str(num)\n", + " return fallback_str, 'standard'\n", + "def get_realistic_spacing() -> str:\n", + " space_values = [\"\", \" \", \" \"]; space_weights = [99.5, 0.4, 0.1]\n", + " if not math.isclose(sum(space_weights), 100.0): print(\"警告:get_realistic_spacing 中的空格权重和不为 100。\"); return \"\"\n", + " try: return random.choices(space_values, weights=space_weights, k=1)[0]\n", + " except Exception as e: print(f\"警告:生成空格时出错: {e}。默认为无空格。\"); return \"\"\n", + "def contains_arabic_numerals(s: str) -> bool: return any(c in \"01234567890123456789\" for c in s)\n", + "def get_distributed_count_from_probs(population: List[int], probabilities: List[float]) -> int:\n", + " if not population: return 1\n", + " if not probabilities or len(population) != len(probabilities) or not all(p >= 0 for p in probabilities): print(\"警告:get_distributed_count_from_probs 中的 population 或 probabilities 无效。将进行均匀选择。\"); return random.choice(population) if population else 1\n", + " prob_sum = sum(probabilities);\n", + " if prob_sum < 1e-9: print(\"警告:概率和接近于零。将进行均匀选择。\"); return random.choice(population) if population else 1\n", + " normalized_probabilities = probabilities\n", + " if not math.isclose(prob_sum, 1.0, abs_tol=1e-5):\n", + " try: normalized_probabilities = [p / prob_sum for p in probabilities]\n", + " except ZeroDivisionError: print(\"警告:概率归一化期间出现 ZeroDivisionError。将进行均匀选择。\"); return random.choice(population) if population else 1\n", + " try: return random.choices(population, weights=normalized_probabilities, k=1)[0]\n", + " except Exception as e: print(f\"random.choices 执行期间出错: {e}。将进行均匀选择。\"); return random.choice(population) if population else 1\n", + "def calculate_digit_probabilities(max_digits: int) -> Dict[int, float]:\n", + " if max_digits <= 0: return {1: 1.0}\n", + " raw_probs = {}; prob_sum = Decimal('0.0'); base_prob = Decimal('0.1'); decay_factor = Decimal('0.95'); increase_factor = Decimal('1.05')\n", + " for n in range(1, max_digits + 1):\n", + " prob = base_prob * (decay_factor**(n - 1)) * (increase_factor**(max_digits - n + 1)); prob = max(Decimal('0.001'), prob); raw_probs[n] = prob; prob_sum += prob\n", + " normalized_probs = {}\n", + " if prob_sum <= 0: print(\"警告:calculate_digit_probabilities 中的原始概率和为零。使用均匀分布。\"); fallback_prob = 1.0 / max(1, max_digits); normalized_probs = {n: fallback_prob for n in range(1, max_digits + 1)}\n", + " else: normalized_probs = {n: float(p / prob_sum) for n, p in raw_probs.items()}\n", + " final_sum = sum(normalized_probs.values())\n", + " if not math.isclose(final_sum, 1.0, abs_tol=1e-9):\n", + " renorm_factor = 1.0 / final_sum if final_sum != 0 else 1.0; total = 0.0; keys = sorted(normalized_probs.keys())\n", + " for i, n in enumerate(keys):\n", + " if i == len(keys) - 1: normalized_probs[n] = max(0.0, 1.0 - total)\n", + " else: norm_p = max(0.0, normalized_probs[n] * renorm_factor); normalized_probs[n] = norm_p; total += norm_p\n", + " if keys: normalized_probs[keys[-1]] = max(0.0, normalized_probs[keys[-1]])\n", + " return normalized_probs\n", + "# --- 多样化自然语言问题格式化函数 ---\n", + "def format_natural_language_question(fmt_a: str, fmt_b: str, op_sym: str) -> str:\n", + " add_words = [\"加\", \"加上\", \"和\", \"的总和是\", \"一共是\"]\n", + " subtract_words = [\"减\", \"减去\", \"减掉\", \"与...的差是\", \"少了\"]\n", + " result_phrases = [\"等于多少\", \"是多少\", \"结果是\", \"等于几\", \"得多少\", \"是多少呢\"]\n", + " question_marks = [\"?\", \"?\", \"\"]\n", + " templates = []\n", + " if op_sym == '+':\n", + " op_words = add_words\n", + " templates.extend([\"{num_a} {op} {num_b} {res}{q_mark}\", \"计算一下 {num_a} {op} {num_b}{q_mark}\", \"请问 {num_a} {op} {num_b} {res}{q_mark}\", \"{num_a} 与 {num_b} 的和是多少{q_mark}\", \"{num_a} {op} {num_b} 等于?\", \"{num_a} 再 {op} {num_b} {res}{q_mark}\", \"帮我算算 {num_a} {op} {num_b} 的结果{q_mark}\"])\n", + " elif op_sym == '-':\n", + " op_words = subtract_words\n", + " templates.extend([\"{num_a} {op} {num_b} {res}{q_mark}\", \"计算一下 {num_a} {op} {num_b}{q_mark}\", \"请问 {num_a} {op} {num_b} {res}{q_mark}\", \"{num_a} 与 {num_b} 的差是多少{q_mark}\", \"{num_a} {op} {num_b} 等于?\", \"{num_a} {op} {num_b} 还剩多少{q_mark}\", \"帮我算算 {num_a} {op} {num_b} {res}{q_mark}\"])\n", + " else: return f\"{fmt_a} {op_sym} {fmt_b}\"\n", + " chosen_template = random.choice(templates); chosen_op_word = random.choice(op_words)\n", + " if chosen_op_word == \"与...的差是\": question_str = chosen_template.format(num_a=fmt_a, num_b=fmt_b, op=\"与\", res=f\"的差 {random.choice(result_phrases)}\", q_mark=random.choice(question_marks))\n", + " elif chosen_op_word in [\"的总和是\", \"一共是\", \"少了\"]: q_mark_only = random.choice(question_marks); res_or_nothing = random.choice([\" \" + random.choice(result_phrases), \"\"]); question_str = chosen_template.format(num_a=fmt_a, num_b=fmt_b, op=chosen_op_word, res=res_or_nothing, q_mark=q_mark_only)\n", + " else: chosen_res_phrase = random.choice(result_phrases); chosen_q_mark = random.choice(question_marks); question_str = chosen_template.format(num_a=fmt_a, num_b=fmt_b, op=chosen_op_word, res=chosen_res_phrase, q_mark=chosen_q_mark)\n", + " try: question_str = ' '.join(question_str.split())\n", + " except KeyError as e: print(f\"警告: 格式化自然语言模板时出错 (KeyError: {e})。模板: '{chosen_template}'\"); question_str = f\"{fmt_a} {op_sym} {fmt_b} = ?\"\n", + " return question_str\n", + "# --- 反向逐位构造函数 (v10.3 实现 - 省略) ---\n", + "def _generate_pair_meeting_cb_criteria(\n", + " target_digits_a: int, target_digits_b: int, sign_a: int, sign_b: int,\n", + " is_decimal: bool, max_decimal_places: int,\n", + " operation_type: str,\n", + " target_total_cb_min: int, target_total_cb_max: Union[int, float],\n", + " target_consecutive_cb_min: int, target_consecutive_cb_max: Union[int, float]\n", + ") -> Optional[Tuple[Union[int, Decimal], Union[int, Decimal]]]:\n", + " \"\"\"(v10.3) 尝试反向逐位构造数字对。\"\"\"\n", + " num_dp = random.randint(1, max_decimal_places) if is_decimal and max_decimal_places > 0 else 0; num_int_digits_a = max(1, target_digits_a); num_int_digits_b = max(1, target_digits_b)\n", + " total_len_a = num_int_digits_a + num_dp; total_len_b = num_int_digits_b + num_dp; max_total_len = max(total_len_a, total_len_b)\n", + " effective_op = operation_type; op1_is_a = True\n", + " if operation_type == 'add':\n", + " if sign_a * sign_b < 0: effective_op = 'subtract'\n", + " elif operation_type == 'subtract':\n", + " if sign_a * sign_b < 0: effective_op = 'add'\n", + " op1_digits_rev = []; op2_digits_rev = []; carry_in = 0; borrow_in = 0; current_total_cb = 0; current_consecutive_cb = 0; max_consecutive_achieved = 0\n", + " op1_target_len = total_len_a if op1_is_a else total_len_b; op2_target_len = total_len_b if op1_is_a else total_len_a; op1_int_digits = num_int_digits_a if op1_is_a else num_int_digits_b; op2_int_digits = num_int_digits_b if op1_is_a else num_int_digits_a\n", + " is_unlimited_range = (target_total_cb_min == 0 and target_total_cb_max == math.inf and target_consecutive_cb_min == 0 and target_consecutive_cb_max == math.inf)\n", + " for i in range(max_total_len):\n", + " pos_from_right = i; is_decimal_pos = (pos_from_right < num_dp); is_int_pos = not is_decimal_pos; int_pos_from_right = pos_from_right - num_dp if is_int_pos else -1\n", + " in_op1 = (pos_from_right < op1_target_len); in_op2 = (pos_from_right < op2_target_len); is_msd_op1_int = in_op1 and is_int_pos and int_pos_from_right == op1_int_digits - 1; is_msd_op2_int = in_op2 and is_int_pos and int_pos_from_right == op2_int_digits - 1\n", + " min_d1 = 1 if is_msd_op1_int and op1_int_digits > 1 else 0; max_d1 = 9 if in_op1 else 0; min_d2 = 1 if is_msd_op2_int and op2_int_digits > 1 else 0; max_d2 = 9 if in_op2 else 0\n", + " target_cb_state = None\n", + " if not is_unlimited_range:\n", + " positions_remaining = max_total_len - (i + 1); min_total_needed = max(0, target_total_cb_min - current_total_cb); max_total_allowed = float('inf') if target_total_cb_max == math.inf else target_total_cb_max - current_total_cb\n", + " if max_total_allowed < 0: return None\n", + " min_consecutive_needed = max(0, target_consecutive_cb_min - current_consecutive_cb); max_consecutive_allowed = float('inf') if target_consecutive_cb_max == math.inf else target_consecutive_cb_max - current_consecutive_cb\n", + " must_gen_cb = (min_total_needed > positions_remaining) or (min_consecutive_needed > positions_remaining); must_avoid_cb = (max_total_allowed < 1) or (max_consecutive_allowed < 1)\n", + " if must_gen_cb and must_avoid_cb: return None\n", + " if must_gen_cb: target_cb_state = True\n", + " elif must_avoid_cb: target_cb_state = False\n", + " else:\n", + " prob_gen_cb = 0.5\n", + " if min_total_needed > 0: prob_gen_cb += 0.2 * (min_total_needed / max(1, positions_remaining + 1))\n", + " if min_consecutive_needed > 0 and max_consecutive_achieved < target_consecutive_cb_min: prob_gen_cb += 0.4 * (min_consecutive_needed / max(1, positions_remaining + 1))\n", + " if target_total_cb_max != math.inf and max_total_allowed <= positions_remaining: prob_gen_cb -= 0.2 * (1 - max_total_allowed / max(1, positions_remaining + 1))\n", + " prob_gen_cb = max(0.0, min(1.0, prob_gen_cb)); target_cb_state = (random.random() < prob_gen_cb)\n", + " found_pair = False; possible_d1_list = list(range(min_d1, max_d1 + 1)); random.shuffle(possible_d1_list); best_d1, best_d2 = -1, -1\n", + " for d1_try in possible_d1_list:\n", + " possible_d2_for_d1 = []\n", + " for d2_try in range(min_d2, max_d2 + 1):\n", + " carry_out = 0; borrow_out = 0; cb_occurred_here = False\n", + " if effective_op == 'add': current_sum = d1_try + d2_try + carry_in; carry_out = 1 if current_sum >= 10 else 0; cb_occurred_here = (carry_out == 1)\n", + " else: current_diff = d1_try - borrow_in - d2_try; borrow_out = 1 if current_diff < 0 else 0; cb_occurred_here = (borrow_out == 1)\n", + " state_matches = (is_unlimited_range or target_cb_state is None) or (cb_occurred_here == target_cb_state); consecutive_ok = True\n", + " if not is_unlimited_range:\n", + " max_consecutive_allowed_check = float('inf') if target_consecutive_cb_max == math.inf else target_consecutive_cb_max - current_consecutive_cb\n", + " if cb_occurred_here and max_consecutive_allowed_check < 1: consecutive_ok = False\n", + " min_consecutive_needed_check = max(0, target_consecutive_cb_min - current_consecutive_cb); positions_remaining_check = max_total_len - (i + 1)\n", + " if not cb_occurred_here and min_consecutive_needed_check > positions_remaining_check: consecutive_ok = False\n", + " if state_matches and consecutive_ok: possible_d2_for_d1.append(d2_try)\n", + " if possible_d2_for_d1: best_d2 = random.choice(possible_d2_for_d1); best_d1 = d1_try; found_pair = True; break\n", + " if not found_pair: return None\n", + " d1, d2 = best_d1, best_d2; op1_digits_rev.append(str(d1)); op2_digits_rev.append(str(d2)); carry_out = 0; borrow_out = 0; cb_occurred = False\n", + " if effective_op == 'add': current_sum = d1 + d2 + carry_in; carry_out = 1 if current_sum >= 10 else 0; cb_occurred = (carry_out == 1)\n", + " else: current_diff = d1 - borrow_in - d2; borrow_out = 1 if current_diff < 0 else 0; cb_occurred = (borrow_out == 1)\n", + " if cb_occurred: current_total_cb += 1; current_consecutive_cb += 1\n", + " else: max_consecutive_achieved = max(max_consecutive_achieved, current_consecutive_cb); current_consecutive_cb = 0\n", + " carry_in = carry_out; borrow_in = borrow_out\n", + " max_consecutive_achieved = max(max_consecutive_achieved, current_consecutive_cb)\n", + " if not is_unlimited_range:\n", + " total_ok = (target_total_cb_min <= current_total_cb <= target_total_cb_max); consecutive_ok = (max_consecutive_achieved >= target_consecutive_cb_min) and (target_consecutive_cb_max == math.inf or max_consecutive_achieved <= target_consecutive_cb_max)\n", + " if not (total_ok and consecutive_ok): return None\n", + " op1_str_rev = \"\".join(op1_digits_rev); op2_str_rev = \"\".join(op2_digits_rev); op1_str = op1_str_rev[::-1]; op2_str = op2_str_rev[::-1]\n", + " def format_str_to_decimal_str(s: str, dp: int) -> str:\n", + " if not s: s = \"0\"\n", + " if dp > 0:\n", + " if len(s) <= dp: s = s.zfill(dp + 1)\n", + " int_part = s[:-dp]; frac_part = s[-dp:]; int_part = int_part.lstrip('0') or \"0\"; return f\"{int_part}.{frac_part}\"\n", + " else: s_int = s.lstrip('0') or \"0\"; return s_int\n", + " op1_final_str = format_str_to_decimal_str(op1_str, num_dp); op2_final_str = format_str_to_decimal_str(op2_str, num_dp)\n", + " try:\n", + " op1_val = Decimal(op1_final_str); op2_val = Decimal(op2_final_str)\n", + " a_val_abs = op1_val if op1_is_a else op2_val; b_val_abs = op2_val if op1_is_a else op1_val\n", + " a_val = a_val_abs.copy_sign(sign_a); b_val = b_val_abs.copy_sign(sign_b)\n", + " if a_val.is_zero() and a_val.is_signed(): a_val = Decimal('0')\n", + " if b_val.is_zero() and b_val.is_signed(): b_val = Decimal('0')\n", + " if not is_decimal and a_val == a_val.to_integral_value() and b_val == b_val.to_integral_value():\n", + " try: a_final = int(a_val)\n", + " except (OverflowError, ValueError): a_final = a_val.normalize()\n", + " try: b_final = int(b_val)\n", + " except (OverflowError, ValueError): b_final = b_val.normalize()\n", + " else: a_final = a_val.normalize(); b_final = b_val.normalize()\n", + " return a_final, b_final\n", + " except InvalidOperation: return None\n", + " except Exception as e: return None\n", + "\n", + "# --- check_carries_borrows 函数 (省略实现 - 同 v10.3) ---\n", + "def check_carries_borrows(num1: Decimal, num2: Decimal, operation: str) -> Tuple[int, int]:\n", + " total_cb = 0; max_consecutive_cb = 0; current_consecutive_cb = 0\n", + " try:\n", + " effective_op = operation; op1: Decimal; op2: Decimal\n", + " if operation == 'add':\n", + " if num1.is_signed() != num2.is_signed(): effective_op = 'subtract'; op1, op2 = (abs(num1), abs(num2)) if abs(num1) >= abs(num2) else (abs(num2), abs(num1))\n", + " else: effective_op = 'add'; op1, op2 = abs(num1), abs(num2)\n", + " elif operation == 'subtract':\n", + " if num1.is_signed() != num2.is_signed(): effective_op = 'add'; op1, op2 = abs(num1), abs(num2)\n", + " else: effective_op = 'subtract'; op1, op2 = (abs(num1), abs(num2)) if abs(num1) >= abs(num2) else (abs(num2), abs(num1))\n", + " else: return -1, -1\n", + " if op1.is_zero() and op2.is_zero(): return 0, 0\n", + " s1 = format_decimal_or_int(op1); s2 = format_decimal_or_int(op2)\n", + " s1_int, s1_frac = s1.split('.') if '.' in s1 else (s1, ''); s2_int, s2_frac = s2.split('.') if '.' in s2 else (s2, '')\n", + " max_frac_len = max(len(s1_frac), len(s2_frac)); s1_frac = s1_frac.ljust(max_frac_len, '0'); s2_frac = s2_frac.ljust(max_frac_len, '0')\n", + " max_int_len = max(len(s1_int), len(s2_int)); s1_int = s1_int.zfill(max_int_len); s2_int = s2_int.zfill(max_int_len)\n", + " aligned_s1 = s1_int + s1_frac; aligned_s2 = s2_int + s2_frac; full_len = len(aligned_s1)\n", + " carry = 0; borrow = 0\n", + " for i in range(full_len - 1, -1, -1):\n", + " try: d1 = int(aligned_s1[i]); d2 = int(aligned_s2[i])\n", + " except (IndexError, ValueError): print(f\"Error parsing digits: {aligned_s1}, {aligned_s2} at index {i}\"); return -1, -1\n", + " cb_occurred = False\n", + " if effective_op == 'add': current_sum = d1 + d2 + carry; carry = 1 if current_sum >= 10 else 0; cb_occurred = (carry == 1)\n", + " else: current_diff = d1 - borrow - d2; borrow = 1 if current_diff < 0 else 0; cb_occurred = (borrow == 1)\n", + " if cb_occurred: total_cb += 1; current_consecutive_cb += 1\n", + " else: max_consecutive_cb = max(max_consecutive_cb, current_consecutive_cb); current_consecutive_cb = 0\n", + " max_consecutive_cb = max(max_consecutive_cb, current_consecutive_cb)\n", + " except Exception as e: print(f\"Error in check_carries_borrows: {e}\"); traceback.print_exc(); return -1, -1\n", + " return total_cb, max_consecutive_cb\n", + "\n", + "# --- 批量写入函数 (省略实现 - 同 v10.3) ---\n", + "def write_batch_to_jsonl(buffer: List[Dict], filename: str, mode: str = 'a') -> int:\n", + " if not buffer: return 0\n", + " lines_written = 0; json_lines_to_write = []; serialization_errors = 0\n", + " for item in buffer:\n", + " try:\n", + " if not isinstance(item, dict) or not item.get(\"text\"): serialization_errors += 1; continue\n", + " json_string = json.dumps(item, ensure_ascii=False)\n", + " if json_string and not json_string.isspace(): json_lines_to_write.append(json_string)\n", + " else: serialization_errors += 1\n", + " except (TypeError, ValueError) as dump_e: serialization_errors += 1\n", + " except Exception as generic_e: serialization_errors += 1\n", + " if json_lines_to_write:\n", + " try:\n", + " with open(filename, mode, encoding='utf-8') as f:\n", + " output_string = '\\n'.join(json_lines_to_write) + '\\n'; f.write(output_string)\n", + " lines_written = len(json_lines_to_write)\n", + " except IOError as e: print(f\"\\n写入文件 '{filename}' 时 IO 错误: {e}\"); return 0\n", + " except Exception as e: print(f\"\\n写入文件时未知错误: {e}\"); return 0\n", + " if serialization_errors > 0: print(f\"\\n警告: 写入批次时 {serialization_errors} 个项目处理失败。\")\n", + " return lines_written\n", + "\n", + "# --- 主要生成函数 ---\n", + "def generate_constructed_arithmetic_diverse(\n", + " filename: str, total_samples: int, add_prob: float, decimal_prob: float,\n", + " max_digits_limit: int, max_decimal_places: int, negative_pool_prob: float,\n", + " target_total_cb_min: int, target_total_cb_max: Union[int, float],\n", + " target_consecutive_cb_min: int, target_consecutive_cb_max: Union[int, float],\n", + " nl_question_prob: float, # 使用新的概率名\n", + " symbolic_equals_suffix_prob: float, # 使用新的概率名\n", + " max_attempts_factor: int,\n", + " batch_save_size: int):\n", + " \"\"\"(v10.6) 通过反向构造生成数据,包含多样化NL问题和中文科学计数法。\"\"\"\n", + "\n", + " # --- 参数验证和准备 ---\n", + " # ... (同 v10.5) ...\n", + " print(f\"--- 开始生成算术数据 (v10.6 - Chinese Sci Notation) ---\") # 更新版本信息\n", + " # ... (打印配置) ...\n", + "\n", + " # --- 计算位数分布, 初始化计数器 ---\n", + " # ... (同 v10.5) ...\n", + " digit_pop: List[int] = []; digit_probs_list: List[float] = []\n", + " if max_digits_limit > 0:\n", + " digit_probabilities_dict = calculate_digit_probabilities(max_digits_limit)\n", + " digit_pop = list(range(1, max_digits_limit + 1)); digit_probs_list = [digit_probabilities_dict.get(n, 0.0) for n in digit_pop]\n", + " prob_sum_check = sum(digit_probs_list)\n", + " if not math.isclose(prob_sum_check, 1.0, abs_tol=1e-5):\n", + " if prob_sum_check > 1e-9: digit_probs_list = [p / prob_sum_check for p in digit_probs_list]\n", + " else: uniform_prob = 1.0 / len(digit_pop) if digit_pop else 1.0; digit_probs_list = [uniform_prob] * len(digit_pop)\n", + " if not digit_probs_list: digit_pop = [1]; digit_probs_list = [1.0]\n", + " else: digit_pop = [1]; digit_probs_list = [1.0]\n", + " generated_count = 0; total_attempts = 0; total_lines_written = 0\n", + " construct_failures = 0; add_count = 0; subtract_count = 0\n", + " integer_op_count = 0; decimal_op_count = 0\n", + " format_counts = Counter(); question_type_counts = Counter(); suffix_counts = Counter()\n", + " errors_in_loop = 0\n", + " difficulty_factor = max(1, TARGET_TOTAL_CARRIES_MIN) if TARGET_TOTAL_CARRIES_MAX != math.inf else 1\n", + " max_total_attempts = total_samples * max(100, max_attempts_factor * difficulty_factor)\n", + " start_time_generate = time.time(); output_buffer = []; last_reported_count = -1; last_save_time = start_time_generate\n", + "\n", + " try:\n", + " with open(filename, 'w', encoding='utf-8') as f: f.write(\"\")\n", + " print(f\"已初始化/清空输出文件: '{filename}'\")\n", + " except IOError as e: print(f\"\\n错误:无法初始化输出文件 '{filename}': {e}\"); return\n", + "\n", + " print(f\"\\n开始构造 {total_samples:,} 条满足条件的数据...\")\n", + "\n", + " # --- 主生成循环 ---\n", + " while generated_count < total_samples:\n", + " total_attempts += 1\n", + " if total_attempts > max_total_attempts:\n", + " print(f\"\\n\\n警告: 尝试次数达到上限 ({total_attempts:,})。\")\n", + " print(f\"当前已生成: {generated_count:,} (构造失败 {construct_failures:,} 次).\")\n", + " print(\"脚本提前终止。\")\n", + " break\n", + "\n", + " pair_data = None\n", + " a: Union[int, Decimal] = 0; b: Union[int, Decimal] = 0\n", + "\n", + " try:\n", + " # --- 选择基本参数 ---\n", + " if not digit_pop or not digit_probs_list or len(digit_pop) != len(digit_probs_list): digits_a = 1; digits_b = 1\n", + " else: digits_a = get_distributed_count_from_probs(digit_pop, digit_probs_list); digits_b = get_distributed_count_from_probs(digit_pop, digit_probs_list)\n", + " sign_a = -1 if random.random() < negative_pool_prob else 1; sign_b = -1 if random.random() < negative_pool_prob else 1\n", + " is_dec_intent = random.random() < decimal_prob; op_type = 'add' if random.random() < add_prob else 'subtract'; op_sym = '+' if op_type == 'add' else '-'\n", + "\n", + " # --- 调用构造函数 ---\n", + " constructed_pair = _generate_pair_meeting_cb_criteria(\n", + " digits_a, digits_b, sign_a, sign_b, is_dec_intent, max_decimal_places,\n", + " op_type, TARGET_TOTAL_CARRIES_MIN, TARGET_TOTAL_CARRIES_MAX,\n", + " TARGET_CONSECUTIVE_CARRIES_MIN, TARGET_CONSECUTIVE_CARRIES_MAX\n", + " )\n", + " if constructed_pair is None: construct_failures += 1; continue\n", + " a, b = constructed_pair\n", + "\n", + " # --- 计算结果 c ---\n", + " c_final: Union[int, Decimal]; answer_str = \"\" # 重命名: 用于最终答案字符串\n", + " try:\n", + " a_calc = Decimal(str(a)) if not isinstance(a, Decimal) else a; b_calc = Decimal(str(b)) if not isinstance(b, Decimal) else b\n", + " if not a_calc.is_finite() or not b_calc.is_finite(): errors_in_loop += 1; continue\n", + " c_calc = a_calc + b_calc if op_type == 'add' else a_calc - b_calc\n", + " if not c_calc.is_finite(): errors_in_loop += 1; continue\n", + " result_decimal_places = 0; nums_for_dp = [a_calc, b_calc]\n", + " for num_in in nums_for_dp:\n", + " if isinstance(num_in, Decimal):\n", + " norm_num = num_in.normalize()\n", + " if norm_num != norm_num.to_integral_value():\n", + " exp = norm_num.as_tuple().exponent\n", + " if isinstance(exp, int) and exp < 0: result_decimal_places = max(result_decimal_places, abs(exp))\n", + " result_decimal_places = min(result_decimal_places, max_decimal_places)\n", + " if result_decimal_places > 0: quantizer = Decimal('1e-' + str(result_decimal_places)); c_final_dec = c_calc.quantize(quantizer, rounding=ROUND_HALF_UP)\n", + " else: c_final_dec = c_calc.to_integral_value(rounding=ROUND_HALF_UP)\n", + " c_final_dec = c_final_dec.normalize()\n", + " if c_final_dec.is_zero() and c_final_dec.is_signed(): c_final_dec = Decimal('0')\n", + " is_a_int_final = isinstance(a, int) or (isinstance(a, Decimal) and a == a.to_integral_value())\n", + " is_b_int_final = isinstance(b, int) or (isinstance(b, Decimal) and b == b.to_integral_value())\n", + " is_c_int_final = (c_final_dec == c_final_dec.to_integral_value())\n", + " if is_c_int_final and is_a_int_final and is_b_int_final and not is_dec_intent:\n", + " try: c_final = int(c_final_dec)\n", + " except (OverflowError, ValueError): c_final = c_final_dec\n", + " else: c_final = c_final_dec\n", + " # --- 修改: 答案也使用 format_number_variant ---\n", + " # 这样答案也会根据数字大小和中文选择,可能变成科学计数法\n", + " # 但 Assistant 的回答通常是标准数字,所以我们直接用 format_decimal_or_int\n", + " answer_str = format_decimal_or_int(c_final)\n", + " # 如果需要答案也多样化,取消下面一行的注释\n", + " # answer_str, _ = format_number_variant(c_final)\n", + "\n", + " except (InvalidOperation, OverflowError, ValueError, ArithmeticError) as calc_e: errors_in_loop += 1; continue\n", + " except Exception as format_e: errors_in_loop += 1; continue\n", + " if not answer_str: errors_in_loop += 1; continue\n", + "\n", + " # --- 进行多样化格式化 ---\n", + " try:\n", + " # 使用 format_number_variant 获取可能包含中文科学计数法的字符串\n", + " fmt_a_str, fmt_a_type = format_number_variant(a)\n", + " final_op_sym = op_sym\n", + " fmt_b_str, fmt_b_type = \"\", \"\"\n", + " try:\n", + " b_dec_val = Decimal(str(b)) if not isinstance(b, Decimal) else b\n", + " if b_dec_val.is_signed() and b_dec_val < 0:\n", + " fmt_b_abs_str, fmt_b_abs_type = format_number_variant(abs(b_dec_val))\n", + " fmt_b_str = fmt_b_abs_str; fmt_b_type = fmt_b_abs_type\n", + " if op_sym == '+': final_op_sym = '-'\n", + " elif op_sym == '-': final_op_sym = '+'\n", + " else: fmt_b_str, fmt_b_type = format_number_variant(b)\n", + " except (InvalidOperation, TypeError, ValueError): fmt_b_str, fmt_b_type = format_number_variant(b)\n", + "\n", + " # 检查初始格式化结果是否有错误\n", + " if fmt_a_type == 'error' or fmt_b_type == 'error' or \\\n", + " fmt_a_str in [\"无效输入\", \"无效输入或溢出\", \"数字过大无法转换\", \"科学计数法解析失败\", \"转换科学计数法出错\"] or \\\n", + " fmt_b_str in [\"无效输入\", \"无效输入或溢出\", \"数字过大无法转换\", \"科学计数法解析失败\", \"转换科学计数法出错\"]:\n", + " errors_in_loop += 1; continue\n", + "\n", + " format_counts[f'a_{fmt_a_type}'] += 1; format_counts[f'b_{fmt_b_type}'] += 1\n", + "\n", + " # --- 移除 v10.5 的 'E' 检查保障,因为格式化逻辑已调整 ---\n", + "\n", + " # --- 决定问题类型 (NL vs 符号) ---\n", + " question_str = \"\"\n", + " a_is_zh = fmt_a_type in ['simple_zh', 'complex_zh']\n", + " b_is_zh = fmt_b_type in ['simple_zh', 'complex_zh']\n", + " is_nl_question = (random.random() < nl_question_prob) and not (a_is_zh and b_is_zh)\n", + "\n", + " if is_nl_question:\n", + " question_type_counts['natural_language'] += 1\n", + " question_str = format_natural_language_question(fmt_a_str, fmt_b_str, final_op_sym)\n", + " # suffix_counts['not_applicable_nl'] += 1\n", + "\n", + " else: # 生成符号问题\n", + " question_type_counts['symbolic'] += 1\n", + " s1 = get_realistic_spacing(); s2 = get_realistic_spacing()\n", + " question_str_base = f\"{fmt_a_str}{s1}{final_op_sym}{s2}{fmt_b_str}\"\n", + " question_suffix = \"\"\n", + " added_suffix = False\n", + " if random.random() < symbolic_equals_suffix_prob:\n", + " question_mark = random.choice([\"?\", \"?\"])\n", + " question_suffix = f\" = {question_mark}\"\n", + " added_suffix = True\n", + " suffix_counts['symbolic_added' if added_suffix else 'symbolic_not_added'] += 1\n", + " question_str = question_str_base + question_suffix\n", + " # --- 结束问题类型决定 ---\n", + "\n", + " if not question_str or question_str.isspace(): errors_in_loop += 1; continue\n", + "\n", + " text_content = f\"User: {question_str}\\n\\nAssistant: {answer_str}\"\n", + " pair_data = {\"text\": text_content}\n", + "\n", + " # --- 更新统计 ---\n", + " generated_count += 1\n", + " if op_type == 'add': add_count += 1; \n", + " else: subtract_count += 1\n", + " is_a_dec_final = isinstance(a, Decimal) and a != a.to_integral_value(); is_b_dec_final = isinstance(b, Decimal) and b != b.to_integral_value()\n", + " is_c_dec_final = isinstance(c_final, Decimal) and c_final != c_final.to_integral_value()\n", + " if is_a_dec_final or is_b_dec_final or is_c_dec_final: decimal_op_count += 1\n", + " else: integer_op_count += 1\n", + " output_buffer.append(pair_data)\n", + "\n", + " # --- 批量保存 ---\n", + " if len(output_buffer) >= batch_save_size:\n", + " write_start_time = time.time(); written_count = write_batch_to_jsonl(output_buffer, filename, mode='a'); write_duration = time.time() - write_start_time\n", + " if written_count > 0:\n", + " total_lines_written += written_count; avg_save_speed = written_count / write_duration if write_duration > 0 else float('inf')\n", + " print(f\"\\r--- 已保存批次 {written_count:>6,} (耗时 {write_duration:.2f}s, {avg_save_speed:.1f}/s). 总计写入: {total_lines_written:>8,} / 生成: {generated_count:>8,} ---{' '*5}\", end=\"\")\n", + " output_buffer.clear(); last_save_time = time.time()\n", + " else:\n", + " print(f\"\\n警告: 写入批处理失败 (gen_count={generated_count:,})。缓冲区已清空。\"); errors_in_loop += len(output_buffer); output_buffer.clear()\n", + "\n", + " except Exception as format_outer_e: errors_in_loop += 1; continue\n", + "\n", + " except KeyboardInterrupt: print(\"\\n用户中断。\"); break\n", + " except Exception as main_loop_e: errors_in_loop += 1; continue\n", + "\n", + " # --- 进度报告 ---\n", + " report_interval = max(1, total_samples // 200) if total_samples > 0 else 1000\n", + " now = time.time(); time_since_last_report_or_save = now - max(last_save_time, start_time_generate if last_reported_count == -1 else last_save_time)\n", + " if generated_count > 0 and (generated_count % report_interval == 0 or generated_count == total_samples or time_since_last_report_or_save > 15):\n", + " if last_reported_count != generated_count:\n", + " progress = generated_count / total_samples if total_samples > 0 else 0; elapsed_time = now - start_time_generate\n", + " samples_per_sec = generated_count / elapsed_time if elapsed_time > 0 else 0; attempts_per_sample = total_attempts / generated_count if generated_count > 0 else float('inf')\n", + " failure_rate = construct_failures / total_attempts if total_attempts > 0 else 0; est_rem_str = \"N/A\"\n", + " if progress > 1e-6 and samples_per_sec > 0:\n", + " remaining_samples = total_samples - generated_count; est_rem_sec = remaining_samples / samples_per_sec\n", + " if est_rem_sec < 60: est_rem_str = f\"{est_rem_sec:.0f}s\"\n", + " elif est_rem_sec < 3600: est_rem_str = f\"{est_rem_sec/60:.1f}m\"\n", + " else: est_rem_str = f\"{est_rem_sec/3600:.1f}h\"\n", + " stats_str = f\"生成: {generated_count:>8,}/{total_samples:<8,} ({progress:5.1%}) | 写入: {total_lines_written:>8,} | 尝试: {total_attempts:>9,} ({attempts_per_sample:5.1f}/样本) | 失败率: {failure_rate:5.1%} | {samples_per_sec:6.1f} 样本/秒 | 耗时: {elapsed_time:6.1f}s | 剩余: ~{est_rem_str:<5}\"\n", + " print(f\"\\r{stats_str.ljust(100)}\", end=\"\"); last_reported_count = generated_count; last_save_time = now\n", + "\n", + " # --- 循环结束后 ---\n", + " print(\" \" * 120, end=\"\\r\"); print(f\"\\n构造循环结束。目标: {total_samples:,}, 实际生成: {generated_count:,} (尝试 {total_attempts:,} 次, 构造失败 {construct_failures:,} 次).\")\n", + "\n", + " # --- 写入剩余数据 ---\n", + " if output_buffer:\n", + " print(f\"写入最后 {len(output_buffer):,} 条数据...\"); write_start = time.time()\n", + " final_written = write_batch_to_jsonl(output_buffer, filename, mode='a'); write_end = time.time()\n", + " if final_written > 0: total_lines_written += final_written; print(f\"最终批次写入完成 ({final_written:,} 条). 耗时: {write_end - write_start:.2f}s.\")\n", + " else: print(\"警告: 最终批次写入失败。\"); errors_in_loop += len(output_buffer)\n", + " output_buffer.clear()\n", + " else: print(\"无剩余数据需写入。\")\n", + "\n", + " # --- 结束日志和统计 ---\n", + " end_generate = time.time(); total_gen_time = end_generate - start_time_generate\n", + " print(f\"\\n生成与写入完毕。目标: {total_samples:,} -> 生成: {generated_count:,} -> 写入: {total_lines_written:,}\")\n", + " if total_lines_written != generated_count and generated_count > 0: print(f\"警告: 写入行数({total_lines_written:,}) 与 生成数({generated_count:,}) 不匹配!\")\n", + " attempts_per_actual = total_attempts / max(1, generated_count) if generated_count > 0 else float('inf')\n", + " failure_rate_overall = construct_failures / total_attempts if total_attempts > 0 else 0\n", + " print(f\"总尝试次数: {total_attempts:,} (平均 {attempts_per_actual:.2f} 次/有效样本)\")\n", + " print(f\"构造失败次数: {construct_failures:,} (失败率: {failure_rate_overall:.2%})\")\n", + " print(f\"总耗时: {total_gen_time:.2f} 秒。格式化/计算/写入错误: {errors_in_loop:,}.\")\n", + "\n", + " # --- 打印详细统计 ---\n", + " print(\"\\n\" + \"=\"*15 + \" 详细统计 (基于生成的有效样本) \" + \"=\"*15)\n", + " if generated_count > 0:\n", + " print(f\"总有效样本: {generated_count:,}\")\n", + " print(\"-\" * 50); print(\"1. 算术题类型:\"); print(f\" - 加法: {add_count:,} ({add_count/generated_count:.1%})\"); print(f\" - 减法: {subtract_count:,} ({subtract_count/generated_count:.1%})\")\n", + " print(\"-\" * 50); print(\"2. 运算数类型:\"); print(f\" - 纯整数运算*: {integer_op_count:,} ({integer_op_count/generated_count:.1%})\"); print(f\" - 含小数运算*: {decimal_op_count:,} ({decimal_op_count/generated_count:.1%})\"); print(\" *注: 基于输入或输出是否含小数部分。\")\n", + " print(\"-\" * 50); total_a_counts = sum(format_counts[k] for k in format_counts if k.startswith('a_')); print(f\"3. 问题格式 - 操作数 A (总计: {total_a_counts:,}):\")\n", + " a_order = ['a_standard', 'a_full_width', 'a_simple_zh', 'a_complex_zh']; [print(f\" - {fmt_key[2:]: <15}: {format_counts[fmt_key]:>10,} ({(format_counts[fmt_key] / total_a_counts * 100) if total_a_counts > 0 else 0:>6.1f}%)\") for fmt_key in a_order]\n", + " print(\"-\" * 50); total_b_counts = sum(format_counts[k] for k in format_counts if k.startswith('b_')); print(f\"4. 问题格式 - 操作数 B (总计: {total_b_counts:,}):\")\n", + " b_order = ['b_standard', 'b_full_width', 'b_simple_zh', 'b_complex_zh']; [print(f\" - {fmt_key[2:]: <15}: {format_counts[fmt_key]:>10,} ({(format_counts[fmt_key] / total_b_counts * 100) if total_b_counts > 0 else 0:>6.1f}%)\") for fmt_key in b_order]\n", + " print(\"-\" * 50); total_qtype_counts = sum(question_type_counts.values()); print(f\"5. 问题格式 - 类型 (总计: {total_qtype_counts:,}):\")\n", + " qtype_order = ['symbolic', 'natural_language'];\n", + " for qtype_key in qtype_order:\n", + " count = question_type_counts[qtype_key]; percent = count / total_qtype_counts * 100 if total_qtype_counts > 0 else 0\n", + " display_name = {'symbolic': '符号格式 (+/-)', 'natural_language': '自然语言格式 (多样化)'}.get(qtype_key, qtype_key)\n", + " print(f\" - {display_name: <22}: {count:>10,} ({percent:>6.1f}%)\")\n", + " print(\"-\" * 50); total_sym_suffix_counts = suffix_counts.get('symbolic_added', 0) + suffix_counts.get('symbolic_not_added', 0)\n", + " print(f\"6. 符号问题格式 - 等号后缀 (总计符号问题: {total_sym_suffix_counts:,}):\")\n", + " suffix_order = ['symbolic_added', 'symbolic_not_added'];\n", + " for sfx_key in suffix_order:\n", + " count = suffix_counts[sfx_key]; percent = count / total_sym_suffix_counts * 100 if total_sym_suffix_counts > 0 else 0\n", + " display_name = {'symbolic_added': '添加 \" = ?/?\"', 'symbolic_not_added': '未添加后缀'}.get(sfx_key, sfx_key)\n", + " print(f\" - {display_name: <18}: {count:>10,} ({percent:>6.1f}%)\")\n", + " print(\"=\"*50)\n", + " else: print(\"\\n--- 未生成有效样本,无详细统计 ---\"); print(\"=\"*50)\n", + "\n", + "# ===============================================\n", + "# 主程序入口\n", + "# ===============================================\n", + "if __name__ == \"__main__\":\n", + " total_start_time = time.time()\n", + " print(\"=\"*30); print(\" 算术题生成脚本 (v10.6) \"); print(\"=\"*30) # 更新版本号\n", + "\n", + " # --- 预检查条件 ---\n", + " max_possible_dig = MAX_DIGITS + MAX_DECIMAL_PLACES\n", + " if max_possible_dig <= 0: print(\"!!! 配置错误: MAX_DIGITS 和 MAX_DECIMAL_PLACES 必须至少有一个大于0。\"); exit()\n", + " max_possible_cb = MAX_DIGITS + MAX_DECIMAL_PLACES + (1 if MAX_DECIMAL_PLACES > 0 else 0)\n", + " if TARGET_TOTAL_CARRIES_MAX != math.inf and TARGET_TOTAL_CARRIES_MIN > max_possible_cb: print(f\"\\n!!! 配置警告: 目标最小总数({TARGET_TOTAL_CARRIES_MIN}) > 估算最大可能({max_possible_cb})。可能无法构造。 !!!\")\n", + " if TARGET_CONSECUTIVE_CARRIES_MAX != math.inf and TARGET_CONSECUTIVE_CARRIES_MIN > max_possible_cb: print(f\"\\n!!! 配置警告: 目标最小连续数({TARGET_CONSECUTIVE_CARRIES_MIN}) > 估算最大可能({max_possible_cb})。可能无法构造。 !!!\")\n", + " if TARGET_TOTAL_CARRIES_MAX != 0 and TARGET_CONSECUTIVE_CARRIES_MIN > TARGET_TOTAL_CARRIES_MIN: print(f\"\\n!!! 配置提示: 目标最小连续数({TARGET_CONSECUTIVE_CARRIES_MIN}) > 目标最小总数({TARGET_TOTAL_CARRIES_MIN})。\")\n", + "\n", + " try:\n", + " # 调用主生成函数, 传入新的概率参数名\n", + " generate_constructed_arithmetic_diverse(\n", + " filename=OUTPUT_FILENAME,\n", + " total_samples=TOTAL_SAMPLES,\n", + " add_prob=ADD_PROBABILITY,\n", + " decimal_prob=DECIMAL_PROBABILITY,\n", + " max_digits_limit=MAX_DIGITS,\n", + " max_decimal_places=MAX_DECIMAL_PLACES,\n", + " negative_pool_prob=NEGATIVE_POOL_PROB,\n", + " target_total_cb_min=TARGET_TOTAL_CARRIES_MIN,\n", + " target_total_cb_max=TARGET_TOTAL_CARRIES_MAX,\n", + " target_consecutive_cb_min=TARGET_CONSECUTIVE_CARRIES_MIN,\n", + " target_consecutive_cb_max=TARGET_CONSECUTIVE_CARRIES_MAX,\n", + " nl_question_prob=NL_QUESTION_PROBABILITY, # 使用新概率名\n", + " symbolic_equals_suffix_prob=SYMBOLIC_EQUALS_SUFFIX_PROB, # 使用新概率名\n", + " max_attempts_factor=MAX_ATTEMPTS_FACTOR,\n", + " batch_save_size=BATCH_SAVE_SIZE\n", + " )\n", + " except ValueError as ve: print(f\"\\n配置错误: {ve}\"); traceback.print_exc()\n", + " except MemoryError: print(\"\\n内存错误: 尝试减少 BATCH_SAVE_SIZE 或 TOTAL_SAMPLES。\"); traceback.print_exc()\n", + " except Exception as main_e: print(f\"\\n主程序发生未预料错误: {main_e}\"); traceback.print_exc()\n", + " finally: pass\n", + "\n", + " total_end_time = time.time()\n", + " print(\"\\n\" + \"=\"*30); print(f\"脚本执行完毕。总耗时: {total_end_time - total_start_time:.2f} 秒。\"); print(f\"数据文件: {OUTPUT_FILENAME}\"); print(\"=\"*30)" + ] + }, + { + "cell_type": "markdown", + "id": "2d25fc7c", + "metadata": {}, + "source": [ + "# 逐位随机进行数字简繁体替换\n", + "\n", + "用于生成:\n", + "\n", + "训练:ADD_random_0.25M 和 ADD_random_4M \n", + "\n", + "测试:ADD_random_test\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "278311e2", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "==============================\n", + " 算术题生成脚本 (v10.10) \n", + "==============================\n", + "--- 开始生成算术数据 (v10.10 - Intra-Character Spacing) ---\n", + "中文数字内字符样式随机化已启用。\n", + "中文逐位念读已启用 (概率: 30.0%).\n", + "字符间随机空格已启用。\n", + "通用字符级损坏未启用。\n", + "已初始化/清空输出文件: 'qa_add-逐位随机_中英混合.jsonl'\n", + "\n", + "开始构造 2,500 条满足条件的数据...\n", + "生成: 2,500/2,500 (100.0%) | 写入: 2,500 | 尝试: 2,500 ( 1.0/样本) | 失败率: 0.0% | 6900.3 样本/秒 | 耗时: 0.4s | 剩余: ~0s \n", + "构造循环结束。目标: 2,500, 实际生成: 2,500 (尝试 2,500 次, 构造失败 0 次).\n", + "无剩余数据需写入.\n", + "\n", + "生成与写入完毕。目标: 2,500 -> 生成: 2,500 -> 写入: 2,500\n", + "总尝试次数: 2,500 (平均 1.00 次/有效样本)\n", + "构造失败次数: 0 (失败率: 0.00%)\n", + "总耗时: 0.36 秒。格式化/计算/写入等循环内错误: 0.\n", + "\n", + "=============== 详细统计 (基于生成的有效样本) ===============\n", + "总有效样本: 2,500\n", + "--------------------------------------------------\n", + "1. 算术题类型:\n", + " - 加法: 1,272 ( 50.9%)\n", + " - 减法: 1,228 ( 49.1%)\n", + "--------------------------------------------------\n", + "2. 运算数类型:\n", + " - 纯整数运算*: 1,485 ( 59.4%)\n", + " - 含小数运算*: 1,015 ( 40.6%)\n", + " *注: 基于操作数或结果是否包含实际小数部分,或生成意图是否为小数。\n", + "--------------------------------------------------\n", + "3. 问题格式 - 操作数 A (总计: 2,500):\n", + " - standard : 478 ( 19.1%)\n", + " - full_width : 521 ( 20.8%)\n", + " - simple_zh : 755 ( 30.2%)\n", + " - complex_zh : 746 ( 29.8%)\n", + "--------------------------------------------------\n", + "4. 问题格式 - 操作数 B (总计: 2,500):\n", + " - standard : 491 ( 19.6%)\n", + " - full_width : 515 ( 20.6%)\n", + " - simple_zh : 724 ( 29.0%)\n", + " - complex_zh : 770 ( 30.8%)\n", + "--------------------------------------------------\n", + "5. 问题格式 - 类型 (总计: 2,500):\n", + " - 符号格式 (+/-) : 2,379 ( 95.2%)\n", + " - 自然语言格式 : 121 ( 4.8%)\n", + "--------------------------------------------------\n", + "6. 符号问题格式 - 等号后缀 (总计符号问题: 2,379):\n", + " - 添加 \" = ?/?\" : 1,145 ( 48.1%)\n", + " - 未添加后缀 : 1,234 ( 51.9%)\n", + "==================================================\n", + "\n", + "==============================\n", + "脚本执行完毕。总耗时: 0.36 秒。\n", + "数据文件: qa_add-逐位随机_中英混合.jsonl\n", + "==============================\n" + ] + } + ], + "source": [ + "# -*- coding: utf-8 -*-\n", + "# 生成满足指定进/借位范围条件,且问题格式多样化的算术问题数据集脚本。\n", + "# 采用反向逐位构造方法优化生成效率。\n", + "# v10.10: Add random intra-character spacing for numbers in question.\n", + "\n", + "import json\n", + "import random\n", + "import time\n", + "import math\n", + "from typing import List, Tuple, Union, Dict, Optional, Callable\n", + "from decimal import Decimal, getcontext, ROUND_DOWN, ROUND_HALF_UP, InvalidOperation\n", + "import traceback\n", + "from collections import Counter\n", + "import string\n", + "\n", + "# ===============================================\n", + "# 配置参数区域\n", + "# ===============================================\n", + "# --- 主要数量和文件名 ---\n", + "TOTAL_SAMPLES = 2500\n", + "OUTPUT_FILENAME = f\"ADD_random_0.25M.jsonl\"\n", + "ADD_PROBABILITY: float = 0.5\n", + "BATCH_SAVE_SIZE: int = 20\n", + "\n", + "# --- 数字生成控制 ---\n", + "MAX_DIGITS: int = 12\n", + "MAX_DECIMAL_PLACES: int = 5\n", + "DECIMAL_PROBABILITY: float = 0.4\n", + "NEGATIVE_POOL_PROB: float = 0.1\n", + "SCI_THRESHOLD_POS = 100\n", + "SCI_THRESHOLD_NEG = -30\n", + "\n", + "# --- 进/借位条件范围 ---\n", + "TARGET_TOTAL_CARRIES_MIN: int = 0\n", + "TARGET_TOTAL_CARRIES_MAX: int = math.inf\n", + "TARGET_CONSECUTIVE_CARRIES_MIN: int = 0\n", + "TARGET_CONSECUTIVE_CARRIES_MAX: int = math.inf\n", + "\n", + "# --- 格式化控制 (问题部分数字的样式) ---\n", + "STANDARD_ARABIC_PROB: float = 0.20\n", + "FULL_WIDTH_ARABIC_PROB: float = 0.20\n", + "SIMPLE_CHINESE_PROB: float = 0.30\n", + "COMPLEX_CHINESE_PROB: float = 0.30\n", + "_format_prob_sum = STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB + SIMPLE_CHINESE_PROB + COMPLEX_CHINESE_PROB\n", + "if not math.isclose(_format_prob_sum, 1.0):\n", + " raise ValueError(f\"数字格式概率总和必须为 1.0,当前为: {_format_prob_sum}\")\n", + "\n", + "# --- 中文数字内字符随机化控制 (v10.8 功能) ---\n", + "RANDOMIZE_DIGITS_WITHIN_CHINESE_NUMBERS: bool = True\n", + "\n", + "# --- 中文逐位念读控制 (v10.9 功能) ---\n", + "CHINESE_DIGIT_BY_DIGIT_READING_PROB: float = 0.3\n", + "\n", + "# --- 新增:字符间随机空格控制 (应用于问题中的操作数) ---\n", + "APPLY_INTRA_CHAR_SPACING: bool = True # 是否启用字符间随机空格\n", + "# 定义 (空格数量, 概率) 的列表。概率和应为1。\n", + "INTRA_CHAR_SPACING_CONFIG: List[Tuple[int, float]] = [\n", + " (0, 0.97), # 0个空格的概率\n", + " (1, 0.02), # 1个空格的概率\n", + " (2, 0.01) # 2个空格的概率\n", + "]\n", + "# 校验 INTRA_CHAR_SPACING_CONFIG 概率和\n", + "_intra_space_prob_sum = sum(p for _, p in INTRA_CHAR_SPACING_CONFIG)\n", + "if not math.isclose(_intra_space_prob_sum, 1.0):\n", + " raise ValueError(f\"INTRA_CHAR_SPACING_CONFIG 的概率总和必须为 1.0,当前为: {_intra_space_prob_sum}\")\n", + "\n", + "# --- 自然语言概率控制 ---\n", + "NL_QUESTION_PROBABILITY: float = 0.30\n", + "\n", + "# --- 等号后缀概率控制 (仅符号问题) ---\n", + "SYMBOLIC_EQUALS_SUFFIX_PROB: float = 0.50\n", + "\n", + "# --- 字符级随机替换控制 (通用,应用于最终文本 - v10.7 功能) ---\n", + "APPLY_GENERAL_CHAR_REPLACEMENT: bool = False\n", + "GENERAL_CHAR_REPLACEMENT_PROBABILITY: float = 0.005\n", + "GENERAL_CHAR_REPLACEMENT_POOL: str = string.ascii_letters + string.digits + \".,?! \"\n", + "\n", + "# --- 其他控制 ---\n", + "MAX_ATTEMPTS_FACTOR = 5000\n", + "\n", + "# ===============================================\n", + "# 核心代码\n", + "# ===============================================\n", + "getcontext().prec = MAX_DIGITS + MAX_DECIMAL_PLACES + 30\n", + "\n", + "CHINESE_DIGIT_LOOKUP = {\n", + " '零': '0', '一': '1', '二': '2', '两': '2', '三': '3', '四': '4', '五': '5', '六': '6', '七': '7', '八': '8', '九': '9',\n", + " '壹': '1', '贰': '2', '貳': '2', '叁': '3', '參': '3', '肆': '4', '伍': '5', '陆': '6', '陸': '6', '柒': '7', '捌': '8', '玖': '9'\n", + "}\n", + "POSSIBLE_DIGIT_REPRESENTATIONS = {\n", + " '0': ['0', '0', '零', '零'], '1': ['1', '1', '一', '壹'], '2': ['2', '2', '二', '贰'],\n", + " '3': ['3', '3', '三', '叁'], '4': ['4', '4', '四', '肆'], '5': ['5', '5', '五', '伍'],\n", + " '6': ['6', '6', '六', '陆'], '7': ['7', '7', '七', '柒'], '8': ['8', '8', '八', '捌'],\n", + " '9': ['9', '9', '九', '玖'],\n", + "}\n", + "\n", + "digit_map_simple = {'0': '零', '1': '一', '2': '二', '3': '三', '4': '四', '5': '五', '6': '六', '7': '七', '8': '八', '9': '九'}\n", + "unit_map_section_simple = ['', '十', '百', '千']\n", + "unit_map_large_simple = ['', '万', '亿', '兆']\n", + "digit_map_complex = {'0': '零', '1': '壹', '2': '贰', '3': '叁', '4': '肆', '5': '伍', '6': '陆', '7': '柒', '8': '捌', '9': '玖'}\n", + "unit_map_section_complex = ['', '拾', '佰', '仟']\n", + "unit_map_large_complex = ['', '萬', '億', '兆']\n", + "\n", + "# --- 之前版本的中文转换函数等 ---\n", + "# _convert_section, num_to_chinese, decimal_to_chinese, _decimal_to_chinese_scientific\n", + "# _randomize_digits_in_chinese_string, _decimal_to_chinese_digit_by_digit\n", + "# to_full_width, format_decimal_or_int\n", + "# (这些函数与 v10.9 基本相同,为简洁省略,实际代码中应保留它们)\n", + "# ... (v10.9 的这些函数实现) ...\n", + "def _convert_section(section_str: str, complex_form: bool = False) -> str:\n", + " digit_map = digit_map_complex if complex_form else digit_map_simple\n", + " unit_map_section = unit_map_section_complex if complex_form else unit_map_section_simple\n", + " if not section_str: return \"\"\n", + " try: section_int = int(section_str)\n", + " except ValueError: return \"无效输入\"\n", + " if section_int == 0: return digit_map['0']\n", + " chinese_s = \"\"; length = len(section_str); need_zero = False\n", + " for i in range(length):\n", + " digit_char = section_str[i]; place_value_idx = length - 1 - i\n", + " if digit_char == '0': need_zero = True\n", + " else:\n", + " if need_zero and chinese_s and not chinese_s.endswith(digit_map['0']): chinese_s += digit_map['0']\n", + " need_zero = False; current_digit_chinese = \"\"\n", + " if not complex_form and digit_char == '2':\n", + " is_leading_two_and_high_place = (i == 0 and place_value_idx >= 2)\n", + " is_leading_two_in_ten = (i == 0 and place_value_idx == 1 and length > 1)\n", + " if (is_leading_two_and_high_place or is_leading_two_in_ten) and random.random() < 0.7: current_digit_chinese = '两'\n", + " else: current_digit_chinese = digit_map['2']\n", + " else: current_digit_chinese = digit_map[digit_char]\n", + " is_leading_one_in_ten_place = (not complex_form and digit_char == '1' and place_value_idx == 1 and i == 0 and length > 1)\n", + " if is_leading_one_in_ten_place and length == 2 : chinese_s += unit_map_section[place_value_idx]\n", + " else: chinese_s += current_digit_chinese + unit_map_section[place_value_idx]\n", + " if chinese_s.endswith(digit_map['0']) and len(chinese_s) > len(digit_map['0']): chinese_s = chinese_s[:-len(digit_map['0'])]\n", + " if not complex_form and chinese_s == digit_map_simple['1'] + unit_map_section_simple[1]: chinese_s = unit_map_section_simple[1]\n", + " return chinese_s\n", + "\n", + "def num_to_chinese(num: int, complex_form: bool = False) -> str:\n", + " if not isinstance(num, int): return \"无效输入\"\n", + " digit_map = digit_map_complex if complex_form else digit_map_simple\n", + " unit_map_large = unit_map_large_complex if complex_form else unit_map_large_simple\n", + " negative_word = \"负\"\n", + " if num == 0: return digit_map['0']\n", + " if num < 0: return negative_word + num_to_chinese(abs(num), complex_form)\n", + " s_num = str(num)\n", + " if len(s_num) > 50: return \"数字过大无法转换\"\n", + " result_chinese = \"\"; sections_str_list = []\n", + " current_idx = len(s_num)\n", + " while current_idx > 0:\n", + " start_idx = max(0, current_idx - 4)\n", + " sections_str_list.append(s_num[start_idx:current_idx])\n", + " current_idx -= 4\n", + " sections_str_list.reverse()\n", + " last_section_was_zero = False; num_sections = len(sections_str_list)\n", + " for i, section_s in enumerate(sections_str_list):\n", + " section_val = int(section_s); large_unit_idx = num_sections - 1 - i\n", + " if section_val == 0:\n", + " last_section_was_zero = True\n", + " if result_chinese and not result_chinese.endswith(digit_map['0']) and \\\n", + " large_unit_idx > 0 and (i + 1 < num_sections and int(sections_str_list[i+1]) != 0):\n", + " result_chinese += digit_map['0']\n", + " continue\n", + " if last_section_was_zero and result_chinese and not result_chinese.endswith(digit_map['0']):\n", + " result_chinese += digit_map['0']\n", + " section_chinese_str = _convert_section(section_s, complex_form)\n", + " result_chinese += section_chinese_str\n", + " if large_unit_idx > 0: result_chinese += unit_map_large[large_unit_idx]\n", + " last_section_was_zero = False\n", + " return result_chinese if result_chinese else digit_map['0']\n", + "\n", + "def decimal_to_chinese(num: Decimal, complex_form: bool = False) -> str:\n", + " if not isinstance(num, Decimal): return \"无效输入\"\n", + " if not num.is_finite(): return \"无效输入\"\n", + " digit_map = digit_map_complex if complex_form else digit_map_simple\n", + " point_word = \"点\" if not complex_form else \"點\"; negative_word = \"负\"\n", + " if num.is_zero() and num.is_signed(): num = Decimal('0')\n", + " try:\n", + " int_val_test = num.to_integral_value(rounding=ROUND_DOWN)\n", + " if num == int_val_test:\n", + " if abs(num).adjusted() >= MAX_DIGITS + 10 : return \"数字过大无法转换\"\n", + " return num_to_chinese(int(num), complex_form)\n", + " except (ValueError, TypeError, OverflowError, InvalidOperation): return \"无效输入或溢出\"\n", + " if num < 0: return negative_word + decimal_to_chinese(abs(num), complex_form)\n", + " s_num = format_decimal_or_int(num)\n", + " if s_num in [\"Infinity\", \"-Infinity\", \"NaN\", \"无效输入\", \"无效输入或溢出\"]: return \"无效输入\"\n", + " if '.' not in s_num:\n", + " try:\n", + " num_int_again = int(s_num)\n", + " if abs(Decimal(s_num)).adjusted() >= MAX_DIGITS + 10: return \"数字过大无法转换\"\n", + " return num_to_chinese(num_int_again, complex_form)\n", + " except (ValueError, OverflowError): return \"无效输入或溢出\"\n", + " integer_part_str, fractional_part_str = s_num.split('.', 1)\n", + " chinese_int_part = \"\"\n", + " if integer_part_str == '0': chinese_int_part = digit_map['0']\n", + " else:\n", + " try:\n", + " int_val = int(integer_part_str)\n", + " if abs(Decimal(integer_part_str)).adjusted() >= MAX_DIGITS + 10: return \"数字过大无法转换\"\n", + " chinese_int_part = num_to_chinese(int_val, complex_form)\n", + " if chinese_int_part == \"无效输入\": return \"无效输入\"\n", + " except (ValueError, OverflowError): return \"无效输入或溢出\"\n", + " chinese_frac_part = \"\".join(digit_map.get(d, '?') for d in fractional_part_str if d.isdigit())\n", + " if not fractional_part_str: return chinese_int_part\n", + " if not chinese_frac_part and fractional_part_str: return chinese_int_part\n", + " if integer_part_str == '0' and chinese_int_part == digit_map['0']:\n", + " return f\"{digit_map['0']}{point_word}{chinese_frac_part}\"\n", + " else: return f\"{chinese_int_part}{point_word}{chinese_frac_part}\"\n", + "\n", + "def _decimal_to_chinese_scientific(num: Decimal, complex_form: bool = False) -> str:\n", + " if not isinstance(num, Decimal): return \"无效输入\"\n", + " if not num.is_finite(): return \"无效输入\"\n", + " digit_map_loc = digit_map_complex if complex_form else digit_map_simple\n", + " if num.is_zero(): return digit_map_loc['0']\n", + " sign_prefix = \"\"; negative_word = \"负\"\n", + " if num < 0: sign_prefix = negative_word; num = abs(num)\n", + " try:\n", + " sci_str = \"{:e}\".format(num.normalize()); parts = sci_str.lower().split('e')\n", + " if len(parts) != 2: return \"科学计数法解析失败\"\n", + " coeff_str, exp_str = parts[0], parts[1]\n", + " coeff_dec = Decimal(coeff_str); exp_int = int(exp_str)\n", + " coeff_chinese = decimal_to_chinese(coeff_dec, complex_form)\n", + " if \"无效\" in coeff_chinese or \"过大\" in coeff_chinese or \"失败\" in coeff_chinese: return coeff_chinese\n", + " exp_chinese = num_to_chinese(exp_int, complex_form)\n", + " if \"无效\" in exp_chinese or \"过大\" in exp_chinese: return exp_chinese\n", + " times_word = \"乘以十的\"; power_word = \"次方\"\n", + " return f\"{sign_prefix}{coeff_chinese}{times_word}{exp_chinese}{power_word}\"\n", + " except (ValueError, IndexError, TypeError, InvalidOperation): return \"转换科学计数法出错\"\n", + " except Exception: return \"转换科学计数法出错\"\n", + "\n", + "def _randomize_digits_in_chinese_string(pure_chinese_str: str) -> str:\n", + " if not RANDOMIZE_DIGITS_WITHIN_CHINESE_NUMBERS or not pure_chinese_str: return pure_chinese_str\n", + " result_chars = []\n", + " for char_cn in pure_chinese_str:\n", + " if char_cn in CHINESE_DIGIT_LOOKUP:\n", + " canonical_digit_arabic = CHINESE_DIGIT_LOOKUP[char_cn]\n", + " chosen_representation = random.choice(POSSIBLE_DIGIT_REPRESENTATIONS[canonical_digit_arabic])\n", + " result_chars.append(chosen_representation)\n", + " else: result_chars.append(char_cn)\n", + " return \"\".join(result_chars)\n", + "\n", + "def _decimal_to_chinese_digit_by_digit(num: Decimal, complex_form: bool = False) -> str:\n", + " if not isinstance(num, Decimal): return \"无效输入\"\n", + " if not num.is_finite(): return \"无效输入\"\n", + " s_num = format_decimal_or_int(num)\n", + " if s_num in [\"Infinity\", \"-Infinity\", \"NaN\", \"无效输入\", \"无效输入或溢出\"]: return \"无效输入\"\n", + " target_digit_map = digit_map_complex if complex_form else digit_map_simple\n", + " point_word = \"点\" if not complex_form else \"點\"; negative_word = \"负\"\n", + " result_chinese_chars = []\n", + " if s_num.startswith('-'): result_chinese_chars.append(negative_word); s_num = s_num[1:]\n", + " for char_digit in s_num:\n", + " if char_digit.isdigit(): result_chinese_chars.append(target_digit_map.get(char_digit, '?'))\n", + " elif char_digit == '.': result_chinese_chars.append(point_word)\n", + " else: result_chinese_chars.append(char_digit)\n", + " return \"\".join(result_chinese_chars)\n", + "\n", + "half_to_full_map = str.maketrans(\"0123456789.-+\", \"0123456789.-+\")\n", + "def to_full_width(text: str) -> str: return text.translate(half_to_full_map)\n", + "def format_decimal_or_int(num: Union[int, Decimal]) -> str:\n", + " try:\n", + " if isinstance(num, int): return str(num)\n", + " if isinstance(num, Decimal):\n", + " if not num.is_finite(): return str(num)\n", + " s = num.to_eng_string();\n", + " if '.' in s: s = s.rstrip('0').rstrip('.')\n", + " if '.' not in s and len(s) > 1 and s.startswith('0'): s = s.lstrip('0')\n", + " if not s: s = \"0\";\n", + " if s == \"-0\": s = \"0\"\n", + " return s\n", + " return str(num)\n", + " except Exception:\n", + " try:\n", + " normalized_num = Decimal(str(num)).normalize(); temp_s = \"{:f}\".format(normalized_num)\n", + " if '.' in temp_s: temp_s = temp_s.rstrip('0').rstrip('.')\n", + " if not temp_s: temp_s = \"0\";\n", + " if temp_s == \"-0\": temp_s = \"0\"\n", + " return temp_s\n", + " except: return str(num)\n", + "\n", + "# --- 新增:字符间随机空格函数 ---\n", + "_intra_space_num_list = [s[0] for s in INTRA_CHAR_SPACING_CONFIG]\n", + "_intra_space_prob_list = [s[1] for s in INTRA_CHAR_SPACING_CONFIG]\n", + "\n", + "def _insert_random_intra_char_spacing(text: str) -> str:\n", + " \"\"\"在字符串的字符间随机插入空格。\"\"\"\n", + " if not text or not APPLY_INTRA_CHAR_SPACING or len(text) <= 1:\n", + " return text\n", + "\n", + " new_string_parts = [text[0]] # 第一个字符先放进去\n", + " for i in range(len(text) - 1):\n", + " # 决定在 text[i] 和 text[i+1] 之间插入多少空格\n", + " num_spaces = random.choices(_intra_space_num_list, weights=_intra_space_prob_list, k=1)[0]\n", + " if num_spaces > 0:\n", + " new_string_parts.append(\" \" * num_spaces)\n", + " new_string_parts.append(text[i+1]) # 添加下一个字符\n", + " \n", + " return \"\".join(new_string_parts)\n", + "# --- 结束新增函数 ---\n", + "\n", + "\n", + "def format_number_variant(num: Union[int, Decimal]) -> Tuple[str, str]:\n", + " \"\"\"\n", + " (v10.10) 核心数字格式化函数。\n", + " 包括标准、全角、中文(标准带单位、逐位念读)、中文科学计数法。\n", + " 中文结果会经过内部数字样式随机化(如果启用)。\n", + " 最终结果(操作数)会经过字符间随机空格处理(如果启用)。\n", + " \"\"\"\n", + " fmt_choice = random.random()\n", + " try:\n", + " num_dec = Decimal(str(num)) if not isinstance(num, Decimal) else num\n", + " except InvalidOperation: return str(num), 'standard'\n", + "\n", + " target_format_name = 'standard'\n", + " if fmt_choice < STANDARD_ARABIC_PROB: target_format_name = 'standard'\n", + " elif fmt_choice < STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB: target_format_name = 'full_width'\n", + " elif fmt_choice < STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB + SIMPLE_CHINESE_PROB: target_format_name = 'simple_zh'\n", + " else: target_format_name = 'complex_zh'\n", + "\n", + " # --- 内部函数,用于处理最终的字符串修饰(字符间空格) ---\n", + " def finalize_output(s: str, fmt_name: str) -> Tuple[str, str]:\n", + " final_s = _insert_random_intra_char_spacing(s) # 应用字符间空格\n", + " return final_s, fmt_name\n", + " # --- 结束内部函数 ---\n", + "\n", + " try:\n", + " if not num_dec.is_finite():\n", + " s_num_non_finite = str(num_dec)\n", + " res_str = to_full_width(s_num_non_finite) if target_format_name == 'full_width' else s_num_non_finite\n", + " return finalize_output(res_str, 'full_width' if target_format_name == 'full_width' else 'standard')\n", + "\n", + " s_formatted_arabic = format_decimal_or_int(num_dec)\n", + "\n", + " if target_format_name == 'standard':\n", + " return finalize_output(s_formatted_arabic, 'standard')\n", + " elif target_format_name == 'full_width':\n", + " return finalize_output(to_full_width(s_formatted_arabic), 'full_width')\n", + " else: # simple_zh or complex_zh\n", + " is_complex_chinese = (target_format_name == 'complex_zh')\n", + " pure_chinese_output_str = \"\"\n", + " \n", + " exponent = num_dec.normalize().adjusted()\n", + " use_sci_chinese = (exponent >= SCI_THRESHOLD_POS or exponent <= SCI_THRESHOLD_NEG)\n", + "\n", + " if use_sci_chinese:\n", + " pure_chinese_output_str = _decimal_to_chinese_scientific(num_dec, complex_form=is_complex_chinese)\n", + " else:\n", + " use_digit_by_digit_reading = (random.random() < CHINESE_DIGIT_BY_DIGIT_READING_PROB)\n", + " if use_digit_by_digit_reading:\n", + " pure_chinese_output_str = _decimal_to_chinese_digit_by_digit(num_dec, complex_form=is_complex_chinese)\n", + " else:\n", + " pure_chinese_output_str = decimal_to_chinese(num_dec, complex_form=is_complex_chinese)\n", + " \n", + " if pure_chinese_output_str in [\"无效输入\", \"无效输入或溢出\", \"数字过大无法转换\", \"科学计数法解析失败\", \"转换科学计数法出错\"]:\n", + " return finalize_output(s_formatted_arabic, 'standard')\n", + "\n", + " final_mixed_chinese_output = _randomize_digits_in_chinese_string(pure_chinese_output_str)\n", + " return finalize_output(final_mixed_chinese_output, target_format_name)\n", + " \n", + " except Exception as e_format_logic:\n", + " try:\n", + " fallback_str = format_decimal_or_int(num_dec if 'num_dec' in locals() else num)\n", + " return finalize_output(fallback_str, 'standard')\n", + " except:\n", + " return finalize_output(str(num), 'standard') # 绝对回退\n", + "\n", + "\n", + "# --- get_realistic_spacing, contains_arabic_numerals, get_distributed_count_from_probs, calculate_digit_probabilities ---\n", + "# --- format_natural_language_question, _generate_pair_meeting_cb_criteria, check_carries_borrows ---\n", + "# --- write_batch_to_jsonl, randomly_replace_characters_in_string (v10.7) ---\n", + "# (这些函数与 v10.9 基本相同,为简洁省略,实际代码中应保留它们)\n", + "# ... (v10.9 的这些函数实现) ...\n", + "def get_realistic_spacing() -> str:\n", + " space_values = [\"\", \" \", \" \"]; space_weights = [99.5, 0.4, 0.1]\n", + " if not math.isclose(sum(space_weights), 100.0): print(\"警告:get_realistic_spacing 中的空格权重和不为 100。\"); return \"\"\n", + " try: return random.choices(space_values, weights=space_weights, k=1)[0]\n", + " except Exception as e: print(f\"警告:生成空格时出错: {e}。默认为无空格。\"); return \"\"\n", + "def contains_arabic_numerals(s: str) -> bool: return any(c in \"01234567890123456789\" for c in s)\n", + "def get_distributed_count_from_probs(population: List[int], probabilities: List[float]) -> int:\n", + " if not population: return 1\n", + " if not probabilities or len(population) != len(probabilities) or not all(p >= 0 for p in probabilities): print(\"警告:get_distributed_count_from_probs population/probabilities 无效。\"); return random.choice(population) if population else 1\n", + " prob_sum = sum(probabilities);\n", + " if prob_sum < 1e-9: print(\"警告:概率和接近于零。\"); return random.choice(population) if population else 1\n", + " normalized_probabilities = probabilities\n", + " if not math.isclose(prob_sum, 1.0, abs_tol=1e-5):\n", + " try: normalized_probabilities = [p / prob_sum for p in probabilities]\n", + " except ZeroDivisionError: print(\"警告:概率归一化 ZeroDivisionError。\"); return random.choice(population) if population else 1\n", + " try: return random.choices(population, weights=normalized_probabilities, k=1)[0]\n", + " except Exception as e: print(f\"random.choices 执行出错: {e}。\"); return random.choice(population) if population else 1\n", + "def calculate_digit_probabilities(max_digits: int) -> Dict[int, float]:\n", + " if max_digits <= 0: return {1: 1.0}\n", + " raw_probs = {}; prob_sum = Decimal('0.0'); base_prob = Decimal('0.1'); decay_factor = Decimal('0.95'); increase_factor = Decimal('1.05')\n", + " for n in range(1, max_digits + 1):\n", + " prob = base_prob * (decay_factor**(n - 1)) * (increase_factor**(max_digits - n + 1)); prob = max(Decimal('0.001'), prob); raw_probs[n] = prob; prob_sum += prob\n", + " normalized_probs = {}\n", + " if prob_sum <= 0: fallback_prob = 1.0 / max(1, max_digits); normalized_probs = {n: fallback_prob for n in range(1, max_digits + 1)}\n", + " else: normalized_probs = {n: float(p / prob_sum) for n, p in raw_probs.items()}\n", + " final_sum = sum(normalized_probs.values())\n", + " if not math.isclose(final_sum, 1.0, abs_tol=1e-9):\n", + " renorm_factor = 1.0 / final_sum if final_sum != 0 else 1.0; total = 0.0; keys = sorted(normalized_probs.keys())\n", + " for i, n_key in enumerate(keys):\n", + " if i == len(keys) - 1: normalized_probs[n_key] = max(0.0, 1.0 - total)\n", + " else: norm_p = max(0.0, normalized_probs[n_key] * renorm_factor); normalized_probs[n_key] = norm_p; total += norm_p\n", + " if keys: normalized_probs[keys[-1]] = max(0.0, normalized_probs[keys[-1]])\n", + " return normalized_probs\n", + "def format_natural_language_question(fmt_a: str, fmt_b: str, op_sym: str) -> str:\n", + " add_words = [\"加\", \"加上\", \"和\", \"的总和是\", \"一共是\"]; subtract_words = [\"减\", \"减去\", \"减掉\", \"与...的差是\", \"少了\"]\n", + " result_phrases = [\"等于多少\", \"是多少\", \"结果是\", \"等于几\", \"得多少\", \"是多少呢\"]; question_marks = [\"?\", \"?\", \"\"]\n", + " templates = []\n", + " if op_sym == '+':\n", + " op_words = add_words\n", + " templates.extend([\"{num_a} {op} {num_b} {res}{q_mark}\", \"计算一下 {num_a} {op} {num_b}{q_mark}\", \"请问 {num_a} {op} {num_b} {res}{q_mark}\", \"{num_a} 与 {num_b} 的和是多少{q_mark}\", \"{num_a} {op} {num_b} 等于?\", \"{num_a} 再 {op} {num_b} {res}{q_mark}\", \"帮我算算 {num_a} {op} {num_b} 的结果{q_mark}\"])\n", + " elif op_sym == '-':\n", + " op_words = subtract_words\n", + " templates.extend([\"{num_a} {op} {num_b} {res}{q_mark}\", \"计算一下 {num_a} {op} {num_b}{q_mark}\", \"请问 {num_a} {op} {num_b} {res}{q_mark}\", \"{num_a} 与 {num_b} 的差是多少{q_mark}\", \"{num_a} {op} {num_b} 等于?\", \"{num_a} {op} {num_b} 还剩多少{q_mark}\", \"帮我算算 {num_a} {op} {num_b} {res}{q_mark}\"])\n", + " else: return f\"{fmt_a} {op_sym} {fmt_b}\"\n", + " chosen_template = random.choice(templates); chosen_op_word = random.choice(op_words)\n", + " try:\n", + " if \"{res}\" in chosen_template: question_str = chosen_template.format(num_a=fmt_a, num_b=fmt_b, op=chosen_op_word, res=random.choice(result_phrases), q_mark=random.choice(question_marks))\n", + " else: question_str = chosen_template.format(num_a=fmt_a, num_b=fmt_b, op=chosen_op_word, q_mark=random.choice(question_marks))\n", + " question_str = ' '.join(question_str.split())\n", + " except KeyError as e: question_str = f\"{fmt_a} {op_sym} {fmt_b} = ?\"\n", + " return question_str\n", + "def _generate_pair_meeting_cb_criteria(\n", + " target_digits_a: int, target_digits_b: int, sign_a: int, sign_b: int,\n", + " is_decimal: bool, max_decimal_places_config: int, operation_type: str,\n", + " target_total_cb_min: int, target_total_cb_max: Union[int, float],\n", + " target_consecutive_cb_min: int, target_consecutive_cb_max: Union[int, float]\n", + ") -> Optional[Tuple[Union[int, Decimal], Union[int, Decimal]]]:\n", + " num_dp = random.randint(1, max_decimal_places_config) if is_decimal and max_decimal_places_config > 0 else 0\n", + " num_int_digits_a = max(1, target_digits_a); num_int_digits_b = max(1, target_digits_b)\n", + " total_len_a = num_int_digits_a + num_dp; total_len_b = num_int_digits_b + num_dp\n", + " max_total_len = max(total_len_a, total_len_b)\n", + " effective_op = operation_type\n", + " if operation_type == 'add':\n", + " if sign_a * sign_b < 0: effective_op = 'subtract'\n", + " elif operation_type == 'subtract':\n", + " if sign_a * sign_b < 0: effective_op = 'add'\n", + " op1_digits_rev = []; op2_digits_rev = []\n", + " carry_in = 0; borrow_in = 0\n", + " current_total_cb = 0; current_consecutive_cb = 0; max_consecutive_achieved = 0\n", + " op1_target_len = total_len_a; op2_target_len = total_len_b\n", + " op1_int_digits = num_int_digits_a; op2_int_digits = num_int_digits_b\n", + " is_unlimited_cb_range = (target_total_cb_min == 0 and target_total_cb_max == math.inf and \\\n", + " target_consecutive_cb_min == 0 and target_consecutive_cb_max == math.inf)\n", + " for i in range(max_total_len):\n", + " pos_from_right = i; is_decimal_pos = (pos_from_right < num_dp)\n", + " is_int_pos = not is_decimal_pos; int_pos_from_right = pos_from_right - num_dp if is_int_pos else -1\n", + " in_op1 = (pos_from_right < op1_target_len); in_op2 = (pos_from_right < op2_target_len)\n", + " is_msd_op1_int = in_op1 and is_int_pos and int_pos_from_right == op1_int_digits - 1\n", + " is_msd_op2_int = in_op2 and is_int_pos and int_pos_from_right == op2_int_digits - 1\n", + " min_d1 = 1 if is_msd_op1_int and op1_int_digits > 1 else 0; max_d1 = 9 if in_op1 else 0\n", + " min_d2 = 1 if is_msd_op2_int and op2_int_digits > 1 else 0; max_d2 = 9 if in_op2 else 0\n", + " target_cb_state_for_this_pos = None\n", + " if not is_unlimited_cb_range:\n", + " positions_remaining = max_total_len - (i + 1)\n", + " min_total_cb_needed_later = max(0, target_total_cb_min - current_total_cb)\n", + " max_total_cb_allowed_later = float('inf') if target_total_cb_max == math.inf else target_total_cb_max - current_total_cb\n", + " if max_total_cb_allowed_later < 0: return None\n", + " min_consecutive_cb_needed_from_here = max(0, target_consecutive_cb_min - current_consecutive_cb)\n", + " must_generate_cb = (min_total_cb_needed_later > positions_remaining) or \\\n", + " (min_consecutive_cb_needed_from_here > positions_remaining and \\\n", + " max_consecutive_achieved < target_consecutive_cb_min and \\\n", + " current_consecutive_cb < target_consecutive_cb_min)\n", + " must_avoid_cb_due_to_total = (max_total_cb_allowed_later < 1)\n", + " must_avoid_cb_due_to_consecutive = (current_consecutive_cb + 1 > target_consecutive_cb_max) if target_consecutive_cb_max != math.inf else False\n", + " must_avoid_cb = must_avoid_cb_due_to_total or must_avoid_cb_due_to_consecutive\n", + " if must_generate_cb and must_avoid_cb : return None\n", + " if must_generate_cb: target_cb_state_for_this_pos = True\n", + " elif must_avoid_cb: target_cb_state_for_this_pos = False\n", + " else:\n", + " prob_try_generate_cb = 0.5\n", + " if min_total_cb_needed_later > 0 : prob_try_generate_cb += 0.2 * (min_total_cb_needed_later / max(1, positions_remaining +1))\n", + " if min_consecutive_cb_needed_from_here > 0 and max_consecutive_achieved < target_consecutive_cb_min : prob_try_generate_cb += 0.3\n", + " if target_total_cb_max != math.inf and max_total_cb_allowed_later <= positions_remaining : prob_try_generate_cb -= 0.2 * (1 - max_total_cb_allowed_later / max(1, positions_remaining +1))\n", + " if target_consecutive_cb_max != math.inf and current_consecutive_cb +1 >= target_consecutive_cb_max and min_consecutive_cb_needed_from_here == 0: prob_try_generate_cb = 0.1\n", + " prob_try_generate_cb = max(0.05, min(0.95, prob_try_generate_cb))\n", + " target_cb_state_for_this_pos = (random.random() < prob_try_generate_cb)\n", + " found_d1_d2_pair_for_pos = False\n", + " possible_d1_values = list(range(min_d1, max_d1 + 1)); random.shuffle(possible_d1_values)\n", + " chosen_d1, chosen_d2 = -1, -1\n", + " for d1_try in possible_d1_values:\n", + " possible_d2_values_for_d1_try = []\n", + " d2_value_range = list(range(min_d2, max_d2 + 1)); random.shuffle(d2_value_range)\n", + " for d2_try in d2_value_range:\n", + " cb_generated_by_this_pair = False\n", + " if effective_op == 'add': cb_generated_by_this_pair = ((d1_try + d2_try + carry_in) >= 10)\n", + " else: cb_generated_by_this_pair = ((d1_try - borrow_in - d2_try) < 0)\n", + " cb_state_matches_target = (target_cb_state_for_this_pos is None) or (cb_generated_by_this_pair == target_cb_state_for_this_pos)\n", + " temp_next_consecutive_cb = current_consecutive_cb + 1 if cb_generated_by_this_pair else 0\n", + " consecutive_constraint_ok = True\n", + " if target_consecutive_cb_max != math.inf and temp_next_consecutive_cb > target_consecutive_cb_max: consecutive_constraint_ok = False\n", + " min_consecutive_still_achievable = True\n", + " if not cb_generated_by_this_pair and target_consecutive_cb_min > 0:\n", + " max_achieved_before_reset = max(max_consecutive_achieved, current_consecutive_cb)\n", + " if max_achieved_before_reset < target_consecutive_cb_min and positions_remaining < target_consecutive_cb_min : min_consecutive_still_achievable = False\n", + " if cb_state_matches_target and consecutive_constraint_ok and min_consecutive_still_achievable: possible_d2_values_for_d1_try.append(d2_try)\n", + " if possible_d2_values_for_d1_try:\n", + " chosen_d2 = random.choice(possible_d2_values_for_d1_try); chosen_d1 = d1_try\n", + " found_d1_d2_pair_for_pos = True; break\n", + " if not found_d1_d2_pair_for_pos: return None\n", + " op1_digits_rev.append(str(chosen_d1)); op2_digits_rev.append(str(chosen_d2))\n", + " cb_occurred_at_this_pos = False\n", + " if effective_op == 'add':\n", + " current_sum_val = chosen_d1 + chosen_d2 + carry_in; carry_in = 1 if current_sum_val >= 10 else 0; borrow_in = 0\n", + " cb_occurred_at_this_pos = (carry_in == 1)\n", + " else:\n", + " current_diff_val = chosen_d1 - borrow_in - chosen_d2; borrow_in = 1 if current_diff_val < 0 else 0; carry_in = 0\n", + " cb_occurred_at_this_pos = (borrow_in == 1)\n", + " if cb_occurred_at_this_pos: current_total_cb += 1; current_consecutive_cb += 1\n", + " else: max_consecutive_achieved = max(max_consecutive_achieved, current_consecutive_cb); current_consecutive_cb = 0\n", + " max_consecutive_achieved = max(max_consecutive_achieved, current_consecutive_cb)\n", + " if not is_unlimited_cb_range:\n", + " total_cb_ok = (target_total_cb_min <= current_total_cb <= target_total_cb_max)\n", + " consecutive_cb_ok = (max_consecutive_achieved >= target_consecutive_cb_min) and \\\n", + " (target_consecutive_cb_max == math.inf or max_consecutive_achieved <= target_consecutive_cb_max)\n", + " if not (total_cb_ok and consecutive_cb_ok): return None\n", + " op1_str_msd_first = \"\".join(reversed(op1_digits_rev)); op2_str_msd_first = \"\".join(reversed(op2_digits_rev))\n", + " def _format_digit_str_to_decimal_val(s: str, dp_count: int) -> Decimal:\n", + " if not s: s = \"0\"\n", + " if dp_count > 0:\n", + " if len(s) <= dp_count: s = s.zfill(dp_count + 1)\n", + " full_s_with_point = f\"{s[:-dp_count]}.{s[-dp_count:]}\"\n", + " else: full_s_with_point = s\n", + " if '.' in full_s_with_point:\n", + " integer_part, fractional_part = full_s_with_point.split('.',1)\n", + " integer_part = integer_part.lstrip('0') or \"0\"\n", + " full_s_with_point = f\"{integer_part}.{fractional_part}\"\n", + " else: full_s_with_point = full_s_with_point.lstrip('0') or \"0\"\n", + " return Decimal(full_s_with_point)\n", + " try:\n", + " val1_abs = _format_digit_str_to_decimal_val(op1_str_msd_first, num_dp)\n", + " val2_abs = _format_digit_str_to_decimal_val(op2_str_msd_first, num_dp)\n", + " a_val_final_signed = val1_abs.copy_sign(sign_a); b_val_final_signed = val2_abs.copy_sign(sign_b)\n", + " if a_val_final_signed.is_zero() and a_val_final_signed.is_signed(): a_val_final_signed = Decimal('0')\n", + " if b_val_final_signed.is_zero() and b_val_final_signed.is_signed(): b_val_final_signed = Decimal('0')\n", + " if not is_decimal and num_dp == 0:\n", + " a_final_val = int(a_val_final_signed) if a_val_final_signed == a_val_final_signed.to_integral_value() else a_val_final_signed.normalize()\n", + " b_final_val = int(b_val_final_signed) if b_val_final_signed == b_val_final_signed.to_integral_value() else b_val_final_signed.normalize()\n", + " else:\n", + " a_final_val = a_val_final_signed.normalize(); b_final_val = b_val_final_signed.normalize()\n", + " if a_final_val.is_zero() and a_final_val.is_signed(): a_final_val = Decimal('0')\n", + " if b_final_val.is_zero() and b_final_val.is_signed(): b_final_val = Decimal('0')\n", + " return a_final_val, b_final_val\n", + " except InvalidOperation: return None\n", + " except Exception: return None\n", + "def check_carries_borrows(num1: Decimal, num2: Decimal, operation: str) -> Tuple[int, int]:\n", + " total_cb = 0; max_consecutive_cb = 0; current_consecutive_cb = 0\n", + " try:\n", + " effective_op = operation; op1: Decimal; op2: Decimal\n", + " if operation == 'add':\n", + " if num1.is_signed() != num2.is_signed():\n", + " effective_op = 'subtract'\n", + " if abs(num1) >= abs(num2): op1, op2 = abs(num1), abs(num2)\n", + " else: op1, op2 = abs(num2), abs(num1)\n", + " else: effective_op = 'add'; op1, op2 = abs(num1), abs(num2)\n", + " elif operation == 'subtract':\n", + " if num1.is_signed() != num2.is_signed(): effective_op = 'add'; op1, op2 = abs(num1), abs(num2)\n", + " else:\n", + " effective_op = 'subtract'\n", + " if abs(num1) >= abs(num2): op1, op2 = abs(num1), abs(num2)\n", + " else: op1, op2 = abs(num2), abs(num1)\n", + " else: return -1, -1\n", + " if op1.is_zero() and op2.is_zero(): return 0, 0\n", + " s1 = format_decimal_or_int(op1); s2 = format_decimal_or_int(op2)\n", + " s1_int_part, s1_frac_part = s1.split('.') if '.' in s1 else (s1, '')\n", + " s2_int_part, s2_frac_part = s2.split('.') if '.' in s2 else (s2, '')\n", + " max_frac_len = max(len(s1_frac_part), len(s2_frac_part))\n", + " s1_frac_part = s1_frac_part.ljust(max_frac_len, '0'); s2_frac_part = s2_frac_part.ljust(max_frac_len, '0')\n", + " max_int_len = max(len(s1_int_part), len(s2_int_part))\n", + " s1_int_part = s1_int_part.zfill(max_int_len); s2_int_part = s2_int_part.zfill(max_int_len)\n", + " aligned_s1 = s1_int_part + s1_frac_part; aligned_s2 = s2_int_part + s2_frac_part\n", + " full_len = len(aligned_s1); carry = 0; borrow = 0\n", + " for i in range(full_len - 1, -1, -1):\n", + " try: d1 = int(aligned_s1[i]); d2 = int(aligned_s2[i])\n", + " except (IndexError, ValueError): return -1, -1\n", + " cb_occurred_this_digit = False\n", + " if effective_op == 'add':\n", + " current_sum_digit = d1 + d2 + carry; carry = 1 if current_sum_digit >= 10 else 0\n", + " cb_occurred_this_digit = (carry == 1)\n", + " else:\n", + " current_diff_digit = d1 - borrow - d2; borrow = 1 if current_diff_digit < 0 else 0\n", + " cb_occurred_this_digit = (borrow == 1)\n", + " if cb_occurred_this_digit: total_cb += 1; current_consecutive_cb += 1\n", + " else: max_consecutive_cb = max(max_consecutive_cb, current_consecutive_cb); current_consecutive_cb = 0\n", + " max_consecutive_cb = max(max_consecutive_cb, current_consecutive_cb)\n", + " except Exception as e: return -1, -1\n", + " return total_cb, max_consecutive_cb\n", + "def write_batch_to_jsonl(buffer: List[Dict], filename: str, mode: str = 'a') -> int:\n", + " if not buffer: return 0\n", + " lines_written = 0; json_lines_to_write = []; serialization_errors = 0\n", + " for item in buffer:\n", + " try:\n", + " if not isinstance(item, dict) or not item.get(\"text\"): serialization_errors += 1; continue\n", + " json_string = json.dumps(item, ensure_ascii=False)\n", + " if json_string and not json_string.isspace(): json_lines_to_write.append(json_string)\n", + " else: serialization_errors += 1\n", + " except (TypeError, ValueError): serialization_errors += 1\n", + " except Exception: serialization_errors += 1\n", + " if json_lines_to_write:\n", + " try:\n", + " with open(filename, mode, encoding='utf-8') as f: f.write('\\n'.join(json_lines_to_write) + '\\n')\n", + " lines_written = len(json_lines_to_write)\n", + " except IOError: return 0\n", + " except Exception: return 0\n", + " if serialization_errors > 0: print(f\"\\n警告: 写入批次时 {serialization_errors} 个项目处理失败。\")\n", + " return lines_written\n", + "def randomly_replace_characters_in_string(text: str, replacement_prob: float, char_pool: str) -> str:\n", + " if not text or replacement_prob <= 0 or not char_pool: return text\n", + " new_chars = list(text)\n", + " for i in range(len(new_chars)):\n", + " if random.random() < replacement_prob:\n", + " if new_chars[i] not in ['\\n', '\\r']: new_chars[i] = random.choice(char_pool)\n", + " return \"\".join(new_chars)\n", + "\n", + "\n", + "# --- 主要生成函数 ---\n", + "def generate_constructed_arithmetic_diverse(\n", + " filename: str, total_samples: int, add_prob: float, decimal_prob: float,\n", + " max_digits_limit: int, max_decimal_places_cfg: int, negative_pool_prob: float,\n", + " target_total_cb_min: int, target_total_cb_max: Union[int, float],\n", + " target_consecutive_cb_min: int, target_consecutive_cb_max: Union[int, float],\n", + " nl_question_prob: float,\n", + " symbolic_equals_suffix_prob: float,\n", + " max_attempts_factor: int,\n", + " batch_save_size: int,\n", + " apply_general_char_corr: bool,\n", + " general_char_corr_prob: float,\n", + " general_char_corr_pool: str\n", + " ):\n", + " \"\"\"(v10.10) 生成数据,增加字符间随机空格功能。\"\"\"\n", + " print(f\"--- 开始生成算术数据 (v10.10 - Intra-Character Spacing) ---\")\n", + " if RANDOMIZE_DIGITS_WITHIN_CHINESE_NUMBERS: print(f\"中文数字内字符样式随机化已启用。\")\n", + " else: print(\"中文数字内字符样式随机化未启用。\")\n", + " if CHINESE_DIGIT_BY_DIGIT_READING_PROB > 0: print(f\"中文逐位念读已启用 (概率: {CHINESE_DIGIT_BY_DIGIT_READING_PROB*100:.1f}%).\")\n", + " else: print(\"中文逐位念读未启用。\")\n", + " if APPLY_INTRA_CHAR_SPACING: print(f\"字符间随机空格已启用。\")\n", + " else: print(\"字符间随机空格未启用。\")\n", + " if apply_general_char_corr: print(f\"通用字符级损坏已启用: 概率={general_char_corr_prob*100:.2f}%\")\n", + " else: print(\"通用字符级损坏未启用。\")\n", + "\n", + " # ... (初始化与 v10.9 相同) ...\n", + " digit_pop: List[int] = []; digit_probs_list: List[float] = []\n", + " if max_digits_limit > 0:\n", + " digit_probabilities_dict = calculate_digit_probabilities(max_digits_limit)\n", + " digit_pop = list(range(1, max_digits_limit + 1)); digit_probs_list = [digit_probabilities_dict.get(n, 0.0) for n in digit_pop]\n", + " prob_sum_check = sum(digit_probs_list)\n", + " if not math.isclose(prob_sum_check, 1.0, abs_tol=1e-5):\n", + " if prob_sum_check > 1e-9: digit_probs_list = [p / prob_sum_check for p in digit_probs_list]\n", + " else: uniform_prob = 1.0 / len(digit_pop) if digit_pop else 1.0; digit_probs_list = [uniform_prob] * len(digit_pop)\n", + " if not digit_probs_list and digit_pop: digit_probs_list = [1.0/len(digit_pop)]*len(digit_pop)\n", + " elif not digit_pop : digit_pop = [1]; digit_probs_list = [1.0]\n", + " else: digit_pop = [1]; digit_probs_list = [1.0]\n", + " generated_count = 0; total_attempts = 0; total_lines_written = 0\n", + " construct_failures = 0; add_count = 0; subtract_count = 0\n", + " integer_op_count = 0; decimal_op_count = 0\n", + " format_counts = Counter(); question_type_counts = Counter(); suffix_counts = Counter()\n", + " errors_in_loop = 0\n", + " difficulty_factor_cb = max(1, target_total_cb_min) if target_total_cb_max != math.inf else 1\n", + " difficulty_factor_cb = max(difficulty_factor_cb, target_consecutive_cb_min // 2 if target_consecutive_cb_max !=math.inf else 1)\n", + " max_total_attempts = total_samples * max(100, max_attempts_factor * difficulty_factor_cb)\n", + " start_time_generate = time.time(); output_buffer = []; last_reported_count = -1; last_save_time = start_time_generate\n", + " try:\n", + " with open(filename, 'w', encoding='utf-8') as f: f.write(\"\")\n", + " print(f\"已初始化/清空输出文件: '{filename}'\")\n", + " except IOError as e: print(f\"\\n错误:无法初始化输出文件 '{filename}': {e}\"); return\n", + " print(f\"\\n开始构造 {total_samples:,} 条满足条件的数据...\")\n", + " \n", + " # --- 主生成循环 ---\n", + " while generated_count < total_samples:\n", + " total_attempts += 1\n", + " if total_attempts > max_total_attempts:\n", + " print(f\"\\n\\n警告: 尝试次数达到上限 ({total_attempts:,})。\"); print(f\"当前已生成: {generated_count:,} (构造失败 {construct_failures:,} 次).\"); print(\"脚本提前终止.\"); break\n", + " \n", + " a: Union[int, Decimal] = Decimal('0'); b: Union[int, Decimal] = Decimal('0')\n", + " try:\n", + " # 1. 选择基本参数\n", + " if not digit_pop or not digit_probs_list or len(digit_pop) != len(digit_probs_list):\n", + " digits_a = random.randint(1, max(1,max_digits_limit)); digits_b = random.randint(1, max(1,max_digits_limit))\n", + " else:\n", + " digits_a = get_distributed_count_from_probs(digit_pop, digit_probs_list); digits_b = get_distributed_count_from_probs(digit_pop, digit_probs_list)\n", + " sign_a = -1 if random.random() < negative_pool_prob else 1\n", + " sign_b = -1 if random.random() < negative_pool_prob else 1\n", + " is_dec_intent_current = random.random() < decimal_prob\n", + " op_type_current = 'add' if random.random() < add_prob else 'subtract'\n", + " op_sym_current = '+' if op_type_current == 'add' else '-'\n", + "\n", + " # 2. 构造数字对 (a,b)\n", + " constructed_pair = _generate_pair_meeting_cb_criteria(\n", + " digits_a, digits_b, sign_a, sign_b, is_dec_intent_current, max_decimal_places_cfg,\n", + " op_type_current, target_total_cb_min, target_total_cb_max,\n", + " target_consecutive_cb_min, target_consecutive_cb_max)\n", + " if constructed_pair is None: construct_failures += 1; continue\n", + " a, b = constructed_pair\n", + "\n", + " # 3. 计算结果 c\n", + " c_final: Union[int, Decimal]; answer_str = \"\"\n", + " try:\n", + " a_calc = Decimal(str(a)) if not isinstance(a, Decimal) else a\n", + " b_calc = Decimal(str(b)) if not isinstance(b, Decimal) else b\n", + " if not a_calc.is_finite() or not b_calc.is_finite(): errors_in_loop += 1; continue\n", + " c_calc = a_calc + b_calc if op_type_current == 'add' else a_calc - b_calc\n", + " if not c_calc.is_finite(): errors_in_loop += 1; continue\n", + " \n", + " effective_dp_a = 0; effective_dp_b = 0\n", + " if isinstance(a_calc, Decimal) and a_calc.as_tuple().exponent < 0: effective_dp_a = abs(a_calc.as_tuple().exponent)\n", + " if isinstance(b_calc, Decimal) and b_calc.as_tuple().exponent < 0: effective_dp_b = abs(b_calc.as_tuple().exponent)\n", + " result_dp = max(effective_dp_a, effective_dp_b)\n", + " if not is_dec_intent_current and effective_dp_a == 0 and effective_dp_b == 0: result_dp = 0\n", + " result_dp = min(result_dp, max_decimal_places_cfg)\n", + " \n", + " if result_dp > 0: c_final_dec = c_calc.quantize(Decimal('1e-' + str(result_dp)), rounding=ROUND_HALF_UP)\n", + " else: c_final_dec = c_calc.to_integral_value(rounding=ROUND_HALF_UP)\n", + " c_final_dec = c_final_dec.normalize()\n", + " if c_final_dec.is_zero() and c_final_dec.is_signed(): c_final_dec = Decimal('0')\n", + " \n", + " is_a_actually_int = isinstance(a, int) or (isinstance(a, Decimal) and a == a.to_integral_value())\n", + " is_b_actually_int = isinstance(b, int) or (isinstance(b, Decimal) and b == b.to_integral_value())\n", + " is_c_actually_int = (c_final_dec == c_final_dec.to_integral_value())\n", + " if is_c_actually_int and is_a_actually_int and is_b_actually_int and not is_dec_intent_current:\n", + " try: c_final = int(c_final_dec)\n", + " except (OverflowError, ValueError): c_final = c_final_dec\n", + " else: c_final = c_final_dec\n", + " answer_str = format_decimal_or_int(c_final) # 答案不应用字符间空格\n", + " except (InvalidOperation, OverflowError, ValueError, ArithmeticError): errors_in_loop += 1; continue\n", + " except Exception: errors_in_loop += 1; continue\n", + " if not answer_str: errors_in_loop += 1; continue\n", + "\n", + " # 4. 多样化格式化 (问题部分),现在 format_number_variant 内部会处理字符间空格\n", + " try:\n", + " fmt_a_str_processed, fmt_a_type = format_number_variant(a) # 已包含内部空格处理\n", + " \n", + " final_op_sym_for_question = op_sym_current; fmt_b_str_processed, fmt_b_type = \"\", \"\"\n", + " try:\n", + " b_dec_for_fmt = Decimal(str(b)) if not isinstance(b, Decimal) else b\n", + " if b_dec_for_fmt.is_signed() and b_dec_for_fmt < 0:\n", + " # format_number_variant 对 abs(b) 应用,结果已包含空格\n", + " fmt_b_abs_str_processed, fmt_b_abs_type = format_number_variant(abs(b_dec_for_fmt))\n", + " fmt_b_str_processed = fmt_b_abs_str_processed; fmt_b_type = fmt_b_abs_type\n", + " if op_sym_current == '+': final_op_sym_for_question = '-'\n", + " elif op_sym_current == '-': final_op_sym_for_question = '+'\n", + " else: \n", + " fmt_b_str_processed, fmt_b_type = format_number_variant(b) # 已包含内部空格处理\n", + " except (InvalidOperation, TypeError, ValueError): \n", + " fmt_b_str_processed, fmt_b_type = format_number_variant(b) # 已包含内部空格处理\n", + "\n", + " if not fmt_a_str_processed or not fmt_b_str_processed: errors_in_loop +=1; continue\n", + " format_counts[f'a_{fmt_a_type}'] += 1; format_counts[f'b_{fmt_b_type}'] += 1\n", + "\n", + " # 5. 构建问题字符串\n", + " question_str = \"\"\n", + " a_is_chinese_style = fmt_a_type in ['simple_zh', 'complex_zh']\n", + " b_is_chinese_style = fmt_b_type in ['simple_zh', 'complex_zh']\n", + " is_nl_question_current = (random.random() < nl_question_prob) and not (a_is_chinese_style or b_is_chinese_style)\n", + " if is_nl_question_current:\n", + " question_type_counts['natural_language'] += 1\n", + " # fmt_a_str_processed 和 fmt_b_str_processed 已包含字符间空格\n", + " question_str = format_natural_language_question(fmt_a_str_processed, fmt_b_str_processed, final_op_sym_for_question)\n", + " else:\n", + " question_type_counts['symbolic'] += 1\n", + " space1_op = get_realistic_spacing(); space2_op = get_realistic_spacing() # 操作符两侧空格\n", + " # fmt_a_str_processed 和 fmt_b_str_processed 已包含字符间空格\n", + " question_str_base = f\"{fmt_a_str_processed}{space1_op}{final_op_sym_for_question}{space2_op}{fmt_b_str_processed}\"\n", + " question_suffix = \"\"; added_suffix_flag = False\n", + " if random.random() < symbolic_equals_suffix_prob:\n", + " q_mark = random.choice([\"?\", \"?\"]); space_eq1 = get_realistic_spacing(); space_eq2 = get_realistic_spacing()\n", + " question_suffix = f\"{space_eq1}={space_eq2}{q_mark}\"; added_suffix_flag = True\n", + " suffix_counts['symbolic_added' if added_suffix_flag else 'symbolic_not_added'] += 1\n", + " question_str = question_str_base + question_suffix\n", + " if not question_str or question_str.isspace(): errors_in_loop += 1; continue\n", + "\n", + " # 6. 构建最终输出 text\n", + " text_content = f\"User: {question_str}\\n\\nAssistant: {answer_str}\"\n", + "\n", + " # 7. (可选) 通用字符损坏\n", + " if apply_general_char_corr:\n", + " text_content = randomly_replace_characters_in_string(text_content, general_char_corr_prob, general_char_corr_pool)\n", + " \n", + " pair_data = {\"text\": text_content}\n", + " \n", + " # 更新统计 (与v10.9相同)\n", + " generated_count += 1\n", + " if op_type_current == 'add': add_count += 1\n", + " else: subtract_count += 1\n", + " is_a_truly_decimal_val = isinstance(a, Decimal) and a != a.to_integral_value()\n", + " is_b_truly_decimal_val = isinstance(b, Decimal) and b != b.to_integral_value()\n", + " is_c_truly_decimal_val = isinstance(c_final, Decimal) and c_final != c_final.to_integral_value()\n", + " if is_dec_intent_current or is_a_truly_decimal_val or is_b_truly_decimal_val or is_c_truly_decimal_val: decimal_op_count += 1\n", + " else: integer_op_count += 1\n", + " output_buffer.append(pair_data)\n", + "\n", + " # 8. 批量保存 (与v10.9相同)\n", + " if len(output_buffer) >= batch_save_size:\n", + " write_op_start_time = time.time()\n", + " num_written_this_batch = write_batch_to_jsonl(output_buffer, filename, mode='a')\n", + " write_op_duration = time.time() - write_op_start_time\n", + " if num_written_this_batch > 0:\n", + " total_lines_written += num_written_this_batch\n", + " avg_save_sps = num_written_this_batch / write_op_duration if write_op_duration > 0 else float('inf')\n", + " print(f\"\\r--- 已保存批次 {num_written_this_batch:>6,} (耗时 {write_op_duration:.2f}s, {avg_save_sps:.1f}/s). 总计写入: {total_lines_written:>8,} / 生成: {generated_count:>8,} ---{' '*5}\", end=\"\")\n", + " output_buffer.clear(); last_save_time = time.time()\n", + " else:\n", + " print(f\"\\n警告: 写入批处理失败 (已生成 {generated_count:,} 条)。缓冲区已清空.\")\n", + " errors_in_loop += len(output_buffer); output_buffer.clear()\n", + " except Exception as format_stage_error: errors_in_loop += 1; continue\n", + " except KeyboardInterrupt: print(\"\\n用户中断。\"); break\n", + " except Exception as main_loop_iter_error: errors_in_loop += 1; continue\n", + " \n", + " # 9. 进度报告 (与v10.9相同)\n", + " report_freq_interval = max(1, total_samples // 200) if total_samples > 0 else 1000\n", + " current_time = time.time(); time_since_last_activity = current_time - max(last_save_time, start_time_generate if last_reported_count == -1 else last_save_time)\n", + " if generated_count > 0 and (generated_count % report_freq_interval == 0 or generated_count == total_samples or time_since_last_activity > 15):\n", + " if last_reported_count != generated_count:\n", + " progress_percent = generated_count / total_samples if total_samples > 0 else 0; elapsed_seconds = current_time - start_time_generate\n", + " samples_per_sec_rate = generated_count / elapsed_seconds if elapsed_seconds > 0 else 0\n", + " attempts_per_gen_sample = total_attempts / generated_count if generated_count > 0 else float('inf')\n", + " construct_failure_rate = construct_failures / total_attempts if total_attempts > 0 else 0; est_remaining_time_str = \"N/A\"\n", + " if progress_percent > 1e-6 and samples_per_sec_rate > 0:\n", + " remaining_samples_to_gen = total_samples - generated_count; est_remaining_seconds = remaining_samples_to_gen / samples_per_sec_rate\n", + " if est_remaining_seconds < 60: est_remaining_time_str = f\"{est_remaining_seconds:.0f}s\"\n", + " elif est_remaining_seconds < 3600: est_remaining_time_str = f\"{est_remaining_seconds/60:.1f}m\"\n", + " else: est_remaining_time_str = f\"{est_remaining_seconds/3600:.1f}h\"\n", + " stats_line = f\"生成: {generated_count:>8,}/{total_samples:<8,} ({progress_percent:5.1%}) | 写入: {total_lines_written:>8,} | 尝试: {total_attempts:>9,} ({attempts_per_gen_sample:5.1f}/样本) | 失败率: {construct_failure_rate:5.1%} | {samples_per_sec_rate:6.1f} 样本/秒 | 耗时: {elapsed_seconds:6.1f}s | 剩余: ~{est_remaining_time_str:<5}\"\n", + " print(f\"\\r{stats_line.ljust(120)}\", end=\"\"); last_reported_count = generated_count\n", + "\n", + " # --- 循环结束后 ---\n", + " # ... (与 v10.9 相同,包括修正后的统计打印) ...\n", + " print(\" \" * 120, end=\"\\r\"); print(f\"\\n构造循环结束。目标: {total_samples:,}, 实际生成: {generated_count:,} (尝试 {total_attempts:,} 次, 构造失败 {construct_failures:,} 次).\")\n", + " if output_buffer:\n", + " print(f\"写入最后 {len(output_buffer):,} 条数据...\"); final_write_start = time.time()\n", + " num_final_written = write_batch_to_jsonl(output_buffer, filename, mode='a'); final_write_duration = time.time() - final_write_start\n", + " if num_final_written > 0: total_lines_written += num_final_written; print(f\"最终批次写入完成 ({num_final_written:,} 条). 耗时: {final_write_duration:.2f}s.\")\n", + " else: print(\"警告: 最终批次写入失败.\"); errors_in_loop += len(output_buffer)\n", + " output_buffer.clear()\n", + " else: print(\"无剩余数据需写入.\")\n", + " total_generation_end_time = time.time(); total_generation_duration = total_generation_end_time - start_time_generate\n", + " print(f\"\\n生成与写入完毕。目标: {total_samples:,} -> 生成: {generated_count:,} -> 写入: {total_lines_written:,}\")\n", + " if total_lines_written != generated_count and generated_count > 0: print(f\"警告: 写入行数({total_lines_written:,}) 与 生成数({generated_count:,}) 不匹配!\")\n", + " avg_attempts_per_actual_sample = total_attempts / max(1, generated_count) if generated_count > 0 else float('inf')\n", + " overall_construct_failure_rate = construct_failures / total_attempts if total_attempts > 0 else 0\n", + " print(f\"总尝试次数: {total_attempts:,} (平均 {avg_attempts_per_actual_sample:.2f} 次/有效样本)\")\n", + " print(f\"构造失败次数: {construct_failures:,} (失败率: {overall_construct_failure_rate:.2%})\")\n", + " print(f\"总耗时: {total_generation_duration:.2f} 秒。格式化/计算/写入等循环内错误: {errors_in_loop:,}.\")\n", + " print(\"\\n\" + \"=\"*15 + \" 详细统计 (基于生成的有效样本) \" + \"=\"*15)\n", + " if generated_count > 0:\n", + " print(f\"总有效样本: {generated_count:,}\")\n", + " print(\"-\" * 50); print(\"1. 算术题类型:\"); print(f\" - 加法: {add_count:>10,} ({add_count/generated_count:>7.1%})\"); print(f\" - 减法: {subtract_count:>10,} ({subtract_count/generated_count:>7.1%})\")\n", + " print(\"-\" * 50); print(\"2. 运算数类型:\"); print(f\" - 纯整数运算*: {integer_op_count:>10,} ({integer_op_count/generated_count:>7.1%})\"); print(f\" - 含小数运算*: {decimal_op_count:>10,} ({decimal_op_count/generated_count:>7.1%})\"); print(\" *注: 基于操作数或结果是否包含实际小数部分,或生成意图是否为小数。\")\n", + " total_fmt_a_counts = sum(format_counts[k] for k in format_counts if k.startswith('a_')); print(\"-\" * 50); print(f\"3. 问题格式 - 操作数 A (总计: {total_fmt_a_counts:,}):\")\n", + " ordered_fmt_keys_a = ['a_standard', 'a_full_width', 'a_simple_zh', 'a_complex_zh']; [print(f\" - {fmt_key[2:]: <15}: {format_counts.get(fmt_key, 0):>10,} ({(format_counts.get(fmt_key, 0) / total_fmt_a_counts * 100) if total_fmt_a_counts > 0 else 0:>6.1f}%)\") for fmt_key in ordered_fmt_keys_a]\n", + " total_fmt_b_counts = sum(format_counts[k] for k in format_counts if k.startswith('b_')); print(\"-\" * 50); print(f\"4. 问题格式 - 操作数 B (总计: {total_fmt_b_counts:,}):\")\n", + " ordered_fmt_keys_b = ['b_standard', 'b_full_width', 'b_simple_zh', 'b_complex_zh']; [print(f\" - {fmt_key[2:]: <15}: {format_counts.get(fmt_key, 0):>10,} ({(format_counts.get(fmt_key, 0) / total_fmt_b_counts * 100) if total_fmt_b_counts > 0 else 0:>6.1f}%)\") for fmt_key in ordered_fmt_keys_b]\n", + " \n", + " total_q_type_counts = sum(question_type_counts.values())\n", + " print(\"-\" * 50); print(f\"5. 问题格式 - 类型 (总计: {total_q_type_counts:,}):\")\n", + " ordered_q_type_keys = ['symbolic', 'natural_language']\n", + " display_name_map_qtype = {'symbolic': '符号格式 (+/-)', 'natural_language': '自然语言格式'}\n", + " for q_type_key in ordered_q_type_keys:\n", + " count = question_type_counts.get(q_type_key, 0)\n", + " percent = count / total_q_type_counts * 100 if total_q_type_counts > 0 else 0\n", + " display_name = display_name_map_qtype.get(q_type_key, q_type_key)\n", + " print(f\" - {display_name: <22}: {count:>10,} ({percent:>6.1f}%)\")\n", + "\n", + " total_symbolic_suffix_counts = suffix_counts.get('symbolic_added', 0) + suffix_counts.get('symbolic_not_added', 0)\n", + " print(\"-\" * 50); print(f\"6. 符号问题格式 - 等号后缀 (总计符号问题: {total_symbolic_suffix_counts:,}):\")\n", + " ordered_suffix_keys = ['symbolic_added', 'symbolic_not_added']\n", + " display_name_map_suffix = {'symbolic_added': '添加 \" = ?/?\"', 'symbolic_not_added': '未添加后缀'}\n", + " for suffix_key in ordered_suffix_keys:\n", + " count = suffix_counts.get(suffix_key,0)\n", + " percent = count / total_symbolic_suffix_counts * 100 if total_symbolic_suffix_counts > 0 else 0\n", + " display_name = display_name_map_suffix.get(suffix_key, suffix_key)\n", + " print(f\" - {display_name: <18}: {count:>10,} ({percent:>6.1f}%)\")\n", + " print(\"=\"*50)\n", + " else: print(\"\\n--- 未生成有效样本,无详细统计 ---\"); print(\"=\"*50)\n", + "\n", + "\n", + "# ===============================================\n", + "# 主程序入口\n", + "# ===============================================\n", + "if __name__ == \"__main__\":\n", + " script_total_start_time = time.time()\n", + " print(\"=\"*30); print(\" 算术题生成脚本 (v10.10) \"); print(\"=\"*30)\n", + " # ... (预检查与 v10.9 相同) ...\n", + " max_possible_digits_overall = MAX_DIGITS + MAX_DECIMAL_PLACES\n", + " if max_possible_digits_overall <= 0: print(\"!!! 配置错误: MAX_DIGITS 和 MAX_DECIMAL_PLACES 必须至少有一个大于0。脚本终止.\"); exit()\n", + " max_possible_cb_rough_estimate = MAX_DIGITS + MAX_DECIMAL_PLACES + (1 if MAX_DECIMAL_PLACES > 0 else 0)\n", + " if TARGET_TOTAL_CARRIES_MAX != math.inf and TARGET_TOTAL_CARRIES_MIN > max_possible_cb_rough_estimate: print(f\"\\n!!! 配置警告: 目标最小总进/借位数 ({TARGET_TOTAL_CARRIES_MIN}) > 估算的位数上限 ({max_possible_cb_rough_estimate})。可能难以构造或无法构造。 !!!\")\n", + " if TARGET_CONSECUTIVE_CARRIES_MAX != math.inf and TARGET_CONSECUTIVE_CARRIES_MIN > max_possible_cb_rough_estimate: print(f\"\\n!!! 配置警告: 目标最小连续进/借位数 ({TARGET_CONSECUTIVE_CARRIES_MIN}) > 估算的位数上限 ({max_possible_cb_rough_estimate})。可能难以构造或无法构造。 !!!\")\n", + " if TARGET_TOTAL_CARRIES_MAX != 0 and TARGET_CONSECUTIVE_CARRIES_MIN > TARGET_TOTAL_CARRIES_MIN: print(f\"\\n!!! 配置提示: 目标最小连续数 ({TARGET_CONSECUTIVE_CARRIES_MIN}) 大于目标最小总数 ({TARGET_TOTAL_CARRIES_MIN})。\")\n", + "\n", + " try:\n", + " generate_constructed_arithmetic_diverse(\n", + " filename=OUTPUT_FILENAME,\n", + " total_samples=TOTAL_SAMPLES,\n", + " add_prob=ADD_PROBABILITY,\n", + " decimal_prob=DECIMAL_PROBABILITY,\n", + " max_digits_limit=MAX_DIGITS,\n", + " max_decimal_places_cfg=MAX_DECIMAL_PLACES,\n", + " negative_pool_prob=NEGATIVE_POOL_PROB,\n", + " target_total_cb_min=TARGET_TOTAL_CARRIES_MIN,\n", + " target_total_cb_max=TARGET_TOTAL_CARRIES_MAX,\n", + " target_consecutive_cb_min=TARGET_CONSECUTIVE_CARRIES_MIN,\n", + " target_consecutive_cb_max=TARGET_CONSECUTIVE_CARRIES_MAX,\n", + " nl_question_prob=NL_QUESTION_PROBABILITY,\n", + " symbolic_equals_suffix_prob=SYMBOLIC_EQUALS_SUFFIX_PROB,\n", + " max_attempts_factor=MAX_ATTEMPTS_FACTOR,\n", + " batch_save_size=BATCH_SAVE_SIZE,\n", + " apply_general_char_corr=APPLY_GENERAL_CHAR_REPLACEMENT,\n", + " general_char_corr_prob=GENERAL_CHAR_REPLACEMENT_PROBABILITY,\n", + " general_char_corr_pool=GENERAL_CHAR_REPLACEMENT_POOL\n", + " )\n", + " except ValueError as val_err: print(f\"\\n配置或值错误: {val_err}\"); traceback.print_exc()\n", + " except MemoryError: print(\"\\n内存错误: 尝试减少 BATCH_SAVE_SIZE 或 TOTAL_SAMPLES。\"); traceback.print_exc()\n", + " except Exception as main_exec_err: print(f\"\\n主程序发生未预料错误: {main_exec_err}\"); traceback.print_exc()\n", + " finally: pass\n", + "\n", + " script_total_end_time = time.time()\n", + " print(\"\\n\" + \"=\"*30); print(f\"脚本执行完毕。总耗时: {script_total_end_time - script_total_start_time:.2f} 秒。\"); print(f\"数据文件: {OUTPUT_FILENAME}\"); print(\"=\"*30)" + ] + }, + { + "cell_type": "markdown", + "id": "9d6be8e8", + "metadata": {}, + "source": [ + "# 生成乱码\n", + "\n", + "用于生成:\n", + "\n", + "训练集:qa_gibberish_unanswerable\n", + "\n", + "测试集:qa_gibberish_unanswerable-test" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "29f356fc", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "==============================\n", + " 乱码问答生成脚本 (v1.0) \n", + "==============================\n", + "--- 开始生成乱码问答数据集 (v1.0) ---\n", + "总样本数: 100\n", + "乱码长度范围: 1-50\n", + "字符池大小: 95\n", + "固定答案: '无法回答'\n", + "输出文件: 'qa_gibberish_unanswerable-test.jsonl'\n", + "已初始化/清空输出文件: 'qa_gibberish_unanswerable-test.jsonl'\n", + "\n", + "开始生成 100 条数据...\n", + "生成: 100/100 (100.0%) | 写入: 100 | 26649.1 样本/秒 | 耗时: 0.0s | 剩余: ~0s \n", + "生成循环结束。目标: 100, 实际生成: 100.\n", + "无剩余数据需写入.\n", + "\n", + "生成与写入完毕。目标: 100 -> 生成: 100 -> 写入: 100\n", + "总耗时: 0.00 秒。\n", + "==================================================\n", + "\n", + "==============================\n", + "脚本执行完毕。总耗时: 0.00 秒。\n", + "数据文件: qa_gibberish_unanswerable-test.jsonl\n", + "==============================\n" + ] + } + ], + "source": [ + "# -*- coding: utf-8 -*-\n", + "# 生成乱码问题和固定答案“无法回答”的数据集脚本。\n", + "# v1.0: Initial version for generating gibberish questions.\n", + "\n", + "import json\n", + "import random\n", + "import string # For character pools\n", + "import time\n", + "from typing import List, Dict\n", + "\n", + "# ===============================================\n", + "# 配置参数区域\n", + "# ===============================================\n", + "# --- 主要数量和文件名 ---\n", + "TOTAL_SAMPLES: int = 100\n", + "OUTPUT_FILENAME: str = \"qa_gibberish_unanswerable-test.jsonl\"\n", + "BATCH_SAVE_SIZE: int = 100 # How many samples to write to file at once\n", + "\n", + "# --- 乱码生成控制 ---\n", + "MIN_GIBBERISH_LENGTH: int = 1 # 最小乱码长度\n", + "MAX_GIBBERISH_LENGTH: int = 50 # 最大乱码长度 (不超过50)\n", + "if MAX_GIBBERISH_LENGTH > 50:\n", + " MAX_GIBBERISH_LENGTH = 50\n", + " print(\"警告: MAX_GIBBERISH_LENGTH 超过50,已自动修正为50。\")\n", + "if MIN_GIBBERISH_LENGTH > MAX_GIBBERISH_LENGTH:\n", + " MIN_GIBBERISH_LENGTH = 1\n", + " MAX_GIBBERISH_LENGTH = 50 # Or raise error\n", + " print(\"警告: MIN_GIBBERISH_LENGTH 大于 MAX_GIBBERISH_LENGTH,已重置为1-50。\")\n", + "\n", + "\n", + "# 可选字符集 (可以根据需要修改)\n", + "# string.ascii_letters: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\n", + "# string.digits: '0123456789'\n", + "# string.punctuation: '!\"#$%&\\'()*+,-./:;<=>?@[\\\\]^_`{|}~'\n", + "# string.whitespace: ' \\t\\n\\r\\x0b\\x0c' (通常不希望在单行乱码中包含换行符)\n", + "\n", + "# 组合常用字符,排除显式的换行和制表符,但保留空格\n", + "CHARACTER_POOL: str = string.ascii_letters + string.digits + string.punctuation + ' '\n", + "# 如果需要更广泛的字符,包括一些特殊符号或非英文字符,可以手动添加:\n", + "# CHARACTER_POOL += \"中文符号也可以添加在这里!?。「」、・ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙゚\"\n", + "# CHARACTER_POOL += \"😊👍🎉\" # 表情符号等\n", + "\n", + "if not CHARACTER_POOL:\n", + " raise ValueError(\"CHARACTER_POOL 不能为空。请至少定义一个字符。\")\n", + "\n", + "# --- 固定答案 ---\n", + "FIXED_ANSWER: str = \"无法回答\"\n", + "\n", + "# ===============================================\n", + "# 核心代码\n", + "# ===============================================\n", + "\n", + "def generate_gibberish_string(min_len: int, max_len: int, char_pool: str) -> str:\n", + " \"\"\"生成指定长度范围内的随机字符串。\"\"\"\n", + " if min_len < 1:\n", + " min_len = 1\n", + " if max_len < min_len:\n", + " max_len = min_len\n", + " \n", + " length = random.randint(min_len, max_len)\n", + " return ''.join(random.choice(char_pool) for _ in range(length))\n", + "\n", + "def write_batch_to_jsonl(buffer: List[Dict], filename: str, mode: str = 'a') -> int:\n", + " \"\"\"将数据批量写入 JSONL 文件。\"\"\"\n", + " if not buffer:\n", + " return 0\n", + " lines_written = 0\n", + " json_lines_to_write = []\n", + " serialization_errors = 0\n", + "\n", + " for item in buffer:\n", + " try:\n", + " if not isinstance(item, dict) or \"text\" not in item:\n", + " serialization_errors += 1\n", + " continue\n", + " json_string = json.dumps(item, ensure_ascii=False)\n", + " if json_string and not json_string.isspace():\n", + " json_lines_to_write.append(json_string)\n", + " else:\n", + " serialization_errors +=1\n", + " except (TypeError, ValueError):\n", + " serialization_errors += 1\n", + " except Exception: # Catch any other unexpected error during serialization\n", + " serialization_errors += 1\n", + " \n", + " if json_lines_to_write:\n", + " try:\n", + " with open(filename, mode, encoding='utf-8') as f:\n", + " f.write('\\n'.join(json_lines_to_write) + '\\n')\n", + " lines_written = len(json_lines_to_write)\n", + " except IOError:\n", + " print(f\"\\n错误: 写入文件 '{filename}' IO错误。\")\n", + " return 0 # Indicate failure\n", + " except Exception as e:\n", + " print(f\"\\n错误: 写入文件时发生未知错误: {e}\")\n", + " return 0\n", + " \n", + " if serialization_errors > 0:\n", + " print(f\"\\n警告: 写入批次时 {serialization_errors} 个项目序列化失败。\")\n", + " return lines_written\n", + "\n", + "# --- 主要生成函数 ---\n", + "def generate_gibberish_qa_dataset(\n", + " filename: str,\n", + " total_samples: int,\n", + " min_len: int,\n", + " max_len: int,\n", + " char_pool: str,\n", + " answer_text: str,\n", + " batch_size: int\n", + " ):\n", + " print(f\"--- 开始生成乱码问答数据集 (v1.0) ---\")\n", + " print(f\"总样本数: {total_samples:,}\")\n", + " print(f\"乱码长度范围: {min_len}-{max_len}\")\n", + " print(f\"字符池大小: {len(char_pool)}\")\n", + " print(f\"固定答案: '{answer_text}'\")\n", + " print(f\"输出文件: '{filename}'\")\n", + "\n", + " generated_count = 0\n", + " total_lines_written = 0\n", + " output_buffer: List[Dict] = []\n", + " \n", + " start_time_generate = time.time()\n", + " last_reported_count = -1\n", + " last_save_time = start_time_generate\n", + "\n", + " try:\n", + " # 初始化/清空输出文件\n", + " with open(filename, 'w', encoding='utf-8') as f:\n", + " f.write(\"\") \n", + " print(f\"已初始化/清空输出文件: '{filename}'\")\n", + " except IOError as e:\n", + " print(f\"\\n错误:无法初始化输出文件 '{filename}': {e}\")\n", + " return\n", + "\n", + " print(f\"\\n开始生成 {total_samples:,} 条数据...\")\n", + "\n", + " while generated_count < total_samples:\n", + " try:\n", + " question_gibberish = generate_gibberish_string(min_len, max_len, char_pool)\n", + " \n", + " # 构建最终输出 text\n", + " text_content = f\"User: {question_gibberish}\\n\\nAssistant: {answer_text}\"\n", + " \n", + " pair_data = {\"text\": text_content}\n", + " output_buffer.append(pair_data)\n", + " generated_count += 1\n", + "\n", + " # 批量保存\n", + " if len(output_buffer) >= batch_size:\n", + " write_op_start_time = time.time()\n", + " num_written_this_batch = write_batch_to_jsonl(output_buffer, filename, mode='a')\n", + " write_op_duration = time.time() - write_op_start_time\n", + " \n", + " if num_written_this_batch > 0:\n", + " total_lines_written += num_written_this_batch\n", + " avg_save_sps = num_written_this_batch / write_op_duration if write_op_duration > 0 else float('inf')\n", + " print(f\"\\r--- 已保存批次 {num_written_this_batch:>6,} (耗时 {write_op_duration:.2f}s, {avg_save_sps:.1f}/s). 总计写入: {total_lines_written:>8,} / 生成: {generated_count:>8,} ---{' '*5}\", end=\"\")\n", + " output_buffer.clear()\n", + " last_save_time = time.time()\n", + " else:\n", + " # Error during writing, could be disk full or permissions.\n", + " # Attempting to continue might just repeat the error.\n", + " print(f\"\\n严重警告: 写入批处理失败 (已生成 {generated_count:,} 条)。脚本将终止以避免数据丢失或进一步错误。\")\n", + " break \n", + "\n", + " # 进度报告\n", + " report_freq_interval = max(1, total_samples // 100) if total_samples > 0 else 100\n", + " current_time = time.time()\n", + " time_since_last_activity = current_time - max(last_save_time, start_time_generate if last_reported_count == -1 else last_save_time)\n", + "\n", + " if generated_count > 0 and (generated_count % report_freq_interval == 0 or generated_count == total_samples or time_since_last_activity > 10):\n", + " if last_reported_count != generated_count:\n", + " progress_percent = generated_count / total_samples if total_samples > 0 else 0\n", + " elapsed_seconds = current_time - start_time_generate\n", + " samples_per_sec_rate = generated_count / elapsed_seconds if elapsed_seconds > 0 else 0\n", + " \n", + " est_remaining_time_str = \"N/A\"\n", + " if progress_percent > 1e-6 and samples_per_sec_rate > 0:\n", + " remaining_samples_to_gen = total_samples - generated_count\n", + " est_remaining_seconds = remaining_samples_to_gen / samples_per_sec_rate\n", + " if est_remaining_seconds < 60: est_remaining_time_str = f\"{est_remaining_seconds:.0f}s\"\n", + " elif est_remaining_seconds < 3600: est_remaining_time_str = f\"{est_remaining_seconds/60:.1f}m\"\n", + " else: est_remaining_time_str = f\"{est_remaining_seconds/3600:.1f}h\"\n", + " \n", + " stats_line = f\"生成: {generated_count:>8,}/{total_samples:<8,} ({progress_percent:5.1%}) | 写入: {total_lines_written:>8,} | {samples_per_sec_rate:6.1f} 样本/秒 | 耗时: {elapsed_seconds:6.1f}s | 剩余: ~{est_remaining_time_str:<5}\"\n", + " print(f\"\\r{stats_line.ljust(100)}\", end=\"\")\n", + " last_reported_count = generated_count\n", + "\n", + " except KeyboardInterrupt:\n", + " print(\"\\n用户中断。\")\n", + " break\n", + " except Exception as e:\n", + " print(f\"\\n生成过程中发生错误: {e}\")\n", + " # Decide if you want to break or continue\n", + " # For now, let's break on unexpected errors to investigate\n", + " break \n", + " \n", + " # --- 循环结束后 ---\n", + " print(\" \" * 100, end=\"\\r\") # Clear progress line\n", + " print(f\"\\n生成循环结束。目标: {total_samples:,}, 实际生成: {generated_count:,}.\")\n", + "\n", + " if output_buffer:\n", + " print(f\"写入最后 {len(output_buffer):,} 条数据...\")\n", + " final_write_start = time.time()\n", + " num_final_written = write_batch_to_jsonl(output_buffer, filename, mode='a')\n", + " final_write_duration = time.time() - final_write_start\n", + " if num_final_written > 0:\n", + " total_lines_written += num_final_written\n", + " print(f\"最终批次写入完成 ({num_final_written:,} 条). 耗时: {final_write_duration:.2f}s.\")\n", + " else:\n", + " print(\"警告: 最终批次写入失败.\")\n", + " output_buffer.clear()\n", + " else:\n", + " print(\"无剩余数据需写入.\")\n", + "\n", + " total_generation_end_time = time.time()\n", + " total_generation_duration = total_generation_end_time - start_time_generate\n", + "\n", + " print(f\"\\n生成与写入完毕。目标: {total_samples:,} -> 生成: {generated_count:,} -> 写入: {total_lines_written:,}\")\n", + " if total_lines_written != generated_count and generated_count > 0:\n", + " print(f\"警告: 写入行数({total_lines_written:,}) 与 生成数({generated_count:,}) 不匹配!\")\n", + " \n", + " print(f\"总耗时: {total_generation_duration:.2f} 秒。\")\n", + " print(\"=\"*50)\n", + "\n", + "\n", + "# ===============================================\n", + "# 主程序入口\n", + "# ===============================================\n", + "if __name__ == \"__main__\":\n", + " script_total_start_time = time.time()\n", + " print(\"=\"*30)\n", + " print(\" 乱码问答生成脚本 (v1.0) \")\n", + " print(\"=\"*30)\n", + "\n", + " try:\n", + " generate_gibberish_qa_dataset(\n", + " filename=OUTPUT_FILENAME,\n", + " total_samples=TOTAL_SAMPLES,\n", + " min_len=MIN_GIBBERISH_LENGTH,\n", + " max_len=MAX_GIBBERISH_LENGTH,\n", + " char_pool=CHARACTER_POOL,\n", + " answer_text=FIXED_ANSWER,\n", + " batch_size=BATCH_SAVE_SIZE\n", + " )\n", + " except ValueError as val_err: # Catch config errors\n", + " print(f\"\\n配置错误: {val_err}\")\n", + " except Exception as main_exec_err:\n", + " print(f\"\\n主程序发生未预料错误: {main_exec_err}\")\n", + " traceback.print_exc()\n", + " finally:\n", + " pass\n", + "\n", + " script_total_end_time = time.time()\n", + " print(\"\\n\" + \"=\"*30)\n", + " print(f\"脚本执行完毕。总耗时: {script_total_end_time - script_total_start_time:.2f} 秒。\")\n", + " print(f\"数据文件: {OUTPUT_FILENAME}\")\n", + " print(\"=\"*30)" + ] + }, + { + "cell_type": "markdown", + "id": "4fb9b8c9", + "metadata": {}, + "source": [ + "# 英文随机(整个数字+逐个字符)\n", + "\n", + "用于生成:\n", + "\n", + "训练集:ADD_en_random_mix\n", + "\n", + "测试集:ADD_en_mix_test" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9fcd42a9", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "==============================\n", + " 算术题生成脚本 (v10.15 - Independent Word Casing) \n", + "==============================\n", + "--- 开始生成算术数据 (v10.15 - Independent Word Casing) ---\n", + "数字格式概率: Standard Arabic: 30.0%, Full-width: 30.0%, English Words: 40.0%\n", + "英文数字大小写: 80% 整体(逐词独立风格)随机, 20% 逐字符随机\n", + "符号题中英文运算符概率: 30.0%\n", + "字符间随机空格 (数字/单词内部) 未启用。仅运算符周围有随机空格。\n", + "通用字符级损坏未启用。\n", + "已初始化/清空输出文件: 'qa_add_英文大小写混合-test.jsonl'\n", + "\n", + "开始构造 500 条满足条件的数据...\n", + "生成: 500/500 (100.0%) | 写入: 500 | 尝试: 500 ( 1.0/样本) | 失败率: 0.0% | 7738.1 样本/秒 | 耗时: 0.1s | 剩余: ~0s \n", + "构造循环结束。目标: 500, 实际生成: 500 (尝试 500 次, 构造失败 0 次).\n", + "无剩余数据需写入.\n", + "\n", + "生成与写入完毕。目标: 500 -> 生成: 500 -> 写入: 500\n", + "总尝试次数: 500 (平均 1.00 次/有效样本)\n", + "构造失败次数: 0 (失败率: 0.00%)\n", + "总耗时: 0.06 秒。格式化/计算/写入等循环内错误: 0.\n", + "\n", + "=============== 详细统计 (基于生成的有效样本) ===============\n", + "总有效样本: 500\n", + "--------------------------------------------------\n", + "1. 算术题类型:\n", + " - 加法: 253 ( 50.6%)\n", + " - 减法: 247 ( 49.4%)\n", + "--------------------------------------------------\n", + "2. 运算数类型:\n", + " - 纯整数运算*: 293 ( 58.6%)\n", + " - 含小数运算*: 207 ( 41.4%)\n", + " *注: 基于操作数或结果是否包含实际小数部分,或生成意图是否为小数。\n", + "--------------------------------------------------\n", + "3. 问题格式 - 操作数 A (总计: 500):\n", + " - standard : 153 ( 30.6%)\n", + " - full_width : 150 ( 30.0%)\n", + " - english_words : 197 ( 39.4%)\n", + "--------------------------------------------------\n", + "4. 问题格式 - 操作数 B (总计: 500):\n", + " - standard : 153 ( 30.6%)\n", + " - full_width : 150 ( 30.0%)\n", + " - english_words : 197 ( 39.4%)\n", + "--------------------------------------------------\n", + "5. 问题格式 - 符号题运算符 (总计符号题运算符: 347):\n", + " - 符号 (+, -): 230 ( 66.3%)\n", + " - 英文单词: 117 ( 33.7%)\n", + "--------------------------------------------------\n", + "6. 问题格式 - 类型 (总计: 500):\n", + " - 符号格式 (+/- or words) : 347 ( 69.4%)\n", + " - 自然语言格式 (English) : 153 ( 30.6%)\n", + "--------------------------------------------------\n", + "7. 符号问题格式 - 等号后缀 (总计符号问题: 347):\n", + " - 添加 ' = ?': 191 ( 55.0%)\n", + " - 未添加后缀: 156 ( 45.0%)\n", + "==================================================\n", + "\n", + "==============================\n", + "脚本执行完毕。总耗时: 0.07 秒。\n", + "数据文件: qa_add_英文大小写混合-test.jsonl\n", + "==============================\n" + ] + } + ], + "source": [ + "# -*- coding: utf-8 -*-\n", + "# 生成满足指定进/借位范围条件,且问题格式多样化的算术问题数据集脚本。\n", + "# 采用反向逐位构造方法优化生成效率。\n", + "# v10.15: For 'entire string' casing, each word in a phrase now gets an *independent* random style (lower, upper, title).\n", + "\n", + "import json\n", + "import random\n", + "import time\n", + "import math\n", + "from typing import List, Tuple, Union, Dict, Optional, Callable\n", + "from decimal import Decimal, getcontext, ROUND_DOWN, ROUND_HALF_UP, InvalidOperation\n", + "import traceback\n", + "from collections import Counter\n", + "import string\n", + "\n", + "# ===============================================\n", + "# 配置参数区域\n", + "# ===============================================\n", + "# --- 主要数量和文件名 ---\n", + "TOTAL_SAMPLES = 500\n", + "OUTPUT_FILENAME = f\"ADD_en_random_mix.jsonl\" \n", + "ADD_PROBABILITY: float = 0.5\n", + "BATCH_SAVE_SIZE: int = 20\n", + "\n", + "# --- 数字生成控制 ---\n", + "MAX_DIGITS: int = 12\n", + "MAX_DECIMAL_PLACES: int = 5\n", + "DECIMAL_PROBABILITY: float = 0.4\n", + "NEGATIVE_POOL_PROB: float = 0.1\n", + "SCI_THRESHOLD_POS = 10**70 \n", + "SCI_THRESHOLD_NEG = -60 \n", + "\n", + "# --- 进/借位条件范围 ---\n", + "TARGET_TOTAL_CARRIES_MIN: int = 0\n", + "TARGET_TOTAL_CARRIES_MAX: int = math.inf\n", + "TARGET_CONSECUTIVE_CARRIES_MIN: int = 0\n", + "TARGET_CONSECUTIVE_CARRIES_MAX: int = math.inf\n", + "\n", + "# --- 格式化控制 (问题部分数字的样式) ---\n", + "STANDARD_ARABIC_PROB: float = 0.30\n", + "FULL_WIDTH_ARABIC_PROB: float = 0.30\n", + "ENGLISH_WORDS_PROB: float = 0.40 \n", + "_format_prob_sum = STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB + ENGLISH_WORDS_PROB\n", + "if not math.isclose(_format_prob_sum, 1.0):\n", + " raise ValueError(f\"数字格式概率总和必须为 1.0,当前为: {_format_prob_sum}\")\n", + "\n", + "# --- English Number Casing Control ---\n", + "ENGLISH_NUMBER_ENTIRE_STRING_CASE_PROB: float = 0.8 # This now means \"apply independent word casing\"\n", + "\n", + "# --- Operator Word Control (for symbolic questions) ---\n", + "SYMBOLIC_OPERATOR_WORD_PROB: float = 0.3 \n", + "\n", + "# --- 字符间随机空格控制 ---\n", + "APPLY_INTRA_CHAR_SPACING: bool = False \n", + "\n", + "# --- 自然语言概率控制 ---\n", + "NL_QUESTION_PROBABILITY: float = 0.30\n", + "\n", + "# --- 等号后缀概率控制 (仅符号问题) ---\n", + "SYMBOLIC_EQUALS_SUFFIX_PROB: float = 0.50\n", + "\n", + "# --- 字符级随机替换控制 (通用,应用于最终文本) ---\n", + "APPLY_GENERAL_CHAR_REPLACEMENT: bool = False\n", + "GENERAL_CHAR_REPLACEMENT_PROBABILITY: float = 0.005\n", + "GENERAL_CHAR_REPLACEMENT_POOL: str = string.ascii_letters + string.digits + \".,?! \"\n", + "\n", + "# --- 其他控制 ---\n", + "MAX_ATTEMPTS_FACTOR = 5000\n", + "\n", + "# ===============================================\n", + "# 核心代码\n", + "# ===============================================\n", + "getcontext().prec = MAX_DIGITS + MAX_DECIMAL_PLACES + 30\n", + "\n", + "_ENGLISH_DIGITS = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"]\n", + "_ENGLISH_TEENS = [\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\n", + "_ENGLISH_TENS = [\"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\n", + "_ENGLISH_LARGE_UNITS = [\"\", \"thousand\", \"million\", \"billion\", \"trillion\", \"quadrillion\", \"quintillion\",\n", + " \"sextillion\", \"septillion\", \"octillion\", \"nonillion\", \"decillion\"]\n", + "\n", + "def _num_to_english_chunk(n: int) -> str:\n", + " # ... (Unchanged, produces raw lowercase words) ...\n", + " if not 0 <= n <= 999: return \"\"\n", + " if n == 0: return \"\"\n", + " parts = []\n", + " if n >= 100:\n", + " parts.append(_ENGLISH_DIGITS[n // 100])\n", + " parts.append(\"hundred\")\n", + " n %= 100\n", + " if n > 0:\n", + " if 0 < n < 10: parts.append(_ENGLISH_DIGITS[n])\n", + " elif 10 <= n < 20: parts.append(_ENGLISH_TEENS[n - 10])\n", + " else:\n", + " parts.append(_ENGLISH_TENS[n // 10])\n", + " if n % 10 > 0: parts.append(_ENGLISH_DIGITS[n % 10])\n", + " return \" \".join(parts)\n", + "\n", + "\n", + "def integer_to_english_words(num: int) -> str:\n", + " # ... (Unchanged, produces raw lowercase words with \"minus \" if negative) ...\n", + " if num == 0: return _ENGLISH_DIGITS[0]\n", + " if abs(num) > (10**(len(_ENGLISH_LARGE_UNITS) * 3) -1) :\n", + " return f\"Number too large for English word conversion ({num})\"\n", + " sign = \"minus \" if num < 0 else \"\" \n", + " num_abs = abs(num)\n", + " parts = []\n", + " chunk_index = 0\n", + " if num_abs == 0: return _ENGLISH_DIGITS[0] \n", + "\n", + " temp_num = num_abs\n", + " while temp_num > 0:\n", + " if temp_num % 1000 != 0:\n", + " chunk_words = _num_to_english_chunk(temp_num % 1000)\n", + " unit_word = _ENGLISH_LARGE_UNITS[chunk_index] if chunk_index > 0 else \"\"\n", + " if unit_word: parts.append(unit_word)\n", + " parts.append(chunk_words)\n", + " temp_num //= 1000\n", + " chunk_index += 1\n", + " if chunk_index >= len(_ENGLISH_LARGE_UNITS) and temp_num > 0:\n", + " return f\"Number too large for defined English units ({temp_num} remaining, index {chunk_index})\"\n", + " \n", + " result_words = \" \".join(p for p in reversed(parts) if p).strip() \n", + " return (sign + result_words).strip()\n", + "\n", + "def decimal_to_english_words(num: Decimal) -> str:\n", + " # ... (Unchanged, produces raw lowercase words with \"minus \", \"point\") ...\n", + " if not isinstance(num, Decimal) or not num.is_finite():\n", + " return \"Invalid number for English conversion\"\n", + " if num.is_zero() and num.is_signed(): num = Decimal('0')\n", + " \n", + " sign_str = \"\"\n", + " num_abs_for_words = abs(num)\n", + " if num < 0: sign_str = \"minus \"\n", + "\n", + " int_part_val = int(num_abs_for_words.to_integral_value(rounding=ROUND_DOWN))\n", + " frac_part_dec = num_abs_for_words - Decimal(int_part_val)\n", + " \n", + " int_words = integer_to_english_words(int_part_val)\n", + " \n", + " if frac_part_dec.is_zero():\n", + " return (sign_str + int_words).strip()\n", + "\n", + " s_num_abs_for_frac = format_decimal_or_int(num_abs_for_words)\n", + " if '.' not in s_num_abs_for_frac:\n", + " return (sign_str + int_words).strip() \n", + " \n", + " _, frac_str_digits = s_num_abs_for_frac.split('.', 1)\n", + " frac_word_list = []\n", + " if frac_str_digits:\n", + " for digit_char in frac_str_digits:\n", + " if digit_char.isdigit(): frac_word_list.append(_ENGLISH_DIGITS[int(digit_char)])\n", + " \n", + " if not frac_word_list:\n", + " return (sign_str + int_words).strip()\n", + "\n", + " point_word_raw = \"point\" \n", + " \n", + " final_assembly_parts = [int_words] \n", + " if point_word_raw: final_assembly_parts.append(point_word_raw)\n", + " if frac_word_list: final_assembly_parts.extend(frac_word_list)\n", + " \n", + " assembled_num_words = \" \".join(p for p in final_assembly_parts if p)\n", + " return (sign_str + assembled_num_words).strip()\n", + "\n", + "\n", + "def decimal_to_english_scientific(num: Decimal) -> str:\n", + " # This function now returns a list of tuples: (raw_word, type)\n", + " # type can be 'number' or 'operator' for different casing by the caller.\n", + " if not isinstance(num, Decimal) or not num.is_finite():\n", + " return \"Invalid number for English scientific conversion\" # Return string for error\n", + " \n", + " if num.is_zero(): \n", + " return _ENGLISH_DIGITS[0] # Raw \"zero\", caller will case as number\n", + "\n", + " raw_word_parts = [] # List to hold raw words before casing by caller\n", + "\n", + " if num < 0:\n", + " raw_word_parts.append(\"minus\")\n", + " num = abs(num)\n", + "\n", + " try:\n", + " sci_str = \"{:e}\".format(num.normalize()) \n", + " coeff_str, exp_str = sci_str.lower().split('e')\n", + " \n", + " coeff_dec = Decimal(coeff_str) \n", + " exp_int = int(exp_str)\n", + "\n", + " coeff_english_raw = decimal_to_english_words(coeff_dec) \n", + " exp_english_raw = integer_to_english_words(exp_int) # Handles its own sign if exp_int is negative\n", + "\n", + " raw_word_parts.extend(coeff_english_raw.split())\n", + " raw_word_parts.append(\"times\")\n", + " raw_word_parts.append(\"ten\")\n", + " raw_word_parts.extend(\"to the power of\".split())\n", + " raw_word_parts.extend(exp_english_raw.split())\n", + " \n", + " return \" \".join(p for p in raw_word_parts if p)\n", + "\n", + " except Exception:\n", + " return format_decimal_or_int(num) # Fallback to string\n", + "\n", + "\n", + "# --- Casing Functions (NEW AND MODIFIED) ---\n", + "def _apply_random_word_case_style(word: str) -> str:\n", + " \"\"\"Applies a randomly chosen style (lower, upper, title) to a single word.\"\"\"\n", + " if not word or not any(c.isalpha() for c in word):\n", + " return word\n", + " \n", + " style_choice = random.random()\n", + " if style_choice < 0.4: # All lowercase\n", + " return word.lower()\n", + " elif style_choice < 0.8: # All uppercase\n", + " return word.upper()\n", + " else: # Title case (capitalize first letter)\n", + " return word.capitalize()\n", + "\n", + "def _apply_independent_word_casing(text: str) -> str:\n", + " \"\"\"\n", + " Splits text into words, and applies an *independent* random word case style\n", + " (lower, upper, title) to each word.\n", + " \"\"\"\n", + " if not text or not any(c.isalpha() for c in text):\n", + " return text\n", + "\n", + " words = text.split(' ')\n", + " cased_words = [_apply_random_word_case_style(word) for word in words]\n", + " return \" \".join(cased_words)\n", + "\n", + "def _apply_random_case_char_by_char(text: str) -> str:\n", + " \"\"\"Applies random casing to each character of the text.\"\"\"\n", + " if not text or not any(c.isalpha() for c in text):\n", + " return text\n", + " return \"\".join(random.choice([char.lower(), char.upper()]) if char.isalpha() else char for char in text)\n", + "\n", + "def _apply_random_case_number_style(text: str) -> str:\n", + " \"\"\"Applies casing to a string representing a number in words.\"\"\"\n", + " if not text or not any(c.isalpha() for c in text): return text\n", + " if random.random() < ENGLISH_NUMBER_ENTIRE_STRING_CASE_PROB:\n", + " # This now means: apply independent random style to each word of the number phrase\n", + " return _apply_independent_word_casing(text) \n", + " else:\n", + " # This remains: apply random casing to each character of the entire phrase\n", + " return _apply_random_case_char_by_char(text)\n", + "\n", + "def _apply_random_case_operator_style(text: str) -> str:\n", + " \"\"\"Applies casing to a string representing an operator or keyword in words.\"\"\"\n", + " # Operators/keywords also follow the independent word casing for their \"entire string\" style.\n", + " # There's no char-by-char option for operators in this setup, but could be added if needed.\n", + " if not text or not any(c.isalpha() for c in text): return text\n", + " return _apply_independent_word_casing(text) \n", + "\n", + "\n", + "# --- Formatting and Utility functions ---\n", + "half_to_full_map = str.maketrans(\"0123456789.-+\", \"0123456789.-+\")\n", + "def to_full_width(text: str) -> str: return text.translate(half_to_full_map)\n", + "\n", + "def format_decimal_or_int(num: Union[int, Decimal]) -> str:\n", + " # ... (Unchanged) ...\n", + " try:\n", + " if isinstance(num, int): return str(num)\n", + " if isinstance(num, Decimal):\n", + " if not num.is_finite(): return str(num)\n", + " num_normalized = num.normalize()\n", + " if num_normalized.is_zero() and num_normalized.is_signed():\n", + " num_normalized = Decimal('0')\n", + " s = num_normalized.to_eng_string()\n", + " if '.' in s:\n", + " integer_part, decimal_part = s.split('.', 1)\n", + " if all(c == '0' for c in decimal_part): s = integer_part\n", + " if s.startswith('.'): s = '0' + s\n", + " if s.startswith('-.'): s = '-0' + s[1:]\n", + " if not s: s = \"0\"\n", + " return s\n", + " return str(num)\n", + " except Exception:\n", + " try:\n", + " normalized_num = Decimal(str(num)).normalize()\n", + " if normalized_num.is_zero() and normalized_num.is_signed():\n", + " normalized_num = Decimal('0')\n", + " temp_s = \"{:f}\".format(normalized_num)\n", + " if '.' in temp_s:\n", + " integer_part, decimal_part = temp_s.split('.', 1)\n", + " decimal_part = decimal_part.rstrip('0')\n", + " if not decimal_part: temp_s = integer_part\n", + " else: temp_s = integer_part + '.' + decimal_part\n", + " if not temp_s: temp_s = \"0\"\n", + " return temp_s\n", + " except: return str(num)\n", + "\n", + "def _insert_random_intra_char_spacing(text: str) -> str: # Unchanged (disabled)\n", + " if not text or not APPLY_INTRA_CHAR_SPACING or len(text) <= 1: return text\n", + " return text \n", + "\n", + "def format_number_variant(num: Union[int, Decimal]) -> Tuple[str, str]:\n", + " fmt_choice = random.random()\n", + " try: num_dec = Decimal(str(num)) if not isinstance(num, Decimal) else num\n", + " except InvalidOperation: return str(num), 'standard'\n", + " target_format_name = 'standard'\n", + " if fmt_choice < STANDARD_ARABIC_PROB: target_format_name = 'standard'\n", + " elif fmt_choice < STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB: target_format_name = 'full_width'\n", + " else: target_format_name = 'english_words'\n", + "\n", + " def finalize_output(s: str, fmt_name: str) -> Tuple[str, str]:\n", + " final_s = _insert_random_intra_char_spacing(s) \n", + " return final_s, fmt_name\n", + "\n", + " try:\n", + " if not num_dec.is_finite():\n", + " s_num_non_finite = str(num_dec)\n", + " res_str = to_full_width(s_num_non_finite) if target_format_name == 'full_width' else s_num_non_finite\n", + " actual_fmt_name = target_format_name if target_format_name != 'english_words' else 'standard'\n", + " return finalize_output(res_str, actual_fmt_name)\n", + " \n", + " s_formatted_arabic = format_decimal_or_int(num_dec)\n", + "\n", + " if target_format_name == 'standard':\n", + " return finalize_output(s_formatted_arabic, 'standard')\n", + " elif target_format_name == 'full_width':\n", + " return finalize_output(to_full_width(s_formatted_arabic), 'full_width')\n", + " elif target_format_name == 'english_words':\n", + " exponent = num_dec.normalize().adjusted()\n", + " use_sci_english = (exponent >= math.log10(SCI_THRESHOLD_POS) if SCI_THRESHOLD_POS > 0 else False) or \\\n", + " (exponent <= SCI_THRESHOLD_NEG if SCI_THRESHOLD_NEG != 0 else False)\n", + " \n", + " final_english_str_cased = \"\"\n", + " raw_english_phrase = \"\"\n", + "\n", + " if use_sci_english:\n", + " raw_english_phrase = decimal_to_english_scientific(num_dec)\n", + " # Scientific phrases are complex. \"minus one point two three times ten to the power of five\"\n", + " # \"minus\", \"times\", \"to the power of\" are operators. \"one point two three\", \"ten\", \"five\" are numbers.\n", + " # For simplicity with scientific, we'll apply _apply_random_case_number_style to the whole phrase.\n", + " # A more granular approach would require decimal_to_english_scientific to return structured parts.\n", + " # Let's try to make decimal_to_english_scientific do the casing internally.\n", + " # UPDATE: decimal_to_english_scientific was changed to return raw words.\n", + " # We will case it here.\n", + " # The issue is that \"times\", \"ten\", \"to the power of\" should get operator style.\n", + " # \"minus\" (if present), coeff, exponent get number style.\n", + "\n", + " # Simpler approach for scientific: let _apply_random_case_number_style handle it.\n", + " # It will apply independent word casing if chosen for \"entire string\" style.\n", + " # This means \"times\" might become \"TIMES\" and \"ten\" \"ten\" etc. which is the goal.\n", + " if \"Invalid\" in raw_english_phrase or \"too large\" in raw_english_phrase: # Check raw output\n", + " final_english_str_cased = s_formatted_arabic # Fallback to arabic\n", + " target_format_name = 'standard' # Change type if falling back\n", + " else:\n", + " final_english_str_cased = _apply_random_case_number_style(raw_english_phrase)\n", + "\n", + " else: # Regular number to words\n", + " raw_english_phrase = decimal_to_english_words(num_dec)\n", + " if \"Invalid\" in raw_english_phrase or \"too large\" in raw_english_phrase:\n", + " final_english_str_cased = s_formatted_arabic\n", + " target_format_name = 'standard'\n", + " else:\n", + " final_english_str_cased = _apply_random_case_number_style(raw_english_phrase)\n", + " \n", + " return finalize_output(final_english_str_cased, target_format_name) # Use potentially updated target_format_name\n", + " else: return finalize_output(s_formatted_arabic, 'standard') \n", + " \n", + " except Exception: \n", + " try:\n", + " fallback_str = format_decimal_or_int(num_dec if 'num_dec' in locals() else num)\n", + " return finalize_output(fallback_str, 'standard')\n", + " except: return finalize_output(str(num), 'standard')\n", + "\n", + "\n", + "def get_realistic_spacing() -> str: # Unchanged\n", + " space_values = [\"\", \" \", \" \"]; space_weights = [0.8, 0.15, 0.05]\n", + " _sw_sum = sum(space_weights)\n", + " if not math.isclose(_sw_sum, 1.0):\n", + " if _sw_sum > 1e-9 : space_weights = [w/_sw_sum for w in space_weights]\n", + " else: space_weights = [1.0/len(space_values)] * len(space_values)\n", + " try: return random.choices(space_values, weights=space_weights, k=1)[0]\n", + " except Exception: return \"\"\n", + "\n", + "def contains_arabic_numerals(s: str) -> bool: # Unchanged\n", + " return any(c in \"01234567890123456789\" for c in s)\n", + "\n", + "def get_distributed_count_from_probs(population: List[int], probabilities: List[float]) -> int: # Unchanged\n", + " if not population: return 1\n", + " if not probabilities or len(population) != len(probabilities) or not all(p >= 0 for p in probabilities):\n", + " return random.choice(population) if population else 1\n", + " prob_sum = sum(probabilities)\n", + " if prob_sum < 1e-9: return random.choice(population) if population else 1\n", + " normalized_probabilities = probabilities\n", + " if not math.isclose(prob_sum, 1.0, abs_tol=1e-5):\n", + " try: normalized_probabilities = [p / prob_sum for p in probabilities]\n", + " except ZeroDivisionError: return random.choice(population) if population else 1\n", + " try: return random.choices(population, weights=normalized_probabilities, k=1)[0]\n", + " except Exception: return random.choice(population) if population else 1\n", + "\n", + "def calculate_digit_probabilities(max_digits: int) -> Dict[int, float]: # Unchanged\n", + " if max_digits <= 0: return {1: 1.0}\n", + " raw_probs = {}; prob_sum = Decimal('0.0'); base_prob = Decimal('0.1'); decay_factor = Decimal('0.95'); increase_factor = Decimal('1.05')\n", + " for n in range(1, max_digits + 1):\n", + " prob = base_prob * (decay_factor**(n - 1)) * (increase_factor**(max_digits - n + 1)); prob = max(Decimal('0.001'), prob); raw_probs[n] = prob; prob_sum += prob\n", + " normalized_probs = {}\n", + " if prob_sum <= 0: fallback_prob = 1.0 / max(1, max_digits); normalized_probs = {n: fallback_prob for n in range(1, max_digits + 1)}\n", + " else: normalized_probs = {n: float(p / prob_sum) for n, p in raw_probs.items()}\n", + " final_sum = sum(normalized_probs.values())\n", + " if not math.isclose(final_sum, 1.0, abs_tol=1e-9):\n", + " renorm_factor = 1.0 / final_sum if final_sum != 0 else 1.0; total = 0.0; keys = sorted(normalized_probs.keys())\n", + " for i, n_key in enumerate(keys):\n", + " if i == len(keys) - 1: normalized_probs[n_key] = max(0.0, 1.0 - total)\n", + " else: norm_p = max(0.0, normalized_probs[n_key] * renorm_factor); normalized_probs[n_key] = norm_p; total += norm_p\n", + " if keys: normalized_probs[keys[-1]] = max(0.0, normalized_probs[keys[-1]])\n", + " return normalized_probs\n", + "\n", + "ENGLISH_OPERATOR_WORDS = {\n", + " '+': [\"plus\", \"add\", \"and\"],\n", + " '-': [\"minus\", \"subtract\", \"take away\", \"less\"]\n", + "}\n", + "\n", + "def format_natural_language_question(fmt_a: str, fmt_b: str, op_sym: str) -> str:\n", + " # Relies on _apply_random_case_operator_style for word casing\n", + " raw_add_words = [\"plus\", \"added to\", \"and\", \"combined with\", \"summed with\"]\n", + " raw_subtract_words = [\"minus\", \"subtract\", \"take away\", \"less\", \"deducted by\"]\n", + " \n", + " result_phrases_en_raw = [\"equals what\", \"is what\", \"results in what\", \"gives what\", \"what is the total\", \"what is the difference\", \"how much is that\"]\n", + " question_marks = [\"?\", \"\"]\n", + " templates = []\n", + " \n", + " chosen_op_word_cased = op_sym # Default to symbol if not a word\n", + " if op_sym == '+':\n", + " chosen_op_word_cased = _apply_random_case_operator_style(random.choice(raw_add_words))\n", + " templates.extend([\n", + " \"What is {num_a} {op} {num_b}{q_mark}\", \"Calculate {num_a} {op} {num_b}{q_mark}\",\n", + " \"If you have {num_a} and add {num_b}, what do you get{q_mark}\",\n", + " \"{num_a} {op} {num_b} {res_phrase}{q_mark}\",\n", + " \"The sum of {num_a} and {num_b} {res_phrase}{q_mark}\",])\n", + " elif op_sym == '-':\n", + " chosen_op_word_cased = _apply_random_case_operator_style(random.choice(raw_subtract_words))\n", + " templates.extend([\n", + " \"What is {num_a} {op} {num_b}{q_mark}\", \"Calculate {num_a} {op} {num_b}{q_mark}\",\n", + " \"If you have {num_a} and take away {num_b}, what remains{q_mark}\",\n", + " \"{num_a} {op} {num_b} {res_phrase}{q_mark}\",\n", + " \"The difference between {num_a} and {num_b} {res_phrase}{q_mark}\",])\n", + " else: return f\"{fmt_a} {op_sym} {fmt_b}\" # Should not happen for +,-\n", + " \n", + " if not templates: return f\"{fmt_a} {op_sym} {fmt_b} = ?\"\n", + " \n", + " chosen_template = random.choice(templates)\n", + " chosen_res_phrase_cased = _apply_random_case_operator_style(random.choice(result_phrases_en_raw))\n", + " chosen_q_mark = random.choice(question_marks)\n", + " \n", + " try:\n", + " placeholders = {\"num_a\": fmt_a, \"num_b\": fmt_b, \"op\": chosen_op_word_cased, \n", + " \"res_phrase\": chosen_res_phrase_cased, \"q_mark\": chosen_q_mark}\n", + " format_args = {k: v for k, v in placeholders.items() if \"{\"+k+\"}\" in chosen_template}\n", + " question_str = chosen_template.format(**format_args)\n", + " question_str = ' '.join(question_str.split()) \n", + " except KeyError: question_str = f\"{fmt_a} {op_sym} {fmt_b} = ?\" \n", + " return question_str\n", + "\n", + "\n", + "def _generate_pair_meeting_cb_criteria(\n", + " target_digits_a: int, target_digits_b: int, sign_a: int, sign_b: int,\n", + " is_decimal: bool, max_decimal_places_config: int, operation_type: str,\n", + " target_total_cb_min: int, target_total_cb_max: Union[int, float],\n", + " target_consecutive_cb_min: int, target_consecutive_cb_max: Union[int, float]\n", + ") -> Optional[Tuple[Union[int, Decimal], Union[int, Decimal]]]:\n", + " # ... (Unchanged) ...\n", + " num_dp = random.randint(1, max_decimal_places_config) if is_decimal and max_decimal_places_config > 0 else 0\n", + " num_int_digits_a = max(1, target_digits_a); num_int_digits_b = max(1, target_digits_b)\n", + " total_len_a = num_int_digits_a + num_dp; total_len_b = num_int_digits_b + num_dp\n", + " max_total_len = max(total_len_a, total_len_b)\n", + " if max_total_len == 0 and num_dp == 0: max_total_len = 1 \n", + " elif max_total_len == 0 and num_dp > 0 : max_total_len = num_dp \n", + "\n", + " effective_op = operation_type\n", + " if operation_type == 'add':\n", + " if sign_a * sign_b < 0: effective_op = 'subtract'\n", + " elif operation_type == 'subtract':\n", + " if sign_a * sign_b < 0: effective_op = 'add'\n", + " op1_digits_rev = []; op2_digits_rev = []\n", + " carry_in = 0; borrow_in = 0\n", + " current_total_cb = 0; current_consecutive_cb = 0; max_consecutive_achieved = 0\n", + " op1_target_len = total_len_a; op2_target_len = total_len_b\n", + " op1_int_digits_orig = num_int_digits_a; op2_int_digits_orig = num_int_digits_b \n", + " is_unlimited_cb_range = (target_total_cb_min == 0 and target_total_cb_max == math.inf and \\\n", + " target_consecutive_cb_min == 0 and target_consecutive_cb_max == math.inf)\n", + " for i in range(max_total_len):\n", + " pos_from_right = i; is_decimal_pos = (pos_from_right < num_dp)\n", + " is_int_pos = not is_decimal_pos; int_pos_from_right = pos_from_right - num_dp if is_int_pos else -1\n", + " \n", + " in_op1 = (pos_from_right < op1_target_len); \n", + " in_op2 = (pos_from_right < op2_target_len)\n", + " \n", + " is_msd_op1_int = in_op1 and is_int_pos and int_pos_from_right == op1_int_digits_orig - 1\n", + " is_msd_op2_int = in_op2 and is_int_pos and int_pos_from_right == op2_int_digits_orig - 1\n", + "\n", + " min_d1 = 0; max_d1 = 0\n", + " if in_op1:\n", + " min_d1 = 1 if is_msd_op1_int and (op1_int_digits_orig > 0 or (op1_int_digits_orig == 0 and num_dp == 0 and total_len_a == 1)) else 0\n", + " max_d1 = 9\n", + " \n", + " min_d2 = 0; max_d2 = 0\n", + " if in_op2:\n", + " min_d2 = 1 if is_msd_op2_int and (op2_int_digits_orig > 0 or (op2_int_digits_orig == 0 and num_dp == 0 and total_len_b == 1)) else 0\n", + " max_d2 = 9\n", + " \n", + " if op1_int_digits_orig == 0 and is_msd_op1_int: min_d1 = 0\n", + " if op2_int_digits_orig == 0 and is_msd_op2_int: min_d2 = 0\n", + "\n", + " target_cb_state_for_this_pos = None\n", + " if not is_unlimited_cb_range:\n", + " positions_remaining = max_total_len - (i + 1)\n", + " min_total_cb_needed_later = max(0, target_total_cb_min - current_total_cb)\n", + " max_total_cb_allowed_later = float('inf') if target_total_cb_max == math.inf else target_total_cb_max - current_total_cb\n", + " if max_total_cb_allowed_later < 0: return None\n", + " min_consecutive_cb_needed_from_here = max(0, target_consecutive_cb_min - current_consecutive_cb)\n", + " must_generate_cb = (min_total_cb_needed_later > positions_remaining) or \\\n", + " (min_consecutive_cb_needed_from_here > positions_remaining and \\\n", + " max_consecutive_achieved < target_consecutive_cb_min and \\\n", + " current_consecutive_cb < target_consecutive_cb_min)\n", + " must_avoid_cb_due_to_total = (max_total_cb_allowed_later < 1)\n", + " must_avoid_cb_due_to_consecutive = (current_consecutive_cb + 1 > target_consecutive_cb_max) if target_consecutive_cb_max != math.inf else False\n", + " must_avoid_cb = must_avoid_cb_due_to_total or must_avoid_cb_due_to_consecutive\n", + " if must_generate_cb and must_avoid_cb : return None\n", + " if must_generate_cb: target_cb_state_for_this_pos = True\n", + " elif must_avoid_cb: target_cb_state_for_this_pos = False\n", + " else:\n", + " prob_try_generate_cb = 0.5 \n", + " if min_total_cb_needed_later > 0 : prob_try_generate_cb += 0.2 * (min_total_cb_needed_later / max(1, positions_remaining +1))\n", + " if min_consecutive_cb_needed_from_here > 0 and max_consecutive_achieved < target_consecutive_cb_min : prob_try_generate_cb += 0.3\n", + " if target_total_cb_max != math.inf and max_total_cb_allowed_later <= positions_remaining : prob_try_generate_cb -= 0.2 * (1 - max_total_cb_allowed_later / max(1, positions_remaining +1))\n", + " if target_consecutive_cb_max != math.inf and current_consecutive_cb +1 >= target_consecutive_cb_max and min_consecutive_cb_needed_from_here == 0: prob_try_generate_cb = 0.1 \n", + " prob_try_generate_cb = max(0.05, min(0.95, prob_try_generate_cb)) \n", + " target_cb_state_for_this_pos = (random.random() < prob_try_generate_cb)\n", + " \n", + " found_d1_d2_pair_for_pos = False\n", + " possible_d1_values = list(range(min_d1, max_d1 + 1)); random.shuffle(possible_d1_values)\n", + " chosen_d1, chosen_d2 = -1, -1\n", + " for d1_try in possible_d1_values:\n", + " possible_d2_values_for_d1_try = []\n", + " d2_value_range = list(range(min_d2, max_d2 + 1)); random.shuffle(d2_value_range)\n", + " for d2_try in d2_value_range:\n", + " cb_generated_by_this_pair = False\n", + " if effective_op == 'add': cb_generated_by_this_pair = ((d1_try + d2_try + carry_in) >= 10)\n", + " else: cb_generated_by_this_pair = ((d1_try - borrow_in - d2_try) < 0)\n", + " cb_state_matches_target = (target_cb_state_for_this_pos is None) or (cb_generated_by_this_pair == target_cb_state_for_this_pos)\n", + " temp_next_consecutive_cb = current_consecutive_cb + 1 if cb_generated_by_this_pair else 0\n", + " consecutive_constraint_ok = True\n", + " if target_consecutive_cb_max != math.inf and temp_next_consecutive_cb > target_consecutive_cb_max: consecutive_constraint_ok = False\n", + " min_consecutive_still_achievable = True\n", + " if not cb_generated_by_this_pair and target_consecutive_cb_min > 0:\n", + " max_achieved_before_reset = max(max_consecutive_achieved, current_consecutive_cb)\n", + " if max_achieved_before_reset < target_consecutive_cb_min and positions_remaining < target_consecutive_cb_min : min_consecutive_still_achievable = False\n", + " if cb_state_matches_target and consecutive_constraint_ok and min_consecutive_still_achievable: possible_d2_values_for_d1_try.append(d2_try)\n", + " if possible_d2_values_for_d1_try:\n", + " chosen_d2 = random.choice(possible_d2_values_for_d1_try); chosen_d1 = d1_try\n", + " found_d1_d2_pair_for_pos = True; break\n", + " if not found_d1_d2_pair_for_pos: return None\n", + " op1_digits_rev.append(str(chosen_d1)); op2_digits_rev.append(str(chosen_d2))\n", + " cb_occurred_at_this_pos = False\n", + " if effective_op == 'add':\n", + " current_sum_val = chosen_d1 + chosen_d2 + carry_in; carry_in = 1 if current_sum_val >= 10 else 0; borrow_in = 0\n", + " cb_occurred_at_this_pos = (carry_in == 1)\n", + " else:\n", + " current_diff_val = chosen_d1 - borrow_in - chosen_d2; borrow_in = 1 if current_diff_val < 0 else 0; carry_in = 0\n", + " cb_occurred_at_this_pos = (borrow_in == 1)\n", + " if cb_occurred_at_this_pos: current_total_cb += 1; current_consecutive_cb += 1\n", + " else: max_consecutive_achieved = max(max_consecutive_achieved, current_consecutive_cb); current_consecutive_cb = 0\n", + " max_consecutive_achieved = max(max_consecutive_achieved, current_consecutive_cb)\n", + " if not is_unlimited_cb_range:\n", + " total_cb_ok = (target_total_cb_min <= current_total_cb <= target_total_cb_max)\n", + " consecutive_cb_ok = (max_consecutive_achieved >= target_consecutive_cb_min) and \\\n", + " (target_consecutive_cb_max == math.inf or max_consecutive_achieved <= target_consecutive_cb_max)\n", + " if not (total_cb_ok and consecutive_cb_ok): return None\n", + " op1_str_msd_first = \"\".join(reversed(op1_digits_rev)); op2_str_msd_first = \"\".join(reversed(op2_digits_rev))\n", + "\n", + " def _format_digit_str_to_decimal_val(s: str, dp_count: int) -> Decimal:\n", + " if not s: s = \"0\"\n", + " total_digits_in_s = len(s)\n", + " if dp_count > 0:\n", + " int_part_len_in_s = total_digits_in_s - dp_count\n", + " if int_part_len_in_s <=0:\n", + " integer_str = \"0\"\n", + " fractional_str = s.zfill(dp_count)\n", + " else:\n", + " integer_str = s[:int_part_len_in_s]\n", + " fractional_str = s[int_part_len_in_s:]\n", + " full_s_with_point = f\"{integer_str}.{fractional_str}\"\n", + " else:\n", + " full_s_with_point = s\n", + " if '.' in full_s_with_point:\n", + " integer_part, fractional_part = full_s_with_point.split('.',1)\n", + " integer_part = integer_part.lstrip('0')\n", + " if not integer_part: integer_part = \"0\"\n", + " full_s_with_point = f\"{integer_part}.{fractional_part}\"\n", + " else:\n", + " full_s_with_point = full_s_with_point.lstrip('0')\n", + " if not full_s_with_point: full_s_with_point = \"0\"\n", + " return Decimal(full_s_with_point)\n", + " try:\n", + " val1_abs = _format_digit_str_to_decimal_val(op1_str_msd_first, num_dp)\n", + " val2_abs = _format_digit_str_to_decimal_val(op2_str_msd_first, num_dp)\n", + " a_val_final_signed = val1_abs.copy_sign(Decimal(sign_a))\n", + " b_val_final_signed = val2_abs.copy_sign(Decimal(sign_b))\n", + " if a_val_final_signed.is_zero() and a_val_final_signed.is_signed(): a_val_final_signed = Decimal('0')\n", + " if b_val_final_signed.is_zero() and b_val_final_signed.is_signed(): b_val_final_signed = Decimal('0')\n", + " if not is_decimal and num_dp == 0:\n", + " a_final_val = int(a_val_final_signed) if a_val_final_signed == a_val_final_signed.to_integral_value() else a_val_final_signed.normalize()\n", + " b_final_val = int(b_val_final_signed) if b_val_final_signed == b_val_final_signed.to_integral_value() else b_val_final_signed.normalize()\n", + " else:\n", + " a_final_val = a_val_final_signed.normalize(); b_final_val = b_val_final_signed.normalize()\n", + " if a_final_val.is_zero() and a_final_val.is_signed(): a_final_val = Decimal('0')\n", + " if b_final_val.is_zero() and b_final_val.is_signed(): b_final_val = Decimal('0')\n", + " return a_final_val, b_final_val\n", + " except InvalidOperation: return None\n", + " except Exception: return None\n", + "\n", + "\n", + "def check_carries_borrows(num1: Decimal, num2: Decimal, operation: str) -> Tuple[int, int]: # Unchanged\n", + " total_cb = 0; max_consecutive_cb = 0; current_consecutive_cb = 0\n", + " try:\n", + " effective_op = operation; op1: Decimal; op2: Decimal\n", + " num1_norm = num1.normalize(); num2_norm = num2.normalize()\n", + " if num1_norm.is_zero() and num1_norm.is_signed(): num1_norm = Decimal('0')\n", + " if num2_norm.is_zero() and num2_norm.is_signed(): num2_norm = Decimal('0')\n", + "\n", + " if operation == 'add':\n", + " if num1_norm.is_signed() != num2_norm.is_signed():\n", + " effective_op = 'subtract'\n", + " if abs(num1_norm) >= abs(num2_norm): op1, op2 = abs(num1_norm), abs(num2_norm)\n", + " else: op1, op2 = abs(num2_norm), abs(num1_norm)\n", + " else: effective_op = 'add'; op1, op2 = abs(num1_norm), abs(num2_norm)\n", + " elif operation == 'subtract':\n", + " if num1_norm.is_signed() != num2_norm.is_signed(): effective_op = 'add'; op1, op2 = abs(num1_norm), abs(num2_norm)\n", + " else:\n", + " effective_op = 'subtract'\n", + " if abs(num1_norm) >= abs(num2_norm): op1, op2 = abs(num1_norm), abs(num2_norm)\n", + " else: op1, op2 = abs(num2_norm), abs(num1_norm)\n", + " else: return -1, -1 \n", + " \n", + " op1 = abs(op1.normalize())\n", + " op2 = abs(op2.normalize())\n", + " if op1.is_zero() and op1.is_signed(): op1 = Decimal('0')\n", + " if op2.is_zero() and op2.is_signed(): op2 = Decimal('0')\n", + "\n", + " if op1.is_zero() and op2.is_zero(): return 0, 0\n", + " s1 = format_decimal_or_int(op1); s2 = format_decimal_or_int(op2)\n", + " s1_int_part, s1_frac_part = s1.split('.') if '.' in s1 else (s1, '')\n", + " s2_int_part, s2_frac_part = s2.split('.') if '.' in s2 else (s2, '')\n", + " max_frac_len = max(len(s1_frac_part), len(s2_frac_part))\n", + " s1_frac_part = s1_frac_part.ljust(max_frac_len, '0'); s2_frac_part = s2_frac_part.ljust(max_frac_len, '0')\n", + " max_int_len = max(len(s1_int_part), len(s2_int_part))\n", + " s1_int_part = s1_int_part.zfill(max_int_len); s2_int_part = s2_int_part.zfill(max_int_len)\n", + " aligned_s1 = s1_int_part + s1_frac_part; aligned_s2 = s2_int_part + s2_frac_part\n", + " full_len = len(aligned_s1); carry = 0; borrow = 0\n", + " for i in range(full_len - 1, -1, -1):\n", + " try: d1 = int(aligned_s1[i]); d2 = int(aligned_s2[i])\n", + " except (IndexError, ValueError): return -1, -1 \n", + " cb_occurred_this_digit = False\n", + " if effective_op == 'add':\n", + " current_sum_digit = d1 + d2 + carry; carry = 1 if current_sum_digit >= 10 else 0\n", + " cb_occurred_this_digit = (carry == 1)\n", + " else: \n", + " current_diff_digit = d1 - borrow - d2; borrow = 1 if current_diff_digit < 0 else 0\n", + " cb_occurred_this_digit = (borrow == 1)\n", + " if cb_occurred_this_digit: total_cb += 1; current_consecutive_cb += 1\n", + " else: max_consecutive_cb = max(max_consecutive_cb, current_consecutive_cb); current_consecutive_cb = 0\n", + " max_consecutive_cb = max(max_consecutive_cb, current_consecutive_cb)\n", + " except Exception: return -1, -1\n", + " return total_cb, max_consecutive_cb\n", + "\n", + "\n", + "def write_batch_to_jsonl(buffer: List[Dict], filename: str, mode: str = 'a') -> int: # Unchanged\n", + " if not buffer: return 0\n", + " lines_written = 0; json_lines_to_write = []; serialization_errors = 0\n", + " for item in buffer:\n", + " try:\n", + " if not isinstance(item, dict) or not item.get(\"text\"): serialization_errors += 1; continue\n", + " json_string = json.dumps(item, ensure_ascii=False)\n", + " if json_string and not json_string.isspace(): json_lines_to_write.append(json_string)\n", + " else: serialization_errors += 1\n", + " except (TypeError, ValueError): serialization_errors += 1\n", + " except Exception: serialization_errors += 1\n", + " if json_lines_to_write:\n", + " try:\n", + " with open(filename, mode, encoding='utf-8') as f: f.write('\\n'.join(json_lines_to_write) + '\\n')\n", + " lines_written = len(json_lines_to_write)\n", + " except IOError: return 0\n", + " except Exception: return 0\n", + " if serialization_errors > 0: print(f\"\\n警告: 写入批次时 {serialization_errors} 个项目处理失败。\")\n", + " return lines_written\n", + "\n", + "def randomly_replace_characters_in_string(text: str, replacement_prob: float, char_pool: str) -> str: # Unchanged\n", + " if not text or replacement_prob <= 0 or not char_pool: return text\n", + " new_chars = list(text)\n", + " for i in range(len(new_chars)):\n", + " if random.random() < replacement_prob:\n", + " if new_chars[i] not in ['\\n', '\\r']: new_chars[i] = random.choice(char_pool)\n", + " return \"\".join(new_chars)\n", + "\n", + "# --- 主要生成函数 ---\n", + "def generate_constructed_arithmetic_diverse(\n", + " filename: str, total_samples: int, add_prob: float, decimal_prob: float,\n", + " max_digits_limit: int, max_decimal_places_cfg: int, negative_pool_prob: float,\n", + " target_total_cb_min: int, target_total_cb_max: Union[int, float],\n", + " target_consecutive_cb_min: int, target_consecutive_cb_max: Union[int, float],\n", + " nl_question_prob: float,\n", + " symbolic_equals_suffix_prob: float,\n", + " max_attempts_factor: int,\n", + " batch_save_size: int,\n", + " apply_general_char_corr: bool,\n", + " general_char_corr_prob: float,\n", + " general_char_corr_pool: str\n", + " ):\n", + " # ... (大部分与 v10.14 相同, 依赖于修正后的 casing 函数) ...\n", + " print(f\"--- 开始生成算术数据 (v10.15 - Independent Word Casing) ---\")\n", + " print(f\"数字格式概率: Standard Arabic: {STANDARD_ARABIC_PROB*100:.1f}%, Full-width: {FULL_WIDTH_ARABIC_PROB*100:.1f}%, English Words: {ENGLISH_WORDS_PROB*100:.1f}%\")\n", + " print(f\"英文数字大小写: {ENGLISH_NUMBER_ENTIRE_STRING_CASE_PROB*100:.0f}% 整体(逐词独立风格)随机, { (1-ENGLISH_NUMBER_ENTIRE_STRING_CASE_PROB)*100:.0f}% 逐字符随机\")\n", + " print(f\"符���题中英文运算符概率: {SYMBOLIC_OPERATOR_WORD_PROB*100:.1f}%\")\n", + " if APPLY_INTRA_CHAR_SPACING: print(f\"字符间随机空格已启用。\") \n", + " else: print(\"字符间随机空格 (数字/单词内部) 未启用。仅运算符周围有随机空格。\")\n", + " if apply_general_char_corr: print(f\"通用字符级损坏已启用: 概率={general_char_corr_prob*100:.2f}%\")\n", + " else: print(\"通用字符级损坏未启用。\")\n", + "\n", + " digit_pop: List[int] = []; digit_probs_list: List[float] = []\n", + " if max_digits_limit > 0:\n", + " digit_probabilities_dict = calculate_digit_probabilities(max_digits_limit)\n", + " digit_pop = list(range(1, max_digits_limit + 1)); digit_probs_list = [digit_probabilities_dict.get(n, 0.0) for n in digit_pop]\n", + " prob_sum_check = sum(digit_probs_list)\n", + " if not math.isclose(prob_sum_check, 1.0, abs_tol=1e-5):\n", + " if prob_sum_check > 1e-9: digit_probs_list = [p / prob_sum_check for p in digit_probs_list]\n", + " else: uniform_prob = 1.0 / len(digit_pop) if digit_pop else 1.0; digit_probs_list = [uniform_prob] * len(digit_pop)\n", + " if not digit_probs_list and digit_pop: digit_probs_list = [1.0/len(digit_pop)]*len(digit_pop)\n", + " elif not digit_pop : digit_pop = [1]; digit_probs_list = [1.0]\n", + " else: digit_pop = [1]; digit_probs_list = [1.0]\n", + " generated_count = 0; total_attempts = 0; total_lines_written = 0\n", + " construct_failures = 0; add_count = 0; subtract_count = 0\n", + " integer_op_count = 0; decimal_op_count = 0\n", + " format_counts = Counter(); question_type_counts = Counter(); suffix_counts = Counter()\n", + " errors_in_loop = 0\n", + " difficulty_factor_cb = max(1, target_total_cb_min) if target_total_cb_max != math.inf else 1\n", + " difficulty_factor_cb = max(difficulty_factor_cb, target_consecutive_cb_min // 2 if target_consecutive_cb_max !=math.inf else 1)\n", + " max_total_attempts = total_samples * max(100, max_attempts_factor * difficulty_factor_cb)\n", + " start_time_generate = time.time(); output_buffer = []; last_reported_count = -1; last_save_time = start_time_generate\n", + " try:\n", + " with open(filename, 'w', encoding='utf-8') as f: f.write(\"\")\n", + " print(f\"已初始化/清空输出文件: '{filename}'\")\n", + " except IOError as e: print(f\"\\n错误:无法初始化输出文件 '{filename}': {e}\"); return\n", + " print(f\"\\n开始构造 {total_samples:,} 条满足条件的数据...\")\n", + " \n", + " while generated_count < total_samples:\n", + " total_attempts += 1\n", + " if total_attempts > max_total_attempts:\n", + " print(f\"\\n\\n警告: 尝试次数达到上限 ({total_attempts:,})。\"); print(f\"当前已生成: {generated_count:,} (构造失败 {construct_failures:,} 次).\"); print(\"脚本提前终止.\"); break\n", + " a: Union[int, Decimal] = Decimal('0'); b: Union[int, Decimal] = Decimal('0')\n", + " try:\n", + " if not digit_pop or not digit_probs_list or len(digit_pop) != len(digit_probs_list):\n", + " digits_a = random.randint(1, max(1,max_digits_limit)); digits_b = random.randint(1, max(1,max_digits_limit))\n", + " else:\n", + " digits_a = get_distributed_count_from_probs(digit_pop, digit_probs_list); digits_b = get_distributed_count_from_probs(digit_pop, digit_probs_list)\n", + " sign_a = -1 if random.random() < negative_pool_prob else 1\n", + " sign_b = -1 if random.random() < negative_pool_prob else 1\n", + " is_dec_intent_current = random.random() < decimal_prob\n", + " op_type_current = 'add' if random.random() < add_prob else 'subtract'\n", + " op_sym_current = '+' if op_type_current == 'add' else '-'\n", + " constructed_pair = _generate_pair_meeting_cb_criteria(\n", + " digits_a, digits_b, sign_a, sign_b, is_dec_intent_current, max_decimal_places_cfg,\n", + " op_type_current, target_total_cb_min, target_total_cb_max,\n", + " target_consecutive_cb_min, target_consecutive_cb_max)\n", + " if constructed_pair is None: construct_failures += 1; continue\n", + " a, b = constructed_pair\n", + " c_final: Union[int, Decimal]; answer_str = \"\"\n", + " try:\n", + " a_calc = Decimal(str(a)) if not isinstance(a, Decimal) else a\n", + " b_calc = Decimal(str(b)) if not isinstance(b, Decimal) else b\n", + " if not a_calc.is_finite() or not b_calc.is_finite(): errors_in_loop += 1; continue\n", + " c_calc = a_calc + b_calc if op_type_current == 'add' else a_calc - b_calc\n", + " if not c_calc.is_finite(): errors_in_loop += 1; continue\n", + " effective_dp_a = 0; effective_dp_b = 0\n", + " if isinstance(a_calc, Decimal) and a_calc.as_tuple().exponent < 0: effective_dp_a = abs(a_calc.as_tuple().exponent)\n", + " if isinstance(b_calc, Decimal) and b_calc.as_tuple().exponent < 0: effective_dp_b = abs(b_calc.as_tuple().exponent)\n", + " result_dp = max(effective_dp_a, effective_dp_b)\n", + " if not is_dec_intent_current and effective_dp_a == 0 and effective_dp_b == 0: result_dp = 0\n", + " result_dp = min(result_dp, max_decimal_places_cfg)\n", + " if result_dp > 0: c_final_dec = c_calc.quantize(Decimal('1e-' + str(result_dp)), rounding=ROUND_HALF_UP)\n", + " else: c_final_dec = c_calc.to_integral_value(rounding=ROUND_HALF_UP)\n", + " c_final_dec = c_final_dec.normalize()\n", + " if c_final_dec.is_zero() and c_final_dec.is_signed(): c_final_dec = Decimal('0')\n", + " is_a_actually_int = isinstance(a, int) or (isinstance(a, Decimal) and a == a.to_integral_value())\n", + " is_b_actually_int = isinstance(b, int) or (isinstance(b, Decimal) and b == b.to_integral_value())\n", + " is_c_actually_int = (c_final_dec == c_final_dec.to_integral_value())\n", + " if is_c_actually_int and is_a_actually_int and is_b_actually_int and not is_dec_intent_current:\n", + " try: c_final = int(c_final_dec)\n", + " except (OverflowError, ValueError): c_final = c_final_dec\n", + " else: c_final = c_final_dec\n", + " answer_str = format_decimal_or_int(c_final)\n", + " except (InvalidOperation, OverflowError, ValueError, ArithmeticError): errors_in_loop += 1; continue\n", + " except Exception: errors_in_loop += 1; continue\n", + " if not answer_str: errors_in_loop += 1; continue\n", + " try:\n", + " fmt_a_str_processed, fmt_a_type = format_number_variant(a)\n", + " final_op_sym_for_question = op_sym_current\n", + " fmt_b_str_processed, fmt_b_type = \"\", \"\"\n", + " b_dec_for_fmt = Decimal(str(b)) if not isinstance(b, Decimal) else b\n", + " if b_dec_for_fmt.is_signed() and b_dec_for_fmt < 0:\n", + " fmt_b_abs_str_processed, fmt_b_abs_type = format_number_variant(abs(b_dec_for_fmt))\n", + " fmt_b_str_processed = fmt_b_abs_str_processed; fmt_b_type = fmt_b_abs_type\n", + " if op_sym_current == '+': final_op_sym_for_question = '-'\n", + " elif op_sym_current == '-': final_op_sym_for_question = '+'\n", + " else: fmt_b_str_processed, fmt_b_type = format_number_variant(b)\n", + " if not fmt_a_str_processed or not fmt_b_str_processed: errors_in_loop +=1; continue\n", + " format_counts[f'a_{fmt_a_type}'] += 1; format_counts[f'b_{fmt_b_type}'] += 1\n", + " question_str = \"\"\n", + " is_nl_question_current = random.random() < nl_question_prob\n", + " display_op_for_symbolic = final_op_sym_for_question \n", + " if not is_nl_question_current and random.random() < SYMBOLIC_OPERATOR_WORD_PROB:\n", + " if final_op_sym_for_question in ENGLISH_OPERATOR_WORDS:\n", + " word_choices = ENGLISH_OPERATOR_WORDS[final_op_sym_for_question]\n", + " chosen_word_raw = random.choice(word_choices)\n", + " display_op_for_symbolic = _apply_random_case_operator_style(chosen_word_raw)\n", + " format_counts['operator_word'] += 1\n", + " else: format_counts['operator_symbol'] += 1 \n", + " elif not is_nl_question_current: format_counts['operator_symbol'] += 1\n", + "\n", + " if is_nl_question_current:\n", + " question_type_counts['natural_language'] += 1\n", + " question_str = format_natural_language_question(fmt_a_str_processed, fmt_b_str_processed, final_op_sym_for_question)\n", + " else:\n", + " question_type_counts['symbolic'] += 1\n", + " space1_op = get_realistic_spacing(); space2_op = get_realistic_spacing()\n", + " question_str_base = f\"{fmt_a_str_processed}{space1_op}{display_op_for_symbolic}{space2_op}{fmt_b_str_processed}\"\n", + " question_suffix = \"\"; added_suffix_flag = False\n", + " if random.random() < symbolic_equals_suffix_prob:\n", + " q_mark = random.choice([\"?\", \"\"])\n", + " space_eq1 = get_realistic_spacing(); space_eq2 = get_realistic_spacing()\n", + " equals_sign = \"=\" \n", + " question_suffix = f\"{space_eq1}{equals_sign}{space_eq2}{q_mark}\"; added_suffix_flag = True\n", + " suffix_counts['symbolic_added_equals' if added_suffix_flag else 'symbolic_no_equals'] += 1\n", + " question_str = question_str_base + question_suffix\n", + " if not question_str or question_str.isspace(): errors_in_loop += 1; continue\n", + " text_content = f\"User: {question_str}\\n\\nAssistant: {answer_str}\"\n", + " if apply_general_char_corr:\n", + " text_content = randomly_replace_characters_in_string(text_content, general_char_corr_prob, general_char_corr_pool)\n", + " pair_data = {\"text\": text_content}\n", + " generated_count += 1\n", + " if op_type_current == 'add': add_count += 1\n", + " else: subtract_count += 1\n", + " is_a_truly_decimal_val = isinstance(a, Decimal) and a != a.to_integral_value()\n", + " is_b_truly_decimal_val = isinstance(b, Decimal) and b != b.to_integral_value()\n", + " is_c_truly_decimal_val = isinstance(c_final, Decimal) and c_final != c_final.to_integral_value()\n", + " if is_dec_intent_current or is_a_truly_decimal_val or is_b_truly_decimal_val or is_c_truly_decimal_val: decimal_op_count += 1\n", + " else: integer_op_count += 1\n", + " output_buffer.append(pair_data)\n", + " if len(output_buffer) >= batch_save_size:\n", + " write_op_start_time = time.time()\n", + " num_written_this_batch = write_batch_to_jsonl(output_buffer, filename, mode='a')\n", + " write_op_duration = time.time() - write_op_start_time\n", + " if num_written_this_batch > 0:\n", + " total_lines_written += num_written_this_batch\n", + " avg_save_sps = num_written_this_batch / write_op_duration if write_op_duration > 0 else float('inf')\n", + " print(f\"\\r--- 已保存批次 {num_written_this_batch:>6,} (耗时 {write_op_duration:.2f}s, {avg_save_sps:.1f}/s). 总计写入: {total_lines_written:>8,} / 生成: {generated_count:>8,} ---{' '*5}\", end=\"\")\n", + " output_buffer.clear(); last_save_time = time.time()\n", + " else:\n", + " print(f\"\\n警告: 写入批处理失败 (已生成 {generated_count:,} 条)。缓冲区已清空.\")\n", + " errors_in_loop += len(output_buffer); output_buffer.clear()\n", + " except Exception: errors_in_loop += 1; continue\n", + " except KeyboardInterrupt: print(\"\\n用户中断。\"); break\n", + " except Exception: errors_in_loop += 1; continue\n", + " report_freq_interval = max(1, total_samples // 200) if total_samples > 0 else 1000\n", + " current_time = time.time(); time_since_last_activity = current_time - max(last_save_time, start_time_generate if last_reported_count == -1 else last_save_time)\n", + " if generated_count > 0 and (generated_count % report_freq_interval == 0 or generated_count == total_samples or time_since_last_activity > 15):\n", + " if last_reported_count != generated_count:\n", + " progress_percent = generated_count / total_samples if total_samples > 0 else 0; elapsed_seconds = current_time - start_time_generate\n", + " samples_per_sec_rate = generated_count / elapsed_seconds if elapsed_seconds > 0 else 0\n", + " attempts_per_gen_sample = total_attempts / generated_count if generated_count > 0 else float('inf')\n", + " construct_failure_rate = construct_failures / total_attempts if total_attempts > 0 else 0; est_remaining_time_str = \"N/A\"\n", + " if progress_percent > 1e-6 and samples_per_sec_rate > 0:\n", + " remaining_samples_to_gen = total_samples - generated_count; est_remaining_seconds = remaining_samples_to_gen / samples_per_sec_rate\n", + " if est_remaining_seconds < 60: est_remaining_time_str = f\"{est_remaining_seconds:.0f}s\"\n", + " elif est_remaining_seconds < 3600: est_remaining_time_str = f\"{est_remaining_seconds/60:.1f}m\"\n", + " else: est_remaining_time_str = f\"{est_remaining_seconds/3600:.1f}h\"\n", + " stats_line = f\"生成: {generated_count:>8,}/{total_samples:<8,} ({progress_percent:5.1%}) | 写入: {total_lines_written:>8,} | 尝试: {total_attempts:>9,} ({attempts_per_gen_sample:5.1f}/样本) | 失败率: {construct_failure_rate:5.1%} | {samples_per_sec_rate:6.1f} 样本/秒 | 耗时: {elapsed_seconds:6.1f}s | 剩余: ~{est_remaining_time_str:<5}\"\n", + " print(f\"\\r{stats_line.ljust(120)}\", end=\"\"); last_reported_count = generated_count\n", + " print(\" \" * 120, end=\"\\r\"); print(f\"\\n构造循环结束。目标: {total_samples:,}, 实际生成: {generated_count:,} (尝试 {total_attempts:,} 次, 构造失败 {construct_failures:,} 次).\")\n", + " if output_buffer:\n", + " print(f\"写入最后 {len(output_buffer):,} 条数据...\"); final_write_start = time.time()\n", + " num_final_written = write_batch_to_jsonl(output_buffer, filename, mode='a'); final_write_duration = time.time() - final_write_start\n", + " if num_final_written > 0: total_lines_written += num_final_written; print(f\"最终批次写入完成 ({num_final_written:,} 条). 耗时: {final_write_duration:.2f}s.\")\n", + " else: print(\"警告: 最终批次写入失败.\"); errors_in_loop += len(output_buffer)\n", + " output_buffer.clear()\n", + " else: print(\"无剩余数据需写入.\")\n", + " total_generation_end_time = time.time(); total_generation_duration = total_generation_end_time - start_time_generate\n", + " print(f\"\\n生成与写入完毕。目标: {total_samples:,} -> 生成: {generated_count:,} -> 写入: {total_lines_written:,}\")\n", + " if total_lines_written != generated_count and generated_count > 0: print(f\"警告: 写入行数({total_lines_written:,}) 与 生成数({generated_count:,}) 不匹配!\")\n", + " avg_attempts_per_actual_sample = total_attempts / max(1, generated_count) if generated_count > 0 else float('inf')\n", + " overall_construct_failure_rate = construct_failures / total_attempts if total_attempts > 0 else 0\n", + " print(f\"总尝试次数: {total_attempts:,} (平均 {avg_attempts_per_actual_sample:.2f} 次/有效样本)\")\n", + " print(f\"构造失败次数: {construct_failures:,} (失败率: {overall_construct_failure_rate:.2%})\")\n", + " print(f\"总耗时: {total_generation_duration:.2f} 秒。格式化/计算/写入等循环内错误: {errors_in_loop:,}.\")\n", + " print(\"\\n\" + \"=\"*15 + \" 详细统计 (基于生成的有效样本) \" + \"=\"*15)\n", + " if generated_count > 0:\n", + " print(f\"总有效样本: {generated_count:,}\")\n", + " print(\"-\" * 50); print(\"1. 算术题类型:\"); print(f\" - 加法: {add_count:>10,} ({add_count/generated_count:>7.1%})\"); print(f\" - 减法: {subtract_count:>10,} ({subtract_count/generated_count:>7.1%})\")\n", + " print(\"-\" * 50); print(\"2. 运算数类型:\"); print(f\" - 纯整数运算*: {integer_op_count:>10,} ({integer_op_count/generated_count:>7.1%})\"); print(f\" - 含小数运算*: {decimal_op_count:>10,} ({decimal_op_count/generated_count:>7.1%})\"); print(\" *注: 基于操作数或结果是否包含实际小数部分,或生成意图是否为小数。\")\n", + " total_fmt_a_counts = sum(format_counts[k] for k in format_counts if k.startswith('a_'))\n", + " print(\"-\" * 50); print(f\"3. 问题格式 - 操作数 A (总计: {total_fmt_a_counts:,}):\")\n", + " ordered_fmt_keys_num = ['a_standard', 'a_full_width', 'a_english_words']\n", + " for fmt_key in ordered_fmt_keys_num:\n", + " print(f\" - {fmt_key[2:]: <15}: {format_counts.get(fmt_key, 0):>10,} ({(format_counts.get(fmt_key, 0) / total_fmt_a_counts * 100) if total_fmt_a_counts > 0 else 0:>6.1f}%)\")\n", + " total_fmt_b_counts = sum(format_counts[k] for k in format_counts if k.startswith('b_'))\n", + " print(\"-\" * 50); print(f\"4. 问题格式 - 操作数 B (总计: {total_fmt_b_counts:,}):\")\n", + " for fmt_key in ordered_fmt_keys_num:\n", + " print(f\" - {fmt_key[2:]: <15}: {format_counts.get(fmt_key, 0):>10,} ({(format_counts.get(fmt_key, 0) / total_fmt_b_counts * 100) if total_fmt_b_counts > 0 else 0:>6.1f}%)\")\n", + " total_op_format_counts = format_counts.get('operator_word', 0) + format_counts.get('operator_symbol', 0)\n", + " print(\"-\" * 50); print(f\"5. 问题格式 - 符号题运算符 (总计符号题运算符: {total_op_format_counts:,}):\")\n", + " print(f\" - 符号 (+, -): {format_counts.get('operator_symbol', 0):>10,} ({(format_counts.get('operator_symbol', 0) / total_op_format_counts * 100) if total_op_format_counts > 0 else 0:>6.1f}%)\")\n", + " print(f\" - 英文单词: {format_counts.get('operator_word', 0):>10,} ({(format_counts.get('operator_word', 0) / total_op_format_counts * 100) if total_op_format_counts > 0 else 0:>6.1f}%)\")\n", + " total_q_type_counts = sum(question_type_counts.values())\n", + " print(\"-\" * 50); print(f\"6. 问题格式 - 类型 (总计: {total_q_type_counts:,}):\")\n", + " ordered_q_type_keys = ['symbolic', 'natural_language']\n", + " display_name_map_qtype = {'symbolic': '符号格式 (+/- or words)', 'natural_language': '自然语言格式 (English)'}\n", + " for q_type_key in ordered_q_type_keys:\n", + " count = question_type_counts.get(q_type_key, 0)\n", + " percent = count / total_q_type_counts * 100 if total_q_type_counts > 0 else 0\n", + " display_name = display_name_map_qtype.get(q_type_key, q_type_key)\n", + " print(f\" - {display_name: <25}: {count:>10,} ({percent:>6.1f}%)\")\n", + " total_symbolic_suffix_counts = suffix_counts.get('symbolic_added_equals', 0) + suffix_counts.get('symbolic_no_equals', 0)\n", + " print(\"-\" * 50); print(f\"7. 符号问题格式 - 等号后缀 (总计符号问题: {total_symbolic_suffix_counts:,}):\")\n", + " print(f\" - 添加 ' = ?': {suffix_counts.get('symbolic_added_equals', 0):>10,} ({(suffix_counts.get('symbolic_added_equals', 0) / total_symbolic_suffix_counts * 100) if total_symbolic_suffix_counts > 0 else 0:>6.1f}%)\")\n", + " print(f\" - 未添加后缀: {suffix_counts.get('symbolic_no_equals', 0):>10,} ({(suffix_counts.get('symbolic_no_equals', 0) / total_symbolic_suffix_counts * 100) if total_symbolic_suffix_counts > 0 else 0:>6.1f}%)\")\n", + " print(\"=\"*50)\n", + " else: print(\"\\n--- 未生成有效样本,无详细统计 ---\"); print(\"=\"*50)\n", + "\n", + "# ===============================================\n", + "# 主程序入口\n", + "# ===============================================\n", + "if __name__ == \"__main__\":\n", + " script_total_start_time = time.time()\n", + " print(\"=\"*30); print(\" 算术题生成脚本 (v10.15 - Independent Word Casing) \"); print(\"=\"*30)\n", + " max_possible_digits_overall = MAX_DIGITS + MAX_DECIMAL_PLACES\n", + " if max_possible_digits_overall <= 0: print(\"!!! 配置错误: MAX_DIGITS 和 MAX_DECIMAL_PLACES 必须至少有一个大于0。脚本终止.\"); exit()\n", + " max_possible_cb_rough_estimate = MAX_DIGITS + MAX_DECIMAL_PLACES + (1 if MAX_DECIMAL_PLACES > 0 else 0)\n", + " if TARGET_TOTAL_CARRIES_MAX != math.inf and TARGET_TOTAL_CARRIES_MIN > max_possible_cb_rough_estimate: print(f\"\\n!!! 配置警告: 目标最小总进/借位数 ({TARGET_TOTAL_CARRIES_MIN}) > 估算的位数上限 ({max_possible_cb_rough_estimate})。可能难以构造或无法构造。 !!!\")\n", + " if TARGET_CONSECUTIVE_CARRIES_MAX != math.inf and TARGET_CONSECUTIVE_CARRIES_MIN > max_possible_cb_rough_estimate: print(f\"\\n!!! 配置警告: 目标最小连续进/借位数 ({TARGET_CONSECUTIVE_CARRIES_MIN}) > 估算的位数上限 ({max_possible_cb_rough_estimate})。可能难以构造或无法构造。 !!!\")\n", + " if TARGET_TOTAL_CARRIES_MAX != 0 and TARGET_CONSECUTIVE_CARRIES_MIN > TARGET_TOTAL_CARRIES_MIN : print(f\"\\n!!! 配置提示: 目标最小连续数 ({TARGET_CONSECUTIVE_CARRIES_MIN}) 大于目标最小总数 ({TARGET_TOTAL_CARRIES_MIN})。\")\n", + " try:\n", + " generate_constructed_arithmetic_diverse(\n", + " filename=OUTPUT_FILENAME,\n", + " total_samples=TOTAL_SAMPLES,\n", + " add_prob=ADD_PROBABILITY,\n", + " decimal_prob=DECIMAL_PROBABILITY,\n", + " max_digits_limit=MAX_DIGITS,\n", + " max_decimal_places_cfg=MAX_DECIMAL_PLACES,\n", + " negative_pool_prob=NEGATIVE_POOL_PROB,\n", + " target_total_cb_min=TARGET_TOTAL_CARRIES_MIN,\n", + " target_total_cb_max=TARGET_TOTAL_CARRIES_MAX,\n", + " target_consecutive_cb_min=TARGET_CONSECUTIVE_CARRIES_MIN,\n", + " target_consecutive_cb_max=TARGET_CONSECUTIVE_CARRIES_MAX,\n", + " nl_question_prob=NL_QUESTION_PROBABILITY,\n", + " symbolic_equals_suffix_prob=SYMBOLIC_EQUALS_SUFFIX_PROB,\n", + " max_attempts_factor=MAX_ATTEMPTS_FACTOR,\n", + " batch_save_size=BATCH_SAVE_SIZE,\n", + " apply_general_char_corr=APPLY_GENERAL_CHAR_REPLACEMENT,\n", + " general_char_corr_prob=GENERAL_CHAR_REPLACEMENT_PROBABILITY,\n", + " general_char_corr_pool=GENERAL_CHAR_REPLACEMENT_POOL\n", + " )\n", + " except ValueError as val_err: print(f\"\\n配置或值错误: {val_err}\"); traceback.print_exc()\n", + " except MemoryError: print(\"\\n内存错误: 尝试减少 BATCH_SAVE_SIZE 或 TOTAL_SAMPLES。\"); traceback.print_exc()\n", + " except Exception as main_exec_err: print(f\"\\n主程序发生未预料错误: {main_exec_err}\"); traceback.print_exc()\n", + " finally: pass\n", + " script_total_end_time = time.time()\n", + " print(\"\\n\" + \"=\"*30); print(f\"脚本执行完毕。总耗时: {script_total_end_time - script_total_start_time:.2f} 秒。\"); print(f\"数据文件: {OUTPUT_FILENAME}\"); print(\"=\"*30)" + ] + }, + { + "cell_type": "markdown", + "id": "de1d9a9f", + "metadata": {}, + "source": [ + "# 生成带连接符的英文\n", + "\n", + "用于生成:\n", + "\n", + "训练集:ADD_use-connect\n", + "\n", + "测试集:ADD_use-connect_test" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2766a744", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "==============================\n", + " 简易英文算术题生成脚本 (含小数, 符号运算符) \n", + "==============================\n", + "--- 开始生成简易英文算术题 (含小数, 符号运算符, 数字单词连字符) ---\n", + "目标样本数: 500, 输出文件: qa_强制连接符-test.jsonl\n", + "整数部分最大位数: 12, 小数部分最大位数: 6, 小数生成概率: 50.0%\n", + "已初始化/清空输出文件: 'qa_强制连接符-test.jsonl'\n", + "已生成: 500/500 | 已写入: 500...\n", + "生成完成。总共生成: 500, 总共写入: 500\n", + "总耗时: 0.04 秒。\n", + "\n", + "==============================\n", + "脚本执行完毕。总执行时间: 0.04 秒。\n", + "数据文件: qa_强制连接符-test.jsonl\n", + "==============================\n" + ] + } + ], + "source": [ + "# -*- coding: utf-8 -*-\n", + "# v11.2: 简化的英文算术题(使用符号运算符+、-),\n", + "# 数字(可为小数)使用连字符连接的英文单词,混合大小写,运算符两侧有随机空格。\n", + "# 增加了小数部分及其位数控制。\n", + "\n", + "import json\n", + "import random\n", + "import time\n", + "from typing import List, Tuple, Union, Dict, Optional\n", + "from decimal import Decimal, getcontext, ROUND_HALF_UP # 用于精确的小数运算和四舍五入\n", + "import traceback\n", + "\n", + "# ===============================================\n", + "# 配置参数区域\n", + "# ===============================================\n", + "TOTAL_SAMPLES = 500\n", + "OUTPUT_FILENAME = f\"ADD_use-connect_test.jsonl\"\n", + "ADD_PROBABILITY: float = 0.5\n", + "BATCH_SAVE_SIZE: int = 100\n", + "\n", + "# --- 数字生成控制 ---\n", + "MAX_DIGITS: int = 12 # 整数部分的最大位数\n", + "MAX_DECIMAL_PLACES: int = 6 # 小数部分的最大位数\n", + "DECIMAL_PROBABILITY: float = 0.5 # 生成小数的概率\n", + "NEGATIVE_POOL_PROB: float = 0.2\n", + "\n", + "# --- 英文数字大小写控制 ---\n", + "ENGLISH_ENTIRE_WORD_CASE_PROB: float = 0.7\n", + "\n", + "# 设置Decimal的精度,应足够大以避免计算中的精度损失\n", + "# MAX_DIGITS + MAX_DECIMAL_PLACES 是一个操作数的最大总长度,结果可能更长,所以加一些余量\n", + "getcontext().prec = MAX_DIGITS + MAX_DECIMAL_PLACES + 10\n", + "\n", + "# ===============================================\n", + "# 核心代码\n", + "# ===============================================\n", + "\n", + "_ENGLISH_DIGITS = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"]\n", + "_ENGLISH_TEENS = [\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\n", + "_ENGLISH_TENS = [\"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\n", + "_ENGLISH_LARGE_UNITS = [\"\", \"thousand\", \"million\", \"billion\", \"trillion\"]\n", + "\n", + "def _num_to_english_chunk_hyphenated(n: int) -> str:\n", + " \"\"\"将0-999的整数转为连字符英文 (与之前版本相同)\"\"\"\n", + " if not 0 <= n <= 999: return \"\"\n", + " if n == 0: return \"\"\n", + " parts = []\n", + " if n >= 100:\n", + " parts.append(_ENGLISH_DIGITS[n // 100])\n", + " parts.append(\"hundred\")\n", + " n %= 100\n", + " if n > 0:\n", + " if 0 < n < 10: parts.append(_ENGLISH_DIGITS[n])\n", + " elif 10 <= n < 20: parts.append(_ENGLISH_TEENS[n - 10])\n", + " else:\n", + " tens_word = _ENGLISH_TENS[n // 10]\n", + " unit_word = \"\"\n", + " if n % 10 > 0: unit_word = _ENGLISH_DIGITS[n % 10]\n", + " if unit_word: parts.append(f\"{tens_word}-{unit_word}\")\n", + " else: parts.append(tens_word)\n", + " return \"-\".join(filter(None, parts))\n", + "\n", + "def integer_to_english_words_hyphenated(num: int) -> str:\n", + " \"\"\"将整数转为连字符英文 (与之前版本相同,除了错误处理中对大数的判断)\"\"\"\n", + " if num == 0: return _ENGLISH_DIGITS[0]\n", + " max_val_representable = (10**(len(_ENGLISH_LARGE_UNITS) * 3)) - 1\n", + " if abs(num) > max_val_representable:\n", + " print(f\"警告 (整数转换): 数字 {num} 太大,将以字符串形式返回。\")\n", + " return str(num)\n", + " sign_word = \"minus\" if num < 0 else \"\"\n", + " num_abs = abs(num)\n", + " if num_abs == 0: return _ENGLISH_DIGITS[0]\n", + " collected_word_segments = []\n", + " chunk_index = 0\n", + " temp_num = num_abs\n", + " while temp_num > 0:\n", + " current_chunk_value = temp_num % 1000\n", + " if current_chunk_value != 0:\n", + " chunk_as_words = _num_to_english_chunk_hyphenated(current_chunk_value)\n", + " large_unit_word = _ENGLISH_LARGE_UNITS[chunk_index] if chunk_index > 0 else \"\"\n", + " current_segment = chunk_as_words\n", + " if large_unit_word and chunk_as_words: current_segment = f\"{chunk_as_words}-{large_unit_word}\"\n", + " if current_segment: collected_word_segments.append(current_segment)\n", + " temp_num //= 1000\n", + " chunk_index += 1\n", + " if chunk_index >= len(_ENGLISH_LARGE_UNITS) and temp_num > 0:\n", + " print(f\"警告 (整数转换): 数字某部分 {temp_num} 超出定义大单位,剩余部分将以字符串返回。\")\n", + " collected_word_segments.append(str(temp_num % 1000))\n", + " break\n", + " final_parts_to_join = []\n", + " if sign_word: final_parts_to_join.append(sign_word)\n", + " if collected_word_segments: final_parts_to_join.extend(s for s in reversed(collected_word_segments) if s)\n", + " elif not sign_word: return _ENGLISH_DIGITS[0]\n", + " if not final_parts_to_join: return _ENGLISH_DIGITS[0]\n", + " return \"-\".join(filter(None, final_parts_to_join))\n", + "\n", + "def decimal_to_english_words_hyphenated(num_decimal: Decimal) -> str:\n", + " \"\"\"\n", + " 将 Decimal 对象转换为完全用连字符连接的英文单词。\n", + " 例如:Decimal(\"-12.34\") -> \"minus-twelve-point-three-four\"\n", + " 例如:Decimal(\"0.05\") -> \"zero-point-zero-five\"\n", + " \"\"\"\n", + " if num_decimal.is_zero():\n", + " # 处理 -0.0 的情况,确保符号正确\n", + " if num_decimal.is_signed():\n", + " return \"minus-zero\" # 或根据需要调整为 \"zero\" 如果不区分 -0\n", + " return _ENGLISH_DIGITS[0] # \"zero\"\n", + "\n", + " # 规范化Decimal,去除尾随的0,例如1.20 -> 1.2\n", + " num_decimal = num_decimal.normalize()\n", + "\n", + " sign_word = \"minus\" if num_decimal < Decimal(0) else \"\"\n", + " num_abs = abs(num_decimal)\n", + "\n", + " # 将Decimal分割为整数部分和小数部分的字符串\n", + " # .to_eng_string() 避免科学计数法\n", + " s_num_abs = num_abs.to_eng_string()\n", + "\n", + " int_part_str: str\n", + " frac_part_str: str # 小数点后的数字字符串\n", + "\n", + " if '.' in s_num_abs:\n", + " int_part_str, frac_part_str = s_num_abs.split('.', 1)\n", + " else:\n", + " int_part_str = s_num_abs\n", + " frac_part_str = \"\"\n", + "\n", + " int_part_val = int(int_part_str) # 整数部分的数值\n", + " int_words = integer_to_english_words_hyphenated(int_part_val) # 整数部分的英文\n", + "\n", + " all_final_word_components = []\n", + " if sign_word:\n", + " all_final_word_components.append(sign_word)\n", + " all_final_word_components.append(int_words)\n", + "\n", + " if frac_part_str: # 如果有小数部分\n", + " all_final_word_components.append(\"point\")\n", + " for digit_char in frac_part_str: # 逐个转换小数部分的数字\n", + " if digit_char.isdigit(): # 再次确认是数字\n", + " all_final_word_components.append(_ENGLISH_DIGITS[int(digit_char)])\n", + " else: # 不太可能发生,但作为防御\n", + " # print(f\"警告 (小数转换): 在小数部分 '{frac_part_str}' 遇到非数字字符 '{digit_char}'\")\n", + " A = 1\n", + "\n", + "\n", + " return \"-\".join(filter(None, all_final_word_components))\n", + "\n", + "\n", + "# --- 大小写处理函数 (与之前版本相同) ---\n", + "def _apply_single_style_to_word(word: str) -> str:\n", + " if not word or not any(c.isalpha() for c in word): return word\n", + " style_choice = random.random()\n", + " if style_choice < 0.4: return word.lower()\n", + " elif style_choice < 0.8: return word.upper()\n", + " else: return word.capitalize()\n", + "\n", + "def _apply_char_by_char_random_case(text: str) -> str:\n", + " if not text or not any(c.isalpha() for c in text): return text\n", + " return \"\".join(random.choice([char.lower(), char.upper()]) if char.isalpha() else char for char in text)\n", + "\n", + "def apply_mixed_case_to_english_number_word(word: str) -> str:\n", + " if not word or not any(c.isalpha() for c in word): return word\n", + " use_entire_word_style = random.random() < ENGLISH_ENTIRE_WORD_CASE_PROB\n", + " if use_entire_word_style: return _apply_single_style_to_word(word)\n", + " else: return _apply_char_by_char_random_case(word)\n", + "\n", + "# --- 工具函数 (与之前版本相同) ---\n", + "def get_random_spacing() -> str:\n", + " r = random.random()\n", + " if r < 0.6: return \"\"\n", + " elif r < 0.9: return \" \"\n", + " else: return \" \"\n", + "\n", + "def write_batch_to_jsonl(buffer: List[Dict], filename: str, mode: str = 'a') -> int:\n", + " if not buffer: return 0\n", + " lines_written = 0\n", + " json_lines_to_write = []\n", + " serialization_errors = 0\n", + " for item in buffer:\n", + " try:\n", + " if not isinstance(item, dict) or \"text\" not in item:\n", + " serialization_errors += 1; continue\n", + " json_string = json.dumps(item, ensure_ascii=False)\n", + " if json_string and not json_string.isspace():\n", + " json_lines_to_write.append(json_string)\n", + " else: serialization_errors += 1\n", + " except (TypeError, ValueError): serialization_errors += 1\n", + " except Exception: serialization_errors += 1\n", + " if json_lines_to_write:\n", + " try:\n", + " with open(filename, mode, encoding='utf-8') as f:\n", + " f.write('\\n'.join(json_lines_to_write) + '\\n')\n", + " lines_written = len(json_lines_to_write)\n", + " except IOError: print(f\"写入文件 {filename} 时发生IOError\"); return 0\n", + " except Exception: print(f\"写入文件 {filename} 时发生一般错误\"); return 0\n", + " if serialization_errors > 0: print(f\"\\n警告: {serialization_errors} 个项目序列化失败。\")\n", + " return lines_written\n", + "\n", + "def format_decimal_answer(d: Decimal, max_dp: int) -> str:\n", + " \"\"\"格式化Decimal答案为字符串,控制小数位数,并去除尾随的0(如果是整数)。\"\"\"\n", + " # 使用ROUND_HALF_UP进行四舍五入到目标小数位数\n", + " quantizer = Decimal('1e-' + str(max_dp)) if max_dp > 0 else Decimal('1')\n", + " d_quantized = d.quantize(quantizer, rounding=ROUND_HALF_UP)\n", + "\n", + " # 规范化以去除整数末尾不必要的 .0 或 .00\n", + " d_normalized = d_quantized.normalize()\n", + "\n", + " # 如果规范化后是-0,则变为0\n", + " if d_normalized.is_zero() and d_normalized.is_signed():\n", + " d_normalized = Decimal('0')\n", + "\n", + " s = d_normalized.to_eng_string() # 转换为工程字符串以避免科学计数法\n", + "\n", + " # 如果是整数且结果是 x.0,则去除 .0\n", + " if '.' in s:\n", + " integer_part, decimal_part = s.split('.', 1)\n", + " if all(c == '0' for c in decimal_part):\n", + " return integer_part\n", + " return s\n", + "\n", + "\n", + "# --- 主要生成函数 ---\n", + "def generate_simple_english_arithmetic(\n", + " filename: str,\n", + " total_samples: int,\n", + " add_prob: float,\n", + " max_int_digits: int, # 整数部分最大位数\n", + " max_decimal_places: int, # 小数部分最大位数\n", + " decimal_num_prob: float, # 生成小数的概率\n", + " negative_prob: float,\n", + " batch_save_size: int\n", + " ):\n", + " print(f\"--- 开始生成简易英文算术题 (含小数, 符号运算符, 数字单词连字符) ---\")\n", + " print(f\"目标样本数: {total_samples}, 输出文件: {filename}\")\n", + " print(f\"整数部分最大位数: {max_int_digits}, 小数部分最大位数: {max_decimal_places}, 小数生成概率: {decimal_num_prob*100}%\")\n", + "\n", + "\n", + " generated_count = 0\n", + " total_attempts = 0\n", + " total_lines_written = 0\n", + " output_buffer = []\n", + " start_time_generate = time.time()\n", + "\n", + " try:\n", + " with open(filename, 'w', encoding='utf-8') as f:\n", + " f.write(\"\")\n", + " print(f\"已初始化/清空输出文件: '{filename}'\")\n", + " except IOError as e:\n", + " print(f\"\\n错误: 无法初始化输出文件 '{filename}': {e}\")\n", + " return\n", + "\n", + " while generated_count < total_samples:\n", + " total_attempts += 1\n", + " try:\n", + " operands_data = [] # 存储每个操作数的值和实际小数位数\n", + " final_operands_english_cased = [] # 存储转换并加大小写后的英文操作数\n", + "\n", + " max_actual_dp_in_operands = 0 # 记录操作数中实际出现的最大小数位数\n", + "\n", + " for _ in range(2): # 生成两个操作数\n", + " # 1. 生成整数部分\n", + " int_part = random.randint(0, 10**max_int_digits - 1)\n", + "\n", + " # 2. 根据概率决定是否生成小数部分\n", + " frac_part_str = \"\"\n", + " actual_dp = 0\n", + " if max_decimal_places > 0 and random.random() < decimal_num_prob:\n", + " actual_dp = random.randint(1, max_decimal_places) # 随机小数位数\n", + " for _ in range(actual_dp):\n", + " frac_part_str += str(random.randint(0, 9))\n", + " \n", + " num_str = str(int_part)\n", + " if frac_part_str:\n", + " num_str += \".\" + frac_part_str\n", + " \n", + " operand_val = Decimal(num_str)\n", + "\n", + " if random.random() < negative_prob:\n", + " operand_val *= Decimal(\"-1\")\n", + " \n", + " operands_data.append({\"value\": operand_val, \"dp\": actual_dp})\n", + " if actual_dp > max_actual_dp_in_operands:\n", + " max_actual_dp_in_operands = actual_dp\n", + "\n", + " # 转换操作数为英文并应用大小写\n", + " if actual_dp > 0 or '.' in operand_val.to_eng_string(): # 如果是小数或者Decimal表现为小数(如1.0)\n", + " eng_operand = decimal_to_english_words_hyphenated(operand_val)\n", + " else: # 否则按整数处理\n", + " eng_operand = integer_to_english_words_hyphenated(int(operand_val))\n", + " \n", + " final_operands_english_cased.append(apply_mixed_case_to_english_number_word(eng_operand))\n", + "\n", + " num1_val = operands_data[0][\"value\"]\n", + " num2_val = operands_data[1][\"value\"]\n", + " num1_cased = final_operands_english_cased[0]\n", + " num2_cased = final_operands_english_cased[1]\n", + "\n", + " # 3. 选择运算符号\n", + " op_sym = '+' if random.random() < add_prob else '-'\n", + "\n", + " # 4. 计算结果\n", + " result_val: Decimal\n", + " if op_sym == '+':\n", + " result_val = num1_val + num2_val\n", + " else:\n", + " result_val = num1_val - num2_val\n", + "\n", + " # 5. 组装问题字符串\n", + " space1 = get_random_spacing()\n", + " space2 = get_random_spacing()\n", + " question_str = f\"{num1_cased}{space1}{op_sym}{space2}{num2_cased} = ?\"\n", + "\n", + " # 6. 格式化答案字符串\n", + " # 答案的小数位数通常取操作数中最大的小数位数,或者根据题目类型固定\n", + " # 这里我们使用 max_actual_dp_in_operands 来保持与操作数一致的精度\n", + " # 如果要求答案总是特定小数位,可以修改这里的 max_dp_for_answer\n", + " max_dp_for_answer = max_actual_dp_in_operands\n", + " if max_dp_for_answer == 0 and (DECIMAL_PROBABILITY > 0 or max_decimal_places > 0):\n", + " # 如果操作数都是整数,但题目可能涉及小数,答案保留一定小数位可能更合理\n", + " # 但如果严格按操作数,这里是0. 为了简单,如果操作数都是整数,答案也尽量是整数。\n", + " # 如果所有操作数都没有小数,结果也倾向于没有不必要的小数位。\n", + " pass\n", + "\n", + "\n", + " answer_str = format_decimal_answer(result_val, max_dp_for_answer)\n", + "\n", + "\n", + " # 7. 创建 JSONL 输出\n", + " text_content = f\"User: {question_str}\\n\\nAssistant: {answer_str}\"\n", + " pair_data = {\"text\": text_content}\n", + "\n", + " output_buffer.append(pair_data)\n", + " generated_count += 1\n", + "\n", + " if len(output_buffer) >= batch_save_size or generated_count == total_samples:\n", + " num_written = write_batch_to_jsonl(output_buffer, filename, mode='a')\n", + " if num_written > 0:\n", + " total_lines_written += num_written\n", + " print(f\"\\r已生成: {generated_count}/{total_samples} | 已写入: {total_lines_written}...\", end=\"\")\n", + " output_buffer.clear()\n", + " else:\n", + " print(f\"\\n警告: 写入 {len(output_buffer)} 条数据的批处理失败。跳过。\")\n", + " output_buffer.clear()\n", + "\n", + " except KeyboardInterrupt:\n", + " print(\"\\n用户中断了生成过程。\")\n", + " break\n", + " except Exception as e:\n", + " print(f\"\\n生成循环中发生错误: {e}\")\n", + " traceback.print_exc()\n", + " continue\n", + "\n", + " print(f\"\\n生成完成。总共生成: {generated_count}, 总共写入: {total_lines_written}\")\n", + "\n", + " if output_buffer:\n", + " print(f\"正在写入最后 {len(output_buffer)} 条数据...\")\n", + " num_written = write_batch_to_jsonl(output_buffer, filename, mode='a')\n", + " if num_written > 0: total_lines_written += num_written\n", + " print(f\"最终写入完成。文件中总行数: {total_lines_written}\")\n", + "\n", + " end_time_generate = time.time()\n", + " print(f\"总耗时: {end_time_generate - start_time_generate:.2f} 秒。\")\n", + "\n", + "# ===============================================\n", + "# 主程序入口\n", + "# ===============================================\n", + "if __name__ == \"__main__\":\n", + " script_total_start_time = time.time()\n", + " print(\"=\"*30); print(\" 简易英文算术题生成脚本 (含小数, 符号运算符) \"); print(\"=\"*30)\n", + "\n", + " if MAX_DIGITS <= 0 and MAX_DECIMAL_PLACES <= 0 : # 配置检查\n", + " print(\"!!! 配置错误: MAX_DIGITS 和 MAX_DECIMAL_PLACES 至少有一个必须大于 0。脚本终止。\")\n", + " exit()\n", + " if MAX_DECIMAL_PLACES < 0:\n", + " print(\"!!! 配置错误: MAX_DECIMAL_PLACES 不能为负数。脚本终止。\")\n", + " exit()\n", + "\n", + " try:\n", + " generate_simple_english_arithmetic(\n", + " filename=OUTPUT_FILENAME,\n", + " total_samples=TOTAL_SAMPLES,\n", + " add_prob=ADD_PROBABILITY,\n", + " max_int_digits=MAX_DIGITS,\n", + " max_decimal_places=MAX_DECIMAL_PLACES,\n", + " decimal_num_prob=DECIMAL_PROBABILITY,\n", + " negative_prob=NEGATIVE_POOL_PROB,\n", + " batch_save_size=BATCH_SAVE_SIZE\n", + " )\n", + " except Exception as main_exec_err:\n", + " print(f\"\\n主执行过程中发生未处理错误: {main_exec_err}\")\n", + " traceback.print_exc()\n", + " finally:\n", + " script_total_end_time = time.time()\n", + " print(\"\\n\" + \"=\"*30)\n", + " print(f\"脚本执行完毕。总执行时间: {script_total_end_time - script_total_start_time:.2f} 秒。\")\n", + " print(f\"数据文件: {OUTPUT_FILENAME}\")\n", + " print(\"=\"*30)" + ] + }, + { + "cell_type": "markdown", + "id": "157fe29a", + "metadata": {}, + "source": [ + "# 直译为英文\n", + "\n", + "用于生成:\n", + "\n", + "训练集:ADD_en\n", + "\n", + "测试集:ADD_en_test" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6c5f529f", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "==============================\n", + " 算术题生成脚本 (v10.15 - Independent Word Casing & Digit-by-Digit English) \n", + "==============================\n", + "--- 开始生成算术数据 (v10.15 - Independent Word Casing & Digit-by-Digit English) ---\n", + "数字格式概率: Standard Arabic: 30.0%, Full-width: 30.0%, English Words: 40.0%\n", + "英文数字大小写: 80% 整体(逐词独立风格)随机, 20% 逐字符随机\n", + "符号题中英文运算符概率: 30.0%\n", + "字符间随机空格 (数字/单词内部) 未启用。仅运算符周围有随机空格。\n", + "通用字符级损坏未启用。\n", + "已初始化/清空输出文件: 'qa_add_直译为英文-test.jsonl'\n", + "\n", + "开始构造 500 条满足条件的数据...\n", + "生成: 500/500 (100.0%) | 写入: 500 | 尝试: 500 ( 1.0/样本) | 失败率: 0.0% | 7734.3 样本/秒 | 耗时: 0.1s | 剩余: ~0s \n", + "构造循环结束。目标: 500, 实际生成: 500 (尝试 500 次, 构造失败 0 次).\n", + "无剩余数据需写入.\n", + "\n", + "生成与写入完毕。目标: 500 -> 生成: 500 -> 写入: 500\n", + "总尝试次数: 500 (平均 1.00 次/有效样本)\n", + "构造失败次数: 0 (失败率: 0.00%)\n", + "总耗时: 0.06 秒。格式化/计算/写入等循环内错误: 0.\n", + "\n", + "=============== 详细统计 (基于生成的有效样本) ===============\n", + "总有效样本: 500\n", + "--------------------------------------------------\n", + "1. 算术题类型:\n", + " - 加法: 242 ( 48.4%)\n", + " - 减法: 258 ( 51.6%)\n", + "--------------------------------------------------\n", + "2. 运算数类型:\n", + " - 纯整数运算*: 298 ( 59.6%)\n", + " - 含小数运算*: 202 ( 40.4%)\n", + " *注: 基于操作数或结果是否包含实际小数部分,或生成意图是否为小数。\n", + "--------------------------------------------------\n", + "3. 问题格式 - 操作数 A (总计: 500):\n", + " - standard : 158 ( 31.6%)\n", + " - full_width : 128 ( 25.6%)\n", + " - english_words : 214 ( 42.8%)\n", + "--------------------------------------------------\n", + "4. 问题格式 - 操作数 B (总计: 500):\n", + " - standard : 124 ( 24.8%)\n", + " - full_width : 148 ( 29.6%)\n", + " - english_words : 228 ( 45.6%)\n", + "--------------------------------------------------\n", + "5. 问题格式 - 符号题运算符 (总计符号题运算符: 354):\n", + " - 符号 (+, -): 245 ( 69.2%)\n", + " - 英文单词: 109 ( 30.8%)\n", + "--------------------------------------------------\n", + "6. 问题格式 - 类型 (总计: 500):\n", + " - 符号格式 (+/- or words) : 354 ( 70.8%)\n", + " - 自然语言格式 (English) : 146 ( 29.2%)\n", + "--------------------------------------------------\n", + "7. 符号问题格式 - 等号后缀 (总计符号问题: 354):\n", + " - 添加 ' = ?': 188 ( 53.1%)\n", + " - 未添加后缀: 166 ( 46.9%)\n", + "==================================================\n", + "\n", + "==============================\n", + "脚本执行完毕。总耗时: 0.07 秒。\n", + "数据文件: qa_add_直译为英文-test.jsonl\n", + "==============================\n" + ] + } + ], + "source": [ + "# -*- coding: utf-8 -*-\n", + "# 生成满足指定进/借位范围条件,且问题格式多样化的算术问题数据集脚本。\n", + "# 采用反向逐位构造方法优化生成效率。\n", + "# v10.15: For 'entire string' casing, each word in a phrase now gets an *independent* random style (lower, upper, title).\n", + "# MODIFIED: English number words are now digit-by-digit translations (e.g., 678 -> \"six seven eight\").\n", + "\n", + "import json\n", + "import random\n", + "import time\n", + "import math\n", + "from typing import List, Tuple, Union, Dict, Optional, Callable\n", + "from decimal import Decimal, getcontext, ROUND_DOWN, ROUND_HALF_UP, InvalidOperation\n", + "import traceback\n", + "from collections import Counter\n", + "import string\n", + "\n", + "# ===============================================\n", + "# 配置参数区域\n", + "# ===============================================\n", + "# --- 主要数量和文件名 ---\n", + "TOTAL_SAMPLES = 500 # Reduced for quick testing; set back to 1500000 for full run\n", + "OUTPUT_FILENAME = f\"ADD_en.jsonl\"\n", + "ADD_PROBABILITY: float = 0.5\n", + "BATCH_SAVE_SIZE: int = 20\n", + "\n", + "# --- 数字生成控制 ---\n", + "MAX_DIGITS: int = 12\n", + "MAX_DECIMAL_PLACES: int = 5\n", + "DECIMAL_PROBABILITY: float = 0.4\n", + "NEGATIVE_POOL_PROB: float = 0.1\n", + "SCI_THRESHOLD_POS = 10**70\n", + "SCI_THRESHOLD_NEG = -60\n", + "\n", + "# --- 进/借位条件范围 ---\n", + "TARGET_TOTAL_CARRIES_MIN: int = 0\n", + "TARGET_TOTAL_CARRIES_MAX: int = math.inf\n", + "TARGET_CONSECUTIVE_CARRIES_MIN: int = 0\n", + "TARGET_CONSECUTIVE_CARRIES_MAX: int = math.inf\n", + "\n", + "# --- 格式化控制 (问题部分数字的样式) ---\n", + "STANDARD_ARABIC_PROB: float = 0.30\n", + "FULL_WIDTH_ARABIC_PROB: float = 0.30\n", + "ENGLISH_WORDS_PROB: float = 0.40\n", + "_format_prob_sum = STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB + ENGLISH_WORDS_PROB\n", + "if not math.isclose(_format_prob_sum, 1.0):\n", + " raise ValueError(f\"数字格式概率总和必须为 1.0,当前为: {_format_prob_sum}\")\n", + "\n", + "# --- English Number Casing Control ---\n", + "ENGLISH_NUMBER_ENTIRE_STRING_CASE_PROB: float = 0.8 # This now means \"apply independent word casing\"\n", + "\n", + "# --- Operator Word Control (for symbolic questions) ---\n", + "SYMBOLIC_OPERATOR_WORD_PROB: float = 0.3\n", + "\n", + "# --- 字符间随机空格控制 ---\n", + "APPLY_INTRA_CHAR_SPACING: bool = False\n", + "\n", + "# --- 自然语言概率控制 ---\n", + "NL_QUESTION_PROBABILITY: float = 0.30\n", + "\n", + "# --- 等号后缀概率控制 (仅符号问题) ---\n", + "SYMBOLIC_EQUALS_SUFFIX_PROB: float = 0.50\n", + "\n", + "# --- 字符级随机替换控制 (通用,应用于最终文本) ---\n", + "APPLY_GENERAL_CHAR_REPLACEMENT: bool = False\n", + "GENERAL_CHAR_REPLACEMENT_PROBABILITY: float = 0.005\n", + "GENERAL_CHAR_REPLACEMENT_POOL: str = string.ascii_letters + string.digits + \".,?! \"\n", + "\n", + "# --- 其他控制 ---\n", + "MAX_ATTEMPTS_FACTOR = 5000\n", + "\n", + "# ===============================================\n", + "# 核心代码\n", + "# ===============================================\n", + "getcontext().prec = MAX_DIGITS + MAX_DECIMAL_PLACES + 30\n", + "\n", + "_ENGLISH_DIGITS = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"]\n", + "# The following (_TEENS, _TENS, _LARGE_UNITS) are part of the old number-to-word system (e.g., \"one hundred twenty-three\").\n", + "# They are kept for potential future use or if the old system needs to be reinstated,\n", + "# but the current 'english_words' format uses digit-by-digit translation.\n", + "_ENGLISH_TEENS = [\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\n", + "_ENGLISH_TENS = [\"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\n", + "_ENGLISH_LARGE_UNITS = [\"\", \"thousand\", \"million\", \"billion\", \"trillion\", \"quadrillion\", \"quintillion\",\n", + " \"sextillion\", \"septillion\", \"octillion\", \"nonillion\", \"decillion\"]\n", + "\n", + "# --- [NEW] Digit-by-digit integer to English words function ---\n", + "def integer_to_english_digits_only(num: int) -> str:\n", + " \"\"\"Converts an integer to digit-by-digit English words. e.g., 678 -> \"six seven eight\", -10 -> \"minus one zero\" \"\"\"\n", + " if num == 0:\n", + " return _ENGLISH_DIGITS[0]\n", + "\n", + " s_num = str(num) # Converts int to string, e.g., -123 -> \"-123\"\n", + " \n", + " parts = []\n", + " if s_num.startswith('-'):\n", + " parts.append(\"minus\")\n", + " s_num = s_num[1:] # Remove leading minus for digit processing\n", + "\n", + " # s_num can be empty if original num was, for example, just \"-\" (invalid int, but defensive)\n", + " # or if num was 0 and somehow skipped the first check.\n", + " # However, for valid integer inputs (after sign stripping), s_num should not be empty.\n", + " if not s_num: # Should ideally not be reached if num was a valid non-zero int.\n", + " # If num was 0, it's caught above. If num was negative, s_num[1:] might be empty if num was e.g. int(\"-\") (invalid)\n", + " # For safety, if s_num becomes empty, and we haven't added \"minus\", treat as zero.\n", + " # If \"minus\" was added and s_num is empty, it's an anomaly (e.g. from int(\"-\")).\n", + " if \"minus\" in parts: # \"minus\" by itself\n", + " return \" \".join(parts) # or raise error, or return \"minus zero\" ? For now, just \"minus\"\n", + " return _ENGLISH_DIGITS[0] # Fallback for unexpected empty s_num\n", + "\n", + " for digit_char in s_num:\n", + " # Assuming s_num contains only digits after sign stripping\n", + " parts.append(_ENGLISH_DIGITS[int(digit_char)])\n", + " \n", + " return \" \".join(parts)\n", + "\n", + "\n", + "# --- [KEPT] Old number-to-word chunk function (not used by new digit-by-digit logic) ---\n", + "def _num_to_english_chunk(n: int) -> str:\n", + " if not 0 <= n <= 999: return \"\"\n", + " if n == 0: return \"\" # \"zero\" should be handled by the calling function explicitly\n", + " parts = []\n", + " if n >= 100:\n", + " parts.append(_ENGLISH_DIGITS[n // 100])\n", + " parts.append(\"hundred\")\n", + " n %= 100\n", + " if n > 0:\n", + " if 0 < n < 10: parts.append(_ENGLISH_DIGITS[n])\n", + " elif 10 <= n < 20: parts.append(_ENGLISH_TEENS[n - 10])\n", + " else:\n", + " parts.append(_ENGLISH_TENS[n // 10])\n", + " if n % 10 > 0: parts.append(_ENGLISH_DIGITS[n % 10])\n", + " return \" \".join(parts)\n", + "\n", + "# --- [KEPT] Old integer-to-word function (not used by new digit-by-digit logic) ---\n", + "def integer_to_english_words(num: int) -> str:\n", + " if num == 0: return _ENGLISH_DIGITS[0]\n", + " if abs(num) > (10**(len(_ENGLISH_LARGE_UNITS) * 3) -1) :\n", + " return f\"Number too large for English word conversion ({num})\" # Fallback\n", + " sign = \"minus \" if num < 0 else \"\"\n", + " num_abs = abs(num)\n", + " parts = []\n", + " chunk_index = 0\n", + " if num_abs == 0: return _ENGLISH_DIGITS[0] # Should be caught by initial num == 0\n", + "\n", + " temp_num = num_abs\n", + " while temp_num > 0:\n", + " if temp_num % 1000 != 0:\n", + " chunk_words = _num_to_english_chunk(temp_num % 1000)\n", + " unit_word = _ENGLISH_LARGE_UNITS[chunk_index] if chunk_index > 0 else \"\"\n", + " if unit_word: parts.append(unit_word)\n", + " parts.append(chunk_words)\n", + " temp_num //= 1000\n", + " chunk_index += 1\n", + " if chunk_index >= len(_ENGLISH_LARGE_UNITS) and temp_num > 0:\n", + " return f\"Number too large for defined English units ({temp_num} remaining, index {chunk_index})\" # Fallback\n", + "\n", + " result_words = \" \".join(p for p in reversed(parts) if p).strip()\n", + " return (sign + result_words).strip()\n", + "\n", + "# --- [MODIFIED] Decimal to English words (digit-by-digit) ---\n", + "def decimal_to_english_words(num: Decimal) -> str:\n", + " if not isinstance(num, Decimal) or not num.is_finite():\n", + " return \"Invalid number for English conversion\" # Fallback\n", + "\n", + " # Normalize -0 to 0 for consistent \"zero\" output without \"minus\"\n", + " if num.is_zero() and num.is_signed():\n", + " num = Decimal('0')\n", + " \n", + " if num.is_zero(): # Handles 0, 0.0 after normalization\n", + " return _ENGLISH_DIGITS[0]\n", + "\n", + " sign_str = \"\"\n", + " num_abs_for_words = abs(num)\n", + " if num < 0: # Sign for genuinely negative numbers\n", + " sign_str = \"minus \"\n", + "\n", + " # Integer part conversion using digit-by-digit\n", + " # int() truncates, which is correct for getting the integer part value\n", + " int_part_val = int(num_abs_for_words.to_integral_value(rounding=ROUND_DOWN))\n", + " int_words = integer_to_english_digits_only(int_part_val) # e.g., 0 -> \"zero\", 123 -> \"one two three\"\n", + "\n", + " # Fractional part processing\n", + " # Use format_decimal_or_int to get a canonical string representation like \"123.45\" or \"0.5\"\n", + " # format_decimal_or_int also strips trailing \".0\" (e.g., 123.0 becomes \"123\")\n", + " s_num_abs_canonical = format_decimal_or_int(num_abs_for_words)\n", + " \n", + " frac_word_list = []\n", + " if '.' in s_num_abs_canonical:\n", + " _, frac_str_digits = s_num_abs_canonical.split('.', 1)\n", + " if frac_str_digits: # Make sure there are digits after decimal point\n", + " for digit_char in frac_str_digits:\n", + " if digit_char.isdigit(): # Should always be true from format_decimal_or_int\n", + " frac_word_list.append(_ENGLISH_DIGITS[int(digit_char)])\n", + "\n", + " # Assemble the full number string\n", + " final_assembly_parts = []\n", + " if sign_str:\n", + " final_assembly_parts.append(sign_str.strip()) # \"minus\"\n", + " \n", + " final_assembly_parts.append(int_words) # \"zero\", \"one two three\", etc.\n", + "\n", + " if frac_word_list: # Only add \"point\" and fractional words if they exist\n", + " final_assembly_parts.append(\"point\")\n", + " final_assembly_parts.extend(frac_word_list)\n", + " \n", + " assembled_num_words = \" \".join(p for p in final_assembly_parts if p or p == _ENGLISH_DIGITS[0])\n", + " \n", + " return assembled_num_words.strip()\n", + "\n", + "\n", + "# --- [MODIFIED] Decimal to English scientific (digit-by-digit for coefficient and exponent) ---\n", + "def decimal_to_english_scientific(num: Decimal) -> str:\n", + " if not isinstance(num, Decimal) or not num.is_finite():\n", + " return \"Invalid number for English scientific conversion\" # Fallback\n", + " \n", + " if num.is_zero():\n", + " # Let the main decimal_to_english_words handle \"zero\" consistently\n", + " return decimal_to_english_words(num)\n", + "\n", + " raw_word_parts = []\n", + "\n", + " try:\n", + " # Use {:e} for a standard scientific notation string like \"1.23e+5\" or \"-4.56e-7\"\n", + " sci_str = \"{:e}\".format(num) # num.normalize() might not always give 'e' form\n", + " coeff_str, exp_str = sci_str.lower().split('e')\n", + " \n", + " coeff_dec = Decimal(coeff_str)\n", + " exp_int = int(exp_str)\n", + "\n", + " # Coefficient: uses the modified decimal_to_english_words (digit-by-digit)\n", + " # This will handle the sign of the coefficient internally.\n", + " coeff_english_raw = decimal_to_english_words(coeff_dec)\n", + "\n", + " # Exponent: uses integer_to_english_digits_only (digit-by-digit)\n", + " # This will handle the sign of the exponent internally (e.g., \"minus three\").\n", + " exp_english_raw = integer_to_english_digits_only(exp_int)\n", + "\n", + " # Assemble parts\n", + " # coeff_english_raw can be multiple words (e.g. \"minus one point two three\")\n", + " raw_word_parts.extend(coeff_english_raw.split())\n", + " \n", + " raw_word_parts.append(\"times\")\n", + " raw_word_parts.append(\"ten\") # \"ten\" itself is a keyword, not \"one zero\" here\n", + " raw_word_parts.append(\"to\")\n", + " raw_word_parts.append(\"the\")\n", + " raw_word_parts.append(\"power\")\n", + " raw_word_parts.append(\"of\")\n", + " \n", + " # exp_english_raw can be multiple words (e.g. \"minus three\", \"one zero\")\n", + " raw_word_parts.extend(exp_english_raw.split())\n", + " \n", + " return \" \".join(p for p in raw_word_parts if p).strip()\n", + "\n", + " except Exception: # Fallback if parsing or conversion fails\n", + " # Try to return the number as a string if conversion to scientific words fails\n", + " return format_decimal_or_int(num)\n", + "\n", + "\n", + "# --- Casing Functions (Unchanged, will operate on new word format) ---\n", + "def _apply_random_word_case_style(word: str) -> str:\n", + " \"\"\"Applies a randomly chosen style (lower, upper, title) to a single word.\"\"\"\n", + " if not word or not any(c.isalpha() for c in word):\n", + " return word\n", + " \n", + " style_choice = random.random()\n", + " if style_choice < 0.4: # All lowercase\n", + " return word.lower()\n", + " elif style_choice < 0.8: # All uppercase\n", + " return word.upper()\n", + " else: # Title case (capitalize first letter)\n", + " return word.capitalize()\n", + "\n", + "def _apply_independent_word_casing(text: str) -> str:\n", + " \"\"\"\n", + " Splits text into words, and applies an *independent* random word case style\n", + " (lower, upper, title) to each word.\n", + " \"\"\"\n", + " if not text or not any(c.isalpha() for c in text):\n", + " return text\n", + "\n", + " words = text.split(' ')\n", + " cased_words = [_apply_random_word_case_style(word) for word in words]\n", + " return \" \".join(cased_words)\n", + "\n", + "def _apply_random_case_char_by_char(text: str) -> str:\n", + " \"\"\"Applies random casing to each character of the text.\"\"\"\n", + " if not text or not any(c.isalpha() for c in text):\n", + " return text\n", + " return \"\".join(random.choice([char.lower(), char.upper()]) if char.isalpha() else char for char in text)\n", + "\n", + "def _apply_random_case_number_style(text: str) -> str:\n", + " \"\"\"Applies casing to a string representing a number in words.\"\"\"\n", + " if not text or not any(c.isalpha() for c in text): return text\n", + " if random.random() < ENGLISH_NUMBER_ENTIRE_STRING_CASE_PROB:\n", + " # This now means: apply independent random style to each word of the number phrase\n", + " return _apply_independent_word_casing(text)\n", + " else:\n", + " # This remains: apply random casing to each character of the entire phrase\n", + " return _apply_random_case_char_by_char(text)\n", + "\n", + "def _apply_random_case_operator_style(text: str) -> str:\n", + " \"\"\"Applies casing to a string representing an operator or keyword in words.\"\"\"\n", + " if not text or not any(c.isalpha() for c in text): return text\n", + " return _apply_independent_word_casing(text)\n", + "\n", + "\n", + "# --- Formatting and Utility functions ---\n", + "half_to_full_map = str.maketrans(\"0123456789.-+\", \"0123456789.-+\")\n", + "def to_full_width(text: str) -> str: return text.translate(half_to_full_map)\n", + "\n", + "def format_decimal_or_int(num: Union[int, Decimal]) -> str:\n", + " # ... (Unchanged from original script) ...\n", + " try:\n", + " if isinstance(num, int): return str(num)\n", + " if isinstance(num, Decimal):\n", + " if not num.is_finite(): return str(num) # handles 'Infinity', 'NaN', etc.\n", + " # Normalize to remove trailing zeros from fractional part and ensure -0 becomes 0\n", + " num_normalized = num.normalize()\n", + " if num_normalized.is_zero() and num_normalized.is_signed(): # convert -Decimal('0') to Decimal('0')\n", + " num_normalized = Decimal('0')\n", + " \n", + " s = num_normalized.to_eng_string() # Use to_eng_string to avoid scientific notation for large/small numbers here\n", + "\n", + " # Further ensure that if it's an integer value after normalization, no decimal point is present.\n", + " # e.g., Decimal('123.000') normalized is Decimal('123'), to_eng_string is '123'\n", + " # e.g., Decimal('0.0') normalized is Decimal('0'), to_eng_string is '0'\n", + " # e.g., Decimal('123.450') normalized is Decimal('123.45'), to_eng_string is '123.45'\n", + " if '.' in s:\n", + " integer_part, decimal_part = s.split('.', 1)\n", + " # If all characters in decimal_part are '0', then it's effectively an integer\n", + " if all(c == '0' for c in decimal_part):\n", + " s = integer_part\n", + " \n", + " # Ensure numbers like .5 become 0.5 and -.5 become -0.5\n", + " if s.startswith('.'): s = '0' + s\n", + " if s.startswith('-.'): s = '-0' + s[1:]\n", + " if not s: s = \"0\" # Should not happen with Decimal\n", + " return s\n", + " return str(num) # Fallback for other types\n", + " except Exception:\n", + " # More robust fallback for unexpected issues\n", + " try:\n", + " # Try to convert to Decimal and format again if input was string-like\n", + " normalized_num = Decimal(str(num)).normalize()\n", + " if normalized_num.is_zero() and normalized_num.is_signed():\n", + " normalized_num = Decimal('0')\n", + " temp_s = \"{:f}\".format(normalized_num) # {:f} to avoid scientific notation\n", + " if '.' in temp_s:\n", + " integer_part, decimal_part = temp_s.split('.', 1)\n", + " decimal_part = decimal_part.rstrip('0') # remove trailing zeros\n", + " if not decimal_part: # if only zeros were after point\n", + " temp_s = integer_part\n", + " else:\n", + " temp_s = integer_part + '.' + decimal_part\n", + " if not temp_s: temp_s = \"0\"\n", + " return temp_s\n", + " except:\n", + " return str(num) # Absolute fallback\n", + "\n", + "def _insert_random_intra_char_spacing(text: str) -> str: # Unchanged (disabled by default)\n", + " if not text or not APPLY_INTRA_CHAR_SPACING or len(text) <= 1: return text\n", + " # Simplified: if enabled, could insert spaces. For now, it's a no-op if APPLY_INTRA_CHAR_SPACING is False.\n", + " return text\n", + "\n", + "def format_number_variant(num: Union[int, Decimal]) -> Tuple[str, str]:\n", + " # This function's direct logic is unchanged, but its behavior for 'english_words'\n", + " # will change because decimal_to_english_words and decimal_to_english_scientific\n", + " # have been modified to produce digit-by-digit translations.\n", + " fmt_choice = random.random()\n", + " try: num_dec = Decimal(str(num)) if not isinstance(num, Decimal) else num\n", + " except InvalidOperation: return str(num), 'standard' # Fallback for unparsable num\n", + " target_format_name = 'standard' # Default\n", + " if fmt_choice < STANDARD_ARABIC_PROB: target_format_name = 'standard'\n", + " elif fmt_choice < STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB: target_format_name = 'full_width'\n", + " else: target_format_name = 'english_words'\n", + "\n", + " def finalize_output(s: str, fmt_name: str) -> Tuple[str, str]:\n", + " final_s = _insert_random_intra_char_spacing(s)\n", + " return final_s, fmt_name\n", + "\n", + " try:\n", + " if not num_dec.is_finite(): # Handle Inf, NaN\n", + " s_num_non_finite = str(num_dec) # e.g., \"Infinity\", \"NaN\"\n", + " res_str = to_full_width(s_num_non_finite) if target_format_name == 'full_width' else s_num_non_finite\n", + " actual_fmt_name = target_format_name if target_format_name != 'english_words' else 'standard' # Non-finite usually not words\n", + " return finalize_output(res_str, actual_fmt_name)\n", + " \n", + " s_formatted_arabic = format_decimal_or_int(num_dec) # Canonical Arabic string\n", + "\n", + " if target_format_name == 'standard':\n", + " return finalize_output(s_formatted_arabic, 'standard')\n", + " elif target_format_name == 'full_width':\n", + " return finalize_output(to_full_width(s_formatted_arabic), 'full_width')\n", + " elif target_format_name == 'english_words':\n", + " # Determine if scientific notation should be used for English words\n", + " # Based on magnitude, not just if format_decimal_or_int would use 'e'\n", + " exponent = num_dec.normalize().adjusted() # Gets the exponent for scientific notation form\n", + " use_sci_english = (exponent >= math.log10(SCI_THRESHOLD_POS) if SCI_THRESHOLD_POS > 0 else False) or \\\n", + " (exponent <= SCI_THRESHOLD_NEG if SCI_THRESHOLD_NEG != 0 else False)\n", + " \n", + " final_english_str_cased = \"\"\n", + " raw_english_phrase = \"\"\n", + "\n", + " if use_sci_english:\n", + " raw_english_phrase = decimal_to_english_scientific(num_dec) # Uses NEW digit-by-digit logic\n", + " # Error/fallback check (decimal_to_english_scientific might return non-word string on error)\n", + " if \"Invalid\" in raw_english_phrase or \"too large\" in raw_english_phrase or not any(c.isalpha() for c in raw_english_phrase):\n", + " final_english_str_cased = s_formatted_arabic # Fallback to arabic\n", + " target_format_name = 'standard' # Change type if falling back\n", + " else:\n", + " final_english_str_cased = _apply_random_case_number_style(raw_english_phrase)\n", + " else: # Regular number to words\n", + " raw_english_phrase = decimal_to_english_words(num_dec) # Uses NEW digit-by-digit logic\n", + " if \"Invalid\" in raw_english_phrase or \"too large\" in raw_english_phrase or not any(c.isalpha() for c in raw_english_phrase):\n", + " final_english_str_cased = s_formatted_arabic\n", + " target_format_name = 'standard'\n", + " else:\n", + " final_english_str_cased = _apply_random_case_number_style(raw_english_phrase)\n", + " \n", + " return finalize_output(final_english_str_cased, target_format_name) # Use potentially updated target_format_name\n", + " else: # Should not be reached if probabilities sum to 1\n", + " return finalize_output(s_formatted_arabic, 'standard')\n", + " \n", + " except Exception: # Broad exception catch during formatting\n", + " # Fallback to a simple string representation if anything goes wrong\n", + " try:\n", + " fallback_str = format_decimal_or_int(num_dec if 'num_dec' in locals() else num)\n", + " return finalize_output(fallback_str, 'standard')\n", + " except:\n", + " return finalize_output(str(num), 'standard') # Absolute fallback\n", + "\n", + "\n", + "def get_realistic_spacing() -> str: # Unchanged\n", + " space_values = [\"\", \" \", \" \"]; space_weights = [0.8, 0.15, 0.05]\n", + " _sw_sum = sum(space_weights)\n", + " if not math.isclose(_sw_sum, 1.0):\n", + " if _sw_sum > 1e-9 : space_weights = [w/_sw_sum for w in space_weights]\n", + " else: space_weights = [1.0/len(space_values)] * len(space_values)\n", + " try: return random.choices(space_values, weights=space_weights, k=1)[0]\n", + " except Exception: return \"\"\n", + "\n", + "def contains_arabic_numerals(s: str) -> bool: # Unchanged\n", + " return any(c in \"01234567890123456789\" for c in s)\n", + "\n", + "def get_distributed_count_from_probs(population: List[int], probabilities: List[float]) -> int: # Unchanged\n", + " if not population: return 1\n", + " if not probabilities or len(population) != len(probabilities) or not all(p >= 0 for p in probabilities):\n", + " return random.choice(population) if population else 1\n", + " prob_sum = sum(probabilities)\n", + " if prob_sum < 1e-9: return random.choice(population) if population else 1\n", + " normalized_probabilities = probabilities\n", + " if not math.isclose(prob_sum, 1.0, abs_tol=1e-5):\n", + " try: normalized_probabilities = [p / prob_sum for p in probabilities]\n", + " except ZeroDivisionError: return random.choice(population) if population else 1\n", + " try: return random.choices(population, weights=normalized_probabilities, k=1)[0]\n", + " except Exception: return random.choice(population) if population else 1\n", + "\n", + "def calculate_digit_probabilities(max_digits: int) -> Dict[int, float]: # Unchanged\n", + " if max_digits <= 0: return {1: 1.0}\n", + " raw_probs = {}; prob_sum = Decimal('0.0'); base_prob = Decimal('0.1'); decay_factor = Decimal('0.95'); increase_factor = Decimal('1.05')\n", + " for n in range(1, max_digits + 1):\n", + " prob = base_prob * (decay_factor**(n - 1)) * (increase_factor**(max_digits - n + 1)); prob = max(Decimal('0.001'), prob); raw_probs[n] = prob; prob_sum += prob\n", + " normalized_probs = {}\n", + " if prob_sum <= 0: fallback_prob = 1.0 / max(1, max_digits); normalized_probs = {n: fallback_prob for n in range(1, max_digits + 1)}\n", + " else: normalized_probs = {n: float(p / prob_sum) for n, p in raw_probs.items()}\n", + " final_sum = sum(normalized_probs.values())\n", + " if not math.isclose(final_sum, 1.0, abs_tol=1e-9):\n", + " renorm_factor = 1.0 / final_sum if final_sum != 0 else 1.0; total = 0.0; keys = sorted(normalized_probs.keys())\n", + " for i, n_key in enumerate(keys):\n", + " if i == len(keys) - 1: normalized_probs[n_key] = max(0.0, 1.0 - total)\n", + " else: norm_p = max(0.0, normalized_probs[n_key] * renorm_factor); normalized_probs[n_key] = norm_p; total += norm_p\n", + " if keys: normalized_probs[keys[-1]] = max(0.0, normalized_probs[keys[-1]])\n", + " return normalized_probs\n", + "\n", + "ENGLISH_OPERATOR_WORDS = {\n", + " '+': [\"plus\", \"add\", \"and\"],\n", + " '-': [\"minus\", \"subtract\", \"take away\", \"less\"]\n", + "}\n", + "\n", + "def format_natural_language_question(fmt_a: str, fmt_b: str, op_sym: str) -> str: # Unchanged\n", + " raw_add_words = [\"plus\", \"added to\", \"and\", \"combined with\", \"summed with\"]\n", + " raw_subtract_words = [\"minus\", \"subtract\", \"take away\", \"less\", \"deducted by\"]\n", + " \n", + " result_phrases_en_raw = [\"equals what\", \"is what\", \"results in what\", \"gives what\", \"what is the total\", \"what is the difference\", \"how much is that\"]\n", + " question_marks = [\"?\", \"\"]\n", + " templates = []\n", + " \n", + " chosen_op_word_cased = op_sym \n", + " if op_sym == '+':\n", + " chosen_op_word_cased = _apply_random_case_operator_style(random.choice(raw_add_words))\n", + " templates.extend([\n", + " \"What is {num_a} {op} {num_b}{q_mark}\", \"Calculate {num_a} {op} {num_b}{q_mark}\",\n", + " \"If you have {num_a} and add {num_b}, what do you get{q_mark}\",\n", + " \"{num_a} {op} {num_b} {res_phrase}{q_mark}\",\n", + " \"The sum of {num_a} and {num_b} {res_phrase}{q_mark}\",])\n", + " elif op_sym == '-':\n", + " chosen_op_word_cased = _apply_random_case_operator_style(random.choice(raw_subtract_words))\n", + " templates.extend([\n", + " \"What is {num_a} {op} {num_b}{q_mark}\", \"Calculate {num_a} {op} {num_b}{q_mark}\",\n", + " \"If you have {num_a} and take away {num_b}, what remains{q_mark}\",\n", + " \"{num_a} {op} {num_b} {res_phrase}{q_mark}\",\n", + " \"The difference between {num_a} and {num_b} {res_phrase}{q_mark}\",])\n", + " else: return f\"{fmt_a} {op_sym} {fmt_b}\" \n", + " \n", + " if not templates: return f\"{fmt_a} {op_sym} {fmt_b} = ?\"\n", + " \n", + " chosen_template = random.choice(templates)\n", + " chosen_res_phrase_cased = _apply_random_case_operator_style(random.choice(result_phrases_en_raw))\n", + " chosen_q_mark = random.choice(question_marks)\n", + " \n", + " try:\n", + " placeholders = {\"num_a\": fmt_a, \"num_b\": fmt_b, \"op\": chosen_op_word_cased,\n", + " \"res_phrase\": chosen_res_phrase_cased, \"q_mark\": chosen_q_mark}\n", + " format_args = {k: v for k, v in placeholders.items() if \"{\"+k+\"}\" in chosen_template}\n", + " question_str = chosen_template.format(**format_args)\n", + " question_str = ' '.join(question_str.split())\n", + " except KeyError: question_str = f\"{fmt_a} {op_sym} {fmt_b} = ?\"\n", + " return question_str\n", + "\n", + "\n", + "def _generate_pair_meeting_cb_criteria( # Unchanged\n", + " target_digits_a: int, target_digits_b: int, sign_a: int, sign_b: int,\n", + " is_decimal: bool, max_decimal_places_config: int, operation_type: str,\n", + " target_total_cb_min: int, target_total_cb_max: Union[int, float],\n", + " target_consecutive_cb_min: int, target_consecutive_cb_max: Union[int, float]\n", + ") -> Optional[Tuple[Union[int, Decimal], Union[int, Decimal]]]:\n", + " # ... (Original logic for generating number pairs based on carry/borrow) ...\n", + " num_dp = random.randint(1, max_decimal_places_config) if is_decimal and max_decimal_places_config > 0 else 0\n", + " num_int_digits_a = max(1, target_digits_a); num_int_digits_b = max(1, target_digits_b)\n", + " total_len_a = num_int_digits_a + num_dp; total_len_b = num_int_digits_b + num_dp\n", + " max_total_len = max(total_len_a, total_len_b)\n", + " if max_total_len == 0 and num_dp == 0: max_total_len = 1 \n", + " elif max_total_len == 0 and num_dp > 0 : max_total_len = num_dp \n", + "\n", + " effective_op = operation_type\n", + " if operation_type == 'add':\n", + " if sign_a * sign_b < 0: effective_op = 'subtract'\n", + " elif operation_type == 'subtract':\n", + " if sign_a * sign_b < 0: effective_op = 'add'\n", + " op1_digits_rev = []; op2_digits_rev = []\n", + " carry_in = 0; borrow_in = 0\n", + " current_total_cb = 0; current_consecutive_cb = 0; max_consecutive_achieved = 0\n", + " op1_target_len = total_len_a; op2_target_len = total_len_b\n", + " op1_int_digits_orig = num_int_digits_a; op2_int_digits_orig = num_int_digits_b \n", + " is_unlimited_cb_range = (target_total_cb_min == 0 and target_total_cb_max == math.inf and \\\n", + " target_consecutive_cb_min == 0 and target_consecutive_cb_max == math.inf)\n", + " for i in range(max_total_len):\n", + " pos_from_right = i; is_decimal_pos = (pos_from_right < num_dp)\n", + " is_int_pos = not is_decimal_pos; int_pos_from_right = pos_from_right - num_dp if is_int_pos else -1\n", + " \n", + " in_op1 = (pos_from_right < op1_target_len); \n", + " in_op2 = (pos_from_right < op2_target_len)\n", + " \n", + " is_msd_op1_int = in_op1 and is_int_pos and int_pos_from_right == op1_int_digits_orig - 1\n", + " is_msd_op2_int = in_op2 and is_int_pos and int_pos_from_right == op2_int_digits_orig - 1\n", + "\n", + " min_d1 = 0; max_d1 = 0\n", + " if in_op1:\n", + " min_d1 = 1 if is_msd_op1_int and (op1_int_digits_orig > 0 or (op1_int_digits_orig == 0 and num_dp == 0 and total_len_a == 1)) else 0\n", + " max_d1 = 9\n", + " \n", + " min_d2 = 0; max_d2 = 0\n", + " if in_op2:\n", + " min_d2 = 1 if is_msd_op2_int and (op2_int_digits_orig > 0 or (op2_int_digits_orig == 0 and num_dp == 0 and total_len_b == 1)) else 0\n", + " max_d2 = 9\n", + " \n", + " if op1_int_digits_orig == 0 and is_msd_op1_int: min_d1 = 0 # If int part is 0-digits, MSD can be 0.\n", + " if op2_int_digits_orig == 0 and is_msd_op2_int: min_d2 = 0\n", + "\n", + " target_cb_state_for_this_pos = None # True: try to generate CB, False: try to avoid, None: random/opportunistic\n", + " if not is_unlimited_cb_range:\n", + " positions_remaining = max_total_len - (i + 1)\n", + " min_total_cb_needed_later = max(0, target_total_cb_min - current_total_cb)\n", + " max_total_cb_allowed_later = float('inf') if target_total_cb_max == math.inf else target_total_cb_max - current_total_cb\n", + " if max_total_cb_allowed_later < 0: return None # Cannot meet max total constraint\n", + "\n", + " min_consecutive_cb_needed_from_here = max(0, target_consecutive_cb_min - current_consecutive_cb)\n", + " \n", + " must_generate_cb = (min_total_cb_needed_later > positions_remaining) or \\\n", + " (min_consecutive_cb_needed_from_here > positions_remaining and \\\n", + " max_consecutive_achieved < target_consecutive_cb_min and \\\n", + " current_consecutive_cb < target_consecutive_cb_min) # Must generate to meet min consecutive if current path won't\n", + " \n", + " must_avoid_cb_due_to_total = (max_total_cb_allowed_later < 1) # No more CB allowed for total\n", + " must_avoid_cb_due_to_consecutive = (current_consecutive_cb + 1 > target_consecutive_cb_max) if target_consecutive_cb_max != math.inf else False\n", + " \n", + " must_avoid_cb = must_avoid_cb_due_to_total or must_avoid_cb_due_to_consecutive\n", + "\n", + " if must_generate_cb and must_avoid_cb : return None # Conflicting hard constraints\n", + " \n", + " if must_generate_cb: target_cb_state_for_this_pos = True\n", + " elif must_avoid_cb: target_cb_state_for_this_pos = False\n", + " else: # Heuristic choice\n", + " prob_try_generate_cb = 0.5 # Base probability\n", + " # Adjust based on needs and allowances\n", + " if min_total_cb_needed_later > 0 : prob_try_generate_cb += 0.2 * (min_total_cb_needed_later / max(1, positions_remaining +1))\n", + " if min_consecutive_cb_needed_from_here > 0 and max_consecutive_achieved < target_consecutive_cb_min : prob_try_generate_cb += 0.3\n", + " if target_total_cb_max != math.inf and max_total_cb_allowed_later <= positions_remaining : prob_try_generate_cb -= 0.2 * (1 - max_total_cb_allowed_later / max(1, positions_remaining +1))\n", + " if target_consecutive_cb_max != math.inf and current_consecutive_cb +1 >= target_consecutive_cb_max and min_consecutive_cb_needed_from_here == 0: prob_try_generate_cb = 0.1 # strongly avoid if at max consecutive unless needed\n", + " \n", + " prob_try_generate_cb = max(0.05, min(0.95, prob_try_generate_cb)) # Clamp probability\n", + " target_cb_state_for_this_pos = (random.random() < prob_try_generate_cb)\n", + " \n", + " found_d1_d2_pair_for_pos = False\n", + " possible_d1_values = list(range(min_d1, max_d1 + 1)); random.shuffle(possible_d1_values)\n", + " chosen_d1, chosen_d2 = -1, -1\n", + "\n", + " for d1_try in possible_d1_values:\n", + " possible_d2_values_for_d1_try = []\n", + " d2_value_range = list(range(min_d2, max_d2 + 1)); random.shuffle(d2_value_range)\n", + " \n", + " for d2_try in d2_value_range:\n", + " cb_generated_by_this_pair = False\n", + " if effective_op == 'add': cb_generated_by_this_pair = ((d1_try + d2_try + carry_in) >= 10)\n", + " else: cb_generated_by_this_pair = ((d1_try - borrow_in - d2_try) < 0)\n", + " \n", + " cb_state_matches_target = (target_cb_state_for_this_pos is None) or (cb_generated_by_this_pair == target_cb_state_for_this_pos)\n", + " \n", + " # Check future consecutive CB feasibility\n", + " temp_next_consecutive_cb = current_consecutive_cb + 1 if cb_generated_by_this_pair else 0\n", + " consecutive_constraint_ok = True\n", + " if target_consecutive_cb_max != math.inf and temp_next_consecutive_cb > target_consecutive_cb_max:\n", + " consecutive_constraint_ok = False \n", + " \n", + " min_consecutive_still_achievable = True\n", + " if not cb_generated_by_this_pair and target_consecutive_cb_min > 0 : # if we break a sequence\n", + " max_achieved_before_reset = max(max_consecutive_achieved, current_consecutive_cb)\n", + " if max_achieved_before_reset < target_consecutive_cb_min and positions_remaining < target_consecutive_cb_min :\n", + " min_consecutive_still_achievable = False # Cannot achieve min consecutive anymore if this CB is not generated\n", + "\n", + " if cb_state_matches_target and consecutive_constraint_ok and min_consecutive_still_achievable:\n", + " possible_d2_values_for_d1_try.append(d2_try)\n", + "\n", + " if possible_d2_values_for_d1_try:\n", + " chosen_d2 = random.choice(possible_d2_values_for_d1_try); chosen_d1 = d1_try\n", + " found_d1_d2_pair_for_pos = True; break\n", + " \n", + " if not found_d1_d2_pair_for_pos: return None # No valid d1,d2 pair for this position\n", + " \n", + " op1_digits_rev.append(str(chosen_d1)); op2_digits_rev.append(str(chosen_d2))\n", + " \n", + " cb_occurred_at_this_pos = False\n", + " if effective_op == 'add':\n", + " current_sum_val = chosen_d1 + chosen_d2 + carry_in; carry_in = 1 if current_sum_val >= 10 else 0; borrow_in = 0\n", + " cb_occurred_at_this_pos = (carry_in == 1)\n", + " else: # subtract\n", + " current_diff_val = chosen_d1 - borrow_in - chosen_d2; borrow_in = 1 if current_diff_val < 0 else 0; carry_in = 0\n", + " cb_occurred_at_this_pos = (borrow_in == 1)\n", + " \n", + " if cb_occurred_at_this_pos: current_total_cb += 1; current_consecutive_cb += 1\n", + " else: max_consecutive_achieved = max(max_consecutive_achieved, current_consecutive_cb); current_consecutive_cb = 0\n", + " \n", + " max_consecutive_achieved = max(max_consecutive_achieved, current_consecutive_cb) # Final update for max_consecutive\n", + " \n", + " if not is_unlimited_cb_range: # Final check of constraints if they are active\n", + " total_cb_ok = (target_total_cb_min <= current_total_cb <= target_total_cb_max)\n", + " consecutive_cb_ok = (max_consecutive_achieved >= target_consecutive_cb_min) and \\\n", + " (target_consecutive_cb_max == math.inf or max_consecutive_achieved <= target_consecutive_cb_max)\n", + " if not (total_cb_ok and consecutive_cb_ok): return None\n", + "\n", + " op1_str_msd_first = \"\".join(reversed(op1_digits_rev)); op2_str_msd_first = \"\".join(reversed(op2_digits_rev))\n", + "\n", + " def _format_digit_str_to_decimal_val(s: str, dp_count: int) -> Decimal:\n", + " if not s: s = \"0\" # Should not happen if constructed properly\n", + " total_digits_in_s = len(s)\n", + " if dp_count > 0:\n", + " int_part_len_in_s = total_digits_in_s - dp_count\n", + " if int_part_len_in_s <=0: # e.g. s=\"12\", dp=3 -> \"0.012\" ; s=\"123\", dp=3 -> \"0.123\"\n", + " integer_str = \"0\"\n", + " fractional_str = s.zfill(dp_count) # Pad with leading zeros if s is shorter than dp_count\n", + " else:\n", + " integer_str = s[:int_part_len_in_s]\n", + " fractional_str = s[int_part_len_in_s:]\n", + " full_s_with_point = f\"{integer_str}.{fractional_str}\"\n", + " else: # Integer\n", + " full_s_with_point = s\n", + " \n", + " # Normalize leading zeros for integer part, e.g. \"05\" -> \"5\", \"0.5\" -> \"0.5\"\n", + " # But be careful not to make \"0\" from \"0.xx\" into \"\"\n", + " if '.' in full_s_with_point:\n", + " integer_part, fractional_part = full_s_with_point.split('.',1)\n", + " integer_part = integer_part.lstrip('0')\n", + " if not integer_part: integer_part = \"0\" # for cases like \".5\" becoming \"0.5\"\n", + " full_s_with_point = f\"{integer_part}.{fractional_part}\"\n", + " else: # Integer string\n", + " full_s_with_point = full_s_with_point.lstrip('0')\n", + " if not full_s_with_point: full_s_with_point = \"0\" # for \"00\" becoming \"0\"\n", + " \n", + " return Decimal(full_s_with_point)\n", + "\n", + " try:\n", + " val1_abs = _format_digit_str_to_decimal_val(op1_str_msd_first, num_dp)\n", + " val2_abs = _format_digit_str_to_decimal_val(op2_str_msd_first, num_dp)\n", + " \n", + " a_val_final_signed = val1_abs.copy_sign(Decimal(sign_a))\n", + " b_val_final_signed = val2_abs.copy_sign(Decimal(sign_b))\n", + "\n", + " # Normalize -0 to 0\n", + " if a_val_final_signed.is_zero() and a_val_final_signed.is_signed(): a_val_final_signed = Decimal('0')\n", + " if b_val_final_signed.is_zero() and b_val_final_signed.is_signed(): b_val_final_signed = Decimal('0')\n", + "\n", + " if not is_decimal and num_dp == 0: # Intended as integers\n", + " a_final_val = int(a_val_final_signed) # Convert to int if it's an integer type\n", + " b_final_val = int(b_val_final_signed)\n", + " else: # Intended as decimals or mixed\n", + " a_final_val = a_val_final_signed.normalize() # Keep as Decimal, normalize\n", + " b_final_val = b_val_final_signed.normalize()\n", + " # Redo -0 to 0 after normalize, as normalize might reintroduce it for some ops\n", + " if a_final_val.is_zero() and a_final_val.is_signed(): a_final_val = Decimal('0')\n", + " if b_final_val.is_zero() and b_final_val.is_signed(): b_final_val = Decimal('0')\n", + "\n", + " return a_final_val, b_final_val\n", + " except InvalidOperation: return None # Error during Decimal conversion\n", + " except Exception: return None # Other unexpected errors\n", + "\n", + "\n", + "def check_carries_borrows(num1: Decimal, num2: Decimal, operation: str) -> Tuple[int, int]: # Unchanged\n", + " total_cb = 0; max_consecutive_cb = 0; current_consecutive_cb = 0\n", + " try:\n", + " effective_op = operation; op1: Decimal; op2: Decimal\n", + " # Normalize inputs first\n", + " num1_norm = num1.normalize(); num2_norm = num2.normalize()\n", + " if num1_norm.is_zero() and num1_norm.is_signed(): num1_norm = Decimal('0')\n", + " if num2_norm.is_zero() and num2_norm.is_signed(): num2_norm = Decimal('0')\n", + "\n", + " # Determine effective operation and operands (always positive for digit math)\n", + " if operation == 'add':\n", + " if num1_norm.is_signed() != num2_norm.is_signed(): # e.g. 5 + (-3) -> 5 - 3 ; -5 + 3 -> -(5 - 3)\n", + " effective_op = 'subtract'\n", + " if abs(num1_norm) >= abs(num2_norm): op1, op2 = abs(num1_norm), abs(num2_norm)\n", + " else: op1, op2 = abs(num2_norm), abs(num1_norm) # Larger abs first for std subtraction\n", + " else: # 5 + 3 or -5 + (-3) -> -(5+3)\n", + " effective_op = 'add'; op1, op2 = abs(num1_norm), abs(num2_norm)\n", + " elif operation == 'subtract':\n", + " if num1_norm.is_signed() != num2_norm.is_signed(): # e.g. 5 - (-3) -> 5 + 3 ; -5 - 3 -> -(5+3)\n", + " effective_op = 'add'; op1, op2 = abs(num1_norm), abs(num2_norm)\n", + " else: # 5 - 3 or -5 - (-3) -> -5 + 3 -> -(5-3)\n", + " effective_op = 'subtract'\n", + " if abs(num1_norm) >= abs(num2_norm): op1, op2 = abs(num1_norm), abs(num2_norm)\n", + " else: op1, op2 = abs(num2_norm), abs(num1_norm)\n", + " else: return -1, -1 # Invalid operation type\n", + " \n", + " op1 = abs(op1.normalize()) # Ensure positive and normalized\n", + " op2 = abs(op2.normalize())\n", + " if op1.is_zero() and op1.is_signed(): op1 = Decimal('0') # Redundant given earlier, but safe\n", + " if op2.is_zero() and op2.is_signed(): op2 = Decimal('0')\n", + "\n", + " if op1.is_zero() and op2.is_zero(): return 0, 0 # No CBs for 0 +/- 0\n", + "\n", + " # Convert to strings and align decimal points\n", + " s1 = format_decimal_or_int(op1); s2 = format_decimal_or_int(op2)\n", + " s1_int_part, s1_frac_part = s1.split('.') if '.' in s1 else (s1, '')\n", + " s2_int_part, s2_frac_part = s2.split('.') if '.' in s2 else (s2, '')\n", + " \n", + " max_frac_len = max(len(s1_frac_part), len(s2_frac_part))\n", + " s1_frac_part = s1_frac_part.ljust(max_frac_len, '0'); s2_frac_part = s2_frac_part.ljust(max_frac_len, '0')\n", + " \n", + " max_int_len = max(len(s1_int_part), len(s2_int_part))\n", + " s1_int_part = s1_int_part.zfill(max_int_len); s2_int_part = s2_int_part.zfill(max_int_len)\n", + " \n", + " aligned_s1 = s1_int_part + s1_frac_part; aligned_s2 = s2_int_part + s2_frac_part\n", + " \n", + " full_len = len(aligned_s1) # Should be same for both after alignment\n", + " carry = 0; borrow = 0 # For add and subtract respectively\n", + "\n", + " for i in range(full_len - 1, -1, -1): # Iterate from rightmost digit (LSD)\n", + " try: d1 = int(aligned_s1[i]); d2 = int(aligned_s2[i])\n", + " except (IndexError, ValueError): return -1, -1 # Should not happen with proper alignment\n", + " \n", + " cb_occurred_this_digit = False\n", + " if effective_op == 'add':\n", + " current_sum_digit = d1 + d2 + carry\n", + " carry = 1 if current_sum_digit >= 10 else 0\n", + " cb_occurred_this_digit = (carry == 1)\n", + " else: # subtract (op1 is guaranteed >= op2 for this block)\n", + " current_diff_digit = d1 - borrow - d2\n", + " borrow = 1 if current_diff_digit < 0 else 0\n", + " cb_occurred_this_digit = (borrow == 1)\n", + " \n", + " if cb_occurred_this_digit:\n", + " total_cb += 1\n", + " current_consecutive_cb += 1\n", + " else:\n", + " max_consecutive_cb = max(max_consecutive_cb, current_consecutive_cb)\n", + " current_consecutive_cb = 0\n", + " \n", + " max_consecutive_cb = max(max_consecutive_cb, current_consecutive_cb) # Final update\n", + " except Exception:\n", + " # traceback.print_exc() # For debugging\n", + " return -1, -1 # Error in calculation\n", + " return total_cb, max_consecutive_cb\n", + "\n", + "\n", + "def write_batch_to_jsonl(buffer: List[Dict], filename: str, mode: str = 'a') -> int: # Unchanged\n", + " if not buffer: return 0\n", + " lines_written = 0; json_lines_to_write = []; serialization_errors = 0\n", + " for item in buffer:\n", + " try:\n", + " if not isinstance(item, dict) or not item.get(\"text\"): # Basic validation\n", + " serialization_errors += 1; continue\n", + " json_string = json.dumps(item, ensure_ascii=False)\n", + " if json_string and not json_string.isspace(): # Ensure not empty string\n", + " json_lines_to_write.append(json_string)\n", + " else:\n", + " serialization_errors += 1\n", + " except (TypeError, ValueError): serialization_errors += 1 # Common JSON errors\n", + " except Exception: serialization_errors += 1 # Other unexpected errors\n", + " \n", + " if json_lines_to_write:\n", + " try:\n", + " with open(filename, mode, encoding='utf-8') as f:\n", + " f.write('\\n'.join(json_lines_to_write) + '\\n') # Add trailing newline for robustness\n", + " lines_written = len(json_lines_to_write)\n", + " except IOError: return 0 # Failed to write to file\n", + " except Exception: return 0 # Other write errors\n", + " \n", + " if serialization_errors > 0:\n", + " print(f\"\\n警告: 写入批次时 {serialization_errors} 个项目处理失败。\")\n", + " return lines_written\n", + "\n", + "def randomly_replace_characters_in_string(text: str, replacement_prob: float, char_pool: str) -> str: # Unchanged\n", + " if not text or replacement_prob <= 0 or not char_pool: return text\n", + " new_chars = list(text)\n", + " for i in range(len(new_chars)):\n", + " if random.random() < replacement_prob:\n", + " # Avoid replacing newlines to maintain structure\n", + " if new_chars[i] not in ['\\n', '\\r']:\n", + " new_chars[i] = random.choice(char_pool)\n", + " return \"\".join(new_chars)\n", + "\n", + "# --- 主要生成函数 ---\n", + "def generate_constructed_arithmetic_diverse(\n", + " filename: str, total_samples: int, add_prob: float, decimal_prob: float,\n", + " max_digits_limit: int, max_decimal_places_cfg: int, negative_pool_prob: float,\n", + " target_total_cb_min: int, target_total_cb_max: Union[int, float],\n", + " target_consecutive_cb_min: int, target_consecutive_cb_max: Union[int, float],\n", + " nl_question_prob: float,\n", + " symbolic_equals_suffix_prob: float,\n", + " max_attempts_factor: int,\n", + " batch_save_size: int,\n", + " apply_general_char_corr: bool,\n", + " general_char_corr_prob: float,\n", + " general_char_corr_pool: str\n", + " ):\n", + " # ... (Unchanged from original logic, relies on modified underlying functions) ...\n", + " print(f\"--- 开始生成算术数据 (v10.15 - Independent Word Casing & Digit-by-Digit English) ---\") # Updated print\n", + " print(f\"数字格式概率: Standard Arabic: {STANDARD_ARABIC_PROB*100:.1f}%, Full-width: {FULL_WIDTH_ARABIC_PROB*100:.1f}%, English Words: {ENGLISH_WORDS_PROB*100:.1f}%\")\n", + " print(f\"英文数字大小写: {ENGLISH_NUMBER_ENTIRE_STRING_CASE_PROB*100:.0f}% 整体(逐词独立风格)随机, { (1-ENGLISH_NUMBER_ENTIRE_STRING_CASE_PROB)*100:.0f}% 逐字符随机\")\n", + " print(f\"符号题中英文运算符概率: {SYMBOLIC_OPERATOR_WORD_PROB*100:.1f}%\")\n", + " if APPLY_INTRA_CHAR_SPACING: print(f\"字符间随机空格已启用。\") \n", + " else: print(\"字符间随机空格 (数字/单词内部) 未启用。仅运算符周围有随机空格。\")\n", + " if apply_general_char_corr: print(f\"通用字符级损坏已启用: 概率={general_char_corr_prob*100:.2f}%\")\n", + " else: print(\"通用字符级损坏未启用。\")\n", + "\n", + " digit_pop: List[int] = []; digit_probs_list: List[float] = []\n", + " if max_digits_limit > 0:\n", + " digit_probabilities_dict = calculate_digit_probabilities(max_digits_limit)\n", + " digit_pop = list(range(1, max_digits_limit + 1)); digit_probs_list = [digit_probabilities_dict.get(n, 0.0) for n in digit_pop]\n", + " prob_sum_check = sum(digit_probs_list)\n", + " if not math.isclose(prob_sum_check, 1.0, abs_tol=1e-5): # Normalize if not close to 1.0\n", + " if prob_sum_check > 1e-9: digit_probs_list = [p / prob_sum_check for p in digit_probs_list]\n", + " else: # Fallback to uniform if sum is too small (e.g., all zeros)\n", + " uniform_prob = 1.0 / len(digit_pop) if digit_pop else 1.0; digit_probs_list = [uniform_prob] * len(digit_pop)\n", + " if not digit_probs_list and digit_pop: # If list became empty but pop exists (should not happen with above)\n", + " digit_probs_list = [1.0/len(digit_pop)]*len(digit_pop)\n", + " elif not digit_pop : # If max_digits_limit was 0 or negative (handled by calculate_digit_probabilities returning {1:1.0})\n", + " digit_pop = [1]; digit_probs_list = [1.0]\n", + " else: # max_digits_limit is 0 or less\n", + " digit_pop = [1]; digit_probs_list = [1.0] # Default to 1 digit if max_digits is not positive\n", + "\n", + " generated_count = 0; total_attempts = 0; total_lines_written = 0\n", + " construct_failures = 0; add_count = 0; subtract_count = 0\n", + " integer_op_count = 0; decimal_op_count = 0 # Based on intent or actual values\n", + " format_counts = Counter(); question_type_counts = Counter(); suffix_counts = Counter()\n", + " errors_in_loop = 0 # For non-construction errors within the main loop\n", + "\n", + " # Adjust max_attempts based on difficulty of carry/borrow constraints\n", + " difficulty_factor_cb = max(1, target_total_cb_min) if target_total_cb_max != math.inf else 1\n", + " difficulty_factor_cb = max(difficulty_factor_cb, target_consecutive_cb_min // 2 if target_consecutive_cb_max !=math.inf else 1) # Heuristic\n", + " max_total_attempts = total_samples * max(100, max_attempts_factor * difficulty_factor_cb)\n", + "\n", + " start_time_generate = time.time(); output_buffer = []; last_reported_count = -1; last_save_time = start_time_generate\n", + "\n", + " try: # Initialize/clear output file\n", + " with open(filename, 'w', encoding='utf-8') as f: f.write(\"\") # Clears the file\n", + " print(f\"已初始化/清空输出文件: '{filename}'\")\n", + " except IOError as e:\n", + " print(f\"\\n错误:无法初始化输出文件 '{filename}': {e}\"); return\n", + "\n", + " print(f\"\\n开始构造 {total_samples:,} 条满足条件的数据...\")\n", + " \n", + " while generated_count < total_samples:\n", + " total_attempts += 1\n", + " if total_attempts > max_total_attempts:\n", + " print(f\"\\n\\n警告: 尝试次数达到上限 ({total_attempts:,})。\");\n", + " print(f\"当前已生成: {generated_count:,} (构造失败 {construct_failures:,} 次).\");\n", + " print(\"脚本提前终止.\"); break\n", + " \n", + " a: Union[int, Decimal] = Decimal('0'); b: Union[int, Decimal] = Decimal('0') # Type hints for clarity\n", + " try:\n", + " # Determine number of digits for operands\n", + " if not digit_pop or not digit_probs_list or len(digit_pop) != len(digit_probs_list): # Safety check\n", + " digits_a = random.randint(1, max(1,max_digits_limit))\n", + " digits_b = random.randint(1, max(1,max_digits_limit))\n", + " else:\n", + " digits_a = get_distributed_count_from_probs(digit_pop, digit_probs_list)\n", + " digits_b = get_distributed_count_from_probs(digit_pop, digit_probs_list)\n", + "\n", + " sign_a = -1 if random.random() < negative_pool_prob else 1\n", + " sign_b = -1 if random.random() < negative_pool_prob else 1\n", + " is_dec_intent_current = random.random() < decimal_prob\n", + " op_type_current = 'add' if random.random() < add_prob else 'subtract'\n", + " op_sym_current = '+' if op_type_current == 'add' else '-'\n", + "\n", + " # Generate number pair meeting carry/borrow criteria\n", + " constructed_pair = _generate_pair_meeting_cb_criteria(\n", + " digits_a, digits_b, sign_a, sign_b, is_dec_intent_current, max_decimal_places_cfg,\n", + " op_type_current, target_total_cb_min, target_total_cb_max,\n", + " target_consecutive_cb_min, target_consecutive_cb_max)\n", + "\n", + " if constructed_pair is None:\n", + " construct_failures += 1; continue # Try again\n", + " \n", + " a, b = constructed_pair\n", + " \n", + " # Calculate the true answer\n", + " c_final: Union[int, Decimal]; answer_str = \"\"\n", + " try:\n", + " # Ensure a and b are Decimals for calculation, robustly\n", + " a_calc = Decimal(str(a)) if not isinstance(a, Decimal) else a\n", + " b_calc = Decimal(str(b)) if not isinstance(b, Decimal) else b\n", + "\n", + " if not a_calc.is_finite() or not b_calc.is_finite(): # Safety for Inf/NaN from construction (should not happen)\n", + " errors_in_loop += 1; continue\n", + "\n", + " c_calc = a_calc + b_calc if op_type_current == 'add' else a_calc - b_calc\n", + " if not c_calc.is_finite(): # Safety for Inf/NaN result\n", + " errors_in_loop += 1; continue\n", + "\n", + " # Determine precision for the result based on operands and intent\n", + " effective_dp_a = 0; effective_dp_b = 0\n", + " if isinstance(a_calc, Decimal) and a_calc.as_tuple().exponent < 0: # Negative exponent means decimal places\n", + " effective_dp_a = abs(a_calc.as_tuple().exponent)\n", + " if isinstance(b_calc, Decimal) and b_calc.as_tuple().exponent < 0:\n", + " effective_dp_b = abs(b_calc.as_tuple().exponent)\n", + " \n", + " result_dp = max(effective_dp_a, effective_dp_b) # Result precision matches max operand precision\n", + " if not is_dec_intent_current and effective_dp_a == 0 and effective_dp_b == 0: # If integer op was intended and operands are ints\n", + " result_dp = 0\n", + " \n", + " result_dp = min(result_dp, max_decimal_places_cfg) # Cap by global max decimal places\n", + "\n", + " # Quantize and normalize the result\n", + " if result_dp > 0:\n", + " c_final_dec = c_calc.quantize(Decimal('1e-' + str(result_dp)), rounding=ROUND_HALF_UP)\n", + " else: # Integer result\n", + " c_final_dec = c_calc.to_integral_value(rounding=ROUND_HALF_UP)\n", + " \n", + " c_final_dec = c_final_dec.normalize() # Clean up e.g. trailing zeros, 1.0 -> 1\n", + " if c_final_dec.is_zero() and c_final_dec.is_signed(): # -0 -> 0\n", + " c_final_dec = Decimal('0')\n", + "\n", + " # Determine if final answer should be int or Decimal\n", + " is_a_actually_int = isinstance(a, int) or (isinstance(a, Decimal) and a == a.to_integral_value())\n", + " is_b_actually_int = isinstance(b, int) or (isinstance(b, Decimal) and b == b.to_integral_value())\n", + " is_c_actually_int = (c_final_dec == c_final_dec.to_integral_value())\n", + "\n", + " if is_c_actually_int and is_a_actually_int and is_b_actually_int and not is_dec_intent_current:\n", + " try: c_final = int(c_final_dec) # Prefer int if all are ints and intent was int\n", + " except (OverflowError, ValueError): c_final = c_final_dec # If too large for int\n", + " else:\n", + " c_final = c_final_dec # Keep as Decimal\n", + " \n", + " answer_str = format_decimal_or_int(c_final) # Format answer for output\n", + "\n", + " except (InvalidOperation, OverflowError, ValueError, ArithmeticError) as calc_err:\n", + " errors_in_loop += 1; # print(f\"Calc error: {calc_err}, a={a}, b={b}, op={op_type_current}\");\n", + " continue\n", + " except Exception as e_calc: # Other calculation errors\n", + " errors_in_loop += 1; # print(f\"Unexpected calc error: {e_calc}\");\n", + " continue\n", + "\n", + " if not answer_str: # If answer formatting failed\n", + " errors_in_loop += 1; continue\n", + "\n", + " # Format question string\n", + " try:\n", + " fmt_a_str_processed, fmt_a_type = format_number_variant(a)\n", + " \n", + " final_op_sym_for_question = op_sym_current # May change if b is negative\n", + " fmt_b_str_processed, fmt_b_type = \"\", \"\"\n", + "\n", + " # Handle negative b: abs(b) is formatted, operator might flip\n", + " b_dec_for_fmt = Decimal(str(b)) if not isinstance(b, Decimal) else b # Ensure Decimal\n", + " if b_dec_for_fmt.is_signed() and b_dec_for_fmt < 0:\n", + " # Format absolute value of b\n", + " fmt_b_abs_str_processed, fmt_b_abs_type = format_number_variant(abs(b_dec_for_fmt))\n", + " fmt_b_str_processed = fmt_b_abs_str_processed\n", + " fmt_b_type = fmt_b_abs_type\n", + " # Flip operator: a + (-b) -> a - b; a - (-b) -> a + b\n", + " if op_sym_current == '+': final_op_sym_for_question = '-'\n", + " elif op_sym_current == '-': final_op_sym_for_question = '+'\n", + " else: # b is positive or zero\n", + " fmt_b_str_processed, fmt_b_type = format_number_variant(b)\n", + "\n", + " if not fmt_a_str_processed or not fmt_b_str_processed: # Formatting failed for operands\n", + " errors_in_loop +=1; continue\n", + " \n", + " format_counts[f'a_{fmt_a_type}'] += 1; format_counts[f'b_{fmt_b_type}'] += 1\n", + " \n", + " question_str = \"\"\n", + " is_nl_question_current = random.random() < nl_question_prob\n", + " \n", + " display_op_for_symbolic = final_op_sym_for_question # Default symbol\n", + " if not is_nl_question_current and random.random() < SYMBOLIC_OPERATOR_WORD_PROB:\n", + " # Try to use English word for operator in symbolic questions\n", + " if final_op_sym_for_question in ENGLISH_OPERATOR_WORDS:\n", + " word_choices = ENGLISH_OPERATOR_WORDS[final_op_sym_for_question]\n", + " chosen_word_raw = random.choice(word_choices)\n", + " display_op_for_symbolic = _apply_random_case_operator_style(chosen_word_raw)\n", + " format_counts['operator_word'] += 1\n", + " else: # Fallback to symbol if not defined (should not happen for +/-)\n", + " format_counts['operator_symbol'] += 1 \n", + " elif not is_nl_question_current: # Symbolic question using symbol\n", + " format_counts['operator_symbol'] += 1\n", + "\n", + " if is_nl_question_current:\n", + " question_type_counts['natural_language'] += 1\n", + " question_str = format_natural_language_question(fmt_a_str_processed, fmt_b_str_processed, final_op_sym_for_question)\n", + " else: # Symbolic question\n", + " question_type_counts['symbolic'] += 1\n", + " space1_op = get_realistic_spacing(); space2_op = get_realistic_spacing()\n", + " question_str_base = f\"{fmt_a_str_processed}{space1_op}{display_op_for_symbolic}{space2_op}{fmt_b_str_processed}\"\n", + " \n", + " question_suffix = \"\"; added_suffix_flag = False\n", + " if random.random() < symbolic_equals_suffix_prob:\n", + " q_mark = random.choice([\"?\", \"\"]) # Optional question mark\n", + " space_eq1 = get_realistic_spacing(); space_eq2 = get_realistic_spacing()\n", + " equals_sign = random.choice([\"=\"]) # Could add full-width equals later if desired\n", + " question_suffix = f\"{space_eq1}{equals_sign}{space_eq2}{q_mark}\"\n", + " added_suffix_flag = True\n", + " \n", + " suffix_counts['symbolic_added_equals' if added_suffix_flag else 'symbolic_no_equals'] += 1\n", + " question_str = question_str_base + question_suffix\n", + "\n", + " if not question_str or question_str.isspace(): # Final check on question string\n", + " errors_in_loop += 1; continue\n", + " \n", + " # Apply general character corruption if enabled\n", + " text_content = f\"User: {question_str}\\n\\nAssistant: {answer_str}\"\n", + " if apply_general_char_corr:\n", + " text_content = randomly_replace_characters_in_string(text_content, general_char_corr_prob, general_char_corr_pool)\n", + "\n", + " pair_data = {\"text\": text_content}\n", + " output_buffer.append(pair_data)\n", + " generated_count += 1\n", + "\n", + " # Update statistics\n", + " if op_type_current == 'add': add_count += 1\n", + " else: subtract_count += 1\n", + " \n", + " is_a_truly_decimal_val = isinstance(a, Decimal) and a != a.to_integral_value()\n", + " is_b_truly_decimal_val = isinstance(b, Decimal) and b != b.to_integral_value()\n", + " is_c_truly_decimal_val = isinstance(c_final, Decimal) and c_final != c_final.to_integral_value()\n", + " if is_dec_intent_current or is_a_truly_decimal_val or is_b_truly_decimal_val or is_c_truly_decimal_val:\n", + " decimal_op_count += 1\n", + " else:\n", + " integer_op_count += 1\n", + "\n", + " # Batch save\n", + " if len(output_buffer) >= batch_save_size:\n", + " write_op_start_time = time.time()\n", + " num_written_this_batch = write_batch_to_jsonl(output_buffer, filename, mode='a')\n", + " write_op_duration = time.time() - write_op_start_time\n", + " if num_written_this_batch > 0:\n", + " total_lines_written += num_written_this_batch\n", + " avg_save_sps = num_written_this_batch / write_op_duration if write_op_duration > 0 else float('inf')\n", + " # print(f\"\\r--- 已保存批次 {num_written_this_batch:>6,} (耗时 {write_op_duration:.2f}s, {avg_save_sps:.1f}/s). 总计写入: {total_lines_written:>8,} / 生成: {generated_count:>8,} ---{' '*5}\", end=\"\")\n", + " output_buffer.clear(); last_save_time = time.time()\n", + " else: # Write failure\n", + " print(f\"\\n警告: 写入批处理失败 (已生成 {generated_count:,} 条)。缓冲区已清空但数据丢失。\")\n", + " errors_in_loop += len(output_buffer) # Count lost items as errors\n", + " output_buffer.clear()\n", + " \n", + " except Exception as fmt_err: # Error during formatting/question gen\n", + " errors_in_loop += 1; # print(f\"Formatting error: {fmt_err}\");\n", + " continue\n", + "\n", + " except KeyboardInterrupt: print(\"\\n用户中断。\"); break\n", + " except Exception as outer_loop_err: # Catch-all for other unexpected errors in the loop\n", + " errors_in_loop += 1; # print(f\"Outer loop error: {outer_loop_err}, traceback: {traceback.format_exc()}\");\n", + " continue\n", + " \n", + " # Progress reporting\n", + " report_freq_interval = max(1, total_samples // 200) if total_samples > 0 else 1000\n", + " current_time = time.time()\n", + " time_since_last_activity = current_time - max(last_save_time, start_time_generate if last_reported_count == -1 else last_save_time)\n", + "\n", + " if generated_count > 0 and (generated_count % report_freq_interval == 0 or generated_count == total_samples or time_since_last_activity > 15): # Report every N samples or if 15s idle\n", + " if last_reported_count != generated_count: # Avoid re-printing same status\n", + " progress_percent = generated_count / total_samples if total_samples > 0 else 0\n", + " elapsed_seconds = current_time - start_time_generate\n", + " samples_per_sec_rate = generated_count / elapsed_seconds if elapsed_seconds > 0 else 0\n", + " attempts_per_gen_sample = total_attempts / generated_count if generated_count > 0 else float('inf')\n", + " construct_failure_rate = construct_failures / total_attempts if total_attempts > 0 else 0\n", + " est_remaining_time_str = \"N/A\"\n", + " if progress_percent > 1e-6 and samples_per_sec_rate > 0: # Avoid division by zero or tiny progress\n", + " remaining_samples_to_gen = total_samples - generated_count\n", + " est_remaining_seconds = remaining_samples_to_gen / samples_per_sec_rate\n", + " if est_remaining_seconds < 60: est_remaining_time_str = f\"{est_remaining_seconds:.0f}s\"\n", + " elif est_remaining_seconds < 3600: est_remaining_time_str = f\"{est_remaining_seconds/60:.1f}m\"\n", + " else: est_remaining_time_str = f\"{est_remaining_seconds/3600:.1f}h\"\n", + " \n", + " stats_line = f\"生成: {generated_count:>8,}/{total_samples:<8,} ({progress_percent:5.1%}) | 写入: {total_lines_written:>8,} | 尝试: {total_attempts:>9,} ({attempts_per_gen_sample:5.1f}/样本) | 失败率: {construct_failure_rate:5.1%} | {samples_per_sec_rate:6.1f} 样本/秒 | 耗时: {elapsed_seconds:6.1f}s | 剩余: ~{est_remaining_time_str:<5}\"\n", + " print(f\"\\r{stats_line.ljust(120)}\", end=\"\") # ljust to clear previous line\n", + " last_reported_count = generated_count\n", + " \n", + " # --- End of generation loop ---\n", + " print(\" \" * 120, end=\"\\r\") # Clear final progress line\n", + " print(f\"\\n构造循环结束。目标: {total_samples:,}, 实际生成: {generated_count:,} (尝试 {total_attempts:,} 次, 构造失败 {construct_failures:,} 次).\")\n", + "\n", + " if output_buffer: # Write any remaining samples\n", + " print(f\"写入最后 {len(output_buffer):,} 条数据...\"); final_write_start = time.time()\n", + " num_final_written = write_batch_to_jsonl(output_buffer, filename, mode='a')\n", + " final_write_duration = time.time() - final_write_start\n", + " if num_final_written > 0:\n", + " total_lines_written += num_final_written\n", + " print(f\"最终批次写入完成 ({num_final_written:,} 条). 耗时: {final_write_duration:.2f}s.\")\n", + " else:\n", + " print(\"警告: 最终批次写入失败.\"); errors_in_loop += len(output_buffer)\n", + " output_buffer.clear()\n", + " else:\n", + " print(\"无剩余数据需写入.\")\n", + "\n", + " total_generation_end_time = time.time()\n", + " total_generation_duration = total_generation_end_time - start_time_generate\n", + "\n", + " print(f\"\\n生成与写入完毕。目标: {total_samples:,} -> 生成: {generated_count:,} -> 写入: {total_lines_written:,}\")\n", + " if total_lines_written != generated_count and generated_count > 0 : # Mismatch check\n", + " print(f\"警告: 写入行数({total_lines_written:,}) 与 生成数({generated_count:,}) 不匹配!\")\n", + " \n", + " avg_attempts_per_actual_sample = total_attempts / max(1, generated_count) if generated_count > 0 else float('inf')\n", + " overall_construct_failure_rate = construct_failures / total_attempts if total_attempts > 0 else 0\n", + " print(f\"总尝试次数: {total_attempts:,} (平均 {avg_attempts_per_actual_sample:.2f} 次/有效样本)\")\n", + " print(f\"构造失败次数: {construct_failures:,} (失败率: {overall_construct_failure_rate:.2%})\")\n", + " print(f\"总耗时: {total_generation_duration:.2f} 秒。格式化/计算/写入等循环内错误: {errors_in_loop:,}.\")\n", + "\n", + " # Detailed statistics\n", + " print(\"\\n\" + \"=\"*15 + \" 详细统计 (基于生成的有效样本) \" + \"=\"*15)\n", + " if generated_count > 0:\n", + " print(f\"总有效样本: {generated_count:,}\")\n", + " print(\"-\" * 50); print(\"1. 算术题类型:\");\n", + " print(f\" - 加法: {add_count:>10,} ({add_count/generated_count*100:>6.1f}%)\")\n", + " print(f\" - 减法: {subtract_count:>10,} ({subtract_count/generated_count*100:>6.1f}%)\")\n", + " \n", + " print(\"-\" * 50); print(\"2. 运算数类型:\");\n", + " print(f\" - 纯整数运算*: {integer_op_count:>10,} ({integer_op_count/generated_count*100:>6.1f}%)\")\n", + " print(f\" - 含小数运算*: {decimal_op_count:>10,} ({decimal_op_count/generated_count*100:>6.1f}%)\")\n", + " print(\" *注: 基于操作数或结果是否包含实际小数部分,或生成意图是否为小数。\")\n", + "\n", + " total_fmt_a_counts = sum(format_counts[k] for k in format_counts if k.startswith('a_'))\n", + " print(\"-\" * 50); print(f\"3. 问题格式 - 操作数 A (总计: {total_fmt_a_counts:,}):\")\n", + " ordered_fmt_keys_num = ['a_standard', 'a_full_width', 'a_english_words']\n", + " for fmt_key in ordered_fmt_keys_num:\n", + " print(f\" - {fmt_key[2:]: <15}: {format_counts.get(fmt_key, 0):>10,} ({(format_counts.get(fmt_key, 0) / total_fmt_a_counts * 100) if total_fmt_a_counts > 0 else 0:>6.1f}%)\")\n", + " \n", + " total_fmt_b_counts = sum(format_counts[k] for k in format_counts if k.startswith('b_'))\n", + " print(\"-\" * 50); print(f\"4. 问题格式 - 操作数 B (总计: {total_fmt_b_counts:,}):\")\n", + " for fmt_key in ordered_fmt_keys_num: # Same keys for B\n", + " print(f\" - {fmt_key[2:]: <15}: {format_counts.get(fmt_key.replace('a_','b_'), 0):>10,} ({(format_counts.get(fmt_key.replace('a_','b_'), 0) / total_fmt_b_counts * 100) if total_fmt_b_counts > 0 else 0:>6.1f}%)\")\n", + "\n", + " total_op_format_counts = format_counts.get('operator_word', 0) + format_counts.get('operator_symbol', 0)\n", + " print(\"-\" * 50); print(f\"5. 问题格式 - 符号题运算符 (总计符号题运算符: {total_op_format_counts:,}):\")\n", + " print(f\" - 符号 (+, -): {format_counts.get('operator_symbol', 0):>10,} ({(format_counts.get('operator_symbol', 0) / total_op_format_counts * 100) if total_op_format_counts > 0 else 0:>6.1f}%)\")\n", + " print(f\" - 英文单词: {format_counts.get('operator_word', 0):>10,} ({(format_counts.get('operator_word', 0) / total_op_format_counts * 100) if total_op_format_counts > 0 else 0:>6.1f}%)\")\n", + "\n", + " total_q_type_counts = sum(question_type_counts.values())\n", + " print(\"-\" * 50); print(f\"6. 问题格式 - 类型 (总计: {total_q_type_counts:,}):\")\n", + " ordered_q_type_keys = ['symbolic', 'natural_language']\n", + " display_name_map_qtype = {'symbolic': '符号格式 (+/- or words)', 'natural_language': '自然语言格式 (English)'}\n", + " for q_type_key in ordered_q_type_keys:\n", + " count = question_type_counts.get(q_type_key, 0)\n", + " percent = count / total_q_type_counts * 100 if total_q_type_counts > 0 else 0\n", + " display_name = display_name_map_qtype.get(q_type_key, q_type_key)\n", + " print(f\" - {display_name: <25}: {count:>10,} ({percent:>6.1f}%)\")\n", + "\n", + " total_symbolic_suffix_counts = suffix_counts.get('symbolic_added_equals', 0) + suffix_counts.get('symbolic_no_equals', 0)\n", + " print(\"-\" * 50); print(f\"7. 符号问题格式 - 等号后缀 (总计符号问题: {total_symbolic_suffix_counts:,}):\")\n", + " print(f\" - 添加 ' = ?': {suffix_counts.get('symbolic_added_equals', 0):>10,} ({(suffix_counts.get('symbolic_added_equals', 0) / total_symbolic_suffix_counts * 100) if total_symbolic_suffix_counts > 0 else 0:>6.1f}%)\")\n", + " print(f\" - 未添加后缀: {suffix_counts.get('symbolic_no_equals', 0):>10,} ({(suffix_counts.get('symbolic_no_equals', 0) / total_symbolic_suffix_counts * 100) if total_symbolic_suffix_counts > 0 else 0:>6.1f}%)\")\n", + " print(\"=\"*50)\n", + " else:\n", + " print(\"\\n--- 未生成有效样本,无详细统计 ---\"); print(\"=\"*50)\n", + "\n", + "\n", + "# ===============================================\n", + "# 主程序入口\n", + "# ===============================================\n", + "if __name__ == \"__main__\":\n", + " script_total_start_time = time.time()\n", + " print(\"=\"*30); print(\" 算术题生成脚本 (v10.15 - Independent Word Casing & Digit-by-Digit English) \"); print(\"=\"*30) # Updated print\n", + " \n", + " # Configuration validation\n", + " max_possible_digits_overall = MAX_DIGITS + MAX_DECIMAL_PLACES\n", + " if max_possible_digits_overall <= 0:\n", + " print(\"!!! 配置错误: MAX_DIGITS 和 MAX_DECIMAL_PLACES 必须至少有一个大于0。脚本终止.\"); exit()\n", + "\n", + " # Rough estimate for max possible carries/borrows (can be slightly more complex with decimals)\n", + " max_possible_cb_rough_estimate = MAX_DIGITS + MAX_DECIMAL_PLACES + (1 if MAX_DECIMAL_PLACES > 0 else 0) \n", + " if TARGET_TOTAL_CARRIES_MAX != math.inf and TARGET_TOTAL_CARRIES_MIN > max_possible_cb_rough_estimate:\n", + " print(f\"\\n!!! 配置警告: 目标最小总进/借位数 ({TARGET_TOTAL_CARRIES_MIN}) > 估算的位数上限 ({max_possible_cb_rough_estimate})。可能难以构造或无法构造。 !!!\")\n", + " if TARGET_CONSECUTIVE_CARRIES_MAX != math.inf and TARGET_CONSECUTIVE_CARRIES_MIN > max_possible_cb_rough_estimate:\n", + " print(f\"\\n!!! 配置警告: 目标最小连续进/借位数 ({TARGET_CONSECUTIVE_CARRIES_MIN}) > 估算的位数上限 ({max_possible_cb_rough_estimate})。可能难以构造或无法构造。 !!!\")\n", + " if TARGET_TOTAL_CARRIES_MAX != 0 and TARGET_CONSECUTIVE_CARRIES_MIN > TARGET_TOTAL_CARRIES_MIN : # Max can be 0 if min is also 0\n", + " print(f\"\\n!!! 配置提示: 目标最小连续数 ({TARGET_CONSECUTIVE_CARRIES_MIN}) 大于目标最小总数 ({TARGET_TOTAL_CARRIES_MIN})。\")\n", + "\n", + " try:\n", + " generate_constructed_arithmetic_diverse(\n", + " filename=OUTPUT_FILENAME,\n", + " total_samples=TOTAL_SAMPLES,\n", + " add_prob=ADD_PROBABILITY,\n", + " decimal_prob=DECIMAL_PROBABILITY,\n", + " max_digits_limit=MAX_DIGITS,\n", + " max_decimal_places_cfg=MAX_DECIMAL_PLACES,\n", + " negative_pool_prob=NEGATIVE_POOL_PROB,\n", + " target_total_cb_min=TARGET_TOTAL_CARRIES_MIN,\n", + " target_total_cb_max=TARGET_TOTAL_CARRIES_MAX,\n", + " target_consecutive_cb_min=TARGET_CONSECUTIVE_CARRIES_MIN,\n", + " target_consecutive_cb_max=TARGET_CONSECUTIVE_CARRIES_MAX,\n", + " nl_question_prob=NL_QUESTION_PROBABILITY,\n", + " symbolic_equals_suffix_prob=SYMBOLIC_EQUALS_SUFFIX_PROB,\n", + " max_attempts_factor=MAX_ATTEMPTS_FACTOR,\n", + " batch_save_size=BATCH_SAVE_SIZE,\n", + " apply_general_char_corr=APPLY_GENERAL_CHAR_REPLACEMENT,\n", + " general_char_corr_prob=GENERAL_CHAR_REPLACEMENT_PROBABILITY,\n", + " general_char_corr_pool=GENERAL_CHAR_REPLACEMENT_POOL\n", + " )\n", + " except ValueError as val_err: # Config or value errors during setup or runtime\n", + " print(f\"\\n配置或值错误: {val_err}\"); traceback.print_exc()\n", + " except MemoryError: # If dealing with very large batches or samples\n", + " print(\"\\n内存错误: 尝试减少 BATCH_SAVE_SIZE 或 TOTAL_SAMPLES。\"); traceback.print_exc()\n", + " except Exception as main_exec_err: # Other unhandled exceptions from the main function\n", + " print(f\"\\n主程序发生未预料错误: {main_exec_err}\"); traceback.print_exc()\n", + " finally:\n", + " pass # Cleanup if any needed in future\n", + "\n", + " script_total_end_time = time.time()\n", + " print(\"\\n\" + \"=\"*30);\n", + " print(f\"脚本执行完毕。总耗时: {script_total_end_time - script_total_start_time:.2f} 秒。\");\n", + " print(f\"数据文件: {OUTPUT_FILENAME}\");\n", + " print(\"=\"*30)" + ] + }, + { + "cell_type": "markdown", + "id": "1b283d28", + "metadata": {}, + "source": [ + "# 英文+自然语言描述\n", + "\n", + "用于生成:\n", + "\n", + "训练集:ADD_en_by-desc\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0e72faf2", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "==============================\n", + " Arithmetic Problem Generation Script (v10.17) \n", + "==============================\n", + "--- 开始生成算术数据 (v10.17 - Descriptive Statement Questions) ---\n", + "Question type probs: Symbolic: 70.0%, Interrogative NL: 15.0%, Descriptive Stmt: 15.0%\n", + "已初始化/清空输出文件: 'qa_add_英文自然语言描述.jsonl'\n", + "\n", + "开始构造 500,000 条满足条件的数据...\n", + "Gen: 500,000/500,000 | Attempt: 500,000 | Fail%: 0.0% | Rate: 7312.0/s \n", + "Loop ended. Target: 500,000, Generated: 500,000 (Attempts: 500,000, Construct Fails: 0).\n", + "No remaining data to write.\n", + "\n", + "Generation complete. Target: 500,000 -> Generated: 500,000 -> Written: 500,000\n", + "Total time: 68.38s. In-loop errors: 0.\n", + "\n", + "=============== Detailed Statistics ===============\n", + "Total valid samples: 500,000\n", + "--------------------------------------------------\n", + "1. Arithmetic Operation Type:\n", + " - Addition: 250,128 ( 50.0%)\n", + " - Subtraction: 249,872 ( 50.0%)\n", + "--------------------------------------------------\n", + "2. Operand Type (based on intent or actual values):\n", + " - Integer operations: 299,597 ( 59.9%)\n", + " - Decimal operations: 200,403 ( 40.1%)\n", + "--------------------------------------------------\n", + "3. Number Format - Operand A (Total: 500,000):\n", + " - standard : 127,614 ( 25.5%)\n", + " - full_width : 127,347 ( 25.5%)\n", + " - english_words : 245,039 ( 49.0%)\n", + "--------------------------------------------------\n", + "4. Number Format - Operand B (Total: 500,000):\n", + " - standard : 127,474 ( 25.5%)\n", + " - full_width : 127,778 ( 25.6%)\n", + " - english_words : 244,748 ( 48.9%)\n", + "--------------------------------------------------\n", + "5. Operator Format (Symbolic/Descriptive) (Total: 425,403):\n", + " - Symbol (+, -): 245,509 ( 57.7%)\n", + " - English word: 179,894 ( 42.3%)\n", + "--------------------------------------------------\n", + "6. Question Format - Type (Total: 500,000):\n", + " - Symbolic (+/-/words) : 350,340 ( 70.1%)\n", + " - Interrogative NL (What is..) : 74,597 ( 14.9%)\n", + " - Descriptive Statement (X plus Y.): 75,063 ( 15.0%)\n", + "--------------------------------------------------\n", + "7. Symbolic Question Suffix (Total Symbolic: 350,340):\n", + " - With ' = ?': 174,088 ( 49.7%)\n", + " - No suffix: 176,252 ( 50.3%)\n", + "==================================================\n", + "\n", + "==============================\n", + "Script finished. Total time: 68.38s.\n", + "Output file: qa_add_英文自然语言描述.jsonl\n", + "==============================\n" + ] + } + ], + "source": [ + "# -*- coding: utf-8 -*-\n", + "# 生成满足指定进/借位范围条件,且问题格式多样化的算术问题数据集脚本。\n", + "# 采用反向逐位构造方法优化生成效率。\n", + "# v10.17: Added descriptive statement question format (e.g., \"One plus two.\").\n", + "\n", + "import json\n", + "import random\n", + "import time\n", + "import math\n", + "from typing import List, Tuple, Union, Dict, Optional, Callable\n", + "from decimal import Decimal, getcontext, ROUND_DOWN, ROUND_HALF_UP, InvalidOperation\n", + "import traceback\n", + "from collections import Counter\n", + "import string\n", + "\n", + "# ===============================================\n", + "# 配置参数区域\n", + "# ===============================================\n", + "# --- 主要数量和文件名 ---\n", + "TOTAL_SAMPLES = 500000\n", + "OUTPUT_FILENAME = f\"ADD_en_by-desc.jsonl\"\n", + "ADD_PROBABILITY: float = 0.5\n", + "BATCH_SAVE_SIZE: int = 20\n", + "\n", + "# --- 数字生成控制 ---\n", + "MAX_DIGITS: int = 12\n", + "MAX_DECIMAL_PLACES: int = 5\n", + "DECIMAL_PROBABILITY: float = 0.4\n", + "NEGATIVE_POOL_PROB: float = 0.1\n", + "SCI_THRESHOLD_POS = 10**70\n", + "SCI_THRESHOLD_NEG = -60\n", + "\n", + "# --- 进/借位条件范围 ---\n", + "TARGET_TOTAL_CARRIES_MIN: int = 0\n", + "TARGET_TOTAL_CARRIES_MAX: int = math.inf\n", + "TARGET_CONSECUTIVE_CARRIES_MIN: int = 0\n", + "TARGET_CONSECUTIVE_CARRIES_MAX: int = math.inf\n", + "\n", + "# --- 格式化控制 (问题部分数字的样式) ---\n", + "STANDARD_ARABIC_PROB: float = 0.30 \n", + "FULL_WIDTH_ARABIC_PROB: float = 0.30 \n", + "ENGLISH_WORDS_PROB: float = 0.40 \n", + "_format_prob_sum = STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB + ENGLISH_WORDS_PROB\n", + "if not math.isclose(_format_prob_sum, 1.0):\n", + " raise ValueError(f\"数字格式概率总和必须为 1.0,当前为: {_format_prob_sum}\")\n", + "\n", + "# --- English Number Casing Control ---\n", + "ENGLISH_NUMBER_ENTIRE_STRING_CASE_PROB: float = 0.8\n", + "\n", + "# --- Operator Word Control (for symbolic questions using words) ---\n", + "SYMBOLIC_OPERATOR_WORD_PROB: float = 0.3\n", + "\n", + "# --- 字符间随机空格控制 ---\n", + "APPLY_INTRA_CHAR_SPACING: bool = False\n", + "\n", + "# --- Question Type Probabilities ---\n", + "NL_INTERROGATIVE_QUESTION_PROB: float = 0.15 \n", + "DESCRIPTIVE_STATEMENT_QUESTION_PROB: float = 0.15 \n", + "_question_type_prob_sum = NL_INTERROGATIVE_QUESTION_PROB + DESCRIPTIVE_STATEMENT_QUESTION_PROB\n", + "if _question_type_prob_sum > 1.0 or (_question_type_prob_sum > 1.0 and not math.isclose(_question_type_prob_sum, 1.0)) : \n", + " raise ValueError(f\"Sum of NL_INTERROGATIVE_QUESTION_PROB and DESCRIPTIVE_STATEMENT_QUESTION_PROB must be <= 1.0. Current sum: {_question_type_prob_sum}\")\n", + "SYMBOLIC_QUESTION_PROB = 1.0 - _question_type_prob_sum\n", + "\n", + "# --- 等号后缀概率控制 (仅符号问题) ---\n", + "SYMBOLIC_EQUALS_SUFFIX_PROB: float = 0.50\n", + "\n", + "# --- 字符级随机替换控制 (通用,应用于最终文本) ---\n", + "APPLY_GENERAL_CHAR_REPLACEMENT: bool = False\n", + "GENERAL_CHAR_REPLACEMENT_PROBABILITY: float = 0.005\n", + "GENERAL_CHAR_REPLACEMENT_POOL: str = string.ascii_letters + string.digits + \".,?! \"\n", + "\n", + "# --- 其他控制 ---\n", + "MAX_ATTEMPTS_FACTOR = 5000\n", + "\n", + "# ===============================================\n", + "# 核心代码\n", + "# ===============================================\n", + "getcontext().prec = MAX_DIGITS + MAX_DECIMAL_PLACES + 30\n", + "\n", + "_ENGLISH_DIGITS = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"]\n", + "_ENGLISH_TEENS = [\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\n", + "_ENGLISH_TENS = [\"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\n", + "_ENGLISH_LARGE_UNITS = [\"\", \"thousand\", \"million\", \"billion\", \"trillion\", \"quadrillion\", \"quintillion\",\n", + " \"sextillion\", \"septillion\", \"octillion\", \"nonillion\", \"decillion\"]\n", + "\n", + "def integer_to_english_digits_only(num: int) -> str:\n", + " if num == 0: return _ENGLISH_DIGITS[0]\n", + " s_num = str(num); parts = []\n", + " if s_num.startswith('-'): parts.append(\"minus\"); s_num = s_num[1:]\n", + " if not s_num: return \" \".join(parts) if \"minus\" in parts else _ENGLISH_DIGITS[0]\n", + " for digit_char in s_num: parts.append(_ENGLISH_DIGITS[int(digit_char)])\n", + " return \" \".join(parts)\n", + "\n", + "def _num_to_english_chunk(n: int) -> str: \n", + " if not 0 <= n <= 999: return \"\"\n", + " if n == 0: return \"\"\n", + " parts = []\n", + " if n >= 100: parts.append(_ENGLISH_DIGITS[n // 100]); parts.append(\"hundred\"); n %= 100\n", + " if n > 0:\n", + " if 0 < n < 10: parts.append(_ENGLISH_DIGITS[n])\n", + " elif 10 <= n < 20: parts.append(_ENGLISH_TEENS[n - 10])\n", + " else: parts.append(_ENGLISH_TENS[n // 10]); \\\n", + " (parts.append(_ENGLISH_DIGITS[n % 10]) if n % 10 > 0 else None)\n", + " return \" \".join(parts)\n", + "\n", + "def integer_to_english_words(num: int) -> str: \n", + " if num == 0: return _ENGLISH_DIGITS[0]\n", + " if abs(num) > (10**(len(_ENGLISH_LARGE_UNITS) * 3) -1) : return f\"Num too large ({num})\"\n", + " sign = \"minus \" if num < 0 else \"\"; num_abs = abs(num); parts = []; chunk_idx = 0\n", + " if num_abs == 0: return _ENGLISH_DIGITS[0]\n", + " tmp = num_abs\n", + " while tmp > 0:\n", + " if tmp % 1000 != 0:\n", + " chunk = _num_to_english_chunk(tmp % 1000)\n", + " unit = _ENGLISH_LARGE_UNITS[chunk_idx] if chunk_idx > 0 else \"\"\n", + " if unit: parts.append(unit)\n", + " parts.append(chunk)\n", + " tmp //= 1000; chunk_idx += 1\n", + " if chunk_idx >= len(_ENGLISH_LARGE_UNITS) and tmp > 0: return f\"Num too large ({tmp})\"\n", + " return (sign + \" \".join(p for p in reversed(parts) if p).strip()).strip()\n", + "\n", + "def decimal_to_english_words(num: Decimal) -> str:\n", + " if not isinstance(num, Decimal) or not num.is_finite(): return \"Invalid num\"\n", + " if num.is_zero() and num.is_signed(): num = Decimal('0')\n", + " if num.is_zero(): return _ENGLISH_DIGITS[0]\n", + " sign_str = \"minus \" if num < 0 else \"\"; num_abs = abs(num)\n", + " int_part_val = int(num_abs.to_integral_value(rounding=ROUND_DOWN))\n", + " int_words = integer_to_english_digits_only(int_part_val)\n", + " s_num_abs_canon = format_decimal_or_int(num_abs); frac_words = []\n", + " if '.' in s_num_abs_canon:\n", + " _, frac_digits = s_num_abs_canon.split('.', 1)\n", + " if frac_digits:\n", + " for char_digit in frac_digits:\n", + " if char_digit.isdigit(): frac_words.append(_ENGLISH_DIGITS[int(char_digit)])\n", + " final_parts = [sign_str.strip()] if sign_str else []\n", + " final_parts.append(int_words)\n", + " if frac_words: final_parts.append(\"point\"); final_parts.extend(frac_words)\n", + " return \" \".join(p for p in final_parts if p or p == _ENGLISH_DIGITS[0]).strip()\n", + "\n", + "def decimal_to_english_scientific(num: Decimal) -> str:\n", + " if not isinstance(num, Decimal) or not num.is_finite(): return \"Invalid num\"\n", + " if num.is_zero(): return decimal_to_english_words(num)\n", + " parts = []\n", + " try:\n", + " sci_s = \"{:e}\".format(num); coeff_s, exp_s = sci_s.lower().split('e')\n", + " coeff_d, exp_i = Decimal(coeff_s), int(exp_s)\n", + " coeff_en = decimal_to_english_words(coeff_d)\n", + " exp_en = integer_to_english_digits_only(exp_i)\n", + " parts.extend(coeff_en.split())\n", + " parts.extend([\"times\", \"ten\", \"to\", \"the\", \"power\", \"of\"])\n", + " parts.extend(exp_en.split())\n", + " return \" \".join(p for p in parts if p).strip()\n", + " except Exception: return format_decimal_or_int(num)\n", + "\n", + "def _apply_random_word_case_style(word: str) -> str:\n", + " if not word or not any(c.isalpha() for c in word): return word\n", + " choice = random.random()\n", + " if choice < 0.4: return word.lower()\n", + " elif choice < 0.8: return word.upper()\n", + " else: return word.capitalize()\n", + "\n", + "def _apply_independent_word_casing(text: str) -> str:\n", + " if not text or not any(c.isalpha() for c in text): return text\n", + " return \" \".join([_apply_random_word_case_style(w) for w in text.split(' ')])\n", + "\n", + "def _apply_random_case_char_by_char(text: str) -> str:\n", + " if not text or not any(c.isalpha() for c in text): return text\n", + " return \"\".join(random.choice([c.lower(), c.upper()]) if c.isalpha() else c for c in text)\n", + "\n", + "def _apply_random_case_number_style(text: str) -> str:\n", + " if not text or not any(c.isalpha() for c in text): return text\n", + " return _apply_independent_word_casing(text) if random.random() < ENGLISH_NUMBER_ENTIRE_STRING_CASE_PROB else _apply_random_case_char_by_char(text)\n", + "\n", + "def _apply_random_case_operator_style(text: str) -> str:\n", + " if not text or not any(c.isalpha() for c in text): return text\n", + " return _apply_independent_word_casing(text)\n", + "\n", + "half_to_full_map = str.maketrans(\"0123456789.-+\", \"0123456789.-+\")\n", + "def to_full_width(text: str) -> str: return text.translate(half_to_full_map)\n", + "\n", + "def format_decimal_or_int(num: Union[int, Decimal]) -> str:\n", + " try: \n", + " if isinstance(num, int): return str(num)\n", + " if isinstance(num, Decimal):\n", + " if not num.is_finite(): return str(num)\n", + " norm_num = num.normalize()\n", + " if norm_num.is_zero() and norm_num.is_signed(): norm_num = Decimal('0')\n", + " s = norm_num.to_eng_string()\n", + " if '.' in s and all(c == '0' for c in s.split('.', 1)[1]): s = s.split('.', 1)[0]\n", + " if s.startswith('.'): s = '0' + s\n", + " if s.startswith('-.'): s = '-0' + s[1:]\n", + " return s if s else \"0\"\n", + " return str(num)\n", + " except: return str(num) \n", + "\n", + "def _insert_random_intra_char_spacing(text: str) -> str:\n", + " if not text or not APPLY_INTRA_CHAR_SPACING or len(text) <= 1: return text\n", + " return text\n", + "\n", + "def format_number_variant(num: Union[int, Decimal], force_english_words: bool = False) -> Tuple[str, str]:\n", + " try: num_dec = Decimal(str(num)) if not isinstance(num, Decimal) else num\n", + " except InvalidOperation: return str(num), 'standard'\n", + "\n", + " target_format_name = 'english_words' if force_english_words else 'standard' \n", + " if not force_english_words:\n", + " fmt_choice = random.random()\n", + " if fmt_choice < STANDARD_ARABIC_PROB: target_format_name = 'standard'\n", + " elif fmt_choice < STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB: target_format_name = 'full_width'\n", + " else: target_format_name = 'english_words'\n", + "\n", + " def finalize_output(s: str, fmt_name: str) -> Tuple[str, str]:\n", + " return _insert_random_intra_char_spacing(s), fmt_name\n", + "\n", + " try:\n", + " if not num_dec.is_finite(): \n", + " s_non_finite = str(num_dec)\n", + " res_str = to_full_width(s_non_finite) if target_format_name == 'full_width' and not force_english_words else s_non_finite\n", + " actual_fmt = target_format_name if target_format_name != 'english_words' or force_english_words else 'standard'\n", + " return finalize_output(res_str, actual_fmt)\n", + " \n", + " s_arabic = format_decimal_or_int(num_dec)\n", + "\n", + " if target_format_name == 'standard': return finalize_output(s_arabic, 'standard')\n", + " if target_format_name == 'full_width': return finalize_output(to_full_width(s_arabic), 'full_width')\n", + " if target_format_name == 'english_words': \n", + " exponent = num_dec.normalize().adjusted()\n", + " use_sci = (exponent >= math.log10(SCI_THRESHOLD_POS) if SCI_THRESHOLD_POS > 0 else False) or \\\n", + " (exponent <= SCI_THRESHOLD_NEG if SCI_THRESHOLD_NEG != 0 else False)\n", + " raw_en = decimal_to_english_scientific(num_dec) if use_sci else decimal_to_english_words(num_dec)\n", + " if \"Invalid\" in raw_en or \"too large\" in raw_en or not any(c.isalpha() for c in raw_en):\n", + " return finalize_output(s_arabic, 'standard') \n", + " return finalize_output(_apply_random_case_number_style(raw_en), 'english_words')\n", + " return finalize_output(s_arabic, 'standard') \n", + " except Exception: return finalize_output(str(num), 'standard') \n", + "\n", + "def get_realistic_spacing() -> str: \n", + " return random.choices([\"\", \" \", \" \"], weights=[0.8, 0.15, 0.05], k=1)[0]\n", + "\n", + "ENGLISH_OPERATOR_WORDS = {'+': [\"plus\", \"add\", \"and\"], '-': [\"minus\", \"subtract\", \"take away\", \"less\"]}\n", + "\n", + "def format_interrogative_nl_question(fmt_a: str, fmt_b: str, op_sym: str) -> str:\n", + " raw_add = [\"plus\", \"added to\", \"and\", \"combined with\", \"summed with\"]\n", + " raw_sub = [\"minus\", \"subtract\", \"take away\", \"less\", \"deducted by\"]\n", + " res_phrases = [\"equals what\", \"is what\", \"results in what\", \"gives what\", \"what is the total\", \"what is the difference\", \"how much is that\"]\n", + " q_marks = [\"?\", \"\"]\n", + " templates = []\n", + " op_word_cased = op_sym\n", + " if op_sym == '+':\n", + " op_word_cased = _apply_random_case_operator_style(random.choice(raw_add))\n", + " templates.extend([f\"What is {{num_a}} {{op}} {{num_b}}{{q_mark}}\", f\"Calculate {{num_a}} {{op}} {{num_b}}{{q_mark}}\"]) \n", + " elif op_sym == '-':\n", + " op_word_cased = _apply_random_case_operator_style(random.choice(raw_sub))\n", + " templates.extend([f\"What is {{num_a}} {{op}} {{num_b}}{{q_mark}}\", f\"Calculate {{num_a}} {{op}} {{num_b}}{{q_mark}}\"]) \n", + " else: return f\"{fmt_a} {op_sym} {fmt_b}\"\n", + " if not templates: return f\"{fmt_a} {op_sym} {fmt_b} = ?\"\n", + " \n", + " chosen_tmpl = random.choice(templates)\n", + " res_phrase_cased = _apply_random_case_operator_style(random.choice(res_phrases)) \n", + " q_mark_choice = random.choice(q_marks)\n", + " \n", + " try:\n", + " placeholders = {\"num_a\": fmt_a, \"num_b\": fmt_b, \"op\": op_word_cased, \"q_mark\": q_mark_choice, \"res_phrase\": res_phrase_cased}\n", + " args = {k: v for k,v in placeholders.items() if \"{\"+k+\"}\" in chosen_tmpl}\n", + " return ' '.join(chosen_tmpl.format(**args).split())\n", + " except KeyError: return f\"{fmt_a} {op_sym} {fmt_b} = ?\"\n", + "\n", + "def format_descriptive_statement_question(\n", + " num_a_val: Union[int, Decimal],\n", + " num_b_val: Union[int, Decimal],\n", + " operation_symbol: str \n", + ") -> str:\n", + " a_words_cased, _ = format_number_variant(num_a_val, force_english_words=True)\n", + " b_words_cased, _ = format_number_variant(num_b_val, force_english_words=True)\n", + "\n", + " op_word_choices = ENGLISH_OPERATOR_WORDS.get(operation_symbol, [operation_symbol])\n", + " op_word_cased = _apply_random_case_operator_style(random.choice(op_word_choices))\n", + " \n", + " templates = [ f\"{{num_a}} {op_word_cased} {{num_b}}.\" ]\n", + " chosen_template = random.choice(templates)\n", + " statement = chosen_template.format(num_a=a_words_cased, num_b=b_words_cased)\n", + " return ' '.join(statement.split())\n", + "\n", + "def _generate_pair_meeting_cb_criteria(\n", + " target_digits_a: int, target_digits_b: int, sign_a: int, sign_b: int,\n", + " is_decimal: bool, max_decimal_places_config: int, operation_type: str,\n", + " target_total_cb_min: int, target_total_cb_max: Union[int, float],\n", + " target_consecutive_cb_min: int, target_consecutive_cb_max: Union[int, float]\n", + ") -> Optional[Tuple[Union[int, Decimal], Union[int, Decimal]]]:\n", + " num_dp = random.randint(1, max_decimal_places_config) if is_decimal and max_decimal_places_config > 0 else 0\n", + " num_int_digits_a = max(1, target_digits_a); num_int_digits_b = max(1, target_digits_b)\n", + " total_len_a = num_int_digits_a + num_dp; total_len_b = num_int_digits_b + num_dp\n", + " max_total_len = max(total_len_a, total_len_b)\n", + " if max_total_len == 0: max_total_len = 1 if num_dp == 0 else num_dp \n", + "\n", + " effective_op = operation_type\n", + " if operation_type == 'add' and sign_a * sign_b < 0: effective_op = 'subtract'\n", + " elif operation_type == 'subtract' and sign_a * sign_b < 0: effective_op = 'add'\n", + " \n", + " op1_digits_rev, op2_digits_rev = [], []\n", + " carry_in, borrow_in = 0, 0\n", + " current_total_cb, current_consecutive_cb, max_consecutive_achieved = 0, 0, 0\n", + " op1_int_digits_orig, op2_int_digits_orig = num_int_digits_a, num_int_digits_b\n", + " is_unlimited_cb_range = (target_total_cb_min == 0 and target_total_cb_max == math.inf and \\\n", + " target_consecutive_cb_min == 0 and target_consecutive_cb_max == math.inf)\n", + "\n", + " for i in range(max_total_len):\n", + " pos_from_right = i; is_decimal_pos = pos_from_right < num_dp; is_int_pos = not is_decimal_pos\n", + " int_pos_from_right = pos_from_right - num_dp if is_int_pos else -1\n", + " in_op1 = pos_from_right < total_len_a; in_op2 = pos_from_right < total_len_b\n", + " \n", + " is_msd_op1_int = in_op1 and is_int_pos and int_pos_from_right == op1_int_digits_orig - 1\n", + " is_msd_op2_int = in_op2 and is_int_pos and int_pos_from_right == op2_int_digits_orig - 1\n", + "\n", + " min_d1 = (1 if is_msd_op1_int and (op1_int_digits_orig > 0 or (op1_int_digits_orig == 0 and num_dp == 0 and total_len_a == 1)) else 0) if in_op1 else 0\n", + " max_d1 = 9 if in_op1 else 0\n", + " min_d2 = (1 if is_msd_op2_int and (op2_int_digits_orig > 0 or (op2_int_digits_orig == 0 and num_dp == 0 and total_len_b == 1)) else 0) if in_op2 else 0\n", + " max_d2 = 9 if in_op2 else 0\n", + " \n", + " if op1_int_digits_orig == 0 and is_msd_op1_int: min_d1 = 0\n", + " if op2_int_digits_orig == 0 and is_msd_op2_int: min_d2 = 0\n", + " \n", + " target_cb_state = None\n", + " if not is_unlimited_cb_range:\n", + " rem_pos = max_total_len - (i + 1)\n", + " min_tot_needed = max(0, target_total_cb_min - current_total_cb)\n", + " max_tot_allowed = float('inf') if target_total_cb_max == math.inf else target_total_cb_max - current_total_cb\n", + " if max_tot_allowed < 0: return None\n", + " min_cons_needed = max(0, target_consecutive_cb_min - current_consecutive_cb)\n", + " must_gen_cb = (min_tot_needed > rem_pos) or \\\n", + " (min_cons_needed > rem_pos and max_consecutive_achieved < target_consecutive_cb_min and current_consecutive_cb < target_consecutive_cb_min)\n", + " must_avoid_tot = max_tot_allowed < 1\n", + " must_avoid_cons = (target_consecutive_cb_max != math.inf and current_consecutive_cb + 1 > target_consecutive_cb_max)\n", + " must_avoid_cb = must_avoid_tot or must_avoid_cons\n", + " if must_gen_cb and must_avoid_cb: return None\n", + " if must_gen_cb: target_cb_state = True\n", + " elif must_avoid_cb: target_cb_state = False\n", + " else:\n", + " prob = 0.5\n", + " if min_tot_needed > 0: prob += 0.2 * (min_tot_needed / max(1, rem_pos + 1))\n", + " if min_cons_needed > 0 and max_consecutive_achieved < target_consecutive_cb_min: prob += 0.3\n", + " if target_total_cb_max != math.inf and max_tot_allowed <= rem_pos: prob -= 0.2 * (1 - max_tot_allowed / max(1, rem_pos + 1))\n", + " if target_consecutive_cb_max != math.inf and current_consecutive_cb + 1 >= target_consecutive_cb_max and min_cons_needed == 0: prob = 0.1\n", + " target_cb_state = random.random() < max(0.05, min(0.95, prob))\n", + " \n", + " found_pair = False; chosen_d1, chosen_d2 = -1, -1\n", + " shuffled_d1s = list(range(min_d1, max_d1 + 1)); random.shuffle(shuffled_d1s)\n", + " for d1_try in shuffled_d1s:\n", + " valid_d2s_for_d1 = []\n", + " shuffled_d2s = list(range(min_d2, max_d2 + 1)); random.shuffle(shuffled_d2s)\n", + " for d2_try in shuffled_d2s:\n", + " is_cb_generated = ((d1_try + d2_try + carry_in) >= 10) if effective_op == 'add' else ((d1_try - borrow_in - d2_try) < 0)\n", + " matches_target_state = (target_cb_state is None) or (is_cb_generated == target_cb_state)\n", + " next_consecutive = current_consecutive_cb + 1 if is_cb_generated else 0\n", + " consecutive_ok = (target_consecutive_cb_max == math.inf or next_consecutive <= target_consecutive_cb_max)\n", + " min_consecutive_achievable = True\n", + " if not is_cb_generated and target_consecutive_cb_min > 0:\n", + " max_ach_before_reset = max(max_consecutive_achieved, current_consecutive_cb)\n", + " if max_ach_before_reset < target_consecutive_cb_min and rem_pos < target_consecutive_cb_min:\n", + " min_consecutive_achievable = False\n", + " if matches_target_state and consecutive_ok and min_consecutive_achievable:\n", + " valid_d2s_for_d1.append(d2_try)\n", + " if valid_d2s_for_d1:\n", + " chosen_d1, chosen_d2 = d1_try, random.choice(valid_d2s_for_d1); found_pair = True; break\n", + " if not found_pair: return None\n", + " \n", + " op1_digits_rev.append(str(chosen_d1)); op2_digits_rev.append(str(chosen_d2))\n", + " cb_this_pos = False\n", + " if effective_op == 'add':\n", + " current_sum = chosen_d1 + chosen_d2 + carry_in; carry_in = 1 if current_sum >= 10 else 0; borrow_in = 0\n", + " cb_this_pos = (carry_in == 1)\n", + " else: \n", + " current_diff = chosen_d1 - borrow_in - chosen_d2; borrow_in = 1 if current_diff < 0 else 0; carry_in = 0\n", + " cb_this_pos = (borrow_in == 1)\n", + " if cb_this_pos: current_total_cb += 1; current_consecutive_cb += 1\n", + " else: max_consecutive_achieved = max(max_consecutive_achieved, current_consecutive_cb); current_consecutive_cb = 0\n", + " \n", + " max_consecutive_achieved = max(max_consecutive_achieved, current_consecutive_cb)\n", + " if not is_unlimited_cb_range:\n", + " total_ok = (target_total_cb_min <= current_total_cb <= target_total_cb_max)\n", + " consecutive_ok = (max_consecutive_achieved >= target_consecutive_cb_min and \\\n", + " (target_consecutive_cb_max == math.inf or max_consecutive_achieved <= target_consecutive_cb_max))\n", + " if not (total_ok and consecutive_ok): return None\n", + " \n", + " op1_s, op2_s = \"\".join(reversed(op1_digits_rev)), \"\".join(reversed(op2_digits_rev))\n", + "\n", + " def _format_s_to_dec(s_val: str, dp_val: int) -> Decimal: # Corrected internal helper\n", + " if not s_val: s_val = \"0\"\n", + " s_full_val: str\n", + " if dp_val > 0:\n", + " int_len = len(s_val) - dp_val\n", + " s_int_part: str; s_frac_part: str\n", + " if int_len <= 0: \n", + " s_int_part = \"0\"; s_frac_part = s_val.zfill(dp_val)\n", + " else: \n", + " s_int_part = s_val[:int_len]; s_frac_part = s_val[int_len:]\n", + " s_int_part = s_int_part.lstrip('0') or \"0\"\n", + " s_full_val = f\"{s_int_part}.{s_frac_part}\"\n", + " else: \n", + " s_full_val = s_val.lstrip('0') or \"0\"\n", + " return Decimal(s_full_val)\n", + "\n", + " try:\n", + " v1_abs = _format_s_to_dec(op1_s, num_dp)\n", + " v2_abs = _format_s_to_dec(op2_s, num_dp)\n", + " \n", + " av = v1_abs.copy_sign(Decimal(sign_a))\n", + " bv = v2_abs.copy_sign(Decimal(sign_b))\n", + " \n", + " if av.is_zero() and av.is_signed(): av = Decimal('0')\n", + " if bv.is_zero() and bv.is_signed(): bv = Decimal('0')\n", + " \n", + " if not is_decimal and num_dp == 0:\n", + " a_final, b_final = int(av), int(bv)\n", + " else:\n", + " a_final, b_final = av.normalize(), bv.normalize()\n", + " if a_final.is_zero() and a_final.is_signed(): a_final = Decimal('0')\n", + " if b_final.is_zero() and b_final.is_signed(): b_final = Decimal('0')\n", + " return a_final, b_final\n", + " except InvalidOperation: return None\n", + " except Exception: return None\n", + "\n", + "def check_carries_borrows(num1: Decimal, num2: Decimal, operation: str) -> Tuple[int, int]: \n", + " tcb,mcc,ccc=0,0,0\n", + " try:\n", + " n1,n2=num1.normalize(),num2.normalize()\n", + " if n1.is_zero()and n1.is_signed():n1=Decimal('0')\n", + " if n2.is_zero()and n2.is_signed():n2=Decimal('0')\n", + " eff,o1,o2=operation,abs(n1),abs(n2)\n", + " if operation=='add':\n", + " if n1.is_signed()!=n2.is_signed():eff='subtract';o1,o2=(abs(n1),abs(n2))if abs(n1)>=abs(n2)else(abs(n2),abs(n1))\n", + " elif operation=='subtract':\n", + " if n1.is_signed()!=n2.is_signed():eff='add'\n", + " else:o1,o2=(abs(n1),abs(n2))if abs(n1)>=abs(n2)else(abs(n2),abs(n1)) \n", + " else:return -1,-1\n", + " o1,o2=o1.normalize(),o2.normalize() \n", + " if o1.is_zero()and o1.is_signed():o1=Decimal('0')\n", + " if o2.is_zero()and o2.is_signed():o2=Decimal('0')\n", + " if o1.is_zero()and o2.is_zero():return 0,0\n", + " s1,s2=format_decimal_or_int(o1),format_decimal_or_int(o2);s1i,s1f=s1.split('.')if'.'in s1 else(s1,'');s2i,s2f=s2.split('.')if'.'in s2 else(s2,'')\n", + " mf=max(len(s1f),len(s2f));s1f,s2f=s1f.ljust(mf,'0'),s2f.ljust(mf,'0');mi=max(len(s1i),len(s2i));s1i,s2i=s1i.zfill(mi),s2i.zfill(mi)\n", + " a1,a2=s1i+s1f,s2i+s2f;l=len(a1);cy,bw=0,0\n", + " for i in range(l-1,-1,-1):\n", + " d1,d2=int(a1[i]),int(a2[i]);cb=False\n", + " if eff=='add':cs=d1+d2+cy;cy=1 if cs>=10 else 0;cb=(cy==1)\n", + " else:cd=d1-bw-d2;bw=1 if cd<0 else 0;cb=(bw==1)\n", + " if cb:tcb+=1;ccc+=1\n", + " else:mcc=max(mcc,ccc);ccc=0\n", + " mcc=max(mcc,ccc)\n", + " except:return -1,-1\n", + " return tcb,mcc\n", + "\n", + "def write_batch_to_jsonl(buffer: List[Dict], filename: str, mode: str = 'a') -> int: \n", + " if not buffer:return 0\n", + " lns,jsons,errs=0,[],0\n", + " for item in buffer:\n", + " try:\n", + " if not isinstance(item,dict)or not item.get(\"text\"):errs+=1;continue\n", + " js=json.dumps(item,ensure_ascii=False)\n", + " if js and not js.isspace():jsons.append(js)\n", + " else:errs+=1\n", + " except:errs+=1\n", + " if jsons:\n", + " try:\n", + " with open(filename,mode,encoding='utf-8')as f:f.write('\\n'.join(jsons)+'\\n')\n", + " lns=len(jsons)\n", + " except:return 0\n", + " if errs>0:print(f\"\\nWarn: {errs} items failed serialization.\")\n", + " return lns\n", + "\n", + "def randomly_replace_characters_in_string(text: str, prob: float, pool: str) -> str: \n", + " if not text or prob<=0 or not pool:return text\n", + " chars=list(text)\n", + " for i in range(len(chars)):\n", + " if random.random() max_total_attempts:\n", + " print(f\"\\n\\n警告: 尝试次数达到上限. 脚本提前终止.\"); break\n", + " \n", + " try:\n", + " digits_a = get_distributed_count_from_probs(digit_pop, digit_probs_list)\n", + " digits_b = get_distributed_count_from_probs(digit_pop, digit_probs_list)\n", + " sign_a = -1 if random.random() < negative_pool_prob else 1\n", + " sign_b = -1 if random.random() < negative_pool_prob else 1\n", + " is_dec_intent = random.random() < decimal_prob\n", + " op_type = 'add' if random.random() < add_prob else 'subtract'\n", + " op_sym = '+' if op_type == 'add' else '-'\n", + "\n", + " constructed_pair = _generate_pair_meeting_cb_criteria(\n", + " digits_a, digits_b, sign_a, sign_b, is_dec_intent, max_decimal_places_cfg,\n", + " op_type, target_total_cb_min, target_total_cb_max,\n", + " target_consecutive_cb_min, target_consecutive_cb_max)\n", + "\n", + " if constructed_pair is None: construct_failures += 1; continue\n", + " a_orig, b_orig = constructed_pair\n", + "\n", + " c_final_val: Union[int, Decimal]; answer_s = \"\"\n", + " try: \n", + " a_calc,b_calc=Decimal(str(a_orig)),Decimal(str(b_orig));c_calc=a_calc+b_calc if op_type=='add'else a_calc-b_calc\n", + " if not c_calc.is_finite():errors_in_loop+=1;continue\n", + " dp_a=abs(a_calc.as_tuple().exponent)if isinstance(a_calc,Decimal)and a_calc.as_tuple().exponent<0 else 0\n", + " dp_b=abs(b_calc.as_tuple().exponent)if isinstance(b_calc,Decimal)and b_calc.as_tuple().exponent<0 else 0\n", + " res_dp=min(max(dp_a,dp_b)if is_dec_intent or dp_a>0 or dp_b>0 else 0,max_decimal_places_cfg)\n", + " c_q=c_calc.quantize(Decimal('1e-'+str(res_dp)),ROUND_HALF_UP)if res_dp>0 else c_calc.to_integral_value(ROUND_HALF_UP);c_n=c_q.normalize()\n", + " if c_n.is_zero()and c_n.is_signed():c_n=Decimal('0')\n", + " is_a_int=isinstance(a_orig,int)or(isinstance(a_orig,Decimal)and a_orig==a_orig.to_integral_value())\n", + " is_b_int=isinstance(b_orig,int)or(isinstance(b_orig,Decimal)and b_orig==b_orig.to_integral_value())\n", + " c_final_val=int(c_n)if(c_n==c_n.to_integral_value())and is_a_int and is_b_int and not is_dec_intent else c_n\n", + " answer_s=format_decimal_or_int(c_final_val)\n", + " except: errors_in_loop += 1; continue\n", + " if not answer_s: errors_in_loop += 1; continue\n", + "\n", + " q_str = \"\"\n", + " question_style_choice = random.random()\n", + " \n", + " a_for_q, b_for_q = a_orig, b_orig\n", + " final_op_q_sym_for_non_descriptive = op_sym\n", + " \n", + " b_dec_check = Decimal(str(b_orig))\n", + " if b_dec_check.is_signed() and b_dec_check < 0:\n", + " b_for_q = abs(b_dec_check) \n", + " if op_sym == '+': final_op_q_sym_for_non_descriptive = '-'\n", + " elif op_sym == '-': final_op_q_sym_for_non_descriptive = '+'\n", + "\n", + " if question_style_choice < DESCRIPTIVE_STATEMENT_QUESTION_PROB:\n", + " question_type_counts['descriptive_statement'] += 1\n", + " q_str = format_descriptive_statement_question(a_orig, b_orig, op_sym)\n", + " format_counts['a_english_words'] += 1 \n", + " format_counts['b_english_words'] += 1\n", + " format_counts['operator_word'] += 1\n", + " elif question_style_choice < DESCRIPTIVE_STATEMENT_QUESTION_PROB + NL_INTERROGATIVE_QUESTION_PROB:\n", + " question_type_counts['interrogative_nl'] += 1\n", + " fmt_a_str, fmt_a_type = format_number_variant(a_for_q)\n", + " fmt_b_str, fmt_b_type = format_number_variant(b_for_q)\n", + " if not fmt_a_str or not fmt_b_str: errors_in_loop +=1; continue\n", + " format_counts[f'a_{fmt_a_type}'] += 1; format_counts[f'b_{fmt_b_type}'] += 1\n", + " q_str = format_interrogative_nl_question(fmt_a_str, fmt_b_str, final_op_q_sym_for_non_descriptive)\n", + " else: \n", + " question_type_counts['symbolic'] += 1\n", + " fmt_a_str, fmt_a_type = format_number_variant(a_for_q)\n", + " fmt_b_str, fmt_b_type = format_number_variant(b_for_q)\n", + " if not fmt_a_str or not fmt_b_str: errors_in_loop +=1; continue\n", + " format_counts[f'a_{fmt_a_type}'] += 1; format_counts[f'b_{fmt_b_type}'] += 1\n", + "\n", + " disp_op_sym = final_op_q_sym_for_non_descriptive\n", + " if random.random() < SYMBOLIC_OPERATOR_WORD_PROB: \n", + " if final_op_q_sym_for_non_descriptive in ENGLISH_OPERATOR_WORDS:\n", + " disp_op_sym = _apply_random_case_operator_style(random.choice(ENGLISH_OPERATOR_WORDS[final_op_q_sym_for_non_descriptive]))\n", + " format_counts['operator_word'] += 1\n", + " else: format_counts['operator_symbol'] += 1\n", + " else: format_counts['operator_symbol'] += 1\n", + " \n", + " sp1, sp2 = get_realistic_spacing(), get_realistic_spacing()\n", + " q_base = f\"{fmt_a_str}{sp1}{disp_op_sym}{sp2}{fmt_b_str}\"\n", + " suffix = \"\"; added_sfx = False\n", + " if random.random() < symbolic_equals_suffix_prob:\n", + " q_mark = random.choice([\"?\", \"\"]); sp_eq1, sp_eq2 = get_realistic_spacing(), get_realistic_spacing()\n", + " suffix = f\"{sp_eq1}={sp_eq2}{q_mark}\"; added_sfx = True\n", + " suffix_counts['symbolic_added_equals' if added_sfx else 'symbolic_no_equals'] += 1\n", + " q_str = q_base + suffix\n", + "\n", + " if not q_str or q_str.isspace(): errors_in_loop += 1; continue\n", + " \n", + " text_content = f\"User: {q_str}\\n\\nAssistant: {answer_s}\"\n", + " if apply_general_char_corr:\n", + " text_content = randomly_replace_characters_in_string(text_content, general_char_corr_prob, general_char_corr_pool)\n", + " \n", + " pair_data = {\"text\": text_content} \n", + " output_buffer.append(pair_data)\n", + " generated_count += 1\n", + "\n", + " if op_type == 'add': add_count += 1; \n", + " else: subtract_count += 1\n", + " is_a_dec_val=isinstance(a_orig,Decimal)and a_orig!=a_orig.to_integral_value();is_b_dec_val=isinstance(b_orig,Decimal)and b_orig!=b_orig.to_integral_value();is_c_dec_val=isinstance(c_final_val,Decimal)and c_final_val!=c_final_val.to_integral_value()\n", + " if is_dec_intent or is_a_dec_val or is_b_dec_val or is_c_dec_val: decimal_op_count += 1\n", + " else: integer_op_count += 1\n", + "\n", + "\n", + " if len(output_buffer) >= batch_save_size: \n", + " written_batch = write_batch_to_jsonl(output_buffer, filename, mode='a')\n", + " if written_batch > 0: total_lines_written += written_batch; output_buffer.clear(); last_save_time = time.time()\n", + " else: print(f\"\\nWarn: Batch write failed.\"); errors_in_loop += len(output_buffer); output_buffer.clear()\n", + "\n", + " except KeyboardInterrupt: print(\"\\nUser interrupted.\"); break\n", + " except Exception as e_outer: errors_in_loop += 1; # traceback.print_exc() \n", + " \n", + " current_t = time.time() \n", + " if generated_count > 0 and (generated_count % max(1, total_samples // 100) == 0 or current_t - last_save_time > 15):\n", + " if last_reported_count != generated_count:\n", + " elapsed = current_t - start_time; rate = generated_count / elapsed if elapsed > 0 else 0\n", + " print(f\"\\rGen: {generated_count:,}/{total_samples:,} | Attempt: {total_attempts:,} | Fail%: {construct_failures/total_attempts if total_attempts else 0:.1%} | Rate: {rate:.1f}/s \", end=\"\")\n", + " last_reported_count = generated_count; \n", + "\n", + " print(\" \" * 120, end=\"\\r\") \n", + " print(f\"\\nLoop ended. Target: {total_samples:,}, Generated: {generated_count:,} (Attempts: {total_attempts:,}, Construct Fails: {construct_failures:,}).\")\n", + " if output_buffer: \n", + " final_written = write_batch_to_jsonl(output_buffer, filename, mode='a')\n", + " if final_written > 0: total_lines_written += final_written; print(f\"Final batch written ({final_written:,}).\")\n", + " else: print(\"Warn: Final batch write failed.\"); errors_in_loop += len(output_buffer)\n", + " else: print(\"No remaining data to write.\")\n", + " \n", + " total_duration = time.time() - start_time\n", + " print(f\"\\nGeneration complete. Target: {total_samples:,} -> Generated: {generated_count:,} -> Written: {total_lines_written:,}\")\n", + " if total_lines_written != generated_count and generated_count > 0: print(f\"WARN: Written lines mismatch generated lines!\")\n", + " print(f\"Total time: {total_duration:.2f}s. In-loop errors: {errors_in_loop:,}.\")\n", + "\n", + " print(\"\\n\" + \"=\"*15 + \" Detailed Statistics \" + \"=\"*15)\n", + " if generated_count > 0:\n", + " print(f\"Total valid samples: {generated_count:,}\")\n", + " print(\"-\" * 50); print(\"1. Arithmetic Operation Type:\");\n", + " print(f\" - Addition: {add_count:>10,} ({add_count/generated_count*100:>6.1f}%)\")\n", + " print(f\" - Subtraction: {subtract_count:>10,} ({subtract_count/generated_count*100:>6.1f}%)\")\n", + " \n", + " print(\"-\" * 50); print(\"2. Operand Type (based on intent or actual values):\");\n", + " print(f\" - Integer operations: {integer_op_count:>10,} ({integer_op_count/generated_count*100:>6.1f}%)\")\n", + " print(f\" - Decimal operations: {decimal_op_count:>10,} ({decimal_op_count/generated_count*100:>6.1f}%)\")\n", + "\n", + " total_fmt_a_counts = sum(format_counts[k] for k in format_counts if k.startswith('a_'))\n", + " print(\"-\" * 50); print(f\"3. Number Format - Operand A (Total: {total_fmt_a_counts:,}):\")\n", + " for fmt_key in ['a_standard', 'a_full_width', 'a_english_words']:\n", + " print(f\" - {fmt_key[2:]: <15}: {format_counts.get(fmt_key, 0):>10,} ({(format_counts.get(fmt_key, 0) / total_fmt_a_counts * 100) if total_fmt_a_counts > 0 else 0:>6.1f}%)\")\n", + " \n", + " total_fmt_b_counts = sum(format_counts[k] for k in format_counts if k.startswith('b_'))\n", + " print(\"-\" * 50); print(f\"4. Number Format - Operand B (Total: {total_fmt_b_counts:,}):\")\n", + " for fmt_key in ['b_standard', 'b_full_width', 'b_english_words']:\n", + " print(f\" - {fmt_key[2:]: <15}: {format_counts.get(fmt_key, 0):>10,} ({(format_counts.get(fmt_key, 0) / total_fmt_b_counts * 100) if total_fmt_b_counts > 0 else 0:>6.1f}%)\")\n", + "\n", + " total_op_fmt_counts = format_counts.get('operator_word', 0) + format_counts.get('operator_symbol', 0)\n", + " print(\"-\" * 50); print(f\"5. Operator Format (Symbolic/Descriptive) (Total: {total_op_fmt_counts:,}):\")\n", + " print(f\" - Symbol (+, -): {format_counts.get('operator_symbol', 0):>10,} ({(format_counts.get('operator_symbol', 0) / total_op_fmt_counts * 100) if total_op_fmt_counts > 0 else 0:>6.1f}%)\")\n", + " print(f\" - English word: {format_counts.get('operator_word', 0):>10,} ({(format_counts.get('operator_word', 0) / total_op_fmt_counts * 100) if total_op_fmt_counts > 0 else 0:>6.1f}%)\")\n", + "\n", + " total_q_type_counts = sum(question_type_counts.values())\n", + " print(\"-\" * 50); print(f\"6. Question Format - Type (Total: {total_q_type_counts:,}):\")\n", + " q_type_map = {\n", + " 'symbolic': 'Symbolic (+/-/words)',\n", + " 'interrogative_nl': 'Interrogative NL (What is..)',\n", + " 'descriptive_statement': 'Descriptive Statement (X plus Y.)'\n", + " }\n", + " for q_key, q_disp_name in q_type_map.items():\n", + " count = question_type_counts.get(q_key, 0)\n", + " percent = count / total_q_type_counts * 100 if total_q_type_counts > 0 else 0\n", + " print(f\" - {q_disp_name:<30}: {count:>10,} ({percent:>6.1f}%)\")\n", + " \n", + " total_sym_suffix_counts = suffix_counts.get('symbolic_added_equals', 0) + suffix_counts.get('symbolic_no_equals', 0)\n", + " print(\"-\" * 50); print(f\"7. Symbolic Question Suffix (Total Symbolic: {total_sym_suffix_counts:,}):\")\n", + " print(f\" - With ' = ?': {suffix_counts.get('symbolic_added_equals', 0):>10,} ({(suffix_counts.get('symbolic_added_equals', 0) / total_sym_suffix_counts * 100) if total_sym_suffix_counts > 0 else 0:>6.1f}%)\")\n", + " print(f\" - No suffix: {suffix_counts.get('symbolic_no_equals', 0):>10,} ({(suffix_counts.get('symbolic_no_equals', 0) / total_sym_suffix_counts * 100) if total_sym_suffix_counts > 0 else 0:>6.1f}%)\")\n", + "\n", + " else: print(\"\\n--- No valid samples generated, no detailed stats ---\")\n", + " print(\"=\"*50)\n", + "\n", + "if __name__ == \"__main__\":\n", + " script_start_time = time.time()\n", + " print(\"=\"*30); print(\" Arithmetic Problem Generation Script (v10.17) \"); print(\"=\"*30)\n", + " try:\n", + " generate_constructed_arithmetic_diverse(\n", + " filename=OUTPUT_FILENAME, total_samples=TOTAL_SAMPLES, add_prob=ADD_PROBABILITY,\n", + " decimal_prob=DECIMAL_PROBABILITY, max_digits_limit=MAX_DIGITS,\n", + " max_decimal_places_cfg=MAX_DECIMAL_PLACES, negative_pool_prob=NEGATIVE_POOL_PROB,\n", + " target_total_cb_min=TARGET_TOTAL_CARRIES_MIN, target_total_cb_max=TARGET_TOTAL_CARRIES_MAX,\n", + " target_consecutive_cb_min=TARGET_CONSECUTIVE_CARRIES_MIN, target_consecutive_cb_max=TARGET_CONSECUTIVE_CARRIES_MAX,\n", + " symbolic_equals_suffix_prob=SYMBOLIC_EQUALS_SUFFIX_PROB,\n", + " max_attempts_factor=MAX_ATTEMPTS_FACTOR, batch_save_size=BATCH_SAVE_SIZE,\n", + " apply_general_char_corr=APPLY_GENERAL_CHAR_REPLACEMENT,\n", + " general_char_corr_prob=GENERAL_CHAR_REPLACEMENT_PROBABILITY,\n", + " general_char_corr_pool=GENERAL_CHAR_REPLACEMENT_POOL\n", + " )\n", + " except ValueError as ve: print(f\"\\nConfig/Value Error: {ve}\"); traceback.print_exc()\n", + " except MemoryError: print(\"\\nMemory Error.\"); traceback.print_exc()\n", + " except Exception as e: print(f\"\\nMain execution error: {e}\"); traceback.print_exc()\n", + " \n", + " script_end_time = time.time()\n", + " print(\"\\n\" + \"=\"*30); print(f\"Script finished. Total time: {script_end_time - script_start_time:.2f}s.\"); print(f\"Output file: {OUTPUT_FILENAME}\"); print(\"=\"*30)" + ] + }, + { + "cell_type": "markdown", + "id": "9aa6afd4", + "metadata": {}, + "source": [ + "# 检测jsonl是否有科学计数法\n", + "\n", + "有则删除整行\n", + "\n", + "因为环境和 Python 的配置问题,无法在代码中确保完全无科学计数法,因此选择生成后删除含科学技术法的行\n" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "e70e43c5", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "开始在目录 '../Test' 中处理所有 .jsonl 文件...\n", + "\n", + "找到 18 个 .jsonl 文件准备处理。\n", + "\n", + "--- 开始处理文件: qa_add-逐位随机—中英混合-test.jsonl ---\n", + " 处理完成 500 行。\n", + " 统计: 共处理 500 行, 删除 0 行 (User或Assistant含科学计数法), 格式跳过 0 行, 错误 0 行。\n", + " 正在用处理后的文件替换原文件 'qa_add-逐位随机—中英混合-test.jsonl'...\n", + " 文件 'qa_add-逐位随机—中英混合-test.jsonl' 替换成功。\n", + "--- 文件处理完毕: qa_add-逐位随机—中英混合-test.jsonl ---\n", + "\n", + "--- 开始处理文件: qa_add_base_EN-test.jsonl ---\n", + " 处理完成 500 行。\n", + " 统计: 共处理 500 行, 删除 0 行 (User或Assistant含科学计数法), 格式跳过 0 行, 错误 0 行。\n", + " 正在用处理后的文件替换原文件 'qa_add_base_EN-test.jsonl'...\n", + " 文件 'qa_add_base_EN-test.jsonl' 替换成功。\n", + "--- 文件处理完毕: qa_add_base_EN-test.jsonl ---\n", + "\n", + "--- 开始处理文件: qa_add_int_many0-50-test.jsonl ---\n", + " 处理完成 50 行。\n", + " 统计: 共处理 50 行, 删除 0 行 (User或Assistant含科学计数法), 格式跳过 0 行, 错误 0 行。\n", + " 正在用处理后的文件替换原文件 'qa_add_int_many0-50-test.jsonl'...\n", + " 文件 'qa_add_int_many0-50-test.jsonl' 替换成功。\n", + "--- 文件处理完毕: qa_add_int_many0-50-test.jsonl ---\n", + "\n", + "--- 开始处理文件: qa_add_n0m0-test.jsonl ---\n", + " 处理完成 500 行。\n", + " 统计: 共处理 500 行, 删除 1 行 (User或Assistant含科学计数法), 格式跳过 0 行, 错误 0 行。\n", + " 正在用处理后的文件替换原文件 'qa_add_n0m0-test.jsonl'...\n", + " 文件 'qa_add_n0m0-test.jsonl' 替换成功。\n", + "--- 文件处理完毕: qa_add_n0m0-test.jsonl ---\n", + "\n", + "--- 开始处理文件: qa_add_n0m0-test_20250513.jsonl ---\n", + " 处理完成 500 行。\n", + " 统计: 共处理 500 行, 删除 0 行 (User或Assistant含科学计数法), 格式跳过 500 行, 错误 0 行。\n", + " 正在用处理后的文件替换原文件 'qa_add_n0m0-test_20250513.jsonl'...\n", + " 文件 'qa_add_n0m0-test_20250513.jsonl' 替换成功。\n", + " 注意: 文件 'qa_add_n0m0-test_20250513.jsonl' 中有 500 行因问题被按原样保留。\n", + "--- 文件处理完毕: qa_add_n0m0-test_20250513.jsonl ---\n", + "\n", + "--- 开始处理文件: qa_add_only-int-500.jsonl ---\n", + " 处理完成 500 行。\n", + " 统计: 共处理 500 行, 删除 0 行 (User或Assistant含科学计数法), 格式跳过 0 行, 错误 0 行。\n", + " 正在用处理后的文件替换原文件 'qa_add_only-int-500.jsonl'...\n", + " 文件 'qa_add_only-int-500.jsonl' 替换成功。\n", + "--- 文件处理完毕: qa_add_only-int-500.jsonl ---\n", + "\n", + "--- 开始处理文件: qa_add_random_n10m0_test.jsonl ---\n", + " 处理完成 461 行。\n", + " 统计: 共处理 461 行, 删除 0 行 (User或Assistant含科学计数法), 格式跳过 0 行, 错误 0 行。\n", + " 正在用处理后的文件替换原文件 'qa_add_random_n10m0_test.jsonl'...\n", + " 文件 'qa_add_random_n10m0_test.jsonl' 替换成功。\n", + "--- 文件处理完毕: qa_add_random_n10m0_test.jsonl ---\n", + "\n", + "--- 开始处理文件: qa_add_random_n7m3_test.jsonl ---\n", + " 处理完成 463 行。\n", + " 统计: 共处理 463 行, 删除 0 行 (User或Assistant含科学计数法), 格式跳过 0 行, 错误 0 行。\n", + " 正在用处理后的文件替换原文件 'qa_add_random_n7m3_test.jsonl'...\n", + " 文件 'qa_add_random_n7m3_test.jsonl' 替换成功。\n", + "--- 文件处理完毕: qa_add_random_n7m3_test.jsonl ---\n", + "\n", + "--- 开始处理文件: qa_add_直译为英文-test.jsonl ---\n", + " 处理完成 500 行。\n", + " 统计: 共处理 500 行, 删除 9 行 (User或Assistant含科学计数法), 格式跳过 0 行, 错误 0 行。\n", + " 正在用处理后的文件替换原文件 'qa_add_直译为英文-test.jsonl'...\n", + " 文件 'qa_add_直译为英文-test.jsonl' 替换成功。\n", + "--- 文件处理完毕: qa_add_直译为英文-test.jsonl ---\n", + "\n", + "--- 开始处理文件: qa_add_英文大小写混合-test.jsonl ---\n", + " 处理完成 500 行。\n", + " 统计: 共处理 500 行, 删除 12 行 (User或Assistant含科学计数法), 格式跳过 0 行, 错误 0 行。\n", + " 正在用处理后的文件替换原文件 'qa_add_英文大小写混合-test.jsonl'...\n", + " 文件 'qa_add_英文大小写混合-test.jsonl' 替换成功。\n", + "--- 文件处理完毕: qa_add_英文大小写混合-test.jsonl ---\n", + "\n", + "--- 开始处理文件: qa_add_解方程-test.jsonl ---\n", + " 处理完成 500 行。\n", + " 统计: 共处理 500 行, 删除 0 行 (User或Assistant含科学计数法), 格式跳过 0 行, 错误 0 行。\n", + " 正在用处理后的文件替换原文件 'qa_add_解方程-test.jsonl'...\n", + " 文件 'qa_add_解方程-test.jsonl' 替换成功。\n", + "--- 文件处理完毕: qa_add_解方程-test.jsonl ---\n", + "\n", + "--- 开始处理文件: qa_add_解方程-test_char_mixed_eng.jsonl ---\n", + " 处理完成 500 行。\n", + " 统计: 共处理 500 行, 删除 0 行 (User或Assistant含科学计数法), 格式跳过 0 行, 错误 0 行。\n", + " 正在用处理后的文件替换原文件 'qa_add_解方程-test_char_mixed_eng.jsonl'...\n", + " 文件 'qa_add_解方程-test_char_mixed_eng.jsonl' 替换成功。\n", + "--- 文件处理完毕: qa_add_解方程-test_char_mixed_eng.jsonl ---\n", + "\n", + "--- 开始处理文件: qa_add_逐位随机-test.jsonl ---\n", + " 处理完成 1,000 行。\n", + " 统计: 共处理 1,000 行, 删除 0 行 (User或Assistant含科学计数法), 格式跳过 0 行, 错误 0 行。\n", + " 正在用处理后的文件替换原文件 'qa_add_逐位随机-test.jsonl'...\n", + " 文件 'qa_add_逐位随机-test.jsonl' 替换成功。\n", + "--- 文件处理完毕: qa_add_逐位随机-test.jsonl ---\n", + "\n", + "--- 开始处理文件: qa_add_逐位随机_解方程-test.jsonl ---\n", + " 处理完成 500 行。\n", + " 统计: 共处理 500 行, 删除 0 行 (User或Assistant含科学计数法), 格式跳过 0 行, 错误 0 行。\n", + " 正在用处理后的文件替换原文件 'qa_add_逐位随机_解方程-test.jsonl'...\n", + " 文件 'qa_add_逐位随机_解方程-test.jsonl' 替换成功。\n", + "--- 文件处理完毕: qa_add_逐位随机_解方程-test.jsonl ---\n", + "\n", + "--- 开始处理文件: qa_gibberish_unanswerable-test.jsonl ---\n", + " 处理完成 100 行。\n", + " 统计: 共处理 100 行, 删除 0 行 (User或Assistant含科学计数法), 格式跳过 0 行, 错误 0 行。\n", + " 正在用处理后的文件替换原文件 'qa_gibberish_unanswerable-test.jsonl'...\n", + " 文件 'qa_gibberish_unanswerable-test.jsonl' 替换成功。\n", + "--- 文件处理完毕: qa_gibberish_unanswerable-test.jsonl ---\n", + "\n", + "--- 开始处理文件: qa_解方程_en-test.jsonl ---\n", + " 处理完成 500 行。\n", + " 统计: 共处理 500 行, 删除 0 行 (User或Assistant含科学计数法), 格式跳过 0 行, 错误 0 行。\n", + " 正在用处理后的文件替换原文件 'qa_解方程_en-test.jsonl'...\n", + " 文件 'qa_解方程_en-test.jsonl' 替换成功。\n", + "--- 文件处理完毕: qa_解方程_en-test.jsonl ---\n", + "\n", + "--- 开始处理文件: qa_解方程_en-test_20250513.jsonl ---\n", + " 处理完成 58 行。\n", + " 统计: 共处理 58 行, 删除 0 行 (User或Assistant含科学计数法), 格式跳过 58 行, 错误 0 行。\n", + " 正在用处理后的文件替换原文件 'qa_解方程_en-test_20250513.jsonl'...\n", + " 文件 'qa_解方程_en-test_20250513.jsonl' 替换成功。\n", + " 注意: 文件 'qa_解方程_en-test_20250513.jsonl' 中有 58 行因问题被按原样保留。\n", + "--- 文件处理完毕: qa_解方程_en-test_20250513.jsonl ---\n", + "\n", + "--- 开始处理文件: qa_解方程_中英混合-test.jsonl ---\n", + " 处理完成 100 行。\n", + " 统计: 共处理 100 行, 删除 0 行 (User或Assistant含科学计数法), 格式跳过 0 ���, 错误 0 行。\n", + " 正在用处理后的文件替换原文件 'qa_解方程_中英混合-test.jsonl'...\n", + " 文件 'qa_解方程_中英混合-test.jsonl' 替换成功。\n", + "--- 文件处理完毕: qa_解方程_中英混合-test.jsonl ---\n", + "\n", + "===================================================\n", + " 总体处理报告\n", + "===================================================\n", + "处理的文件总数: 18\n", + "其中有修改(删除行)的文件数: 3\n", + "所有文件中累计处理的总行数: 7,732\n", + "所有文件中累计删除的总行数: 22\n", + "所有文件中累计的格式跳过总数: 558\n", + "所有文件中累计的错误总数: 0 (这些行被保留)\n", + "===================================================\n" + ] + } + ], + "source": [ + "# -*- coding: utf-8 -*-\n", + "# 脚本功能:检测并删除指定文件夹下所有 JSONL 文件中 'User' 或 'Assistant' 字段包含科学计数法的行。\n", + "# 版本: v2.2 - 修改为同时检查 User 和 Assistant 部分,并添加中文注释。\n", + "\n", + "import json # 用于处理 JSON 数据\n", + "import re # 用于正则表达式操作,匹配科学计数法\n", + "import os # 用于操作系统相关功能,如文件和目录操作\n", + "import sys # 用于与 Python 解释器交互,如此处的 sys.exit\n", + "import traceback # 用于打印详细的错误追踪信息\n", + "\n", + "# ===============================================\n", + "# 配置区域\n", + "# ===============================================\n", + "# !! 修改此处的 INPUT_DIRECTORY 为你存放 .jsonl 文件的实际目录路径 !!\n", + "INPUT_DIRECTORY = \"../Test\" # 例如: \"/path/to/your/data\" 或 \"data_folder\"\n", + "# 单个文件内处理行数的报告间隔\n", + "REPORT_INTERVAL = 50000\n", + "\n", + "# ===============================================\n", + "# 文件处理逻辑\n", + "# ===============================================\n", + "\n", + "def process_file(input_filename: str) -> tuple[int, int, int, int]:\n", + " \"\"\"\n", + " 读取一个 JSONL 文件,检测 'User' 或 'Assistant' 文本中是否包含科学计数法。\n", + " 如果任一部分包含,则删除该行(不写入输出文件)。否则,保留该行。\n", + " 处理结果写入一个临时文件,然后用临时文件替换原始文件。\n", + "\n", + " 参数:\n", + " input_filename (str): 输入的 JSONL 文件路径。\n", + "\n", + " 返回:\n", + " tuple: (已处理行数, 已删除行数, 错误行数, 因格式问题跳过的行数)\n", + " \"\"\"\n", + " # 检查输入文件是否存在\n", + " if not os.path.exists(input_filename):\n", + " print(f\"错误:输入文件 '{input_filename}' 不存在。\")\n", + " return 0, 0, 0, 0 # 返回 (已处理行数, 已删除行数, 错误行数, 跳过行数)\n", + "\n", + " # 定义临时文件名,在原文件名后加 .tmp\n", + " temp_filename = input_filename + \".tmp\"\n", + " # 编译正则表达式以匹配科学计数法\n", + " pattern_sci = re.compile(r\"([+-]?\\d+(?:\\.\\d*)?|\\.\\d+)[Ee][+-]?\\d+\")\n", + "\n", + " # 初始化计数器\n", + " processed_lines_count = 0\n", + " deleted_lines_count = 0\n", + " error_lines_count = 0\n", + " skipped_format_issue_lines_count = 0\n", + "\n", + " try:\n", + " # 同时打开输入文件(读取模式)和临时文件(写入模式)\n", + " with open(input_filename, 'r', encoding='utf-8') as infile, \\\n", + " open(temp_filename, 'w', encoding='utf-8') as outfile:\n", + "\n", + " # 逐行读取输入文件\n", + " for i, line in enumerate(infile):\n", + " processed_lines_count += 1\n", + " if processed_lines_count % REPORT_INTERVAL == 0:\n", + " print(f\"\\r 已处理 {processed_lines_count:,} 行...\", end=\"\")\n", + "\n", + " try:\n", + " data = json.loads(line.strip())\n", + " except json.JSONDecodeError:\n", + " error_lines_count += 1\n", + " outfile.write(line)\n", + " continue\n", + "\n", + " if not isinstance(data, dict) or \"text\" not in data or not isinstance(data[\"text\"], str):\n", + " skipped_format_issue_lines_count += 1\n", + " outfile.write(line)\n", + " continue\n", + "\n", + " original_text = data[\"text\"]\n", + " parts = original_text.split(\"\\n\\nAssistant:\", 1)\n", + " if len(parts) != 2 or not parts[0].startswith(\"User:\"):\n", + " skipped_format_issue_lines_count += 1\n", + " outfile.write(line)\n", + " continue\n", + "\n", + " user_prefix = \"User: \"\n", + " user_text = parts[0][len(user_prefix):]\n", + " assistant_text = parts[1] # 提取 Assistant 文本\n", + "\n", + " # 检查 User 文本或 Assistant 文本中是否包含科学计数法\n", + " user_contains_sci = pattern_sci.search(user_text)\n", + " assistant_contains_sci = pattern_sci.search(assistant_text)\n", + "\n", + " if user_contains_sci or assistant_contains_sci:\n", + " deleted_lines_count += 1\n", + " # 如果 User 或 Assistant 任一部分找到科学计数法,则删除该行\n", + " else:\n", + " # 如果两部分都未找到科学计数法,则将原始 JSON 数据写回临时文件\n", + " try:\n", + " outfile.write(json.dumps(data, ensure_ascii=False) + '\\n')\n", + " except Exception:\n", + " error_lines_count += 1\n", + " outfile.write(line)\n", + "\n", + " print(f\"\\r 处理完成 {processed_lines_count:,} 行。\")\n", + " print(f\" 统计: 共处理 {processed_lines_count:,} 行, 删除 {deleted_lines_count:,} 行 (User或Assistant含科学计数法), 格式跳过 {skipped_format_issue_lines_count:,} 行, 错误 {error_lines_count:,} 行。\")\n", + "\n", + " print(f\" 正在用处理后的文件替换原文件 '{os.path.basename(input_filename)}'...\")\n", + " os.replace(temp_filename, input_filename)\n", + " print(f\" 文件 '{os.path.basename(input_filename)}' 替换成功。\")\n", + " if error_lines_count > 0 or skipped_format_issue_lines_count > 0:\n", + " print(f\" 注意: 文件 '{os.path.basename(input_filename)}' 中有 {error_lines_count + skipped_format_issue_lines_count:,} 行因问题被按原样保留。\")\n", + "\n", + " except IOError as e:\n", + " print(f\"\\n文件 '{input_filename}' 读写错误: {e}\")\n", + " error_lines_count += processed_lines_count\n", + " if os.path.exists(temp_filename):\n", + " try: os.remove(temp_filename)\n", + " except OSError as oe: print(f\"错误:无法删除临时文件 '{temp_filename}': {oe}\")\n", + " except Exception as e:\n", + " print(f\"\\n处理文件 '{input_filename}' 时发生意外错误: {e}\")\n", + " traceback.print_exc()\n", + " error_lines_count += processed_lines_count\n", + " if os.path.exists(temp_filename):\n", + " try: os.remove(temp_filename)\n", + " except OSError as oe: print(f\"错误:无法删除临时文件 '{temp_filename}': {oe}\")\n", + " \n", + " return processed_lines_count, deleted_lines_count, error_lines_count, skipped_format_issue_lines_count\n", + "\n", + "# ===============================================\n", + "# 主程序入口\n", + "# ===============================================\n", + "if __name__ == \"__main__\":\n", + " # 检查 INPUT_DIRECTORY 是否已配置或仍为占位符\n", + " if not INPUT_DIRECTORY or INPUT_DIRECTORY == \"your_jsonl_files_directory_here\":\n", + " print(\"错误:请在脚本中设置正确的 INPUT_DIRECTORY 变量。\")\n", + " sys.exit(1) # 退出程序\n", + "\n", + " # 检查 INPUT_DIRECTORY 是否是一个有效的目录\n", + " if not os.path.isdir(INPUT_DIRECTORY):\n", + " print(f\"错误:指定的输入路径 '{INPUT_DIRECTORY}' 不是一个有效的目录。\")\n", + " sys.exit(1) # 退出程序\n", + "\n", + " print(f\"开始在目录 '{INPUT_DIRECTORY}' 中处理所有 .jsonl 文件...\\n\")\n", + " \n", + " # 初始化所有文件的总计数器\n", + " total_files_processed_successfully = 0\n", + " total_files_with_deletions = 0\n", + " \n", + " grand_total_lines_processed = 0\n", + " grand_total_lines_deleted = 0\n", + " grand_total_errors = 0\n", + " grand_total_skipped_format = 0\n", + "\n", + " # 查找目录中所有 .jsonl 文件\n", + " jsonl_files_found = []\n", + " for filename in os.listdir(INPUT_DIRECTORY):\n", + " if filename.lower().endswith(\".jsonl\"):\n", + " jsonl_files_found.append(os.path.join(INPUT_DIRECTORY, filename))\n", + "\n", + " if not jsonl_files_found:\n", + " print(\"在指定目录中未找到 .jsonl 文件。\")\n", + " sys.exit(0)\n", + " \n", + " print(f\"找到 {len(jsonl_files_found)} 个 .jsonl 文件准备处理。\\n\")\n", + "\n", + " for filepath in jsonl_files_found:\n", + " print(f\"--- 开始处理文件: {os.path.basename(filepath)} ---\")\n", + " processed, deleted, errors, skipped = process_file(filepath)\n", + " \n", + " grand_total_lines_processed += processed\n", + " grand_total_lines_deleted += deleted\n", + " grand_total_errors += errors\n", + " grand_total_skipped_format += skipped\n", + " \n", + " if processed > 0 :\n", + " total_files_processed_successfully += 1\n", + " if deleted > 0:\n", + " total_files_with_deletions +=1\n", + " print(f\"--- 文件处理完毕: {os.path.basename(filepath)} ---\\n\")\n", + "\n", + " print(\"===================================================\")\n", + " print(\" 总体处理报告\")\n", + " print(\"===================================================\")\n", + " print(f\"处理的文件总数: {total_files_processed_successfully}\")\n", + " if total_files_processed_successfully > 0:\n", + " print(f\"其中有修改(删除行)的文件数: {total_files_with_deletions}\")\n", + " print(f\"所有文件中累计处理的总行数: {grand_total_lines_processed:,}\")\n", + " print(f\"所有文件中累计删除的总行数: {grand_total_lines_deleted:,}\")\n", + " print(f\"所有文件中累计的格式跳过总数: {grand_total_skipped_format:,}\")\n", + " print(f\"所有文件中累计的错误总数: {grand_total_errors:,} (这些行被保留)\")\n", + " else:\n", + " print(\"没有文件被成功处理。\")\n", + " print(\"===================================================\")" + ] + }, + { + "cell_type": "markdown", + "id": "92999c11", + "metadata": {}, + "source": [ + "# 生成解方程\n", + "\n", + "用于生成:\n", + "\n", + "训练集:X_ch_mix\n", + "\n", + "测试集:X_ch_mix_test" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a919eeda", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "==============================\n", + " 格式多样化、带提问和解题过程(x可为小数)解方程数据生成脚本 \n", + "==============================\n", + "提示: TOTAL_SAMPLES (500) < X_POOL_SIZE (1000), 可能无法完全覆盖 x整数部分 0-999。\n", + "--- 开始生成格式多样化、带提问和解题过程(x可为小数)的解方程数据 ---\n", + "输出文件: qa_add_解方程-test.jsonl\n", + "目标样本数: 500\n", + "A的配置: 最大整数位数=11, 最大小数位数=5, 小数概率=30.0%, 负数概率=30.0%\n", + "X的配置: 最大整数位数=11 (同A), 最大小数位数=5, 小数概率=50.0%\n", + "问题格式: 数字格式随机(标:75.0%, 全:10.0%, 简:10.0%, 繁:5.0%), 随机间距(0空格:90.0%), 结尾附加随机提问\n", + "答案格式: Assistant 部分包含解题过程 (x = <计算步骤> = <答案x>),答案x为标准阿拉伯数字\n", + "\n", + "开始生成 500 条格式多样化、带提问和解题过程(x可为小数)的解方程数据 (缓冲写入)...\n", + "进度: 500/500 (100.0%) | 已写入: 0 | 30671.3 条/秒 | 耗时:0.0s | 剩余:~0.0s \n", + "\n", + "[写入最后 500 条数据...]\n", + "\n", + "生成与写入完毕。目标样本: 500 -> 实际生成: 500 -> 写入文件: 500\n", + "总耗时: 0.02 秒。循环/写入错误数: 0。\n", + "\n", + "==============================\n", + "脚本执行完毕。总耗时: 0.02 秒。\n", + "数据文件: qa_add_解方程-test.jsonl\n", + "==============================\n" + ] + } + ], + "source": [ + "# -*- coding: utf-8 -*-\n", + "# 这是一个用于生成解一元一次方程问题数据集的 Python 脚本。\n", + "# 方程形式为 x op a = b 或 a op x = b (x 系数固定为1)。\n", + "# 方程中的已知数 (系数a, 结果b) 采用**多样化格式**。\n", + "# 方程末尾会**附加随机提问短语**。\n", + "# 答案 (x) 固定为标准阿拉伯数字, x 可以是小数。 # 已修改\n", + "# 使用**缓冲写入**方式,分批写入文件,降低内存消耗。\n", + "# 输出严格遵循 {\"text\": \"User: <多样化格式的方程 + 提问短语>\\n\\nAssistant: <解题过程 + 标准数字答案x>\"} 格式。\n", + "\n", + "import json\n", + "import random\n", + "import time\n", + "import math\n", + "from typing import List, Tuple, Union, Dict, Optional\n", + "from decimal import Decimal, getcontext, ROUND_DOWN, ROUND_HALF_UP, InvalidOperation\n", + "import traceback\n", + "from collections import Counter # 用于方便计数\n", + "\n", + "# ===============================================\n", + "# 配置参数区域 (用户应在此处���改)\n", + "# ===============================================\n", + "# --- 主要数量和文件名 ---\n", + "TOTAL_SAMPLES = 500 # 数据集中的目标总样本数\n", + "OUTPUT_FILENAME = f\"X_ch_mix_test.jsonl\" # 已修改:文件名反映中文注释\n", + "BUFFER_WRITE_SIZE = 10000 # 缓冲区大小,每 N 条数据写入一次文件\n", + "\n", + "# --- 数字生成控制 ---\n", + "# -- 针对系数 'a' --\n", + "MAX_DIGITS: int = 11 # 整数部分最大位数 (系数a和目标x整数部分的量级)\n", + "MAX_DECIMAL_PLACES: int = 5 # 小数部分最大位数 (系数a的小数位数)\n", + "DECIMAL_PROBABILITY: float = 0.30 # 方程系数 a 为小数的概率\n", + "NEGATIVE_POOL_PROB: float = 0.30 # 方程系数 a 为负的概率 (x的负号由其生成范围决定)\n", + "\n", + "# -- 针对目标 'x' --\n", + "X_DECIMAL_PROBABILITY: float = 0.50 # 目标 x 为小数的概率 # 新增\n", + "X_MAX_DECIMAL_PLACES: int = 5 # 目标 x 的小数部分最大位数 # 新增\n", + "\n", + "# --- 格式化控制 (问题部分:方程字符串) ---\n", + "# -- 数字表示法概率 (总和应为 1.0) --\n", + "STANDARD_ARABIC_PROB: float = 0.75 # 标准半角阿拉伯数字\n", + "FULL_WIDTH_ARABIC_PROB: float = 0.10 # 全角阿拉伯数字\n", + "SIMPLE_CHINESE_PROB: float = 0.10 # 简单中文数字\n", + "COMPLEX_CHINESE_PROB: float = 0.05 # 大写中文数字\n", + "_format_prob_sum = STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB + SIMPLE_CHINESE_PROB + COMPLEX_CHINESE_PROB\n", + "if not math.isclose(_format_prob_sum, 1.0):\n", + " raise ValueError(f\"数字格式概率总和必须为 1.0,当前为: {_format_prob_sum}\")\n", + "\n", + "# -- 间距控制 --\n", + "ZERO_SPACE_PROB: float = 0.90 # 0 个空格的概率\n", + "MAX_RANDOM_SPACES: int = 2 # 随机空格的最大数量 (当非 0 时)\n", + "\n", + "# -- 方程结尾提问短语列表 --\n", + "EQUATION_QUESTION_PROMPTS: List[str] = [\n", + " \", x = ?\", \", x=?\", \", x=?\", \", x = ?\", \", x 等于多少?\", \", x 等于多少?\",\n", + " \", 求 x。\", \", 求 x 的值。\", \", x 的值是?\", \", 请问 x 是多少?\", \", 计算 x。\", \", 求解 x。\"\n", + "]\n", + "\n", + "# --- 其他控制 ---\n", + "EQUATION_X_POOL_SIZE = 1000 # 用于确保 x 整数部分 0-(POOL_SIZE-1) 覆盖率的池大小\n", + "MAX_ATTEMPTS_FACTOR = 100 # 每个目标样本最多尝试生成的次数因子\n", + "\n", + "# ===============================================\n", + "# 核心代码\n", + "# ===============================================\n", + "\n", + "# --- 设置 Decimal 精度 ---\n", + "# b 可能的最大小数位数是 max(MAX_DECIMAL_PLACES, X_MAX_DECIMAL_PLACES)\n", + "# 最大整数位数 + 结果可能的最大小数位数 + 用于中间计算的缓冲\n", + "getcontext().prec = MAX_DIGITS + max(MAX_DECIMAL_PLACES, X_MAX_DECIMAL_PLACES) + 30\n", + "\n", + "# --- 中文数字转换函数 (无变化) ---\n", + "digit_map_simple = {'0': '零', '1': '一', '2': '二', '3': '三', '4': '四', '5': '五', '6': '六', '7': '七', '8': '八', '9': '九'}\n", + "unit_map_section_simple = ['', '十', '百', '千']\n", + "unit_map_large_simple = ['', '万', '亿', '兆']\n", + "digit_map_complex = {'0': '零', '1': '壹', '2': '贰', '3': '叁', '4': '肆', '5': '伍', '6': '陆', '7': '柒', '8': '捌', '9': '玖'}\n", + "unit_map_section_complex = ['', '拾', '佰', '仟']\n", + "unit_map_large_complex = ['', '萬', '億', '兆']\n", + "\n", + "def _convert_section(section_str: str, complex_form: bool = False) -> str:\n", + " digit_map = digit_map_complex if complex_form else digit_map_simple; unit_map_section = unit_map_section_complex if complex_form else unit_map_section_simple\n", + " if not section_str: return \"\"\n", + " try: section_int = int(section_str)\n", + " except ValueError: return \"无效输入\"\n", + " if section_int == 0: return digit_map['0']\n", + " chinese_s = \"\"; length = len(section_str); need_zero = False\n", + " for i in range(length):\n", + " digit = section_str[i]; place = length - 1 - i\n", + " if digit == '0': need_zero = True\n", + " else:\n", + " if need_zero and chinese_s and not chinese_s.endswith(digit_map['0']): chinese_s += digit_map['0']\n", + " need_zero = False; current_digit_chinese = \"\"\n", + " use_liang = False # 是否使用“两”\n", + " if not complex_form and digit == '2': # 非大写且数字是2\n", + " # 可能使用“两”的情况:在百位、千位,并且是该节的开头数字(如200,2000,220)\n", + " is_potentially_liang = place >= 2 # 是否在百位或更高位\n", + " is_leading_two_in_section = (i == 0) or all(d == '0' for d in section_str[:i]) # 是否是节的首个非零数字\n", + " if is_potentially_liang and is_leading_two_in_section: use_liang = True\n", + " if use_liang and random.random() < 0.8: current_digit_chinese = '两' # 80%概率用“两”\n", + " else: current_digit_chinese = digit_map['2']\n", + " else: current_digit_chinese = digit_map[digit]\n", + " # 处理“一十”的情况,如“一十二”应为“十二”\n", + " is_leading_one_in_ten_place = (not complex_form and digit == '1' and place == 1 and (i == 0 or all(d == '0' for d in section_str[:i])) and length > 1)\n", + " if is_leading_one_in_ten_place: chinese_s += unit_map_section[place] # 只加“十”\n", + " else: chinese_s += current_digit_chinese + unit_map_section[place]\n", + " # 如果末尾是“零”且长度大于1(不是单个“零”),则移除末尾的“零”\n", + " if chinese_s.endswith(digit_map['0']) and len(chinese_s) > len(digit_map['0']): chinese_s = chinese_s[:-1]\n", + " return chinese_s\n", + "\n", + "def num_to_chinese(num: int, complex_form: bool = False) -> str:\n", + " if not isinstance(num, int): return \"无效输入\"\n", + " digit_map = digit_map_complex if complex_form else digit_map_simple; unit_map_large = unit_map_large_complex if complex_form else unit_map_large_simple\n", + " if num == 0: return digit_map['0']\n", + " if num < 0: return (\"负\" if not complex_form else \"负\") + num_to_chinese(abs(num), complex_form)\n", + " s_num = str(num); result = \"\"; sections = []\n", + " # 将数字按四位分节\n", + " while len(s_num) > 0: sections.append(s_num[-4:]); s_num = s_num[:-4]\n", + " zero_padding_needed = False; last_section_was_zero = True; last_section_non_zero = False\n", + " for i in range(len(sections) - 1, -1, -1): # 从最高位节开始处理\n", + " section = sections[i];\n", + " try: section_int = int(section)\n", + " except ValueError: return \"无效输入\"\n", + " if section_int == 0: # 当前节是0\n", + " if i > 0 and last_section_non_zero: zero_padding_needed = True # 如果不是最低位的节,且前一节非零,则可能需要补零\n", + " last_section_was_zero = True; last_section_non_zero = False; continue\n", + " if zero_padding_needed: result += digit_map['0']; zero_padding_needed = False # 补零\n", + " section_chinese = _convert_section(section.lstrip('0'), complex_form) # 转换当前节\n", + " if not section_chinese or section_chinese == \"无效输入\": return \"无效输入\" # 转换失败\n", + " # 处理“两万”、“两亿”等情况,有10%概率用“二”代替“两”\n", + " is_single_two_and_has_large_unit = (not complex_form and section_chinese == \"两\" and len(section.lstrip('0'))==1 and i > 0)\n", + " if is_single_two_and_has_large_unit and random.random() < 0.1: result += \"二\"\n", + " else: result += section_chinese\n", + " last_section_was_zero = False; last_section_non_zero = True\n", + " if i > 0: result += unit_map_large[i] # 添加大单位(万、亿等)\n", + " # 清理末尾的零(例如,如果结果是“一千零”)\n", + " if result.endswith(digit_map['0']) and len(result) > len(digit_map['0']): result = result[:-1]\n", + " # 将开头的“一十”简化为“十”(非大写)\n", + " if not complex_form and result.startswith('一十') and len(result) > 1: result = result[1:]\n", + " return result\n", + "\n", + "def decimal_to_chinese(num: Decimal, complex_form: bool = False) -> str:\n", + " if not isinstance(num, Decimal): return \"无效输入\"\n", + " if not num.is_finite(): return \"无效输入\" # 处理 NaN, Inf\n", + " digit_map = digit_map_complex if complex_form else digit_map_simple\n", + " try: is_integer = (num == num.to_integral_value(rounding=ROUND_DOWN)) # 判断是否为整数\n", + " except Exception: is_integer = False # 捕获 to_integral_value 可能出现的错误\n", + " if is_integer:\n", + " try:\n", + " int_val = num.to_integral_value(rounding=ROUND_DOWN)\n", + " # 限制大小以进行实际的中文转换\n", + " if abs(int_val) < Decimal(10**100): return num_to_chinese(int(int_val), complex_form)\n", + " else: return \"数字过大无法转换\"\n", + " except (ValueError, TypeError, OverflowError, InvalidOperation): return \"无效输入或溢出\"\n", + " if num < 0: return (\"负\" if not complex_form else \"负\") + decimal_to_chinese(abs(num), complex_form)\n", + " try: s_num = \"{:f}\".format(num.normalize()) # 使用 normalize 处理 Decimal 可能的科学计数法\n", + " except Exception: return \"无效输入\" # 捕获格式化错误\n", + " if '.' not in s_num: # 如果没有小数点,应为整数,重新检查\n", + " try:\n", + " int_val_dec = Decimal(s_num)\n", + " if abs(int_val_dec) < Decimal(10**100): return num_to_chinese(int(int_val_dec), complex_form)\n", + " else: return \"数字过大无法转换\"\n", + " except (ValueError, TypeError, OverflowError, InvalidOperation): return \"无效输入或溢出\"\n", + " integer_part_str, fractional_part_str = s_num.split('.')\n", + " if integer_part_str == '0': chinese_int = digit_map['0']\n", + " else:\n", + " try:\n", + " int_val_dec = Decimal(integer_part_str)\n", + " if abs(int_val_dec) < Decimal(10**100):\n", + " chinese_int = num_to_chinese(int(int_val_dec), complex_form)\n", + " if not chinese_int or chinese_int == \"无效输入\": return \"无效输入\" # 传递错误\n", + " else: return \"数字过大无法转换\"\n", + " except (ValueError, TypeError, OverflowError, InvalidOperation): return \"无效输入或溢出\"\n", + " chinese_frac = \"\".join(digit_map.get(digit, '?') for digit in fractional_part_str) # 转换小数部分\n", + " point_word = \"点\" # 小数点\n", + " return f\"{chinese_int}{point_word}{chinese_frac}\"\n", + "\n", + "# --- 全角转换 (无变化) ---\n", + "half_to_full_map = str.maketrans(\"0123456789.-+\", \"0123456789.-+\")\n", + "def to_full_width(text: str) -> str: return text.translate(half_to_full_map)\n", + "\n", + "# --- 格式化数字变体 (无变化) ---\n", + "def format_number_variant(num: Union[int, Decimal]) -> str:\n", + " fmt_choice = random.random()\n", + " try: num_dec = Decimal(str(num)) if not isinstance(num, Decimal) else num\n", + " except InvalidOperation: return str(num) # 如果 num 不能转换为 Decimal,则回退\n", + "\n", + " target_format = 'std' # 默认格式\n", + " if fmt_choice < STANDARD_ARABIC_PROB: target_format = 'std'\n", + " elif fmt_choice < STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB: target_format = 'full'\n", + " elif fmt_choice < STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB + SIMPLE_CHINESE_PROB: target_format = 'simple_zh'\n", + " else: target_format = 'complex_zh'\n", + "\n", + " try:\n", + " if not num_dec.is_finite(): # 处理 NaN, Inf\n", + " s_num = str(num_dec) # 获取它们的字符串表示\n", + " return to_full_width(s_num) if target_format == 'full' else s_num\n", + "\n", + " if target_format == 'std': return format_decimal_or_int(num_dec)\n", + " elif target_format == 'full':\n", + " s = format_decimal_or_int(num_dec)\n", + " return to_full_width(s)\n", + " elif target_format == 'simple_zh':\n", + " result = decimal_to_chinese(num_dec, complex_form=False)\n", + " # 如果中文转换失败,则回退到标准格式\n", + " return result if result not in [\"无效输入\", \"数字过大无法转换\"] else format_decimal_or_int(num_dec)\n", + " else: # complex_zh\n", + " result = decimal_to_chinese(num_dec, complex_form=True)\n", + " return result if result not in [\"无效输入\", \"数字过大无法转换\"] else format_decimal_or_int(num_dec)\n", + " except Exception as e:\n", + " # print(f\"警告: format_number_variant 中格式化 {num} 时出错: {e}。回退到标准格式。\")\n", + " return format_decimal_or_int(num) # 如果发生任何错误,则回退到标准格式\n", + "\n", + "# --- 获取随机间距 (无变化) ---\n", + "def get_random_spacing() -> str:\n", + " if random.random() < ZERO_SPACE_PROB: return \"\"\n", + " else: return \" \" * random.randint(1, MAX_RANDOM_SPACES)\n", + "\n", + "# --- 辅助函数 (无变化, 但确保健壮性) ---\n", + "def format_decimal_or_int(num: Union[int, Decimal]) -> str:\n", + " try:\n", + " if isinstance(num, int): return str(num)\n", + " if isinstance(num, Decimal):\n", + " if not num.is_finite(): return str(num) # 处理 NaN, Inf\n", + " # 标准化以移除可能的科学计数法中的尾随零,然后格式化为定点数\n", + " s = \"{:f}\".format(num.normalize())\n", + " if '.' in s:\n", + " s = s.rstrip('0').rstrip('.') # 移除尾随零,如果是整数则移除尾随点\n", + " return s\n", + " return str(num) # 其他类型的回退\n", + " except Exception:\n", + " # 如果发生任何格式化错误,返回字符串表示\n", + " return str(num)\n", + "\n", + "\n", + "def get_distributed_count_from_probs(population: List[int], probabilities: List[float]) -> int:\n", + " if not population: return 1 # 如果总体为空,则默认为1\n", + " if not probabilities or len(population) != len(probabilities) or not all(p >= 0 for p in probabilities):\n", + " return random.choice(population) # 如果概率无效,则回退\n", + "\n", + " prob_sum = sum(probabilities)\n", + " if prob_sum < 1e-9: # 实际上所有概率都为零\n", + " return random.choice(population)\n", + "\n", + " normalized_probabilities = probabilities\n", + " if not math.isclose(prob_sum, 1.0, abs_tol=1e-5): # 如果总和不接近1.0,则进行归一化\n", + " try:\n", + " normalized_probabilities = [p / prob_sum for p in probabilities]\n", + " except ZeroDivisionError: # 应该被 prob_sum < 1e-9 捕获,但作为保障\n", + " return random.choice(population)\n", + "\n", + " try:\n", + " return random.choices(population, weights=normalized_probabilities, k=1)[0]\n", + " except Exception as e: # 捕获 random.choices 的任何其他错误\n", + " # print(f\"警告: get_distributed_count_from_probs 中出错: {e}。回退到 random.choice。\")\n", + " return random.choice(population)\n", + "\n", + "\n", + "def calculate_digit_probabilities(max_digits: int) -> Dict[int, float]:\n", + " if max_digits <= 0: return {1: 1.0} # 单个数字 '1' 的概率为 1.0\n", + "\n", + " raw_probs = {}\n", + " prob_sum = Decimal('0.0')\n", + " # 更平缓的衰减:较短的数字概率略高\n", + " base_prob = Decimal('0.1') # 1位数字的基础概率\n", + " decay_factor = Decimal('0.95') # 衰减的乘法因子\n", + " increase_factor = Decimal('1.05') # 对较长数字的轻微增加,以抵消过度的衰减\n", + "\n", + " for n in range(1, max_digits + 1):\n", + " # 等比数列,但有所调整\n", + " prob = base_prob * (decay_factor**(n - 1)) * (increase_factor**(n-1)) # 使其不那么陡峭\n", + " prob = max(Decimal('0.01'), prob) # 确保最小概率\n", + " raw_probs[n] = prob\n", + " prob_sum += prob\n", + "\n", + " normalized_probs = {}\n", + " if prob_sum <= 0: # 如果总和为零或负(不应发生,因为有max(0.01)),则回退\n", + " fallback_prob = 1.0 / max(1, max_digits)\n", + " normalized_probs = {n: fallback_prob for n in range(1, max_digits + 1)}\n", + " else:\n", + " normalized_probs = {n: float(p / prob_sum) for n, p in raw_probs.items()}\n", + "\n", + " # 由于潜在的浮点数不精确性,确保总和正好是1.0\n", + " final_sum = sum(normalized_probs.values())\n", + " if not math.isclose(final_sum, 1.0, abs_tol=1e-9):\n", + " # print(f\"警告: 数字位数概率总和为 {final_sum},强制重新归一化。\")\n", + " renorm_factor = 1.0 / final_sum if final_sum != 0 else 1.0\n", + " total = 0.0\n", + " keys = sorted(normalized_probs.keys()) # 按定义顺序处理\n", + " for i, n in enumerate(keys):\n", + " if i == len(keys) - 1: # 最后一个元素获取剩余部分\n", + " normalized_probs[n] = max(0.0, 1.0 - total)\n", + " else:\n", + " normalized_probs[n] = max(0.0, normalized_probs[n] * renorm_factor)\n", + " total += normalized_probs[n]\n", + " return normalized_probs\n", + "\n", + "def _generate_positive_integer_with_digits(num_digits: int) -> int:\n", + " if num_digits <= 0: num_digits = 1 # 确保至少1位\n", + " if num_digits == 1:\n", + " min_val, max_val = 0, 9 # 允许单位数数字为0\n", + " else:\n", + " min_val = 10**(num_digits - 1)\n", + " max_val = 10**num_digits - 1\n", + " if min_val > max_val: return max_val # 如果 num_digits >= 1,则不应发生\n", + " try:\n", + " return random.randint(min_val, max_val)\n", + " except ValueError: # 当前逻辑不应发生\n", + " return max_val\n", + "\n", + "\n", + "# --- 文件写入辅助函数 (无变化) ---\n", + "def write_buffer_to_file(filename: str, buffer: List[str]):\n", + " if not buffer: return\n", + " try:\n", + " with open(filename, 'a', encoding='utf-8') as f:\n", + " f.write('\\n'.join(buffer) + '\\n')\n", + " except IOError as e: print(f\"\\n错误:写入文件 '{filename}' 时发生 IO 错误: {e}\"); traceback.print_exc()\n", + " except Exception as e: print(f\"\\n错误:写入文件时发生未知错误: {e}\"); traceback.print_exc()\n", + "\n", + "# --- 主要生成函数 (已修改以处理小数x) ---\n", + "def generate_equations_diverse_format_buffered(\n", + " filename: str, total_samples: int,\n", + " # 系数 'a' 的参数\n", + " decimal_prob_a: float, max_digits_a: int, max_decimal_places_a: int, negative_prob_a: float,\n", + " # 目标 'x' 的参数\n", + " decimal_prob_x: float, max_decimal_places_x: int, # x 的整数部分最大��数使用 max_digits_a\n", + " # 通用参数\n", + " buffer_write_size: int, max_attempts_factor: int):\n", + " \"\"\"生成问题格式多样化、带结尾提问、带解题过程(x可以是小数)的解方程数据。\"\"\"\n", + " # --- 0. 参数验证和准备 ---\n", + " if total_samples <= 0: print(\"警告:total_samples 必须大于 0。\"); return\n", + " if buffer_write_size <= 0: print(\"警告:BUFFER_WRITE_SIZE 必须大于 0,设置为 1。\"); buffer_write_size = 1\n", + " if not EQUATION_QUESTION_PROMPTS: print(\"警告:EQUATION_QUESTION_PROMPTS 列表为空,将不添加结尾提问。\")\n", + "\n", + " # --- 打印配置信息 ---\n", + " print(f\"--- 开始生成格式多样化、带提问和解题过程(x可为小数)的解方程数据 ---\")\n", + " print(f\"输出文件: {filename}\")\n", + " print(f\"目标样本数: {total_samples:,}\")\n", + " print(f\"A的配置: 最大整数位数={max_digits_a}, 最大小数位数={max_decimal_places_a}, 小数概率={decimal_prob_a:.1%}, 负数概率={negative_prob_a:.1%}\")\n", + " print(f\"X的配置: 最大整数位数={max_digits_a} (同A), 最大小数位数={max_decimal_places_x}, 小数概率={decimal_prob_x:.1%}\") # x的负号由池决定\n", + " print(f\"问题格式: 数字格式随机(标:{STANDARD_ARABIC_PROB:.1%}, 全:{FULL_WIDTH_ARABIC_PROB:.1%}, 简:{SIMPLE_CHINESE_PROB:.1%}, 繁:{COMPLEX_CHINESE_PROB:.1%}), 随机间距(0空格:{ZERO_SPACE_PROB:.1%}), 结尾附加随机提问\")\n", + " print(f\"答案格式: Assistant 部分包含解题过程 (x = <计算步骤> = <答案x>),答案x为标准阿拉伯数字\")\n", + "\n", + " # --- 计算整数部分位数分布 (用于 'a' 和 'x' 的整数部分) ---\n", + " digit_pop: List[int] = []; digit_probs_list: List[float] = []\n", + " if max_digits_a > 0: # max_digits_a 控制 a 和 x 的整数部分大小\n", + " digit_probabilities_dict = calculate_digit_probabilities(max_digits_a)\n", + " digit_pop = list(range(1, max_digits_a + 1)); digit_probs_list = [digit_probabilities_dict.get(n, 0.0) for n in digit_pop]\n", + " if not math.isclose(sum(digit_probs_list), 1.0, abs_tol=1e-5): print(f\"警告: 位数概率列表和为 {sum(digit_probs_list):.4f}。\")\n", + " if not digit_probs_list: digit_pop = [1]; digit_probs_list = [1.0] # 回退\n", + " else: # max_digits_a 为 0,意味着 'a' 和 'x' 的整数部分为 0\n", + " digit_pop = [1]; digit_probs_list = [1.0] # _generate_positive_integer_with_digits 将产生 0\n", + "\n", + " # --- 准备方程 x 整数部分值池 ---\n", + " base_x_pool = list(range(EQUATION_X_POOL_SIZE)); random.shuffle(base_x_pool)\n", + " repeats = math.ceil(total_samples / len(base_x_pool)) if base_x_pool else 1\n", + " equation_x_int_part_pool = (base_x_pool * repeats)[:total_samples]; random.shuffle(equation_x_int_part_pool)\n", + " additional_needed = total_samples - len(equation_x_int_part_pool)\n", + " if additional_needed > 0:\n", + " print(f\"信息: x 整数部分池不足 {total_samples}, 补充 {additional_needed} 个随机 x 整数部分。\")\n", + " # x 整数部分的最大值\n", + " max_x_int_val = 10**max_digits_a -1 if max_digits_a > 0 else 0\n", + " min_x_int_val = -(10**max_digits_a -1) if max_digits_a > 0 else 0\n", + " \n", + " actual_min_x_int = min(min_x_int_val, max_x_int_val) # 处理 max_digits_a=0 的情况,此时两者都为 0\n", + " actual_max_x_int = max(min_x_int_val, max_x_int_val)\n", + "\n", + " for _ in range(additional_needed):\n", + " equation_x_int_part_pool.append(random.randint(actual_min_x_int, actual_max_x_int))\n", + " random.shuffle(equation_x_int_part_pool)\n", + "\n", + " # --- 初始化计数器和写入缓冲区 ---\n", + " generated_count = 0; total_attempts = 0; errors_in_loop = 0; lines_written_total = 0\n", + " max_total_attempts = total_samples * max(10, max_attempts_factor)\n", + " start_time_generate = time.time()\n", + " write_buffer: List[str] = []\n", + " print(f\"\\n开始生成 {total_samples:,} 条格式多样化、带提问和解题过程(x可为小数)的解方程数据 (缓冲写入)...\")\n", + " last_reported_count = -1\n", + "\n", + " # --- 清空或创建输出文件 ---\n", + " try:\n", + " with open(filename, 'w', encoding='utf-8') as f: f.write(\"\")\n", + " except IOError as e: print(f\"\\n错误:无法初始化输出文件 '{filename}': {e}\"); return\n", + "\n", + " # --- 主生成循环 ---\n", + " while generated_count < total_samples:\n", + " total_attempts += 1\n", + " if total_attempts > max_total_attempts:\n", + " print(f\"\\n\\n警告: 尝试次数达到上限 ({total_attempts:,}) 仍未生成 {total_samples:,} 条数据��\")\n", + " print(f\"当前已生成: {generated_count:,} 条。可能存在持续错误。\")\n", + " print(\"脚本提前终止。\")\n", + " break\n", + " if not equation_x_int_part_pool: print(\"\\n错误: x 整数部分池意外耗尽。\"); break\n", + "\n", + " target_x_int_part = equation_x_int_part_pool.pop(0) # 从池中获取 x 的整数部分\n", + "\n", + " try:\n", + " # --- 生成目标 x (可以是小数) ---\n", + " x_calc: Decimal # 用于计算的 x (Decimal类型)\n", + " x_is_decimal_type = random.random() < decimal_prob_x # 判断 x 是否为小数类型\n", + " x_decimal_places_actual = 0 # 当前 x 的实际小数位数\n", + "\n", + " if x_is_decimal_type and max_decimal_places_x > 0:\n", + " x_decimal_places_actual = random.randint(1, max_decimal_places_x)\n", + " # 生成小数部分的绝对值\n", + " frac_x_val_abs = Decimal(random.randint(0, 10**x_decimal_places_actual - 1)) / (Decimal(10)**x_decimal_places_actual)\n", + " \n", + " base_x_dec = Decimal(str(target_x_int_part))\n", + " # 正确地添加/减去小数部分以扩展数值大小\n", + " if base_x_dec.is_zero() or base_x_dec > Decimal('0'): # 如果是0或正数,则相加\n", + " x_calc = base_x_dec + frac_x_val_abs\n", + " else: # base_x_dec < 0, 相减使其更负\n", + " x_calc = base_x_dec - frac_x_val_abs\n", + " \n", + " try:\n", + " # 量化并标准化 x\n", + " x_calc = x_calc.quantize(Decimal(f\"1e-{x_decimal_places_actual}\"), rounding=ROUND_HALF_UP).normalize()\n", + " if x_calc.is_zero() and x_calc.is_signed(): x_calc = Decimal('0') # 将 -0 标准化为 0\n", + " except InvalidOperation: # 量化失败的回退\n", + " x_calc = Decimal(str(target_x_int_part)) # 回退到整数\n", + " x_is_decimal_type = False # 标记为非小数\n", + " x_decimal_places_actual = 0 # 重置小数位数\n", + " else: # x 是整数\n", + " x_calc = Decimal(str(target_x_int_part))\n", + " x_is_decimal_type = False # 明确标记为非小数\n", + " x_decimal_places_actual = 0 # 小数位数为0\n", + "\n", + "\n", + " # --- 生成系数 a ---\n", + " struct = random.choice(['x_op_a', 'a_op_x']); eq_op = random.choice(['+', '-'])\n", + " # 使用 max_digits_a 作为 'a' 的整数部分位数\n", + " a_digits_count = get_distributed_count_from_probs(digit_pop, digit_probs_list) \n", + " a_is_decimal_type = random.random() < decimal_prob_a # 判断 a 是否为小数类型\n", + " a_sign = -1 if random.random() < negative_prob_a else 1 # a 的符号\n", + "\n", + " a_base_abs_val = _generate_positive_integer_with_digits(a_digits_count) # a 的整数部分的绝对值\n", + " a_val_for_question: Union[int, Decimal] # 用于问题中显示的 a (可能经过格式化)\n", + " a_decimal_places_actual = 0 # 当前 a 的实际小数位数\n", + "\n", + " if a_is_decimal_type and max_decimal_places_a > 0:\n", + " a_decimal_places_actual = random.randint(1, max_decimal_places_a)\n", + " frac_a_val = Decimal(random.randint(0, 10**a_decimal_places_actual - 1)) / (Decimal(10)**a_decimal_places_actual)\n", + " a_temp_decimal = Decimal(a_base_abs_val) + frac_a_val\n", + " a_val_for_question = a_temp_decimal * a_sign\n", + " try: \n", + " # 仅当 a 不是有效整数时才量化\n", + " if not (a_val_for_question == a_val_for_question.to_integral_value()):\n", + " a_val_for_question = a_val_for_question.quantize(Decimal(f\"1e-{a_decimal_places_actual}\"), rounding=ROUND_HALF_UP).normalize()\n", + " else: # 如果求和后变成整数,则视为整数\n", + " a_val_for_question = a_val_for_question.to_integral_value(rounding=ROUND_HALF_UP)\n", + "\n", + " if isinstance(a_val_for_question, Decimal) and a_val_for_question.is_zero() and a_val_for_question.is_signed():\n", + " a_val_for_question = Decimal('0') # 将 -0 标准化为 0\n", + " except InvalidOperation: # 量化失败的回退\n", + " a_val_for_question = Decimal(a_base_abs_val * a_sign) # 回退到整数乘以符号\n", + " else: # 'a' 是整数\n", + " a_val_for_question = a_base_abs_val * a_sign\n", + " \n", + " a_calc = Decimal(str(a_val_for_question)) # 用于与 x_calc 进行精确计算的 a (Decimal类型)\n", + "\n", + " # --- 计算 b (方程的结果) ---\n", + " b_val_calc: Decimal # 用于计算的 b (总是 Decimal 类型)\n", + " if struct == 'x_op_a': # 方程形式: x op a = b\n", + " b_val_calc = x_calc + a_calc if eq_op == '+' else x_calc - a_calc\n", + " else: # 方程形式: a op x = b\n", + " b_val_calc = a_calc + x_calc if eq_op == '+' else a_calc - x_calc\n", + "\n", + " b_val_for_question: Union[int, Decimal] # 用于问题中显示的 b\n", + " # 判断 b 是否实际上是整数\n", + " is_b_effectively_integer = b_val_calc.is_finite() and \\\n", + " (b_val_calc == b_val_calc.to_integral_value(rounding=ROUND_DOWN))\n", + " \n", + " # 根据输入,b 可能需要的最大小数位数\n", + " max_b_dp_from_inputs = 0\n", + " if a_is_decimal_type: max_b_dp_from_inputs = max(max_b_dp_from_inputs, a_decimal_places_actual)\n", + " if x_is_decimal_type: max_b_dp_from_inputs = max(max_b_dp_from_inputs, x_decimal_places_actual)\n", + " \n", + " # 根据配置,b 的小数位数的总体上限\n", + " b_display_dp_cap = max(max_decimal_places_a, max_decimal_places_x)\n", + " \n", + " if is_b_effectively_integer: # 如果 b 是整数\n", + " try: b_val_for_question = int(b_val_calc.to_integral_value(rounding=ROUND_DOWN))\n", + " except (OverflowError, InvalidOperation): b_val_for_question = b_val_calc # 回退\n", + " elif b_val_calc.is_finite(): # 如果 b 是有限小数\n", + " # 确定在问题中显示 b 的小数位数\n", + " b_decimal_places_to_show = min(max_b_dp_from_inputs, b_display_dp_cap)\n", + " b_decimal_places_to_show = max(0, b_decimal_places_to_show) # 确保非负\n", + " \n", + " if b_decimal_places_to_show > 0 : # 如果需要显示小数位\n", + " try:\n", + " b_val_for_question = b_val_calc.quantize(Decimal(f\"1e-{b_decimal_places_to_show}\"), rounding=ROUND_HALF_UP).normalize()\n", + " except InvalidOperation: b_val_for_question = b_val_calc # 回退\n", + " else: # 如果目标小数位数为0,则视为整数\n", + " try: b_val_for_question = int(b_val_calc.to_integral_value(rounding=ROUND_HALF_UP))\n", + " except (OverflowError, InvalidOperation): b_val_for_question = b_val_calc # 回退\n", + " \n", + " # 将 -0 标准化为 0\n", + " if isinstance(b_val_for_question, Decimal) and b_val_for_question.is_zero() and b_val_for_question.is_signed():\n", + " b_val_for_question = Decimal('0')\n", + " else: # b_val_calc 不是有限数 (例如 NaN, Inf)\n", + " errors_in_loop += 1; continue # 跳过此样本\n", + "\n", + " answer_str = format_decimal_or_int(x_calc) # 最终答案 (x) 的标准格式\n", + "\n", + " # --- 构建解题过程字符串 ---\n", + " str_a_calc_solution = format_decimal_or_int(a_calc) # 解题步骤中 a 的标准格式\n", + " # 在解题步骤中使用精确计算的 b (b_val_calc),而不是用于问题显示的 b_val_for_question\n", + " str_b_calc_solution_step = format_decimal_or_int(b_val_calc) \n", + " str_abs_a_calc_solution = format_decimal_or_int(abs(a_calc)) # a 绝对值的标准格式\n", + " \n", + " solution_intermediate_step = \"x = \" # 解题步骤的开头\n", + " if struct == 'x_op_a': # 方程形式: x original_op a_calc = b_calc\n", + " solution_intermediate_step += str_b_calc_solution_step # 以 b_calc 开头\n", + " if eq_op == '+': # 原始方程: x + a_calc = b_calc => 推导: x = b_calc - a_calc\n", + " solution_intermediate_step += f\" - {str_a_calc_solution}\" if a_calc >= 0 else f\" + {str_abs_a_calc_solution}\"\n", + " else: # 原始方程: x - a_calc = b_calc => 推导: x = b_calc + a_calc\n", + " solution_intermediate_step += f\" + {str_a_calc_solution}\" if a_calc >= 0 else f\" - {str_abs_a_calc_solution}\"\n", + " elif struct == 'a_op_x': # 方程形式: a_calc original_op x = b_calc\n", + " if eq_op == '+': # 原始方程: a_calc + x = b_calc => 推导: x = b_calc - a_calc\n", + " solution_intermediate_step += str_b_calc_solution_step # 以 b_calc 开头\n", + " solution_intermediate_step += f\" - {str_a_calc_solution}\" if a_calc >= 0 else f\" + {str_abs_a_calc_solution}\"\n", + " else: # 原始方程: a_calc - x = b_calc => 推导: -x = b_calc - a_calc => x = a_calc - b_calc\n", + " solution_intermediate_step += str_a_calc_solution # 以 a_calc 开头\n", + " # 这里,b_val_calc 用于减法项\n", + " solution_intermediate_step += f\" - {str_b_calc_solution_step}\" if b_val_calc >= 0 else f\" + {format_decimal_or_int(abs(b_val_calc))}\"\n", + " \n", + " assistant_response_str = f\"{solution_intermediate_step} = {answer_str}\" # 完整的 Assistant 回答\n", + "\n", + " # --- 格式化问题字符串中的数字 ---\n", + " fmt_a_for_question = format_number_variant(a_val_for_question) # 问题中 a 的多样化格式\n", + " fmt_b_for_question = format_number_variant(b_val_for_question) # 问题中 b 的多样化格式 (可能已取近似值)\n", + "\n", + " current_op_display_in_question = eq_op # 问题中显示的操作符\n", + " # 处理 'x op a = b' 形式中 a 为负数的情况,以便在问题字符串中更清晰地显示\n", + " if struct == 'x_op_a' and isinstance(a_val_for_question, (int, Decimal)) and a_val_for_question < 0:\n", + " fmt_a_for_question = format_number_variant(abs(a_val_for_question)) # 显示时使用绝对值\n", + " # x + (-a) 变为 x - a; x - (-a) 变为 x + a\n", + " current_op_display_in_question = '-' if eq_op == '+' else '+' \n", + " \n", + " s = [get_random_spacing() for _ in range(4)]; parts = [] # 随机间距\n", + " if struct == 'x_op_a':\n", + " parts = ['x', s[0], current_op_display_in_question, s[1], fmt_a_for_question, s[2], '=', s[3], fmt_b_for_question]\n", + " else: # struct == 'a_op_x'\n", + " parts = [fmt_a_for_question, s[0], eq_op, s[1], 'x', s[2], '=', s[3], fmt_b_for_question]\n", + " base_question_str = \"\".join(parts) # 基础方程字符串\n", + "\n", + " # 添加结尾提问短语\n", + " final_question_str = base_question_str\n", + " if EQUATION_QUESTION_PROMPTS: # 确保列表不为空\n", + " chosen_prompt = random.choice(EQUATION_QUESTION_PROMPTS)\n", + " final_question_str += get_random_spacing() + chosen_prompt # 添加随机间距和提问短语\n", + " \n", + " text_content = f\"User: {final_question_str}\\n\\nAssistant: {assistant_response_str}\" # 最终的 JSON 内容\n", + "\n", + " # --- 序列化并添加到缓冲区 ---\n", + " try:\n", + " json_string = json.dumps({\"text\": text_content}, ensure_ascii=False)\n", + " if json_string and not json_string.isspace(): # 确保 JSON 字符串非空\n", + " write_buffer.append(json_string)\n", + " generated_count += 1\n", + " if len(write_buffer) >= buffer_write_size: # 如果缓冲区已满\n", + " write_buffer_to_file(filename, write_buffer) # 写入文件\n", + " lines_written_total += len(write_buffer)\n", + " write_buffer = [] # 清空缓冲区\n", + " else: print(f\"\\n警告: 生成了空的 JSON 字符串: {text_content}\"); errors_in_loop += 1\n", + " except Exception as dump_err: print(f\"\\n错误:序列化 JSON 时出错: {dump_err} for item: {text_content}\"); errors_in_loop += 1\n", + "\n", + " except KeyboardInterrupt: print(\"\\n接收到中断信号,停止生成...\"); break # 用户中断\n", + " except Exception as loop_err: print(f\"\\n处理样本时意外错误: {loop_err}\"); traceback.print_exc(); errors_in_loop += 1; continue # 循环内其他错误\n", + "\n", + " # --- 进度报告 ---\n", + " report_interval = max(1, total_samples // 100) if total_samples > 0 else 1 # 报告间隔\n", + " if generated_count > 0 and (generated_count % report_interval == 0 or last_reported_count != generated_count or generated_count == total_samples):\n", + " progress = generated_count / total_samples if total_samples > 0 else 0; elapsed_time = time.time() - start_time_generate\n", + " samples_per_sec = generated_count / elapsed_time if elapsed_time > 0 else 0\n", + " est_remaining_gen = float('inf') # 预计剩余时间\n", + " if progress > 1e-6 and samples_per_sec > 0: est_remaining_gen = (total_samples - generated_count) / samples_per_sec\n", + " rem_time_str = f\"{est_remaining_gen:.1f}s\" if est_remaining_gen != float('inf') else \"N/A\"\n", + " print(f\"\\r进度: {generated_count:,}/{total_samples:,} ({progress:.1%}) | 已写入: {lines_written_total:,} | {samples_per_sec:.1f} 条/秒 | 耗时:{elapsed_time:.1f}s | 剩余:~{rem_time_str} \", end=\"\")\n", + " last_reported_count = generated_count\n", + "\n", + " print(\" \" * 130, end=\"\\r\"); print() # 清除进度条\n", + "\n", + " # --- 最后一次写入剩余缓冲区内容 ---\n", + " if write_buffer:\n", + " print(f\"\\n[写入最后 {len(write_buffer)} 条数据...]\")\n", + " write_buffer_to_file(filename, write_buffer)\n", + " lines_written_total += len(write_buffer)\n", + " write_buffer = []\n", + "\n", + " # --- 结束日志和统计 ---\n", + " end_generate = time.time(); total_gen_time = end_generate - start_time_generate\n", + " print(f\"\\n生成与写入完毕。目标样本: {total_samples:,} -> 实际生成: {generated_count:,} -> 写入文件: {lines_written_total:,}\")\n", + " print(f\"总耗时: {total_gen_time:.2f} 秒。循环/写入错误数: {errors_in_loop:,}。\")\n", + "\n", + "# ===============================================\n", + "# 主程序入口\n", + "# ===============================================\n", + "if __name__ == \"__main__\":\n", + " total_start_time = time.time()\n", + " print(\"=\"*30); print(\" 格式多样化、带提问和解题过程(x可为小数)解方程数据生成脚本 \"); print(\"=\"*30)\n", + " if TOTAL_SAMPLES < EQUATION_X_POOL_SIZE: print(f\"提示: TOTAL_SAMPLES ({TOTAL_SAMPLES}) < X_POOL_SIZE ({EQUATION_X_POOL_SIZE}), 可能无法完全覆盖 x整数部分 0-{EQUATION_X_POOL_SIZE-1}。\")\n", + "\n", + " try:\n", + " # 调用主生成函数\n", + " generate_equations_diverse_format_buffered(\n", + " filename=OUTPUT_FILENAME,\n", + " total_samples=TOTAL_SAMPLES,\n", + " # 系数 'a' 的参数\n", + " decimal_prob_a=DECIMAL_PROBABILITY,\n", + " max_digits_a=MAX_DIGITS,\n", + " max_decimal_places_a=MAX_DECIMAL_PLACES,\n", + " negative_prob_a=NEGATIVE_POOL_PROB,\n", + " # 目标 'x' 的参数\n", + " decimal_prob_x=X_DECIMAL_PROBABILITY,\n", + " max_decimal_places_x=X_MAX_DECIMAL_PLACES,\n", + " # 通用参数\n", + " buffer_write_size=BUFFER_WRITE_SIZE,\n", + " max_attempts_factor=MAX_ATTEMPTS_FACTOR\n", + " )\n", + " except ValueError as ve: print(f\"\\n配置错误: {ve}\")\n", + " except Exception as main_e: print(f\"\\n生成数据过程中发生未捕获的主错误: {main_e}\"); traceback.print_exc()\n", + " finally: pass # 确保任何情况下都能执行\n", + "\n", + " total_end_time = time.time()\n", + " print(\"\\n\" + \"=\"*30); print(f\"脚本执行完毕。总耗时: {total_end_time - total_start_time:.2f} 秒。\"); print(f\"数据文件: {OUTPUT_FILENAME}\"); print(\"=\"*30)" + ] + }, + { + "cell_type": "markdown", + "id": "79a45f39", + "metadata": {}, + "source": [ + "# 中英混合解方程\n", + "\n", + "用于生成:\n", + "\n", + "训练集:X_ch_en_mix\n", + "\n", + "测试集:X_ch_en_mix_test_v2 ,X_ch_en_mix_test_v1" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2a27391b", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "==============================\n", + " 解方程数据生成脚本 (v1.15 - 含英文格式) \n", + "==============================\n", + "提示: TOTAL_SAMPLES (500) < X_POOL_SIZE (1000), 可能无法完全覆盖 x整数部分 0-999。\n", + "--- 开始生成格式多样化(含英文、字符级混合)、带提问和解题过程(x可为小数)的解方程数据 ---\n", + "输出文件: qa_解方程_中英混合_more-test.jsonl\n", + "目标样本数: 500\n", + "A的配置: 最大整数位数=11, 最大小数位数=5, 小数概率=30.0%, 负数概率=30.0%\n", + "X的配置: 最大整数位数=11 (同A), 最大小数位数=5, 小数概率=50.0%\n", + "问题格式: 基础数字格式随机(标:20.0%, 全:10.0%, 简:25.0%, 繁:20.0%, 英:25.0%)\n", + " 字符级混合概率 (非英文): 25.0%\n", + " 英文数字大小写: 80% 逐词独立风格, 20% 逐字符\n", + " 随机间距(0空格:90.0%), 结尾附加随机提问\n", + "答案格式: Assistant 部分包含解题过程 (x = <计算步骤> = <答案x>),答案x为标准阿拉伯数字\n", + "\n", + "开始生成 500 条数据 (缓冲写入)...\n", + "进度: 500/500 (100.0%) | 已写入: 0 | 16475.0 条/秒 | 耗时:0.0s | 剩余:~0.0s \n", + "\n", + "[写入最后 500 条数据...]\n", + "\n", + "生成与写入完毕。目标样本: 500 -> 实际生成: 500 -> 写入文件: 500\n", + "总耗时: 0.03 秒。循环/写入错误数: 0。\n", + "\n", + "==============================\n", + "脚本执行完毕。总耗时: 0.03 秒。\n", + "数据文件: qa_解方程_中英混合_more-test.jsonl\n", + "==============================\n" + ] + } + ], + "source": [ + "# -*- coding: utf-8 -*-\n", + "# 这是一个用于生成解一元一次方程问题数据集的 Python 脚本。\n", + "# v1.15: Integrated English word conversion and advanced random casing for numbers a and b.\n", + "# Retained Chinese and Arabic formats with char mixing.\n", + "# Operators and question prompts remain primarily non-English for now.\n", + "\n", + "import json\n", + "import random\n", + "import time\n", + "import math\n", + "from typing import List, Tuple, Union, Dict, Optional\n", + "from decimal import Decimal, getcontext, ROUND_DOWN, ROUND_HALF_UP, InvalidOperation\n", + "import traceback\n", + "from collections import Counter \n", + "\n", + "# ===============================================\n", + "# 配置参数区域 (用户应在此处修改)\n", + "# ===============================================\n", + "# --- 主要数量和文件名 ---\n", + "TOTAL_SAMPLES = 500 \n", + "OUTPUT_FILENAME = f\"X_ch_en_mix_test_v2.jsonl\" \n", + "BUFFER_WRITE_SIZE = 10000 \n", + "\n", + "# --- 数字生成控制 ---\n", + "# -- 针对系数 'a' --\n", + "MAX_DIGITS: int = 11 \n", + "MAX_DECIMAL_PLACES: int = 5 \n", + "DECIMAL_PROBABILITY: float = 0.30 \n", + "NEGATIVE_POOL_PROB: float = 0.30 \n", + "\n", + "# -- 针对目标 'x' --\n", + "X_DECIMAL_PROBABILITY: float = 0.50 \n", + "X_MAX_DECIMAL_PLACES: int = 5 \n", + "\n", + "# --- 格式化控制 (问题部分:方程字符串) ---\n", + "# -- 数字表示法概率 (总和应为 1.0) --\n", + "STANDARD_ARABIC_PROB: float = 0.20 \n", + "FULL_WIDTH_ARABIC_PROB: float = 0.10 \n", + "SIMPLE_CHINESE_PROB: float = 0.25 \n", + "COMPLEX_CHINESE_PROB: float = 0.20 \n", + "ENGLISH_WORDS_PROB: float = 0.25 # 新增英文单词格式概率\n", + "_format_prob_sum = (STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB + \n", + " SIMPLE_CHINESE_PROB + COMPLEX_CHINESE_PROB + ENGLISH_WORDS_PROB)\n", + "if not math.isclose(_format_prob_sum, 1.0):\n", + " raise ValueError(f\"数字格式概率总和必须为 1.0,当前为: {_format_prob_sum}\")\n", + "\n", + "# -- 字符级别混合概率 (仅适用于非英文格式) --\n", + "CHAR_MIX_PROBABILITY: float = 0.25 \n", + "\n", + "# -- English Number Casing Control (仅适用于英文格式) --\n", + "ENGLISH_NUMBER_ENTIRE_STRING_CASE_PROB: float = 0.8 # 80% 逐词独立风格, 20% 逐字符\n", + "\n", + "# -- 间距控制 --\n", + "ZERO_SPACE_PROB: float = 0.90 \n", + "MAX_RANDOM_SPACES: int = 2 \n", + "\n", + "# -- 方程结尾提问短语列表 (保持中文,可按需修改为英文) --\n", + "EQUATION_QUESTION_PROMPTS: List[str] = [\n", + " \", x = ?\", \", x=?\", \", x=?\", \", x = ?\", \", x 等于多少?\", \", x 等于多少?\",\n", + " \", 求 x。\", \", 求 x 的值。\", \", x 的值是?\", \", 请问 x 是多少?\", \", 计算 x。\", \", 求解 x。\"\n", + "]\n", + "# 如果需要英文提问短语:\n", + "# ENGLISH_QUESTION_PROMPTS: List[str] = [\n", + "# \", what is x?\", \", x = ?\", \", solve for x.\", \", find x.\", \", calculate x.\"\n", + "# ]\n", + "\n", + "# --- 其他控制 ---\n", + "EQUATION_X_POOL_SIZE = 1000 \n", + "MAX_ATTEMPTS_FACTOR = 100 \n", + "SCI_THRESHOLD_POS_EQ = 10**7 # For English scientific notation in equations (if ever needed)\n", + "SCI_THRESHOLD_NEG_EQ = -6 # For English scientific notation in equations\n", + "\n", + "# ===============================================\n", + "# 核心代码\n", + "# ===============================================\n", + "\n", + "getcontext().prec = MAX_DIGITS + max(MAX_DECIMAL_PLACES, X_MAX_DECIMAL_PLACES) + 30\n", + "\n", + "# --- 中文数字转换函数 (保留) ---\n", + "digit_map_simple = {'0': '零', '1': '一', '2': '二', '3': '三', '4': '四', '5': '五', '6': '六', '7': '七', '8': '八', '9': '九'}\n", + "unit_map_section_simple = ['', '十', '百', '千']\n", + "unit_map_large_simple = ['', '万', '亿', '兆']\n", + "digit_map_complex = {'0': '零', '1': '壹', '2': '贰', '3': '叁', '4': '肆', '5': '伍', '6': '陆', '7': '柒', '8': '捌', '9': '玖'}\n", + "unit_map_section_complex = ['', '拾', '佰', '仟']\n", + "unit_map_large_complex = ['', '萬', '億', '兆']\n", + "CHINESE_UNITS = set(\n", + " [u for u in unit_map_section_simple if u] + [u for u in unit_map_large_simple if u] +\n", + " [u for u in unit_map_section_complex if u] + [u for u in unit_map_large_complex if u]\n", + ")\n", + "# ... (中文转换函数 _convert_section, num_to_chinese, decimal_to_chinese 原样保留) ...\n", + "def _convert_section(section_str: str, complex_form: bool = False) -> str:\n", + " digit_map = digit_map_complex if complex_form else digit_map_simple; unit_map_section = unit_map_section_complex if complex_form else unit_map_section_simple\n", + " if not section_str: return \"\"\n", + " try: section_int = int(section_str)\n", + " except ValueError: return \"无效输入\"\n", + " if section_int == 0: return digit_map['0']\n", + " chinese_s = \"\"; length = len(section_str); need_zero = False\n", + " for i in range(length):\n", + " digit = section_str[i]; place = length - 1 - i\n", + " if digit == '0': need_zero = True\n", + " else:\n", + " if need_zero and chinese_s and not chinese_s.endswith(digit_map['0']): chinese_s += digit_map['0']\n", + " need_zero = False; current_digit_chinese = \"\"\n", + " use_liang = False \n", + " if not complex_form and digit == '2': \n", + " is_potentially_liang = place >= 2 \n", + " is_leading_two_in_section = (i == 0) or all(d == '0' for d in section_str[:i]) \n", + " if is_potentially_liang and is_leading_two_in_section: use_liang = True\n", + " if use_liang and random.random() < 0.8: current_digit_chinese = '两' \n", + " else: current_digit_chinese = digit_map['2']\n", + " else: current_digit_chinese = digit_map[digit]\n", + " is_leading_one_in_ten_place = (not complex_form and digit == '1' and place == 1 and (i == 0 or all(d == '0' for d in section_str[:i])) and length > 1)\n", + " if is_leading_one_in_ten_place: chinese_s += unit_map_section[place] \n", + " else: chinese_s += current_digit_chinese + unit_map_section[place]\n", + " if chinese_s.endswith(digit_map['0']) and len(chinese_s) > len(digit_map['0']): chinese_s = chinese_s[:-1]\n", + " return chinese_s\n", + "\n", + "def num_to_chinese(num: int, complex_form: bool = False) -> str:\n", + " if not isinstance(num, int): return \"无效输入\"\n", + " digit_map = digit_map_complex if complex_form else digit_map_simple; unit_map_large = unit_map_large_complex if complex_form else unit_map_large_simple\n", + " if num == 0: return digit_map['0']\n", + " if num < 0: return (\"负\" if not complex_form else \"负\") + num_to_chinese(abs(num), complex_form)\n", + " s_num = str(num); result = \"\"; sections = []\n", + " while len(s_num) > 0: sections.append(s_num[-4:]); s_num = s_num[:-4]\n", + " zero_padding_needed = False; last_section_was_zero = True; last_section_non_zero = False\n", + " for i in range(len(sections) - 1, -1, -1): \n", + " section = sections[i];\n", + " try: section_int = int(section)\n", + " except ValueError: return \"无效输入\"\n", + " if section_int == 0: \n", + " if i > 0 and last_section_non_zero: zero_padding_needed = True \n", + " last_section_was_zero = True; last_section_non_zero = False; continue\n", + " if zero_padding_needed: result += digit_map['0']; zero_padding_needed = False \n", + " section_chinese = _convert_section(section.lstrip('0'), complex_form) \n", + " if not section_chinese or section_chinese == \"无效输入\": return \"无效输入\" \n", + " is_single_two_and_has_large_unit = (not complex_form and section_chinese == \"两\" and len(section.lstrip('0'))==1 and i > 0)\n", + " if is_single_two_and_has_large_unit and random.random() < 0.1: result += \"二\"\n", + " else: result += section_chinese\n", + " last_section_was_zero = False; last_section_non_zero = True\n", + " if i > 0: result += unit_map_large[i] \n", + " if result.endswith(digit_map['0']) and len(result) > len(digit_map['0']): result = result[:-1]\n", + " if not complex_form and result.startswith('一十') and len(result) > 1: result = result[1:]\n", + " return result\n", + "\n", + "def decimal_to_chinese(num: Decimal, complex_form: bool = False) -> str:\n", + " if not isinstance(num, Decimal): return \"无效输入\"\n", + " if not num.is_finite(): return \"无效输入\" \n", + " digit_map = digit_map_complex if complex_form else digit_map_simple\n", + " try: is_integer = (num == num.to_integral_value(rounding=ROUND_DOWN))\n", + " except Exception: is_integer = False \n", + " if is_integer:\n", + " try:\n", + " int_val = num.to_integral_value(rounding=ROUND_DOWN)\n", + " # Increased limit for very large integers if needed for some edge cases\n", + " # but MAX_DIGITS should generally keep this in check for 'a' and 'b'\n", + " if abs(int_val) < Decimal(10**(MAX_DIGITS + 5)): return num_to_chinese(int(int_val), complex_form)\n", + " else: return \"数字过大无法转换\"\n", + " except (ValueError, TypeError, OverflowError, InvalidOperation): return \"无效输入或溢出\"\n", + " if num < 0: return (\"负\" if not complex_form else \"负\") + decimal_to_chinese(abs(num), complex_form)\n", + " try: s_num = \"{:f}\".format(num.normalize()) \n", + " except Exception: return \"无效输入\" \n", + " if '.' not in s_num: \n", + " try:\n", + " int_val_dec = Decimal(s_num)\n", + " if abs(int_val_dec) < Decimal(10**(MAX_DIGITS + 5)): return num_to_chinese(int(int_val_dec), complex_form)\n", + " else: return \"数字过大无法转换\"\n", + " except (ValueError, TypeError, OverflowError, InvalidOperation): return \"无效输入或溢出\"\n", + " integer_part_str, fractional_part_str = s_num.split('.')\n", + " if integer_part_str == '0': chinese_int = digit_map['0']\n", + " else:\n", + " try:\n", + " int_val_dec = Decimal(integer_part_str)\n", + " if abs(int_val_dec) < Decimal(10**(MAX_DIGITS + 5)):\n", + " chinese_int = num_to_chinese(int(int_val_dec), complex_form)\n", + " if not chinese_int or chinese_int == \"无效输入\": return \"无效输入\" \n", + " else: return \"数字过大无法转换\"\n", + " except (ValueError, TypeError, OverflowError, InvalidOperation): return \"无效输入或溢出\"\n", + " chinese_frac = \"\".join(digit_map.get(digit, '?') for digit in fractional_part_str) \n", + " point_word = \"点\" \n", + " return f\"{chinese_int}{point_word}{chinese_frac}\"\n", + "\n", + "\n", + "# --- 英文数字转换函数 (从 v10.15 复制) ---\n", + "_ENGLISH_DIGITS = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"]\n", + "_ENGLISH_TEENS = [\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\n", + "_ENGLISH_TENS = [\"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\n", + "_ENGLISH_LARGE_UNITS = [\"\", \"thousand\", \"million\", \"billion\", \"trillion\"] # Reduced for typical equation numbers\n", + "\n", + "def _num_to_english_chunk_eq(n: int) -> str: # Renamed to avoid conflict if other script parts are merged\n", + " if not 0 <= n <= 999: return \"\"\n", + " if n == 0: return \"\"\n", + " parts = []\n", + " if n >= 100:\n", + " parts.append(_ENGLISH_DIGITS[n // 100])\n", + " parts.append(\"hundred\")\n", + " n %= 100\n", + " if n > 0:\n", + " if 0 < n < 10: parts.append(_ENGLISH_DIGITS[n])\n", + " elif 10 <= n < 20: parts.append(_ENGLISH_TEENS[n - 10])\n", + " else:\n", + " parts.append(_ENGLISH_TENS[n // 10])\n", + " if n % 10 > 0: parts.append(_ENGLISH_DIGITS[n % 10])\n", + " return \" \".join(parts)\n", + "\n", + "def integer_to_english_words_eq(num: int) -> str:\n", + " if num == 0: return _ENGLISH_DIGITS[0]\n", + " # Adjust limit based on reduced _ENGLISH_LARGE_UNITS for equations\n", + " if abs(num) > (10**(len(_ENGLISH_LARGE_UNITS) * 3) -1) :\n", + " return f\"Num too large for Eng words ({num})\" # Simpler error\n", + " sign = \"minus \" if num < 0 else \"\" \n", + " num_abs = abs(num)\n", + " parts = []\n", + " chunk_index = 0\n", + " if num_abs == 0: return _ENGLISH_DIGITS[0] \n", + " temp_num = num_abs\n", + " while temp_num > 0:\n", + " if temp_num % 1000 != 0:\n", + " chunk_words = _num_to_english_chunk_eq(temp_num % 1000)\n", + " unit_word = _ENGLISH_LARGE_UNITS[chunk_index] if chunk_index > 0 else \"\"\n", + " if unit_word: parts.append(unit_word)\n", + " if chunk_words: parts.append(chunk_words) # Ensure chunk_words is not empty\n", + " temp_num //= 1000\n", + " chunk_index += 1\n", + " if chunk_index >= len(_ENGLISH_LARGE_UNITS) and temp_num > 0:\n", + " return f\"Num too large for Eng units ({temp_num})\"\n", + " result_words = \" \".join(p for p in reversed(parts) if p).strip() \n", + " return (sign + result_words).strip()\n", + "\n", + "def decimal_to_english_words_eq(num: Decimal) -> str:\n", + " if not isinstance(num, Decimal) or not num.is_finite():\n", + " return \"Invalid num for Eng conv\"\n", + " if num.is_zero() and num.is_signed(): num = Decimal('0')\n", + " sign_str = \"\"\n", + " num_abs_for_words = abs(num)\n", + " if num < 0: sign_str = \"minus \"\n", + " int_part_val = int(num_abs_for_words.to_integral_value(rounding=ROUND_DOWN))\n", + " frac_part_dec = num_abs_for_words - Decimal(int_part_val)\n", + " int_words = integer_to_english_words_eq(int_part_val)\n", + " if frac_part_dec.is_zero():\n", + " return (sign_str + int_words).strip()\n", + " s_num_abs_for_frac = format_decimal_or_int(num_abs_for_words) # Uses shared helper\n", + " if '.' not in s_num_abs_for_frac:\n", + " return (sign_str + int_words).strip() \n", + " _, frac_str_digits = s_num_abs_for_frac.split('.', 1)\n", + " frac_word_list = []\n", + " if frac_str_digits:\n", + " for digit_char in frac_str_digits:\n", + " if digit_char.isdigit(): frac_word_list.append(_ENGLISH_DIGITS[int(digit_char)])\n", + " if not frac_word_list:\n", + " return (sign_str + int_words).strip()\n", + " point_word_raw = \"point\" \n", + " final_assembly_parts = [int_words] \n", + " if point_word_raw: final_assembly_parts.append(point_word_raw)\n", + " if frac_word_list: final_assembly_parts.extend(frac_word_list)\n", + " assembled_num_words = \" \".join(p for p in final_assembly_parts if p)\n", + " return (sign_str + assembled_num_words).strip()\n", + "\n", + "def decimal_to_english_scientific_eq(num: Decimal) -> str:\n", + " if not isinstance(num, Decimal) or not num.is_finite():\n", + " return \"Invalid num for Eng sci conv\"\n", + " if num.is_zero(): return _ENGLISH_DIGITS[0]\n", + " raw_word_parts = []\n", + " if num < 0:\n", + " raw_word_parts.append(\"minus\")\n", + " num = abs(num)\n", + " try:\n", + " sci_str = \"{:e}\".format(num.normalize()) \n", + " coeff_str, exp_str = sci_str.lower().split('e')\n", + " coeff_dec = Decimal(coeff_str); exp_int = int(exp_str)\n", + " coeff_english_raw = decimal_to_english_words_eq(coeff_dec) \n", + " exp_english_raw = integer_to_english_words_eq(exp_int)\n", + " raw_word_parts.extend(coeff_english_raw.split())\n", + " raw_word_parts.append(\"times\"); raw_word_parts.append(\"ten\")\n", + " raw_word_parts.extend(\"to the power of\".split())\n", + " raw_word_parts.extend(exp_english_raw.split())\n", + " return \" \".join(p for p in raw_word_parts if p)\n", + " except Exception:\n", + " return format_decimal_or_int(num)\n", + "\n", + "\n", + "# --- 英文大小写处理函数 (从 v10.15 复制) ---\n", + "def _apply_random_word_case_style(word: str) -> str:\n", + " if not word or not any(c.isalpha() for c in word): return word\n", + " style_choice = random.random()\n", + " if style_choice < 0.4: return word.lower()\n", + " elif style_choice < 0.8: return word.upper()\n", + " else: return word.capitalize()\n", + "\n", + "def _apply_independent_word_casing(text: str) -> str:\n", + " if not text or not any(c.isalpha() for c in text): return text\n", + " words = text.split(' ')\n", + " cased_words = [_apply_random_word_case_style(word) for word in words]\n", + " return \" \".join(cased_words)\n", + "\n", + "def _apply_random_case_char_by_char(text: str) -> str:\n", + " if not text or not any(c.isalpha() for c in text): return text\n", + " return \"\".join(random.choice([char.lower(), char.upper()]) if char.isalpha() else char for char in text)\n", + "\n", + "def _apply_random_case_number_style_eq(text: str) -> str: # Renamed for clarity\n", + " if not text or not any(c.isalpha() for c in text): return text\n", + " if random.random() < ENGLISH_NUMBER_ENTIRE_STRING_CASE_PROB:\n", + " return _apply_independent_word_casing(text) \n", + " else:\n", + " return _apply_random_case_char_by_char(text)\n", + "\n", + "# _apply_random_case_operator_style might be needed if operators/prompts become English\n", + "# def _apply_random_case_operator_style_eq(text: str) -> str:\n", + "# if not text or not any(c.isalpha() for c in text): return text\n", + "# return _apply_independent_word_casing(text) \n", + "\n", + "# --- 全角转换 (保留) ---\n", + "half_to_full_map = str.maketrans(\"0123456789.-+\", \"0123456789.-+\")\n", + "def to_full_width(text: str) -> str: return text.translate(half_to_full_map)\n", + "\n", + "# --- 格式化数字变体 (核心修改处) ---\n", + "def format_number_variant(num: Union[int, Decimal]) -> str:\n", + " # This function now incorporates English words and their casing.\n", + " # It also retains the Chinese/Arabic formats and char_mixing for them.\n", + " try:\n", + " num_dec = Decimal(str(num)) if not isinstance(num, Decimal) else num\n", + " except InvalidOperation:\n", + " return str(num) \n", + "\n", + " base_format_str = \"\"\n", + " chosen_format_type = \"\" # To track if English was chosen, for skipping char_mix\n", + " fmt_choice_roll = random.random()\n", + "\n", + " # 1. Determine Base Format String (Arabic, Full-width, Chinese, or English)\n", + " if fmt_choice_roll < STANDARD_ARABIC_PROB:\n", + " base_format_str = format_decimal_or_int(num_dec)\n", + " chosen_format_type = \"arabic\"\n", + " elif fmt_choice_roll < STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB:\n", + " base_format_str = to_full_width(format_decimal_or_int(num_dec))\n", + " chosen_format_type = \"full_width_arabic\"\n", + " elif fmt_choice_roll < STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB + SIMPLE_CHINESE_PROB:\n", + " base_format_str = decimal_to_chinese(num_dec, complex_form=False)\n", + " chosen_format_type = \"simple_chinese\"\n", + " if \"无效\" in base_format_str or \"过大\" in base_format_str: # Fallback for Chinese\n", + " base_format_str = format_decimal_or_int(num_dec)\n", + " chosen_format_type = \"arabic_fallback\"\n", + " elif fmt_choice_roll < STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB + SIMPLE_CHINESE_PROB + COMPLEX_CHINESE_PROB:\n", + " base_format_str = decimal_to_chinese(num_dec, complex_form=True)\n", + " chosen_format_type = \"complex_chinese\"\n", + " if \"无效\" in base_format_str or \"过大\" in base_format_str: # Fallback for Chinese\n", + " base_format_str = format_decimal_or_int(num_dec)\n", + " chosen_format_type = \"arabic_fallback\"\n", + " else: # ENGLISH_WORDS_PROB\n", + " chosen_format_type = \"english\"\n", + " # For equations, numbers are usually not extremely large/small to need scientific\n", + " # but we can add a simplified check if needed.\n", + " # exponent = num_dec.normalize().adjusted()\n", + " # use_sci_english = (exponent >= math.log10(SCI_THRESHOLD_POS_EQ) if SCI_THRESHOLD_POS_EQ > 0 else False) or \\\n", + " # (exponent <= SCI_THRESHOLD_NEG_EQ if SCI_THRESHOLD_NEG_EQ != 0 else False)\n", + " # if use_sci_english:\n", + " # raw_english = decimal_to_english_scientific_eq(num_dec)\n", + " # else:\n", + " raw_english = decimal_to_english_words_eq(num_dec)\n", + "\n", + " if \"Invalid\" in raw_english or \"too large\" in raw_english or \"Num\" in raw_english : # Fallback for English\n", + " base_format_str = format_decimal_or_int(num_dec)\n", + " chosen_format_type = \"arabic_fallback\" # Mark as fallback, will skip char_mix\n", + " else:\n", + " base_format_str = _apply_random_case_number_style_eq(raw_english)\n", + " # English is fully processed here, no further char mixing needed.\n", + "\n", + " # If English was chosen and successfully formatted, or if char mixing is off, return\n", + " if chosen_format_type == \"english\" or chosen_format_type == \"arabic_fallback\" or not CHAR_MIX_PROBABILITY > 0:\n", + " return base_format_str\n", + "\n", + " # 2. Character-by-Character Mixing Pass (Only for non-English types if enabled)\n", + " mixed_chars = []\n", + " simple_chinese_to_arabic_digit = {v: k for k, v in digit_map_simple.items() if k.isdigit()}\n", + " complex_chinese_to_arabic_digit = {v: k for k, v in digit_map_complex.items() if k.isdigit()}\n", + " full_width_to_std_arabic_digit = {to_full_width(k): k for k in \"0123456789\"}\n", + "\n", + " for char_original in base_format_str:\n", + " current_char_output = char_original\n", + " if char_original in CHINESE_UNITS:\n", + " mixed_chars.append(current_char_output); continue\n", + " if random.random() < CHAR_MIX_PROBABILITY:\n", + " swapped_char = \"\"\n", + " if '0' <= char_original <= '9': # Standard Arabic\n", + " options = [to_full_width(char_original), digit_map_simple.get(char_original, ''), digit_map_complex.get(char_original, '')]\n", + " elif char_original in full_width_to_std_arabic_digit: # Full-width\n", + " std_digit = full_width_to_std_arabic_digit[char_original]\n", + " options = [std_digit, digit_map_simple.get(std_digit, ''), digit_map_complex.get(std_digit, '')]\n", + " elif char_original in simple_chinese_to_arabic_digit: # Simple Chinese\n", + " std_digit = simple_chinese_to_arabic_digit[char_original]\n", + " options = [std_digit, to_full_width(std_digit), digit_map_complex.get(std_digit, '')]\n", + " elif char_original in complex_chinese_to_arabic_digit: # Complex Chinese\n", + " std_digit = complex_chinese_to_arabic_digit[char_original]\n", + " options = [std_digit, to_full_width(std_digit), digit_map_simple.get(std_digit, '')]\n", + " elif char_original == '.': options = ['.', '点']\n", + " elif char_original == '.': options = ['.', '点']\n", + " elif char_original == '点': options = ['.', '.']\n", + " elif char_original == '-': options = ['-', '负']\n", + " elif char_original == '-': options = ['-', '负']\n", + " elif char_original == '负': options = ['-', '-']\n", + " elif char_original == '+': options = ['+', '正']\n", + " elif char_original == '+': options = ['+', '正']\n", + " elif char_original == '正': options = ['+', '+']\n", + " else: options = []\n", + " \n", + " valid_options = [opt for opt in options if opt]\n", + " if valid_options: swapped_char = random.choice(valid_options)\n", + " if swapped_char: current_char_output = swapped_char\n", + " mixed_chars.append(current_char_output)\n", + " return \"\".join(mixed_chars)\n", + "\n", + "# --- 获取随机间距 ---\n", + "def get_random_spacing() -> str:\n", + " if random.random() < ZERO_SPACE_PROB: return \"\"\n", + " else: return \" \" * random.randint(1, MAX_RANDOM_SPACES)\n", + "\n", + "# --- 辅助函数 (保留) ---\n", + "def format_decimal_or_int(num: Union[int, Decimal]) -> str:\n", + " try:\n", + " if isinstance(num, int): return str(num)\n", + " if isinstance(num, Decimal):\n", + " if not num.is_finite(): return str(num) \n", + " # Normalize -0 to 0\n", + " num_norm = num.normalize()\n", + " if num_norm.is_zero() and num_norm.is_signed():\n", + " num_norm = Decimal('0')\n", + " s = \"{:f}\".format(num_norm) # Use :f to avoid sci notation for reasonable numbers\n", + " if '.' in s:\n", + " integer_part, decimal_part = s.split('.', 1)\n", + " decimal_part = decimal_part.rstrip('0')\n", + " if not decimal_part: # e.g., \"1.00\" -> \"1\"\n", + " s = integer_part\n", + " else:\n", + " s = integer_part + \".\" + decimal_part\n", + " return s\n", + " return str(num) \n", + " except Exception:\n", + " return str(num) # Fallback\n", + "\n", + "\n", + "def get_distributed_count_from_probs(population: List[int], probabilities: List[float]) -> int:\n", + " if not population: return 1 \n", + " if not probabilities or len(population) != len(probabilities) or not all(p >= 0 for p in probabilities):\n", + " return random.choice(population) if population else 1\n", + "\n", + " prob_sum = sum(probabilities)\n", + " if prob_sum < 1e-9: \n", + " return random.choice(population) if population else 1\n", + "\n", + " normalized_probabilities = probabilities\n", + " if not math.isclose(prob_sum, 1.0, abs_tol=1e-5): \n", + " try:\n", + " normalized_probabilities = [p / prob_sum for p in probabilities]\n", + " except ZeroDivisionError: \n", + " return random.choice(population) if population else 1\n", + " try:\n", + " return random.choices(population, weights=normalized_probabilities, k=1)[0]\n", + " except Exception: \n", + " return random.choice(population) if population else 1\n", + "\n", + "\n", + "def calculate_digit_probabilities(max_digits: int) -> Dict[int, float]:\n", + " if max_digits <= 0: return {1: 1.0} \n", + " raw_probs = {}; prob_sum = Decimal('0.0'); base_prob = Decimal('0.1'); decay_factor = Decimal('0.95'); increase_factor = Decimal('1.05') \n", + " for n in range(1, max_digits + 1):\n", + " prob = base_prob * (decay_factor**(n - 1)) * (increase_factor**(n-1)) \n", + " prob = max(Decimal('0.01'), prob) \n", + " raw_probs[n] = prob; prob_sum += prob\n", + " normalized_probs = {}\n", + " if prob_sum <= 0: \n", + " fallback_prob = 1.0 / max(1, max_digits)\n", + " normalized_probs = {n: fallback_prob for n in range(1, max_digits + 1)}\n", + " else:\n", + " normalized_probs = {n: float(p / prob_sum) for n, p in raw_probs.items()}\n", + " final_sum = sum(normalized_probs.values())\n", + " if not math.isclose(final_sum, 1.0, abs_tol=1e-9):\n", + " renorm_factor = 1.0 / final_sum if final_sum != 0 else 1.0\n", + " total = 0.0; keys = sorted(normalized_probs.keys()) \n", + " for i, k_n in enumerate(keys): # Renamed n to k_n to avoid conflict\n", + " if i == len(keys) - 1: \n", + " normalized_probs[k_n] = max(0.0, 1.0 - total)\n", + " else:\n", + " normalized_probs[k_n] = max(0.0, normalized_probs[k_n] * renorm_factor)\n", + " total += normalized_probs[k_n]\n", + " return normalized_probs\n", + "\n", + "def _generate_positive_integer_with_digits(num_digits: int) -> int:\n", + " if num_digits <= 0: num_digits = 1 \n", + " if num_digits == 1: min_val, max_val = 0, 9 \n", + " else: min_val = 10**(num_digits - 1); max_val = 10**num_digits - 1\n", + " if min_val > max_val: return max_val \n", + " try: return random.randint(min_val, max_val)\n", + " except ValueError: return max_val\n", + "\n", + "\n", + "# --- 文件写入辅助函数 ---\n", + "def write_buffer_to_file(filename: str, buffer: List[str]):\n", + " if not buffer: return\n", + " try:\n", + " with open(filename, 'a', encoding='utf-8') as f:\n", + " f.write('\\n'.join(buffer) + '\\n')\n", + " except IOError as e: print(f\"\\n错误:写入文件 '{filename}' 时发生 IO 错误: {e}\"); traceback.print_exc()\n", + " except Exception as e: print(f\"\\n错误:写入文件时发生未知错误: {e}\"); traceback.print_exc()\n", + "\n", + "# --- 主要生成函数 ---\n", + "def generate_equations_diverse_format_buffered(\n", + " filename: str, total_samples: int,\n", + " decimal_prob_a: float, max_digits_a: int, max_decimal_places_a: int, negative_prob_a: float,\n", + " decimal_prob_x: float, max_decimal_places_x: int,\n", + " buffer_write_size: int, max_attempts_factor: int):\n", + " # ... (Initialization largely unchanged, messages updated) ...\n", + " if total_samples <= 0: print(\"警告:total_samples 必须大于 0。\"); return\n", + " if buffer_write_size <= 0: print(\"警告:BUFFER_WRITE_SIZE 必须大于 0,设置为 1。\"); buffer_write_size = 1\n", + " if not EQUATION_QUESTION_PROMPTS: print(\"警告:EQUATION_QUESTION_PROMPTS 列表为空,将不添加结尾提问。\")\n", + "\n", + " print(f\"--- 开始生成格式多样化(含英文、字符级混合)、带提问和解题过程(x可为小数)的解方程数据 ---\")\n", + " print(f\"输出文件: {filename}\")\n", + " print(f\"目标样本数: {total_samples:,}\")\n", + " print(f\"A的配置: 最大整数位数={max_digits_a}, 最大小数位数={max_decimal_places_a}, 小数概率={decimal_prob_a:.1%}, 负数概率={negative_prob_a:.1%}\")\n", + " print(f\"X的配置: 最大整数位数={max_digits_a} (同A), 最大小数位数={max_decimal_places_x}, 小数概率={decimal_prob_x:.1%}\")\n", + " print(f\"问题格式: 基础数字格式随机(标:{STANDARD_ARABIC_PROB:.1%}, 全:{FULL_WIDTH_ARABIC_PROB:.1%}, 简:{SIMPLE_CHINESE_PROB:.1%}, 繁:{COMPLEX_CHINESE_PROB:.1%}, 英:{ENGLISH_WORDS_PROB:.1%})\")\n", + " print(f\" 字符级混合概率 (非英文): {CHAR_MIX_PROBABILITY:.1%}\")\n", + " print(f\" 英文数字大小写: {ENGLISH_NUMBER_ENTIRE_STRING_CASE_PROB*100:.0f}% 逐词独立风格, {(1-ENGLISH_NUMBER_ENTIRE_STRING_CASE_PROB)*100:.0f}% 逐字符\")\n", + " print(f\" 随机间距(0空格:{ZERO_SPACE_PROB:.1%}), 结尾附加随机提问\")\n", + " print(f\"答案格式: Assistant 部分包含解题过程 (x = <计算步骤> = <答案x>),答案x为标准阿拉伯数字\")\n", + " \n", + " digit_pop: List[int] = []; digit_probs_list: List[float] = []\n", + " if max_digits_a > 0: \n", + " digit_probabilities_dict = calculate_digit_probabilities(max_digits_a)\n", + " digit_pop = list(range(1, max_digits_a + 1)); digit_probs_list = [digit_probabilities_dict.get(n, 0.0) for n in digit_pop]\n", + " if not math.isclose(sum(digit_probs_list), 1.0, abs_tol=1e-5): print(f\"警告: 位数概率列表和为 {sum(digit_probs_list):.4f}。\")\n", + " if not digit_probs_list and digit_pop: digit_pop = [1]; digit_probs_list = [1.0] \n", + " elif not digit_pop: digit_pop = [1]; digit_probs_list = [1.0]\n", + " else: \n", + " digit_pop = [1]; digit_probs_list = [1.0] \n", + "\n", + " base_x_pool = list(range(EQUATION_X_POOL_SIZE)); random.shuffle(base_x_pool)\n", + " repeats = math.ceil(total_samples / len(base_x_pool)) if base_x_pool else 1\n", + " equation_x_int_part_pool = (base_x_pool * repeats)[:total_samples]; random.shuffle(equation_x_int_part_pool)\n", + " additional_needed = total_samples - len(equation_x_int_part_pool)\n", + " if additional_needed > 0:\n", + " print(f\"信息: x 整数部分池不足 {total_samples}, 补充 {additional_needed} 个随机 x 整数部分。\")\n", + " max_x_int_val = 10**max_digits_a -1 if max_digits_a > 0 else 0\n", + " min_x_int_val = -(10**max_digits_a -1) if max_digits_a > 0 else 0\n", + " actual_min_x_int = min(min_x_int_val, max_x_int_val) \n", + " actual_max_x_int = max(min_x_int_val, max_x_int_val)\n", + " for _ in range(additional_needed):\n", + " equation_x_int_part_pool.append(random.randint(actual_min_x_int, actual_max_x_int))\n", + " random.shuffle(equation_x_int_part_pool)\n", + "\n", + " generated_count = 0; total_attempts = 0; errors_in_loop = 0; lines_written_total = 0\n", + " max_total_attempts = total_samples * max(10, max_attempts_factor)\n", + " start_time_generate = time.time()\n", + " write_buffer: List[str] = []\n", + " print(f\"\\n开始生成 {total_samples:,} 条数据 (缓冲写入)...\")\n", + " last_reported_count = -1\n", + "\n", + " try:\n", + " with open(filename, 'w', encoding='utf-8') as f: f.write(\"\")\n", + " except IOError as e: print(f\"\\n错误:无法初始化输出文件 '{filename}': {e}\"); return\n", + "\n", + " while generated_count < total_samples:\n", + " total_attempts += 1\n", + " if total_attempts > max_total_attempts:\n", + " print(f\"\\n\\n警告: 尝试次数达到上限 ({total_attempts:,}) 仍未生成 {total_samples:,} 条数据。\")\n", + " print(f\"当前已生成: {generated_count:,} 条。脚本提前终止。\")\n", + " break\n", + " if not equation_x_int_part_pool: print(\"\\n错误: x 整数部分池意外耗尽。\"); break\n", + "\n", + " target_x_int_part = equation_x_int_part_pool.pop(0) \n", + "\n", + " try:\n", + " x_calc: Decimal \n", + " x_is_decimal_type = random.random() < decimal_prob_x \n", + " x_decimal_places_actual = 0 \n", + "\n", + " if x_is_decimal_type and max_decimal_places_x > 0:\n", + " x_decimal_places_actual = random.randint(1, max_decimal_places_x)\n", + " frac_x_val_abs = Decimal(random.randint(0, 10**x_decimal_places_actual - 1)) / (Decimal(10)**x_decimal_places_actual)\n", + " base_x_dec = Decimal(str(target_x_int_part))\n", + " if base_x_dec.is_zero() or base_x_dec > Decimal('0'): \n", + " x_calc = base_x_dec + frac_x_val_abs\n", + " else: \n", + " x_calc = base_x_dec - frac_x_val_abs\n", + " try:\n", + " x_calc = x_calc.quantize(Decimal(f\"1e-{x_decimal_places_actual}\"), rounding=ROUND_HALF_UP).normalize()\n", + " if x_calc.is_zero() and x_calc.is_signed(): x_calc = Decimal('0') \n", + " except InvalidOperation: \n", + " x_calc = Decimal(str(target_x_int_part)) \n", + " x_is_decimal_type = False \n", + " x_decimal_places_actual = 0 \n", + " else: \n", + " x_calc = Decimal(str(target_x_int_part))\n", + " x_is_decimal_type = False \n", + " x_decimal_places_actual = 0 \n", + "\n", + " struct = random.choice(['x_op_a', 'a_op_x']); eq_op = random.choice(['+', '-'])\n", + " a_digits_count = get_distributed_count_from_probs(digit_pop, digit_probs_list) \n", + " a_is_decimal_type = random.random() < decimal_prob_a \n", + " a_sign = -1 if random.random() < negative_prob_a else 1 \n", + " a_base_abs_val = _generate_positive_integer_with_digits(a_digits_count) \n", + " a_val_for_question: Union[int, Decimal] \n", + " a_decimal_places_actual = 0 \n", + "\n", + " if a_is_decimal_type and max_decimal_places_a > 0:\n", + " a_decimal_places_actual = random.randint(1, max_decimal_places_a)\n", + " frac_a_val = Decimal(random.randint(0, 10**a_decimal_places_actual - 1)) / (Decimal(10)**a_decimal_places_actual)\n", + " a_temp_decimal = Decimal(a_base_abs_val) + frac_a_val\n", + " a_val_for_question = a_temp_decimal * a_sign\n", + " try: \n", + " if not (a_val_for_question == a_val_for_question.to_integral_value()):\n", + " a_val_for_question = a_val_for_question.quantize(Decimal(f\"1e-{a_decimal_places_actual}\"), rounding=ROUND_HALF_UP).normalize()\n", + " else: \n", + " a_val_for_question = a_val_for_question.to_integral_value(rounding=ROUND_HALF_UP)\n", + " if isinstance(a_val_for_question, Decimal) and a_val_for_question.is_zero() and a_val_for_question.is_signed():\n", + " a_val_for_question = Decimal('0') \n", + " except InvalidOperation: \n", + " a_val_for_question = Decimal(a_base_abs_val * a_sign) \n", + " else: \n", + " a_val_for_question = a_base_abs_val * a_sign\n", + " \n", + " a_calc = Decimal(str(a_val_for_question)) \n", + "\n", + " b_val_calc: Decimal \n", + " if struct == 'x_op_a': \n", + " b_val_calc = x_calc + a_calc if eq_op == '+' else x_calc - a_calc\n", + " else: \n", + " b_val_calc = a_calc + x_calc if eq_op == '+' else a_calc - x_calc\n", + "\n", + " b_val_for_question: Union[int, Decimal] \n", + " is_b_effectively_integer = b_val_calc.is_finite() and \\\n", + " (b_val_calc == b_val_calc.to_integral_value(rounding=ROUND_DOWN))\n", + " \n", + " max_b_dp_from_inputs = 0\n", + " if a_is_decimal_type: max_b_dp_from_inputs = max(max_b_dp_from_inputs, a_decimal_places_actual)\n", + " if x_is_decimal_type: max_b_dp_from_inputs = max(max_b_dp_from_inputs, x_decimal_places_actual)\n", + " b_display_dp_cap = max(max_decimal_places_a, max_decimal_places_x)\n", + " \n", + " if is_b_effectively_integer: \n", + " try: b_val_for_question = int(b_val_calc.to_integral_value(rounding=ROUND_DOWN))\n", + " except (OverflowError, InvalidOperation): b_val_for_question = b_val_calc \n", + " elif b_val_calc.is_finite(): \n", + " b_decimal_places_to_show = min(max_b_dp_from_inputs, b_display_dp_cap)\n", + " b_decimal_places_to_show = max(0, b_decimal_places_to_show) \n", + " if b_decimal_places_to_show > 0 : \n", + " try:\n", + " b_val_for_question = b_val_calc.quantize(Decimal(f\"1e-{b_decimal_places_to_show}\"), rounding=ROUND_HALF_UP).normalize()\n", + " except InvalidOperation: b_val_for_question = b_val_calc \n", + " else: \n", + " try: b_val_for_question = int(b_val_calc.to_integral_value(rounding=ROUND_HALF_UP))\n", + " except (OverflowError, InvalidOperation): b_val_for_question = b_val_calc \n", + " if isinstance(b_val_for_question, Decimal) and b_val_for_question.is_zero() and b_val_for_question.is_signed():\n", + " b_val_for_question = Decimal('0')\n", + " else: \n", + " errors_in_loop += 1; continue \n", + "\n", + " answer_str = format_decimal_or_int(x_calc) \n", + " str_a_calc_solution = format_decimal_or_int(a_calc) \n", + " str_b_calc_solution_step = format_decimal_or_int(b_val_calc) \n", + " str_abs_a_calc_solution = format_decimal_or_int(abs(a_calc)) \n", + " \n", + " solution_intermediate_step = \"x = \" \n", + " if struct == 'x_op_a': \n", + " solution_intermediate_step += str_b_calc_solution_step \n", + " if eq_op == '+': \n", + " solution_intermediate_step += f\" - {str_a_calc_solution}\" if a_calc >= 0 else f\" + {str_abs_a_calc_solution}\"\n", + " else: \n", + " solution_intermediate_step += f\" + {str_a_calc_solution}\" if a_calc >= 0 else f\" - {str_abs_a_calc_solution}\"\n", + " elif struct == 'a_op_x': \n", + " if eq_op == '+': \n", + " solution_intermediate_step += str_b_calc_solution_step \n", + " solution_intermediate_step += f\" - {str_a_calc_solution}\" if a_calc >= 0 else f\" + {str_abs_a_calc_solution}\"\n", + " else: # a - x = b => x = a - b\n", + " solution_intermediate_step += str_a_calc_solution \n", + " solution_intermediate_step += f\" - {str_b_calc_solution_step}\" if b_val_calc >= 0 else f\" + {format_decimal_or_int(abs(b_val_calc))}\"\n", + " \n", + " assistant_response_str = f\"{solution_intermediate_step} = {answer_str}\" \n", + "\n", + " fmt_a_for_question = format_number_variant(a_val_for_question) \n", + " fmt_b_for_question = format_number_variant(b_val_for_question) \n", + "\n", + " current_op_display_in_question = eq_op \n", + " # Handle negative 'a' in \"x op a = b\" structure by changing operator and using abs(a)\n", + " if struct == 'x_op_a' and isinstance(a_val_for_question, (int, Decimal)) and a_val_for_question < 0:\n", + " # Check if fmt_a_for_question actually starts with a negative sign (e.g. not \"minus ...\")\n", + " # This logic is tricky if fmt_a_for_question is already in words \"minus...\"\n", + " # For simplicity, we'll assume format_number_variant on abs(a) is sufficient.\n", + " # The character mixing for '-' vs '负' in format_number_variant might also play a role.\n", + " # A robust way is to check if the *original* a_val_for_question was negative.\n", + " fmt_a_for_question = format_number_variant(abs(a_val_for_question)) \n", + " current_op_display_in_question = '-' if eq_op == '+' else '+' \n", + " \n", + " s = [get_random_spacing() for _ in range(4)]; parts = [] \n", + " if struct == 'x_op_a':\n", + " parts = ['x', s[0], current_op_display_in_question, s[1], fmt_a_for_question, s[2], '=', s[3], fmt_b_for_question]\n", + " else: # a op x = b\n", + " # If a is negative and not English words, we might want to avoid \"--\" or \"+-\"\n", + " # This can get complex with mixed formats. For now, keep it direct.\n", + " # Example: -5 + x = b -> 负五 + x = b or -FIVE + x = b\n", + " parts = [fmt_a_for_question, s[0], eq_op, s[1], 'x', s[2], '=', s[3], fmt_b_for_question]\n", + " base_question_str = \"\".join(parts) \n", + "\n", + " final_question_str = base_question_str\n", + " if EQUATION_QUESTION_PROMPTS: \n", + " chosen_prompt = random.choice(EQUATION_QUESTION_PROMPTS)\n", + " # If prompts were English and cased:\n", + " # chosen_prompt = _apply_random_case_operator_style_eq(random.choice(ENGLISH_QUESTION_PROMPTS))\n", + " final_question_str += get_random_spacing() + chosen_prompt \n", + " \n", + " text_content = f\"User: {final_question_str}\\n\\nAssistant: {assistant_response_str}\" \n", + "\n", + " try:\n", + " json_string = json.dumps({\"text\": text_content}, ensure_ascii=False)\n", + " if json_string and not json_string.isspace(): \n", + " write_buffer.append(json_string)\n", + " generated_count += 1\n", + " if len(write_buffer) >= buffer_write_size: \n", + " write_buffer_to_file(filename, write_buffer) \n", + " lines_written_total += len(write_buffer)\n", + " write_buffer = [] \n", + " else: print(f\"\\n警告: 生成了空的 JSON 字符串: {text_content}\"); errors_in_loop += 1\n", + " except Exception as dump_err: print(f\"\\n错误:序列化 JSON 时出错: {dump_err} for item: {text_content}\"); errors_in_loop += 1\n", + "\n", + " except KeyboardInterrupt: print(\"\\n接收到中断信号,停止生成...\"); break \n", + " except Exception as loop_err: print(f\"\\n处理样本时意外错误: {loop_err}\"); traceback.print_exc(); errors_in_loop += 1; continue \n", + "\n", + " report_interval = max(1, total_samples // 100) if total_samples > 0 else 1 \n", + " if generated_count > 0 and (generated_count % report_interval == 0 or last_reported_count != generated_count or generated_count == total_samples):\n", + " progress = generated_count / total_samples if total_samples > 0 else 0; elapsed_time = time.time() - start_time_generate\n", + " samples_per_sec = generated_count / elapsed_time if elapsed_time > 0 else 0\n", + " est_remaining_gen = float('inf') \n", + " if progress > 1e-6 and samples_per_sec > 0: est_remaining_gen = (total_samples - generated_count) / samples_per_sec\n", + " rem_time_str = f\"{est_remaining_gen:.1f}s\" if est_remaining_gen != float('inf') else \"N/A\"\n", + " print(f\"\\r进度: {generated_count:,}/{total_samples:,} ({progress:.1%}) | 已写入: {lines_written_total:,} | {samples_per_sec:.1f} 条/秒 | 耗时:{elapsed_time:.1f}s | 剩余:~{rem_time_str} \", end=\"\")\n", + " last_reported_count = generated_count\n", + "\n", + " print(\" \" * 130, end=\"\\r\"); print() \n", + "\n", + " if write_buffer:\n", + " print(f\"\\n[写入最后 {len(write_buffer)} 条数据...]\")\n", + " write_buffer_to_file(filename, write_buffer)\n", + " lines_written_total += len(write_buffer)\n", + " write_buffer = []\n", + "\n", + " end_generate = time.time(); total_gen_time = end_generate - start_time_generate\n", + " print(f\"\\n生成与写入完毕。目标样本: {total_samples:,} -> 实际生成: {generated_count:,} -> 写入文件: {lines_written_total:,}\")\n", + " print(f\"总耗时: {total_gen_time:.2f} 秒。循环/写入错误数: {errors_in_loop:,}。\")\n", + "\n", + "# ===============================================\n", + "# 主程序入口\n", + "# ===============================================\n", + "if __name__ == \"__main__\":\n", + " total_start_time = time.time()\n", + " print(\"=\"*30); print(\" 解方程数据生成脚本 (v1.15 - 含英文格式) \"); print(\"=\"*30)\n", + " if TOTAL_SAMPLES < EQUATION_X_POOL_SIZE: print(f\"提示: TOTAL_SAMPLES ({TOTAL_SAMPLES}) < X_POOL_SIZE ({EQUATION_X_POOL_SIZE}), 可能无法完全覆盖 x整数部分 0-{EQUATION_X_POOL_SIZE-1}。\")\n", + "\n", + " try:\n", + " generate_equations_diverse_format_buffered(\n", + " filename=OUTPUT_FILENAME,\n", + " total_samples=TOTAL_SAMPLES,\n", + " decimal_prob_a=DECIMAL_PROBABILITY,\n", + " max_digits_a=MAX_DIGITS,\n", + " max_decimal_places_a=MAX_DECIMAL_PLACES,\n", + " negative_prob_a=NEGATIVE_POOL_PROB,\n", + " decimal_prob_x=X_DECIMAL_PROBABILITY,\n", + " max_decimal_places_x=X_MAX_DECIMAL_PLACES,\n", + " buffer_write_size=BUFFER_WRITE_SIZE,\n", + " max_attempts_factor=MAX_ATTEMPTS_FACTOR\n", + " )\n", + " except ValueError as ve: print(f\"\\n配置错误: {ve}\")\n", + " except Exception as main_e: print(f\"\\n生成数据过程中发生未捕获的主错误: {main_e}\"); traceback.print_exc()\n", + " finally: pass \n", + "\n", + " total_end_time = time.time()\n", + " print(\"\\n\" + \"=\"*30); print(f\"脚本执行完毕。总耗时: {total_end_time - total_start_time:.2f} 秒。\"); print(f\"数据文件: {OUTPUT_FILENAME}\"); print(\"=\"*30)" + ] + }, + { + "cell_type": "markdown", + "id": "6c00b6ac", + "metadata": {}, + "source": [ + "# 逐位随机英文解方程\n", + "\n", + "用于生成:\n", + "\n", + "训练集:X_en_random_mix\n", + "\n", + "测试集:X_en_mix_test" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6c00b6ac", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "==============================\n", + " Equation Solver Data Generation Script (v1.16 - English Only) \n", + "==============================\n", + "--- Starting generation of equation data (English only formats) ---\n", + "Output file: qa_解方程_英文大小写混合.jsonl\n", + "Target samples: 1,000,000\n", + "Config for 'a': Max int D=11, Max dec P=5, Dec prob=30.0%, Neg prob=30.0%\n", + "Config for 'x': Max int D=11, Max dec P=5, Dec prob=50.0%\n", + "Number formats: Standard Arabic (40.0%), Full-width (20.0%), English Words (40.0%)\n", + "English casing: 80% independent word style, 20% char-by-char\n", + "Operator words (e.g., 'plus'): 30.0% probability\n", + "Spacing: Zero space prob (90.0%), English question prompts appended.\n", + "Answer format: Assistant includes solution steps (x = ... = answer_x), answer_x is standard Arabic.\n", + "\n", + "Generating 1,000,000 samples (buffered write)...\n", + "Progress: 1,000,000/1,000,000 (100.0%) | Written: 1,000,000 | 3696.6 eq/s | Elapsed:270.5s | ETA:~0.0s \n", + "\n", + "Generation and writing complete. Target: 1,000,000 -> Generated: 1,000,000 -> Written: 1,000,000\n", + "Total time: 270.52 seconds. Errors in loop/write: 0.\n", + "\n", + "==============================\n", + "Script finished. Total execution time: 270.82 seconds.\n", + "Data file: qa_解方程_英文大小写混合.jsonl\n", + "==============================\n" + ] + } + ], + "source": [ + "# -*- coding: utf-8 -*-\n", + "# 这是一个用于生成解一元一次方程问题数据集的 Python 脚本。\n", + "# v1.16: Removed all Chinese number formatting. Uses Arabic, Full-width Arabic, and English words.\n", + "# English question prompts and operators with random casing.\n", + "\n", + "import json\n", + "import random\n", + "import time\n", + "import math\n", + "from typing import List, Tuple, Union, Dict, Optional\n", + "from decimal import Decimal, getcontext, ROUND_DOWN, ROUND_HALF_UP, InvalidOperation\n", + "import traceback\n", + "from collections import Counter \n", + "\n", + "# ===============================================\n", + "# 配置参数区域 (用户应在此处修改)\n", + "# ===============================================\n", + "# --- 主要数量和文件名 ---\n", + "TOTAL_SAMPLES = 1000000 \n", + "OUTPUT_FILENAME = f\"X_en_random_mix.jsonl\" \n", + "BUFFER_WRITE_SIZE = 10000 \n", + "\n", + "# --- 数字生成控制 ---\n", + "MAX_DIGITS: int = 11 \n", + "MAX_DECIMAL_PLACES: int = 5 \n", + "DECIMAL_PROBABILITY: float = 0.30 \n", + "NEGATIVE_POOL_PROB: float = 0.30 \n", + "X_DECIMAL_PROBABILITY: float = 0.50 \n", + "X_MAX_DECIMAL_PLACES: int = 5 \n", + "\n", + "# --- 格式化控制 (问题部分:方程字符串) ---\n", + "# -- 数字表示法概率 (总和应为 1.0) --\n", + "STANDARD_ARABIC_PROB: float = 0.40 \n", + "FULL_WIDTH_ARABIC_PROB: float = 0.20 \n", + "ENGLISH_WORDS_PROB: float = 0.40 \n", + "_format_prob_sum = (STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB + ENGLISH_WORDS_PROB)\n", + "if not math.isclose(_format_prob_sum, 1.0):\n", + " raise ValueError(f\"数字格式概率总和必须为 1.0,当前为: {_format_prob_sum}\")\n", + "\n", + "# -- English Number Casing Control --\n", + "ENGLISH_NUMBER_ENTIRE_STRING_CASE_PROB: float = 0.8 # 80% 逐词独立风格, 20% 逐字符\n", + "\n", + "# -- Operator Word Control (for symbolic questions) --\n", + "# Probability of using \"plus\"/\"minus\"/\"equals\" instead of \"+\"/ \"-\"/ \"=\" in equation\n", + "SYMBOLIC_OPERATOR_WORD_PROB: float = 0.3 \n", + "\n", + "# -- 间距控制 --\n", + "ZERO_SPACE_PROB: float = 0.90 \n", + "MAX_RANDOM_SPACES: int = 2 \n", + "\n", + "# -- 方程结尾提问短语列表 (英文) --\n", + "ENGLISH_QUESTION_PROMPTS: List[str] = [\n", + " \", what is x?\", \", x = ?\", \", solve for x.\", \", find x.\", \", calculate x.\",\n", + " \", what does x equal?\", \", what is the value of x?\"\n", + "]\n", + "\n", + "# --- 其他控制 ---\n", + "EQUATION_X_POOL_SIZE = 1000 \n", + "MAX_ATTEMPTS_FACTOR = 100 \n", + "SCI_THRESHOLD_POS_EQ = 10**7 \n", + "SCI_THRESHOLD_NEG_EQ = -6 \n", + "\n", + "# ===============================================\n", + "# 核心代码\n", + "# ===============================================\n", + "\n", + "getcontext().prec = MAX_DIGITS + max(MAX_DECIMAL_PLACES, X_MAX_DECIMAL_PLACES) + 30\n", + "\n", + "# --- 英文数字转换函数 (从 v10.15 复制/调整) ---\n", + "_ENGLISH_DIGITS = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"]\n", + "_ENGLISH_TEENS = [\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\n", + "_ENGLISH_TENS = [\"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\n", + "_ENGLISH_LARGE_UNITS = [\"\", \"thousand\", \"million\", \"billion\", \"trillion\"] \n", + "\n", + "def _num_to_english_chunk_eq(n: int) -> str: \n", + " if not 0 <= n <= 999: return \"\"\n", + " if n == 0: return \"\"\n", + " parts = []\n", + " if n >= 100:\n", + " parts.append(_ENGLISH_DIGITS[n // 100])\n", + " parts.append(\"hundred\")\n", + " n %= 100\n", + " if n > 0:\n", + " if 0 < n < 10: parts.append(_ENGLISH_DIGITS[n])\n", + " elif 10 <= n < 20: parts.append(_ENGLISH_TEENS[n - 10])\n", + " else:\n", + " parts.append(_ENGLISH_TENS[n // 10])\n", + " if n % 10 > 0: parts.append(_ENGLISH_DIGITS[n % 10])\n", + " return \" \".join(parts)\n", + "\n", + "def integer_to_english_words_eq(num: int) -> str:\n", + " if num == 0: return _ENGLISH_DIGITS[0]\n", + " if abs(num) > (10**(len(_ENGLISH_LARGE_UNITS) * 3) -1) :\n", + " return f\"Num too large for Eng words ({num})\" \n", + " sign = \"minus \" if num < 0 else \"\" \n", + " num_abs = abs(num)\n", + " parts = []\n", + " chunk_index = 0\n", + " if num_abs == 0: return _ENGLISH_DIGITS[0] \n", + " temp_num = num_abs\n", + " while temp_num > 0:\n", + " if temp_num % 1000 != 0:\n", + " chunk_words = _num_to_english_chunk_eq(temp_num % 1000)\n", + " unit_word = _ENGLISH_LARGE_UNITS[chunk_index] if chunk_index > 0 else \"\"\n", + " if unit_word: parts.append(unit_word)\n", + " if chunk_words: parts.append(chunk_words) \n", + " temp_num //= 1000\n", + " chunk_index += 1\n", + " if chunk_index >= len(_ENGLISH_LARGE_UNITS) and temp_num > 0:\n", + " return f\"Num too large for Eng units ({temp_num})\"\n", + " result_words = \" \".join(p for p in reversed(parts) if p).strip() \n", + " return (sign + result_words).strip()\n", + "\n", + "def decimal_to_english_words_eq(num: Decimal) -> str:\n", + " if not isinstance(num, Decimal) or not num.is_finite():\n", + " return \"Invalid num for Eng conv\"\n", + " if num.is_zero() and num.is_signed(): num = Decimal('0')\n", + " sign_str = \"\"\n", + " num_abs_for_words = abs(num)\n", + " if num < 0: sign_str = \"minus \"\n", + " int_part_val = int(num_abs_for_words.to_integral_value(rounding=ROUND_DOWN))\n", + " frac_part_dec = num_abs_for_words - Decimal(int_part_val)\n", + " int_words = integer_to_english_words_eq(int_part_val)\n", + " if frac_part_dec.is_zero():\n", + " return (sign_str + int_words).strip()\n", + " s_num_abs_for_frac = format_decimal_or_int(num_abs_for_words) \n", + " if '.' not in s_num_abs_for_frac:\n", + " return (sign_str + int_words).strip() \n", + " _, frac_str_digits = s_num_abs_for_frac.split('.', 1)\n", + " frac_word_list = []\n", + " if frac_str_digits:\n", + " for digit_char in frac_str_digits:\n", + " if digit_char.isdigit(): frac_word_list.append(_ENGLISH_DIGITS[int(digit_char)])\n", + " if not frac_word_list:\n", + " return (sign_str + int_words).strip()\n", + " point_word_raw = \"point\" \n", + " final_assembly_parts = [int_words] \n", + " if point_word_raw: final_assembly_parts.append(point_word_raw)\n", + " if frac_word_list: final_assembly_parts.extend(frac_word_list)\n", + " assembled_num_words = \" \".join(p for p in final_assembly_parts if p)\n", + " return (sign_str + assembled_num_words).strip()\n", + "\n", + "def decimal_to_english_scientific_eq(num: Decimal) -> str:\n", + " if not isinstance(num, Decimal) or not num.is_finite():\n", + " return \"Invalid num for Eng sci conv\"\n", + " if num.is_zero(): return _ENGLISH_DIGITS[0]\n", + " raw_word_parts = []\n", + " if num < 0:\n", + " raw_word_parts.append(\"minus\")\n", + " num = abs(num)\n", + " try:\n", + " sci_str = \"{:e}\".format(num.normalize()) \n", + " coeff_str, exp_str = sci_str.lower().split('e')\n", + " coeff_dec = Decimal(coeff_str); exp_int = int(exp_str)\n", + " coeff_english_raw = decimal_to_english_words_eq(coeff_dec) \n", + " exp_english_raw = integer_to_english_words_eq(exp_int)\n", + " raw_word_parts.extend(coeff_english_raw.split())\n", + " raw_word_parts.append(\"times\"); raw_word_parts.append(\"ten\")\n", + " raw_word_parts.extend(\"to the power of\".split())\n", + " raw_word_parts.extend(exp_english_raw.split())\n", + " return \" \".join(p for p in raw_word_parts if p)\n", + " except Exception:\n", + " return format_decimal_or_int(num)\n", + "\n", + "\n", + "# --- 英文大小写处理函数 (从 v10.15 复制) ---\n", + "def _apply_random_word_case_style(word: str) -> str:\n", + " if not word or not any(c.isalpha() for c in word): return word\n", + " style_choice = random.random()\n", + " if style_choice < 0.4: return word.lower()\n", + " elif style_choice < 0.8: return word.upper()\n", + " else: return word.capitalize()\n", + "\n", + "def _apply_independent_word_casing(text: str) -> str:\n", + " if not text or not any(c.isalpha() for c in text): return text\n", + " words = text.split(' ')\n", + " cased_words = [_apply_random_word_case_style(word) for word in words]\n", + " return \" \".join(cased_words)\n", + "\n", + "def _apply_random_case_char_by_char(text: str) -> str:\n", + " if not text or not any(c.isalpha() for c in text): return text\n", + " return \"\".join(random.choice([char.lower(), char.upper()]) if char.isalpha() else char for char in text)\n", + "\n", + "def _apply_random_case_number_style_eq(text: str) -> str: \n", + " if not text or not any(c.isalpha() for c in text): return text\n", + " if random.random() < ENGLISH_NUMBER_ENTIRE_STRING_CASE_PROB:\n", + " return _apply_independent_word_casing(text) \n", + " else:\n", + " return _apply_random_case_char_by_char(text)\n", + "\n", + "def _apply_random_case_operator_style_eq(text: str) -> str:\n", + " if not text or not any(c.isalpha() for c in text): return text\n", + " return _apply_independent_word_casing(text) \n", + "\n", + "# --- 全角转换 ---\n", + "half_to_full_map = str.maketrans(\"0123456789.-+\", \"0123456789.-+\")\n", + "def to_full_width(text: str) -> str: return text.translate(half_to_full_map)\n", + "\n", + "# --- 格式化数字变体 (核心修改处 - 移除了中文逻辑) ---\n", + "def format_number_variant(num: Union[int, Decimal]) -> str:\n", + " try:\n", + " num_dec = Decimal(str(num)) if not isinstance(num, Decimal) else num\n", + " except InvalidOperation:\n", + " return str(num) \n", + "\n", + " base_format_str = \"\"\n", + " # chosen_format_type = \"\" # Not strictly needed now as char_mix is removed\n", + " fmt_choice_roll = random.random()\n", + "\n", + " if fmt_choice_roll < STANDARD_ARABIC_PROB:\n", + " base_format_str = format_decimal_or_int(num_dec)\n", + " elif fmt_choice_roll < STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB:\n", + " base_format_str = to_full_width(format_decimal_or_int(num_dec))\n", + " else: # ENGLISH_WORDS_PROB\n", + " # For equations, scientific notation is less common for a, b, but handled\n", + " exponent = num_dec.normalize().adjusted()\n", + " use_sci_english = (exponent >= math.log10(SCI_THRESHOLD_POS_EQ) if SCI_THRESHOLD_POS_EQ > 0 else False) or \\\n", + " (exponent <= SCI_THRESHOLD_NEG_EQ if SCI_THRESHOLD_NEG_EQ != 0 else False)\n", + " \n", + " raw_english_phrase = \"\"\n", + " if use_sci_english:\n", + " raw_english_phrase = decimal_to_english_scientific_eq(num_dec)\n", + " else:\n", + " raw_english_phrase = decimal_to_english_words_eq(num_dec)\n", + "\n", + " if \"Invalid\" in raw_english_phrase or \"too large\" in raw_english_phrase or \"Num\" in raw_english_phrase:\n", + " base_format_str = format_decimal_or_int(num_dec) # Fallback\n", + " else:\n", + " base_format_str = _apply_random_case_number_style_eq(raw_english_phrase)\n", + " \n", + " return base_format_str\n", + "\n", + "\n", + "# --- 获取随机间距 ---\n", + "def get_random_spacing() -> str:\n", + " if random.random() < ZERO_SPACE_PROB: return \"\"\n", + " else: return \" \" * random.randint(1, MAX_RANDOM_SPACES)\n", + "\n", + "# --- 辅助函数 (format_decimal_or_int, etc. - 无变化) ---\n", + "def format_decimal_or_int(num: Union[int, Decimal]) -> str:\n", + " try:\n", + " if isinstance(num, int): return str(num)\n", + " if isinstance(num, Decimal):\n", + " if not num.is_finite(): return str(num) \n", + " num_norm = num.normalize()\n", + " if num_norm.is_zero() and num_norm.is_signed():\n", + " num_norm = Decimal('0')\n", + " s = \"{:f}\".format(num_norm) \n", + " if '.' in s:\n", + " integer_part, decimal_part = s.split('.', 1)\n", + " decimal_part = decimal_part.rstrip('0')\n", + " if not decimal_part: \n", + " s = integer_part\n", + " else:\n", + " s = integer_part + \".\" + decimal_part\n", + " return s\n", + " return str(num) \n", + " except Exception:\n", + " return str(num) \n", + "\n", + "\n", + "def get_distributed_count_from_probs(population: List[int], probabilities: List[float]) -> int:\n", + " if not population: return 1 \n", + " if not probabilities or len(population) != len(probabilities) or not all(p >= 0 for p in probabilities):\n", + " return random.choice(population) if population else 1\n", + " prob_sum = sum(probabilities)\n", + " if prob_sum < 1e-9: \n", + " return random.choice(population) if population else 1\n", + " normalized_probabilities = probabilities\n", + " if not math.isclose(prob_sum, 1.0, abs_tol=1e-5): \n", + " try:\n", + " normalized_probabilities = [p / prob_sum for p in probabilities]\n", + " except ZeroDivisionError: \n", + " return random.choice(population) if population else 1\n", + " try:\n", + " return random.choices(population, weights=normalized_probabilities, k=1)[0]\n", + " except Exception: \n", + " return random.choice(population) if population else 1\n", + "\n", + "\n", + "def calculate_digit_probabilities(max_digits: int) -> Dict[int, float]:\n", + " if max_digits <= 0: return {1: 1.0} \n", + " raw_probs = {}; prob_sum = Decimal('0.0'); base_prob = Decimal('0.1'); decay_factor = Decimal('0.95'); increase_factor = Decimal('1.05') \n", + " for n_idx in range(1, max_digits + 1): # renamed n to n_idx\n", + " prob = base_prob * (decay_factor**(n_idx - 1)) * (increase_factor**(n_idx-1)) \n", + " prob = max(Decimal('0.01'), prob) \n", + " raw_probs[n_idx] = prob; prob_sum += prob\n", + " normalized_probs = {}\n", + " if prob_sum <= 0: \n", + " fallback_prob = 1.0 / max(1, max_digits)\n", + " normalized_probs = {n_idx: fallback_prob for n_idx in range(1, max_digits + 1)}\n", + " else:\n", + " normalized_probs = {n_idx: float(p / prob_sum) for n_idx, p in raw_probs.items()}\n", + " final_sum = sum(normalized_probs.values())\n", + " if not math.isclose(final_sum, 1.0, abs_tol=1e-9):\n", + " renorm_factor = 1.0 / final_sum if final_sum != 0 else 1.0\n", + " total = 0.0; keys = sorted(normalized_probs.keys()) \n", + " for i, k_n in enumerate(keys): \n", + " if i == len(keys) - 1: \n", + " normalized_probs[k_n] = max(0.0, 1.0 - total)\n", + " else:\n", + " normalized_probs[k_n] = max(0.0, normalized_probs[k_n] * renorm_factor)\n", + " total += normalized_probs[k_n]\n", + " return normalized_probs\n", + "\n", + "def _generate_positive_integer_with_digits(num_digits: int) -> int:\n", + " if num_digits <= 0: num_digits = 1 \n", + " if num_digits == 1: min_val, max_val = 0, 9 \n", + " else: min_val = 10**(num_digits - 1); max_val = 10**num_digits - 1\n", + " if min_val > max_val: return max_val \n", + " try: return random.randint(min_val, max_val)\n", + " except ValueError: return max_val\n", + "\n", + "# --- 文件写入辅助函数 ---\n", + "def write_buffer_to_file(filename: str, buffer: List[str]):\n", + " if not buffer: return\n", + " try:\n", + " with open(filename, 'a', encoding='utf-8') as f:\n", + " f.write('\\n'.join(buffer) + '\\n')\n", + " except IOError as e: print(f\"\\n错误:写入文件 '{filename}' 时发生 IO 错误: {e}\"); traceback.print_exc()\n", + " except Exception as e: print(f\"\\n错误:写入文件时发生未知错误: {e}\"); traceback.print_exc()\n", + "\n", + "# --- 主要生成函数 ---\n", + "def generate_equations_diverse_format_buffered(\n", + " filename: str, total_samples: int,\n", + " decimal_prob_a: float, max_digits_a: int, max_decimal_places_a: int, negative_prob_a: float,\n", + " decimal_prob_x: float, max_decimal_places_x: int,\n", + " buffer_write_size: int, max_attempts_factor: int):\n", + " \n", + " if total_samples <= 0: print(\"Warning: total_samples must be > 0.\"); return\n", + " if buffer_write_size <= 0: print(\"Warning: BUFFER_WRITE_SIZE must be > 0, setting to 1.\"); buffer_write_size = 1\n", + " if not ENGLISH_QUESTION_PROMPTS: print(\"Warning: ENGLISH_QUESTION_PROMPTS list is empty, no trailing question will be added.\")\n", + "\n", + " print(f\"--- Starting generation of equation data (English only formats) ---\")\n", + " print(f\"Output file: {filename}\")\n", + " print(f\"Target samples: {total_samples:,}\")\n", + " print(f\"Config for 'a': Max int D={max_digits_a}, Max dec P={max_decimal_places_a}, Dec prob={decimal_prob_a:.1%}, Neg prob={negative_prob_a:.1%}\")\n", + " print(f\"Config for 'x': Max int D={max_digits_a}, Max dec P={max_decimal_places_x}, Dec prob={decimal_prob_x:.1%}\")\n", + " print(f\"Number formats: Standard Arabic ({STANDARD_ARABIC_PROB:.1%}), Full-width ({FULL_WIDTH_ARABIC_PROB:.1%}), English Words ({ENGLISH_WORDS_PROB:.1%})\")\n", + " print(f\"English casing: {ENGLISH_NUMBER_ENTIRE_STRING_CASE_PROB*100:.0f}% independent word style, {(1-ENGLISH_NUMBER_ENTIRE_STRING_CASE_PROB)*100:.0f}% char-by-char\")\n", + " print(f\"Operator words (e.g., 'plus'): {SYMBOLIC_OPERATOR_WORD_PROB*100:.1f}% probability\")\n", + " print(f\"Spacing: Zero space prob ({ZERO_SPACE_PROB:.1%}), English question prompts appended.\")\n", + " print(f\"Answer format: Assistant includes solution steps (x = ... = answer_x), answer_x is standard Arabic.\")\n", + " \n", + " digit_pop: List[int] = []; digit_probs_list: List[float] = []\n", + " if max_digits_a > 0: \n", + " digit_probabilities_dict = calculate_digit_probabilities(max_digits_a)\n", + " digit_pop = list(range(1, max_digits_a + 1)); digit_probs_list = [digit_probabilities_dict.get(n, 0.0) for n in digit_pop]\n", + " if not math.isclose(sum(digit_probs_list), 1.0, abs_tol=1e-5): print(f\"Warning: Digit probability sum is {sum(digit_probs_list):.4f}.\")\n", + " if not digit_probs_list and digit_pop: digit_pop = [1]; digit_probs_list = [1.0] \n", + " elif not digit_pop: digit_pop = [1]; digit_probs_list = [1.0]\n", + " else: \n", + " digit_pop = [1]; digit_probs_list = [1.0] \n", + "\n", + " base_x_pool = list(range(EQUATION_X_POOL_SIZE)); random.shuffle(base_x_pool)\n", + " repeats = math.ceil(total_samples / len(base_x_pool)) if base_x_pool else 1\n", + " equation_x_int_part_pool = (base_x_pool * repeats)[:total_samples]; random.shuffle(equation_x_int_part_pool)\n", + " additional_needed = total_samples - len(equation_x_int_part_pool)\n", + " if additional_needed > 0:\n", + " print(f\"Info: x integer pool insufficient for {total_samples}, adding {additional_needed} random x integer parts.\")\n", + " max_x_int_val = 10**max_digits_a -1 if max_digits_a > 0 else 0\n", + " min_x_int_val = -(10**max_digits_a -1) if max_digits_a > 0 else 0\n", + " actual_min_x_int = min(min_x_int_val, max_x_int_val) \n", + " actual_max_x_int = max(min_x_int_val, max_x_int_val)\n", + " for _ in range(additional_needed):\n", + " equation_x_int_part_pool.append(random.randint(actual_min_x_int, actual_max_x_int))\n", + " random.shuffle(equation_x_int_part_pool)\n", + "\n", + " generated_count = 0; total_attempts = 0; errors_in_loop = 0; lines_written_total = 0\n", + " max_total_attempts = total_samples * max(10, max_attempts_factor)\n", + " start_time_generate = time.time()\n", + " write_buffer: List[str] = []\n", + " print(f\"\\nGenerating {total_samples:,} samples (buffered write)...\")\n", + " last_reported_count = -1\n", + "\n", + " try:\n", + " with open(filename, 'w', encoding='utf-8') as f: f.write(\"\")\n", + " except IOError as e: print(f\"\\nError: Could not initialize output file '{filename}': {e}\"); return\n", + "\n", + " while generated_count < total_samples:\n", + " total_attempts += 1\n", + " if total_attempts > max_total_attempts:\n", + " print(f\"\\n\\nWarning: Max attempts ({total_attempts:,}) reached before generating {total_samples:,} samples.\")\n", + " print(f\"Currently generated: {generated_count:,}. Stopping script.\")\n", + " break\n", + " if not equation_x_int_part_pool: print(\"\\nError: x integer pool exhausted unexpectedly.\"); break\n", + "\n", + " target_x_int_part = equation_x_int_part_pool.pop(0) \n", + "\n", + " try:\n", + " x_calc: Decimal \n", + " x_is_decimal_type = random.random() < decimal_prob_x \n", + " x_decimal_places_actual = 0 \n", + " if x_is_decimal_type and max_decimal_places_x > 0:\n", + " x_decimal_places_actual = random.randint(1, max_decimal_places_x)\n", + " frac_x_val_abs = Decimal(random.randint(0, 10**x_decimal_places_actual - 1)) / (Decimal(10)**x_decimal_places_actual)\n", + " base_x_dec = Decimal(str(target_x_int_part))\n", + " if base_x_dec.is_zero() or base_x_dec > Decimal('0'): x_calc = base_x_dec + frac_x_val_abs\n", + " else: x_calc = base_x_dec - frac_x_val_abs\n", + " try:\n", + " x_calc = x_calc.quantize(Decimal(f\"1e-{x_decimal_places_actual}\"), rounding=ROUND_HALF_UP).normalize()\n", + " if x_calc.is_zero() and x_calc.is_signed(): x_calc = Decimal('0') \n", + " except InvalidOperation: x_calc = Decimal(str(target_x_int_part)); x_is_decimal_type = False; x_decimal_places_actual = 0 \n", + " else: x_calc = Decimal(str(target_x_int_part)); x_is_decimal_type = False; x_decimal_places_actual = 0 \n", + "\n", + " struct = random.choice(['x_op_a', 'a_op_x']); eq_op_sym = random.choice(['+', '-'])\n", + " a_digits_count = get_distributed_count_from_probs(digit_pop, digit_probs_list) \n", + " a_is_decimal_type = random.random() < decimal_prob_a \n", + " a_sign = -1 if random.random() < negative_prob_a else 1 \n", + " a_base_abs_val = _generate_positive_integer_with_digits(a_digits_count) \n", + " a_val_for_question: Union[int, Decimal] \n", + " a_decimal_places_actual = 0 \n", + " if a_is_decimal_type and max_decimal_places_a > 0:\n", + " a_decimal_places_actual = random.randint(1, max_decimal_places_a)\n", + " frac_a_val = Decimal(random.randint(0, 10**a_decimal_places_actual - 1)) / (Decimal(10)**a_decimal_places_actual)\n", + " a_temp_decimal = Decimal(a_base_abs_val) + frac_a_val\n", + " a_val_for_question = a_temp_decimal * a_sign\n", + " try: \n", + " if not (a_val_for_question == a_val_for_question.to_integral_value()):\n", + " a_val_for_question = a_val_for_question.quantize(Decimal(f\"1e-{a_decimal_places_actual}\"), rounding=ROUND_HALF_UP).normalize()\n", + " else: \n", + " a_val_for_question = a_val_for_question.to_integral_value(rounding=ROUND_HALF_UP)\n", + " if isinstance(a_val_for_question, Decimal) and a_val_for_question.is_zero() and a_val_for_question.is_signed():\n", + " a_val_for_question = Decimal('0') \n", + " except InvalidOperation: a_val_for_question = Decimal(a_base_abs_val * a_sign) \n", + " else: a_val_for_question = a_base_abs_val * a_sign\n", + " \n", + " a_calc = Decimal(str(a_val_for_question)) \n", + "\n", + " b_val_calc: Decimal \n", + " if struct == 'x_op_a': b_val_calc = x_calc + a_calc if eq_op_sym == '+' else x_calc - a_calc\n", + " else: b_val_calc = a_calc + x_calc if eq_op_sym == '+' else a_calc - x_calc\n", + "\n", + " b_val_for_question: Union[int, Decimal] \n", + " is_b_effectively_integer = b_val_calc.is_finite() and (b_val_calc == b_val_calc.to_integral_value(rounding=ROUND_DOWN))\n", + " max_b_dp_from_inputs = max(a_decimal_places_actual if a_is_decimal_type else 0, x_decimal_places_actual if x_is_decimal_type else 0)\n", + " b_display_dp_cap = max(max_decimal_places_a, max_decimal_places_x)\n", + " \n", + " if is_b_effectively_integer: \n", + " try: b_val_for_question = int(b_val_calc.to_integral_value(rounding=ROUND_DOWN))\n", + " except (OverflowError, InvalidOperation): b_val_for_question = b_val_calc \n", + " elif b_val_calc.is_finite(): \n", + " b_decimal_places_to_show = min(max_b_dp_from_inputs, b_display_dp_cap); b_decimal_places_to_show = max(0, b_decimal_places_to_show) \n", + " if b_decimal_places_to_show > 0 : \n", + " try: b_val_for_question = b_val_calc.quantize(Decimal(f\"1e-{b_decimal_places_to_show}\"), rounding=ROUND_HALF_UP).normalize()\n", + " except InvalidOperation: b_val_for_question = b_val_calc \n", + " else: \n", + " try: b_val_for_question = int(b_val_calc.to_integral_value(rounding=ROUND_HALF_UP))\n", + " except (OverflowError, InvalidOperation): b_val_for_question = b_val_calc \n", + " if isinstance(b_val_for_question, Decimal) and b_val_for_question.is_zero() and b_val_for_question.is_signed():\n", + " b_val_for_question = Decimal('0')\n", + " else: errors_in_loop += 1; continue \n", + "\n", + " answer_str = format_decimal_or_int(x_calc) \n", + " str_a_calc_solution = format_decimal_or_int(a_calc) \n", + " str_b_calc_solution_step = format_decimal_or_int(b_val_calc) \n", + " str_abs_a_calc_solution = format_decimal_or_int(abs(a_calc)) \n", + " \n", + " solution_intermediate_step = \"x = \" \n", + " if struct == 'x_op_a': \n", + " solution_intermediate_step += str_b_calc_solution_step \n", + " if eq_op_sym == '+': solution_intermediate_step += f\" - {str_a_calc_solution}\" if a_calc >= 0 else f\" + {str_abs_a_calc_solution}\"\n", + " else: solution_intermediate_step += f\" + {str_a_calc_solution}\" if a_calc >= 0 else f\" - {str_abs_a_calc_solution}\"\n", + " elif struct == 'a_op_x': \n", + " if eq_op_sym == '+': solution_intermediate_step += str_b_calc_solution_step; solution_intermediate_step += f\" - {str_a_calc_solution}\" if a_calc >= 0 else f\" + {str_abs_a_calc_solution}\"\n", + " else: solution_intermediate_step += str_a_calc_solution; solution_intermediate_step += f\" - {str_b_calc_solution_step}\" if b_val_calc >= 0 else f\" + {format_decimal_or_int(abs(b_val_calc))}\"\n", + " assistant_response_str = f\"{solution_intermediate_step} = {answer_str}\" \n", + "\n", + " # Operator and Equals Sign display\n", + " op_display = eq_op_sym\n", + " equals_display = \"=\"\n", + " if random.random() < SYMBOLIC_OPERATOR_WORD_PROB:\n", + " if eq_op_sym == '+': op_display = _apply_random_case_operator_style_eq(random.choice([\"plus\", \"add\"]))\n", + " elif eq_op_sym == '-': op_display = _apply_random_case_operator_style_eq(random.choice([\"minus\", \"subtract\"]))\n", + " # Optionally, 'equals' word for '='\n", + " # if random.random() < 0.5: # Further sub-probability for 'equals' word\n", + " # equals_display = _apply_random_case_operator_style_eq(\"equals\")\n", + " \n", + " fmt_a_for_question = format_number_variant(a_val_for_question) \n", + " fmt_b_for_question = format_number_variant(b_val_for_question) \n", + "\n", + " current_op_display_in_question = op_display # Use the potentially worded operator\n", + " # Handle negative 'a' with symbolic operator \"x + (-a)\" -> \"x - a\"\n", + " if struct == 'x_op_a' and isinstance(a_val_for_question, (int, Decimal)) and a_val_for_question < 0:\n", + " if op_display == \"+\" or (isinstance(op_display, str) and op_display.lower() in [\"plus\", \"add\"]): # Check if original intended op was +\n", + " current_op_display_in_question = \"-\" if eq_op_sym == '+' else \"+\" # Flip original symbol\n", + " if random.random() < SYMBOLIC_OPERATOR_WORD_PROB: # Re-check if it should be word\n", + " if current_op_display_in_question == '-': current_op_display_in_question = _apply_random_case_operator_style_eq(random.choice([\"minus\",\"subtract\"]))\n", + " else: current_op_display_in_question = _apply_random_case_operator_style_eq(random.choice([\"plus\",\"add\"]))\n", + " fmt_a_for_question = format_number_variant(abs(a_val_for_question)) \n", + " \n", + " s = [get_random_spacing() for _ in range(4)]; parts = [] \n", + " if struct == 'x_op_a':\n", + " parts = ['x', s[0], current_op_display_in_question, s[1], fmt_a_for_question, s[2], equals_display, s[3], fmt_b_for_question]\n", + " else: \n", + " parts = [fmt_a_for_question, s[0], op_display, s[1], 'x', s[2], equals_display, s[3], fmt_b_for_question]\n", + " base_question_str = \"\".join(parts) \n", + "\n", + " final_question_str = base_question_str\n", + " if ENGLISH_QUESTION_PROMPTS: \n", + " chosen_raw_prompt = random.choice(ENGLISH_QUESTION_PROMPTS)\n", + " cased_prompt = _apply_random_case_operator_style_eq(chosen_raw_prompt) # Prompts are like operators\n", + " final_question_str += get_random_spacing() + cased_prompt \n", + " \n", + " text_content = f\"User: {final_question_str}\\n\\nAssistant: {assistant_response_str}\" \n", + "\n", + " try:\n", + " json_string = json.dumps({\"text\": text_content}, ensure_ascii=False)\n", + " if json_string and not json_string.isspace(): \n", + " write_buffer.append(json_string)\n", + " generated_count += 1\n", + " if len(write_buffer) >= buffer_write_size: \n", + " write_buffer_to_file(filename, write_buffer) \n", + " lines_written_total += len(write_buffer)\n", + " write_buffer = [] \n", + " else: print(f\"\\nWarning: Generated empty JSON string: {text_content}\"); errors_in_loop += 1\n", + " except Exception as dump_err: print(f\"\\nError serializing JSON: {dump_err} for item: {text_content}\"); errors_in_loop += 1\n", + "\n", + " except KeyboardInterrupt: print(\"\\nInterrupt received, stopping generation...\"); break \n", + " except Exception as loop_err: print(f\"\\nUnexpected error processing sample: {loop_err}\"); traceback.print_exc(); errors_in_loop += 1; continue \n", + "\n", + " report_interval = max(1, total_samples // 100) if total_samples > 0 else 1 \n", + " if generated_count > 0 and (generated_count % report_interval == 0 or last_reported_count != generated_count or generated_count == total_samples):\n", + " progress = generated_count / total_samples if total_samples > 0 else 0; elapsed_time = time.time() - start_time_generate\n", + " samples_per_sec = generated_count / elapsed_time if elapsed_time > 0 else 0\n", + " est_remaining_gen = float('inf') \n", + " if progress > 1e-6 and samples_per_sec > 0: est_remaining_gen = (total_samples - generated_count) / samples_per_sec\n", + " rem_time_str = f\"{est_remaining_gen:.1f}s\" if est_remaining_gen != float('inf') else \"N/A\"\n", + " print(f\"\\rProgress: {generated_count:,}/{total_samples:,} ({progress:.1%}) | Written: {lines_written_total:,} | {samples_per_sec:.1f} eq/s | Elapsed:{elapsed_time:.1f}s | ETA:~{rem_time_str} \", end=\"\")\n", + " last_reported_count = generated_count\n", + "\n", + " print(\" \" * 130, end=\"\\r\"); print() \n", + "\n", + " if write_buffer:\n", + " print(f\"\\n[Writing last {len(write_buffer)} records...]\")\n", + " write_buffer_to_file(filename, write_buffer)\n", + " lines_written_total += len(write_buffer)\n", + " write_buffer = []\n", + "\n", + " end_generate = time.time(); total_gen_time = end_generate - start_time_generate\n", + " print(f\"\\nGeneration and writing complete. Target: {total_samples:,} -> Generated: {generated_count:,} -> Written: {lines_written_total:,}\")\n", + " print(f\"Total time: {total_gen_time:.2f} seconds. Errors in loop/write: {errors_in_loop:,}.\")\n", + "\n", + "# ===============================================\n", + "# 主程序入口\n", + "# ===============================================\n", + "if __name__ == \"__main__\":\n", + " total_start_time = time.time()\n", + " print(\"=\"*30); print(\" Equation Solver Data Generation Script (v1.16 - English Only) \"); print(\"=\"*30)\n", + " if TOTAL_SAMPLES < EQUATION_X_POOL_SIZE: print(f\"Info: TOTAL_SAMPLES ({TOTAL_SAMPLES}) < X_POOL_SIZE ({EQUATION_X_POOL_SIZE}), pool might not cover 0-{EQUATION_X_POOL_SIZE-1} fully.\")\n", + "\n", + " try:\n", + " generate_equations_diverse_format_buffered(\n", + " filename=OUTPUT_FILENAME,\n", + " total_samples=TOTAL_SAMPLES,\n", + " decimal_prob_a=DECIMAL_PROBABILITY,\n", + " max_digits_a=MAX_DIGITS,\n", + " max_decimal_places_a=MAX_DECIMAL_PLACES,\n", + " negative_prob_a=NEGATIVE_POOL_PROB,\n", + " decimal_prob_x=X_DECIMAL_PROBABILITY,\n", + " max_decimal_places_x=X_MAX_DECIMAL_PLACES,\n", + " buffer_write_size=BUFFER_WRITE_SIZE,\n", + " max_attempts_factor=MAX_ATTEMPTS_FACTOR\n", + " )\n", + " except ValueError as ve: print(f\"\\nConfiguration Error: {ve}\")\n", + " except Exception as main_e: print(f\"\\nMain unhandled error during generation: {main_e}\"); traceback.print_exc()\n", + " finally: pass \n", + "\n", + " total_end_time = time.time()\n", + " print(\"\\n\" + \"=\"*30); print(f\"Script finished. Total execution time: {total_end_time - total_start_time:.2f} seconds.\"); print(f\"Data file: {OUTPUT_FILENAME}\"); print(\"=\"*30)" + ] + }, + { + "cell_type": "markdown", + "id": "8f67c110", + "metadata": {}, + "source": [ + "# 多增0的强化数据\n", + "\n", + "构造整数但是后面有小数点和连续0的数据\n", + "\n", + "用于生成:\n", + "\n", + "训练集:ADD_many0_50k\n", + "\n", + "测试集:ADD_many0_test_v1 , ADD_many0_test_v2" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b09b9781", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "==============================\n", + " 算术题生成脚本 (Integer with Fake Zeros Mod) \n", + "==============================\n", + "--- 开始生成算术数据 (v_int_fake_zeros) ---\n", + "预期行为: 操作数为整数,问题中带1-5位随机小数0,答案为整数。\n", + "中文数字内字符样式随机化已启用。\n", + "中文逐位念读已启用 (概率: 30.0%).\n", + "字符间随机空���已启用。\n", + "通用字符级损坏未启用。\n", + "已初始化/清空输出文件: 'qa_add_int_many0-500-test.jsonl'\n", + "\n", + "开始构造 500 条满足条件的数据...\n", + "生成: 500/500 (100.0%) | 写入: 500 | 尝试: 500 ( 1.0/样本) | 失败率: 0.0% | 8288.1 样本/秒 | 耗时: 0.1s | 剩余: ~0s \n", + "构造循环结束。目标: 500, 实际生成: 500 (尝试 500 次, 构造失败 0 次).\n", + "无剩余数据需写入.\n", + "\n", + "生成与写入完毕。目标: 500 -> 生成: 500 -> 写入: 500\n", + "总尝试次数: 500 (平均 1.00 次/有效样本)\n", + "构造失败次数: 0 (失败率: 0.00%)\n", + "总耗时: 0.06 秒。格式化/计算/写入等循环内错误: 0.\n", + "\n", + "=============== 详细统计 (基于生成的有效样本) ===============\n", + "总有效样本: 500\n", + "--------------------------------------------------\n", + "1. 算术题类型:\n", + " - 加法: 244 ( 48.8%)\n", + " - 减法: 256 ( 51.2%)\n", + "--------------------------------------------------\n", + "2. 运算数类型:\n", + " - 纯整数运算*: 500 ( 100.0%)\n", + " - 含小数运算*: 0 ( 0.0%)\n", + " *注: 基于操作数或结果是否包含实际小数部分,或生成意图是否为小数。\n", + "--------------------------------------------------\n", + "3. 问题格式 - 操作数 A (总计: 500):\n", + " - standard : 96 ( 19.2%)\n", + " - full_width : 88 ( 17.6%)\n", + " - simple_zh : 161 ( 32.2%)\n", + " - complex_zh : 155 ( 31.0%)\n", + "--------------------------------------------------\n", + "4. 问题格式 - 操作数 B (总计: 500):\n", + " - standard : 107 ( 21.4%)\n", + " - full_width : 83 ( 16.6%)\n", + " - simple_zh : 159 ( 31.8%)\n", + " - complex_zh : 151 ( 30.2%)\n", + "--------------------------------------------------\n", + "5. 问题格式 - 类型 (总计: 500):\n", + " - 符号格式 (+/-) : 477 ( 95.4%)\n", + " - 自然语言格式 : 23 ( 4.6%)\n", + "--------------------------------------------------\n", + "6. 符号问题格式 - 等号后缀 (总计符号问题: 477):\n", + " - 添加 \" = ?/?\" : 242 ( 50.7%)\n", + " - 未添加后缀 : 235 ( 49.3%)\n", + "==================================================\n", + "\n", + "==============================\n", + "脚本执行完毕。总耗时: 0.06 秒。\n", + "数据文件: qa_add_int_many0-500-test.jsonl\n", + "==============================\n" + ] + } + ], + "source": [ + "# -*- coding: utf-8 -*-\n", + "# 生成满足指定进/借位范围条件,且问题格式多样化的算术问题数据集脚本。\n", + "# 采用反向逐位构造方法优化生成效率。\n", + "# v10.10: Add random intra-character spacing for numbers in question.\n", + "# MODIFIED FOR INTEGER-ONLY WITH FAKE TRAILING ZEROS\n", + "\n", + "import json\n", + "import random\n", + "import time\n", + "import math\n", + "from typing import List, Tuple, Union, Dict, Optional, Callable\n", + "from decimal import Decimal, getcontext, ROUND_DOWN, ROUND_HALF_UP, InvalidOperation\n", + "import traceback\n", + "from collections import Counter\n", + "import string\n", + "\n", + "# ===============================================\n", + "# 配置参数区域\n", + "# ===============================================\n", + "# --- 主要数量和文件名 ---\n", + "TOTAL_SAMPLES = 50000\n", + "OUTPUT_FILENAME = f\"ADD_many0_50k.jsonl\" # <<< MODIFIED Example Filename\n", + "ADD_PROBABILITY: float = 0.5\n", + "BATCH_SAVE_SIZE: int = 20\n", + "\n", + "# --- 数字生成控制 ---\n", + "MAX_DIGITS: int = 12\n", + "MAX_DECIMAL_PLACES: int = 0 # <<< MODIFIED: Ensure results are integers\n", + "DECIMAL_PROBABILITY: float = 0.0 # <<< MODIFIED: Generate only integers for a and b\n", + "NEGATIVE_POOL_PROB: float = 0.1\n", + "SCI_THRESHOLD_POS = 100000 # Effectively disable sci for integers\n", + "SCI_THRESHOLD_NEG = -100000 # Effectively disable sci for integers\n", + "\n", + "# --- 进/借位条件范围 ---\n", + "TARGET_TOTAL_CARRIES_MIN: int = 0\n", + "TARGET_TOTAL_CARRIES_MAX: int = math.inf\n", + "TARGET_CONSECUTIVE_CARRIES_MIN: int = 0\n", + "TARGET_CONSECUTIVE_CARRIES_MAX: int = math.inf\n", + "\n", + "# --- 格式化控制 (问题部分数字的样式) ---\n", + "STANDARD_ARABIC_PROB: float = 0.20\n", + "FULL_WIDTH_ARABIC_PROB: float = 0.20\n", + "SIMPLE_CHINESE_PROB: float = 0.30\n", + "COMPLEX_CHINESE_PROB: float = 0.30\n", + "_format_prob_sum = STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB + SIMPLE_CHINESE_PROB + COMPLEX_CHINESE_PROB\n", + "if not math.isclose(_format_prob_sum, 1.0):\n", + " raise ValueError(f\"数字格式概率总和必须为 1.0,当前为: {_format_prob_sum}\")\n", + "\n", + "# --- 中文数字内字符随机化控制 (v10.8 功能) ---\n", + "RANDOMIZE_DIGITS_WITHIN_CHINESE_NUMBERS: bool = True\n", + "\n", + "# --- 中文逐位念读控制 (v10.9 功能) ---\n", + "CHINESE_DIGIT_BY_DIGIT_READING_PROB: float = 0.3\n", + "\n", + "# --- 新增:字符间随机空格控制 (应用于问题中的操作数) ---\n", + "APPLY_INTRA_CHAR_SPACING: bool = True # 是否启用字符间随机空格\n", + "# 定义 (空格数量, 概率) 的列表。概率和应为1。\n", + "INTRA_CHAR_SPACING_CONFIG: List[Tuple[int, float]] = [\n", + " (0, 0.97), # 0个空格的概率\n", + " (1, 0.02), # 1个空格的概率\n", + " (2, 0.01) # 2个空格的概率\n", + "]\n", + "# 校验 INTRA_CHAR_SPACING_CONFIG 概率和\n", + "_intra_space_prob_sum = sum(p for _, p in INTRA_CHAR_SPACING_CONFIG)\n", + "if not math.isclose(_intra_space_prob_sum, 1.0):\n", + " raise ValueError(f\"INTRA_CHAR_SPACING_CONFIG 的概率总和必须为 1.0,当前为: {_intra_space_prob_sum}\")\n", + "\n", + "# --- 自然语言概率控制 ---\n", + "NL_QUESTION_PROBABILITY: float = 0.30\n", + "\n", + "# --- 等号后缀概率控制 (仅符号问题) ---\n", + "SYMBOLIC_EQUALS_SUFFIX_PROB: float = 0.50\n", + "\n", + "# --- 字符级随机替换控制 (通用,应用于最终文本 - v10.7 功能) ---\n", + "APPLY_GENERAL_CHAR_REPLACEMENT: bool = False\n", + "GENERAL_CHAR_REPLACEMENT_PROBABILITY: float = 0.005\n", + "GENERAL_CHAR_REPLACEMENT_POOL: str = string.ascii_letters + string.digits + \".,?! \"\n", + "\n", + "# --- 其他控制 ---\n", + "MAX_ATTEMPTS_FACTOR = 5000\n", + "\n", + "# ===============================================\n", + "# 核心代码\n", + "# ===============================================\n", + "# <<< MODIFIED: Adjusted precision slightly for safety, though MAX_DECIMAL_PLACES is 0\n", + "getcontext().prec = MAX_DIGITS + 5 + 30 # Max 5 fake zeros\n", + "\n", + "CHINESE_DIGIT_LOOKUP = {\n", + " '零': '0', '一': '1', '二': '2', '两': '2', '三': '3', '四': '4', '五': '5', '六': '6', '七': '7', '八': '8', '九': '9',\n", + " '壹': '1', '贰': '2', '貳': '2', '叁': '3', '參': '3', '肆': '4', '伍': '5', '陆': '6', '陸': '6', '柒': '7', '捌': '8', '玖': '9'\n", + "}\n", + "POSSIBLE_DIGIT_REPRESENTATIONS = {\n", + " '0': ['0', '0', '零', '零'], '1': ['1', '1', '一', '壹'], '2': ['2', '2', '二', '贰'],\n", + " '3': ['3', '3', '三', '叁'], '4': ['4', '4', '四', '肆'], '5': ['5', '5', '五', '伍'],\n", + " '6': ['6', '6', '六', '陆'], '7': ['7', '7', '七', '柒'], '8': ['8', '8', '八', '捌'],\n", + " '9': ['9', '9', '九', '玖'],\n", + "}\n", + "\n", + "digit_map_simple = {'0': '零', '1': '一', '2': '二', '3': '三', '4': '四', '5': '五', '6': '六', '7': '七', '8': '八', '9': '九'}\n", + "unit_map_section_simple = ['', '十', '百', '千']\n", + "unit_map_large_simple = ['', '万', '亿', '兆']\n", + "digit_map_complex = {'0': '零', '1': '壹', '2': '贰', '3': '叁', '4': '肆', '5': '伍', '6': '陆', '7': '柒', '8': '捌', '9': '玖'}\n", + "unit_map_section_complex = ['', '拾', '佰', '仟']\n", + "unit_map_large_complex = ['', '萬', '億', '兆']\n", + "\n", + "# --- _convert_section, num_to_chinese, decimal_to_chinese, etc. (Keep as is) ---\n", + "def _convert_section(section_str: str, complex_form: bool = False) -> str:\n", + " digit_map = digit_map_complex if complex_form else digit_map_simple\n", + " unit_map_section = unit_map_section_complex if complex_form else unit_map_section_simple\n", + " if not section_str: return \"\"\n", + " try: section_int = int(section_str)\n", + " except ValueError: return \"无效输入\"\n", + " if section_int == 0: return digit_map['0']\n", + " chinese_s = \"\"; length = len(section_str); need_zero = False\n", + " for i in range(length):\n", + " digit_char = section_str[i]; place_value_idx = length - 1 - i\n", + " if digit_char == '0': need_zero = True\n", + " else:\n", + " if need_zero and chinese_s and not chinese_s.endswith(digit_map['0']): chinese_s += digit_map['0']\n", + " need_zero = False; current_digit_chinese = \"\"\n", + " if not complex_form and digit_char == '2':\n", + " is_leading_two_and_high_place = (i == 0 and place_value_idx >= 2)\n", + " is_leading_two_in_ten = (i == 0 and place_value_idx == 1 and length > 1)\n", + " if (is_leading_two_and_high_place or is_leading_two_in_ten) and random.random() < 0.7: current_digit_chinese = '两'\n", + " else: current_digit_chinese = digit_map['2']\n", + " else: current_digit_chinese = digit_map[digit_char]\n", + " is_leading_one_in_ten_place = (not complex_form and digit_char == '1' and place_value_idx == 1 and i == 0 and length > 1)\n", + " if is_leading_one_in_ten_place and length == 2 : chinese_s += unit_map_section[place_value_idx]\n", + " else: chinese_s += current_digit_chinese + unit_map_section[place_value_idx]\n", + " if chinese_s.endswith(digit_map['0']) and len(chinese_s) > len(digit_map['0']): chinese_s = chinese_s[:-len(digit_map['0'])]\n", + " if not complex_form and chinese_s == digit_map_simple['1'] + unit_map_section_simple[1]: chinese_s = unit_map_section_simple[1]\n", + " return chinese_s\n", + "\n", + "def num_to_chinese(num: int, complex_form: bool = False) -> str:\n", + " if not isinstance(num, int): return \"无效输入\"\n", + " digit_map = digit_map_complex if complex_form else digit_map_simple\n", + " unit_map_large = unit_map_large_complex if complex_form else unit_map_large_simple\n", + " negative_word = \"负\"\n", + " if num == 0: return digit_map['0']\n", + " if num < 0: return negative_word + num_to_chinese(abs(num), complex_form)\n", + " s_num = str(num)\n", + " if len(s_num) > 50: return \"数字过大无法转换\"\n", + " result_chinese = \"\"; sections_str_list = []\n", + " current_idx = len(s_num)\n", + " while current_idx > 0:\n", + " start_idx = max(0, current_idx - 4)\n", + " sections_str_list.append(s_num[start_idx:current_idx])\n", + " current_idx -= 4\n", + " sections_str_list.reverse()\n", + " last_section_was_zero = False; num_sections = len(sections_str_list)\n", + " for i, section_s in enumerate(sections_str_list):\n", + " section_val = int(section_s); large_unit_idx = num_sections - 1 - i\n", + " if section_val == 0:\n", + " last_section_was_zero = True\n", + " if result_chinese and not result_chinese.endswith(digit_map['0']) and \\\n", + " large_unit_idx > 0 and (i + 1 < num_sections and int(sections_str_list[i+1]) != 0):\n", + " result_chinese += digit_map['0']\n", + " continue\n", + " if last_section_was_zero and result_chinese and not result_chinese.endswith(digit_map['0']):\n", + " result_chinese += digit_map['0']\n", + " section_chinese_str = _convert_section(section_s, complex_form)\n", + " result_chinese += section_chinese_str\n", + " if large_unit_idx > 0: result_chinese += unit_map_large[large_unit_idx]\n", + " last_section_was_zero = False\n", + " return result_chinese if result_chinese else digit_map['0']\n", + "\n", + "def decimal_to_chinese(num: Decimal, complex_form: bool = False) -> str:\n", + " if not isinstance(num, Decimal): return \"无效输入\"\n", + " if not num.is_finite(): return \"无效输入\"\n", + " digit_map = digit_map_complex if complex_form else digit_map_simple\n", + " point_word = \"点\" if not complex_form else \"點\"; negative_word = \"负\"\n", + " if num.is_zero() and num.is_signed(): num = Decimal('0') # Normalize -0 to 0 for consistency\n", + " try:\n", + " # Check if it's an integer for num_to_chinese path\n", + " # For 1.000, we want \"一点零零零\", not \"一\"\n", + " # So, only use num_to_chinese if there are NO fractional digits in its string representation\n", + " # format_decimal_or_int handles stripping unnecessary zeros, which is what we want for the *decision* here.\n", + " # But num itself might be Decimal('1.000')\n", + " s_num_canonical = format_decimal_or_int(num) # \"1\" for Decimal('1.000')\n", + " if '.' not in s_num_canonical:\n", + " int_val_test = num.to_integral_value(rounding=ROUND_DOWN)\n", + " if num == int_val_test: # It is an integer like 1, 2, etc.\n", + " if abs(num).adjusted() >= MAX_DIGITS + 10 : return \"数字过大无法转换\" # Check magnitude\n", + " return num_to_chinese(int(num), complex_form)\n", + " except (ValueError, TypeError, OverflowError, InvalidOperation): return \"无效输入或溢出\" # Should not happen if num is Decimal\n", + "\n", + " if num < 0: return negative_word + decimal_to_chinese(abs(num), complex_form)\n", + " \n", + " # Use to_eng_string() to preserve trailing zeros for Chinese fractional part if num is e.g. Decimal('1.00')\n", + " s_num = num.to_eng_string() \n", + " if s_num in [\"Infinity\", \"-Infinity\", \"NaN\", \"无效输入\", \"无效输入或溢出\"]: return \"无效输入\"\n", + " \n", + " # If after to_eng_string, it still looks like an integer (e.g. num was Decimal('1'))\n", + " if '.' not in s_num:\n", + " try:\n", + " num_int_again = int(s_num)\n", + " if abs(Decimal(s_num)).adjusted() >= MAX_DIGITS + 10: return \"数字过大无法转换\"\n", + " return num_to_chinese(num_int_again, complex_form)\n", + " except (ValueError, OverflowError): return \"无效输入或溢出\"\n", + "\n", + " integer_part_str, fractional_part_str = s_num.split('.', 1)\n", + " chinese_int_part = \"\"\n", + " if integer_part_str == '0': chinese_int_part = digit_map['0']\n", + " else:\n", + " try:\n", + " int_val = int(integer_part_str)\n", + " if abs(Decimal(integer_part_str)).adjusted() >= MAX_DIGITS + 10: return \"数字过大无法转换\"\n", + " chinese_int_part = num_to_chinese(int_val, complex_form)\n", + " if chinese_int_part == \"无效输入\": return \"无效输入\"\n", + " except (ValueError, OverflowError): return \"无效输入或溢出\"\n", + "\n", + " # fractional_part_str now correctly contains any trailing zeros like \"00\" from \"1.00\"\n", + " chinese_frac_part = \"\".join(digit_map.get(d, '?') for d in fractional_part_str if d.isdigit())\n", + "\n", + " if not fractional_part_str : return chinese_int_part # Should be caught by earlier checks\n", + " # if not chinese_frac_part and fractional_part_str: return chinese_int_part # e.g. \"1.\" should be \"1\"\n", + " \n", + " # This condition handles cases like 0.123 -> 零点一二三 vs 1.00 -> 一点零零\n", + " if integer_part_str == '0' and chinese_int_part == digit_map['0'] and fractional_part_str: # e.g. 0.123 or 0.00\n", + " return f\"{digit_map['0']}{point_word}{chinese_frac_part}\"\n", + " elif fractional_part_str: # e.g. 1.23 or 1.00\n", + " return f\"{chinese_int_part}{point_word}{chinese_frac_part}\"\n", + " else: # Should be just integer part\n", + " return chinese_int_part\n", + "\n", + "\n", + "def _decimal_to_chinese_scientific(num: Decimal, complex_form: bool = False) -> str:\n", + " if not isinstance(num, Decimal): return \"无效输入\"\n", + " if not num.is_finite(): return \"无效输入\"\n", + " digit_map_loc = digit_map_complex if complex_form else digit_map_simple\n", + " if num.is_zero(): return digit_map_loc['0']\n", + " sign_prefix = \"\"; negative_word = \"负\"\n", + " if num < 0: sign_prefix = negative_word; num = abs(num)\n", + " try:\n", + " sci_str = \"{:e}\".format(num.normalize()); parts = sci_str.lower().split('e')\n", + " if len(parts) != 2: return \"科学计数法解析失败\"\n", + " coeff_str, exp_str = parts[0], parts[1]\n", + " coeff_dec = Decimal(coeff_str); exp_int = int(exp_str)\n", + " # Coeff needs to respect fake zeros if present.\n", + " # decimal_to_chinese is now aware of Decimal('1.00') vs Decimal('1')\n", + " coeff_chinese = decimal_to_chinese(coeff_dec, complex_form)\n", + " if \"无效\" in coeff_chinese or \"过大\" in coeff_chinese or \"失败\" in coeff_chinese: return coeff_chinese\n", + " exp_chinese = num_to_chinese(exp_int, complex_form)\n", + " if \"无效\" in exp_chinese or \"过大\" in exp_chinese: return exp_chinese\n", + " times_word = \"乘以十的\"; power_word = \"次方\"\n", + " return f\"{sign_prefix}{coeff_chinese}{times_word}{exp_chinese}{power_word}\"\n", + " except (ValueError, IndexError, TypeError, InvalidOperation): return \"转换科学计数法出错\"\n", + " except Exception: return \"转换科学计数法出错\"\n", + "\n", + "def _randomize_digits_in_chinese_string(pure_chinese_str: str) -> str:\n", + " if not RANDOMIZE_DIGITS_WITHIN_CHINESE_NUMBERS or not pure_chinese_str: return pure_chinese_str\n", + " result_chars = []\n", + " for char_cn in pure_chinese_str:\n", + " if char_cn in CHINESE_DIGIT_LOOKUP:\n", + " canonical_digit_arabic = CHINESE_DIGIT_LOOKUP[char_cn]\n", + " chosen_representation = random.choice(POSSIBLE_DIGIT_REPRESENTATIONS[canonical_digit_arabic])\n", + " result_chars.append(chosen_representation)\n", + " else: result_chars.append(char_cn)\n", + " return \"\".join(result_chars)\n", + "\n", + "def _decimal_to_chinese_digit_by_digit(num: Decimal, complex_form: bool = False) -> str:\n", + " if not isinstance(num, Decimal): return \"无效输入\"\n", + " if not num.is_finite(): return \"无效输入\"\n", + " \n", + " # Use to_eng_string() to ensure fake zeros are included in s_num\n", + " # e.g., if num is Decimal('1.000'), s_num becomes \"1.000\"\n", + " s_num = num.to_eng_string()\n", + " if s_num in [\"Infinity\", \"-Infinity\", \"NaN\", \"无效输入\", \"无效输入或溢出\"]: return \"无效输入\"\n", + "\n", + " target_digit_map = digit_map_complex if complex_form else digit_map_simple\n", + " point_word = \"点\" if not complex_form else \"點\"; negative_word = \"负\"\n", + " result_chinese_chars = []\n", + " if s_num.startswith('-'): result_chinese_chars.append(negative_word); s_num = s_num[1:]\n", + " for char_digit in s_num:\n", + " if char_digit.isdigit(): result_chinese_chars.append(target_digit_map.get(char_digit, '?'))\n", + " elif char_digit == '.': result_chinese_chars.append(point_word)\n", + " else: result_chinese_chars.append(char_digit) # Should not happen for valid numbers\n", + " return \"\".join(result_chinese_chars)\n", + "\n", + "\n", + "half_to_full_map = str.maketrans(\"0123456789.-+\", \"0123456789.-+\")\n", + "def to_full_width(text: str) -> str: return text.translate(half_to_full_map)\n", + "\n", + "def format_decimal_or_int(num: Union[int, Decimal]) -> str:\n", + " \"\"\"\n", + " Formats a Decimal or int to its canonical string form,\n", + " stripping trailing zeros from decimals unless it's 0.\n", + " E.g., Decimal('1.00') -> \"1\", Decimal('0.00') -> \"0\", Decimal('1.230') -> \"1.23\"\n", + " \"\"\"\n", + " try:\n", + " if isinstance(num, int): return str(num)\n", + " if isinstance(num, Decimal):\n", + " if not num.is_finite(): return str(num) # NaN, Infinity\n", + " \n", + " # Normalize to remove exponent, e.g., 1.23E+2 -> 123\n", + " # And -0 -> 0\n", + " num = num.normalize()\n", + " if num.is_zero() and num.is_signed(): # Handle -0\n", + " num = Decimal('0')\n", + "\n", + " s = num.to_eng_string() # Use to_eng_string to get plain format initially\n", + "\n", + " if '.' in s:\n", + " # Strip trailing zeros from fractional part, then strip trailing decimal point if it becomes \"X.\"\n", + " s = s.rstrip('0').rstrip('.')\n", + " \n", + " # Not typically needed after normalize and rstrip, but as a safeguard\n", + " # if '.' not in s and len(s) > 1 and s.startswith('0'): s = s.lstrip('0') # e.g. \"0123\" -> \"123\"\n", + " # if not s: s = \"0\" # Should not happen\n", + " # if s == \"-0\": s = \"0\" # Handled by normalize()\n", + " return s\n", + " return str(num) # Fallback for other types\n", + " except Exception: # Broad exception for safety if Decimal conversion fails\n", + " # Fallback to simpler formatting if robust one fails\n", + " try:\n", + " temp_s = \"{:f}\".format(Decimal(str(num)).normalize()) # Try to force float notation and normalize\n", + " if '.' in temp_s: temp_s = temp_s.rstrip('0').rstrip('.')\n", + " if not temp_s: temp_s = \"0\";\n", + " if temp_s == \"-0\": temp_s = \"0\"\n", + " return temp_s\n", + " except: return str(num) # Absolute fallback\n", + "\n", + "# --- 新增:字符间随机空格函数 ---\n", + "_intra_space_num_list = [s[0] for s in INTRA_CHAR_SPACING_CONFIG]\n", + "_intra_space_prob_list = [s[1] for s in INTRA_CHAR_SPACING_CONFIG]\n", + "\n", + "def _insert_random_intra_char_spacing(text: str) -> str:\n", + " if not text or not APPLY_INTRA_CHAR_SPACING or len(text) <= 1:\n", + " return text\n", + " new_string_parts = [text[0]]\n", + " for i in range(len(text) - 1):\n", + " num_spaces = random.choices(_intra_space_num_list, weights=_intra_space_prob_list, k=1)[0]\n", + " if num_spaces > 0:\n", + " new_string_parts.append(\" \" * num_spaces)\n", + " new_string_parts.append(text[i+1])\n", + " return \"\".join(new_string_parts)\n", + "\n", + "\n", + "def format_number_variant(num: Union[int, Decimal]) -> Tuple[str, str]:\n", + " \"\"\"\n", + " Formats numbers, adding 1-5 fake trailing zeros to integers for question display.\n", + " \"\"\"\n", + " fmt_choice = random.random()\n", + " try:\n", + " original_num_dec = Decimal(str(num)) if not isinstance(num, Decimal) else num\n", + " except InvalidOperation:\n", + " return _insert_random_intra_char_spacing(str(num)), 'standard'\n", + "\n", + " num_to_format = original_num_dec.normalize()\n", + " if num_to_format.is_zero() and num_to_format.is_signed():\n", + " num_to_format = Decimal('0')\n", + "\n", + " is_originally_integer = (original_num_dec == original_num_dec.to_integral_value())\n", + " \n", + " if is_originally_integer:\n", + " num_fake_zeros = random.randint(1, 5)\n", + " if num_fake_zeros > 0:\n", + " # <<< MODIFIED SECTION TO GET int_part_str MORE ROBUSTLY >>>\n", + " # Start with the integral value of original_num_dec\n", + " temp_integral_for_str = original_num_dec.to_integral_value(rounding=ROUND_DOWN)\n", + " \n", + " # Ensure -0 becomes 0 for consistent string representation\n", + " if temp_integral_for_str.is_zero() and temp_integral_for_str.is_signed():\n", + " temp_integral_for_str = Decimal('0')\n", + " \n", + " # .to_eng_string() on a (normalized) integral Decimal is reliable for \"DDD\" or \"-DDD\" or \"0\"\n", + " int_part_str = temp_integral_for_str.to_eng_string()\n", + " \n", + " # Basic check to ensure int_part_str is what we expect (a simple integer string)\n", + " # This check is mostly for sanity; .to_eng_string() on an integral Decimal should be fine.\n", + " if not (int_part_str and (int_part_str == '0' or int_part_str.lstrip('-').isdigit())):\n", + " # This state indicates a deeper problem if reached, as temp_integral_for_str was expected to be a clean integer.\n", + " # Fallback: use original_num_dec directly, won't have fake zeros in this error case.\n", + " print(f\"WARNING: Problematic int_part_str '{int_part_str}' from {temp_integral_for_str!r}. Reverting to num_to_format without added zeros for this operand.\")\n", + " # num_to_format is already original_num_dec.normalize(), so no change needed here to use it as is.\n", + " # We just won't overwrite it with the version that has fake zeros.\n", + " else:\n", + " try:\n", + " num_to_format = Decimal(f\"{int_part_str}.{'0' * num_fake_zeros}\")\n", + " except decimal.InvalidOperation:\n", + " # If this still fails, there's a very unusual int_part_str.\n", + " # Print diagnostic info and use original_num_dec without fake zeros.\n", + " print(f\"CRITICAL WARNING: Decimal conversion failed for f-string with int_part_str='{int_part_str}'. Reverting for {original_num_dec!r}.\")\n", + " # num_to_format remains original_num_dec.normalize()\n", + " # <<< END MODIFIED SECTION >>>\n", + " \n", + " # The rest of the function remains the same for formatting num_to_format\n", + " target_format_name = 'standard'\n", + " # ... (rest of the function as before)\n", + " if fmt_choice < STANDARD_ARABIC_PROB: target_format_name = 'standard'\n", + " elif fmt_choice < STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB: target_format_name = 'full_width' # Corrected order if you intended it this way\n", + " elif fmt_choice < STANDARD_ARABIC_PROB + FULL_WIDTH_ARABIC_PROB + SIMPLE_CHINESE_PROB: target_format_name = 'simple_zh'\n", + " else: target_format_name = 'complex_zh'\n", + "\n", + "\n", + " def finalize_output(s: str, fmt_name: str) -> Tuple[str, str]:\n", + " final_s = _insert_random_intra_char_spacing(s)\n", + " return final_s, fmt_name\n", + "\n", + " try:\n", + " if not num_to_format.is_finite(): \n", + " s_num_non_finite = str(num_to_format) \n", + " res_str = to_full_width(s_num_non_finite) if target_format_name == 'full_width' else s_num_non_finite\n", + " return finalize_output(res_str, 'full_width' if target_format_name == 'full_width' else 'standard')\n", + "\n", + " s_formatted_arabic_with_potential_zeros = num_to_format.to_eng_string()\n", + "\n", + " if target_format_name == 'standard':\n", + " return finalize_output(s_formatted_arabic_with_potential_zeros, 'standard')\n", + " elif target_format_name == 'full_width':\n", + " return finalize_output(to_full_width(s_formatted_arabic_with_potential_zeros), 'full_width')\n", + " else: \n", + " is_complex_chinese = (target_format_name == 'complex_zh')\n", + " pure_chinese_output_str = \"\"\n", + " \n", + " exponent = num_to_format.normalize().adjusted() \n", + " use_sci_chinese = (exponent >= SCI_THRESHOLD_POS or exponent <= SCI_THRESHOLD_NEG) and not is_originally_integer\n", + "\n", + " if use_sci_chinese:\n", + " pure_chinese_output_str = _decimal_to_chinese_scientific(num_to_format, complex_form=is_complex_chinese)\n", + " else:\n", + " use_digit_by_digit_reading = (random.random() < CHINESE_DIGIT_BY_DIGIT_READING_PROB)\n", + " if use_digit_by_digit_reading:\n", + " pure_chinese_output_str = _decimal_to_chinese_digit_by_digit(num_to_format, complex_form=is_complex_chinese)\n", + " else:\n", + " pure_chinese_output_str = decimal_to_chinese(num_to_format, complex_form=is_complex_chinese)\n", + " \n", + " if pure_chinese_output_str in [\"无效输入\", \"无效输入或溢出\", \"数字过大无法转换\", \"科学计数法解析失败\", \"转换科学计数法出错\"]:\n", + " return finalize_output(s_formatted_arabic_with_potential_zeros, 'standard')\n", + "\n", + " final_mixed_chinese_output = _randomize_digits_in_chinese_string(pure_chinese_output_str)\n", + " return finalize_output(final_mixed_chinese_output, target_format_name)\n", + " \n", + " except Exception as e_format_logic:\n", + " try:\n", + " fallback_str = format_decimal_or_int(original_num_dec)\n", + " return finalize_output(fallback_str, 'standard')\n", + " except:\n", + " return finalize_output(str(num), 'standard')\n", + "\n", + "\n", + "# --- get_realistic_spacing, contains_arabic_numerals, etc. (Keep as is) ---\n", + "def get_realistic_spacing() -> str:\n", + " space_values = [\"\", \" \", \" \"]; space_weights = [99.5, 0.4, 0.1]\n", + " if not math.isclose(sum(space_weights), 100.0): print(\"警告:get_realistic_spacing 中的空格权重和不为 100。\"); return \"\"\n", + " try: return random.choices(space_values, weights=space_weights, k=1)[0]\n", + " except Exception as e: print(f\"警告:生成空格时出错: {e}。默认为无空格。\"); return \"\"\n", + "def contains_arabic_numerals(s: str) -> bool: return any(c in \"01234567890123456789\" for c in s)\n", + "def get_distributed_count_from_probs(population: List[int], probabilities: List[float]) -> int:\n", + " if not population: return 1\n", + " if not probabilities or len(population) != len(probabilities) or not all(p >= 0 for p in probabilities): print(\"警告:get_distributed_count_from_probs population/probabilities 无效。\"); return random.choice(population) if population else 1\n", + " prob_sum = sum(probabilities);\n", + " if prob_sum < 1e-9: print(\"警告:概率和接近于零。\"); return random.choice(population) if population else 1\n", + " normalized_probabilities = probabilities\n", + " if not math.isclose(prob_sum, 1.0, abs_tol=1e-5):\n", + " try: normalized_probabilities = [p / prob_sum for p in probabilities]\n", + " except ZeroDivisionError: print(\"警告:概率归一化 ZeroDivisionError。\"); return random.choice(population) if population else 1\n", + " try: return random.choices(population, weights=normalized_probabilities, k=1)[0]\n", + " except Exception as e: print(f\"random.choices 执行出错: {e}。\"); return random.choice(population) if population else 1\n", + "def calculate_digit_probabilities(max_digits: int) -> Dict[int, float]:\n", + " if max_digits <= 0: return {1: 1.0}\n", + " raw_probs = {}; prob_sum = Decimal('0.0'); base_prob = Decimal('0.1'); decay_factor = Decimal('0.95'); increase_factor = Decimal('1.05')\n", + " for n in range(1, max_digits + 1):\n", + " prob = base_prob * (decay_factor**(n - 1)) * (increase_factor**(max_digits - n + 1)); prob = max(Decimal('0.001'), prob); raw_probs[n] = prob; prob_sum += prob\n", + " normalized_probs = {}\n", + " if prob_sum <= 0: fallback_prob = 1.0 / max(1, max_digits); normalized_probs = {n: fallback_prob for n in range(1, max_digits + 1)}\n", + " else: normalized_probs = {n: float(p / prob_sum) for n, p in raw_probs.items()}\n", + " final_sum = sum(normalized_probs.values())\n", + " if not math.isclose(final_sum, 1.0, abs_tol=1e-9):\n", + " renorm_factor = 1.0 / final_sum if final_sum != 0 else 1.0; total = 0.0; keys = sorted(normalized_probs.keys())\n", + " for i, n_key in enumerate(keys):\n", + " if i == len(keys) - 1: normalized_probs[n_key] = max(0.0, 1.0 - total)\n", + " else: norm_p = max(0.0, normalized_probs[n_key] * renorm_factor); normalized_probs[n_key] = norm_p; total += norm_p\n", + " if keys: normalized_probs[keys[-1]] = max(0.0, normalized_probs[keys[-1]])\n", + " return normalized_probs\n", + "def format_natural_language_question(fmt_a: str, fmt_b: str, op_sym: str) -> str:\n", + " add_words = [\"加\", \"加上\", \"和\", \"的总和是\", \"一共是\"]; subtract_words = [\"减\", \"减去\", \"减掉\", \"与...的差是\", \"少了\"]\n", + " result_phrases = [\"等于多少\", \"是多少\", \"结果是\", \"等于几\", \"得多少\", \"是多少呢\"]; question_marks = [\"?\", \"?\", \"\"]\n", + " templates = []\n", + " if op_sym == '+':\n", + " op_words = add_words\n", + " templates.extend([\"{num_a} {op} {num_b} {res}{q_mark}\", \"计算一下 {num_a} {op} {num_b}{q_mark}\", \"请问 {num_a} {op} {num_b} {res}{q_mark}\", \"{num_a} 与 {num_b} 的和是多少{q_mark}\", \"{num_a} {op} {num_b} 等于?\", \"{num_a} 再 {op} {num_b} {res}{q_mark}\", \"帮我算算 {num_a} {op} {num_b} 的结果{q_mark}\"])\n", + " elif op_sym == '-':\n", + " op_words = subtract_words\n", + " templates.extend([\"{num_a} {op} {num_b} {res}{q_mark}\", \"计算一下 {num_a} {op} {num_b}{q_mark}\", \"请问 {num_a} {op} {num_b} {res}{q_mark}\", \"{num_a} 与 {num_b} 的差是多少{q_mark}\", \"{num_a} {op} {num_b} 等于?\", \"{num_a} {op} {num_b} 还剩多少{q_mark}\", \"帮我算算 {num_a} {op} {num_b} {res}{q_mark}\"])\n", + " else: return f\"{fmt_a} {op_sym} {fmt_b}\"\n", + " chosen_template = random.choice(templates); chosen_op_word = random.choice(op_words)\n", + " try:\n", + " if \"{res}\" in chosen_template: question_str = chosen_template.format(num_a=fmt_a, num_b=fmt_b, op=chosen_op_word, res=random.choice(result_phrases), q_mark=random.choice(question_marks))\n", + " else: question_str = chosen_template.format(num_a=fmt_a, num_b=fmt_b, op=chosen_op_word, q_mark=random.choice(question_marks))\n", + " question_str = ' '.join(question_str.split())\n", + " except KeyError as e: question_str = f\"{fmt_a} {op_sym} {fmt_b} = ?\"\n", + " return question_str\n", + "def _generate_pair_meeting_cb_criteria(\n", + " target_digits_a: int, target_digits_b: int, sign_a: int, sign_b: int,\n", + " is_decimal: bool, max_decimal_places_config: int, operation_type: str, # is_decimal will be False, max_decimal_places_config will be 0\n", + " target_total_cb_min: int, target_total_cb_max: Union[int, float],\n", + " target_consecutive_cb_min: int, target_consecutive_cb_max: Union[int, float]\n", + ") -> Optional[Tuple[Union[int, Decimal], Union[int, Decimal]]]:\n", + " # With DECIMAL_PROBABILITY=0.0, is_decimal will be False.\n", + " # With MAX_DECIMAL_PLACES=0, max_decimal_places_config will be 0.\n", + " # Thus, num_dp will be 0 here.\n", + " num_dp = random.randint(1, max_decimal_places_config) if is_decimal and max_decimal_places_config > 0 else 0\n", + " \n", + " num_int_digits_a = max(1, target_digits_a); num_int_digits_b = max(1, target_digits_b)\n", + " # Since num_dp is 0, total_len_a is num_int_digits_a, etc.\n", + " total_len_a = num_int_digits_a + num_dp; total_len_b = num_int_digits_b + num_dp \n", + " max_total_len = max(total_len_a, total_len_b)\n", + "\n", + " effective_op = operation_type\n", + " if operation_type == 'add':\n", + " if sign_a * sign_b < 0: effective_op = 'subtract'\n", + " elif operation_type == 'subtract':\n", + " if sign_a * sign_b < 0: effective_op = 'add'\n", + " \n", + " op1_digits_rev = []; op2_digits_rev = []\n", + " carry_in = 0; borrow_in = 0\n", + " current_total_cb = 0; current_consecutive_cb = 0; max_consecutive_achieved = 0\n", + " \n", + " op1_target_len = total_len_a; op2_target_len = total_len_b\n", + " op1_int_digits = num_int_digits_a; op2_int_digits = num_int_digits_b\n", + " \n", + " is_unlimited_cb_range = (target_total_cb_min == 0 and target_total_cb_max == math.inf and \\\n", + " target_consecutive_cb_min == 0 and target_consecutive_cb_max == math.inf)\n", + "\n", + " for i in range(max_total_len): # Iterates through integer digits as num_dp is 0\n", + " pos_from_right = i; \n", + " is_decimal_pos = (pos_from_right < num_dp) # Always False as num_dp is 0\n", + " is_int_pos = not is_decimal_pos; # Always True\n", + " int_pos_from_right = pos_from_right - num_dp if is_int_pos else -1 # int_pos_from_right = pos_from_right\n", + "\n", + " in_op1 = (pos_from_right < op1_target_len); in_op2 = (pos_from_right < op2_target_len)\n", + " is_msd_op1_int = in_op1 and is_int_pos and int_pos_from_right == op1_int_digits - 1\n", + " is_msd_op2_int = in_op2 and is_int_pos and int_pos_from_right == op2_int_digits - 1\n", + " \n", + " min_d1 = 1 if is_msd_op1_int and op1_int_digits > 1 else 0; max_d1 = 9 if in_op1 else 0\n", + " min_d2 = 1 if is_msd_op2_int and op2_int_digits > 1 else 0; max_d2 = 9 if in_op2 else 0\n", + " \n", + " target_cb_state_for_this_pos = None\n", + " if not is_unlimited_cb_range:\n", + " positions_remaining = max_total_len - (i + 1)\n", + " min_total_cb_needed_later = max(0, target_total_cb_min - current_total_cb)\n", + " max_total_cb_allowed_later = float('inf') if target_total_cb_max == math.inf else target_total_cb_max - current_total_cb\n", + " if max_total_cb_allowed_later < 0: return None\n", + " min_consecutive_cb_needed_from_here = max(0, target_consecutive_cb_min - current_consecutive_cb)\n", + " \n", + " must_generate_cb = (min_total_cb_needed_later > positions_remaining) or \\\n", + " (min_consecutive_cb_needed_from_here > positions_remaining and \\\n", + " max_consecutive_achieved < target_consecutive_cb_min and \\\n", + " current_consecutive_cb < target_consecutive_cb_min)\n", + " must_avoid_cb_due_to_total = (max_total_cb_allowed_later < 1)\n", + " must_avoid_cb_due_to_consecutive = (current_consecutive_cb + 1 > target_consecutive_cb_max) if target_consecutive_cb_max != math.inf else False\n", + " must_avoid_cb = must_avoid_cb_due_to_total or must_avoid_cb_due_to_consecutive\n", + "\n", + " if must_generate_cb and must_avoid_cb : return None\n", + " if must_generate_cb: target_cb_state_for_this_pos = True\n", + " elif must_avoid_cb: target_cb_state_for_this_pos = False\n", + " else:\n", + " prob_try_generate_cb = 0.5\n", + " if min_total_cb_needed_later > 0 : prob_try_generate_cb += 0.2 * (min_total_cb_needed_later / max(1, positions_remaining +1))\n", + " if min_consecutive_cb_needed_from_here > 0 and max_consecutive_achieved < target_consecutive_cb_min : prob_try_generate_cb += 0.3\n", + " if target_total_cb_max != math.inf and max_total_cb_allowed_later <= positions_remaining : prob_try_generate_cb -= 0.2 * (1 - max_total_cb_allowed_later / max(1, positions_remaining +1))\n", + " if target_consecutive_cb_max != math.inf and current_consecutive_cb +1 >= target_consecutive_cb_max and min_consecutive_cb_needed_from_here == 0: prob_try_generate_cb = 0.1\n", + " prob_try_generate_cb = max(0.05, min(0.95, prob_try_generate_cb))\n", + " target_cb_state_for_this_pos = (random.random() < prob_try_generate_cb)\n", + "\n", + " found_d1_d2_pair_for_pos = False\n", + " possible_d1_values = list(range(min_d1, max_d1 + 1)); random.shuffle(possible_d1_values)\n", + " chosen_d1, chosen_d2 = -1, -1\n", + " for d1_try in possible_d1_values:\n", + " possible_d2_values_for_d1_try = []\n", + " d2_value_range = list(range(min_d2, max_d2 + 1)); random.shuffle(d2_value_range)\n", + " for d2_try in d2_value_range:\n", + " cb_generated_by_this_pair = False\n", + " if effective_op == 'add': cb_generated_by_this_pair = ((d1_try + d2_try + carry_in) >= 10)\n", + " else: cb_generated_by_this_pair = ((d1_try - borrow_in - d2_try) < 0)\n", + " \n", + " cb_state_matches_target = (target_cb_state_for_this_pos is None) or (cb_generated_by_this_pair == target_cb_state_for_this_pos)\n", + " temp_next_consecutive_cb = current_consecutive_cb + 1 if cb_generated_by_this_pair else 0\n", + " consecutive_constraint_ok = True\n", + " if target_consecutive_cb_max != math.inf and temp_next_consecutive_cb > target_consecutive_cb_max: consecutive_constraint_ok = False\n", + " \n", + " min_consecutive_still_achievable = True\n", + " if not cb_generated_by_this_pair and target_consecutive_cb_min > 0:\n", + " max_achieved_before_reset = max(max_consecutive_achieved, current_consecutive_cb)\n", + " if max_achieved_before_reset < target_consecutive_cb_min and positions_remaining < target_consecutive_cb_min : min_consecutive_still_achievable = False\n", + "\n", + " if cb_state_matches_target and consecutive_constraint_ok and min_consecutive_still_achievable: possible_d2_values_for_d1_try.append(d2_try)\n", + "\n", + " if possible_d2_values_for_d1_try:\n", + " chosen_d2 = random.choice(possible_d2_values_for_d1_try); chosen_d1 = d1_try\n", + " found_d1_d2_pair_for_pos = True; break\n", + " \n", + " if not found_d1_d2_pair_for_pos: return None\n", + " \n", + " op1_digits_rev.append(str(chosen_d1)); op2_digits_rev.append(str(chosen_d2))\n", + " \n", + " cb_occurred_at_this_pos = False\n", + " if effective_op == 'add':\n", + " current_sum_val = chosen_d1 + chosen_d2 + carry_in; carry_in = 1 if current_sum_val >= 10 else 0; borrow_in = 0\n", + " cb_occurred_at_this_pos = (carry_in == 1)\n", + " else: # subtract\n", + " current_diff_val = chosen_d1 - borrow_in - chosen_d2; borrow_in = 1 if current_diff_val < 0 else 0; carry_in = 0\n", + " cb_occurred_at_this_pos = (borrow_in == 1)\n", + " \n", + " if cb_occurred_at_this_pos: current_total_cb += 1; current_consecutive_cb += 1\n", + " else: max_consecutive_achieved = max(max_consecutive_achieved, current_consecutive_cb); current_consecutive_cb = 0\n", + "\n", + " max_consecutive_achieved = max(max_consecutive_achieved, current_consecutive_cb)\n", + " if not is_unlimited_cb_range:\n", + " total_cb_ok = (target_total_cb_min <= current_total_cb <= target_total_cb_max)\n", + " consecutive_cb_ok = (max_consecutive_achieved >= target_consecutive_cb_min) and \\\n", + " (target_consecutive_cb_max == math.inf or max_consecutive_achieved <= target_consecutive_cb_max)\n", + " if not (total_cb_ok and consecutive_cb_ok): return None\n", + "\n", + " op1_str_msd_first = \"\".join(reversed(op1_digits_rev)); op2_str_msd_first = \"\".join(reversed(op2_digits_rev))\n", + "\n", + " def _format_digit_str_to_decimal_val(s: str, dp_count: int) -> Decimal: # dp_count will be 0\n", + " if not s: s = \"0\"\n", + " if dp_count > 0: # This block will be skipped\n", + " if len(s) <= dp_count: s = s.zfill(dp_count + 1)\n", + " full_s_with_point = f\"{s[:-dp_count]}.{s[-dp_count:]}\"\n", + " else: # This path is taken\n", + " full_s_with_point = s\n", + " \n", + " # Clean up leading zeros for integers, e.g. \"007\" -> \"7\"\n", + " if '.' not in full_s_with_point:\n", + " full_s_with_point = full_s_with_point.lstrip('0') or \"0\"\n", + " else: # Should not happen if dp_count is 0\n", + " integer_part, fractional_part = full_s_with_point.split('.',1)\n", + " integer_part = integer_part.lstrip('0') or \"0\"\n", + " full_s_with_point = f\"{integer_part}.{fractional_part}\"\n", + " return Decimal(full_s_with_point)\n", + "\n", + " try:\n", + " val1_abs = _format_digit_str_to_decimal_val(op1_str_msd_first, num_dp)\n", + " val2_abs = _format_digit_str_to_decimal_val(op2_str_msd_first, num_dp)\n", + " \n", + " a_val_final_signed = val1_abs.copy_sign(sign_a); b_val_final_signed = val2_abs.copy_sign(sign_b)\n", + " \n", + " # Normalize -0 to 0 for consistency\n", + " if a_val_final_signed.is_zero() and a_val_final_signed.is_signed(): a_val_final_signed = Decimal('0')\n", + " if b_val_final_signed.is_zero() and b_val_final_signed.is_signed(): b_val_final_signed = Decimal('0')\n", + "\n", + " # Since is_decimal is False and num_dp is 0, these should be representable as ints\n", + " # Return as int if possible for type consistency, otherwise Decimal (e.g. if MAX_DIGITS is huge)\n", + " try:\n", + " a_final_val = int(a_val_final_signed)\n", + " except (OverflowError, TypeError): # TypeError if not perfectly int\n", + " a_final_val = a_val_final_signed \n", + " try:\n", + " b_final_val = int(b_val_final_signed)\n", + " except (OverflowError, TypeError):\n", + " b_final_val = b_val_final_signed\n", + " \n", + " return a_final_val, b_final_val\n", + " except InvalidOperation: return None\n", + " except Exception: return None\n", + "\n", + "\n", + "def check_carries_borrows(num1: Decimal, num2: Decimal, operation: str) -> Tuple[int, int]:\n", + " total_cb = 0; max_consecutive_cb = 0; current_consecutive_cb = 0\n", + " try:\n", + " effective_op = operation; op1: Decimal; op2: Decimal\n", + " # Ensure op1 and op2 are Decimal for consistent processing\n", + " d_num1 = Decimal(str(num1)) if not isinstance(num1, Decimal) else num1\n", + " d_num2 = Decimal(str(num2)) if not isinstance(num2, Decimal) else num2\n", + " \n", + " # Normalize for consistent sign checking, e.g. int(0) vs Decimal('0')\n", + " d_num1 = d_num1.normalize()\n", + " d_num2 = d_num2.normalize()\n", + " if d_num1.is_zero() and d_num1.is_signed(): d_num1 = Decimal('0')\n", + " if d_num2.is_zero() and d_num2.is_signed(): d_num2 = Decimal('0')\n", + "\n", + " if operation == 'add':\n", + " if d_num1.is_signed() != d_num2.is_signed(): # e.g. 5 + (-2) or -5 + 2\n", + " effective_op = 'subtract'\n", + " if abs(d_num1) >= abs(d_num2): op1, op2 = abs(d_num1), abs(d_num2)\n", + " else: op1, op2 = abs(d_num2), abs(d_num1)\n", + " else: # 5 + 2 or -5 + (-2)\n", + " effective_op = 'add'; op1, op2 = abs(d_num1), abs(d_num2)\n", + " elif operation == 'subtract':\n", + " if d_num1.is_signed() != d_num2.is_signed(): # e.g. 5 - (-2) or -5 - 2\n", + " effective_op = 'add'; op1, op2 = abs(d_num1), abs(d_num2)\n", + " else: # 5 - 2 or -5 - (-2)\n", + " effective_op = 'subtract'\n", + " if abs(d_num1) >= abs(d_num2): op1, op2 = abs(d_num1), abs(d_num2)\n", + " else: op1, op2 = abs(d_num2), abs(d_num1)\n", + " else: return -1, -1 # Should not happen\n", + "\n", + " if op1.is_zero() and op2.is_zero(): return 0, 0\n", + " \n", + " # Use format_decimal_or_int to get canonical integer strings\n", + " s1 = format_decimal_or_int(op1); s2 = format_decimal_or_int(op2)\n", + " \n", + " # Since they are integers, frac_part will be empty\n", + " s1_int_part, s1_frac_part = s1.split('.') if '.' in s1 else (s1, '')\n", + " s2_int_part, s2_frac_part = s2.split('.') if '.' in s2 else (s2, '')\n", + " \n", + " max_frac_len = max(len(s1_frac_part), len(s2_frac_part)) # Will be 0\n", + " s1_frac_part = s1_frac_part.ljust(max_frac_len, '0'); s2_frac_part = s2_frac_part.ljust(max_frac_len, '0')\n", + " \n", + " max_int_len = max(len(s1_int_part), len(s2_int_part))\n", + " s1_int_part = s1_int_part.zfill(max_int_len); s2_int_part = s2_int_part.zfill(max_int_len)\n", + " \n", + " aligned_s1 = s1_int_part + s1_frac_part; aligned_s2 = s2_int_part + s2_frac_part\n", + " full_len = len(aligned_s1)\n", + " \n", + " carry = 0; borrow = 0\n", + " for i in range(full_len - 1, -1, -1): # Iterate from rightmost (integer) digit\n", + " try: d1 = int(aligned_s1[i]); d2 = int(aligned_s2[i])\n", + " except (IndexError, ValueError): return -1, -1 \n", + " \n", + " cb_occurred_this_digit = False\n", + " if effective_op == 'add':\n", + " current_sum_digit = d1 + d2 + carry; carry = 1 if current_sum_digit >= 10 else 0\n", + " cb_occurred_this_digit = (carry == 1)\n", + " else: # subtract\n", + " current_diff_digit = d1 - borrow - d2; borrow = 1 if current_diff_digit < 0 else 0\n", + " cb_occurred_this_digit = (borrow == 1)\n", + " \n", + " if cb_occurred_this_digit: total_cb += 1; current_consecutive_cb += 1\n", + " else: max_consecutive_cb = max(max_consecutive_cb, current_consecutive_cb); current_consecutive_cb = 0\n", + " max_consecutive_cb = max(max_consecutive_cb, current_consecutive_cb)\n", + " except Exception as e: return -1, -1\n", + " return total_cb, max_consecutive_cb\n", + "\n", + "def write_batch_to_jsonl(buffer: List[Dict], filename: str, mode: str = 'a') -> int:\n", + " if not buffer: return 0\n", + " lines_written = 0; json_lines_to_write = []; serialization_errors = 0\n", + " for item in buffer:\n", + " try:\n", + " if not isinstance(item, dict) or not item.get(\"text\"): serialization_errors += 1; continue\n", + " json_string = json.dumps(item, ensure_ascii=False)\n", + " if json_string and not json_string.isspace(): json_lines_to_write.append(json_string)\n", + " else: serialization_errors += 1\n", + " except (TypeError, ValueError): serialization_errors += 1\n", + " except Exception: serialization_errors += 1\n", + " if json_lines_to_write:\n", + " try:\n", + " with open(filename, mode, encoding='utf-8') as f: f.write('\\n'.join(json_lines_to_write) + '\\n')\n", + " lines_written = len(json_lines_to_write)\n", + " except IOError: return 0\n", + " except Exception: return 0\n", + " if serialization_errors > 0: print(f\"\\n警告: 写入批次时 {serialization_errors} 个项目处理失败。\")\n", + " return lines_written\n", + "def randomly_replace_characters_in_string(text: str, replacement_prob: float, char_pool: str) -> str:\n", + " if not text or replacement_prob <= 0 or not char_pool: return text\n", + " new_chars = list(text)\n", + " for i in range(len(new_chars)):\n", + " if random.random() < replacement_prob:\n", + " if new_chars[i] not in ['\\n', '\\r']: new_chars[i] = random.choice(char_pool)\n", + " return \"\".join(new_chars)\n", + "\n", + "\n", + "# --- 主要生成函数 ---\n", + "def generate_constructed_arithmetic_diverse(\n", + " filename: str, total_samples: int, add_prob: float, \n", + " decimal_prob: float, # Will be 0.0\n", + " max_digits_limit: int, \n", + " max_decimal_places_cfg: int, # Will be 0\n", + " negative_pool_prob: float,\n", + " target_total_cb_min: int, target_total_cb_max: Union[int, float],\n", + " target_consecutive_cb_min: int, target_consecutive_cb_max: Union[int, float],\n", + " nl_question_prob: float,\n", + " symbolic_equals_suffix_prob: float,\n", + " max_attempts_factor: int,\n", + " batch_save_size: int,\n", + " apply_general_char_corr: bool,\n", + " general_char_corr_prob: float,\n", + " general_char_corr_pool: str\n", + " ):\n", + " print(f\"--- 开始生成算术数据 (v_int_fake_zeros) ---\")\n", + " print(f\"预期行为: 操作数为整数,问题中带1-5位随机小数0,答案为整数。\")\n", + " if RANDOMIZE_DIGITS_WITHIN_CHINESE_NUMBERS: print(f\"中文数字内字符样式随机化已启用。\")\n", + " else: print(\"中文数字内字符样式随机化未启用。\")\n", + " if CHINESE_DIGIT_BY_DIGIT_READING_PROB > 0: print(f\"中文逐��念读已启用 (概率: {CHINESE_DIGIT_BY_DIGIT_READING_PROB*100:.1f}%).\")\n", + " else: print(\"中文逐位念读未启用。\")\n", + " if APPLY_INTRA_CHAR_SPACING: print(f\"字符间随机空格已启用。\")\n", + " else: print(\"字符间随机空格未启用。\")\n", + " if apply_general_char_corr: print(f\"通用字符级损坏已启用: 概率={general_char_corr_prob*100:.2f}%\")\n", + " else: print(\"通用字符级损坏未启用。\")\n", + "\n", + " digit_pop: List[int] = []; digit_probs_list: List[float] = []\n", + " if max_digits_limit > 0:\n", + " digit_probabilities_dict = calculate_digit_probabilities(max_digits_limit)\n", + " digit_pop = list(range(1, max_digits_limit + 1)); digit_probs_list = [digit_probabilities_dict.get(n, 0.0) for n in digit_pop]\n", + " prob_sum_check = sum(digit_probs_list)\n", + " if not math.isclose(prob_sum_check, 1.0, abs_tol=1e-5):\n", + " if prob_sum_check > 1e-9: digit_probs_list = [p / prob_sum_check for p in digit_probs_list]\n", + " else: uniform_prob = 1.0 / len(digit_pop) if digit_pop else 1.0; digit_probs_list = [uniform_prob] * len(digit_pop)\n", + " if not digit_probs_list and digit_pop: digit_probs_list = [1.0/len(digit_pop)]*len(digit_pop)\n", + " elif not digit_pop : digit_pop = [1]; digit_probs_list = [1.0]\n", + " else: digit_pop = [1]; digit_probs_list = [1.0]\n", + " \n", + " generated_count = 0; total_attempts = 0; total_lines_written = 0\n", + " construct_failures = 0; add_count = 0; subtract_count = 0\n", + " integer_op_count = 0; decimal_op_count = 0 # decimal_op_count should be 0 or very low\n", + " format_counts = Counter(); question_type_counts = Counter(); suffix_counts = Counter()\n", + " errors_in_loop = 0\n", + " \n", + " difficulty_factor_cb = max(1, target_total_cb_min) if target_total_cb_max != math.inf else 1\n", + " difficulty_factor_cb = max(difficulty_factor_cb, target_consecutive_cb_min // 2 if target_consecutive_cb_max !=math.inf else 1)\n", + " max_total_attempts = total_samples * max(100, max_attempts_factor * difficulty_factor_cb)\n", + " \n", + " start_time_generate = time.time(); output_buffer = []; last_reported_count = -1; last_save_time = start_time_generate\n", + " try:\n", + " with open(filename, 'w', encoding='utf-8') as f: f.write(\"\")\n", + " print(f\"已初始化/清空输出文件: '{filename}'\")\n", + " except IOError as e: print(f\"\\n错误:无法初始化输出文件 '{filename}': {e}\"); return\n", + " print(f\"\\n开始构造 {total_samples:,} 条满足条件的数据...\")\n", + " \n", + " while generated_count < total_samples:\n", + " total_attempts += 1\n", + " if total_attempts > max_total_attempts:\n", + " print(f\"\\n\\n警告: 尝试次数达到上限 ({total_attempts:,})。\"); print(f\"当前已生成: {generated_count:,} (构造失败 {construct_failures:,} 次).\"); print(\"脚本提前终止.\"); break\n", + " \n", + " a: Union[int, Decimal] = 0; b: Union[int, Decimal] = 0 # Expecting int or Decimal(int_value)\n", + " try:\n", + " # 1. 选择基本参数\n", + " if not digit_pop or not digit_probs_list or len(digit_pop) != len(digit_probs_list):\n", + " digits_a = random.randint(1, max(1,max_digits_limit)); digits_b = random.randint(1, max(1,max_digits_limit))\n", + " else:\n", + " digits_a = get_distributed_count_from_probs(digit_pop, digit_probs_list); digits_b = get_distributed_count_from_probs(digit_pop, digit_probs_list)\n", + " \n", + " sign_a = -1 if random.random() < negative_pool_prob else 1\n", + " sign_b = -1 if random.random() < negative_pool_prob else 1\n", + " \n", + " # is_dec_intent_current will be False due to decimal_prob=0.0\n", + " is_dec_intent_current = random.random() < decimal_prob \n", + " op_type_current = 'add' if random.random() < add_prob else 'subtract'\n", + " op_sym_current = '+' if op_type_current == 'add' else '-'\n", + "\n", + " # 2. 构造数字对 (a,b) - will be integers due to is_dec_intent_current=False and max_decimal_places_cfg=0\n", + " constructed_pair = _generate_pair_meeting_cb_criteria(\n", + " digits_a, digits_b, sign_a, sign_b, \n", + " is_dec_intent_current, # False\n", + " max_decimal_places_cfg, # 0\n", + " op_type_current, target_total_cb_min, target_total_cb_max,\n", + " target_consecutive_cb_min, target_consecutive_cb_max)\n", + " \n", + " if constructed_pair is None: construct_failures += 1; continue\n", + " a, b = constructed_pair # a and b should be int or Decimal(int_value)\n", + "\n", + " # 3. 计算结果 c\n", + " c_final: Union[int, Decimal]; answer_str = \"\"\n", + " try:\n", + " # Ensure a_calc and b_calc are Decimal for arithmetic\n", + " a_calc = Decimal(str(a)) if not isinstance(a, Decimal) else a\n", + " b_calc = Decimal(str(b)) if not isinstance(b, Decimal) else b\n", + "\n", + " if not a_calc.is_finite() or not b_calc.is_finite(): errors_in_loop += 1; continue\n", + " c_calc = a_calc + b_calc if op_type_current == 'add' else a_calc - b_calc\n", + " if not c_calc.is_finite(): errors_in_loop += 1; continue\n", + " \n", + " # Determine result decimal places. Since a,b are int, effective_dp will be 0.\n", + " # max_decimal_places_cfg is also 0. So result_dp will be 0.\n", + " effective_dp_a = 0\n", + " if isinstance(a_calc, Decimal) and a_calc.as_tuple().exponent < 0: # Should not be true\n", + " effective_dp_a = abs(a_calc.as_tuple().exponent)\n", + " effective_dp_b = 0\n", + " if isinstance(b_calc, Decimal) and b_calc.as_tuple().exponent < 0: # Should not be true\n", + " effective_dp_b = abs(b_calc.as_tuple().exponent)\n", + " \n", + " result_dp = max(effective_dp_a, effective_dp_b) # result_dp = 0\n", + " result_dp = min(result_dp, max_decimal_places_cfg) # result_dp = min(0, 0) = 0\n", + " \n", + " # Quantize to integer\n", + " if result_dp > 0: # False\n", + " c_final_dec = c_calc.quantize(Decimal('1e-' + str(result_dp)), rounding=ROUND_HALF_UP)\n", + " else: # True\n", + " c_final_dec = c_calc.to_integral_value(rounding=ROUND_HALF_UP)\n", + " \n", + " c_final_dec = c_final_dec.normalize()\n", + " if c_final_dec.is_zero() and c_final_dec.is_signed(): c_final_dec = Decimal('0')\n", + " \n", + " # c_final should be an integer\n", + " # is_a_actually_int and is_b_actually_int will be true\n", + " is_a_actually_int = isinstance(a, int) or (isinstance(a, Decimal) and a == a.to_integral_value())\n", + " is_b_actually_int = isinstance(b, int) or (isinstance(b, Decimal) and b == b.to_integral_value())\n", + " is_c_actually_int = (c_final_dec == c_final_dec.to_integral_value()) # True\n", + "\n", + " if is_c_actually_int and is_a_actually_int and is_b_actually_int and not is_dec_intent_current: # All true\n", + " try: c_final = int(c_final_dec)\n", + " except (OverflowError, ValueError): c_final = c_final_dec # Fallback if too large for int\n", + " else: # Should not happen\n", + " c_final = c_final_dec \n", + " \n", + " # Answer string is the plain integer\n", + " answer_str = format_decimal_or_int(c_final) \n", + " except (InvalidOperation, OverflowError, ValueError, ArithmeticError) as e_calc: errors_in_loop += 1; continue\n", + " except Exception as e_calc_generic: errors_in_loop += 1; continue\n", + " if not answer_str: errors_in_loop += 1; continue\n", + "\n", + " # 4. 多样化格式化 (问题部分)\n", + " # format_number_variant will add fake zeros to a and b if they are integers\n", + " try:\n", + " fmt_a_str_processed, fmt_a_type = format_number_variant(a)\n", + " \n", + " final_op_sym_for_question = op_sym_current; fmt_b_str_processed, fmt_b_type = \"\", \"\"\n", + " try:\n", + " b_dec_for_fmt = Decimal(str(b)) if not isinstance(b, Decimal) else b\n", + " b_dec_for_fmt_norm = b_dec_for_fmt.normalize()\n", + " if b_dec_for_fmt_norm.is_zero() and b_dec_for_fmt_norm.is_signed(): b_dec_for_fmt_norm = Decimal('0')\n", + "\n", + " if b_dec_for_fmt_norm.is_signed() and b_dec_for_fmt_norm < 0:\n", + " fmt_b_abs_str_processed, fmt_b_abs_type = format_number_variant(abs(b_dec_for_fmt))\n", + " fmt_b_str_processed = fmt_b_abs_str_processed; fmt_b_type = fmt_b_abs_type\n", + " if op_sym_current == '+': final_op_sym_for_question = '-'\n", + " elif op_sym_current == '-': final_op_sym_for_question = '+'\n", + " else: \n", + " fmt_b_str_processed, fmt_b_type = format_number_variant(b)\n", + " except (InvalidOperation, TypeError, ValueError) as e_fmt_b:\n", + " fmt_b_str_processed, fmt_b_type = format_number_variant(b) # Fallback\n", + "\n", + " if not fmt_a_str_processed or not fmt_b_str_processed: errors_in_loop +=1; continue\n", + " format_counts[f'a_{fmt_a_type}'] += 1; format_counts[f'b_{fmt_b_type}'] += 1\n", + "\n", + " # 5. 构建问题字符串\n", + " question_str = \"\"\n", + " a_is_chinese_style = fmt_a_type in ['simple_zh', 'complex_zh']\n", + " b_is_chinese_style = fmt_b_type in ['simple_zh', 'complex_zh']\n", + " is_nl_question_current = (random.random() < nl_question_prob) and not (a_is_chinese_style or b_is_chinese_style)\n", + " if is_nl_question_current:\n", + " question_type_counts['natural_language'] += 1\n", + " question_str = format_natural_language_question(fmt_a_str_processed, fmt_b_str_processed, final_op_sym_for_question)\n", + " else:\n", + " question_type_counts['symbolic'] += 1\n", + " space1_op = get_realistic_spacing(); space2_op = get_realistic_spacing()\n", + " question_str_base = f\"{fmt_a_str_processed}{space1_op}{final_op_sym_for_question}{space2_op}{fmt_b_str_processed}\"\n", + " question_suffix = \"\"; added_suffix_flag = False\n", + " if random.random() < symbolic_equals_suffix_prob:\n", + " q_mark = random.choice([\"?\", \"?\"]); space_eq1 = get_realistic_spacing(); space_eq2 = get_realistic_spacing()\n", + " question_suffix = f\"{space_eq1}={space_eq2}{q_mark}\"; added_suffix_flag = True\n", + " suffix_counts['symbolic_added' if added_suffix_flag else 'symbolic_not_added'] += 1\n", + " question_str = question_str_base + question_suffix\n", + " if not question_str or question_str.isspace(): errors_in_loop += 1; continue\n", + "\n", + " text_content = f\"User: {question_str}\\n\\nAssistant: {answer_str}\"\n", + "\n", + " if apply_general_char_corr:\n", + " text_content = randomly_replace_characters_in_string(text_content, general_char_corr_prob, general_char_corr_pool)\n", + " \n", + " pair_data = {\"text\": text_content}\n", + " \n", + " generated_count += 1\n", + " if op_type_current == 'add': add_count += 1\n", + " else: subtract_count += 1\n", + " \n", + " # All ops should be integer ops\n", + " is_a_truly_decimal_val = isinstance(a, Decimal) and a != a.to_integral_value()\n", + " is_b_truly_decimal_val = isinstance(b, Decimal) and b != b.to_integral_value()\n", + " is_c_truly_decimal_val = isinstance(c_final, Decimal) and c_final != c_final.to_integral_value()\n", + " if is_dec_intent_current or is_a_truly_decimal_val or is_b_truly_decimal_val or is_c_truly_decimal_val: \n", + " decimal_op_count += 1 # Should be 0\n", + " else: \n", + " integer_op_count += 1\n", + "\n", + " output_buffer.append(pair_data)\n", + "\n", + " if len(output_buffer) >= batch_save_size:\n", + " write_op_start_time = time.time()\n", + " num_written_this_batch = write_batch_to_jsonl(output_buffer, filename, mode='a')\n", + " write_op_duration = time.time() - write_op_start_time\n", + " if num_written_this_batch > 0:\n", + " total_lines_written += num_written_this_batch\n", + " avg_save_sps = num_written_this_batch / write_op_duration if write_op_duration > 0 else float('inf')\n", + " print(f\"\\r--- 已保存批次 {num_written_this_batch:>6,} (耗时 {write_op_duration:.2f}s, {avg_save_sps:.1f}/s). 总计写入: {total_lines_written:>8,} / 生成: {generated_count:>8,} ---{' '*5}\", end=\"\")\n", + " output_buffer.clear(); last_save_time = time.time()\n", + " else:\n", + " print(f\"\\n警告: 写入批处理失败 (已生成 {generated_count:,} 条)。缓冲区已清空.\")\n", + " errors_in_loop += len(output_buffer); output_buffer.clear()\n", + " except Exception as format_stage_error: errors_in_loop += 1; traceback.print_exc(); continue # Print traceback for formatting errors\n", + " except KeyboardInterrupt: print(\"\\n用户中断。\"); break\n", + " except Exception as main_loop_iter_error: errors_in_loop += 1; traceback.print_exc(); continue # Print traceback for main loop errors\n", + " \n", + " report_freq_interval = max(1, total_samples // 200) if total_samples > 0 else 1000\n", + " current_time = time.time(); time_since_last_activity = current_time - max(last_save_time, start_time_generate if last_reported_count == -1 else last_save_time)\n", + " if generated_count > 0 and (generated_count % report_freq_interval == 0 or generated_count == total_samples or time_since_last_activity > 15):\n", + " if last_reported_count != generated_count:\n", + " progress_percent = generated_count / total_samples if total_samples > 0 else 0; elapsed_seconds = current_time - start_time_generate\n", + " samples_per_sec_rate = generated_count / elapsed_seconds if elapsed_seconds > 0 else 0\n", + " attempts_per_gen_sample = total_attempts / generated_count if generated_count > 0 else float('inf')\n", + " construct_failure_rate = construct_failures / total_attempts if total_attempts > 0 else 0; est_remaining_time_str = \"N/A\"\n", + " if progress_percent > 1e-6 and samples_per_sec_rate > 0:\n", + " remaining_samples_to_gen = total_samples - generated_count; est_remaining_seconds = remaining_samples_to_gen / samples_per_sec_rate\n", + " if est_remaining_seconds < 60: est_remaining_time_str = f\"{est_remaining_seconds:.0f}s\"\n", + " elif est_remaining_seconds < 3600: est_remaining_time_str = f\"{est_remaining_seconds/60:.1f}m\"\n", + " else: est_remaining_time_str = f\"{est_remaining_seconds/3600:.1f}h\"\n", + " stats_line = f\"生成: {generated_count:>8,}/{total_samples:<8,} ({progress_percent:5.1%}) | 写入: {total_lines_written:>8,} | 尝试: {total_attempts:>9,} ({attempts_per_gen_sample:5.1f}/样本) | 失败率: {construct_failure_rate:5.1%} | {samples_per_sec_rate:6.1f} 样本/秒 | 耗时: {elapsed_seconds:6.1f}s | 剩余: ~{est_remaining_time_str:<5}\"\n", + " print(f\"\\r{stats_line.ljust(120)}\", end=\"\"); last_reported_count = generated_count\n", + "\n", + " print(\" \" * 120, end=\"\\r\"); print(f\"\\n构造循环结束。目标: {total_samples:,}, 实际生成: {generated_count:,} (尝试 {total_attempts:,} 次, 构造失败 {construct_failures:,} 次).\")\n", + " if output_buffer:\n", + " print(f\"写入最后 {len(output_buffer):,} 条数据...\"); final_write_start = time.time()\n", + " num_final_written = write_batch_to_jsonl(output_buffer, filename, mode='a'); final_write_duration = time.time() - final_write_start\n", + " if num_final_written > 0: total_lines_written += num_final_written; print(f\"最终批次写入完成 ({num_final_written:,} 条). 耗时: {final_write_duration:.2f}s.\")\n", + " else: print(\"警告: 最终批次写入失败.\"); errors_in_loop += len(output_buffer)\n", + " output_buffer.clear()\n", + " else: print(\"无剩余数据需写入.\")\n", + " total_generation_end_time = time.time(); total_generation_duration = total_generation_end_time - start_time_generate\n", + " print(f\"\\n生成与写入完毕。目标: {total_samples:,} -> 生成: {generated_count:,} -> 写入: {total_lines_written:,}\")\n", + " if total_lines_written != generated_count and generated_count > 0: print(f\"警告: 写入行数({total_lines_written:,}) 与 生成数({generated_count:,}) 不匹配!\")\n", + " avg_attempts_per_actual_sample = total_attempts / max(1, generated_count) if generated_count > 0 else float('inf')\n", + " overall_construct_failure_rate = construct_failures / total_attempts if total_attempts > 0 else 0\n", + " print(f\"总尝试次数: {total_attempts:,} (平均 {avg_attempts_per_actual_sample:.2f} 次/有效样本)\")\n", + " print(f\"构造失败次数: {construct_failures:,} (失败率: {overall_construct_failure_rate:.2%})\")\n", + " print(f\"总耗时: {total_generation_duration:.2f} 秒。格式化/计算/写入等循环内错误: {errors_in_loop:,}.\")\n", + " print(\"\\n\" + \"=\"*15 + \" 详细统计 (基于生成的有效样本) \" + \"=\"*15)\n", + " if generated_count > 0:\n", + " print(f\"总有效样本: {generated_count:,}\")\n", + " print(\"-\" * 50); print(\"1. 算术题类型:\"); print(f\" - 加法: {add_count:>10,} ({add_count/generated_count:>7.1%})\"); print(f\" - 减法: {subtract_count:>10,} ({subtract_count/generated_count:>7.1%})\")\n", + " print(\"-\" * 50); print(\"2. 运算数类型:\"); print(f\" - 纯整数运算*: {integer_op_count:>10,} ({integer_op_count/generated_count:>7.1%})\"); print(f\" - 含小数运算*: {decimal_op_count:>10,} ({decimal_op_count/generated_count:>7.1%})\"); print(\" *注: 基于操作数或结果是否包含实际小数部分,或生成意图是否为小数。\")\n", + " total_fmt_a_counts = sum(format_counts[k] for k in format_counts if k.startswith('a_')); print(\"-\" * 50); print(f\"3. 问题格式 - 操作数 A (总计: {total_fmt_a_counts:,}):\")\n", + " ordered_fmt_keys_a = ['a_standard', 'a_full_width', 'a_simple_zh', 'a_complex_zh']; [print(f\" - {fmt_key[2:]: <15}: {format_counts.get(fmt_key, 0):>10,} ({(format_counts.get(fmt_key, 0) / total_fmt_a_counts * 100) if total_fmt_a_counts > 0 else 0:>6.1f}%)\") for fmt_key in ordered_fmt_keys_a]\n", + " total_fmt_b_counts = sum(format_counts[k] for k in format_counts if k.startswith('b_')); print(\"-\" * 50); print(f\"4. 问题格式 - 操作数 B (总计: {total_fmt_b_counts:,}):\")\n", + " ordered_fmt_keys_b = ['b_standard', 'b_full_width', 'b_simple_zh', 'b_complex_zh']; [print(f\" - {fmt_key[2:]: <15}: {format_counts.get(fmt_key, 0):>10,} ({(format_counts.get(fmt_key, 0) / total_fmt_b_counts * 100) if total_fmt_b_counts > 0 else 0:>6.1f}%)\") for fmt_key in ordered_fmt_keys_b]\n", + " \n", + " total_q_type_counts = sum(question_type_counts.values())\n", + " print(\"-\" * 50); print(f\"5. 问题格式 - 类型 (总计: {total_q_type_counts:,}):\")\n", + " ordered_q_type_keys = ['symbolic', 'natural_language']\n", + " display_name_map_qtype = {'symbolic': '符号格式 (+/-)', 'natural_language': '自然语言格式'}\n", + " for q_type_key in ordered_q_type_keys:\n", + " count = question_type_counts.get(q_type_key, 0)\n", + " percent = count / total_q_type_counts * 100 if total_q_type_counts > 0 else 0\n", + " display_name = display_name_map_qtype.get(q_type_key, q_type_key)\n", + " print(f\" - {display_name: <22}: {count:>10,} ({percent:>6.1f}%)\")\n", + "\n", + " total_symbolic_suffix_counts = suffix_counts.get('symbolic_added', 0) + suffix_counts.get('symbolic_not_added', 0)\n", + " print(\"-\" * 50); print(f\"6. 符号问题格式 - 等号后缀 (总计符号问题: {total_symbolic_suffix_counts:,}):\")\n", + " ordered_suffix_keys = ['symbolic_added', 'symbolic_not_added']\n", + " display_name_map_suffix = {'symbolic_added': '添加 \" = ?/?\"', 'symbolic_not_added': '未添加后缀'}\n", + " for suffix_key in ordered_suffix_keys:\n", + " count = suffix_counts.get(suffix_key,0)\n", + " percent = count / total_symbolic_suffix_counts * 100 if total_symbolic_suffix_counts > 0 else 0\n", + " display_name = display_name_map_suffix.get(suffix_key, suffix_key)\n", + " print(f\" - {display_name: <18}: {count:>10,} ({percent:>6.1f}%)\")\n", + " print(\"=\"*50)\n", + " else: print(\"\\n--- 未生成有效样本,无详细统计 ---\"); print(\"=\"*50)\n", + "\n", + "# ===============================================\n", + "# 主程序入口\n", + "# ===============================================\n", + "if __name__ == \"__main__\":\n", + " script_total_start_time = time.time()\n", + " print(\"=\"*30); print(\" 算术题生成脚本 (Integer with Fake Zeros Mod) \"); print(\"=\"*30)\n", + " \n", + " # max_possible_digits_overall only considers integer part now\n", + " max_possible_digits_overall = MAX_DIGITS \n", + " if max_possible_digits_overall <= 0: print(\"!!! 配置错误: MAX_DIGITS 必须大于0。脚本终止.\"); exit()\n", + " \n", + " # CB checks remain based on MAX_DIGITS as decimals are fake\n", + " max_possible_cb_rough_estimate = MAX_DIGITS \n", + " if TARGET_TOTAL_CARRIES_MAX != math.inf and TARGET_TOTAL_CARRIES_MIN > max_possible_cb_rough_estimate: print(f\"\\n!!! 配置警告: 目标最小总进/借位数 ({TARGET_TOTAL_CARRIES_MIN}) > 估算的位数上限 ({max_possible_cb_rough_estimate})。可能难以构造或无法构造。 !!!\")\n", + " if TARGET_CONSECUTIVE_CARRIES_MAX != math.inf and TARGET_CONSECUTIVE_CARRIES_MIN > max_possible_cb_rough_estimate: print(f\"\\n!!! 配置警告: 目标最小连续进/借位数 ({TARGET_CONSECUTIVE_CARRIES_MIN}) > 估算的位数上限 ({max_possible_cb_rough_estimate})。可能难以构造或无法构造。 !!!\")\n", + " if TARGET_TOTAL_CARRIES_MAX != 0 and TARGET_CONSECUTIVE_CARRIES_MIN > TARGET_TOTAL_CARRIES_MIN: print(f\"\\n!!! 配置提示: 目标最小连续数 ({TARGET_CONSECUTIVE_CARRIES_MIN}) 大于目标最小总数 ({TARGET_TOTAL_CARRIES_MIN})。\")\n", + "\n", + " try:\n", + " generate_constructed_arithmetic_diverse(\n", + " filename=OUTPUT_FILENAME,\n", + " total_samples=TOTAL_SAMPLES,\n", + " add_prob=ADD_PROBABILITY,\n", + " decimal_prob=DECIMAL_PROBABILITY, # 0.0\n", + " max_digits_limit=MAX_DIGITS,\n", + " max_decimal_places_cfg=MAX_DECIMAL_PLACES, # 0\n", + " negative_pool_prob=NEGATIVE_POOL_PROB,\n", + " target_total_cb_min=TARGET_TOTAL_CARRIES_MIN,\n", + " target_total_cb_max=TARGET_TOTAL_CARRIES_MAX,\n", + " target_consecutive_cb_min=TARGET_CONSECUTIVE_CARRIES_MIN,\n", + " target_consecutive_cb_max=TARGET_CONSECUTIVE_CARRIES_MAX,\n", + " nl_question_prob=NL_QUESTION_PROBABILITY,\n", + " symbolic_equals_suffix_prob=SYMBOLIC_EQUALS_SUFFIX_PROB,\n", + " max_attempts_factor=MAX_ATTEMPTS_FACTOR,\n", + " batch_save_size=BATCH_SAVE_SIZE,\n", + " apply_general_char_corr=APPLY_GENERAL_CHAR_REPLACEMENT,\n", + " general_char_corr_prob=GENERAL_CHAR_REPLACEMENT_PROBABILITY,\n", + " general_char_corr_pool=GENERAL_CHAR_REPLACEMENT_POOL\n", + " )\n", + " except ValueError as val_err: print(f\"\\n配置或值错误: {val_err}\"); traceback.print_exc()\n", + " except MemoryError: print(\"\\n内存错误: 尝试减少 BATCH_SAVE_SIZE 或 TOTAL_SAMPLES。\"); traceback.print_exc()\n", + " except Exception as main_exec_err: print(f\"\\n主程序发生未预料错误: {main_exec_err}\"); traceback.print_exc()\n", + " finally: pass\n", + "\n", + " script_total_end_time = time.time()\n", + " print(\"\\n\" + \"=\"*30); print(f\"脚本执行完毕。总耗时: {script_total_end_time - script_total_start_time:.2f} 秒。\"); print(f\"数据文件: {OUTPUT_FILENAME}\"); print(\"=\"*30)" + ] + }, + { + "cell_type": "markdown", + "id": "53db93ff", + "metadata": {}, + "source": [ + "# 检查有多少行含小数\n", + "\n", + "检查指定 jsonl 文件和指定文件夹中的全部 jsonl 文件中有多少行的答案含小数的代码;" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "a5599a50", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "文件中包含小数点的行数: 1181364\n", + "文件中的总行数: 1542000\n" + ] + } + ], + "source": [ + "import json # 导入json模块是好习惯,尽管在这个特定版本中没有直接使用其解析功能\n", + "\n", + "def count_decimal_lines_in_jsonl(filepath):\n", + " \"\"\"\n", + " 读取 JSONL 文件,统计包含小数点的行数和总行数。\n", + "\n", + " Args:\n", + " filepath (str): JSONL 文件的路径。\n", + "\n", + " Returns:\n", + " tuple: (count_lines_with_decimals, total_lines_processed)\n", + " 如果发生错误,则返回 (None, None)。\n", + " \"\"\"\n", + " count_lines_with_decimals = 0\n", + " total_lines_processed = 0\n", + "\n", + " try:\n", + " with open(filepath, 'r', encoding='utf-8') as f:\n", + " for line_content in f:\n", + " # 移除行首尾的空白字符(主要是换行符 \\n)\n", + " stripped_line = line_content.strip()\n", + "\n", + " # 如果 stripping 后行为空,我们仍然将其计为一行已处理。\n", + " # 如果不想计空行,可以加一个判断: if not stripped_line: continue\n", + " total_lines_processed += 1\n", + "\n", + " # 检查原始行字符串中是否含有小数点\n", + " if '.' in stripped_line:\n", + " count_lines_with_decimals += 1\n", + " # 根据需求 \"如果有则直接跳到下一行\",\n", + " # 如果在此 if 条件块之后还有其他*仅针对不含小数点行*的处理逻辑,\n", + " # 那么这里的 'continue' 语句将确保跳过那些逻辑。\n", + " # 对于当前仅计数的任务,'continue' 不是必需的,因为循环会自然进行到下一行。\n", + " # continue # 如果有后续针对非小数点行的逻辑,可以取消此行注释\n", + "\n", + " except FileNotFoundError:\n", + " print(f\"错误: 文件 '{filepath}' 未找到。\")\n", + " return None, None\n", + " except Exception as e:\n", + " print(f\"处理文件时发生错误: {e}\")\n", + " return None, None\n", + "\n", + " return count_lines_with_decimals, total_lines_processed\n", + "\n", + "\n", + "if __name__ == \"__main__\":\n", + "\n", + "\n", + " test_file_path = \"./ADD_use-connect.jsonl\"\n", + "\n", + " # 调用函数处理文件\n", + " decimal_count, total_count = count_decimal_lines_in_jsonl(test_file_path)\n", + "\n", + " # 输出结果\n", + " if decimal_count is not None and total_count is not None:\n", + " print(f\"文件中包含小数点的行数: {decimal_count}\")\n", + " print(f\"文件中的总行数: {total_count}\")\n", + " else:\n", + " print(\"未能成功处理文件。\")\n" + ] + }, + { + "cell_type": "markdown", + "id": "3a8ebb62", + "metadata": {}, + "source": [ + "## 检查一整个文件夹" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "d8e5ecf7", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "创建测试文件: ./test_data.jsonl\n", + "\n", + "正在处理文件: ADD_2M.jsonl\n", + "文件 'ADD_2M.jsonl' 中 'Assistant:' 后包含小数点的行数: 328215\n", + "文件 'ADD_2M.jsonl' 中的总行数: 1999673\n", + "\n", + "正在处理文件: ADD_4M.jsonl\n", + "文件 'ADD_4M.jsonl' 中 'Assistant:' 后包含小数点的行数: 584754\n", + "文件 'ADD_4M.jsonl' 中的总行数: 3997733\n", + "\n", + "正在处理文件: ADD_base_8M.jsonl\n", + "文件 'ADD_base_8M.jsonl' 中 'Assistant:' 后包含小数点的行数: 0\n", + "文件 'ADD_base_8M.jsonl' 中的总行数: 7992002\n", + "\n", + "正在处理文件: ADD_en.jsonl\n", + "文件 'ADD_en.jsonl' 中 'Assistant:' 后包含小数点的行数: 390459\n", + "文件 'ADD_en.jsonl' 中的总行数: 976394\n", + "\n", + "正在处理文件: ADD_en_base_1M.jsonl\n", + "文件 'ADD_en_base_1M.jsonl' 中 'Assistant:' 后包含小数点的行数: 0\n", + "文件 'ADD_en_base_1M.jsonl' 中的总行数: 1000000\n", + "\n", + "正在处理文件: ADD_en_base_500k.jsonl\n", + "文件 'ADD_en_base_500k.jsonl' 中 'Assistant:' 后包含小数点的行数: 0\n", + "文件 'ADD_en_base_500k.jsonl' 中的总行数: 1000000\n", + "\n", + "正在处理文件: ADD_en_by-desc.jsonl\n", + "文件 'ADD_en_by-desc.jsonl' 中 'Assistant:' 后包含小数点的行数: 195833\n", + "文件 'ADD_en_by-desc.jsonl' 中的总行数: 489961\n", + "\n", + "正在处理文件: ADD_en_random_mix.jsonl\n", + "文件 'ADD_en_random_mix.jsonl' 中 'Assistant:' 后包含小数点的行数: 585917\n", + "文件 'ADD_en_random_mix.jsonl' 中的总行数: 1464727\n", + "\n", + "正在处理文件: ADD_many0_50k.jsonl\n", + "文件 'ADD_many0_50k.jsonl' 中 'Assistant:' 后包含小数点的行数: 0\n", + "文件 'ADD_many0_50k.jsonl' 中的总行数: 50000\n", + "\n", + "正在处理文件: ADD_n1m0.jsonl\n", + "文件 'ADD_n1m0.jsonl' 中 'Assistant:' 后包含小数点的行数: 54611\n", + "文件 'ADD_n1m0.jsonl' 中的总行数: 270887\n", + "\n", + "正在处理文件: ADD_n1m1.jsonl\n", + "文件 'ADD_n1m1.jsonl' 中 'Assistant:' 后包含小数点的行数: 28533\n", + "文件 'ADD_n1m1.jsonl' 中的总行数: 199900\n", + "\n", + "正在处理文件: ADD_n2m0.jsonl\n", + "文件 'ADD_n2m0.jsonl' 中 'Assistant:' 后包含小数点的行数: 63265\n", + "文件 'ADD_n2m0.jsonl' 中的总行数: 270798\n", + "\n", + "正在处理文件: ADD_n2m1.jsonl\n", + "文件 'ADD_n2m1.jsonl' 中 'Assistant:' 后包含小数点的行数: 29287\n", + "文件 'ADD_n2m1.jsonl' 中的总行数: 199847\n", + "\n", + "正在处理文件: ADD_n3m0.jsonl\n", + "文件 'ADD_n3m0.jsonl' 中 'Assistant:' 后包含小数点的行数: 72403\n", + "文件 'ADD_n3m0.jsonl' 中的总行数: 270853\n", + "\n", + "正在处理文件: ADD_n4m3.jsonl\n", + "文件 'ADD_n4m3.jsonl' 中 'Assistant:' 后包含小数点的行数: 83920\n", + "文件 'ADD_n4m3.jsonl' 中的总行数: 271345\n", + "\n", + "正在处理文件: ADD_random_0.25M.jsonl\n", + "文件 'ADD_random_0.25M.jsonl' 中 'Assistant:' 后包含小数点的行数: 97604\n", + "文件 'ADD_random_0.25M.jsonl' 中的总行数: 249735\n", + "\n", + "正在处理文件: ADD_random_4M.jsonl\n", + "文件 'ADD_random_4M.jsonl' 中 'Assistant:' 后包含小数点的行数: 1758574\n", + "文件 'ADD_random_4M.jsonl' 中的总行数: 4494484\n", + "\n", + "正在处理文件: ADD_use-connect.jsonl\n", + "文件 'ADD_use-connect.jsonl' 中 'Assistant:' 后包含小数点的行数: 1181364\n", + "文件 'ADD_use-connect.jsonl' 中的总行数: 1542000\n", + "\n", + "正在处理文件: qa_error.jsonl\n", + "文件 'qa_error.jsonl' 中 'Assistant:' 后包含小数点的行数: 0\n", + "文件 'qa_error.jsonl' 中的总行数: 248\n", + "\n", + "正在处理文件: qa_gibberish_unanswerable.jsonl\n", + "文件 'qa_gibberish_unanswerable.jsonl' 中 'Assistant:' 后包含小数点的行数: 0\n", + "文件 'qa_gibberish_unanswerable.jsonl' 中的总行数: 10000\n", + "\n", + "正在处理文件: test_data.jsonl\n", + "文件 'test_data.jsonl' 中 'Assistant:' 后包含小数点的行数: 5\n", + "文件 'test_data.jsonl' 中的总行数: 7\n", + "\n", + "正在处理文件: X_ch_en_mix.jsonl\n", + "文件 'X_ch_en_mix.jsonl' 中 'Assistant:' 后包含小数点的行数: 159485\n", + "文件 'X_ch_en_mix.jsonl' 中的总行数: 250000\n", + "\n", + "正在处理文件: X_ch_mix.jsonl\n", + "文件 'X_ch_mix.jsonl' 中 'Assistant:' 后包含小数点的行数: 1277448\n", + "文件 'X_ch_mix.jsonl' 中的总行数: 2000000\n", + "\n", + "正在处理文件: X_en_random_mix.jsonl\n", + "文件 'X_en_random_mix.jsonl' 中 'Assistant:' 后包含小数点的行数: 640225\n", + "文件 'X_en_random_mix.jsonl' 中的总行数: 1000000\n", + "\n", + "===== 汇总结果 =====\n", + "\n", + "文件: ADD_2M.jsonl\n", + "'Assistant:' 后包含小数点的行数: 328215\n", + "总行数: 1999673\n", + "目标行('Assistant:'后有小数点)占总行数比例: 16.41%\n", + "\n", + "文件: ADD_4M.jsonl\n", + "'Assistant:' 后包含小数点的行数: 584754\n", + "总行数: 3997733\n", + "目标行('Assistant:'后有小数点)占总行数比例: 14.63%\n", + "\n", + "文件: ADD_base_8M.jsonl\n", + "'Assistant:' 后包含小数点的行数: 0\n", + "总行数: 7992002\n", + "目标行('Assistant:'后有小数点)占总行数比例: 0.00%\n", + "\n", + "文件: ADD_en.jsonl\n", + "'Assistant:' 后包含小数点的行数: 390459\n", + "总行数: 976394\n", + "目标行('Assistant:'后有小数点)占总行数比例: 39.99%\n", + "\n", + "文件: ADD_en_base_1M.jsonl\n", + "'Assistant:' 后包含小数点的行数: 0\n", + "总行数: 1000000\n", + "目标行('Assistant:'后有小数点)占总行数比例: 0.00%\n", + "\n", + "文件: ADD_en_base_500k.jsonl\n", + "'Assistant:' 后包含小数点的行数: 0\n", + "总行数: 1000000\n", + "目标行('Assistant:'后有小数点)占总行数比例: 0.00%\n", + "\n", + "文件: ADD_en_by-desc.jsonl\n", + "'Assistant:' 后包含小数点的行数: 195833\n", + "总行数: 489961\n", + "目标行('Assistant:'后有小数点)占总行数比例: 39.97%\n", + "\n", + "文件: ADD_en_random_mix.jsonl\n", + "'Assistant:' 后包含小数点的行数: 585917\n", + "总行数: 1464727\n", + "目标行('Assistant:'后有小数点)占总行数比例: 40.00%\n", + "\n", + "文件: ADD_many0_50k.jsonl\n", + "'Assistant:' 后包含小数点的行数: 0\n", + "总行数: 50000\n", + "目标行('Assistant:'后有小数点)占总行数比例: 0.00%\n", + "\n", + "文件: ADD_n1m0.jsonl\n", + "'Assistant:' 后包含小数点的行数: 54611\n", + "总行数: 270887\n", + "目标行('Assistant:'后有小数点)占总行数比例: 20.16%\n", + "\n", + "文件: ADD_n1m1.jsonl\n", + "'Assistant:' 后包含小数点的行数: 28533\n", + "总行数: 199900\n", + "目标行('Assistant:'后有小数点)占总行数比例: 14.27%\n", + "\n", + "文件: ADD_n2m0.jsonl\n", + "'Assistant:' 后包含小数点的行数: 63265\n", + "总行数: 270798\n", + "目标行('Assistant:'后有小数点)占总行数比例: 23.36%\n", + "\n", + "文件: ADD_n2m1.jsonl\n", + "'Assistant:' 后包含小数点的行数: 29287\n", + "总行数: 199847\n", + "目标行('Assistant:'后有小数点)占总行数比例: 14.65%\n", + "\n", + "文件: ADD_n3m0.jsonl\n", + "'Assistant:' 后包含小数点的行数: 72403\n", + "总行数: 270853\n", + "目标行('Assistant:'后有小数点)占总行数比例: 26.73%\n", + "\n", + "文件: ADD_n4m3.jsonl\n", + "'Assistant:' 后包含小数点的行数: 83920\n", + "总行数: 271345\n", + "目标行('Assistant:'后有小数点)占总行数比例: 30.93%\n", + "\n", + "文件: ADD_random_0.25M.jsonl\n", + "'Assistant:' 后包含小数点的行数: 97604\n", + "总行数: 249735\n", + "目标行('Assistant:'后有小数点)占总行数比例: 39.08%\n", + "\n", + "文件: ADD_random_4M.jsonl\n", + "'Assistant:' 后包含小数点的行数: 1758574\n", + "总行数: 4494484\n", + "目标行('Assistant:'后有小数点)占总行数比例: 39.13%\n", + "\n", + "文件: ADD_use-connect.jsonl\n", + "'Assistant:' 后包含小数点的行数: 1181364\n", + "总行数: 1542000\n", + "目标行('Assistant:'后有小数点)占总行数比例: 76.61%\n", + "\n", + "文件: qa_error.jsonl\n", + "'Assistant:' 后包含小数点的行数: 0\n", + "总行数: 248\n", + "目标行('Assistant:'后有小数点)占总行数比例: 0.00%\n", + "\n", + "文件: qa_gibberish_unanswerable.jsonl\n", + "'Assistant:' 后包含小数点的行数: 0\n", + "总行数: 10000\n", + "目标行('Assistant:'后有小数点)占总行数比例: 0.00%\n", + "\n", + "文件: test_data.jsonl\n", + "'Assistant:' 后包含小数点的行数: 5\n", + "总行数: 7\n", + "目标行('Assistant:'后有小数点)占总行数比例: 71.43%\n", + "\n", + "文件: X_ch_en_mix.jsonl\n", + "'Assistant:' 后包含小数点的行数: 159485\n", + "总行数: 250000\n", + "目标行('Assistant:'后有小数点)占总行数比例: 63.79%\n", + "\n", + "文件: X_ch_mix.jsonl\n", + "'Assistant:' 后包含小数点的行数: 1277448\n", + "总行数: 2000000\n", + "目标行('Assistant:'后有小数点)占总行数比例: 63.87%\n", + "\n", + "文件: X_en_random_mix.jsonl\n", + "'Assistant:' 后包含小数点的行数: 640225\n", + "总行数: 1000000\n", + "目标行('Assistant:'后有小数点)占总行数比例: 64.02%\n" + ] + } + ], + "source": [ + "import json\n", + "import os\n", + "\n", + "def count_decimal_lines_in_jsonl(filepath):\n", + " \"\"\"\n", + " 读取 JSONL 文件,统计 'Assistant:' 之后内容包含小数点的行数和总行数。\n", + "\n", + " Args:\n", + " filepath (str): JSONL 文件的路径。\n", + "\n", + " Returns:\n", + " tuple: (count_lines_with_decimals_after_assistant, total_lines_processed)\n", + " 如果发生错误,则返回 (None, None)。\n", + " \"\"\"\n", + " count_lines_with_decimals_after_assistant = 0\n", + " total_lines_processed = 0\n", + " assistant_marker = \"Assistant:\"\n", + "\n", + " try:\n", + " with open(filepath, 'r', encoding='utf-8') as f:\n", + " for line_content in f:\n", + " stripped_line = line_content.strip()\n", + " total_lines_processed += 1\n", + "\n", + " # 找到 \"Assistant:\" 的位置\n", + " marker_index = stripped_line.find(assistant_marker)\n", + "\n", + " if marker_index != -1:\n", + " # 如果找到了 \"Assistant:\",提取它之后的内容\n", + " content_after_assistant = stripped_line[marker_index + len(assistant_marker):]\n", + " \n", + " # 检查这部分内容是否包含小数点\n", + " if '.' in content_after_assistant:\n", + " count_lines_with_decimals_after_assistant += 1\n", + " # else: 如果没有 \"Assistant:\",则这一行不符合小数点计数条件(针对 'Assistant:' 之后的内容)\n", + "\n", + " except FileNotFoundError:\n", + " print(f\"错误: 文件 '{filepath}' 未找到。\")\n", + " return None, None\n", + " except Exception as e:\n", + " print(f\"处理文件 '{filepath}' 时发生错误: {e}\")\n", + " return None, None\n", + "\n", + " return count_lines_with_decimals_after_assistant, total_lines_processed\n", + "\n", + "\n", + "def process_jsonl_files_in_folder(folder_path):\n", + " \"\"\"\n", + " 处理文件夹中的所有jsonl文件,统计每个文件中 'Assistant:' 之后内容包含小数点的行数和总行数。\n", + "\n", + " Args:\n", + " folder_path (str): 包含jsonl文件的文件夹路径\n", + "\n", + " Returns:\n", + " dict: 以文件名作为键,值为(count_lines_with_decimals_after_assistant, total_lines_processed)的字典\n", + " \"\"\"\n", + " results = {}\n", + " \n", + " try:\n", + " # 获取文件夹中所有文件和目录\n", + " for filename in os.listdir(folder_path):\n", + " filepath = os.path.join(folder_path, filename)\n", + " \n", + " # 检查是否是文件且以.jsonl结尾\n", + " if os.path.isfile(filepath) and filename.endswith('.jsonl'):\n", + " print(f\"\\n正在处理文件: {filename}\")\n", + " decimal_count, total_count = count_decimal_lines_in_jsonl(filepath)\n", + " \n", + " if decimal_count is not None and total_count is not None:\n", + " results[filename] = (decimal_count, total_count)\n", + " print(f\"文件 '{filename}' 中 'Assistant:' 后包含小数点的行数: {decimal_count}\")\n", + " print(f\"文件 '{filename}' 中的总行数: {total_count}\")\n", + " \n", + " except Exception as e:\n", + " print(f\"处理文件夹时发生错误: {e}\")\n", + " \n", + " return results\n", + "\n", + "\n", + "if __name__ == \"__main__\":\n", + " # 指定要处理的文件夹路径\n", + " folder_path = \"./\" # 当前目录,可以修改为你的目标文件夹路径\n", + " \n", + " # 创建一个测试文件\n", + " test_file_content = [\n", + " 'User: Hello Assistant: Hi there. The current value is 3.14.',\n", + " 'User: Question Assistant: The answer is 42.',\n", + " 'Assistant: Another response with 0.5 probability.',\n", + " 'No assistant here, but number 123.456',\n", + " 'Assistant: Just text, no decimals.',\n", + " '{\"user\": \"query\", \"assistant_response\": \"Assistant: value is 99.9 FM\"}', # 'Assistant:' is part of a larger string\n", + " 'User: Tell me something. Assistant:' # Assistant marker present, but no content after it\n", + " ]\n", + " test_filename = \"test_data.jsonl\"\n", + " test_filepath = os.path.join(folder_path, test_filename)\n", + "\n", + " if not os.path.exists(folder_path):\n", + " os.makedirs(folder_path)\n", + " \n", + " with open(test_filepath, 'w', encoding='utf-8') as tf:\n", + " for line in test_file_content:\n", + " tf.write(line + '\\n')\n", + " print(f\"创建测试文件: {test_filepath}\")\n", + "\n", + " # 处理文件夹中的所有jsonl文件\n", + " results = process_jsonl_files_in_folder(folder_path)\n", + " \n", + " # 打印汇总结果\n", + " print(\"\\n===== 汇总结果 =====\")\n", + " for filename, (decimal_count, total_count) in results.items():\n", + " print(f\"\\n文件: {filename}\")\n", + " print(f\"'Assistant:' 后包含小数点的行数: {decimal_count}\")\n", + " print(f\"总行数: {total_count}\")\n", + " if total_count > 0: # 避免除以零错误\n", + " # 注意:这里的占比是 “包含小数点的行数” 占 “总行数” 的比例。\n", + " # 如果你想要 “包含小数点的行数” 占 “包含'Assistant:'的行数” 的比例,计算方式会不同。\n", + " print(f\"目标行('Assistant:'后有小数点)占总行数比例: {decimal_count/total_count:.2%}\") \n", + " else:\n", + " print(\"目标行('Assistant:'后有小数点)占总行数比例: N/A (总行数为0)\")\n", + "\n", + " # 清理测试文件(可选)\n", + " # if os.path.exists(test_filepath):\n", + " # os.remove(test_filepath)\n", + " # print(f\"\\n已删除测试文件: {test_filepath}\")" + ] + }, + { + "cell_type": "markdown", + "id": "3ec94efc", + "metadata": {}, + "source": [ + "# 合并当前文件夹中全部jsonl\n", + "\n", + "合并,并打乱顺序" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f1acb252", + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "import random\n", + "import os\n", + "from pathlib import Path\n", + "\n", + "# --- 配置 ---\n", + "# 指定输出文件的名称\n", + "OUTPUT_FILENAME = \"qa_add_merged.jsonl\"\n", + "# --- 配置结束 ---\n", + "\n", + "def merge_and_shuffle_jsonl(output_filename):\n", + " \"\"\"\n", + " 查找当前目录下的所有 .jsonl 文件(不包括输出文件自身),\n", + " 合并它们的内容,打乱顺序,并写入到指定的输出文件中。\n", + " 确保去除空行,且输出文件最后没有空行。\n", + " \"\"\"\n", + " current_directory = Path.cwd() # 获取当前工作目录\n", + " all_lines = []\n", + " processed_files_count = 0\n", + " total_lines_read = 0\n", + " skipped_empty_lines = 0\n", + "\n", + " print(f\"将在目录: {current_directory} 中查找 .jsonl 文件\")\n", + " print(f\"输出文件将被写入: {output_filename}\")\n", + " print(\"-\" * 30)\n", + "\n", + " # 1. 查找并读取所有 .jsonl 文件\n", + " # 使用 glob 查找所有 .jsonl 文件\n", + " jsonl_files = list(current_directory.glob('*.jsonl'))\n", + "\n", + " if not jsonl_files:\n", + " print(\"错误:在当前目录中未找到任何 .jsonl 文件。\")\n", + " return\n", + "\n", + " output_filepath = current_directory / output_filename\n", + " \n", + " for filepath in jsonl_files:\n", + " # 跳过输出文件本身,防止读取正在写入的文件或重复读取\n", + " if filepath.resolve() == output_filepath.resolve():\n", + " print(f\"跳过输出文件: {filepath.name}\")\n", + " continue\n", + "\n", + " print(f\"正在读取文件: {filepath.name}...\")\n", + " try:\n", + " with open(filepath, 'r', encoding='utf-8') as infile:\n", + " lines_in_file = 0\n", + " for line in infile:\n", + " stripped_line = line.strip()\n", + " # 检查行是否为空白行\n", + " if stripped_line:\n", + " # (可选) 验证是否为有效的 JSON - 如果无效则跳过并警告\n", + " try:\n", + " json.loads(stripped_line) # 尝试解析确保是有效JSON行\n", + " all_lines.append(stripped_line)\n", + " lines_in_file += 1\n", + " except json.JSONDecodeError:\n", + " print(f\" 警告:在文件 {filepath.name} 中发现无效JSON行,已跳过: {line.strip()}\")\n", + " skipped_empty_lines +=1 # 也算作跳过的行\n", + " else:\n", + " # 统计跳过的空行\n", + " skipped_empty_lines += 1\n", + " \n", + " if lines_in_file > 0:\n", + " print(f\" 成功读取 {lines_in_file} 行有效数据。\")\n", + " total_lines_read += lines_in_file\n", + " processed_files_count += 1\n", + " else:\n", + " print(f\" 文件 {filepath.name} 不包含有效数据行或仅包含空行。\")\n", + "\n", + "\n", + " except Exception as e:\n", + " print(f\" 读取文件 {filepath.name} 时出错: {e}\")\n", + "\n", + " print(\"-\" * 30)\n", + "\n", + " if not all_lines:\n", + " print(\"错误:未能从任何文件中读取到有效的 JSONL 数据行。无法生成输出文件。\")\n", + " return\n", + "\n", + " print(f\"共从 {processed_files_count} 个文件中读取了 {total_lines_read} 行有效数据。\")\n", + " if skipped_empty_lines > 0:\n", + " print(f\"读取过程中跳过了 {skipped_empty_lines} 个空行或无效JSON行。\")\n", + "\n", + "\n", + " # 2. 打乱顺序\n", + " print(\"正在打乱数据顺序...\")\n", + " random.shuffle(all_lines)\n", + " print(\"数据已打乱。\")\n", + "\n", + " # 3. 写入到指定文件\n", + " print(f\"正在将 {len(all_lines)} 行数据写入到 {output_filename}...\")\n", + " try:\n", + " with open(output_filepath, 'w', encoding='utf-8') as outfile:\n", + " # 使用 '\\n'.join() 可以确保最后一行后面没有多余的换行符\n", + " output_content = '\\n'.join(all_lines)\n", + " outfile.write(output_content)\n", + " print(f\"成功写入!输出文件位于: {output_filepath}\")\n", + " except Exception as e:\n", + " print(f\"写入文件 {output_filename} 时出错: {e}\")\n", + "\n", + "# --- 执行脚本 ---\n", + "if __name__ == \"__main__\":\n", + " merge_and_shuffle_jsonl(OUTPUT_FILENAME)" + ] + }, + { + "cell_type": "markdown", + "id": "e23750bf", + "metadata": {}, + "source": [ + "# 单轮拼接为多轮\n", + "\n", + "将单个 jsonl 的多行合并为 1 行,可设定最小选取行数和最大选取行" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "63caefa8", + "metadata": {}, + "outputs": [], + "source": [ + "# -*- coding: utf-8 -*-\n", + "import json\n", + "import random\n", + "import sys\n", + "import math\n", + "from tqdm import tqdm # 用于显示进度条,如果未安装请 pip install tqdm\n", + "import numpy as np # 使用 numpy 进行一些计算和类型处理\n", + "from decimal import Decimal, getcontext # 使用 Decimal 进行精确概率计算\n", + "\n", + "# --- 配置参数 ---\n", + "INPUT_FILE = \"qa_add_merged.jsonl\" # <--- 修改为你的输入文件名\n", + "OUTPUT_FILE = \"qa_add_v2.2-30M.jsonl\" # 输出文件名 (反映新策略)\n", + "INPUT_TOTAL_LINES = 30_000_587 # 输入文件总行数 (必须精确)\n", + "# TARGET_OUTPUT_LINES = 200_000 # <--- 已移除:不再需要目标输出行数\n", + "MIN_SEPARATE_LINES = 0 # 最少保留不拼接的行数 (可以为 0)\n", + "MIN_COMBINE = 10 # 拼接时最少合并的行数 (公式中的 n 下限)\n", + "MAX_COMBINE = 20 # 拼接时最多合并的行数 (公式中的 n 上限)\n", + "# --- 配置结束 ---\n", + "\n", + "\n", + "# 设置 Decimal 精度\n", + "getcontext().prec = 50\n", + "\n", + "def load_jsonl(filename, expected_lines):\n", + " \"\"\"从jsonl文件加载数据\"\"\"\n", + " lines = []\n", + " print(f\"[*] 开始加载文件: {filename}\")\n", + " try:\n", + " # 优化:逐行读取和解析,避免一次性读入内存,尤其对于大文件\n", + " line_count = 0\n", + " with open(filename, 'r', encoding='utf-8') as f:\n", + " # 使用tqdm显示读取进度,虽然总行数已知,但逐行解析可能也耗时\n", + " for line in tqdm(f, desc=f\"加载并解析 {os.path.basename(filename)}\", total=expected_lines, unit=\"行\"):\n", + " line_count += 1\n", + " line_stripped = line.strip()\n", + " if not line_stripped: # 跳过空行\n", + " print(f\"\\n[!] 警告: 在第 {line_count} 行发现空行,已跳过。\", file=sys.stderr)\n", + " continue\n", + " try:\n", + " lines.append(json.loads(line_stripped))\n", + " except json.JSONDecodeError:\n", + " print(f\"\\n[!] 警告: 第 {line_count} 行 JSON 解析失败,已跳过: {line_stripped[:100]}...\", file=sys.stderr)\n", + " except FileNotFoundError:\n", + " print(f\"[X] 错误: 输入文件 '{filename}' 未找到.\", file=sys.stderr); sys.exit(1)\n", + " except Exception as e:\n", + " print(f\"[X] 错误: 加载文件时发生错误: {e}\", file=sys.stderr); sys.exit(1)\n", + "\n", + " actual_lines = len(lines)\n", + " print(f\"[*] 加载并解析完成. 共加载 {actual_lines} 行有效JSON数据.\")\n", + " # 仍然检查加载的有效JSON行数与预期是否一致,如果预期是原始文件行数的话\n", + " # 注意:如果原始文件包含空行或无效JSON行,actual_lines会小于expected_lines\n", + " # 这里的检查逻辑可能需要根据expected_lines的真实含义调整\n", + " # 假设 expected_lines 指的是文件中的 *总物理行数*,而非有效JSON行数\n", + " # 我们可能需要一个单独的变量来记录物理行数 line_count\n", + "\n", + " # 重新思考检查:我们加载的是有效JSON行。如果用户提供的 expected_lines\n", + " # 是指文件物理行数,那么这个检查意义不大,除非文件保证100%有效。\n", + " # 如果 expected_lines 指的是期望的 *有效JSON行数*,则检查有效。\n", + " # 暂时保留检查,但提示用户注意其含义。\n", + " print(f\"[*] 原始文件物理行数 (包括空行/无效行): {line_count}\") # 增加物理行数报告\n", + " if actual_lines != expected_lines:\n", + " print(f\"[!] 警告: 实际加载的有效JSON行数 ({actual_lines}) 与配置的输入总行数 ({expected_lines}) 不符。\")\n", + " print(f\"[!] 这可能是因为输入文件包含空行或无效JSON。脚本将基于加载的 {actual_lines} 行继续。\")\n", + " # 根据需求决定是否在这里退出\n", + " # sys.exit(1)\n", + "\n", + " # 基本可行性检查 (移除与 TARGET_OUTPUT_LINES 相关的检查)\n", + " if MIN_SEPARATE_LINES < 0: print(f\"[X] 错误: 最少保留行数 ({MIN_SEPARATE_LINES}) 不能为负数.\", file=sys.stderr); sys.exit(1)\n", + " # 使用 actual_lines 进行后续检查更安全\n", + " if actual_lines < MIN_SEPARATE_LINES:\n", + " print(f\"[X] 错误: 加载的有效行数 ({actual_lines}) 少于要求的最小保留行数 ({MIN_SEPARATE_LINES}).\", file=sys.stderr); sys.exit(1)\n", + " if MIN_COMBINE > MAX_COMBINE or MIN_COMBINE < 2:\n", + " print(f\"[X] 错误: 组合范围无效 (MIN_COMBINE={MIN_COMBINE}, MAX_COMBINE={MAX_COMBINE}).\", file=sys.stderr); sys.exit(1)\n", + " return lines, actual_lines # 返回加载的数据和实际加载的行数\n", + "\n", + "def combine_texts(lines_to_combine):\n", + " \"\"\"将多个单轮对话拼接成一个多轮对话文本\"\"\"\n", + " if not lines_to_combine: return None\n", + " full_text = \"\"; valid_lines_count = 0\n", + " for i, line_data in enumerate(lines_to_combine):\n", + " # 确保line_data是字典且有'text'键\n", + " if isinstance(line_data, dict) and \"text\" in line_data and isinstance(line_data[\"text\"], str):\n", + " text_content = line_data[\"text\"]; cleaned_text = text_content.strip()\n", + " # 只有当cleaned_text非空时才加入\n", + " if cleaned_text:\n", + " if valid_lines_count > 0: # 在有效文本之间加换行\n", + " full_text += \"\\n\\n\"\n", + " full_text += cleaned_text\n", + " valid_lines_count += 1\n", + " else: print(f\"\\n[!] 警告: 拼接中发现无效数据或缺失'text'键,跳过: {line_data}\", file=sys.stderr)\n", + " # 只有当拼接后有实际内容时才返回\n", + " return {\"text\": full_text} if full_text else None\n", + "\n", + "# --- 修改后的函数 ---\n", + "def save_jsonl(data, filename):\n", + " \"\"\"将数据保存为jsonl文件,确保最后一行末尾没有换行符。\"\"\"\n", + " actual_lines = len(data)\n", + " if actual_lines == 0:\n", + " print(f\"[!] 警告: 没有数据可以保存到 {filename}。\")\n", + " try:\n", + " with open(filename, 'w', encoding='utf-8') as f:\n", + " pass # 创建一个空文件\n", + " print(f\"[*] 已创建空的输出文件: {filename}\")\n", + " return 0\n", + " except Exception as e:\n", + " print(f\"[X] 错误: 尝试创建空文件时发生错误: {e}\", file=sys.stderr)\n", + " sys.exit(1) # Or return 0/raise error\n", + "\n", + " print(f\"[*] 开始保存文件: {filename} (共 {actual_lines} 行)\")\n", + " saved_count = 0\n", + " try:\n", + " with open(filename, 'w', encoding='utf-8') as f:\n", + " # 使用 enumerate 获取索引\n", + " for index, item in enumerate(tqdm(data, desc=\"保存中\", unit=\"行\")):\n", + " # 增加对 item 类型的检查,确保是字典\n", + " if isinstance(item, dict):\n", + " try:\n", + " line_to_write = json.dumps(item, ensure_ascii=False)\n", + " f.write(line_to_write)\n", + " # 只有当不是最后一行时,才写入换行符\n", + " if index < actual_lines - 1:\n", + " f.write('\\n')\n", + " saved_count += 1\n", + " except (TypeError, ValueError) as json_err: # 更具体地捕获JSON序列化错误\n", + " print(f\"\\n[!] 警告: 序列化第 {index+1} 项数据时出错,已跳过: {item} - 错误: {json_err}\", file=sys.stderr)\n", + " except Exception as write_err: # 捕获写入错误\n", + " print(f\"\\n[!] 警告: 写入第 {index+1} 行数据时出错,已跳过: {item} - 错误: {write_err}\", file=sys.stderr)\n", + " else:\n", + " # 如果item不是字典,也记录警告并跳过\n", + " print(f\"\\n[!] 警告: 尝试保存非字典类型数据 (第 {index+1} 行),已跳过: {type(item)} - {str(item)[:100]}...\", file=sys.stderr)\n", + "\n", + " print(f\"[*] 保存完成. 成功写入 {saved_count:,} 行。\")\n", + " # 检查是否有跳过的情况\n", + " if saved_count != actual_lines:\n", + " print(f\"[!] 注意: 内存中有 {actual_lines:,} 条数据,但由于无效格式或写入错误,实际只保存了 {saved_count:,} 行。\")\n", + " return saved_count # 返回实际保存的行数\n", + " except Exception as e: # 捕获文件打开/关闭等IO错误\n", + " print(f\"[X] 错误: 保存文件时发生严重错误: {e}\", file=sys.stderr)\n", + " # 决定是否退出或返回部分计数\n", + " # sys.exit(1)\n", + " return saved_count # 返回到错误发生前已保存的行数\n", + "\n", + "# --- 新的分配计算函数 (保持不变) ---\n", + "def calculate_distribution_consume_input(\n", + " total_input, min_separate, min_k, max_k\n", + "):\n", + " \"\"\"\n", + " 根据公式计算组合分配,目标是根据比例消耗尽可能多的可用输入行。\n", + " 使用向下取整确定对话数,返回未使用的输入行。\n", + " \"\"\"\n", + " print(\"[*] 开始计算组合分配 (基于公式消耗输入)...\")\n", + "\n", + " input_available_for_comb = total_input - min_separate # 可用于组合的输入行数\n", + " print(f\"[*] 总有效输入行数: {total_input:,}\") # 使用有效行数\n", + " print(f\"[*] 基础保留单轮行数: {min_separate:,}\")\n", + " print(f\"[*] 可用组合输入行数: {input_available_for_comb:,}\")\n", + "\n", + " if input_available_for_comb <= 0:\n", + " print(\"[*] 没有可用于组合的输入行。\")\n", + " # 确保返回正确的未使用行数:即所有可用行都未使用\n", + " unused_lines_here = max(0, input_available_for_comb) # 可能是0或负数,取max(0,...)\n", + " total_unused = total_input - min_separate - 0 # 总输入 - 保留 - 已用组合(0)\n", + " return {}, 0, total_unused # 返回空字典, 0行已用, 剩余行数\n", + "\n", + " # 1. 计算权重和归一化概率\n", + " weights = {}\n", + " total_weight = Decimal('0')\n", + " possible_lengths = list(range(min_k, max_k + 1))\n", + " print(f\"[*] 计算权重 (n={min_k}到{max_k})...\")\n", + " for n in possible_lengths:\n", + " # 确保 n - min_k 不会是负数导致 0.8 的负指数\n", + " exponent = max(0, n - min_k)\n", + " # weight = min(Decimal('0.1'), Decimal('0.2') * (Decimal('0.8')**(n - min_k)))\n", + " weight = min(Decimal('0.1'), Decimal('0.2') * (Decimal('0.8')**exponent))\n", + " weights[n] = weight; total_weight += weight\n", + "\n", + " if total_weight <= 0: print(f\"[X] 错误: 计算的总权重为零或负 ({total_weight}).\", file=sys.stderr); sys.exit(1)\n", + "\n", + " probabilities = {n: weights[n] / total_weight for n in possible_lengths}\n", + " prob_sum_check = sum(probabilities.values())\n", + " print(f\"[*] 权重计算完成. 总权重={total_weight:.6f}, 概率和={float(prob_sum_check):.6f}\")\n", + " if not math.isclose(float(prob_sum_check), 1.0, abs_tol=1e-9):\n", + " print(\"[!] 警告: 概率和不严格等于 1.0。\", file=sys.stderr)\n", + "\n", + " # 2. 计算每个长度 k 理想分配到的输入行数\n", + " ideal_input_alloc = {n: input_available_for_comb * probabilities[n] for n in possible_lengths}\n", + "\n", + " # 3. 根据理想输入行数和长度 k,计算能生成的对话数 (向下取整)\n", + " final_counts = {}\n", + " total_input_used_for_comb = 0\n", + " print(f\"[*] 计算各长度对话数 (向下取整)...\")\n", + " for n in possible_lengths:\n", + " # 从理想分配的输入行数计算能生成的最大整数对话数\n", + " # 确保 ideal_input_alloc[n] > 0 且 n > 0\n", + " if n > 0 and ideal_input_alloc[n] > 0:\n", + " num_dialogs_n = math.floor(float(ideal_input_alloc[n]) / n) # 需要转 float 进行 floor\n", + " else:\n", + " num_dialogs_n = 0\n", + " final_counts[n] = num_dialogs_n\n", + " # 计算这部分实际消耗的输入行数\n", + " input_used_n = num_dialogs_n * n\n", + " total_input_used_for_comb += input_used_n\n", + " # print(f\"[*] n={n}, ideal_input={float(ideal_input_alloc[n]):.2f}, dialogues={num_dialogs_n}, input_used={input_used_n}\") # 调试\n", + "\n", + " # 4. 计算未使用的输入行数\n", + " unused_input_lines = input_available_for_comb - total_input_used_for_comb\n", + "\n", + " print(f\"[*] 组合分配计算完成 (公式驱动输入消耗):\")\n", + " final_total_dialogs = 0\n", + " for k in sorted(final_counts.keys()):\n", + " if final_counts[k] > 0:\n", + " print(f\"[*] {k}-轮对话: {final_counts[k]:,} 个\")\n", + " final_total_dialogs += final_counts[k]\n", + "\n", + " print(f\"[*] 计算出的组合对话总数: {final_total_dialogs:,}\")\n", + " print(f\"[*] 实际用于组合的总输入行数: {total_input_used_for_comb:,}\")\n", + " print(f\"[*] 计算出未使用的输入行数 (将作为单轮): {unused_input_lines:,}\")\n", + "\n", + " # 校验\n", + " if unused_input_lines < 0:\n", + " print(f\"[X] 严重错误: 未使用的输入行数为负数 ({unused_input_lines:,})!\", file=sys.stderr); sys.exit(1)\n", + " if total_input_used_for_comb + unused_input_lines != input_available_for_comb:\n", + " # 使用isclose处理可能的浮点数精度问题\n", + " if not math.isclose(total_input_used_for_comb + unused_input_lines, input_available_for_comb, rel_tol=1e-9):\n", + " print(f\"[X] 严重错误: 已用输入 ({total_input_used_for_comb:,}) + 未用输入 ({unused_input_lines:,}) != 可用输入 ({input_available_for_comb:,})!\", file=sys.stderr); sys.exit(1)\n", + "\n", + " # 过滤掉数量为0的条目\n", + " final_counts_filtered = {k: v for k, v in final_counts.items() if v > 0}\n", + "\n", + " return final_counts_filtered, total_input_used_for_comb, unused_input_lines\n", + "\n", + "# --- 主逻辑 ---\n", + "if __name__ == \"__main__\":\n", + " # 导入 os 模块\n", + " import os\n", + "\n", + " # 1. 加载数据\n", + " # load_jsonl 现在返回 (数据, 实际加载行数)\n", + " all_lines_data, actual_loaded_lines = load_jsonl(INPUT_FILE, INPUT_TOTAL_LINES)\n", + "\n", + " # 使用实际加载的行数进行后续计算\n", + " effective_total_input = actual_loaded_lines\n", + "\n", + " # 2. 计算组合分配 (使用新的公式驱动函数和实际加载行数)\n", + " combination_counts, input_used_for_comb, unused_input_lines = calculate_distribution_consume_input(\n", + " effective_total_input, MIN_SEPARATE_LINES, MIN_COMBINE, MAX_COMBINE\n", + " )\n", + "\n", + " # 3. 随机打乱\n", + " print(\"[*] 开始打乱数据...\")\n", + " random.shuffle(all_lines_data)\n", + " print(\"[*] 数据打乱完成.\")\n", + "\n", + " # 4. 准备输出列表和索引\n", + " final_output_lines = []\n", + " input_pool_start_index = 0\n", + "\n", + " # 5. 添加基础的保留单轮对话\n", + " num_base_separate = MIN_SEPARATE_LINES\n", + " if num_base_separate > 0:\n", + " print(f\"[*] 添加 {num_base_separate:,} 条基础保留的单轮对话...\")\n", + " # 确保索引不越界 (使用 effective_total_input)\n", + " if input_pool_start_index + num_base_separate > effective_total_input:\n", + " print(f\"[X] 错误: 实际加载的输入 ({effective_total_input}) 不足以满足基础保留 ({num_base_separate})!\", file=sys.stderr); sys.exit(1)\n", + " final_output_lines.extend(all_lines_data[input_pool_start_index : input_pool_start_index + num_base_separate])\n", + " input_pool_start_index += num_base_separate\n", + " print(f\"[*] 当前输出列表大小: {len(final_output_lines):,}\")\n", + " print(f\"[*] 下一个可用输入索引: {input_pool_start_index:,}\")\n", + " else:\n", + " print(\"[*] 配置为不基础保留单轮对话。\")\n", + "\n", + " # 6. 添加因公式计算和取整而未使用的单轮对话\n", + " num_additional_separate = unused_input_lines\n", + " if num_additional_separate > 0:\n", + " print(f\"[*] 添加 {num_additional_separate:,} 条因公式/取整未使用的单轮对话...\")\n", + " # 确保索引不越界\n", + " if input_pool_start_index + num_additional_separate > effective_total_input:\n", + " print(f\"[X] 错误: 实际加载的输入 ({effective_total_input}) 不足以添加未使用的行 ({num_additional_separate})! (当前索引 {input_pool_start_index})\", file=sys.stderr); sys.exit(1)\n", + " final_output_lines.extend(all_lines_data[input_pool_start_index : input_pool_start_index + num_additional_separate])\n", + " input_pool_start_index += num_additional_separate\n", + " print(f\"[*] 当前输出列表大小: {len(final_output_lines):,}\")\n", + " print(f\"[*] 下一个可用输入索引: {input_pool_start_index:,}\")\n", + " else:\n", + " print(\"[*] 没有因公式/取整未使用的输入行。\")\n", + "\n", + " # 7. 生成组合对话\n", + " print(\"[*] 开始生成组合对话...\")\n", + " num_combined_dialogs_generated = 0\n", + " total_combined_dialogs_calculated = sum(combination_counts.values())\n", + " # 校验可用输入是否足够\n", + " remaining_input_for_comb_check = effective_total_input - input_pool_start_index\n", + " # 使用 isclose 进行浮点数比较可能更安全,尽管这里应该是整数\n", + " if not math.isclose(remaining_input_for_comb_check, input_used_for_comb, abs_tol=1e-9):\n", + " print(f\"[!] 警告: 剩余输入 ({remaining_input_for_comb_check:,}) 与计算出的组合所需输入 ({input_used_for_comb:,}) 不完全相等。差值: {remaining_input_for_comb_check - input_used_for_comb}\", file=sys.stderr)\n", + " # 检查剩余输入是否 *小于* 所需输入,这才是关键错误\n", + " if remaining_input_for_comb_check < input_used_for_comb:\n", + " print(f\"[X] 严重错误: 剩余输入不足以满足组合所需!\", file=sys.stderr); sys.exit(1)\n", + "\n", + " if total_combined_dialogs_calculated > 0:\n", + " pbar_combine = tqdm(total=total_combined_dialogs_calculated, desc=\"组合对话\", unit=\"对话\")\n", + " # 按 k 排序处理,确保消耗输入的顺序确定性(虽然数据已打乱)\n", + " for k in sorted(combination_counts.keys()):\n", + " num_dialogs_k = combination_counts[k]\n", + " if num_dialogs_k > 0:\n", + " num_input_lines_k = num_dialogs_k * k\n", + " # 索引检查\n", + " if input_pool_start_index + num_input_lines_k > effective_total_input:\n", + " print(f\"\\n[X] 严重错误: 尝试为 {k}-轮 获取输入时超出界限! 需要 {num_input_lines_k}, 可用 {effective_total_input - input_pool_start_index}, 当前索引 {input_pool_start_index}\", file=sys.stderr); sys.exit(1)\n", + "\n", + " input_chunk_for_k = all_lines_data[input_pool_start_index : input_pool_start_index + num_input_lines_k]\n", + " input_pool_start_index += num_input_lines_k # 更新索引\n", + "\n", + " for i in range(num_dialogs_k): # 直接按对话数循环\n", + " start_idx = i * k\n", + " end_idx = start_idx + k\n", + " lines_to_combine = input_chunk_for_k[start_idx : end_idx]\n", + "\n", + " # 再次检查获取的行数是否正确,理论上应该总是正确的\n", + " if len(lines_to_combine) == k:\n", + " combined_entry = combine_texts(lines_to_combine)\n", + " # 仅当 combine_texts 成功返回有效数据时才添加\n", + " if combined_entry:\n", + " final_output_lines.append(combined_entry)\n", + " num_combined_dialogs_generated += 1\n", + " pbar_combine.update(1)\n", + " else:\n", + " print(f\"\\n[!] 警告: 为 {k}-轮对话组合的第 {i+1} 个块未能生成有效文本 (可能所有行为空或无效),已跳过。\", file=sys.stderr)\n", + " # 考虑是否需要从 total_combined_dialogs_calculated 中减去,以使最终报告更准确?\n", + " # 或者保持计算值不变,报告实际生成值\n", + " else:\n", + " # 这个错误理论上不应发生,除非前面的切片逻辑错误\n", + " print(f\"\\n[X] 严重逻辑错误: 组合{k}轮时未能从块中获取足够行 ({len(lines_to_combine)}/{k}) for dialog {i+1}\", file=sys.stderr)\n", + " # 可能需要中断处理\n", + " pbar_combine.close()\n", + " if num_combined_dialogs_generated != total_combined_dialogs_calculated:\n", + " # 区分���因为 combine_texts 返回 None 还是其他原因\n", + " print(f\"[!] 提示: 实际生成组合数 ({num_combined_dialogs_generated:,}) 与计算出的目标组合数 ({total_combined_dialogs_calculated:,}) 不符。这可能是因为部分组合的源数据无效或为空。\", file=sys.stderr)\n", + " else: print(\"[*] 无需生成组合对话。\")\n", + "\n", + " # 8. 最终报告\n", + " final_actual_output_lines = len(final_output_lines)\n", + " total_separate_added = num_base_separate + num_additional_separate\n", + " print(\"\\n\" + \"=\"*30)\n", + " print(\" 处理结果摘要 \")\n", + " print(\"=\"*30)\n", + " print(f\"[*] 原始文件: {INPUT_FILE}\")\n", + " print(f\"[*] 配置的总行数: {INPUT_TOTAL_LINES:,}\")\n", + " print(f\"[*] 实际加载的有效JSON行数: {effective_total_input:,}\")\n", + " print(f\"[*] 输出文件: {OUTPUT_FILE}\")\n", + " print(f\"[*] 最终生成数据条数: {final_actual_output_lines:,}\")\n", + " print(f\"[*] 其中单轮对话: {total_separate_added:,}\")\n", + " print(f\"[*] - 基础保留: {num_base_separate:,}\")\n", + " print(f\"[*] - 未用于组合的行: {num_additional_separate:,}\")\n", + " print(f\"[*] 其中组合对话 (实际生成): {num_combined_dialogs_generated:,}\")\n", + " print(f\"[*] (计算出的目标组合数: {total_combined_dialogs_calculated:,})\")\n", + " print(f\"[*] 使用的总输入行数 (来自有效加载行): {input_pool_start_index:,}\")\n", + "\n", + " # 最终校验:使用的输入行数是否等于加载的有效行数\n", + " if input_pool_start_index != effective_total_input:\n", + " print(f\"[X] 严重错误: 最终使用的输入行数 ({input_pool_start_index:,}) 与加载的有效行数 ({effective_total_input:,}) 不符!\", file=sys.stderr)\n", + " else:\n", + " print(\"[*] (校验通过: 所有加载的有效输入行均已处理)\")\n", + "\n", + " # 9. 最后打乱一次 (可选,但通常推荐)\n", + " print(\"[*] 开始最后打乱...\")\n", + " random.shuffle(final_output_lines)\n", + " print(\"[*] 最后打乱完成.\")\n", + "\n", + " # 10. 保存 (使用修改后的 save_jsonl)\n", + " saved_lines_count = save_jsonl(final_output_lines, OUTPUT_FILE)\n", + " print(\"\\n\" + \"=\"*30)\n", + " if saved_lines_count == final_actual_output_lines:\n", + " print(f\"[*] 处理成功完成!\")\n", + " elif saved_lines_count > 0:\n", + " print(f\"[!] 处理部分完成 (内存中有 {final_actual_output_lines:,} 条, 成功保存了 {saved_lines_count:,} 条)。请检查警告信息。\")\n", + " else: # saved_lines_count is 0\n", + " if final_actual_output_lines > 0:\n", + " print(f\"[X] 处理失败!内存中有 {final_actual_output_lines:,} 条数据,但未能保存任何行。\")\n", + " else:\n", + " print(f\"[!] 处理完成,但没有生成或保存任何数据。\")\n", + "\n", + " print(\"=\"*30)" + ] + }, + { + "cell_type": "markdown", + "id": "8ba3d4f5", + "metadata": {}, + "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 +}