File size: 3,978 Bytes
b54df69
 
54e2f2a
73327e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54e2f2a
 
 
 
 
 
 
 
4aa29f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6e934d
54e2f2a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import streamlit as st
import pandas as pd
import openai

# Streamlit App
def main():
    st.title("Invoice Interest Calculator and Conversation")

    # Prompt user for OpenAI API key
    api_key = st.text_input("Enter your OpenAI API key:")

    if api_key:
        # Allow user to upload Excel sheet
        uploaded_file = st.file_uploader("Upload Excel file", type=["xlsx", "xls"])

        if uploaded_file is not None:
            df = pd.read_excel(uploaded_file)

            # Display uploaded data
            st.write("Uploaded Data:")
            st.write(df)

            # Analyze Excel sheet
            due_dates, payment_dates, amounts = analyze_excel(df)

            # Allow user to specify late interest rate
            late_interest_rate = st.number_input("Enter Late Interest Rate (%):", min_value=0.0, max_value=100.0, step=0.1)

            # Calculate late interest if due dates and payment dates are available
            if due_dates and payment_dates:
                # Create DataFrame with extracted due dates, payment dates, and placeholder amount
                df_calculate = pd.DataFrame({
                    'due_date': due_dates,
                    'payment_date': payment_dates,
                    'amount': amounts
                })

                # Calculate late interest
                df_with_interest = calculate_late_interest(df_calculate, late_interest_rate)

                # Display calculated late interest
                total_late_interest = df_with_interest['late_interest'].sum()
                st.write("Calculated Late Interest:")
                st.write(total_late_interest)

            # Generate conversation prompt
            prompt = "I have analyzed the provided Excel sheet. "
            if due_dates:
                prompt += f"The due dates in the sheet are: {', '.join(str(date) for date in due_dates)}. "
            if payment_dates:
                prompt += f"The payment dates in the sheet are: {', '.join(str(date) for date in payment_dates)}. "
            if amounts:
                prompt += f"The amounts in the sheet are: {', '.join(str(amount) for amount in amounts)}. "
            prompt += "Based on this information, what would you like to discuss?"

            # Allow user to engage in conversation
            user_input = st.text_input("Start a conversation:")
            if st.button("Send"):
                openai.api_key = api_key  # Set user-provided OpenAI API key
                
                completion = openai.ChatCompletion.create(
                    model="gpt-3.5-turbo",
                    messages=[
                        {"role": "system", "content": prompt},
                        {"role": "user", "content": user_input}
                    ],
                    max_tokens=1800  # Adjust this value to allow longer responses
                )
                response = completion.choices[0].message['content']
                st.write("AI's Response:")
                st.write(response)
    else:
        st.warning("Please enter your OpenAI API key.")

# Function to calculate late interest
def calculate_late_interest(data, late_interest_rate):
    # Calculate late days and late interest
    data['late_days'] = (data['payment_date'] - data['due_date']).dt.days.clip(lower=0)
    data['late_interest'] = data['late_days'] * data['amount'] * (late_interest_rate / 100)
    return data

# Function to analyze Excel sheet and extract relevant information
def analyze_excel(df):
    # Extract due dates and payment dates
    due_dates = df.iloc[:, 0].dropna().tolist()
    payment_dates = df.iloc[:, 1].dropna().tolist()
    amounts = []

    # Extract and clean amounts from third column
    for amount in df.iloc[:, 2]:
        if isinstance(amount, str):
            amount = amount.replace('"', '').replace(',', '')
        amounts.append(float(amount))

    return due_dates, payment_dates, amounts

if __name__ == "__main__":
    main()