File size: 16,207 Bytes
83fb89d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b528057
83fb89d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
import streamlit as st
import pandas as pd
import os
import re
import json
from PIL import Image
from datetime import datetime
from google.cloud import vision
from google.oauth2 import service_account

st.set_page_config(layout="wide")

import database as db 

GCP_SERVICE_ACCOUNT_JSON = os.getenv("GCP_SERVICE_ACCOUNT_JSON")

def get_vision_client():
    if not GCP_SERVICE_ACCOUNT_JSON:
        raise Exception("GCP service account JSON is missing. Check your environment variables.")
    credentials_dict = json.loads(GCP_SERVICE_ACCOUNT_JSON)
    credentials = service_account.Credentials.from_service_account_info(credentials_dict)
    return vision.ImageAnnotatorClient(credentials=credentials)

client = get_vision_client()

def parse_description(description):
    """
    A naive regex approach that grabs lines containing $XX.XX 
    and pairs them with the line above as the item name.
    """
    lines = description.split("\n")
    items = []
    price_pattern = r"\$(\d+\.\d{2})"

    for i in range(1, len(lines)):
        line = lines[i].strip()
        prev_line = lines[i - 1].strip()
        match = re.search(price_pattern, line)
        if match:
            item_name = prev_line
            price = float(match.group(1))
            items.append({"name": item_name, "price": price})

    return items

def extract_invoice_data(image_data: bytes):
    """
    Calls Google Vision to detect text from the uploaded image bytes,
    then uses parse_description to produce a list of item dicts.
    """
    image = vision.Image(content=image_data)
    response = client.text_detection(image=image)
    if response.error.message:
        raise Exception(f"Vision API Error: {response.error.message}")

    response_dict = vision.AnnotateImageResponse.to_dict(response)
    annotations = response_dict.get("text_annotations", [])
    if not annotations:
        return []

    description = annotations[0]["description"]
    return parse_description(description)

def load_existing_data():
    if 'logged_in' not in st.session_state:
        st.session_state['logged_in'] = False
    if 'email' not in st.session_state:
        st.session_state['email'] = None
    if 'section' not in st.session_state:
        st.session_state['section'] = None
    if 'participants' not in st.session_state:
        st.session_state['participants'] = []
    if 'items' not in st.session_state:
        st.session_state['items'] = []
    if 'selected_items' not in st.session_state:
        st.session_state['selected_items'] = []
    if 'submitted_items' not in st.session_state:
        st.session_state['submitted_items'] = []
    if 'submitted' not in st.session_state:
        st.session_state['submitted'] = False
    if 'sections_loaded' not in st.session_state:
        st.session_state['sections_loaded'] = False
    if 'existing_sections' not in st.session_state:
        st.session_state['existing_sections'] = []

def load_section_from_db(section_name):
    owner_email = st.session_state['email']
    section_doc = db.get_section(owner_email, section_name)
    if section_doc:
        st.session_state['section'] = section_name
        st.session_state['participants'] = section_doc['participants']
        st.session_state['items'] = []
        st.session_state['selected_items'] = []
        st.session_state['submitted_items'] = []
        st.session_state['submitted'] = False

def save_section_to_db(section_name, participants):
    owner_email = st.session_state['email']
    db.update_section(owner_email, section_name, participants)

def update_submitted_items():
    owner_email = st.session_state['email']
    section_name = st.session_state['section']
    st.session_state['submitted_items'] = db.get_submitted_items(owner_email, section_name)

def get_most_bought_item():
    owner_email = st.session_state['email']
    section_name = st.session_state['section']
    return db.get_most_bought_item(owner_email, section_name)

