rairo commited on
Commit
cbef1a5
·
verified ·
1 Parent(s): a588d97

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +45 -130
main.py CHANGED
@@ -4,9 +4,7 @@ import os
4
  import io
5
  from flask import Flask, request, jsonify
6
  from flask_cors import CORS, cross_origin
7
- import firebase_admin
8
  import logging
9
- from firebase_admin import credentials, firestore
10
  from dotenv import load_dotenv
11
  from pandasai import SmartDatalake
12
  from pandasai.responses.response_parser import ResponseParser
@@ -14,20 +12,15 @@ from langchain.prompts import PromptTemplate
14
  from langchain.chains import LLMChain
15
  from datetime import datetime
16
  import matplotlib.pyplot as plt
17
- from statsmodels.tsa.holtwinters import ExponentialSmoothing
18
- from prophet import Prophet
19
 
20
  load_dotenv()
21
 
22
  app = Flask(__name__)
23
  cors = CORS(app)
24
 
25
- # Initialize Firebase app
26
- if not firebase_admin._apps:
27
- cred = credentials.Certificate("quant-app-99d09-firebase-adminsdk-6prb1-37f34e1c91.json")
28
- firebase_admin.initialize_app(cred)
29
 
30
- db = firestore.client()
31
 
32
  class FlaskResponse(ResponseParser):
33
  def __init__(self, context) -> None:
@@ -49,140 +42,62 @@ class FlaskResponse(ResponseParser):
49
  return str(result['value'])
50
 
51
  gemini_api_key = os.getenv('Gemini')
52
- llm = ChatGoogleGenerativeAI(api_key=gemini_api_key, model='gemini-1.5-flash-001', temperature=0.1)
53
 
54
- # Endpoint for handling questions to the bot using transaction data
55
- @app.route("/predict", methods=["POST"])
56
- @cross_origin()
57
- def bot():
58
- user_id = request.json.get("user_id")
59
- user_question = request.json.get("user_question")
60
 
61
- inventory_ref = db.collection("system_users").document(user_id).collection('inventory')
62
- tasks_ref = db.collection("system_users").document(user_id).collection('tasks')
63
- transactions_ref = db.collection("system_users").document(user_id).collection('transactions')
64
 
65
- inventory_list = [doc.to_dict() for doc in inventory_ref.stream()]
66
- tasks_list = [doc.to_dict() for doc in tasks_ref.stream()]
67
- transactions_list = [doc.to_dict() for doc in transactions_ref.stream()]
 
 
68
 
69
- inventory_df = pd.DataFrame(inventory_list)
70
- transactions_df = pd.DataFrame(transactions_list)
71
- tasks_df = pd.DataFrame(tasks_list)
 
 
 
 
 
72
 
73
- lake = SmartDatalake([inventory_df, transactions_df, tasks_df], config={"llm": llm, "response_parser": FlaskResponse, "enable_cache": False, "save_logs": False})
74
- response = lake.chat(user_question)
 
 
 
 
 
 
75
  print(user_question)
76
-
77
- return jsonify(str(response))
78
-
79
- # Marketing recommendations endpoint
80
- @app.route("/mrec", methods=["POST"])
 
 
 
 
 
 
81
  @cross_origin()
82
  def marketing_rec():
83
- user_id = request.json.get("user_id")
84
 
85
- transactions_ref = db.collection("system_users").document(user_id).collection('transactions')
86
- transactions_list = [doc.to_dict() for doc in transactions_ref.stream()]
 
 
87
 
88
- transactions_df = pd.DataFrame(transactions_list)
89
- prompt = PromptTemplate.from_template('You are a business analyst. Write a brief analysis and marketing tips for a small business using this transactions data {data_frame}')
90
- chain = LLMChain(llm=llm, prompt=prompt, verbose=True)
91
 
