Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Request
|
| 2 |
+
from fastapi.responses import FileResponse
|
| 3 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
+
import subprocess, tempfile, os
|
| 5 |
+
|
| 6 |
+
app = FastAPI()
|
| 7 |
+
|
| 8 |
+
app.add_middleware(
|
| 9 |
+
CORSMiddleware,
|
| 10 |
+
allow_origins=["*"],
|
| 11 |
+
allow_methods=["*"],
|
| 12 |
+
allow_headers=["*"],
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
@app.get("/")
|
| 16 |
+
def serve_frontend():
|
| 17 |
+
return FileResponse("index.html")
|
| 18 |
+
|
| 19 |
+
@app.post("/run-java")
|
| 20 |
+
async def run_java(request: Request):
|
| 21 |
+
data = await request.json()
|
| 22 |
+
code = data.get("code", "")
|
| 23 |
+
filename = data.get("filename", "Main.java")
|
| 24 |
+
|
| 25 |
+
if not code.strip():
|
| 26 |
+
return {"output": "❌ No code provided."}
|
| 27 |
+
|
| 28 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 29 |
+
filepath = os.path.join(tmpdir, filename)
|
| 30 |
+
with open(filepath, "w") as f:
|
| 31 |
+
f.write(code)
|
| 32 |
+
|
| 33 |
+
compile_proc = subprocess.run(
|
| 34 |
+
["javac", filepath],
|
| 35 |
+
capture_output=True,
|
| 36 |
+
text=True
|
| 37 |
+
)
|
| 38 |
+
if compile_proc.returncode != 0:
|
| 39 |
+
return {"output": "Compilation Error:\n" + compile_proc.stderr}
|
| 40 |
+
|
| 41 |
+
classname = filename.replace(".java", "")
|
| 42 |
+
run_proc = subprocess.run(
|
| 43 |
+
["java", "-cp", tmpdir, classname],
|
| 44 |
+
capture_output=True,
|
| 45 |
+
text=True,
|
| 46 |
+
timeout=5
|
| 47 |
+
)
|
| 48 |
+
return {"output": run_proc.stdout or run_proc.stderr}
|