Spaces:
Sleeping
Sleeping
Download crew.py from plutoa386/Uber-Project-AI: direct link, hf CLI and curl.
- Browser
- Download file 7.34 kB
-
https://huggingface.co/spaces/plutoa386/Uber-Project-AI/resolve/main/crew.py
- Command line
-
hf download hf://spaces/plutoa386/Uber-Project-AI/crew.py
-
curl -L -o crew.py https://huggingface.co/spaces/plutoa386/Uber-Project-AI/resolve/main/crew.py
7.34 kB
| import os | |
| import re | |
| import json | |
| import joblib | |
| import numpy as np | |
| import pickle | |
| from crewai import Agent, Task, Crew, LLM | |
| from crewai.tools import tool | |
| from dataLoader import * | |
| # Load trained model, scaler, and feature columns | |
| model_filename = "modelUberML.pkl" | |
| with open(model_filename, 'rb') as file: | |
| model_data = pickle.load(file) | |
| ride_model = model_data['model'] | |
| scaler = model_data['scaler'] | |
| feature_columns = model_data['feature_columns'] | |
| # Define Tools for the Agents | |
| def predict_ride(rideID: str, return_json: bool = False): | |
| """Predict the success of an Uber ride using the trained ML model and save result to Firebase.""" | |
| ride_data_dict = pull_ride_data(rideID) | |
| if not ride_data_dict: | |
| error = f"Error: No ride data found for document ID '{rideID}'" | |
| if return_json: | |
| return {"status": "error", "message": error} | |
| return error | |
| # Define feature mapping (same as training) | |
| FEATURE_MAPPING = { | |
| "Avg CTAT": "Avg CTAT", | |
| "Avg VTAT": "Avg VTAT", | |
| "Booking Value": "Booking Value", | |
| "Customer Rating": "Customer Rating", | |
| "Driver Ratings": "Driver Ratings", | |
| "Ride Distance": "Ride Distance", | |
| "Booking Status_Cancelled by Driver": "Booking Status_Cancelled by Driver", | |
| "Booking Status_Incomplete": "Booking Status_Incomplete", | |
| "Booking Status_No Driver Found": "Booking Status_No Driver Found", | |
| "Payment Method_Credit Card": "Payment Method_Credit Card", | |
| "Payment Method_Debit Card": "Payment Method_Debit Card", | |
| "Payment Method_UPI": "Payment Method_UPI", | |
| "Payment Method_Uber Wallet": "Payment Method_Uber Wallet", | |
| "Vehicle Type_Bike": "Vehicle Type_Bike", | |
| "Vehicle Type_Go Mini": "Vehicle Type_Go Mini", | |
| "Vehicle Type_Go Sedan": "Vehicle Type_Go Sedan", | |
| "Vehicle Type_Premier Sedan": "Vehicle Type_Premier Sedan", | |
| "Vehicle Type_Uber XL": "Vehicle Type_Uber XL", | |
| "Vehicle Type_eBike": "Vehicle Type_eBike", | |
| "Pickup Location": "Pickup Location", | |
| "Drop Location": "Drop Location", | |
| } | |
| # Extract features | |
| input_features = {} | |
| for firestore_key, model_col in FEATURE_MAPPING.items(): | |
| val = ride_data_dict.get(firestore_key) | |
| if val is None: | |
| error = f"Error: Missing required feature '{firestore_key}'" | |
| if return_json: | |
| return {"status": "error", "message": error} | |
| return error | |
| input_features[model_col] = val | |
| # Create DataFrame | |
| df_sample = pd.DataFrame([input_features]) | |
| # One-hot encode categorical features | |
| categorical_cols = ['Pickup Location', 'Drop Location'] | |
| df_sample = pd.get_dummies(df_sample, columns=categorical_cols) | |
| # Ensure all training columns are present | |
| for col in feature_columns: | |
| if col not in df_sample.columns: | |
| df_sample[col] = 0 | |
| df_sample = df_sample[feature_columns] | |
| # Scale | |
| ride_scaled = scaler.transform(df_sample) | |
| # Predict | |
| prediction = ride_model.predict(ride_scaled)[0] | |
| probability = ride_model.predict_proba(ride_scaled)[0] | |
| confidence = float(max(probability)) | |
| # Save to Firebase | |
| success = push_prediction_result(rideID, prediction, confidence) | |
| # Prepare result | |
| result_dict = { | |
| "prediction": int(prediction), | |
| "confidence": confidence, | |
| "rideID": rideID, | |
| "saved_to_firebase": success | |
| } | |
| if return_json: | |
| return result_dict | |
| else: | |
| return json.dumps(result_dict, indent=2) | |
| def format_prediction(rideID: str, return_json: bool = False): | |
| """Fetch prediction + ride data and format into readable output""" | |
| pred_data = pull_prediction_data(rideID) | |
| ride_data = pull_ride_data(rideID) | |
| if not pred_data: | |
| error = f"No prediction found for rideID {rideID}" | |
| return {"status": "error", "message": f"No prediction found{rideID}"} if return_json else error | |
| if not ride_data: | |
| error = f"No ride data found for rideID {rideID}" | |
| return {"status": "error", "message": error} if return_json else error | |
| #Build the formatted result | |
| formatted = { | |
| "rideID": rideID, | |
| "prediction": pred_data.get("prediction", "N/A"), | |
| "confidence": pred_data.get("confidence", "N/A"), | |
| #Fields | |
| "bookingValue": ride_data.get("Booking Value"), | |
| "avgCTAT": ride_data.get("Avg CTAT"), | |
| "avgVTAT": ride_data.get("Avg VTAT"), | |
| "statusCompleted": ride_data.get("Booking Status_Completed"), | |
| } | |
| return formatted if return_json else json.dumps(formatted, indent=2) | |
| llm = LLM( | |
| model="huggingface/meta-llama/Llama-3.1-8B-Instruct" | |
| ) | |
| # Define Agents | |
| ride_success_predictor = Agent( | |
| role="Ride Success Calculator Agent", | |
| goal="Calculate the success or failure of a ride using ML model and LLM interpretation", | |
| backstory="You combine machine learning predictions with natural language explanations to provide personalized ride success assessments.", | |
| verbose=True, | |
| llm=llm, | |
| tools=[predict_ride] | |
| ) | |
| formatting_agent = Agent( | |
| role="Formatting Agent", | |
| goal="Retrieve prediction + ride data and format into readable output", | |
| backstory="You turn raw ML prediction results into clean, readable formatted summaries.", | |
| verbose=True, | |
| llm=llm, | |
| tools=[format_prediction], | |
| ) | |
| # Define Tasks | |
| predict_ride_success = Task( | |
| description=f"Calculate ride success/failure using the ML model based on ride features.", | |
| expected_output="Binary success/failure, confidence score, and brief explanation.", | |
| agent=ride_success_predictor, | |
| ) | |
| format_prediction_task = Task( | |
| description=f"Pull prediction and ride data for a given rideID, then format the results into a readable report", | |
| expected_output="A structured summary of ride performance and prediction results.", | |
| agent=formatting_agent, | |
| ) | |
| # Define Crew | |
| crew = Crew( | |
| agents=[ride_success_predictor, formatting_agent], | |
| tasks=[predict_ride_success, format_prediction_task], | |
| verbose=True | |
| ) | |
| def run_crew_for_ride(rideID: str): | |
| """Run the full crew pipeline for a given rideID and return the final output.""" | |
| # Inject rideID into tasks dynamically | |
| for task in crew.tasks: | |
| # Dynamically update task descriptions to include rideID | |
| if "predict_ride_success" in task.description or "Calculate ride success" in task.description: | |
| task.description = f"Predict ride success for rideID: {rideID}. Use the predict_ride tool with this rideID." | |
| if "format_prediction_task" in task.description or "Pull prediction and ride data" in task.description: | |
| task.description = f"Format the prediction and ride data for rideID: {rideID}. Use the format_prediction tool with this rideID." | |
| # Run crew | |
| result = crew.kickoff() | |
| return result.raw if hasattr(result, 'raw') else str(result) | |
| # Optional: Keep CLI for local testing | |
| if __name__ == "__main__": | |
| import sys | |
| if len(sys.argv) > 1: | |
| ride_id = sys.argv[1] | |
| print(f"Running crew for rideID: {ride_id}") | |
| output = run_crew_for_ride(ride_id) | |
| print("\n=== FINAL OUTPUT ===\n") | |
| print(output) | |
| else: | |
| print("Usage: python crew.py <rideID>") | |