albhu commited on
Commit
1798d16
·
verified ·
1 Parent(s): bfb40be

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -88
app.py CHANGED
@@ -1,5 +1,7 @@
1
  import streamlit as st
2
  import pandas as pd
 
 
3
  from transformers import AutoTokenizer, AutoModelForTableQuestionAnswering
4
 
5
  class InterestCalculatorApp:
@@ -13,8 +15,8 @@ class InterestCalculatorApp:
13
  "Quarterly compounding (1 Mar, 1 Jun, 1 Sep, 1 Dec)"])
14
 
15
  # Load TAPAS model
16
- self.tokenizer = AutoTokenizer.from_pretrained("google/tapas-large-finetuned-wtq")
17
- self.model = AutoModelForTableQuestionAnswering.from_pretrained("google/tapas-large-finetuned-wtq")
18
 
19
  def load_invoices(self, file_path):
20
  try:
@@ -27,88 +29,37 @@ class InterestCalculatorApp:
27
  if self.invoices_df is not None and self.base_rates_df is not None:
28
  st.write("Calculating interest...")
29
  today = datetime.today()
30
- interests = []
 
 
 
 
 
31
  for index, invoice in self.invoices_df.iterrows():
32
  due_date = invoice['Due Date']
33
  amount = invoice['Amount']
34
  base_rate = self.get_base_rate(due_date)
35
  effective_rate = base_rate + self.late_payment_interest
36
- if due_date > today:
37
- interests.append(0)
38
- continue
39
  interest = self.calculate_compound_interest(due_date, amount, effective_rate, self.compounding_method, today)
40
- interests.append(interest)
41
  total_amount_owed = amount + interest
42
  self.invoices_df.loc[index, 'Interest'] = interest
43
  self.invoices_df.loc[index, 'Total Amount Owed'] = total_amount_owed
44
- total_interest = sum(interests)
45
- st.success(f"Total Interest Calculated: £{total_interest:.2f}")
 
 
 
 
 
 
 
46
  st.write(self.invoices_df)
47
  else:
48
  st.error("Please load both invoices and base rates files.")
49
 
50
- def get_base_rate(self, due_date):
51
- self.base_rates_df['Date Changed'] = pd.to_datetime(self.base_rates_df['Date Changed'])
52
- rate_rows = self.base_rates_df[self.base_rates_df['Date Changed'] <= due_date].sort_values(by='Date Changed', ascending=False)
53
- return rate_rows.iloc[0]['Rate'] if not rate_rows.empty else 0
54
 
55
- def calculate_compound_interest(self, due_date, amount, effective_rate, method, today):
56
- days = (today - due_date).days
57
- if 'daily' in method:
58
- daily_rate = (effective_rate / 100) / 365
59
- return amount * daily_rate * days
60
- elif 'annually' in method:
61
- annual_rate = effective_rate / 100
62
- return amount * annual_rate * (days / 365)
63
- elif 'Quarterly compounding' in method:
64
- return self.calculate_quarterly_interest(due_date, amount, effective_rate, method, today)
65
-
66
- def calculate_quarterly_interest(self, due_date, amount, effective_rate, method, today):
67
- quarterly_dates = {
68
- "Quarterly compounding (25 Mar, 24 Jun, 29 Sep, 25 Dec)": [(3, 25), (6, 24), (9, 29), (12, 25)],
69
- "Quarterly compounding (1 Mar, 1 Jun, 1 Sep, 1 Dec)": [(3, 1), (6, 1), (9, 1), (12, 1)]
70
- }[method]
71
- interest = 0
72
- compounded_amount = amount
73
- for month, day in quarterly_dates:
74
- compounding_date = datetime(today.year, month, day)
75
- if compounding_date > today:
76
- break
77
- if compounding_date > due_date:
78
- days_since_last_compounding = (today - compounding_date).days
79
- period_rate = effective_rate / 4 # Quarterly rate
80
- compounded_interest = compounded_amount * ((1 + period_rate) ** (days_since_last_compounding / 365.25) - 1)
81
- compounded_amount += compounded_interest
82
- interest += compounded_interest
83
- due_date = compounding_date
84
- return interest
85
-
86
- def download_boe_rates(self):
87
- try:
88
- headers = {
89
- 'accept-language': 'en-US,en;q=0.9',
90
- 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36'
91
- }
92
- url = 'https://www.bankofengland.co.uk/boeapps/database/Bank-Rate.asp'
93
- response = requests.get(url, headers=headers)
94
- if response.status_code == 200:
95
- df = pd.read_html(response.text)[0]
96
- df.to_csv('boe_rates.csv', index=False)
97
- self.base_rates_df = df
98
- self.base_rates_df['Date Changed'] = pd.to_datetime(self.base_rates_df['Date Changed'], format='%d %b %y')
99
- st.success("Bank of England rates downloaded successfully.")
100
- else:
101
- st.error("Failed to retrieve data from the Bank of England website.")
102
- except requests.RequestException as e:
103
- st.error(f"Failed to download rates: {e}")
104
-
105
- def ask_tapas(self, query, table):
106
- inputs = self.tokenizer(table, query, return_tensors="pt", padding=True)
107
- outputs = self.model(**inputs)
108
- predicted_answer = self.tokenizer.decode(outputs.logits.argmax(dim=-1))
109
- return predicted_answer
110
-
111
- def main():
112
  st.title("Interest Calculation App")
