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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
import json
|
| 3 |
+
import math
|
| 4 |
+
import time
|
| 5 |
+
import re
|
| 6 |
+
import sys
|
| 7 |
+
import multiprocessing
|
| 8 |
+
import os
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
|
| 11 |
+
NUM_LINES = 2000000
|
| 12 |
+
OUTPUT_FILE = "correct_math_data.jsonl"
|
| 13 |
+
|
| 14 |
+
MIN_LENGTH = 2
|
| 15 |
+
MAX_LENGTH = 8
|
| 16 |
+
MIN_NUMBER = 1
|
| 17 |
+
MAX_NUMBER = 999
|
| 18 |
+
MAX_EXPONENT_BASE = 9
|
| 19 |
+
MAX_EXPONENT_POWER = 5
|
| 20 |
+
|
| 21 |
+
REASONING_CHANCE = 0.8
|
| 22 |
+
WORD_FORM_CHANCE = 0.25
|
| 23 |
+
BRACKET_CHANCE = 0.5
|
| 24 |
+
SENTENCE_FORM_CHANCE = 0.6
|
| 25 |
+
MAX_SOLVER_ITERATIONS = 30 # Reduced from 50 for faster timeout
|
| 26 |
+
|
| 27 |
+
NUM_WORKERS = os.cpu_count() or 1
|
| 28 |
+
|
| 29 |
+
PROMPT_TEMPLATES = [
|
| 30 |
+
"What is {expression}?", "Calculate the value of {expression}.", "Find the result of {expression}.",
|
| 31 |
+
"Can you solve {expression}?", "Solve for {expression}.", "What does {expression} equal?", "Compute {expression}.",
|
| 32 |
+
"What is the solution to {expression}?", "Give me the answer for {expression}.", "Determine the value of {expression}.",
|
| 33 |
+
"Evaluate the expression: {expression}.", "I need the result of {expression}, please."
|
| 34 |
+
]
|
| 35 |
+
COT_INTRO_TEMPLATES = [
|
| 36 |
+
"<think> Let's break down the equation {expression} step by step, following the order of operations (BEDMAS).",
|
| 37 |
+
"<think> Okay, to solve {expression}, I'll follow BEDMAS (Brackets, Exponents, Division/Multiplication, Addition/Subtraction).",
|
| 38 |
+
"<think> Analyzing {expression}. I need to solve this by applying the correct order of operations.",
|
| 39 |
+
"<think> Here's my step-by-step evaluation for {expression}:",
|
| 40 |
+
"<think> To get the answer for {expression}, I will use the order of operations.",
|
| 41 |
+
"<think> Processing {expression} requires following BEDMAS, let's begin.",
|
| 42 |
+
"<think> I will solve {expression} by carefully following the rules of BEDMAS.",
|
| 43 |
+
"<think> The expression is {expression}. My plan is to solve it using the order of operations.",
|
| 44 |
+
"<think> To solve this, I'll go through Brackets, then Exponents, then Multiplication/Division, and finally Addition/Subtraction for {expression}.",
|
| 45 |
+
"<think> Let's start solving {expression}. I'll tackle it one operation at a time based on BEDMAS.",
|
| 46 |
+
"<think> Thinking step-by-step for {expression}..."
|
| 47 |
+
]
|
| 48 |
+
COT_STEP_TEMPLATES = {
|
| 49 |
+
"brackets": [
|
| 50 |
+
"First, I'll solve the expression inside the brackets: {part}. That equals {result}.",
|
| 51 |
+
"Starting with the parentheses, {part} evaluates to {result}.",
|
| 52 |
+
"The brackets are the priority. Calculating {part} gives me {result}.",
|
| 53 |
+
"The calculation inside the parentheses comes first: {part} becomes {result}.",
|
| 54 |
+
"Looking inside the brackets, I see {part}. The result of that is {result}.",
|
| 55 |
+
"I'll begin by simplifying the part in the parentheses: {part} is {result}.",
|
| 56 |
+
"The first step according to BEDMAS is brackets. So, {part} is solved to {result}.",
|
| 57 |
+
"Tackling the parentheses first: {part} simplifies to {result}.",
|
| 58 |
+
"Evaluating the bracketed expression {part} yields {result}.",
|
| 59 |
+
"My focus is on the brackets first. {part} equals {result}."
|
| 60 |
+
],
|
| 61 |
+
"exponents": [
|
| 62 |
+
"Next, I'll handle the exponents. {part} is {result}.",
|
| 63 |
+
"Exponents are next in order. {part} calculates to {result}.",
|
| 64 |
+
"Now for the powers: {part} equals {result}.",
|
| 65 |
+
"Moving on to exponents, {part} results in {result}.",
|
| 66 |
+
"The next priority is exponents. The term {part} becomes {result}.",
|
| 67 |
+
"After brackets, I solve for exponents. {part} gives {result}.",
|
| 68 |
+
"Now, calculating the power: {part} is equal to {result}.",
|
| 69 |
+
"I see an exponent at {part}. This evaluates to {result}.",
|
| 70 |
+
"The 'E' in BEDMAS is for exponents, so I'll solve {part} to get {result}.",
|
| 71 |
+
"Time to resolve the exponents. {part} is {result}."
|
| 72 |
+
],
|
| 73 |
+
"multi_div_mod": [
|
| 74 |
+
"Now, I'll perform multiplication, division, and modulo from left to right. The first is {part}, which is {result}.",
|
| 75 |
+
"Next up is multiplication and division. I see {part}, which gives {result}.",
|
| 76 |
+
"Working through multiplication/division from left to right, {part} results in {result}.",
|
| 77 |
+
"The next step is to resolve multiplication and division. {part} is {result}.",
|
| 78 |
+
"Scanning from left to right for M/D/M, I find {part}. This calculates to {result}.",
|
| 79 |
+
"Now for multiplication and division. The operation {part} equals {result}.",
|
| 80 |
+
"Moving on, I'll handle the multiplication/division. {part} becomes {result}.",
|
| 81 |
+
"The next operations are multiply and divide. I'll solve {part} to get {result}.",
|
| 82 |
+
"I will now compute {part}, which results in {result}.",
|
| 83 |
+
"Left-to-right, the next multiplication or division is {part}, giving {result}."
|
| 84 |
+
],
|
| 85 |
+
"add_sub": [
|
| 86 |
+
"Finally, I'll do the addition and subtraction from left to right. I have {part}, which equals {result}.",
|
| 87 |
+
"Last step is addition and subtraction. {part} becomes {result}.",
|
| 88 |
+
"Finishing up with addition/subtraction, {part} evaluates to {result}.",
|
| 89 |
+
"The final operations are addition and subtraction. {part} results in {result}.",
|
| 90 |
+
"Now for the final calculations, addition and subtraction. {part} is {result}.",
|
| 91 |
+
"Working from left to right, the final step is {part}, which is {result}.",
|
| 92 |
+
"The last part of BEDMAS is addition and subtraction. {part} gives {result}.",
|
| 93 |
+
"To finish, I'll solve {part}, resulting in {result}.",
|
| 94 |
+
"Finally, the addition/subtraction part: {part} equals {result}.",
|
| 95 |
+
"The last calculation is {part}, and the answer is {result}."
|
| 96 |
+
]
|
| 97 |
+
}
|
| 98 |
+
COT_FINALIZER_TEMPLATES = [
|
| 99 |
+
"After all steps, the final answer is {result}.",
|
| 100 |
+
"So, the complete result for the expression is {result}.",
|
| 101 |
+
"Therefore, the final value is {result}.",
|
| 102 |
+
"Bringing it all together, the answer is {result}.",
|
| 103 |
+
"The final computation yields {result}.",
|
| 104 |
+
"Thus, the expression evaluates to {result}.",
|
| 105 |
+
"So the final answer is {result}.",
|
| 106 |
+
"After all those steps, we arrive at the answer: {result}.",
|
| 107 |
+
"The result of the entire calculation is {result}.",
|
| 108 |
+
"In conclusion, the answer is {result}."
|
| 109 |
+
]
|
| 110 |
+
SIMPLE_COMPLETION_TEMPLATES = [
|
| 111 |
+
"The equation {expression} equals {result}.", "The answer is {result}.",
|
| 112 |
+
"The result is {result}.", "It equals {result}.", "The final value is {result}.",
|
| 113 |
+
"{expression} results in {result}.", "The solution is {result}.",
|
| 114 |
+
"The value is {result}.", "After calculation, the answer is {result}.",
|
| 115 |
+
"The final result is {result}."
|
| 116 |
+
]
|
| 117 |
+
|
| 118 |
+
ONES = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
|
| 119 |
+
TENS = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
|
| 120 |
+
TEENS = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
|
| 121 |
+
|
| 122 |
+
def number_to_words(n):
|
| 123 |
+
if not isinstance(n, int): return str(n)
|
| 124 |
+
if n == 0: return 'zero'
|
| 125 |
+
if n < 0: return f"negative {number_to_words(abs(n))}"
|
| 126 |
+
if n < 10: return ONES[n]
|
| 127 |
+
if n < 20: return TEENS[n-10]
|
| 128 |
+
if n < 100: return TENS[n//10] + (f"-{ONES[n%10]}" if n%10 else "")
|
| 129 |
+
if n < 1000: return f"{ONES[n//100]} hundred" + (f" and {number_to_words(n%100)}" if n%100 else "")
|
| 130 |
+
if n < 1000000: return f"{number_to_words(n//1000)} thousand" + (f", {number_to_words(n%1000)}" if n%1000 else "")
|
| 131 |
+
return str(n)
|
| 132 |
+
|
| 133 |
+
def operator_to_word(op):
|
| 134 |
+
return {'+': 'plus', '-': 'minus', '*': 'times', '/': 'divided by', '^': 'to the power of', '%': 'modulo'}.get(op, op)
|
| 135 |
+
|
| 136 |
+
def format_number(n):
|
| 137 |
+
if isinstance(n, float) and not n.is_integer():
|
| 138 |
+
return f"{n:.4f}".rstrip('0').rstrip('.')
|
| 139 |
+
return str(int(round(n)))
|
| 140 |
+
|
| 141 |
+
def generate_expression_parts():
|
| 142 |
+
length = random.randint(MIN_LENGTH, MAX_LENGTH)
|
| 143 |
+
parts = []
|
| 144 |
+
for i in range(length):
|
| 145 |
+
if parts and parts[-1] == '^':
|
| 146 |
+
parts.append(random.randint(2, MAX_EXPONENT_POWER))
|
| 147 |
+
else:
|
| 148 |
+
parts.append(random.randint(MIN_NUMBER, MAX_NUMBER))
|
| 149 |
+
|
| 150 |
+
if i < length - 1:
|
| 151 |
+
if parts and parts[-1] != '^':
|
| 152 |
+
op = random.choice(['+', '-', '*', '/', '%', '^'])
|
| 153 |
+
else:
|
| 154 |
+
op = random.choice(['+', '-', '*', '/', '%'])
|
| 155 |
+
|
| 156 |
+
if op == '^':
|
| 157 |
+
parts[-1] = random.randint(MIN_NUMBER, MAX_EXPONENT_BASE)
|
| 158 |
+
parts.append(op)
|
| 159 |
+
|
| 160 |
+
if random.random() < BRACKET_CHANCE and len(parts) >= 5:
|
| 161 |
+
start = random.randrange(0, len(parts) - 2, 2)
|
| 162 |
+
end = random.randrange(start + 2, len(parts), 2)
|
| 163 |
+
parts.insert(end + 1, ')')
|
| 164 |
+
parts.insert(start, '(')
|
| 165 |
+
return parts
|
| 166 |
+
|
| 167 |
+
def solve_with_cot(expression_str):
|
| 168 |
+
"""Optimized solver with better pattern matching and guaranteed termination."""
|
| 169 |
+
steps = []
|
| 170 |
+
current_expr = expression_str.strip()
|
| 171 |
+
|
| 172 |
+
for iteration in range(MAX_SOLVER_ITERATIONS):
|
| 173 |
+
# Remove extra spaces
|
| 174 |
+
current_expr = re.sub(r'\s+', ' ', current_expr).strip()
|
| 175 |
+
|
| 176 |
+
# Check if we're done (single number)
|
| 177 |
+
try:
|
| 178 |
+
final_result = float(current_expr)
|
| 179 |
+
return {'steps': steps, 'result': final_result}
|
| 180 |
+
except ValueError:
|
| 181 |
+
pass
|
| 182 |
+
|
| 183 |
+
reduction_made = False
|
| 184 |
+
|
| 185 |
+
# 1. Handle brackets first
|
| 186 |
+
bracket_match = re.search(r'\(([^()]+)\)', current_expr)
|
| 187 |
+
if bracket_match:
|
| 188 |
+
bracket_content = bracket_match.group(1).strip()
|
| 189 |
+
sub_solver_result = solve_with_cot(bracket_content)
|
| 190 |
+
if not sub_solver_result:
|
| 191 |
+
return None
|
| 192 |
+
|
| 193 |
+
result = sub_solver_result['result']
|
| 194 |
+
try:
|
| 195 |
+
formatted_result = format_number(result)
|
| 196 |
+
except (ValueError, OverflowError):
|
| 197 |
+
return None
|
| 198 |
+
|
| 199 |
+
steps.append(random.choice(COT_STEP_TEMPLATES["brackets"]).format(part=bracket_content, result=formatted_result))
|
| 200 |
+
current_expr = current_expr[:bracket_match.start()] + ' ' + formatted_result + ' ' + current_expr[bracket_match.end():]
|
| 201 |
+
reduction_made = True
|
| 202 |
+
continue
|
| 203 |
+
|
| 204 |
+
# 2. Handle exponents
|
| 205 |
+
exp_match = re.search(r'(-?\d+(?:\.\d+)?)\s*\^\s*(-?\d+(?:\.\d+)?)', current_expr)
|
| 206 |
+
if exp_match:
|
| 207 |
+
base_str, exp_str = exp_match.groups()
|
| 208 |
+
try:
|
| 209 |
+
base = float(base_str)
|
| 210 |
+
exponent = float(exp_str)
|
| 211 |
+
result = base ** exponent
|
| 212 |
+
if abs(result) > 1e12 or math.isnan(result) or math.isinf(result):
|
| 213 |
+
return None
|
| 214 |
+
formatted_result = format_number(result)
|
| 215 |
+
except (OverflowError, ValueError, ZeroDivisionError):
|
| 216 |
+
return None
|
| 217 |
+
|
| 218 |
+
part = f"{base_str} ^ {exp_str}"
|
| 219 |
+
steps.append(random.choice(COT_STEP_TEMPLATES["exponents"]).format(part=part, result=formatted_result))
|
| 220 |
+
current_expr = current_expr[:exp_match.start()] + ' ' + formatted_result + ' ' + current_expr[exp_match.end():]
|
| 221 |
+
reduction_made = True
|
| 222 |
+
continue
|
| 223 |
+
|
| 224 |
+
# 3. Handle multiplication, division, modulo (left to right)
|
| 225 |
+
mdm_match = re.search(r'(-?\d+(?:\.\d+)?)\s*([*/%])\s*(-?\d+(?:\.\d+)?)', current_expr)
|
| 226 |
+
if mdm_match:
|
| 227 |
+
left_str, op, right_str = mdm_match.groups()
|
| 228 |
+
try:
|
| 229 |
+
left = float(left_str)
|
| 230 |
+
right = float(right_str)
|
| 231 |
+
if op == '*':
|
| 232 |
+
result = left * right
|
| 233 |
+
elif op == '/':
|
| 234 |
+
if right == 0:
|
| 235 |
+
return None
|
| 236 |
+
result = left / right
|
| 237 |
+
elif op == '%':
|
| 238 |
+
if right == 0:
|
| 239 |
+
return None
|
| 240 |
+
result = left % right
|
| 241 |
+
|
| 242 |
+
if abs(result) > 1e12 or math.isnan(result) or math.isinf(result):
|
| 243 |
+
return None
|
| 244 |
+
formatted_result = format_number(result)
|
| 245 |
+
except (OverflowError, ValueError, ZeroDivisionError):
|
| 246 |
+
return None
|
| 247 |
+
|
| 248 |
+
part = f"{left_str} {op} {right_str}"
|
| 249 |
+
steps.append(random.choice(COT_STEP_TEMPLATES["multi_div_mod"]).format(part=part, result=formatted_result))
|
| 250 |
+
current_expr = current_expr[:mdm_match.start()] + ' ' + formatted_result + ' ' + current_expr[mdm_match.end():]
|
| 251 |
+
reduction_made = True
|
| 252 |
+
continue
|
| 253 |
+
|
| 254 |
+
# 4. Handle addition and subtraction (left to right)
|
| 255 |
+
# Match pattern where we have number [+|-] number but not at start of negative number
|
| 256 |
+
as_match = re.search(r'(-?\d+(?:\.\d+)?)\s*([+\-])\s*(-?\d+(?:\.\d+)?)', current_expr)
|
| 257 |
+
if as_match:
|
| 258 |
+
left_str, op, right_str = as_match.groups()
|
| 259 |
+
try:
|
| 260 |
+
left = float(left_str)
|
| 261 |
+
right = float(right_str)
|
| 262 |
+
if op == '+':
|
| 263 |
+
result = left + right
|
| 264 |
+
elif op == '-':
|
| 265 |
+
result = left - right
|
| 266 |
+
|
| 267 |
+
if abs(result) > 1e12 or math.isnan(result) or math.isinf(result):
|
| 268 |
+
return None
|
| 269 |
+
formatted_result = format_number(result)
|
| 270 |
+
except (OverflowError, ValueError):
|
| 271 |
+
return None
|
| 272 |
+
|
| 273 |
+
part = f"{left_str} {op} {right_str}"
|
| 274 |
+
steps.append(random.choice(COT_STEP_TEMPLATES["add_sub"]).format(part=part, result=formatted_result))
|
| 275 |
+
current_expr = current_expr[:as_match.start()] + ' ' + formatted_result + ' ' + current_expr[as_match.end():]
|
| 276 |
+
reduction_made = True
|
| 277 |
+
continue
|
| 278 |
+
|
| 279 |
+
# If no reduction was made, we're stuck - return None
|
| 280 |
+
if not reduction_made:
|
| 281 |
+
return None
|
| 282 |
+
|
| 283 |
+
# Timeout reached
|
| 284 |
+
return None
|
| 285 |
+
|
| 286 |
+
def generate_training_example(_=None):
|
| 287 |
+
"""Generate a single training example with retry logic."""
|
| 288 |
+
max_retries = 50 # Reduced from 100 for faster generation
|
| 289 |
+
for attempt in range(max_retries):
|
| 290 |
+
try:
|
| 291 |
+
expression_parts = generate_expression_parts()
|
| 292 |
+
expression_str = " ".join(map(str, expression_parts))
|
| 293 |
+
|
| 294 |
+
cot_result = solve_with_cot(expression_str)
|
| 295 |
+
|
| 296 |
+
if cot_result and isinstance(cot_result['result'], (int, float)):
|
| 297 |
+
final_result = cot_result['result']
|
| 298 |
+
|
| 299 |
+
# Filter out extreme values
|
| 300 |
+
if abs(final_result) > 1e12 or (final_result != 0 and abs(final_result) < 1e-4):
|
| 301 |
+
continue
|
| 302 |
+
if math.isnan(final_result) or math.isinf(final_result):
|
| 303 |
+
continue
|
| 304 |
+
|
| 305 |
+
result_str = format_number(final_result)
|
| 306 |
+
|
| 307 |
+
if len(result_str) > 20:
|
| 308 |
+
continue
|
| 309 |
+
|
| 310 |
+
use_words = random.random() < WORD_FORM_CHANCE
|
| 311 |
+
if use_words:
|
| 312 |
+
expression_text = ' '.join([number_to_words(p) if isinstance(p, int) else operator_to_word(p) if isinstance(p, str) else str(p) for p in expression_parts])
|
| 313 |
+
result_text = number_to_words(int(round(final_result)))
|
| 314 |
+
completion = random.choice(SIMPLE_COMPLETION_TEMPLATES).format(expression=expression_text, result=result_text)
|
| 315 |
+
else:
|
| 316 |
+
expression_text = expression_str
|
| 317 |
+
result_text = result_str
|
| 318 |
+
use_reasoning = random.random() < REASONING_CHANCE
|
| 319 |
+
if use_reasoning:
|
| 320 |
+
intro = random.choice(COT_INTRO_TEMPLATES).format(expression=expression_text)
|
| 321 |
+
steps_text = " ".join(cot_result['steps'])
|
| 322 |
+
finalizer = random.choice(COT_FINALIZER_TEMPLATES).format(result=result_text)
|
| 323 |
+
completion = f"{intro} {steps_text} {finalizer} </think>"
|
| 324 |
+
else:
|
| 325 |
+
completion = random.choice(SIMPLE_COMPLETION_TEMPLATES).format(expression=expression_text, result=result_text)
|
| 326 |
+
|
| 327 |
+
if random.random() < SENTENCE_FORM_CHANCE:
|
| 328 |
+
prompt = random.choice(PROMPT_TEMPLATES).format(expression=expression_text)
|
| 329 |
+
else:
|
| 330 |
+
prompt = f"{expression_text} ="
|
| 331 |
+
|
| 332 |
+
# Clean up spacing
|
| 333 |
+
prompt = re.sub(r'\s*\(', ' (', prompt)
|
| 334 |
+
prompt = re.sub(r'\)\s*', ') ', prompt).strip()
|
| 335 |
+
prompt = re.sub(r'\s+', ' ', prompt)
|
| 336 |
+
completion = re.sub(r'\s*\(', ' (', completion)
|
| 337 |
+
completion = re.sub(r'\)\s*', ') ', completion).strip()
|
| 338 |
+
completion = re.sub(r'\s+', ' ', completion)
|
| 339 |
+
|
| 340 |
+
return {"prompt": prompt, "completion": " " + completion}
|
| 341 |
+
except Exception as e:
|
| 342 |
+
continue
|
| 343 |
+
|
| 344 |
+
return None
|
| 345 |
+
|
| 346 |
+
def main():
|
| 347 |
+
print(f"🔥 Generating {NUM_LINES:,} examples using {NUM_WORKERS} parallel workers...")
|
| 348 |
+
print(f" Appending to '{OUTPUT_FILE}'...")
|
| 349 |
+
start_time = time.time()
|
| 350 |
+
|
| 351 |
+
generated_count = 0
|
| 352 |
+
failed_count = 0
|
| 353 |
+
|
| 354 |
+
with open(OUTPUT_FILE, "a", encoding="utf-8") as f:
|
| 355 |
+
with multiprocessing.Pool(processes=NUM_WORKERS) as pool:
|
| 356 |
+
results_iterator = pool.imap_unordered(generate_training_example, range(NUM_LINES), chunksize=100)
|
| 357 |
+
|
| 358 |
+
for item in tqdm(results_iterator, total=NUM_LINES, desc="Generating examples"):
|
| 359 |
+
if item:
|
| 360 |
+
f.write(json.dumps(item) + "\n")
|
| 361 |
+
generated_count += 1
|
| 362 |
+
else:
|
| 363 |
+
failed_count += 1
|
| 364 |
+
|
| 365 |
+
elapsed_time = time.time() - start_time
|
| 366 |
+
print(f"\n\n✅ Done! Appended {generated_count:,} new items to '{OUTPUT_FILE}' in {elapsed_time:.2f}s.")
|
| 367 |
+
print(f" 📊 Success rate: {generated_count}/{NUM_LINES} ({100*generated_count/NUM_LINES:.1f}%)")
|
| 368 |
+
if failed_count > 0:
|
| 369 |
+
print(f" ⚠️ {failed_count:,} generation attempts failed (expressions too complex or invalid)")
|
| 370 |
+
|
| 371 |
+
if __name__ == "__main__":
|
| 372 |
+
multiprocessing.freeze_support()
|
| 373 |
+
main()
|