Arafath10 commited on
Commit
e37910a
·
verified ·
1 Parent(s): 4fa048f

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +85 -64
main.py CHANGED
@@ -1,70 +1,91 @@
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("xgb_model.joblib")
11
- encoders = joblib.load("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=["*"],
23
- allow_credentials=True,
24
- allow_methods=["*"],
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
+ import requests
4
  import pandas as pd
5
+ import json
 
6
 
7
+ global data
 
 
 
 
 
 
 
 
 
 
8
  app = FastAPI()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
+ # Declare the continuous function as an async function.
11
+ async def your_continuous_function():
12
+ global data
13
+ while True:
14
+ print("data fetcher running.....")
15
+
16
+ # Initialize an empty DataFrame to store the combined data
17
+ combined_df = pd.DataFrame()
18
+
19
+ # Loop through pages 1 to 4
20
+ for page in range(1,6):
21
+ try:
22
+ # Update the payload for each page
23
+ url = "https://dev3.api.curfox.parallaxtec.com/api/admin/test-dataset?sort=id&paginate=2000&page="+str(page)
24
+
25
+ payload = {}
26
+ headers = {
27
+ 'Accept': 'application/json',
28
+ 'X-Tenant': 'mng',
29
+ 'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiNDE3YTIyNDE4MGUzNDJmMjRiYzlkMjAyYTk3NWE0MjRiYzhlY2I0NDM3NmI0ZDdiN2M5MTQ5NjI4YTM0ZWM1Y2ZlYmZhMGMzOWFkMmNkZWIiLCJpYXQiOjE2OTA3OTk4MjQuNzgwNzY4LCJuYmYiOjE2OTA3OTk4MjQuNzgwNzcyLCJleHAiOjE3MjI0MjIyMjQuNzcwOTk0LCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.OCTRI6oDChKUHsZAbxdrsarqXJEuQpnNuQzo1cp4OWj2KddKfBCMCad9cFA5-aJ2S6INN1WsGZAEa1JtOLSzxnsfLIwRr73ODHiRZM9ZYOLdJukTisbO6ONOkAFbpE48o6CHTFYen_D2QYSxqKmQ1lCO2-FQn18RPK6QOiuHuW1KYTWtxo_wXncRl5Rt2PWyrm88iMClD969-oXcjk-wU7Wr1TFTY01JDLLHYe9sqfUTkRewpzFk2YIg9pt1yTGJRboyF9mqeVcq7fADdOzP7uqUFQnro-dHrzivYYYYXUmc0UBBu7t0FY2SerwHnWObNF-tMxyPX_9xGQjzy9H1NtbvxULIrnqA9WLJBqERhpRGlKH2S_C-eacAUwI548JkwHQGelRJHpAh36xaJqNsOGh0l2HX2LIF52TqdHevj-4FE4AFLPRPqGYYv-v-tL50LRHdbTmLw_n8bpeROba8dNoz7RC-YKdyYRpBsIiaIA78_ltk_-1Qme-u9ArX_Zycf2m9BkefEVpN1DUHOuPRm_pGAyIagkCmMfIFsV9rMiEhCtqT_IV0HmMrBw1OJ2m-c-DxXLdCLpjgiKc4HPb44aCxZgm8s0vJOGGP-2zajtQ1H2IpJ7Zkjyggl4frZ2EkwX4Ay0dsiQxTG5DgKOcQZfvCMgzJCtQPL7So7c8QcUk'
30
+ }
31
+
32
+ response = requests.request("GET", url, headers=headers, data=payload)
33
+
34
+ import pandas as pd
35
+ import json
36
+
37
+ # Sample JSON response
38
+ json_response = response.json()
39
+ # Extracting 'data' for conversion
40
+ data = json_response['data']
41
+
42
+ df = pd.json_normalize(data)
43
+
44
+ # Concatenate the current page's DataFrame with the combined DataFrame
45
+ combined_df = pd.concat([combined_df, df], ignore_index=True)
46
+ except:
47
+ print("data over")
48
+ print("data collected....")
49
+ data = combined_df[combined_df['status.name'].isin(['RETURN TO CLIENT', 'DELIVERED'])]
50
+ data = data[['delivery_possibility','status.name']]
51
+ data = data[data['delivery_possibility'].between(0, 100)]
52
+
53
+ await asyncio.sleep(43200) # Adjust the sleep interval as needed
54
 
55
+ # Create a startup event.
56
+ @app.on_event("startup")
57
+ async def startup_event():
58
+ # Start the continuous function as a background task.
59
+ asyncio.create_task(your_continuous_function())
60
 
61
+ @app.get("/kpi_results")
62
+ def read_root():
63
+ global data
64
+ status_counts_more_than_80 = data[data['delivery_possibility'] > 80]['status.name'].value_counts()
65
+
66
+ status_counts_50_to_80 = data[(data['delivery_possibility'] >= 50) & (data['delivery_possibility'] <= 80)]['status.name'].value_counts()
67
+
68
+ status_counts_30_to_49 = data[(data['delivery_possibility'] >= 30) & (data['delivery_possibility'] <= 49)]['status.name'].value_counts()
69
+
70
+ status_counts_below_30 = data[data['delivery_possibility'] < 30]['status.name'].value_counts()
71
+ kpi_result = {
72
+ "kpi_result": {
73
+ "status_counts_more_than_80": {
74
+ "correct_values": status_counts_more_than_80[0],
75
+ "incorrect_values": status_counts_more_than_80[1]
76
+ },
77
+ "status_counts_50_to_80": {
78
+ "correct_values": status_counts_50_to_80[0],
79
+ "incorrect_values": status_counts_50_to_80[1]
80
+ },
81
+ "status_counts_30_to_49": {
82
+ "correct_values": status_counts_30_to_49[0],
83
+ "incorrect_values": status_counts_30_to_49[1]
84
+ },
85
+ "status_counts_below_30": {
86
+ "correct_values": status_counts_below_30[0],
87
+ "incorrect_values": status_counts_below_30[1]
88
+ }
89
+ }
90
+ }
91
+ return kpi_result