Spaces:
Sleeping
Sleeping
| from fastapi import FastAPI, Request | |
| from fastapi.responses import FileResponse | |
| from fastapi.middleware.cors import CORSMiddleware | |
| import subprocess, tempfile, os | |
| app = FastAPI() | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| def serve_frontend(): | |
| return FileResponse("index.html") | |
| async def run_java(request: Request): | |
| data = await request.json() | |
| code = data.get("code", "") | |
| filename = data.get("filename", "Main.java") | |
| if not code.strip(): | |
| return {"output": "❌ No code provided."} | |
| with tempfile.TemporaryDirectory() as tmpdir: | |
| filepath = os.path.join(tmpdir, filename) | |
| with open(filepath, "w") as f: | |
| f.write(code) | |
| compile_proc = subprocess.run( | |
| ["javac", filepath], | |
| capture_output=True, | |
| text=True | |
| ) | |
| if compile_proc.returncode != 0: | |
| return {"output": "Compilation Error:\n" + compile_proc.stderr} | |
| classname = filename.replace(".java", "") | |
| run_proc = subprocess.run( | |
| ["java", "-cp", tmpdir, classname], | |
| capture_output=True, | |
| text=True, | |
| timeout=5 | |
| ) | |
| return {"output": run_proc.stdout or run_proc.stderr} |