Arafath10 commited on
Commit
f4e3196
·
verified ·
1 Parent(s): 5eb4a0e

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +52 -56
main.py CHANGED
@@ -1,22 +1,12 @@
1
- from fastapi import FastAPI, HTTPException
 
2
  from fastapi.middleware.cors import CORSMiddleware
3
- from pydantic import BaseModel
4
  import pandas as pd
5
- import numpy as np
6
- import joblib
7
 
8
-
9
- # Load your trained model and encoders
10
- xgb_model = joblib.load("model/xgb_model.joblib")
11
- encoders = joblib.load("model/encoders.joblib")
12
-
13
- # Function to handle unseen labels during encoding
14
- def safe_transform(encoder, column):
15
- classes = encoder.classes_
16
- return [encoder.transform([x])[0] if x in classes else -1 for x in column]
17
-
18
- # Define FastAPI app
19
  app = FastAPI()
 
20
  app.add_middleware(
21
  CORSMiddleware,
22
  allow_origins=["*"],
@@ -25,46 +15,52 @@ app.add_middleware(
25
  allow_headers=["*"],
26
  )
27
 
28
- # Endpoint for making predictions
29
- @app.post("/predict")
30
- def predict(customer_name: str,
31
- customer_address: str,
32
- customer_phone: str,
33
- customer_email: str,
34
- cod:str,
35
- weight: str,
36
- pickup_address: str,
37
- origin_city_name: str,
38
- destination_city_name: str,
39
- origin_country: str):
40
- # Convert input data to DataFrame
41
- input_data = {
42
- 'customer_name': customer_name,
43
- 'customer_address': customer_address,
44
- 'customer_phone': customer_phone,
45
- 'customer_email': customer_email,
46
- 'cod': float(cod),
47
- 'weight': float(weight),
48
- 'pickup_address':pickup_address,
49
- 'origin_city.name':origin_city_name,
50
- 'destination_city.name':destination_city_name
51
- }
52
- input_df = pd.DataFrame([input_data])
53
-
54
- # Encode categorical variables using the same encoders used during training
55
- for col in input_df.columns:
56
- if col in encoders:
57
- input_df[col] = safe_transform(encoders[col], input_df[col])
58
-
59
- # Predict and obtain probabilities
60
- pred = xgb_model.predict(input_df)
61
- pred_proba = xgb_model.predict_proba(input_df)
62
-
63
- # Output
64
- predicted_status = "Unknown" if pred[0] == -1 else encoders['status.name'].inverse_transform([pred])[0]
65
- probability = pred_proba[0][pred[0]] * 100 if pred[0] != -1 else "Unknown"
 
66
 
67
- if predicted_status == "RETURN TO CLIENT":
68
- probability = 100 - probability
 
 
 
69
 
70
- return {"Probability": round(probability,2)}
 
 
 
1
+ import asyncio
2
+ from fastapi import FastAPI
3
  from fastapi.middleware.cors import CORSMiddleware
4
+ import requests
5
  import pandas as pd
6
+ import json
 
7
 
 
 
 
 
 
 
 
 
 
 
 
8
  app = FastAPI()
9
+
10
  app.add_middleware(
11
  CORSMiddleware,
12
  allow_origins=["*"],
 
15
  allow_headers=["*"],
16
  )
17
 
18
+ global page
19
+ page = 1
20
+ # Declare the continuous function as an async function.
21
+ async def your_continuous_function():
22
+ import pandas as pd
23
+ import requests
24
+ import json
25
+ global page
26
+ while True:
27
+ print("data fetcher running.....")
28
+
29
+ # Initialize an empty DataFrame to store the combined data
30
+ combined_df = pd.DataFrame()
31
+
32
+ # Update the payload for each page
33
+ url = "https://dev3.api.curfox.parallaxtec.com/api/ml/order-list?sort=id&paginate=500&page="+str(page)
34
+
35
+ payload = {}
36
+ headers = {
37
+ 'Accept': 'application/json',
38
+ 'X-Tenant': 'royalexpress'
39
+ }
40
+
41
+ response = requests.request("GET", url, headers=headers, data=payload)
42
+
43
+ # Sample JSON response
44
+ json_response = response.json()
45
+ # Extracting 'data' for conversion
46
+ data = json_response['data']
47
+
48
+ df = pd.json_normalize(data)
49
+
50
+ # Concatenate the current page's DataFrame with the combined DataFrame
51
+ combined_df = pd.concat([combined_df, df], ignore_index=True)
52
+
53
+ data = combined_df[combined_df['status.name'].isin(['RETURN TO CLIENT', 'DELIVERED'])]
54
+ print("data collected from page : "+str(page))
55
+ page+=1
56
+ await asyncio.sleep(60) # Adjust the sleep interval as needed
57
 
58
+ # Create a startup event.
59
+ @app.on_event("startup")
60
+ async def startup_event():
61
+ # Start the continuous function as a background task.
62
+ asyncio.create_task(your_continuous_function())
63
 
64
+ @app.get("/test_api")
65
+ def test_api():
66
+ return "kpi_result"