albhu commited on
Commit
e8ce164
·
verified ·
1 Parent(s): f83ff36

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -14
app.py CHANGED
@@ -12,7 +12,7 @@ def main():
12
 
13
  if api_key:
14
  # Download BOE rates
15
- download_boe_rates()
16
 
17
  # Allow user to upload Excel sheet
18
  uploaded_file = st.file_uploader("Upload Excel file", type=["xlsx", "xls"])
@@ -40,7 +40,7 @@ def main():
40
  })
41
 
42
  # Calculate late interest
43
- df_with_interest = calculate_late_interest(df_calculate, late_interest_rate)
44
 
45
  # Display calculated late interest
46
  total_late_interest = df_with_interest['late_interest'].sum()
@@ -48,14 +48,7 @@ def main():
48
  st.write(total_late_interest)
49
 
50
  # Generate conversation prompt
51
- prompt = "I have analyzed the provided Excel sheet. "
52
- if due_dates:
53
- prompt += f"The due dates in the sheet are: {', '.join(str(date) for date in due_dates)}. "
54
- if payment_dates:
55
- prompt += f"The payment dates in the sheet are: {', '.join(str(date) for date in payment_dates)}. "
56
- if amounts:
57
- prompt += f"The amounts in the sheet are: {', '.join(str(amount) for amount in amounts)}. "
58
- prompt += "Based on this information, what would you like to discuss?"
59
 
60
  # Allow user to engage in conversation
61
  user_input = st.text_input("Start a conversation:")
@@ -68,7 +61,7 @@ def main():
68
  {"role": "system", "content": prompt},
69
  {"role": "user", "content": user_input}
70
  ],
71
- max_tokens=1800
72
  )
73
  response = completion.choices[0].message['content']
74
  st.write("AI's Response:")
@@ -76,18 +69,50 @@ def main():
76
  else:
77
  st.warning("Please enter your OpenAI API key.")
78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  # Function to calculate late interest
80
- def calculate_late_interest(data, late_interest_rate):
 
 
 
 
81
  # Calculate late days and late interest
82
  data['late_days'] = (data['payment_date'] - data['due_date']).dt.days.clip(lower=0)
83
  data['late_interest'] = data['late_days'] * data['amount'] * (late_interest_rate / 100)
 
 
 
 
 
 
84
  return data
85
 
86
  # Function to analyze Excel sheet and extract relevant information
87
  def analyze_excel(df):
88
  # Extract due dates and payment dates
89
- due_dates = df.iloc[:, 0].dropna().tolist()
90
- payment_dates = df.iloc[:, 1].dropna().tolist()
91
  amounts = []
92
 
93
  # Extract and clean amounts from third column
@@ -111,10 +136,18 @@ def download_boe_rates():
111
  df = pd.read_html(response.text)[0]
112
  df.to_csv('boe_rates.csv', index=False)
113
  st.success("Bank of England rates downloaded successfully.")
 
114
  else:
115
  st.error("Failed to retrieve data from the Bank of England website.")
 
116
  except requests.RequestException as e:
117
  st.error(f"Failed to download rates: {e}")
 
 
 
 
 
 
118
 
119
  if __name__ == "__main__":
120
  main()
 
12
 
13
  if api_key:
14
  # Download BOE rates
15
+ boe_rates_df = download_boe_rates()
16
 
17
  # Allow user to upload Excel sheet
18
  uploaded_file = st.file_uploader("Upload Excel file", type=["xlsx", "xls"])
 
40
  })
41
 
42
  # Calculate late interest
43
+ df_with_interest = calculate_late_interest(df_calculate, late_interest_rate, boe_rates_df)
44
 
45
  # Display calculated late interest
46
  total_late_interest = df_with_interest['late_interest'].sum()
 
48
  st.write(total_late_interest)
49
 
50
  # Generate conversation prompt
51
+ prompt = generate_conversation_prompt(df, boe_rates_df)
 
 
 
 
 
 
 
52
 
