Spaces:
Sleeping
Sleeping
Create main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import threading
|
| 2 |
+
import uvicorn
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import pickle
|
| 5 |
+
from fastapi import FastAPI
|
| 6 |
+
|
| 7 |
+
# Initialize FastAPI app
|
| 8 |
+
app = FastAPI()
|
| 9 |
+
|
| 10 |
+
# Load the saved model
|
| 11 |
+
def load_model():
|
| 12 |
+
try:
|
| 13 |
+
with open('model.pkl', 'rb') as file:
|
| 14 |
+
model = pickle.load(file)
|
| 15 |
+
return model
|
| 16 |
+
except Exception as e:
|
| 17 |
+
raise RuntimeError(f"Error loading model: {e}")
|
| 18 |
+
|
| 19 |
+
model = load_model()
|
| 20 |
+
|
| 21 |
+
# Define the FastAPI endpoint
|
| 22 |
+
@app.post("/predict")
|
| 23 |
+
async def predict_transaction(data: dict):
|
| 24 |
+
try:
|
| 25 |
+
# Convert the input data to a DataFrame
|
| 26 |
+
transaction_data = pd.DataFrame([data])
|
| 27 |
+
prediction = model.predict(transaction_data)
|
| 28 |
+
|
| 29 |
+
result = "Fraudulent transaction" if prediction[0] == 1 else "Acceptable transaction"
|
| 30 |
+
return {"prediction": result}
|
| 31 |
+
except Exception as e:
|
| 32 |
+
return {"error": str(e)}
|
| 33 |
+
|
| 34 |
+
# Function to run the FastAPI server
|
| 35 |
+
def run_fastapi():
|
| 36 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|
| 37 |
+
|
| 38 |
+
# Start the FastAPI server in a separate thread
|
| 39 |
+
thread = threading.Thread(target=run_fastapi, daemon=True)
|
| 40 |
+
thread.start()
|
| 41 |
+
|