Update main.py
Browse files
main.py
CHANGED
|
@@ -97,105 +97,127 @@ def marketing_rec():
|
|
| 97 |
@app.route("/predict_metric", methods=["POST"])
|
| 98 |
@cross_origin()
|
| 99 |
def predict_metric():
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
|
| 150 |
-
|
| 151 |
-
|
|
|
|
| 152 |
|
| 153 |
-
|
| 154 |
-
|
| 155 |
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
df['date'] = df['date'].dt.tz_localize(None)
|
| 159 |
|
| 160 |
-
|
| 161 |
-
|
|
|
|
| 162 |
|
| 163 |
-
|
| 164 |
-
df = df.dropna(subset=['date'])
|
| 165 |
|
| 166 |
-
|
| 167 |
-
|
|
|
|
|
|
|
| 168 |
|
| 169 |
-
|
| 170 |
-
|
|
|
|
| 171 |
|
| 172 |
-
|
| 173 |
-
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
-
|
|
|
|
|
|
|
| 176 |
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
return jsonify({"error": "Not enough data for prediction"})
|
| 181 |
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
model.fit(df)
|
| 185 |
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
forecast = model.predict(future_dates)
|
| 189 |
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
|
| 194 |
-
|
| 195 |
-
|
|
|
|
| 196 |
|
| 197 |
-
# Return predictions in JSON format
|
| 198 |
-
return jsonify({"predictedData": predictions})
|
| 199 |
|
| 200 |
|
| 201 |
|
|
|
|
| 97 |
@app.route("/predict_metric", methods=["POST"])
|
| 98 |
@cross_origin()
|
| 99 |
def predict_metric():
|
| 100 |
+
try:
|
| 101 |
+
request_data = request.json
|
| 102 |
+
user_id = request_data.get("user_id")
|
| 103 |
+
interval = request_data.get("interval", 30)
|
| 104 |
+
metric_type = request_data.get("metric_type", "Profit") # "Profit" or "Customer Engagement"
|
| 105 |
+
|
| 106 |
+
# Log received request data
|
| 107 |
+
print("Received request:", request_data)
|
| 108 |
+
|
| 109 |
+
transactions_ref = db.collection("system_users").document(user_id).collection("transactions")
|
| 110 |
+
data = []
|
| 111 |
+
|
| 112 |
+
if metric_type == "Profit":
|
| 113 |
+
try:
|
| 114 |
+
# Fetch both Income and Expense transactions for Profit calculation
|
| 115 |
+
income_query = transactions_ref.where("transactionType", "==", "Income").stream()
|
| 116 |
+
expense_query = transactions_ref.where("transactionType", "==", "Expense").stream()
|
| 117 |
+
|
| 118 |
+
income_data = {}
|
| 119 |
+
expense_data = {}
|
| 120 |
+
|
| 121 |
+
for doc in income_query:
|
| 122 |
+
transaction = doc.to_dict()
|
| 123 |
+
date_str = transaction["date"].toDate() # Convert Firestore Timestamp to DateTime
|
| 124 |
+
amount = transaction["amountDue"]
|
| 125 |
+
income_data[date_str] = income_data.get(date_str, 0) + amount
|
| 126 |
+
print(f"Income transaction - Date: {date_str}, Amount: {amount}")
|
| 127 |
+
|
| 128 |
+
for doc in expense_query:
|
| 129 |
+
transaction = doc.to_dict()
|
| 130 |
+
date_str = transaction["date"].toDate() # Convert Firestore Timestamp to DateTime
|
| 131 |
+
amount = transaction["amountDue"]
|
| 132 |
+
expense_data[date_str] = expense_data.get(date_str, 0) + amount
|
| 133 |
+
print(f"Expense transaction - Date: {date_str}, Amount: {amount}")
|
| 134 |
+
|
| 135 |
+
# Calculate net profit for each date
|
| 136 |
+
for date, income in income_data.items():
|
| 137 |
+
expense = expense_data.get(date, 0)
|
| 138 |
+
data.append({"date": date, "amountDue": income - expense})
|
| 139 |
+
|
| 140 |
+
except Exception as e:
|
| 141 |
+
print("Error processing Profit data:", str(e))
|
| 142 |
+
return jsonify({"error": "Error processing Profit data"}), 500
|
| 143 |
+
|
| 144 |
+
elif metric_type == "Customer Engagement":
|
| 145 |
+
try:
|
| 146 |
+
# Use count of Income transactions per day as Customer Engagement
|
| 147 |
+
income_query = transactions_ref.where("transactionType", "==", "Income").stream()
|
| 148 |
+
|
| 149 |
+
engagement_data = {}
|
| 150 |
+
for doc in income_query:
|
| 151 |
+
transaction = doc.to_dict()
|
| 152 |
+
date_str = transaction["date"].toDate() # Convert Firestore Timestamp to DateTime
|
| 153 |
+
engagement_data[date_str] = engagement_data.get(date_str, 0) + 1
|
| 154 |
+
print(f"Engagement transaction - Date: {date_str}")
|
| 155 |
+
|
| 156 |
+
for date, count in engagement_data.items():
|
| 157 |
+
data.append({"date": date, "amountDue": count})
|
| 158 |
+
|
| 159 |
+
except Exception as e:
|
| 160 |
+
print("Error processing Customer Engagement data:", str(e))
|
| 161 |
+
return jsonify({"error": "Error processing Customer Engagement data"}), 500
|
| 162 |
+
|
| 163 |
+
# Create DataFrame from the aggregated data
|
| 164 |
+
try:
|
| 165 |
+
df = pd.DataFrame(data)
|
| 166 |
+
print("Data before processing:", df)
|
| 167 |
|
| 168 |
+
# Ensure 'date' column is datetime
|
| 169 |
+
df['date'] = pd.to_datetime(df['date'], errors='coerce')
|
| 170 |
+
df['date'] = df['date'].dt.tz_localize(None)
|
| 171 |
|
| 172 |
+
# Drop rows where 'date' could not be parsed
|
| 173 |
+
df = df.dropna(subset=['date'])
|
| 174 |
|
| 175 |
+
# Set 'date' as index
|
| 176 |
+
df = df.sort_values("date").set_index("date")
|
|
|
|
| 177 |
|
| 178 |
+
# Resample daily to ensure regular intervals (fill missing dates)
|
| 179 |
+
df = df.resample("D").sum().reset_index()
|
| 180 |
+
print("Data after resampling:", df)
|
| 181 |
|
| 182 |
+
df.columns = ["ds", "y"] # ds: date, y: target
|
|
|
|
| 183 |
|
| 184 |
+
# Check if there's enough data to train the model
|
| 185 |
+
if df.shape[0] < 10:
|
| 186 |
+
print("Not enough data for prediction")
|
| 187 |
+
return jsonify({"error": "Not enough data for prediction"}), 400
|
| 188 |
|
| 189 |
+
except Exception as e:
|
| 190 |
+
print("Error processing DataFrame:", str(e))
|
| 191 |
+
return jsonify({"error": "Error processing DataFrame"}), 500
|
| 192 |
|
| 193 |
+
# Prophet prediction
|
| 194 |
+
try:
|
| 195 |
+
# Initialize and fit the Prophet model
|
| 196 |
+
model = Prophet(daily_seasonality=True, yearly_seasonality=True)
|
| 197 |
+
model.fit(df)
|
| 198 |
|
| 199 |
+
# DataFrame for future predictions
|
| 200 |
+
future_dates = model.make_future_dataframe(periods=interval)
|
| 201 |
+
forecast = model.predict(future_dates)
|
| 202 |
|
| 203 |
+
# Extract the forecast for the requested interval
|
| 204 |
+
forecast_data = forecast[['ds', 'yhat']].tail(interval)
|
| 205 |
+
predictions = [{"date": row['ds'].strftime('%Y-%m-%d'), "value": row['yhat']} for _, row in forecast_data.iterrows()]
|
|
|
|
| 206 |
|
| 207 |
+
# Log the predictions before returning
|
| 208 |
+
print("Predictions:", predictions)
|
|
|
|
| 209 |
|
| 210 |
+
# Return predictions in JSON format
|
| 211 |
+
return jsonify({"predictedData": predictions})
|
|
|
|
| 212 |
|
| 213 |
+
except Exception as e:
|
| 214 |
+
print("Error in Prophet prediction:", str(e))
|
| 215 |
+
return jsonify({"error": "Error in Prophet prediction"}), 500
|
| 216 |
|
| 217 |
+
except Exception as e:
|
| 218 |
+
print("General error:", str(e))
|
| 219 |
+
return jsonify({"error": "Internal server error"}), 500
|
| 220 |
|
|
|
|
|
|
|
| 221 |
|
| 222 |
|
| 223 |
|