def main():
    load_existing_data()
    st.title("EzSplit - Scan. Split. Quit Arguing.")

    if not st.session_state['logged_in']:
        tab1, tab2 = st.tabs(["Login", "Sign Up"])

        with tab1:
            st.header("Login")
            email = st.text_input("Email")
            password = st.text_input("Password", type="password")
            if st.button("Login"):
                user_doc = db.get_user_by_email_and_password(email, password)
                if user_doc:
                    st.session_state['logged_in'] = True
                    st.session_state['email'] = email
                    st.rerun()
                else:
                    st.error("Invalid email or password")

        with tab2:
            st.header("Sign Up")
            signup_email = st.text_input("New Email")
            signup_password = st.text_input("New Password", type="password")
            confirm_password = st.text_input("Confirm Password", type="password")
            if st.button("Sign Up"):
                if signup_password == confirm_password:
                    try:
                        db.create_user(signup_email, signup_password)
                        st.success("Sign up successful! Please log in.")
                    except ValueError:
                        st.error("Email already exists")
                else:
                    st.error("Passwords do not match")

    else:
        with st.sidebar:
            st.write(f"Welcome, {st.session_state['email']}")
            if st.button("Sign Out"):
                st.session_state.clear()
                st.rerun()

            st.header("Billing Sections")

            if not st.session_state['sections_loaded']:
                owner_email = st.session_state['email']
                existing_sections = db.get_all_sections(owner_email)
                st.session_state['sections_loaded'] = True
                st.session_state['existing_sections'] = existing_sections

            section_name = st.radio("Select a section",
                                    ["Create New"] + st.session_state['existing_sections'])

            if section_name == "Create New":
                new_section_name = st.text_input("New Section Name")
                participants_str = st.text_area("Participants (comma-separated)")
                if st.button("Create Section"):
                    try:
                        participants_list = [p.strip() for p in participants_str.split(",") if p.strip()]
                        db.create_section(st.session_state['email'], new_section_name, participants_list)
                        st.session_state['section'] = new_section_name
                        st.session_state['participants'] = participants_list
                        st.session_state['items'] = []
                        st.session_state['selected_items'] = []
                        st.session_state['submitted_items'] = []
                        st.session_state['submitted'] = False
                        st.session_state['existing_sections'].append(new_section_name)
                        st.rerun()
                    except ValueError as e:
                        st.error(str(e))
            else:
                if st.button("Load Section"):
                    load_section_from_db(section_name)
                    update_submitted_items()
                    st.rerun()

                if st.button("Delete Section"):
                    db.delete_section(st.session_state['email'], section_name)
                    st.session_state['existing_sections'].remove(section_name)
                    if st.session_state['section'] == section_name:
                        st.session_state['section'] = None
                        st.session_state['participants'] = []
                        st.session_state['items'] = []
                        st.session_state['selected_items'] = []
                        st.session_state['submitted_items'] = []
                        st.session_state['submitted'] = False
                    st.rerun()

        if st.session_state['section'] and st.session_state['participants']:
            col1, col2 = st.columns([3, 1])

            with col1:
                st.subheader(f"Section: {st.session_state['section']}")
                st.write("Participants: " + ", ".join(st.session_state['participants']))

                st.subheader("Bill Image (OCR)")
                uploaded_file = st.file_uploader("Upload a bill image (jpg, jpeg, png)",
                                                 type=["jpg", "jpeg", "png"])

                if uploaded_file is not None:
                    if st.button("Extract Items via OCR"):
                        try:
                            image_data = uploaded_file.read()
                            ocr_items = extract_invoice_data(image_data)
                            if ocr_items:
                                st.session_state['items'].extend(ocr_items)
                                st.success("OCR extraction successful. Items appended.")
                            else:
                                st.warning("No items found in the extracted text.")
                        except Exception as e:
                            st.error(f"OCR failed: {e}")

                st.subheader("Manual Item Entry")
                manual_item_name = st.text_input("Item Name", key="manual_item_name")
                manual_item_price = st.number_input("Item Price", min_value=0.0, step=0.01, key="manual_item_price")

                if st.button("Add Item Manually"):
                    if manual_item_name.strip():
                        st.session_state['items'].append({
                            "name": manual_item_name.strip(),
                            "price": manual_item_price
                        })
                        st.success(f"Added '{manual_item_name}' at ${manual_item_price:.2f}")
                    else:
                        st.warning("Please provide a non-empty item name.")

                st.subheader("Available Items")
                if st.session_state['items']:
                    st.write([f"{itm['name']} (${itm['price']})" for itm in st.session_state['items']])
                else:
                    st.write("No items found yet.")

                if st.session_state['items']:
                    not_submitted = [
                        itm["name"] for itm in st.session_state['items']
                        if itm["name"] not in st.session_state['submitted_items']
                    ]
                    selected_items = st.multiselect("Select Items to Tag", not_submitted, key="item_select")
                    
                    if st.button("Tag Selected Items"):
                        st.session_state['selected_items'] = selected_items
                        st.session_state['submitted'] = True

                if st.session_state['submitted'] and st.session_state['selected_items']:
                    chosen_participant = st.selectbox("Participant to Assign Items",
                                                      st.session_state['participants'],
                                                      key="participant_select")

                    if st.button("Confirm Assignment"):
                        for it in st.session_state['items']:
                            if it['name'] in st.session_state['selected_items']:
                                db.create_bill(
                                    owner_email=st.session_state['email'],
                                    section_name=st.session_state['section'],
                                    participant=chosen_participant,
                                    item=it['name'],
                                    price=it['price']
                                )
                                st.session_state['submitted_items'].append(it['name'])
                        st.success("Items assigned successfully!")
                        st.session_state['submitted'] = False
                        st.session_state['selected_items'] = []

                st.subheader("Billing History")
                history = db.get_billing_history(st.session_state['email'], st.session_state['section'])
                if history:
                    data_list = []
                    for row in history:
                        data_list.append({
                            "Participant": row["_id"],
                            "Total Price": row["total_price"],
                            "Last Updated": row["last_updated"]
                        })
                    df = pd.DataFrame(data_list)
                    st.dataframe(df)
                else:
                    st.write("No bills recorded yet.")

            with col2:
                st.subheader("Most Bought Item")
                top_item = get_most_bought_item()
                if top_item:
                    item_name, count_val, price_val = top_item
                    st.write(f"Item: {item_name}, Count: {count_val}, Price: ${price_val}")
                else:
                    st.write("No items purchased yet.")

                st.subheader("Manage Participants")
                new_participant = st.text_input("Add Participant")
                if st.button("Add Participant"):
                    if new_participant.strip():
                        st.session_state['participants'].append(new_participant.strip())
                        save_section_to_db(st.session_state['section'], st.session_state['participants'])
                        st.rerun()

                remove_part = st.selectbox("Remove Participant", st.session_state['participants'], key="remove_participant")
                if st.button("Remove Participant"):
                    if remove_part:
                        st.session_state['participants'].remove(remove_part)
                        save_section_to_db(st.session_state['section'], st.session_state['participants'])
                        db.remove_items(
                            st.session_state['email'],
                            st.session_state['section'],
                            remove_part,
                            items_to_remove=None
                        )
                        st.rerun()

                st.subheader("Remove Wrongly Tagged Items")
                part_to_remove_from = st.selectbox("Select Participant",
                                                   st.session_state['participants'],
                                                   key="remove_participant_select")
                if part_to_remove_from:
                    pipeline = [
                        {"$match": {
                            "owner_email": st.session_state['email'],
                            "section_name": st.session_state['section'],
                            "participant": part_to_remove_from
                        }}
                    ]
                    results = list(db.bills_coll.aggregate(pipeline))
                    if results:
                        tagged_items = [doc["item"] for doc in results]
                        remove_items_select = st.multiselect("Select Items to Remove",
                                                             tagged_items,
                                                             key="remove_item_select")
                        if st.button("Remove Items"):
                            db.remove_items(
                                st.session_state['email'],
                                st.session_state['section'],
                                part_to_remove_from,
                                remove_items_select
                            )
                            for itm in remove_items_select:
                                if itm in st.session_state['submitted_items']:
                                    st.session_state['submitted_items'].remove(itm)
                            st.success("Items removed successfully!")
                            st.rerun()
                    else:
                        st.write("No items found for this participant.")

if __name__ == "__main__":
    main()