Download backend_core.py from lifefake/Fruad: direct link, hf CLI and curl.
- Browser
- Download file 6.21 kB
-
https://huggingface.co/spaces/lifefake/Fruad/resolve/main/backend_core.py
- Command line
-
hf download hf://spaces/lifefake/Fruad/backend_core.py
-
curl -L -o backend_core.py https://huggingface.co/spaces/lifefake/Fruad/resolve/main/backend_core.py
6.21 kB
| # backend_core.py | |
| # Clean backend logic for Hugging Face. NO Flask. Importable from Gradio app.py. | |
| import os | |
| import pandas as pd | |
| from datetime import datetime | |
| from ml_models import FraudDetectionModel | |
| from data_processor import DataProcessor | |
| # Folders | |
| UPLOAD_FOLDER = "uploads" | |
| MODELS_FOLDER = "models" | |
| ALLOWED_EXTENSIONS = {"csv"} | |
| os.makedirs(UPLOAD_FOLDER, exist_ok=True) | |
| os.makedirs(MODELS_FOLDER, exist_ok=True) | |
| # Instantiate backend classes | |
| try: | |
| fraud_model = FraudDetectionModel() | |
| except Exception as e: | |
| print("Error loading FraudDetectionModel:", e) | |
| fraud_model = None | |
| try: | |
| 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_input | |
| except Exception as e: | |
| return {"error": f"Processor error: {e}"} | |
| else: | |
| data = text_input | |
| # Try model prediction | |
| if fraud_model is None: | |
| return {"error": "Model not available"} | |
| try: | |
| # common model APIs | |
| if hasattr(fraud_model, "predict"): | |
| raw = fraud_model.predict([data]) | |
| pred = raw[0] if isinstance(raw, (list, tuple)) else raw | |
| return {"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"] = filepath | |
| return 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 results | |
| timestamp = 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_FOLDER | |
| fraud_model.load(path) | |
| return {"success": True, "message": f"Loaded {path}"} | |
| except Exception as e: | |
| return {"success": False, "error": str(e)} | |