albhu commited on
Commit
e554cac
·
verified ·
1 Parent(s): 3cddf46

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -112
app.py CHANGED
@@ -1,139 +1,60 @@
1
  import streamlit as st
2
  import pandas as pd
3
- import datetime
4
  from transformers import AutoTokenizer, AutoModelForTableQuestionAnswering
 
5
  import requests
6
 
7
  class InterestCalculatorApp:
8
  def __init__(self):
9
- self.invoices_df = pd.DataFrame() # Initialize as empty DataFrame
10
- self.base_rates_df = pd.DataFrame() # Initialize as empty DataFrame
11
  self.late_payment_interest = st.sidebar.slider("Late Payment Interest Rate (%)", min_value=0.0, max_value=10.0, value=4.0)
12
- self.compounding_method = st.sidebar.selectbox("Compounding Method", ["x% above Base Rate (daily)",
13
- "x% above Base Rate (annually)",
14
- "Quarterly compounding (25 Mar, 24 Jun, 29 Sep, 25 Dec)",
15
- "Quarterly compounding (1 Mar, 1 Jun, 1 Sep, 1 Dec)"])
 
 
 
 
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:
21
- self.invoices_df = pd.read_excel(file_path, parse_dates=['Due Date'])
 
 
22
  st.success("Invoices loaded successfully.")
23
  except Exception as e:
24
  st.error(f"Failed to load invoices: {e}")
25
 
26
- def calculate_interest(self):
27
- if not self.invoices_df.empty and not self.base_rates_df.empty:
28
- st.write("Calculating interest...")
29
- today = datetime.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.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
  if not isinstance(table, pd.DataFrame):
107
  raise TypeError("Expected the table to be a pd.DataFrame, got {}".format(type(table).__name__))
 
 
108
  inputs = self.tokenizer(table=table, queries=[query], return_tensors="pt", padding=True)
109
  outputs = self.model(**inputs)
110
  predicted_answer = self.tokenizer.decode(outputs.logits.argmax(dim=-1))
111
  return predicted_answer
112
 
113
- def main():
114
- st.title("Interest Calculation App")
115
-
116
- app = InterestCalculatorApp()
117
-
118
- file_path = st.file_uploader("Upload Invoices File", type=["xlsx"])
119
-
120
- if file_path is not None:
121
- app.load_invoices(file_path)
122
-
123
- query = st.text_input("Enter your query:")
124
- if query:
125
- if not app.invoices_df.empty:
126
- st.write("Invoice Data:")
127
- st.write(app.invoices_df)
128
- answer = app.ask_tapas(query, app.invoices_df)
129
- st.write("Answer:", answer)
130
- else:
131
- st.warning("Please upload the invoices file first.")
132
-
133
- if st.button("Calculate Interest"):
134
- app.calculate_interest()
135
-
136
- app.download_boe_rates()
137
 
138
  if __name__ == "__main__":
139
- main()
 
 
1
  import streamlit as st
2
  import pandas as pd
 
3
  from transformers import AutoTokenizer, AutoModelForTableQuestionAnswering
4
+ import datetime
5
  import requests
6
 
7
  class InterestCalculatorApp:
8
  def __init__(self):
9
+ self.invoices_df = pd.DataFrame()
10
+ self.base_rates_df = pd.DataFrame()
11
  self.late_payment_interest = st.sidebar.slider("Late Payment Interest Rate (%)", min_value=0.0, max_value=10.0, value=4.0)
12
+ self.compounding_method = st.sidebar.selectbox(
13
+ "Compounding Method", [
14
+ "x% above Base Rate (daily)",
15
+ "x% above Base Rate (annually)",
16
+ "Quarterly compounding (25 Mar, 24 Jun, 29 Sep, 25 Dec)",
17
+ "Quarterly compounding (1 Mar, 1 Jun, 1 Sep, 1 Dec)"
18
+ ]
19
+ )
20
  self.tokenizer = AutoTokenizer.from_pretrained("google/tapas-large-finetuned-wtq")
21
  self.model = AutoModelForTableQuestionAnswering.from_pretrained("google/tapas-large-finetuned-wtq")
22
 
23
  def load_invoices(self, file_path):
24
  try:
25
+ self.invoices_df = pd.read_excel(file_path, parse_dates=True)
26
+ self.invoices_df = self.invoices_df.fillna('N/A') # Handle missing values
27
+ self.invoices_df = self.invoices_df.applymap(lambda x: str(x).strip() if isinstance(x, str) else str(x))
28
  st.success("Invoices loaded successfully.")
29
  except Exception as e:
30
  st.error(f"Failed to load invoices: {e}")
31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  def ask_tapas(self, query, table):
33
  if not isinstance(table, pd.DataFrame):
34
  raise TypeError("Expected the table to be a pd.DataFrame, got {}".format(type(table).__name__))
35
+
36
+ table = table.applymap(lambda x: str(x) if not pd.isnull(x) else "N/A")
37
  inputs = self.tokenizer(table=table, queries=[query], return_tensors="pt", padding=True)
38
  outputs = self.model(**inputs)
39
  predicted_answer = self.tokenizer.decode(outputs.logits.argmax(dim=-1))
40
  return predicted_answer
41
 
42
+ def main():
43
+ st.title("Interest Calculation App")
44
+ file_path = st.file_uploader("Upload Invoices File", type=["xlsx"])
45
+ if file_path is not None:
46
+ self.load_invoices(file_path)
47
+
48
+ query = st.text_input("Enter your query:")
49
+ if query:
50
+ if not self.invoices_df.empty:
51
+ st.write("Invoice Data:")
52
+ st.dataframe(self.invoices_df)
53
+ answer = self.ask_tapas(query, self.invoices_df)
54
+ st.write("Answer:", answer)
55
+ else:
56
+ st.warning("Please upload the invoices file first.")
 
 
 
 
 
 
 
 
 
57
 
58
  if __name__ == "__main__":
59
+ app = InterestCalculatorApp()
60
+ app.main()