92
- response = chain.invoke(input=transactions_df)
93
- print(response)
94
-
95
- return jsonify(str(response['text']))
96
-
97
-
98
- # Profit/Customer Engagement Prediction endpoint
99
- @app.route("/predict_metric", methods=["POST"])
100
- @cross_origin()
101
- def predict_metric():
102
- request_data = request.json
103
- user_id = request_data.get("user_id")
104
- interval = request_data.get("interval", 30)
105
- metric_type = request_data.get("metric_type", "Profit") # "Profit" or "Customer Engagement"
106
-
107
- transactions_ref = db.collection("system_users").document(user_id).collection("transactions")
108
-
109
- data = []
110
-
111
- if metric_type == "Profit":
112
- # Fetch both Income and Expense transactions for Profit calculation
113
- income_query = transactions_ref.where("transactionType", "==", "Income").stream()
114
- expense_query = transactions_ref.where("transactionType", "==", "Expense").stream()
115
-
116
- income_data = {}
117
- expense_data = {}
118
-
119
- for doc in income_query:
120
- transaction = doc.to_dict()
121
- date_str = transaction["date"]
122
- amount = transaction["amountDue"]
123
- income_data[date_str] = income_data.get(date_str, 0) + amount
124
-
125
- for doc in expense_query:
126
- transaction = doc.to_dict()
127
- date_str = transaction["date"]
128
- amount = transaction["amountDue"]
129
- expense_data[date_str] = expense_data.get(date_str, 0) + amount
130
-
131
- # Calculate net profit for each date
132
- for date, income in income_data.items():
133
- expense = expense_data.get(date, 0)
134
- data.append({"date": date, "amountDue": income - expense})
135
-
136
- elif metric_type == "Customer Engagement":
137
- # Use count of Income transactions per day as Customer Engagement
138
- income_query = transactions_ref.where("transactionType", "==", "Income").stream()
139
-
140
- engagement_data = {}
141
- for doc in income_query:
142
- transaction = doc.to_dict()
143
- date_str = transaction["date"]
144
- engagement_data[date_str] = engagement_data.get(date_str, 0) + 1
145
-
146
- for date, count in engagement_data.items():
147
- data.append({"date": date, "amountDue": count})
148
-
149
- # Create DataFrame from the aggregated data
150
- df = pd.DataFrame(data)
151
-
152
- # Ensure 'date' column is datetime
153
- df['date'] = pd.to_datetime(df['date'])
154
- df['date'] = df['date'].dt.tz_localize(None)
155
-
156
- # Set 'date' as index
157
- df = df.sort_values("date").set_index("date")
158
-
159
- # Resample daily to ensure regular intervals (fill missing dates)
160
- df = df.resample("D").sum().reset_index()
161
-
162
- df.columns = ["ds", "y"] # ds: date, y: target
163
-
164
- # Check if there's enough data to train the model
165
- if df.shape[0] < 10:
166
- return jsonify({"error": "Not enough data for prediction"})
167
-
168
- # Initialize and fit the Prophet model
169
- model = Prophet(daily_seasonality=True, yearly_seasonality=True)
170
- model.fit(df)
171
-
172
- # DataFrame for future predictions
173
- future_dates = model.make_future_dataframe(periods=interval)
174
- forecast = model.predict(future_dates)
175
-
176
- # Extract the forecast for the requested interval
177
- forecast_data = forecast[['ds', 'yhat']].tail(interval)
178
- predictions = [{"date": row['ds'].strftime('%Y-%m-%d'), "value": row['yhat']} for _, row in forecast_data.iterrows()]
179
-
180
- # Return predictions in JSON format
181
- return jsonify({"predictedData": predictions})
182
-
183
-
184
 
185
 
 
186
 
187
 
188
 
 
4
  import io
5
  from flask import Flask, request, jsonify
6
  from flask_cors import CORS, cross_origin
 
7
  import logging
 
8
  from dotenv import load_dotenv
9
  from pandasai import SmartDatalake
10
  from pandasai.responses.response_parser import ResponseParser
 
12
  from langchain.chains import LLMChain
13
  from datetime import datetime
14
  import matplotlib.pyplot as plt
15
+ import google.generativeai as genai
16
+
17
 
18
  load_dotenv()
19
 
20
  app = Flask(__name__)
21
  cors = CORS(app)
22
 
 
 
 
 
23
 
 
24
 
25
  class FlaskResponse(ResponseParser):
26
  def __init__(self, context) -> None:
 
42
  return str(result['value'])
43
 
44
  gemini_api_key = os.getenv('Gemini')
45
+ llm = ChatGoogleGenerativeAI(api_key=gemini_api_key, model='gemini-1.5-flash', temperature=0.1)
46
 
47
+ gemini_api_key = os.environ['Gemini']
 
 
 
 
 
48
 
49
+ genai.configure(api_key=gemini_api_key)
 
 
50
 
51
+ generation_config = {
52
+ "temperature": 0.2,
53
+ "top_p": 0.95,
54
+ "max_output_tokens": 5000,
55
+ }
56
 
57
+ model = genai.GenerativeModel(
58
+ model_name="gemini-1.5-flash",
59
+ generation_config=generation_config,
60
+ )
61
+ # Endpoint for chat
62
+ @app.route("/chat", methods=["POST"])
63
+ @cross_origin()
64
+ def bot():
65
 
66
+ json_table = request.json.get("json_table")
67
+ user_question = request.json.get("user_question")
68
+ #data = request.get_json(force=True)TRye
69
+ #print(req_body)
70
+ #data = eval(req_body)
71
+ #json_table = data["json_table"]
72
+ #user_question = data["user_question"]
73
+ #print(json_table)
74
  print(user_question)
75
+ data = eval(str(json_table))
76
+ df = pd.DataFrame(data)
77
+ print(list(df))
78
+ pandas_agent = SmartDataframe(df,config={"llm":llm, "response_parser":StreamLitResponse})
79
+ answer = pandas_agent.chat(user_question)
80
+ return jsonify(answer)
81
+ return answer
82
+ #df = df.rename(co
83
+
84
+ # Reports endpoint
85
+ @app.route("/report", methods=["POST"])
86
  @cross_origin()
87
  def marketing_rec():
88
+ json_data = request.json.get("json_data")
89
 
90
+ prompt = """
91
+ You are an expert business analyst. Analyze the following data and generate a comprehensive and insightful business report, including appropriate key perfomance indicators and recommendations.
92
+ data:
93
+ """ + str(json_data)
94
 
 
 
 
95
 
96
+ response = model.generate_content(prompt)
97
+ report = response.text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
 
99
 
100
+ return jsonify(str(report))
101
 
102
 
103