java-compiler / app.py
blogsupport's picture
Initial upload via HfApi
3e445a5 verified
Raw
History Blame Contribute Delete
2.18 kB
import os
import subprocess
import re # NEW: Import the 're' module for regular expressions
from flask import Flask, request, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route('/')
def home():
return jsonify({
"status": "ok",
"message": "Java compiler backend is running. Send POST requests to /api/run-java"
})
@app.route('/api/run-java', methods=['POST'])
def run_java():
code = request.json.get('code', '')
user_input = request.json.get('input', '')
if not code:
return jsonify({'error': 'No code provided.'}), 400
# --- MODIFIED LOGIC: Find the public class name ---
class_name = "Main" # Default class name
# Regex to find "public class TheClassName"
match = re.search(r'public\s+class\s+([a-zA-Z0-9_]+)', code)
if match:
class_name = match.group(1)
file_path = f"{class_name}.java"
# --- END OF MODIFIED LOGIC ---
with open(file_path, "w") as f:
f.write(code)
try:
compile_process = subprocess.run(
['javac', file_path],
capture_output=True, text=True, timeout=10
)
if compile_process.returncode != 0:
return jsonify({'compileErrors': compile_process.stderr})
except Exception as e:
return jsonify({'error': f"An unexpected error occurred during compilation: {str(e)}"})
finally:
# We need to clean up the .java file even if compilation fails
if os.path.exists(file_path):
os.remove(file_path)
try:
run_process = subprocess.run(
['java', class_name],
input=user_input,
capture_output=True, text=True, timeout=15
)
if run_process.returncode != 0:
return jsonify({'runErrors': run_process.stderr})
else:
return jsonify({'output': run_process.stdout})
finally:
# The .java file is already removed above. Now remove the .class file.
class_file = f"{class_name}.class"
if os.path.exists(class_file):
os.remove(class_file)
if __name__ == '__main__':
app.run(host="0.0.0.0", port=7860)