plutoa386 commited on
Commit
56c0820
·
1 Parent(s): d559b3c

major update with app.py

Browse files
README.md DELETED
@@ -1,12 +0,0 @@
1
- ---
2
- title: Uber Project AI
3
- emoji: 🌍
4
- colorFrom: blue
5
- colorTo: pink
6
- sdk: gradio
7
- sdk_version: 6.0.1
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ import os
3
+ import sys
4
+ import json
5
+
6
+ # Add current dir to path (for local/HF compatibility)
7
+ sys.path.append(os.path.dirname(__file__))
8
+
9
+ # Import the function we just defined
10
+ from crew import run_crew_for_ride
11
+ import gradio as gr
12
+
13
+
14
+ def predict_ride_api(rideID: str):
15
+ """
16
+ API endpoint for Uber ride success prediction.
17
+ Input: rideID (str)
18
+ Output: JSON dict (prediction, confidence, features, etc.)
19
+ """
20
+ if not rideID or not rideID.strip():
21
+ return {"status": "error", "message": "rideID is required"}
22
+
23
+ rideID = rideID.strip()
24
+ result = run_crew_for_ride(rideID)
25
+ return result
26
+
27
+
28
+ # Gradio UI
29
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
30
+ gr.Markdown("# 🚖 Uber Ride Success Predictor (CrewAI + Gradient Boosting)")
31
+ gr.Markdown("Enter a ride ID (e.g., `CNR1000732`) to get ML-based prediction and summary.")
32
+
33
+ ride_id_input = gr.Textbox(
34
+ label="Ride ID",
35
+ placeholder="e.g., CNR1000732",
36
+ value="CNR1000732" # optional default for demo
37
+ )
38
+
39
+ output = gr.JSON(label="Prediction Result")
40
+
41
+ btn = gr.Button("Run Prediction", variant="primary")
42
+ btn.click(
43
+ fn=predict_ride_api,
44
+ inputs=ride_id_input,
45
+ outputs=output
46
+ )
47
+
48
+ gr.Markdown("💡 Behind the scenes: Gradient Boosting model + Llama3.1 for explanation + Firebase sync.")
49
+
50
+ # Launch for HF Spaces
51
+ demo.launch()
crew.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import json
4
+ import joblib
5
+ import numpy as np
6
+ from crewai import Agent, Task, Crew, LLM
7
+ from crewai.tools import tool
8
+ from dataLoader import *
9
+
10
+ # Load trained model, scaler, and feature columns
11
+ model_filename = "modelUberML.pkl"
12
+ with open(model_filename, 'rb') as file:
13
+ model_data = pickle.load(file)
14
+ ride_model = model_data['model']
15
+ scaler = model_data['scaler']
16
+ feature_columns = model_data['feature_columns']
17
+
18
+
19
+ # Define Tools for the Agents
20
+ @tool("predict_ride")
21
+ def predict_ride(rideID: str, return_json: bool = False):
22
+ """Predict the success of an Uber ride using the trained ML model and save result to Firebase."""
23
+ ride_data_dict = pull_ride_data(rideID)
24
+ if not ride_data_dict:
25
+ error = f"Error: No ride data found for document ID '{rideID}'"
26
+ if return_json:
27
+ return {"status": "error", "message": error}
28
+ return error
29
+
30
+ # Define feature mapping (same as training)
31
+ FEATURE_MAPPING = {
32
+ "Avg CTAT": "Avg CTAT",
33
+ "Avg VTAT": "Avg VTAT",
34
+ "Booking Value": "Booking Value",
35
+ "Customer Rating": "Customer Rating",
36
+ "Driver Ratings": "Driver Ratings",
37
+ "Ride Distance": "Ride Distance",
38
+ "Booking Status_Cancelled by Driver": "Booking Status_Cancelled by Driver",
39
+ "Booking Status_Incomplete": "Booking Status_Incomplete",
40
+ "Booking Status_No Driver Found": "Booking Status_No Driver Found",
41
+ "Payment Method_Credit Card": "Payment Method_Credit Card",
42
+ "Payment Method_Debit Card": "Payment Method_Debit Card",
43
+ "Payment Method_UPI": "Payment Method_UPI",
44
+ "Payment Method_Uber Wallet": "Payment Method_Uber Wallet",
45
+ "Vehicle Type_Bike": "Vehicle Type_Bike",
46
+ "Vehicle Type_Go Mini": "Vehicle Type_Go Mini",
47
+ "Vehicle Type_Go Sedan": "Vehicle Type_Go Sedan",
48
+ "Vehicle Type_Premier Sedan": "Vehicle Type_Premier Sedan",
49
+ "Vehicle Type_Uber XL": "Vehicle Type_Uber XL",
50
+ "Vehicle Type_eBike": "Vehicle Type_eBike",
51
+ "Pickup Location": "Pickup Location",
52
+ "Drop Location": "Drop Location",
53
+ }
54
+
55
+ # Extract features
56
+ input_features = {}
57
+ for firestore_key, model_col in FEATURE_MAPPING.items():
58
+ val = ride_data_dict.get(firestore_key)
59
+ if val is None:
60
+ error = f"Error: Missing required feature '{firestore_key}'"
61
+ if return_json:
62
+ return {"status": "error", "message": error}
63
+ return error
64
+ input_features[model_col] = val
65
+
66
+ # Create DataFrame
67
+ df_sample = pd.DataFrame([input_features])
68
+
69
+ # One-hot encode categorical features
70
+ categorical_cols = ['Pickup Location', 'Drop Location']
71
+ df_sample = pd.get_dummies(df_sample, columns=categorical_cols)
72
+
73
+ # Ensure all training columns are present
74
+ for col in feature_columns:
75
+ if col not in df_sample.columns:
76
+ df_sample[col] = 0
77
+ df_sample = df_sample[feature_columns]
78
+
79
+ # Scale
80
+ ride_scaled = scaler.transform(df_sample)
81
+
82
+ # Predict
83
+ prediction = ride_model.predict(ride_scaled)[0]
84
+ probability = ride_model.predict_proba(ride_scaled)[0]
85
+ confidence = float(max(probability))
86
+
87
+ # Save to Firebase
88
+ success = push_prediction_result(rideID, prediction, confidence)
89
+
90
+ # Prepare result
91
+ result_dict = {
92
+ "prediction": int(prediction),
93
+ "confidence": confidence,
94
+ "rideID": rideID,
95
+ "saved_to_firebase": success
96
+ }
97
+
98
+ if return_json:
99
+ return result_dict
100
+ else:
101
+ return json.dumps(result_dict, indent=2)
102
+
103
+ @tool("format_prediction")
104
+ def format_prediction(rideID: str, return_json: bool = False):
105
+ """Fetch prediction + ride data and format into readable output"""
106
+
107
+ pred_data = pull_prediction_data(rideID)
108
+ ride_data = pull_ride_data(rideID)
109
+ if not pred_data:
110
+ error = f"No prediction found for rideID {rideID}"
111
+ return {"status": "error", "message": f"No prediction found{rideID}"} if return_json else error
112
+ if not ride_data:
113
+ error = f"No ride data found for rideID {rideID}"
114
+ return {"status": "error", "message": error} if return_json else error
115
+
116
+ #Build the formatted result
117
+ formatted = {
118
+ "rideID": rideID,
119
+ "prediction": pred_data.get("prediction", "N/A"),
120
+ "confidence": pred_data.get("confidence", "N/A"),
121
+
122
+ #Fields
123
+ "bookingValue": ride_data.get("Booking Value"),
124
+ "avgCTAT": ride_data.get("Avg CTAT"),
125
+ "avgVTAT": ride_data.get("Avg VTAT"),
126
+ "statusCompleted": ride_data.get("Booking Status_Completed"),
127
+ }
128
+
129
+ return formatted if return_json else json.dumps(formatted, indent=2)
130
+
131
+
132
+ llm = LLM(
133
+ model="huggingface/openai/gpt-oss-120b"
134
+ )
135
+
136
+
137
+
138
+ # Define Agents
139
+ ride_success_predictor = Agent(
140
+ role="Ride Success Calculator Agent",
141
+ goal="Calculate the success or failure of a ride using ML model and LLM interpretation",
142
+ backstory="You combine machine learning predictions with natural language explanations to provide personalized ride success assessments.",
143
+ verbose=True,
144
+ llm=llm,
145
+ tools=[predict_ride]
146
+ )
147
+
148
+ formatting_agent = Agent(
149
+ role="Formatting Agent",
150
+ goal="Retrieve prediction + ride data and format into readable output",
151
+ backstory="You turn raw ML prediction results into clean, readable formatted summaries.",
152
+ verbose=True,
153
+ llm=llm,
154
+ tools=[format_prediction],
155
+ )
156
+
157
+ # Define Tasks
158
+ predict_ride_success = Task(
159
+ description=f"Calculate ride success/failure using the ML model based on ride features.",
160
+ expected_output="Binary success/failure, confidence score, and brief explanation.",
161
+ agent=ride_success_predictor,
162
+ )
163
+
164
+ format_prediction_task = Task(
165
+ description=f"Pull prediction and ride data for a given rideID, then format the results into a readable report",
166
+ expected_output="A structured summary of ride performance and prediction results.",
167
+ agent=formatting_agent,
168
+ )
169
+
170
+ # Define Crew
171
+ crew = Crew(
172
+ agents=[ride_success_predictor, formatting_agent],
173
+ tasks=[predict_ride_success, format_prediction_task],
174
+ verbose=True
175
+ )
176
+
177
+ def run_crew_for_ride(rideID: str):
178
+ """Run the full crew pipeline for a given rideID and return the final output."""
179
+ # Inject rideID into tasks dynamically
180
+ for task in crew.tasks:
181
+ # Dynamically update task descriptions to include rideID
182
+ if "predict_ride_success" in task.description or "Calculate ride success" in task.description:
183
+ task.description = f"Predict ride success for rideID: {rideID}. Use the predict_ride tool with this rideID."
184
+ if "format_prediction_task" in task.description or "Pull prediction and ride data" in task.description:
185
+ task.description = f"Format the prediction and ride data for rideID: {rideID}. Use the format_prediction tool with this rideID."
186
+
187
+ # Run crew
188
+ result = crew.kickoff()
189
+ return result.raw if hasattr(result, 'raw') else str(result)
190
+
191
+
192
+ # Optional: Keep CLI for local testing
193
+ if __name__ == "__main__":
194
+ import sys
195
+ if len(sys.argv) > 1:
196
+ ride_id = sys.argv[1]
197
+ print(f"Running crew for rideID: {ride_id}")
198
+ output = run_crew_for_ride(ride_id)
199
+ print("\n=== FINAL OUTPUT ===\n")
200
+ print(output)
201
+ else:
202
+ print("Usage: python crew.py <rideID>")
dataLoader.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pandas as pd
3
+ import librosa
4
+ import numpy as np
5
+ import firebase_admin
6
+ from firebase_admin import credentials, firestore, storage
7
+
8
+ # --- Firebase Initialization ---
9
+ cred_path = r"firebase\uber-analysis-project-98aae-firebase-adminsdk-fbsvc-403ee1126e.json"
10
+ if not firebase_admin._apps:
11
+ cred = credentials.Certificate(cred_path)
12
+ firebase_admin.initialize_app(cred)
13
+
14
+ db = firestore.client()
15
+
16
+ def pull_ride_data(document_id: str):
17
+ """Fetches lifestyle data from Firestore."""
18
+ try:
19
+ doc_ref = db.collection("rides").document(document_id)
20
+ doc = doc_ref.get()
21
+ if doc.exists:
22
+ return doc.to_dict()
23
+ else:
24
+ print(f"Document {document_id} not found.")
25
+ return {}
26
+ except Exception as e:
27
+ print(f"Error fetching document {document_id}: {e}")
28
+ return {}
29
+
30
+ def pull_prediction_data(document_id: str):
31
+ """Fetches prediction data from Firestore."""
32
+ try:
33
+ doc_ref = db.collection("predictions").document(document_id)
34
+ doc = doc_ref.get()
35
+ if doc.exists:
36
+ return doc.to_dict()
37
+ else:
38
+ print(f"Prediction {document_id} not found.")
39
+ return {}
40
+ except Exception as e:
41
+ print(f"Error fetching prediction {document_id}: {e}")
42
+ return {}
43
+
44
+ def push_prediction_result(document_id: str, prediction: int, confidence: float):
45
+ """
46
+ Pushes prediction result to Firestore 'predictions' collection.
47
+ Uses the same document_id as the ride for linking.
48
+ prediction: 1 = Success, 0 = Failure
49
+ confidence: float between 0 and 1
50
+ """
51
+ try:
52
+ # Format prediction as string for readability
53
+ pred_str = "Success" if prediction == 1 else "Failure"
54
+
55
+ doc_ref = db.collection("predictions").document(document_id)
56
+ doc_ref.set({
57
+ "prediction": pred_str,
58
+ "confidence": confidence,
59
+ })
60
+
61
+ print(f"✅ Prediction saved for {document_id} in 'predictions' collection.")
62
+ return True
63
+
64
+ except Exception as e:
65
+ print(f"❌ Error saving prediction for {document_id}: {e}")
66
+ return False
firebase/uber-analysis-project-98aae-firebase-adminsdk-fbsvc-403ee1126e.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "type": "service_account",
3
+ "project_id": "uber-analysis-project-98aae",
4
+ "private_key_id": "403ee1126ee6354d233314245a94edac9269c049",
5
+ "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCz6eGgNMJCJU9F\nJzQfMzY9CZGMlqEBWSVapFd9QbOfMf2+t3kvR1Q1Mt1wrQscaYDgVcQYuyuR2L5Q\nm9V5ya+xDUvKWAk+JN5CD0+/RdnhatHwR6K9UNJ8/q2q/pcX6Vcn47ktqyDeKMVY\njo/Zygh96VPLmluh/Gn21keN9S6C3uV/cPcnmwxtZXSHyA3z5uL0sbKreGI0zBfO\nz0jw754LpRk02Mk/A2aYQk5UrWnMgnKfQK/zGeeKcTvxMjkz+QucjVWqpNG55EV4\n97IQ6+AcI5QMQM2tPyOEis++EQi+SYxN6ezVgkdkowLPd8U6ULx5HUIUnGw1FQ9a\n2UCfSC9VAgMBAAECggEAHS6EYD3ufFgc4XSYaa8ezwusRgdwmg1hl7AsWK69ecbc\nB4Eu8NI7AF39uPb4ZGVgeAKxSemiCYgEZoLAP37NNoSXlHxvE1tbiY9+OeIUkxGG\nd9jGtrpTSd7tQF0HGOPKNTgkoxmsvRwT1mdZQdQZSIL+CnpA/qc4cMcU2Bu6rZM/\nqYHplDgjUBsBKMAu9BUwF3fVVIQD2kaAqRy8dKDxT7rBO8HRTh9tk/5W8Co/kIfr\n5sleslWVC50ZBJDeRWuJ0pb5g7B/IHXOwDLWUmAI1qFFjnYMJs2DdOcMXvIc3dBv\nfOU5NGE6oGmcsPPMAH6YZ9/jMhBqg1MfNJyB405KyQKBgQDz5WMts/d8ZE6265sn\nGcSCtcr87u3qJtTgvQHDwqOF1lPvDB/du+b+hEX+E61oZkZXrXrInUcjxhq3Fnfr\nUyxkIkf9vC1ELQKIJMnrojML3T4yyYFpkwrBsmDfabYzA0GrqY+ARy7wVNK8kyox\nvWPi00mtavyERhAte8+N3EpfswKBgQC8156kjcBgfX9TaS8TixdXgw6rCQsokwnh\nfRUCIzvQ6DPPBHn9erZmKlYerewF9NE3JwN4wRTQjNkITmyXzin4GovzooJ3g/8w\nDx6K0o+Fn5wdmDPv273vzZNwWo55D9Go7jjZqRhcdwbRwfNjH2vjp6ZT1TlMp3Qu\nH67Yk37w1wKBgQCN62G9u2X8TQX8rLZYl0bg5FXcvk9UnAntSC4Zsk2i2Gd4xy5X\nwToVyfRMdzjFchXmePzkdZhquaDb/sgC+B/xmH0ZqYERlbtOa1HPuk9HzRKfTN/w\nBe8RbPGvrvylTHTPJdhpxYILuN/zeRLpZJIV7+qEbafIdFh/jvbkTlY8vwKBgQCq\nGS502pomT+SYpW4aFHd6BDr6JLNAYPHNgnWh70q56e6A0m9vu1EAxbG9ALxQwSyS\nmTmvU3wEPlpf+QQn2TREnuThF8idDvCVwYipUvCkVBizL53Yt/5mOq5LzcX3liAs\nIihjJsUixLQHzMQGzQ7JiQFxEecC/PLReQhtXK5DEQKBgQCV/Ak7TVar2jyTMkEV\nS8RC2xi91Evc124rvTYDO34aZyYpTXaPf/mOKRPY92H+0u089cGtui9A0wsyNauz\nZE9CZUWbbp8GYTAl5SNjpfp8fodisnvBGFr9tShCSD5NgRt3LAWBR/cW+wDnDZ8v\nUY+hdArxkpeLYuwsBD9FOGaH/w==\n-----END PRIVATE KEY-----\n",
6
+ "client_email": "firebase-adminsdk-fbsvc@uber-analysis-project-98aae.iam.gserviceaccount.com",
7
+ "client_id": "109602147730612626857",
8
+ "auth_uri": "https://accounts.google.com/o/oauth2/auth",
9
+ "token_uri": "https://oauth2.googleapis.com/token",
10
+ "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
11
+ "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-fbsvc%40uber-analysis-project-98aae.iam.gserviceaccount.com",
12
+ "universe_domain": "googleapis.com"
13
+ }
modelUberML.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d37704edad2b71913e343767a2fa2ba8606504764fe7bfd2a4ef6810d995d699
3
+ size 290229
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio
2
+ crewai
3
+ firebase-admin
4
+ pandas
5
+ scikit-learn
6
+ numpy
7
+ matplotlib
8
+ seaborn
9
+ joblib
10
+ litellm