53
  # Allow user to engage in conversation
54
  user_input = st.text_input("Start a conversation:")
 
61
  {"role": "system", "content": prompt},
62
  {"role": "user", "content": user_input}
63
  ],
64
+ max_tokens=1800 # Adjust this value to allow longer responses
65
  )
66
  response = completion.choices[0].message['content']
67
  st.write("AI's Response:")
 
69
  else:
70
  st.warning("Please enter your OpenAI API key.")
71
 
72
+ # Function to generate conversation prompt
73
+ def generate_conversation_prompt(df, boe_rates_df):
74
+ prompt = "I have analyzed the provided Excel sheet. "
75
+
76
+ # Include due dates, payment dates, and amounts from the Excel sheet
77
+ due_dates = df['due_date'].tolist()
78
+ payment_dates = df['payment_date'].tolist()
79
+ amounts = df['amount'].tolist()
80
+ prompt += f"The due dates in the sheet are: {', '.join(str(date) for date in due_dates)}. "
81
+ prompt += f"The payment dates in the sheet are: {', '.join(str(date) for date in payment_dates)}. "
82
+ prompt += f"The amounts in the sheet are: {', '.join(str(amount) for amount in amounts)}. "
83
+
84
+ # Include Bank of England base rates
85
+ if boe_rates_df is not None:
86
+ prompt += "The Bank of England base rates are as follows: \n"
87
+ for index, row in boe_rates_df.iterrows():
88
+ prompt += f"On {row['Date Changed']}, the base rate was {row['Current Bank Rate']}. \n"
89
+
90
+ prompt += "Based on this information, what would you like to discuss?"
91
+
92
+ return prompt
93
+
94
  # Function to calculate late interest
95
+ def calculate_late_interest(data, late_interest_rate, boe_rates_df):
96
+ # Convert due_date column to Timestamp objects
97
+ data['due_date'] = pd.to_datetime(data['due_date'])
98
+ data['payment_date'] = pd.to_datetime(data['payment_date'])
99
+
100
  # Calculate late days and late interest
101
  data['late_days'] = (data['payment_date'] - data['due_date']).dt.days.clip(lower=0)
102
  data['late_interest'] = data['late_days'] * data['amount'] * (late_interest_rate / 100)
103
+
104
+ # Consider additional factors like Bank of England base rate
105
+ if boe_rates_df is not None:
106
+ data['boe_base_rate'] = data['due_date'].map(lambda x: get_boe_base_rate(x, boe_rates_df))
107
+ data['late_interest'] += data['amount'] * (data['boe_base_rate'] / 100)
108
+
109
  return data
110
 
111
  # Function to analyze Excel sheet and extract relevant information
112
  def analyze_excel(df):
113
  # Extract due dates and payment dates
114
+ due_dates = pd.to_datetime(df.iloc[:, 0], errors='coerce').dropna() # Convert to datetime and drop NaT values
115
+ payment_dates = pd.to_datetime(df.iloc[:, 1], errors='coerce').dropna() # Convert to datetime and drop NaT values
116
  amounts = []
117
 
118
  # Extract and clean amounts from third column
 
136
  df = pd.read_html(response.text)[0]
137
  df.to_csv('boe_rates.csv', index=False)
138
  st.success("Bank of England rates downloaded successfully.")
139
+ return df # Return the downloaded data
140
  else:
141
  st.error("Failed to retrieve data from the Bank of England website.")
142
+ return None
143
  except requests.RequestException as e:
144
  st.error(f"Failed to download rates: {e}")
145
+ return None
146
+
147
+ def get_boe_base_rate(date, boe_rates_df):
148
+ closest_date_index = (boe_rates_df['Date Changed'] - pd.Timestamp(date)).abs().argsort()[0]
149
+ closest_date = boe_rates_df['Date Changed'].iloc[closest_date_index]
150
+ return boe_rates_df.loc[closest_date_index, 'Current Bank Rate']
151
 
152
  if __name__ == "__main__":
153
  main()