Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108import osimport socketfrom flask import Flask, request, jsonifyfrom flask_cors import CORSimport joblibimport numpy as np# ----------------------------# Flask App Setup# ----------------------------app = Flask(__name__)# Allow frontend domain (adjust for your frontend if needed)CORS(app, resources={r"/*": {"origins": ["https://webrakshak.vercel.app", "http://localhost:3000"]}})# ----------------------------# Model Loading (Optional)# ----------------------------MODEL_PATH = "models/model_compressed.joblib"model = Noneif os.path.exists(MODEL_PATH):model = joblib.load(MODEL_PATH)print("β Local model loaded successfully.")else:print("β οΈ No local model found β will use online updates only.")# ----------------------------# Endpoint: URL Scan# ----------------------------@app.route("/scan/url", methods=["POST"])def scan_url():data = request.get_json()url = data.get("url", "")if not url:return jsonify({"error": "No URL provided"}), 400# Example placeholder predictionscore = np.random.rand()phishing = score > 0.5return jsonify({"url": url,"phishing": bool(phishing),"score": round(float(score), 3)})# ----------------------------# Endpoint: Image Scan# ----------------------------@app.route("/scan/image", methods=["POST"])def scan_image():file = request.files.get("file")if not file:return jsonify({"error": "No image file uploaded"}), 400# Dummy resultscore = np.random.rand()phishing = score > 0.5return jsonify({"filename": file.filename,"phishing": bool(phishing),"score": round(float(score), 3)})# ----------------------------# Endpoint: Feedback / Federated Learning# ----------------------------@app.route("/api/feedback", methods=["POST"])def feedback():data = request.get_json()url = data.get("url", "")label = data.get("label", 0)# Log feedback (simulate federated update)print(f"π§ Feedback received β URL: {url}, Label: {label}")# Here, you could append to CSV or update model weightsreturn jsonify({"message": "Feedback received successfully."})# ----------------------------# Utility: Find Free Port# ----------------------------def find_free_port(default_port=5000):sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)port = default_portwhile True:try:sock.bind(("0.0.0.0", port))sock.close()return portexcept OSError:port += 1# ----------------------------# Run Server# ----------------------------if __name__ == "__main__":port = find_free_port(5000)print("\n======================================")print("π Starting Flask Phish Detection Backend...")print(f"β Backend is running properly at: http://127.0.0.1:{port}")print(f"π Accessible in your network at: http://{socket.gethostbyname(socket.gethostname())}:{port}")print("======================================\n")app.run(host="0.0.0.0", port=port)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576from flask import Flask, request, jsonifyfrom flask_cors import CORSimport requestsimport osapp = Flask(__name__)# Allow only your frontend originsCORS(app, resources={r"/*": {"origins": ["http://localhost:5173","https://webrakshak.vercel.app"]}})# Hugging Face Space backend URLHF_SPACE_URL = "https://huggingface.co/spaces/OnArchit/phish_detection_model"@app.route('/')def home():print("β Backend is running properly!")return jsonify({"message": "Backend is running properly!"})@app.route('/scan', methods=['POST'])def scan_url():"""Forward URL scan requests to the Hugging Face model backend"""try:data = request.get_json()url = data.get("url")if not url:return jsonify({"error": "URL is missing"}), 400print(f"π Scanning URL: {url}")# Forward to Hugging Face backend (server-side call to avoid CORS issues)response = requests.post(f"{HF_SPACE_URL}/scan/url", json={"url": url})try:return jsonify(response.json()), response.status_codeexcept Exception:return jsonify({"error": "Invalid response from HF backend"}), 502except Exception as e:print(f"β Error in /scan: {e}")return jsonify({"error": str(e)}), 500@app.route('/vote', methods=['POST'])def vote_feedback():"""Feedback / Federated Learning data endpoint"""try:data = request.get_json()feedback = {"url": data.get("url"),"label": data.get("label"),"user_feedback": data.get("feedback")}print("π§ Received Feedback/Federated Update:", feedback)# Placeholder for storing or training updates# e.g., save to file, send to database, or federated serverreturn jsonify({"status": "Feedback received successfully","federated_action": "update_queued"}), 200except Exception as e:print(f"β Error in /vote: {e}")return jsonify({"error": str(e)}), 500if __name__ == '__main__':port = int(os.environ.get("PORT", 5000))print(f"π Starting backend on port {port} ...")print("β Backend is running properly and ready for connections!")app.run(host='0.0.0.0', port=port)
app.py+69-101