File size: 6,673 Bytes
0106d5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
import streamlit as st
import io
from utils import mock_api_call, parse_analysis_response, validate_pdf, displayPDF
from styles import apply_custom_styles, show_factor_section, show_detailed_factors, show_factor_summary

from policy_analyser.analyse import analyse

def main():
    # Apply custom styles
    apply_custom_styles()

    # Header
    st.markdown("""
        <div class="header-container">
            <img src="https://acko-brand.ackoassets.com/brand/vector-svg/gradient/horizontal-reverse.svg" height=50 width=100>
                <h1>Insurance Policy Analyzer</h1>
            <p>Upload and compare insurance policies</p>
        </div>
    """, unsafe_allow_html=True)

    # File upload section
    st.markdown('<div class="upload-container">', unsafe_allow_html=True)
    uploaded_files = st.file_uploader("Choose policy PDF files", type="pdf", accept_multiple_files=True)
    st.markdown('</div>', unsafe_allow_html=True)

    if uploaded_files:
        # Create tabs for different views
        tab1, tab2 = st.tabs(["Summary View", "Detailed Comparison"])

        # Store analysis results
        all_analyses = []

        # Process each uploaded file
        for uploaded_file in uploaded_files:
            # Read PDF content
            pdf_bytes = uploaded_file.read()
            # displayPDF(pdf_bytes)

            # Validate PDF
            if not validate_pdf(pdf_bytes):
                st.error(f"Invalid PDF file: {uploaded_file.name}")
                continue

            # Show loading state
            with st.spinner(f"Analyzing {uploaded_file.name}..."):
                try:
                    # Make API call
                    response = analyse(pdf_bytes)
                    print(response)
                    summary = next(
                        (item for item in response if item.get("stage") == "ANALYSIS_SUMMARY"), None
                    )['response']

                    # Parse response
                    good_factors, average_factors, bad_factors = parse_analysis_response(response)

                    # Store results
                    all_analyses.append({
                        'name': uploaded_file.name,
                        'good_factors': good_factors,
                        'average_factors': average_factors,
                        'bad_factors': bad_factors
                    })

                except Exception as e:
                    st.error(f"Error analyzing {uploaded_file.name}: {str(e)}")

        # Summary View Tab
        with tab1:
            for idx, analysis in enumerate(all_analyses):
                with st.expander(f"### Policy {idx + 1}: {analysis['name']}"):
                    with st.container():
                        cols = st.columns(2)
                        displayed = 0
                        for verdict in ['Good', 'Average', 'Bad']:
                            lst = [f.split(':')[0] for f in analysis[f'{verdict.lower()}_factors']]
                            if len(lst) > 0:
                                title = f'{verdict} Factors'
                                if verdict == 'Good':
                                    title += '✅'
                                    sentiment = 'Yay!'
                                elif verdict == 'Average':
                                    title += '⚠️'
                                    sentiment = 'Hmmmm'
                                else:
                                    title += '❌'
                                    sentiment = 'Meh'
                                cols = st.columns(2)
                                with st.container():
                                    with cols[0]:
                                        if displayed % 3 == 0:
                                            show_factor_section(title, lst, verdict.lower())
                                        else:
                                            show_factor_summary(summary[verdict], verdict.lower(), sentiment)
                                    with cols[1]:
                                        if displayed % 3 == 0:
                                            show_factor_summary(summary[verdict], verdict.lower(), sentiment)
                                        else:
                                            show_factor_section(title, lst, verdict.lower())
                                displayed += 1

                    st.markdown('-----')
                    # with st.container():
                        # suggestion = next((item for item in response if item.get("stage") == "SUGGEST"), None)['response']
                        # show_factor_summary(suggestion, 'Good', 'What we have ⛑️')

        # Detailed Comparison Tab
        with tab2:
            if len(all_analyses) > 1:
                # Create comparison matrix
                factors_to_compare = set()
                for analysis in all_analyses:
                    factors_to_compare.update(
                        [f.split(':')[0] for f in analysis['good_factors'] + 
                         analysis['average_factors'] + analysis['bad_factors']]
                    )

                # Create comparison table
                st.markdown("### Policy Comparison Matrix")

                comparison_data = []
                for factor in sorted(factors_to_compare):
                    row = {'Factor': factor}
                    for idx, analysis in enumerate(all_analyses):
                        policy_name = f"Policy {idx + 1}"
                        verdict = 'Not Found'
                        for category in ['good_factors', 'average_factors', 'bad_factors']:
                            for item in analysis[category]:
                                if item.split(':')[0] == factor:
                                    verdict = category.split('_')[0].title()
                                    break
                        row[policy_name] = verdict
                    comparison_data.append(row)

                # Display comparison table
                st.table(comparison_data)
            else:
                st.info("Upload multiple policies to see comparison")

    # Footer
    st.markdown("""
        <div style="margin-top: 50px; text-align: center; color: #666;">
            <p>Upload one or more insurance policy PDFs to get detailed analysis and comparison.</p>
            <p>We support all major insurance providers.</p>
        </div>
    """, unsafe_allow_html=True)

if __name__ == "__main__":
    st.set_page_config(
        page_title="Insurance Policy Analyzer",
        page_icon="📋",
        layout="wide"
    )
    main()