Spaces:
Sleeping
Sleeping
File size: 44,310 Bytes
a2049a0 3485015 a2049a0 3485015 a2049a0 0f90aa0 3485015 0f90aa0 a2049a0 da404fd a2049a0 da404fd a2049a0 da404fd 10e0b64 a2049a0 10e0b64 a2049a0 da404fd a2049a0 da404fd a2049a0 da404fd a2049a0 da404fd a2049a0 da404fd a2049a0 da404fd a2049a0 0f90aa0 da404fd 072178c ea1e28c 072178c da404fd 072178c a2049a0 072178c da404fd ea1e28c 3485015 ea1e28c 3485015 ea1e28c 3485015 ea1e28c 3485015 ea1e28c 3485015 ea1e28c 3485015 ea1e28c 3485015 ea1e28c 3485015 ea1e28c 3485015 ea1e28c 3485015 ea1e28c 3485015 ea1e28c 072178c ea1e28c 072178c a2049a0 ea1e28c 072178c 0f90aa0 ea1e28c 072178c ea1e28c da404fd 072178c a2049a0 0f90aa0 a2049a0 0f90aa0 |
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 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 |
import os
import tempfile
import shutil
import asyncio
from pathlib import Path
from typing import List, Optional, Dict, Any
import uuid
import re
from fastapi import (
UploadFile,
File,
Form,
HTTPException,
FastAPI,
)
from fastapi.responses import JSONResponse
from pydantic import BaseModel
import json
import resource
import platform
from loguru import logger
import subprocess
app = FastAPI(title="Code Execution and Input Analysis API", docs_url="/")
# Configuration
MAX_EXECUTION_TIME = 5 # seconds
MAX_MEMORY = 256 * 1024 * 1024 # 256MB
MAX_FILE_SIZE = 10 * 1024 * 1024 # 10MB
MAX_TOTAL_SIZE = 2 * 1024 * 1024 # 2MB total size limit for uploads and repos
class ExecutionResult(BaseModel):
success: bool
stdout: str
stderr: str
execution_time: float
exit_code: int
error: Optional[str] = None
class InputPattern(BaseModel):
type: str # "input", "scanf", "cin", etc.
line_number: int
variable_name: Optional[str] = None
prompt_message: Optional[str] = None
data_type: Optional[str] = None # "int", "str", "float", etc.
raw_code: str
class InputAnalysisResult(BaseModel):
language: str
total_inputs: int
input_patterns: List[InputPattern]
suggestions: List[str] # UI suggestions for user
class CodeExecutor:
def __init__(self):
self.compilers = {
"c": "clang" if platform.system() == "Darwin" else "gcc",
"cpp": "clang++" if platform.system() == "Darwin" else "g++",
"java": "javac",
"python": "python3",
}
# Check and log ulimits on startup
self._check_ulimits()
def _check_ulimits(self):
"""Check current ulimits and log them"""
try:
# Check various ulimits
limits = {
"RLIMIT_NOFILE": resource.RLIMIT_NOFILE, # file descriptors
"RLIMIT_NPROC": resource.RLIMIT_NPROC, # processes
"RLIMIT_STACK": resource.RLIMIT_STACK, # stack size
}
logger.info("Current ulimits:")
for name, limit_type in limits.items():
try:
soft, hard = resource.getrlimit(limit_type)
logger.info(f"{name}: soft={soft}, hard={hard}")
except:
pass
# Try to increase limits if they're too low
try:
# Increase file descriptors
resource.setrlimit(resource.RLIMIT_NOFILE, (65536, 65536))
except:
try:
# Try a lower value if the high one fails
resource.setrlimit(resource.RLIMIT_NOFILE, (4096, 4096))
except:
pass
except Exception as e:
logger.warning(f"Could not check/set ulimits: {e}")
async def _create_java_wrapper(self, workspace: str, jvm_opts: List[str]) -> str:
"""Create a wrapper script for Java execution with ulimit settings"""
wrapper_content = f"""#!/bin/bash
# Set ulimits to prevent memory allocation issues
ulimit -n 65536 2>/dev/null || ulimit -n 4096
ulimit -u 32768 2>/dev/null || ulimit -u 2048
ulimit -s 8192 2>/dev/null || ulimit -s 4096
ulimit -v unlimited 2>/dev/null || true
ulimit -m unlimited 2>/dev/null || true
# Log current ulimits for debugging
echo "Current ulimits:" >&2
ulimit -a >&2
# Execute Java with the provided options
exec java {' '.join(jvm_opts)} "$@"
"""
wrapper_path = os.path.join(workspace, "java_wrapper.sh")
with open(wrapper_path, 'w') as f:
f.write(wrapper_content)
# Make executable
os.chmod(wrapper_path, 0o755)
return wrapper_path
def set_resource_limits(self):
"""Set resource limits for subprocess (Unix only)"""
if platform.system() == "Linux":
resource.setrlimit(
resource.RLIMIT_CPU, (MAX_EXECUTION_TIME, MAX_EXECUTION_TIME)
)
resource.setrlimit(resource.RLIMIT_AS, (MAX_MEMORY, MAX_MEMORY))
def check_available_memory(self) -> int:
"""Create a wrapper script for Java execution with ulimit settings"""
wrapper_content = f"""#!/bin/bash
# Set ulimits to prevent memory allocation issues
ulimit -n 65536 2>/dev/null || ulimit -n 4096
ulimit -u 32768 2>/dev/null || ulimit -u 2048
ulimit -s 8192 2>/dev/null || ulimit -s 4096
ulimit -v unlimited 2>/dev/null || true
ulimit -m unlimited 2>/dev/null || true
# Log current ulimits for debugging
echo "Current ulimits:" >&2
ulimit -a >&2
# Execute Java with the provided options
exec java {' '.join(jvm_opts)} "$@"
"""
wrapper_path = os.path.join(workspace, "java_wrapper.sh")
with open(wrapper_path, 'w') as f:
f.write(wrapper_content)
# Make executable
os.chmod(wrapper_path, 0o755)
return wrapper_path
"""Check available memory in MB"""
try:
with open('/proc/meminfo', 'r') as f:
meminfo = f.read()
available_match = re.search(r'MemAvailable:\s+(\d+)\s+kB', meminfo)
if available_match:
available_kb = int(available_match.group(1))
available_mb = available_kb // 1024
logger.info(f"Available memory: {available_mb}MB")
return available_mb
# Fallback to MemFree + Cached
free_match = re.search(r'MemFree:\s+(\d+)\s+kB', meminfo)
cached_match = re.search(r'Cached:\s+(\d+)\s+kB', meminfo)
if free_match and cached_match:
free_kb = int(free_match.group(1))
cached_kb = int(cached_match.group(1))
available_mb = (free_kb + cached_kb) // 1024
logger.info(f"Estimated available memory: {available_mb}MB")
return available_mb
except Exception as e:
logger.warning(f"Could not check memory: {e}")
return 0 # Unknown
def analyze_input_patterns(
self, language: str, file_contents: Dict[str, str]
) -> InputAnalysisResult:
"""Analyze code files to detect input patterns"""
patterns = []
if language == "python":
patterns = self._analyze_python_inputs(file_contents)
elif language == "java":
patterns = self._analyze_java_inputs(file_contents)
elif language in ["c", "cpp"]:
patterns = self._analyze_c_cpp_inputs(file_contents)
suggestions = self._generate_input_suggestions(patterns, language)
return InputAnalysisResult(
language=language,
total_inputs=len(patterns),
input_patterns=patterns,
suggestions=suggestions,
)
def _analyze_python_inputs(
self, file_contents: Dict[str, str]
) -> List[InputPattern]:
"""Analyze Python files for input() patterns"""
patterns = []
for filename, content in file_contents.items():
lines = content.split("\n")
for i, line in enumerate(lines, 1):
# Pattern 1: variable = input("prompt")
match = re.search(
r'(\w+)\s*=\s*input\s*\(\s*["\']([^"\']*)["\']?\s*\)', line
)
if match:
var_name, prompt = match.groups()
patterns.append(
InputPattern(
type="input",
line_number=i,
variable_name=var_name,
prompt_message=prompt or f"Enter value for {var_name}",
data_type="str",
raw_code=line.strip(),
)
)
continue
# Pattern 2: variable = int(input("prompt"))
match = re.search(
r'(\w+)\s*=\s*(int|float|str)\s*\(\s*input\s*\(\s*["\']([^"\']*)["\']?\s*\)\s*\)',
line,
)
if match:
var_name, data_type, prompt = match.groups()
patterns.append(
InputPattern(
type="input",
line_number=i,
variable_name=var_name,
prompt_message=prompt
or f"Enter {data_type} value for {var_name}",
data_type=data_type,
raw_code=line.strip(),
)
)
continue
# Pattern 3: Simple input() without assignment
if "input(" in line and "=" not in line:
patterns.append(
InputPattern(
type="input",
line_number=i,
variable_name=None,
prompt_message="Enter input",
data_type="str",
raw_code=line.strip(),
)
)
return patterns
def _analyze_java_inputs(self, file_contents: Dict[str, str]) -> List[InputPattern]:
"""Analyze Java files for Scanner input patterns"""
patterns = []
for filename, content in file_contents.items():
lines = content.split("\n")
for i, line in enumerate(lines, 1):
# Pattern 1: scanner.nextInt(), scanner.nextLine(), etc.
match = re.search(r"(\w+)\s*=\s*(\w+)\.next(\w+)\s*\(\s*\)", line)
if match:
var_name, scanner_name, method = match.groups()
data_type = self._java_method_to_type(method)
patterns.append(
InputPattern(
type="scanner",
line_number=i,
variable_name=var_name,
prompt_message=f"Enter {data_type} value for {var_name}",
data_type=data_type,
raw_code=line.strip(),
)
)
continue
# Pattern 2: Direct scanner calls without assignment
match = re.search(r"(\w+)\.next(\w+)\s*\(\s*\)", line)
if match and "=" not in line:
scanner_name, method = match.groups()
data_type = self._java_method_to_type(method)
patterns.append(
InputPattern(
type="scanner",
line_number=i,
variable_name=None,
prompt_message=f"Enter {data_type} input",
data_type=data_type,
raw_code=line.strip(),
)
)
return patterns
def _analyze_c_cpp_inputs(
self, file_contents: Dict[str, str]
) -> List[InputPattern]:
"""Analyze C/C++ files for input patterns"""
patterns = []
for filename, content in file_contents.items():
lines = content.split("\n")
for i, line in enumerate(lines, 1):
# Pattern 1: scanf("%d", &variable)
match = re.search(
r'scanf\s*\(\s*["\']([^"\']*)["\'],\s*&(\w+)\s*\)', line
)
if match:
format_spec, var_name = match.groups()
data_type = self._c_format_to_type(format_spec)
patterns.append(
InputPattern(
type="scanf",
line_number=i,
variable_name=var_name,
prompt_message=f"Enter {data_type} value for {var_name}",
data_type=data_type,
raw_code=line.strip(),
)
)
continue
# Pattern 2: cin >> variable (C++)
match = re.search(r"cin\s*>>\s*(\w+)", line)
if match:
var_name = match.group(1)
patterns.append(
InputPattern(
type="cin",
line_number=i,
variable_name=var_name,
prompt_message=f"Enter value for {var_name}",
data_type="unknown",
raw_code=line.strip(),
)
)
continue
# Pattern 3: getline(cin, variable) for strings
match = re.search(r"getline\s*\(\s*cin\s*,\s*(\w+)\s*\)", line)
if match:
var_name = match.group(1)
patterns.append(
InputPattern(
type="getline",
line_number=i,
variable_name=var_name,
prompt_message=f"Enter string for {var_name}",
data_type="string",
raw_code=line.strip(),
)
)
return patterns
def _java_method_to_type(self, method: str) -> str:
"""Convert Java Scanner method to data type"""
type_mapping = {
"Int": "int",
"Double": "double",
"Float": "float",
"Long": "long",
"Line": "string",
"": "string",
}
return type_mapping.get(method, "string")
def _c_format_to_type(self, format_spec: str) -> str:
"""Convert C format specifier to data type"""
if "%d" in format_spec or "%i" in format_spec:
return "int"
elif "%f" in format_spec:
return "float"
elif "%lf" in format_spec:
return "double"
elif "%c" in format_spec:
return "char"
elif "%s" in format_spec:
return "string"
return "unknown"
def _generate_input_suggestions(
self, patterns: List[InputPattern], language: str
) -> List[str]:
"""Generate UI suggestions based on detected patterns"""
suggestions = []
if not patterns:
suggestions.append(
"No input patterns detected. Code will run without user input."
)
return suggestions
suggestions.append(
f"Detected {len(patterns)} input requirement(s) in {language} code:"
)
for i, pattern in enumerate(patterns, 1):
if pattern.variable_name:
suggestions.append(
f"{i}. Line {pattern.line_number}: {pattern.prompt_message} "
f"(Variable: {pattern.variable_name}, Type: {pattern.data_type})"
)
else:
suggestions.append(
f"{i}. Line {pattern.line_number}: {pattern.prompt_message} "
f"(Type: {pattern.data_type})"
)
suggestions.append(
"Please provide input values in the order they appear in the code."
)
return suggestions
async def execute_code(
self,
language: str,
main_files: List[str],
workspace: str,
input_data: Optional[List[str]] = None,
) -> ExecutionResult:
"""Execute code based on language with optional input data"""
try:
if language == "python":
return await self._execute_python(main_files, workspace, input_data)
elif language == "java":
return await self._execute_java(main_files, workspace, input_data)
elif language in ["c", "cpp"]:
return await self._execute_c_cpp(
main_files, workspace, language, input_data
)
else:
raise ValueError(f"Unsupported language: {language}")
except Exception as e:
return ExecutionResult(
success=False,
stdout="",
stderr=str(e),
execution_time=0,
exit_code=-1,
error=str(e),
)
async def _execute_with_input(
self, command: List[str], workspace: str, input_data: Optional[List[str]] = None
) -> tuple:
"""Execute process with input data"""
process = await asyncio.create_subprocess_exec(
*command,
cwd=workspace,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
stdin=asyncio.subprocess.PIPE,
preexec_fn=(
self.set_resource_limits if platform.system() == "Linux" else None
),
)
# Prepare input string
stdin_input = None
if input_data:
stdin_input = "\n".join(input_data) + "\n"
stdin_input = stdin_input.encode("utf-8")
try:
stdout, stderr = await asyncio.wait_for(
process.communicate(input=stdin_input), timeout=MAX_EXECUTION_TIME
)
return stdout, stderr, process.returncode
except asyncio.TimeoutError:
process.kill()
await process.wait()
raise asyncio.TimeoutError()
async def _execute_python(
self,
main_files: List[str],
workspace: str,
input_data: Optional[List[str]] = None,
) -> ExecutionResult:
"""Execute Python code with input support"""
results = []
for main_file in main_files:
file_path = os.path.join(workspace, main_file)
if not os.path.exists(file_path):
results.append(
ExecutionResult(
success=False,
stdout="",
stderr=f"File not found: {main_file}",
execution_time=0,
exit_code=-1,
)
)
continue
try:
start_time = asyncio.get_event_loop().time()
stdout, stderr, returncode = await self._execute_with_input(
["python3", main_file], workspace, input_data
)
execution_time = asyncio.get_event_loop().time() - start_time
results.append(
ExecutionResult(
success=returncode == 0,
stdout=stdout.decode("utf-8", errors="replace"),
stderr=stderr.decode("utf-8", errors="replace"),
execution_time=execution_time,
exit_code=returncode,
)
)
except asyncio.TimeoutError:
results.append(
ExecutionResult(
success=False,
stdout="",
stderr="Execution timeout exceeded",
execution_time=MAX_EXECUTION_TIME,
exit_code=-1,
)
)
except Exception as e:
results.append(
ExecutionResult(
success=False,
stdout="",
stderr=str(e),
execution_time=0,
exit_code=-1,
error=str(e),
)
)
return self._combine_results(results, main_files)
async def _execute_java(
self,
main_files: List[str],
workspace: str,
input_data: Optional[List[str]] = None,
) -> ExecutionResult:
"""Compile and execute Java code with optimized memory settings"""
# Check if we have .java files to compile
java_files = list(Path(workspace).glob("*.java"))
needs_compilation = len(java_files) > 0
# If we have .java files, compile them
if needs_compilation:
logger.info(f"Found {len(java_files)} Java source files, compiling...")
# Compile with minimal memory
compile_cmd = ["javac", "-J-Xmx32m"] + [str(f) for f in java_files]
compile_process = await asyncio.create_subprocess_exec(
*compile_cmd,
cwd=workspace,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await compile_process.communicate()
if compile_process.returncode != 0:
return ExecutionResult(
success=False,
stdout="",
stderr=f"Compilation failed:\n{stderr.decode('utf-8', errors='replace')}",
execution_time=0,
exit_code=compile_process.returncode,
)
logger.info("Java compilation successful")
else:
# Check if we have .class files
class_files_missing = []
for main_file in main_files:
if main_file.endswith(".class"):
class_file_path = os.path.join(workspace, main_file)
else:
class_file_path = os.path.join(workspace, f"{main_file}.class")
if not os.path.exists(class_file_path):
class_files_missing.append(main_file)
if class_files_missing:
return ExecutionResult(
success=False,
stdout="",
stderr=f"No Java source files found and missing .class files for: {', '.join(class_files_missing)}",
execution_time=0,
exit_code=-1,
)
logger.info("Using existing .class files, skipping compilation")
# Execute Java with multiple fallback strategies
results = []
for main_file in main_files:
# Determine class name
if main_file.endswith(".class"):
class_name = main_file.replace(".class", "")
elif main_file.endswith(".java"):
class_name = main_file.replace(".java", "")
else:
class_name = main_file
# Verify the .class file exists
class_file_path = os.path.join(workspace, f"{class_name}.class")
if not os.path.exists(class_file_path):
results.append(
ExecutionResult(
success=False,
stdout="",
stderr=f"Class file not found: {class_name}.class",
execution_time=0,
exit_code=-1,
)
)
continue
# Try different JVM configurations
jvm_configs = [
# Config 1: Ultra minimal with no code cache reservation
[
"-Xint", # Interpreter only mode (no JIT)
"-Xmx32m",
"-Xms2m",
"-XX:MaxMetaspaceSize=16m",
"-Djava.awt.headless=true",
],
# Config 2: Minimal with small code cache
[
"-XX:+UseSerialGC",
"-Xmx32m",
"-Xms4m",
"-XX:ReservedCodeCacheSize=8m",
"-XX:InitialCodeCacheSize=2m",
"-XX:MaxMetaspaceSize=24m",
"-XX:-TieredCompilation",
"-Djava.awt.headless=true",
],
# Config 3: Slightly more memory
[
"-Xmx48m",
"-Xms8m",
"-XX:ReservedCodeCacheSize=16m",
"-XX:MaxMetaspaceSize=32m",
"-XX:-TieredCompilation",
"-Djava.awt.headless=true",
],
# Config 4: Use container support
[
"-XX:+UseContainerSupport",
"-XX:MaxRAMPercentage=25.0",
"-XX:-TieredCompilation",
"-Djava.awt.headless=true",
],
]
result = None
for config_idx, jvm_opts in enumerate(jvm_configs):
try:
logger.info(f"Trying JVM config {config_idx + 1} for {class_name}")
start_time = asyncio.get_event_loop().time()
# For first two configs, try with wrapper script
if config_idx < 2:
wrapper_path = await self._create_java_wrapper(workspace, jvm_opts)
java_cmd = [wrapper_path, class_name]
else:
java_cmd = ["java"] + jvm_opts + [class_name]
stdout, stderr, returncode = await self._execute_with_input(
java_cmd, workspace, input_data
)
execution_time = asyncio.get_event_loop().time() - start_time
# Check if it's a memory-related error
stderr_text = stderr.decode("utf-8", errors="replace")
if "Could not reserve" in stderr_text or "insufficient memory" in stderr_text:
logger.warning(f"Config {config_idx + 1} failed with memory error, trying next...")
continue
result = ExecutionResult(
success=returncode == 0,
stdout=stdout.decode("utf-8", errors="replace"),
stderr=stderr_text,
execution_time=execution_time,
exit_code=returncode,
)
logger.info(f"Java execution completed with config {config_idx + 1}")
break
except asyncio.TimeoutError:
result = ExecutionResult(
success=False,
stdout="",
stderr="Execution timeout exceeded",
execution_time=MAX_EXECUTION_TIME,
exit_code=-1,
)
break
except Exception as e:
logger.error(f"Error with config {config_idx + 1}: {str(e)}")
continue
# If all configs failed, return error
if result is None:
result = ExecutionResult(
success=False,
stdout="",
stderr="Failed to execute Java code with all memory configurations. The container environment may have insufficient memory for JVM.",
execution_time=0,
exit_code=-1,
error="All JVM configurations failed"
)
results.append(result)
return self._combine_results(results, main_files)
async def _execute_c_cpp(
self,
main_files: List[str],
workspace: str,
language: str,
input_data: Optional[List[str]] = None,
) -> ExecutionResult:
"""Compile and execute C/C++ code with input support"""
compiler = self.compilers[language]
results = []
for main_file in main_files:
file_path = os.path.join(workspace, main_file)
if not os.path.exists(file_path):
results.append(
ExecutionResult(
success=False,
stdout="",
stderr=f"File not found: {main_file}",
execution_time=0,
exit_code=-1,
)
)
continue
# Output binary name
output_name = main_file.replace(".c", "").replace(".cpp", "")
# Compile
compile_process = await asyncio.create_subprocess_exec(
compiler,
main_file,
"-o",
output_name,
cwd=workspace,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await compile_process.communicate()
if compile_process.returncode != 0:
results.append(
ExecutionResult(
success=False,
stdout="",
stderr=f"Compilation failed:\n{stderr.decode('utf-8', errors='replace')}",
execution_time=0,
exit_code=compile_process.returncode,
)
)
continue
# Execute
try:
start_time = asyncio.get_event_loop().time()
stdout, stderr, returncode = await self._execute_with_input(
[f"./{output_name}"], workspace, input_data
)
execution_time = asyncio.get_event_loop().time() - start_time
results.append(
ExecutionResult(
success=returncode == 0,
stdout=stdout.decode("utf-8", errors="replace"),
stderr=stderr.decode("utf-8", errors="replace"),
execution_time=execution_time,
exit_code=returncode,
)
)
except asyncio.TimeoutError:
results.append(
ExecutionResult(
success=False,
stdout="",
stderr="Execution timeout exceeded",
execution_time=MAX_EXECUTION_TIME,
exit_code=-1,
)
)
except Exception as e:
results.append(
ExecutionResult(
success=False,
stdout="",
stderr=str(e),
execution_time=0,
exit_code=-1,
error=str(e),
)
)
return self._combine_results(results, main_files)
def _combine_results(
self, results: List[ExecutionResult], main_files: List[str]
) -> ExecutionResult:
"""Combine multiple execution results"""
if len(results) == 1:
return results[0]
else:
combined_stdout = "\n".join(
[f"=== {main_files[i]} ===\n{r.stdout}" for i, r in enumerate(results)]
)
combined_stderr = "\n".join(
[
f"=== {main_files[i]} ===\n{r.stderr}"
for i, r in enumerate(results)
if r.stderr
]
)
total_time = sum(r.execution_time for r in results)
all_success = all(r.success for r in results)
return ExecutionResult(
success=all_success,
stdout=combined_stdout,
stderr=combined_stderr,
execution_time=total_time,
exit_code=0 if all_success else -1,
)
def get_directory_size(directory_path: str) -> int:
"""Calculate total size of directory in bytes"""
total_size = 0
try:
for dirpath, dirnames, filenames in os.walk(directory_path):
for filename in filenames:
filepath = os.path.join(dirpath, filename)
if os.path.exists(filepath):
total_size += os.path.getsize(filepath)
except Exception as e:
print(f"Error calculating directory size: {e}")
return float("inf")
return total_size
def validate_upload_size(files: List[UploadFile]) -> tuple[bool, int]:
"""Validate total size of uploaded files"""
total_size = 0
for file in files:
if hasattr(file, "size") and file.size:
total_size += file.size
else:
return True, 0
return total_size <= MAX_TOTAL_SIZE, total_size
# Create executor instance
executor = CodeExecutor()
async def clone_repo(repo_url: str, workspace: str):
"""Clone a git repository into the workspace."""
try:
process = await asyncio.create_subprocess_exec(
"git",
"clone",
repo_url,
".",
cwd=workspace,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
raise HTTPException(
status_code=400, detail=f"Failed to clone repository: {stderr.decode()}"
)
repo_size = get_directory_size(workspace)
if repo_size > MAX_TOTAL_SIZE:
raise HTTPException(
status_code=400,
detail=f"Repository size ({repo_size / 1024 / 1024:.2f}MB) exceeds limit ({MAX_TOTAL_SIZE / 1024 / 1024:.2f}MB)",
)
except HTTPException:
raise
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Error cloning repository: {str(e)}"
)
def detect_language_from_files(main_files: List[str]) -> str:
"""Detect programming language from file extensions"""
if not main_files:
raise HTTPException(status_code=400, detail="No main files provided")
first_file = main_files[0]
if "." not in first_file:
java_extensions = [".java", ".class"]
for file in main_files:
if any(file.endswith(ext) for ext in java_extensions):
return "java"
raise HTTPException(
status_code=400,
detail=f"Cannot detect language: file '{first_file}' has no extension",
)
extension = first_file.split(".")[-1].lower()
extension_to_language = {
"py": "python",
"java": "java",
"class": "java",
"c": "c",
"cpp": "cpp",
"cc": "cpp",
"cxx": "cpp",
"c++": "cpp",
}
if extension not in extension_to_language:
supported_extensions = ", ".join(extension_to_language.keys())
raise HTTPException(
status_code=400,
detail=f"Unsupported file extension '.{extension}'. Supported extensions: {supported_extensions}",
)
detected_language = extension_to_language[extension]
for file in main_files:
if "." in file:
file_ext = file.split(".")[-1].lower()
file_language = extension_to_language.get(file_ext)
if file_language != detected_language:
raise HTTPException(
status_code=400,
detail=f"Mixed languages detected: '{first_file}' ({detected_language}) and '{file}' ({file_language})",
)
return detected_language
@app.get("/health")
async def health_check():
"""Health check endpoint"""
return {"status": "healthy", "timestamp": asyncio.get_event_loop().time()}
@app.post("/analyze-inputs")
async def analyze_inputs(code_content: str = Form(...), language: str = Form(...)):
"""
Analyze code content to detect input patterns with caching
Simple API that takes code content and language, returns input patterns
Args:
code_content: The source code content to analyze
language: Programming language (python, java, c, cpp)
Returns:
InputAnalysisResult with detected input patterns
"""
try:
# Validate language
supported_languages = ["python", "java", "c", "cpp"]
if language.lower() not in supported_languages:
raise HTTPException(
status_code=400,
detail=f"Unsupported language: {language}. Supported: {supported_languages}",
)
# Create a simple file contents dict for analysis
file_contents_dict = {"main": code_content}
analysis_result = executor.analyze_input_patterns(
language.lower(), file_contents_dict
)
result_dict = analysis_result.model_dump()
logger.info(f"Input analysis completed for {language} code")
return JSONResponse(content=result_dict)
except HTTPException:
raise
except Exception as e:
logger.error(f"Error analyzing inputs: {str(e)}")
raise HTTPException(status_code=500, detail=f"Analysis failed: {str(e)}")
@app.post("/judge")
async def judge_code(
main_files: str = Form(...),
files: List[UploadFile] = File(None),
repo_url: Optional[str] = Form(None),
input_data: Optional[str] = Form(None), # JSON array of input strings
):
"""
Judge code submission with optional input data
- main_files: JSON array of main files to execute
- files: Multiple files maintaining folder structure
- repo_url: Git repository URL (alternative to files)
- input_data: JSON array of input strings for programs that require user input
"""
# Parse main_files
try:
main_files_list = json.loads(main_files)
except json.JSONDecodeError:
raise HTTPException(status_code=400, detail="Invalid main_files format")
# Parse input_data if provided
input_list = None
logger.info(f"Received input_data: {input_data}")
if input_data:
try:
input_list = json.loads(input_data)
if not isinstance(input_list, list):
raise ValueError("Input data must be an array")
except (json.JSONDecodeError, ValueError):
raise HTTPException(
status_code=400, detail="Invalid input_data format - must be JSON array"
)
# Auto-detect language from file extensions
language = detect_language_from_files(main_files_list)
# Validate input: either files or repo_url must be provided
if not files and not repo_url:
raise HTTPException(
status_code=400, detail="Either files or repo_url must be provided"
)
if files and repo_url:
raise HTTPException(
status_code=400, detail="Provide either files or repo_url, not both"
)
# Create temporary workspace
workspace = None
try:
# Create unique temporary directory
workspace = tempfile.mkdtemp(prefix=f"judge_{uuid.uuid4().hex}_")
if repo_url:
# Clone repository
await clone_repo(repo_url, workspace)
else:
# Validate total upload size
total_upload_size = 0
file_contents = []
# Pre-read all files to check total size
for file in files:
content = await file.read()
if len(content) > MAX_FILE_SIZE:
raise HTTPException(
status_code=400,
detail=f"File {file.filename} exceeds individual size limit",
)
total_upload_size += len(content)
file_contents.append((file.filename, content))
# Check total size limit
if total_upload_size > MAX_TOTAL_SIZE:
raise HTTPException(
status_code=400,
detail=f"Total upload size ({total_upload_size / 1024 / 1024:.2f}MB) exceeds limit ({MAX_TOTAL_SIZE / 1024 / 1024:.2f}MB)",
)
# Save uploaded files maintaining structure
for filename, content in file_contents:
# Create file path
file_path = os.path.join(workspace, filename)
# Create directories if needed
os.makedirs(os.path.dirname(file_path), exist_ok=True)
# Write file
with open(file_path, "wb") as f:
f.write(content)
# Execute code with input data
result = await executor.execute_code(
language, main_files_list, workspace, input_list
)
logger.info(f"Execution result: {result}")
return JSONResponse(content=result.model_dump())
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
finally:
# Clean up temporary files
if workspace and os.path.exists(workspace):
try:
shutil.rmtree(workspace)
except Exception as e:
print(f"Error cleaning up workspace: {e}")
@app.get("/languages")
async def get_supported_languages():
"""Get supported programming languages with auto-detection info"""
return {
"languages": [
{"id": "python", "name": "Python 3", "extensions": [".py"]},
{"id": "java", "name": "Java", "extensions": [".java", ".class"]},
{"id": "c", "name": "C", "extensions": [".c"]},
{"id": "cpp", "name": "C++", "extensions": [".cpp", ".cc", ".cxx", ".c++"]},
],
"note": "Language is automatically detected from file extensions. For Java, both source (.java) and compiled (.class) files are supported.",
"input_support": "All languages support automatic input detection and handling for interactive programs.",
}
# Example usage endpoints for testing
@app.get("/examples/input-patterns")
async def get_input_pattern_examples():
"""Get examples of supported input patterns for each language"""
return {
"python": [
'name = input("Enter your name: ")',
'age = int(input("Enter your age: "))',
'score = float(input("Enter score: "))',
"input() # Simple input without assignment",
],
"java": [
"String name = scanner.nextLine();",
"int age = scanner.nextInt();",
"double score = scanner.nextDouble();",
"scanner.next(); # Direct call",
],
"c": ['scanf("%s", name);', 'scanf("%d", &age);', 'scanf("%f", &score);'],
"cpp": ["cin >> name;", "cin >> age;", "getline(cin, fullName);"],
}
@app.post("/test-input-analysis")
async def test_input_analysis():
"""Test endpoint with sample code for input analysis"""
# Sample Python code with inputs
sample_code = {
"main.py": """
name = input("Enter your name: ")
age = int(input("Enter your age: "))
score = float(input("Enter your score: "))
print(f"Hello {name}")
print(f"You are {age} years old")
print(f"Your score is {score}")
# Simple input without assignment
input("Press enter to continue...")
"""
}
# Test the analysis
analysis_result = executor.analyze_input_patterns("python", sample_code)
return {
"sample_code": sample_code,
"analysis": analysis_result.model_dump(),
"suggested_inputs": [
"John Doe", # for name
"25", # for age
"95.5", # for score
"", # for press enter
],
}
if __name__ == "__main__":
import uvicorn
uvicorn.run("app:app", host="0.0.0.0", port=8000, reload=True) |