Update backend_core.py
Browse files123456789101112131 unmodified line15161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258import osimport pandas as pdimport jsonfrom datetime import datetime# Import your backend classes (these files must be uploaded)from ml_models import FraudDetectionModelfrom data_processor import DataProcessor# ConfigurationUPLOAD_FOLDER = "uploads"MODELS_FOLDER = "models"ALLOWED_EXTENSIONS = {"csv"}1 unmodified lineos.makedirs(UPLOAD_FOLDER, exist_ok=True)os.makedirs(MODELS_FOLDER, exist_ok=True)# Instantiate global objects (adjust constructors if needed)try:fraud_model = FraudDetectionModel()except Exception:# If your model class requires a path parameter, you can try to pass it:try:fraud_model = FraudDetectionModel(model_path=os.path.join(MODELS_FOLDER))except Exception as e:# Fallback: set to None and handle gracefullyfraud_model = Noneprint("Warning: Could not instantiate FraudDetectionModel:", e)try:processor = DataProcessor()except Exception:processor = Noneprint("Warning: Could not instantiate DataProcessor")# Utilitiesdef _sanitize_filename(filename: str) -> str:"""Simple filename sanitizer: keep basename, replace spaces."""name = os.path.basename(filename or "uploaded.csv")return name.replace(" ", "_")def allowed_file(filename: str) -> bool:return "." in (filename or "") and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS# API-like functions (return JSON-serializable dicts)def health():return {"status": "healthy", "timestamp": datetime.now().isoformat()}def get_sample_data(n=1000):"""Generate sample data using processor.generate_sample_data if available."""if processor is None:return {"success": False, "error": "Processor not available"}try:df = processor.generate_sample_data(n)filepath = os.path.join(UPLOAD_FOLDER, f"sample_data_{int(datetime.now().timestamp())}.csv")df.to_csv(filepath, index=False)# Create serializable sample (first 5 rows)sample_df = df.head(5).copy()for col in sample_df.columns:if pd.api.types.is_datetime64_any_dtype(sample_df[col]):sample_df[col] = sample_df[col].astype(str)elif sample_df[col].dtype == "object":try:sample_df[col] = sample_df[col].astype(str)except Exception:passreturn {"success": True,"message": "Sample data generated","rows": len(df),"columns": list(df.columns),"sample": sample_df.to_dict(orient="records"),"filepath": filepath}except Exception as e:return {"success": False, "error": str(e)}def validate_csv_bytes(file_bytes: bytes, filename: str = "uploaded.csv"):"""Validate CSV content bytes (as uploaded). Returns validation result and saves file if valid.file_bytes: raw bytes of the uploaded file"""if processor is None:return {"success": False, "error": "Processor not available"}if not allowed_file(filename):return {"success": False, "error": "Only CSV files allowed"}if not file_bytes or len(file_bytes) == 0:return {"success": False, "error": "File is empty"}try:decoded = file_bytes.decode("utf-8")except UnicodeDecodeError:return {"success": False, "error": "File encoding not supported. Please use UTF-8 CSV."}try:validation_result = processor.validate_csv(decoded)except Exception as e:return {"success": False, "error": f"Validation failed: {e}"}if validation_result.get("success"):safe_name = _sanitize_filename(filename)filepath = os.path.join(UPLOAD_FOLDER, safe_name)try:with open(filepath, "w", encoding="utf-8") as f:f.write(decoded)validation_result["filepath"] = filepathexcept Exception as e:validation_result = {"success": False, "error": f"Failed to save file: {e}"}return validation_resultdef train_model(filepath: str, fraud_column: str = "is_fraud"):"""Train model using CSV at filepath. Returns stats and saves model to models folder."""if fraud_model is None:return {"success": False, "error": "Model not available"}if not filepath or not os.path.exists(filepath):return {"success": False, "error": "Invalid filepath"}try:df = pd.read_csv(filepath)except Exception as e:return {"success": False, "error": f"Failed to read CSV: {e}"}try:stats = fraud_model.train(df, fraud_column)except Exception as e:return {"success": False, "error": f"Training failed: {e}"}try:fraud_model.save(MODELS_FOLDER)except Exception as e:# Not fatal: model trained but save failedreturn {"success": True, "message": "Model trained but save failed", "stats": stats, "save_error": str(e)}return {"success": True, "message": "Model trained successfully", "stats": stats}def predict_from_filepath(filepath: str):"""Run prediction on CSV file at filepath. Returns statistics, sample results, and saved results filepath."""if fraud_model is None:return {"success": False, "error": "Model not available"}if not filepath or not os.path.exists(filepath):return {"success": False, "error": "Invalid filepath"}try:df = pd.read_csv(filepath)except Exception as e:return {"success": False, "error": f"Failed to read CSV: {e}"}try:results_df = fraud_model.predict(df)except Exception as e:return {"success": False, "error": f"Prediction failed: {e}"}# Ensure required columns exist (same logic as previous)required_cols = ['is_fraud_predicted', 'is_anomaly', 'ensemble_fraud_probability', 'risk_level', 'merchant_category']for col in required_cols:if col not in results_df.columns:if col == 'is_fraud_predicted':results_df[col] = 0elif col == 'is_anomaly':results_df[col] = 0elif col == 'ensemble_fraud_probability':results_df[col] = 0.0elif col == 'risk_level':results_df[col] = 'Low'elif col == 'merchant_category':results_df[col] = 'unknown'# Compute statistics using processor if availabletry:stats = processor.get_statistics(results_df) if processor and hasattr(processor, "get_statistics") else {}except Exception as e:stats = {"stats_error": str(e)}# Make a JSON-serializable sampleresults_for_json = results_df.copy()for col in results_for_json.columns:if results_for_json[col].dtype == "object":try:results_for_json[col] = results_for_json[col].astype(str)except Exception:passtimestamp = datetime.now().strftime("%Y%m%d_%H%M%S")results_filepath = os.path.join(UPLOAD_FOLDER, f"predictions_{timestamp}.csv")try:results_df.to_csv(results_filepath, index=False)except Exception as e:return {"success": False, "error": f"Failed to save results: {e}"}return {"success": True,"statistics": stats,"results": results_for_json.head(100).to_dict(orient="records"),"total_results": len(results_df),"results_file": results_filepath}def download_results_filepath(filename: str):"""Return absolute path to results file if exists (frontend can use to download)."""path = os.path.join(UPLOAD_FOLDER, _sanitize_filename(filename))if not os.path.exists(path):return {"success": False, "error": "File not found"}return {"success": True, "filepath": path}def save_model(name: str):"""Save current model under a named folder inside models/"""if fraud_model is None:return {"success": False, "error": "Model not available"}if not name:return {"success": False, "error": "Model name is required"}try:path = os.path.join(MODELS_FOLDER, _sanitize_filename(name))fraud_model.save(path)return {"success": True, "message": f"Models saved to {path}"}except Exception as e:return {"success": False, "error": str(e)}def model_info():"""Return model metadata if available."""if fraud_model is None:return {"trained": False, "message": "Model not available"}try:feature_names = getattr(fraud_model, "feature_names", None)if feature_names is None:return {"trained": False, "message": "Model not trained yet"}return {"trained": True,"features": feature_names,"num_features": len(feature_names),"model_type": getattr(fraud_model, "model_type", "Unknown")}except Exception as e:return {"success": False, "error": str(e)}def load_model(name: str = None):"""Load model from models/ or named subfolder."""if fraud_model is None:return {"success": False, "error": "Model instance not available to load into"}try:path = os.path.join(MODELS_FOLDER, name) if name else MODELS_FOLDERfraud_model.load(path)return {"success": True,"message": f"Models loaded from {path}","trained": True,"features": getattr(fraud_model, "feature_names", []),"num_features": len(getattr(fraud_model, "feature_names", []) or [])}except Exception as e:return {"success": False, "error": str(e)}123456789101112131 unmodified line15161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219# backend_core.py# Clean backend logic for Hugging Face. NO Flask. Importable from Gradio app.py.import osimport pandas as pdfrom datetime import datetimefrom ml_models import FraudDetectionModelfrom data_processor import DataProcessor# FoldersUPLOAD_FOLDER = "uploads"MODELS_FOLDER = "models"ALLOWED_EXTENSIONS = {"csv"}1 unmodified lineos.makedirs(UPLOAD_FOLDER, exist_ok=True)os.makedirs(MODELS_FOLDER, exist_ok=True)# Instantiate backend classestry:fraud_model = FraudDetectionModel()except Exception as e:print("Error loading FraudDetectionModel:", e)fraud_model = Nonetry:processor = DataProcessor()except Exception as e:print("Error loading DataProcessor:", e)processor = None# -------------------------# Utility Helpers# -------------------------def _sanitize_filename(filename: str) -> str:return os.path.basename(filename).replace(" ", "_")def allowed_file(filename: str) -> bool:return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS# -------------------------# 1) PREDICT FROM TEXT# -------------------------def predict_from_text(text_input):"""Main function Gradio frontend uses.Returns {"prediction": "..."} or {"error": "..."}"""if processor:try:if hasattr(processor, "preprocess_text"):data = processor.preprocess_text(text_input)elif hasattr(processor, "process"):data = processor.process(text_input)else:data = text_inputexcept Exception as e:return {"error": f"Processor error: {e}"}else:data = text_input# Try model predictionif fraud_model is None:return {"error": "Model not available"}try:# common model APIsif hasattr(fraud_model, "predict"):raw = fraud_model.predict([data])pred = raw[0] if isinstance(raw, (list, tuple)) else rawreturn {"prediction": str(pred)}elif hasattr(fraud_model, "predict_proba"):raw = fraud_model.predict_proba([data])return {"prediction": str(raw)}else:raw = fraud_model(data)return {"prediction": str(raw)}except Exception as e:return {"error": f"Prediction error: {e}"}# -------------------------# 2) VALIDATE CSV# -------------------------def validate_csv_bytes(file_bytes, filename="uploaded.csv"):if not allowed_file(filename):return {"success": False, "error": "Only CSV files allowed"}try:decoded = file_bytes.decode("utf-8")except Exception:return {"success": False, "error": "File must be UTF-8 CSV"}if processor is None:return {"success": False, "error": "Processor not available"}try:result = processor.validate_csv(decoded)except Exception as e:return {"success": False, "error": f"Validation failed: {e}"}if result.get("success"):filepath = os.path.join(UPLOAD_FOLDER, _sanitize_filename(filename))with open(filepath, "w", encoding="utf-8") as f:f.write(decoded)result["filepath"] = filepathreturn result# -------------------------# 3) TRAIN MODEL# -------------------------def train_model(filepath, fraud_column="is_fraud"):if fraud_model is None:return {"success": False, "error": "Model not available"}if not os.path.exists(filepath):return {"success": False, "error": "File not found"}try:df = pd.read_csv(filepath)except Exception as e:return {"success": False, "error": f"CSV read error: {e}"}try:stats = fraud_model.train(df, fraud_column)except Exception as e:return {"success": False, "error": f"Training error: {e}"}try:fraud_model.save(MODELS_FOLDER)except Exception as e:return {"success": True, "warning": f"Model trained but save failed: {e}", "stats": stats}return {"success": True, "message": "Model trained", "stats": stats}# -------------------------# 4) PREDICT FROM FILE# -------------------------def predict_from_filepath(filepath):if fraud_model is None:return {"success": False, "error": "Model not available"}if not os.path.exists(filepath):return {"success": False, "error": "File not found"}try:df = pd.read_csv(filepath)except Exception as e:return {"success": False, "error": f"CSV read error: {e}"}try:results = fraud_model.predict(df)except Exception as e:return {"success": False, "error": f"Prediction failed: {e}"}# Save resultstimestamp = datetime.now().strftime("%Y%m%d_%H%M%S")results_path = os.path.join(UPLOAD_FOLDER, f"results_{timestamp}.csv")try:results.to_csv(results_path, index=False)except Exception as e:return {"success": False, "error": f"Error saving results: {e}"}return {"success": True,"total": len(results),"preview": results.head(20).to_dict(orient="records"),"filepath": results_path}# -------------------------# 5) MODEL INFO / LOAD / SAVE# -------------------------def model_info():if fraud_model is None:return {"trained": False}try:features = getattr(fraud_model, "feature_names", [])return {"trained": True, "features": features, "num_features": len(features)}except:return {"trained": False}def save_model(name):if not name:return {"success": False, "error": "Name required"}try:path = os.path.join(MODELS_FOLDER, _sanitize_filename(name))fraud_model.save(path)return {"success": True, "message": f"Saved to {path}"}except Exception as e:return {"success": False, "error": str(e)}def load_model(name=None):try:path = os.path.join(MODELS_FOLDER, name) if name else MODELS_FOLDERfraud_model.load(path)return {"success": True, "message": f"Loaded {path}"}except Exception as e:return {"success": False, "error": str(e)}
backend_core.py+125-164