Mahdi Naser Moghadasi
Add debug logging to verify latest code is executed
41423f7
Raw History Blame Contribute Delete
6.13 kB
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 }
)
}
}