File size: 6,208 Bytes
8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 7b0e996 8544718 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 | # 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)}
|