Spaces:
Sleeping
Sleeping
Download app.py from AfanR/Neuro-Track: direct link, hf CLI and curl.
- Browser
- Download file 9.66 kB
-
https://huggingface.co/spaces/AfanR/Neuro-Track/resolve/main/app.py
- Command line
-
hf download hf://spaces/AfanR/Neuro-Track/app.py
-
curl -L -o app.py https://huggingface.co/spaces/AfanR/Neuro-Track/resolve/main/app.py
9.66 kB
| """ | |
| NeuroTrack - Flask Application for Hugging Face Spaces | |
| Serves static frontend and provides logging/telemetry endpoint. | |
| IMPORTANT: Hugging Face Spaces filesystem is EPHEMERAL. | |
| Logs stored locally will be lost on container restart. | |
| For persistent logging, use external services (Supabase, S3, etc.) | |
| """ | |
| from flask import Flask, request, send_from_directory, jsonify, redirect | |
| import os | |
| import datetime | |
| import json | |
| import hashlib | |
| # Initialize Flask app | |
| app = Flask(__name__, static_folder="assets", static_url_path="/assets") | |
| # Configuration | |
| LOG_DIR = "logs" | |
| DATA_DIR = "data" | |
| PAGES_DIR = "pages" | |
| os.makedirs(LOG_DIR, exist_ok=True) | |
| LOG_FILE = os.path.join(LOG_DIR, "events.log") | |
| # ============================================================ | |
| # STATIC FILE SERVING | |
| # ============================================================ | |
| def index(): | |
| """Serve the main login page""" | |
| return send_from_directory(PAGES_DIR, "login.html") | |
| def serve_page(filename): | |
| """Serve HTML pages from the pages directory""" | |
| return send_from_directory(PAGES_DIR, filename) | |
| def serve_data(filename): | |
| """Serve JSON data files""" | |
| return send_from_directory(DATA_DIR, filename) | |
| def serve_assets(filename): | |
| """Serve static assets (CSS, JS, images)""" | |
| return send_from_directory("assets", filename) | |
| # ============================================================ | |
| # AUTHENTICATION API | |
| # ============================================================ | |
| def load_users(): | |
| """Load users from JSON file""" | |
| users_file = os.path.join(DATA_DIR, "users.json") | |
| try: | |
| with open(users_file, "r", encoding="utf-8") as f: | |
| data = json.load(f) | |
| return data.get("users", []) | |
| except Exception as e: | |
| print(f"Error loading users: {e}") | |
| return [] | |
| def verify_password(stored_hash, password): | |
| """ | |
| Verify password against stored hash. | |
| In production, use bcrypt. For Spaces demo, using simple comparison. | |
| """ | |
| # For demo purposes - in production use proper bcrypt verification | |
| try: | |
| import bcrypt | |
| return bcrypt.checkpw(password.encode('utf-8'), stored_hash.encode('utf-8')) | |
| except ImportError: | |
| # Fallback for demo - compare plain text (NOT for production!) | |
| print("WARNING: bcrypt not available, using demo mode") | |
| # Demo credentials | |
| demo_users = { | |
| "dokter": "dokter123", | |
| "pasien": "pasien123", | |
| "psikioterapi": "psiko123", | |
| "physio": "physio123" | |
| } | |
| return demo_users.get(password.split(":")[0]) == password.split(":")[-1] if ":" in password else False | |
| def login(): | |
| """Handle user login""" | |
| data = request.get_json(silent=True) or {} | |
| username = data.get("username", "").strip() | |
| password = data.get("password", "").strip() | |
| role = data.get("role", "").strip() | |
| if not username or not password: | |
| return jsonify({"success": False, "error": "Username and password required"}), 400 | |
| users = load_users() | |
| for user in users: | |
| if user.get("username") == username and user.get("role") == role: | |
| # Verify password | |
| stored_hash = user.get("passwordHash", "") | |
| try: | |
| import bcrypt | |
| if bcrypt.checkpw(password.encode('utf-8'), stored_hash.encode('utf-8')): | |
| # Login successful | |
| log_event_internal("login", {"username": username, "role": role}) | |
| return jsonify({ | |
| "success": True, | |
| "user": { | |
| "id": user.get("id"), | |
| "username": user.get("username"), | |
| "role": user.get("role"), | |
| "profile": user.get("profile", {}) | |
| } | |
| }) | |
| except Exception as e: | |
| print(f"Password verification error: {e}") | |
| # Fallback demo mode | |
| demo_creds = { | |
| ("dokter", "doctor"): "dokter123", | |
| ("pasien", "patient"): "pasien123", | |
| ("psikioterapi", "psychotherapist"): "psiko123", | |
| ("physio", "physio"): "physio123" | |
| } | |
| if demo_creds.get((username, role)) == password: | |
| log_event_internal("login", {"username": username, "role": role}) | |
| return jsonify({ | |
| "success": True, | |
| "user": { | |
| "id": user.get("id"), | |
| "username": user.get("username"), | |
| "role": user.get("role"), | |
| "profile": user.get("profile", {}) | |
| } | |
| }) | |
| return jsonify({"success": False, "error": "Invalid credentials"}), 401 | |
| def register(): | |
| """Handle user registration""" | |
| data = request.get_json(silent=True) or {} | |
| email = data.get("email", "").strip() | |
| password = data.get("password", "").strip() | |
| role = data.get("role", "").strip() | |
| profile = data.get("profile", {}) | |
| # Validate required fields | |
| if not email or not password or not role: | |
| return jsonify({"success": False, "message": "Email, password, and role are required"}), 400 | |
| # Validate role | |
| valid_roles = ["patient", "doctor", "physio", "psychotherapist"] | |
| if role not in valid_roles: | |
| return jsonify({"success": False, "message": f"Invalid role. Must be one of: {', '.join(valid_roles)}"}), 400 | |
| # Check if user already exists | |
| users = load_users() | |
| for user in users: | |
| if user.get("email") == email: | |
| return jsonify({"success": False, "message": "Email already registered"}), 409 | |
| # For demo purposes, registration is acknowledged but not persisted | |
| # In production, this would save to a database | |
| log_event_internal("register_attempt", {"email": email, "role": role}) | |
| return jsonify({ | |
| "success": True, | |
| "message": "Registration successful. Please log in with your credentials.", | |
| "note": "Demo mode: User data is not persisted on Hugging Face Spaces" | |
| }) | |
| # ============================================================ | |
| # LOGGING/TELEMETRY API | |
| # ============================================================ | |
| def log_event_internal(event_type, data): | |
| """Internal logging function""" | |
| entry = { | |
| "ts": datetime.datetime.utcnow().isoformat() + "Z", | |
| "type": event_type, | |
| "data": data | |
| } | |
| try: | |
| with open(LOG_FILE, "a", encoding="utf-8") as f: | |
| f.write(json.dumps(entry, ensure_ascii=False) + "\n") | |
| except Exception as e: | |
| print(f"Logging error: {e}") | |
| def log_event(): | |
| """ | |
| Accept telemetry/logging data via POST. | |
| WARNING: Hugging Face Spaces filesystem is EPHEMERAL. | |
| Logs will be lost on container restart. | |
| For persistent logging, integrate with external services. | |
| """ | |
| payload = request.get_json(silent=True) or {} | |
| entry = { | |
| "ts": datetime.datetime.utcnow().isoformat() + "Z", | |
| "ip": request.remote_addr, | |
| "user_agent": request.headers.get("User-Agent", "unknown"), | |
| "data": payload | |
| } | |
| # Append newline-delimited JSON to log file | |
| try: | |
| with open(LOG_FILE, "a", encoding="utf-8") as f: | |
| f.write(json.dumps(entry, ensure_ascii=False) + "\n") | |
| return jsonify({"status": "ok", "warning": "Logs are ephemeral on Spaces"}), 200 | |
| except Exception as e: | |
| return jsonify({"status": "error", "message": str(e)}), 500 | |
| def get_logs(): | |
| """Retrieve recent logs (for debugging)""" | |
| try: | |
| if os.path.exists(LOG_FILE): | |
| with open(LOG_FILE, "r", encoding="utf-8") as f: | |
| lines = f.readlines()[-100:] # Last 100 entries | |
| logs = [json.loads(line) for line in lines if line.strip()] | |
| return jsonify({"logs": logs}) | |
| return jsonify({"logs": []}) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| # ============================================================ | |
| # HEALTH CHECK | |
| # ============================================================ | |
| def health(): | |
| """Health check endpoint for monitoring""" | |
| return jsonify({ | |
| "status": "healthy", | |
| "timestamp": datetime.datetime.utcnow().isoformat() + "Z", | |
| "service": "NeuroTrack" | |
| }) | |
| # ============================================================ | |
| # ERROR HANDLERS | |
| # ============================================================ | |
| def not_found(e): | |
| """Handle 404 errors""" | |
| return jsonify({"error": "Not found"}), 404 | |
| def server_error(e): | |
| """Handle 500 errors""" | |
| return jsonify({"error": "Internal server error"}), 500 | |
| # ============================================================ | |
| # MAIN ENTRY POINT | |
| # ============================================================ | |
| if __name__ == "__main__": | |
| # Local development mode | |
| # In production (Spaces), gunicorn is used via Dockerfile CMD | |
| print("Starting NeuroTrack in development mode...") | |
| print("Open http://localhost:7860 to view the application") | |
| app.run(host="0.0.0.0", port=7860, debug=True) | |