Arafath10 commited on
Commit
5a3a837
·
verified ·
1 Parent(s): 8683a5b

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +46 -43
main.py CHANGED
@@ -5,6 +5,7 @@ import data_collector as dc
5
  import pandas as pd
6
  from prophet import Prophet
7
  import math
 
8
 
9
  app = FastAPI()
10
  app.add_middleware(
@@ -15,68 +16,70 @@ app.add_middleware(
15
  allow_headers=["*"],
16
  )
17
 
18
-
19
  def forecast(monthly_sales):
20
- # Prepare the data for Prophet
21
- monthly_sales.rename(columns={'transaction_date': 'ds', 'sell_qty': 'y'}, inplace=True)
 
 
 
 
22
 
23
- # Initialize and fit the Prophet model
24
- model = Prophet()
25
- model.fit(monthly_sales)
26
 
27
- # Make a future dataframe for the next month
28
- future = model.make_future_dataframe(periods=1, freq='M')
29
- forecast = model.predict(future)
30
 
31
- # Extract the forecasted sales for the next month
32
- forecasted_sales = forecast[['ds', 'yhat']].tail(2)
 
 
33
 
34
- # Combine historical and forecasted data
35
- combined_sales = pd.concat([monthly_sales, forecasted_sales[-1:]], ignore_index=True)
36
- original_forecasted_value = combined_sales.tail(1)
37
- rounded_value = combined_sales.tail(1)
38
 
39
- rounded_value['yhat'] = rounded_value['yhat'].apply(lambda x: max(0, math.ceil(x)))
40
 
41
- return combined_sales,original_forecasted_value,rounded_value
 
 
 
 
 
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
  @app.post("/get_product_count_prediction")
45
  async def get_product_count_prediction(b_id: int):
46
  try:
47
  # main
48
  data, message = dc.get_data(b_id=b_id, product_name="sample")
49
-
50
  if message == "done":
51
 
52
  grouped_df = data.groupby('product_name')
53
 
54
  results = []
55
- for product_name, data in grouped_df:
56
- # Summarize the sales count per month
57
- data['transaction_date'] = pd.to_datetime(data['transaction_date'])
58
- data.set_index('transaction_date', inplace=True)
59
- monthly_sales = data['sell_qty'].resample('M').sum().reset_index()
60
-
61
- try:
62
- full_trend, forecasted_value, rounded_value = forecast(monthly_sales)
63
- rounded_value.columns = ["next_month", "y", "predicted_count"]
64
- # Convert to dictionary
65
- result_dict = rounded_value.to_dict(orient="records")[0]
66
- #print(full_trend, forecasted_value, rounded_value)
67
- results.append({
68
- "Product Name" : product_name,
69
- "next_month": str(result_dict["next_month"]),
70
- "predicted_count": result_dict["predicted_count"]
71
- })
72
- except Exception as e:
73
- print(str(e))
74
- results.append({
75
- "Product Name" : product_name,
76
- "next_month": str(e),
77
- "predicted_count": "not predicted"
78
- })
79
- break
80
  response_content = {
81
  "status": "success",
82
  "message": "Prediction successful",
 
5
  import pandas as pd
6
  from prophet import Prophet
7
  import math
8
+ from concurrent.futures import ThreadPoolExecutor, as_completed
9
 
10
  app = FastAPI()
11
  app.add_middleware(
 
16
  allow_headers=["*"],
17
  )
18
 
 
19
  def forecast(monthly_sales):
20
+ # Prepare the data for Prophet
21
+ monthly_sales.rename(columns={'transaction_date': 'ds', 'sell_qty': 'y'}, inplace=True)
22
+
23
+ # Initialize and fit the Prophet model
24
+ model = Prophet()
25
+ model.fit(monthly_sales)
26
 
27
+ # Make a future dataframe for the next month
28
+ future = model.make_future_dataframe(periods=1, freq='M')
29
+ forecast = model.predict(future)
30
 
31
+ # Extract the forecasted sales for the next month
32
+ forecasted_sales = forecast[['ds', 'yhat']].tail(2)
 
33
 
34
+ # Combine historical and forecasted data
35
+ combined_sales = pd.concat([monthly_sales, forecasted_sales[-1:]], ignore_index=True)
36
+ original_forecasted_value = combined_sales.tail(1)
37
+ rounded_value = combined_sales.tail(1)
38
 
39
+ rounded_value['yhat'] = rounded_value['yhat'].apply(lambda x: max(0, math.ceil(x)))
 
 
 
40
 
41
+ return combined_sales, original_forecasted_value, rounded_value
42
 
43
+ def process_product(product_name, data):
44
+ try:
45
+ # Summarize the sales count per month
46
+ data['transaction_date'] = pd.to_datetime(data['transaction_date'])
47
+ data.set_index('transaction_date', inplace=True)
48
+ monthly_sales = data['sell_qty'].resample('M').sum().reset_index()
49
 
50
+ full_trend, forecasted_value, rounded_value = forecast(monthly_sales)
51
+ rounded_value.columns = ["next_month", "y", "predicted_count"]
52
+ # Convert to dictionary
53
+ result_dict = rounded_value.to_dict(orient="records")[0]
54
+
55
+ return {
56
+ "Product Name": product_name,
57
+ "next_month": str(result_dict["next_month"]),
58
+ "predicted_count": result_dict["predicted_count"]
59
+ }
60
+ except Exception as e:
61
+ return {
62
+ "Product Name": product_name,
63
+ "next_month": str(e),
64
+ "predicted_count": "not predicted"
65
+ }
66
 
67
  @app.post("/get_product_count_prediction")
68
  async def get_product_count_prediction(b_id: int):
69
  try:
70
  # main
71
  data, message = dc.get_data(b_id=b_id, product_name="sample")
72
+
73
  if message == "done":
74
 
75
  grouped_df = data.groupby('product_name')
76
 
77
  results = []
78
+ with ThreadPoolExecutor() as executor:
79
+ futures = [executor.submit(process_product, product_name, product_df.copy()) for product_name, product_df in grouped_df]
80
+ for future in as_completed(futures):
81
+ results.append(future.result())
82
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  response_content = {
84
  "status": "success",
85
  "message": "Prediction successful",