Spaces:
Sleeping
Sleeping
Oscar Wang commited on
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364from flask import Flask, request, jsonifyimport osimport subprocessimport tempfileimport jsonimport multiprocessingapp = Flask(__name__)# Dictionary to store donated CPU informationdonated_cpus = {}total_donated_cpus = 0@app.route('/donate_cpu', methods=['POST'])def donate_cpu():global total_donated_cpusdata = request.get_json()host = data['host']cpu_count = data['cpu_count']donated_cpus[host] = {"cpu_count": cpu_count, "usage": 0.0}total_donated_cpus += cpu_countreturn jsonify({"status": "success", "message": f"CPU donated by {host}"})@app.route('/update_cpu_usage', methods=['POST'])def update_cpu_usage():data = request.get_json()host = data['host']usage = data['usage']if host in donated_cpus:donated_cpus[host]['usage'] = usagereturn jsonify({"status": "success", "message": f"Updated CPU usage for {host}: {usage}%"})return jsonify({"status": "error", "message": "Host not found"}), 404@app.route('/execute_script', methods=['POST'])def execute_script():try:data = request.get_json()script_content = data['script_content']# Save the script to a temporary filescript_file = tempfile.NamedTemporaryFile(delete=False, suffix='.py')script_file.write(script_content.encode())script_file.close()# Run the script using the donated CPUscpu_count = total_donated_cpus or 1 # Default to 1 if no CPUs are donatedresult = subprocess.run(['python', script_file.name], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=60)os.remove(script_file.name)return jsonify({"stdout": result.stdout,"stderr": result.stderr,"returncode": result.returncode})except Exception as e:return jsonify({"error": str(e)}), 500@app.route('/cpu_info', methods=['GET'])def cpu_info():info = [{"host": host, "cpu_count": data['cpu_count'], "usage": data['usage']} for host, data in donated_cpus.items()]return jsonify({"cpu_info": info})if __name__ == "__main__":app.run(host='0.0.0.0', port=7860)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167import osimport tempfileimport shutilfrom zipfile import ZipFileimport loggingimport psutilimport subprocessfrom flask import Flask, request, jsonify, render_template, send_fileimport multiprocessing# Configure logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)# Initialize Flask appapp = Flask(__name__)connected_cpus = {"localhost": {"cpu_count": psutil.cpu_count(logical=False), "usage": 0.0}}# Define the target function for multiprocessingdef target_function(script_path, folder_path):output_log = tempfile.TemporaryFile(mode='w+t')try:result = subprocess.run(['python', script_path], cwd=folder_path, stdout=output_log, stderr=subprocess.STDOUT)output_log.seek(0)log_output = output_log.read()except Exception as e:log_output = str(e)finally:output_log.close()return log_output# Endpoint to handle file uploads and script execution@app.route('/upload', methods=['POST'])def handle_upload():try:if 'file' not in request.files or 'script_content' not in request.form:return jsonify({"status": "error", "message": "File or script content not provided"}), 400files = request.files.getlist('file')script_content = request.form['script_content']# Create a temporary directory to store uploaded filestemp_dir = tempfile.mkdtemp()# Save the uploaded files to the temporary directoryfolder_path = os.path.join(temp_dir, 'uploaded_folder')os.makedirs(folder_path, exist_ok=True)for file_obj in files:file_path = os.path.join(folder_path, file_obj.filename)file_obj.save(file_path)# Save the script content to a filescript_path = os.path.join(folder_path, 'user_script.py')with open(script_path, 'w') as script_file:script_file.write(script_content)# Run the script using multiprocessinglog_output = run_script(script_path, folder_path)# Create a zip file of the entire folderzip_path = os.path.join(temp_dir, 'output_folder.zip')with ZipFile(zip_path, 'w') as zipf:for root, _, files in os.walk(folder_path):for file in files:zipf.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), folder_path))return jsonify({"status": "success", "log_output": log_output, "download_url": f"/download/{os.path.basename(zip_path)}"})except Exception as e:logger.error(f"Error in handle_upload: {e}")return jsonify({"status": "error", "message": str(e)}), 500@app.route('/download/<filename>')def download_file(filename):try:return send_file(os.path.join(tempfile.gettempdir(), filename), as_attachment=True)except Exception as e:logger.error(f"Error in download_file: {e}")return jsonify({"status": "error", "message": str(e)}), 500# Endpoint to get connected CPUs information@app.route('/cpu_info', methods=['GET'])def get_cpu_info():try:info = []for host, data in connected_cpus.items():info.append(f"{host}: {data['cpu_count']} CPUs, {data['usage']}% usage")return jsonify({"status": "success", "cpu_info": "\n".join(info)})except Exception as e:logger.error(f"Error in get_cpu_info: {e}")return jsonify({"status": "error", "message": str(e)}), 500# Endpoint to execute commands@app.route('/execute_command', methods=['POST'])def execute_command():try:command = request.form['command']if not command:return jsonify({"status": "error", "message": "No command provided"}), 400# Ensure commands are executed in a safe environmentallowed_commands = ['pip install']if not any(command.startswith(cmd) for cmd in allowed_commands):return jsonify({"status": "error", "message": "Command not allowed"}), 400output_log = tempfile.TemporaryFile(mode='w+t')try:result = subprocess.run(command.split(), stdout=output_log, stderr=subprocess.STDOUT)output_log.seek(0)log_output = output_log.read()except Exception as e:log_output = str(e)finally:output_log.close()return jsonify({"status": "success", "log_output": log_output})except Exception as e:logger.error(f"Error in execute_command: {e}")return jsonify({"status": "error", "message": str(e)}), 500# Endpoint to donate CPU resources@app.route('/donate_cpu', methods=['POST'])def donate_cpu():try:data = request.jsonhost = data['host']cpu_count = data['cpu_count']connected_cpus[host] = {"cpu_count": cpu_count, "usage": 0.0}return jsonify({"status": "success", "message": f"CPU resources from {host} donated successfully."})except Exception as e:logger.error(f"Error in donate_cpu: {e}")return jsonify({"status": "error", "message": str(e)}), 500# Endpoint to update CPU usage@app.route('/update_cpu_usage', methods=['POST'])def update_cpu_usage():try:data = request.jsonhost = data['host']usage = data['usage']if host in connected_cpus:connected_cpus[host]['usage'] = usagereturn jsonify({"status": "success", "message": f"CPU usage from {host} updated successfully."})else:return jsonify({"status": "error", "message": f"Host {host} not found."}), 404except Exception as e:logger.error(f"Error in update_cpu_usage: {e}")return jsonify({"status": "error", "message": str(e)}), 500# Main interface@app.route('/')def index():return render_template('index.html')def run_script(script_path, folder_path):# Collect all available CPUs including the local host CPUtotal_cpus = sum(cpu['cpu_count'] for cpu in connected_cpus.values()) + 1# Use multiprocessing to run the scriptwith multiprocessing.Pool(total_cpus) as pool:log_outputs = pool.starmap(target_function, [(script_path, folder_path)] * total_cpus)return '\n'.join(log_outputs)if __name__ == "__main__":app.run(host='0.0.0.0', port=7860, threaded=True)
app.py+150-47