scam-shield-logistic-regression / prediction_api.py
Ibrahim2017's picture
Add tested Flask prediction API for Admin Website integration
d8501d5 verified
Raw History Blame Contribute Delete
2.08 kB
# Scam Shield - Hugging Face Prediction API
from flask import Flask, request, jsonify
from huggingface_hub import hf_hub_download
from feature_extraction import extract_features
from pathlib import Path
from tempfile import TemporaryDirectory
import joblib
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 15 * 1024 * 1024
# Download the trained model from Hugging Face
REPO_ID = "Ibrahim2017/scam-shield-logistic-regression"
print("Downloading model from Hugging Face...")
model_path = hf_hub_download(
repo_id=REPO_ID,
filename="logistic_regression.joblib"
)
# Load our own trusted trained model
model = joblib.load(model_path)
print("Scam Shield model loaded successfully!")
@app.route("/health", methods=["GET"])
def health():
return jsonify({
"status": "running",
"model": "Logistic Regression",
"source": "Hugging Face"
})
@app.route("/predict", methods=["POST"])
def predict():
if "file" not in request.files:
return jsonify({"error": "No audio file uploaded"}), 400
audio_file = request.files["file"]
if not audio_file.filename.lower().endswith(".wav"):
return jsonify({"error": "Please upload a WAV file"}), 400
try:
# Save audio temporarily
with TemporaryDirectory() as folder:
audio_path = Path(folder) / "recording.wav"
audio_file.save(audio_path)
# Extract the same 26 features used in training
features = extract_features(audio_path)
# Predict voice category
prediction = int(model.predict(features)[0])
result = "AI-GENERATED" if prediction == 1 else "HUMAN"
return jsonify({
"prediction": result,
"encoded_label": prediction,
"model": "Logistic Regression",
"feature_count": 26
})
except Exception as error:
print("Prediction failed:", error)
return jsonify({"error": "Audio processing failed"}), 500
if __name__ == "__main__":
app.run(host="127.0.0.1", port=8080, debug=False)