albhu commited on
Commit
54e2f2a
·
verified ·
1 Parent(s): f77b00f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -56
app.py CHANGED
@@ -1,60 +1,60 @@
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(self):
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() # Corrected call
 
1
  import streamlit as st
2
  import pandas as pd
3
+ import openai
4
+
5
+ # Function to calculate late interest
6
+ def calculate_late_interest(data, late_interest_rate):
7
+ # Check if 'due_date' and 'payment_date' columns exist
8
+ if 'due_date' not in data.columns or 'payment_date' not in data.columns:
9
+ st.error("Error: 'due_date' or 'payment_date' columns not found in the uploaded file.")
10
+ return None
11
+
12
+ # Convert 'due_date' and 'payment_date' to datetime
13
+ data['due_date'] = pd.to_datetime(data['due_date'], errors='coerce')
14
+ data['payment_date'] = pd.to_datetime(data['payment_date'], errors='coerce')
15
+
16
+ # Calculate late days and late interest
17
+ data['late_days'] = (data['payment_date'] - data['due_date']).dt.days.clip(lower=0)
18
+ data['late_interest'] = data['late_days'] * data['amount'] * (late_interest_rate / 100)
19
+ return data
20
+
21
+ # Streamlit App
22
+ def main():
23
+ st.title("Invoice Interest Calculator and Conversation")
24
+
25
+ # Allow user to upload Excel sheet
26
+ uploaded_file = st.file_uploader("Upload Excel file", type=["xlsx", "xls"])
27
+
28
+ if uploaded_file is not None:
29
+ df = pd.read_excel(uploaded_file)
30
+
31
+ # Display uploaded data
32
+ st.write("Uploaded Data:")
33
+ st.write(df)
34
+
35
+ # Allow user to specify late interest rate
36
+ late_interest_rate = st.number_input("Enter Late Interest Rate (%):", min_value=0.0, max_value=100.0, step=0.1)
37
+
38
+ # Analyze data and calculate late interest
39
+ df_with_interest = calculate_late_interest(df, late_interest_rate)
40
+
41
+ if df_with_interest is not None:
42
+ # Display analyzed data
43
+ st.write("Data with Late Interest Calculated:")
44
+ st.write(df_with_interest)
45
+
46
+ # Allow user to engage in conversation
47
+ user_input = st.text_input("Start a conversation:")
48
+ if st.button("Send"):
49
+ openai.api_key = api_key # Set OpenAI API key
50
+ completion = openai.Completion.create(
51
+ engine="davinci-codex",
52
+ prompt=user_input,
53
+ max_tokens=100
54
+ )
55
+ response = completion.choices[0].text.strip()
56
+ st.write("AI's Response:")
57
+ st.write(response)
58
 
59
  if __name__ == "__main__":
60
+ main()