File size: 6,126 Bytes
4623c17 41423f7 4623c17 861b13c 4d5a2c9 4623c17 4d5a2c9 4623c17 4d5a2c9 4623c17 4d5a2c9 4623c17 4d5a2c9 4623c17 4d5a2c9 4623c17 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | import { NextRequest, NextResponse } from 'next/server'
import { spawn } from 'child_process'
import { writeFile, unlink } from 'fs/promises'
import { join } from 'path'
import { tmpdir } from 'os'
export async function POST(request: NextRequest) {
let tempFile: string | null = null
try {
const body = await request.json()
const { code, testCase, functionName } = body
// Debug: Log the code being executed
if (process.env.NODE_ENV === 'development') {
console.log('[execute-python API] Received code to execute:', {
functionName,
codeLength: code?.length || 0,
codePreview: code?.substring(0, 200) || 'empty',
testInput: testCase?.input,
})
}
if (!code || !testCase) {
return NextResponse.json(
{ error: 'Code and test case are required' },
{ status: 400 }
)
}
// Create a temporary Python file
const tempDir = tmpdir()
tempFile = join(tempDir, `python_exec_${Date.now()}_${Math.random().toString(36).substring(7)}.py`)
// Create helper code to convert array to ListNode for linked list problems
const helperCode = `
# Helper to convert list to ListNode
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def list_to_linked_list(arr):
if not arr:
return None
head = ListNode(arr[0])
current = head
for val in arr[1:]:
current.next = ListNode(val)
current = current.next
return head
def linked_list_to_list(head):
result = []
current = head
while current:
result.append(current.val)
current = current.next
return result
# User's code
${code}
# Test execution
import json
import sys
try:
test_input = ${JSON.stringify(testCase.input)}
# Check if this is a linked list problem (only if function name suggests it)
function_name_str = '${functionName}'
is_linked_list = 'List' in function_name_str or 'reverse' in function_name_str or 'merge' in function_name_str
if isinstance(test_input, list) and len(test_input) == 1 and isinstance(test_input[0], list) and is_linked_list:
# Linked list problem - convert array to ListNode
head = list_to_linked_list(test_input[0])
result = ${functionName}(head)
# Convert ListNode back to list
output = linked_list_to_list(result) if result else []
print(json.dumps(output))
elif isinstance(test_input, list) and len(test_input) == 2:
# Two parameters (like Two Sum)
result = ${functionName}(test_input[0], test_input[1])
print(json.dumps(result))
elif isinstance(test_input, list) and len(test_input) == 1:
# Single parameter (array or other)
if isinstance(test_input[0], list):
# Array parameter - pass the inner array directly
result = ${functionName}(test_input[0])
else:
# Single value parameter
result = ${functionName}(test_input[0])
print(json.dumps(result))
else:
# Direct input
result = ${functionName}(test_input)
print(json.dumps(result))
except Exception as e:
import traceback
error_msg = f"ERROR: {str(e)}\\n{traceback.format_exc()}"
print(error_msg, file=sys.stderr)
sys.exit(1)
`
// Ensure tempFile is not null before using it
if (!tempFile) {
return NextResponse.json(
{ error: 'Failed to create temporary file' },
{ status: 500 }
)
}
// Store in const so TypeScript knows it's not null
const pythonFile = tempFile
// Write the Python file
await writeFile(pythonFile, helperCode, 'utf-8')
// Execute Python code
const result = await new Promise<{ output: string; error: string; exitCode: number }>((resolve) => {
const python = spawn('python3', [pythonFile])
let output = ''
let error = ''
python.stdout.on('data', (data) => {
output += data.toString()
})
python.stderr.on('data', (data) => {
error += data.toString()
})
python.on('close', (code) => {
resolve({ output: output.trim(), error: error.trim(), exitCode: code || 0 })
})
// Timeout after 5 seconds
setTimeout(() => {
python.kill()
resolve({ output: '', error: 'Execution timeout (5 seconds)', exitCode: -1 })
}, 5000)
})
// Clean up temp file
if (pythonFile) {
try {
await unlink(pythonFile)
} catch (e) {
// Ignore cleanup errors
}
}
if (result.exitCode !== 0 || result.error) {
// If there's an error but we got some output, try to parse it
if (result.output && result.output.trim()) {
try {
const actualOutput = JSON.parse(result.output)
return NextResponse.json({
success: true,
output: actualOutput,
})
} catch (e) {
// If parsing fails, return the error
}
}
return NextResponse.json({
success: false,
error: result.error || 'Execution failed',
output: result.output,
})
}
// Parse the output
if (!result.output || !result.output.trim()) {
return NextResponse.json({
success: false,
error: 'No output from code execution',
rawOutput: result.output,
})
}
try {
const actualOutput = JSON.parse(result.output)
return NextResponse.json({
success: true,
output: actualOutput,
})
} catch (e) {
return NextResponse.json({
success: false,
error: `Failed to parse output as JSON: ${result.output}`,
rawOutput: result.output,
})
}
} catch (error: any) {
// Clean up temp file on error
const tempFileToClean = tempFile
if (tempFileToClean) {
try {
await unlink(tempFileToClean)
} catch (e) {
// Ignore cleanup errors
}
}
return NextResponse.json(
{ error: error.message || 'Internal server error' },
{ status: 500 }
)
}
}
|