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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -29
app.py CHANGED
@@ -1,23 +1,30 @@
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")
@@ -32,29 +39,56 @@ def main():
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()
 
1
  import streamlit as st
2
  import pandas as pd
3
  import openai
4
+ from dateutil import parser
5
 
6
  # Function to calculate late interest
7
  def calculate_late_interest(data, late_interest_rate):
 
 
 
 
 
 
 
 
 
8
  # Calculate late days and late interest
9
  data['late_days'] = (data['payment_date'] - data['due_date']).dt.days.clip(lower=0)
10
  data['late_interest'] = data['late_days'] * data['amount'] * (late_interest_rate / 100)
11
  return data
12
 
13
+ # Function to analyze Excel sheet and extract relevant information
14
+ def analyze_excel(df):
15
+ # Extract due dates and payment dates
16
+ due_dates = df.iloc[:, 0].dropna().tolist()
17
+ payment_dates = df.iloc[:, 1].dropna().tolist()
18
+ amounts = []
19
+
20
+ # Extract and clean amounts from third column
21
+ for amount in df.iloc[:, 2]:
22
+ if isinstance(amount, str):
23
+ amount = amount.replace('"', '').replace(',', '')
24
+ amounts.append(float(amount))
25
+
26
+ return due_dates, payment_dates, amounts
27
+
28
  # Streamlit App
29
  def main():
30
  st.title("Invoice Interest Calculator and Conversation")
 
39
  st.write("Uploaded Data:")
40
  st.write(df)
41
 
42
+ # Analyze Excel sheet
43
+ due_dates, payment_dates, amounts = analyze_excel(df)
44
+
45
  # Allow user to specify late interest rate
46
  late_interest_rate = st.number_input("Enter Late Interest Rate (%):", min_value=0.0, max_value=100.0, step=0.1)
47
 
48
+ # Calculate late interest if due dates and payment dates are available
49
+ if due_dates and payment_dates:
50
+ # Create DataFrame with extracted due dates, payment dates, and placeholder amount
51
+ df_calculate = pd.DataFrame({
52
+ 'due_date': due_dates,
53
+ 'payment_date': payment_dates,
54
+ 'amount': [0] * len(due_dates) # Placeholder amount for calculation
55
+ })
56
+
57
+ # Calculate late interest
58
+ df_with_interest = calculate_late_interest(df_calculate, late_interest_rate)
59
+
60
+ # Display calculated late interest
61
+ st.write("Calculated Late Interest:")
62
+ st.write(df_with_interest['late_interest'].sum())
63
+
64
+ # Generate conversation prompt
65
+ prompt = "I have analyzed the provided Excel sheet. "
66
+ if due_dates:
67
+ prompt += f"The due dates in the sheet are: {', '.join(str(date) for date in due_dates)}. "
68
+ if payment_dates:
69
+ prompt += f"The payment dates in the sheet are: {', '.join(str(date) for date in payment_dates)}. "
70
+ if amounts:
71
+ prompt += f"The amounts in the sheet are: {', '.join(str(amount) for amount in amounts)}. "
72
+ prompt += "Based on this information, what would you like to discuss?"
73
+
74
+ # Allow user to engage in conversation
75
+ user_input = st.text_input("Start a conversation:")
76
+ if st.button("Send"):
77
+ if 'api_key' not in st.session_state:
78
+ st.session_state.api_key = st.text_input("Enter your OpenAI API key:")
79
+ openai.api_key = st.session_state.api_key # Set OpenAI API key
80
+
81
+ completion = openai.ChatCompletion.create(
82
+ model="gpt-3.5-turbo",
83
+ messages=[
84
+ {"role": "system", "content": prompt},
85
+ {"role": "user", "content": user_input}
86
+ ],
87
+ max_tokens=800 # Adjust this value to allow longer responses
88
+ )
89
+ response = completion.choices[0].message['content']
90
+ st.write("AI's Response:")
91
+ st.write(response)
92
 
93
  if __name__ == "__main__":
94
  main()