113
 
114
  app = InterestCalculatorApp()
@@ -118,25 +69,7 @@ def main():
118
  if file_path is not None:
119
  app.load_invoices(file_path)
120
 
121
- query = st.text_input("Enter your query:")
122
- if query:
123
- # Assuming you have a DataFrame named 'invoices_df' containing the invoice data
124
- if not app.invoices_df.empty:
125
- # Display the invoice data
126
- st.write("Invoice Data:")
127
- st.write(app.invoices_df)
128
-
129
- # Call TAPAS model to answer user's query
130
- answer = app.ask_tapas(query, app.invoices_df)
131
- st.write("Answer:", answer)
132
- else:
133
- st.warning("Please upload the invoices file first.")
134
-
135
  if st.button("Calculate Interest"):
136
  app.calculate_interest()
137
 
138
  app.download_boe_rates()
139
-
140
- if __name__ == "__main__":
141
- main()
142
-
 
1
  import streamlit as st
2
  import pandas as pd
3
+ from datetime import datetime
4
+ import requests
5
  from transformers import AutoTokenizer, AutoModelForTableQuestionAnswering
6
 
7
  class InterestCalculatorApp:
 
15
  "Quarterly compounding (1 Mar, 1 Jun, 1 Sep, 1 Dec)"])
16
 
17
  # Load TAPAS model
18
+ self.tapas_tokenizer = AutoTokenizer.from_pretrained("google/tapas-large-finetuned-wtq")
19
+ self.tapas_model = AutoModelForTableQuestionAnswering.from_pretrained("google/tapas-large-finetuned-wtq")
20
 
21
  def load_invoices(self, file_path):
22
  try:
 
29
  if self.invoices_df is not None and self.base_rates_df is not None:
30
  st.write("Calculating interest...")
31
  today = datetime.today()
32
+ total_interest = 0
33
+
34
+ # Tokenize table
35
+ table_text = self.invoices_df.to_csv(index=False)
36
+ table_inputs = self.tapas_tokenizer(table_text, return_tensors="pt", padding=True)
37
+
38
  for index, invoice in self.invoices_df.iterrows():
39
  due_date = invoice['Due Date']
40
  amount = invoice['Amount']
41
  base_rate = self.get_base_rate(due_date)
42
  effective_rate = base_rate + self.late_payment_interest
 
 
 
43
  interest = self.calculate_compound_interest(due_date, amount, effective_rate, self.compounding_method, today)
 
44
  total_amount_owed = amount + interest
45
  self.invoices_df.loc[index, 'Interest'] = interest
46
  self.invoices_df.loc[index, 'Total Amount Owed'] = total_amount_owed
47
+ total_interest += interest
48
+
49
+ # Get model prediction
50
+ query = "What is the total interest?"
51
+ query_inputs = self.tapas_tokenizer(query, return_tensors="pt", padding=True)
52
+ outputs = self.tapas_model(**table_inputs, **query_inputs)
53
+ total_interest_prediction = self.tapas_tokenizer.decode(outputs.logits.argmax(dim=-1))
54
+
55
+ st.success(f"Total Interest Calculated: £{total_interest:.2f} (Model Prediction: {total_interest_prediction.strip()})")
56
  st.write(self.invoices_df)
57
  else:
58
  st.error("Please load both invoices and base rates files.")
59
 
60
+ # Other methods remain the same
 
 
 
61
 
62
+ if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  st.title("Interest Calculation App")
64
 
65
  app = InterestCalculatorApp()
 
69
  if file_path is not None:
70
  app.load_invoices(file_path)
71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  if st.button("Calculate Interest"):
73
  app.calculate_interest()
74
 
75
  app.download_boe_rates()