yoursdvniel commited on
Commit
d25a8b4
·
verified ·
1 Parent(s): 49d9f84

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +49 -18
main.py CHANGED
@@ -93,28 +93,58 @@ def marketing_rec():
93
 
94
  return jsonify(str(response['text']))
95
 
96
- # Income/Expenses Prediction endpoint
97
- @app.route("/predict_revenue", methods=["POST"])
98
  @cross_origin()
99
- def predict_revenue():
100
  request_data = request.json
101
  user_id = request_data.get("user_id")
102
  interval = request_data.get("interval", 30)
103
- transaction_type = request_data.get("transaction_type", "Income")
104
 
105
- # Fetch transaction data based on user and transaction type
106
  transactions_ref = db.collection("system_users").document(user_id).collection("transactions")
107
- query = transactions_ref.where("transactionType", "==", transaction_type).stream()
108
-
109
  data = []
110
- for doc in query:
111
- transaction = doc.to_dict()
112
- data.append({
113
- "date": transaction["date"],
114
- "amountDue": transaction["amountDue"]
115
- })
116
-
117
- # Create DataFrame from transaction data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  df = pd.DataFrame(data)
119
 
120
  # Ensure 'date' column is datetime
@@ -124,7 +154,7 @@ def predict_revenue():
124
  # Set 'date' as index
125
  df = df.sort_values("date").set_index("date")
126
 
127
- # Resample daily to ensure regular intervals
128
  df = df.resample("D").sum().reset_index()
129
 
130
  df.columns = ["ds", "y"] # ds: date, y: target
@@ -137,17 +167,18 @@ def predict_revenue():
137
  model = Prophet(daily_seasonality=True, yearly_seasonality=True)
138
  model.fit(df)
139
 
140
- # dataframe for future predictions
141
  future_dates = model.make_future_dataframe(periods=interval)
142
  forecast = model.predict(future_dates)
143
 
144
  # Extract the forecast for the requested interval
145
- forecast_data = forecast[['ds', 'yhat']].tail(interval)
146
  predictions = [{"date": row['ds'].strftime('%Y-%m-%d'), "value": row['yhat']} for _, row in forecast_data.iterrows()]
147
 
148
  # Return predictions in JSON format
149
  return jsonify({"predictedData": predictions})
150
 
151
 
 
152
  if __name__ == "__main__":
153
  app.run(debug=True, host="0.0.0.0", port=7860)
 
93
 
94
  return jsonify(str(response['text']))
95
 
96
+ # Profit/Customer Engagement Prediction endpoint
97
+ @app.route("/predict_metric", methods=["POST"])
98
  @cross_origin()
99
+ def predict_metric():
100
  request_data = request.json
101
  user_id = request_data.get("user_id")
102
  interval = request_data.get("interval", 30)
103
+ metric_type = request_data.get("metric_type", "Profit") # "Profit" or "Customer Engagement"
104
 
 
105
  transactions_ref = db.collection("system_users").document(user_id).collection("transactions")
106
+
 
107
  data = []
108
+
109
+ if metric_type == "Profit":
110
+ # Fetch both Income and Expense transactions for Profit calculation
111
+ income_query = transactions_ref.where("transactionType", "==", "Income").stream()
112
+ expense_query = transactions_ref.where("transactionType", "==", "Expense").stream()
113
+
114
+ income_data = {}
115
+ expense_data = {}
116
+
117
+ for doc in income_query:
118
+ transaction = doc.to_dict()
119
+ date_str = transaction["date"]
120
+ amount = transaction["amountDue"]
121
+ income_data[date_str] = income_data.get(date_str, 0) + amount
122
+
123
+ for doc in expense_query:
124
+ transaction = doc.to_dict()
125
+ date_str = transaction["date"]
126
+ amount = transaction["amountDue"]
127
+ expense_data[date_str] = expense_data.get(date_str, 0) + amount
128
+
129
+ # Calculate net profit for each date
130
+ for date, income in income_data.items():
131
+ expense = expense_data.get(date, 0)
132
+ data.append({"date": date, "amountDue": income - expense})
133
+
134
+ elif metric_type == "Customer Engagement":
135
+ # Use count of Income transactions per day as Customer Engagement
136
+ income_query = transactions_ref.where("transactionType", "==", "Income").stream()
137
+
138
+ engagement_data = {}
139
+ for doc in income_query:
140
+ transaction = doc.to_dict()
141
+ date_str = transaction["date"]
142
+ engagement_data[date_str] = engagement_data.get(date_str, 0) + 1
143
+
144
+ for date, count in engagement_data.items():
145
+ data.append({"date": date, "amountDue": count})
146
+
147
+ # Create DataFrame from the aggregated data
148
  df = pd.DataFrame(data)
149
 
150
  # Ensure 'date' column is datetime
 
154
  # Set 'date' as index
155
  df = df.sort_values("date").set_index("date")
156
 
157
+ # Resample daily to ensure regular intervals (fill missing dates)
158
  df = df.resample("D").sum().reset_index()
159
 
160
  df.columns = ["ds", "y"] # ds: date, y: target
 
167
  model = Prophet(daily_seasonality=True, yearly_seasonality=True)
168
  model.fit(df)
169
 
170
+ # DataFrame for future predictions
171
  future_dates = model.make_future_dataframe(periods=interval)
172
  forecast = model.predict(future_dates)
173
 
174
  # Extract the forecast for the requested interval
175
+ forecast_data = forecast[['ds', 'yhat']].tail(interval)
176
  predictions = [{"date": row['ds'].strftime('%Y-%m-%d'), "value": row['yhat']} for _, row in forecast_data.iterrows()]
177
 
178
  # Return predictions in JSON format
179
  return jsonify({"predictedData": predictions})
180
 
181
 
182
+
183
  if __name__ == "__main__":
184
  app.run(debug=True, host="0.0.0.0", port=7860)