* Preprocess input string to make it more JSON-compatible * @param {string} input * @returns {string}
(input)
| 223 | * @returns {string} |
| 224 | */ |
| 225 | static preprocess(input) { |
| 226 | let result = input.trim(); |
| 227 | |
| 228 | // Remove Python comments |
| 229 | result = result.replace(/#.*$/gm, ''); |
| 230 | |
| 231 | // Remove numpy array wrapper if present |
| 232 | result = result.replace(/np\.array\s*\(/g, ''); |
| 233 | result = result.replace(/numpy\.array\s*\(/g, ''); |
| 234 | result = result.replace(/array\s*\(/g, ''); |
| 235 | result = result.replace(/torch\.tensor\s*\(/g, ''); |
| 236 | result = result.replace(/tensor\s*\(/g, ''); |
| 237 | |
| 238 | // Remove dtype specifications |
| 239 | result = result.replace(/,?\s*dtype\s*=\s*[^,\)]+/g, ''); |
| 240 | |
| 241 | // Remove trailing parentheses from numpy/torch wrappers |
| 242 | // Count opening brackets/parens and remove extra closing ones |
| 243 | let bracketCount = 0; |
| 244 | let parenCount = 0; |
| 245 | for (const char of result) { |
| 246 | if (char === '[') bracketCount++; |
| 247 | if (char === ']') bracketCount--; |
| 248 | if (char === '(') parenCount++; |
| 249 | if (char === ')') parenCount--; |
| 250 | } |
| 251 | while (parenCount > 0) { |
| 252 | result = result.replace(/\)\s*$/, ''); |
| 253 | parenCount--; |
| 254 | } |
| 255 | |
| 256 | // Replace Python True/False/None with JSON equivalents |
| 257 | result = result.replace(/\bTrue\b/g, 'true'); |
| 258 | result = result.replace(/\bFalse\b/g, 'false'); |
| 259 | result = result.replace(/\bNone\b/g, 'null'); |
| 260 | |
| 261 | // Handle scientific notation (e.g., 1e-5 or 1E+5) |
| 262 | // This should already work in JSON, but ensure proper formatting |
| 263 | |
| 264 | // Remove trailing commas before closing brackets (common in Python) |
| 265 | result = result.replace(/,(\s*[\]\)])/g, '$1'); |
| 266 | |
| 267 | // Ensure the string starts and ends with brackets |
| 268 | result = result.trim(); |
| 269 | |
| 270 | return result; |
| 271 | } |
| 272 | |
| 273 | /** |
| 274 | * Parse Python list notation that might not be valid JSON |