Update src/streamlit_app.py
Browse files31 unmodified lines32333435363738394041561 unmodified lines6036046056066076086096106116126136146156166173 unmodified lines62162262362462562662762862963063163263314 unmodified lines64864965065165265365472 unmodified lines72772872973073173222 unmodified lines7557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927931 unmodified line7957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308313 unmodified lines83583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587623 unmodified lines90090190290390490590690790890991031 unmodified linesfrom PIL import Imagefrom huggingface_hub import login# π ADD CALLBACK FUNCTION AT TOP LEVELdef trigger_rerun():# Forces immediate rerun after any edit β ensures edited_df is freshpass# ---------------------------# UI: main561 unmodified lines# RESULTS VIEW β Show selector + editable form# ---------------------------elif len(st.session_state.batch_results) > 0:# ---------------------------# Global Download All β produce a single Excel file (concatenated rows) and trigger direct download# ---------------------------if st.button("π¦ Download All Results (Excel)", key="download_all"):# Collect rows from all invoices and concatenate into one DataFrameall_rows = []for file_hash, result in st.session_state.batch_results.items():rows = flatten_invoice_to_rows(result["edited_data"])# Annotate rows with source file name so user can identify which invoice each row came fromfor r in rows:r["Source File"] = result.get("file_name", file_hash)all_rows.extend(rows)3 unmodified lineselse:full_df = pd.DataFrame(all_rows)# Reorder columns to put Source File firstcols = list(full_df.columns)if "Source File" in cols:cols = ["Source File"] + [c for c in cols if c != "Source File"]full_df = full_df[cols]# Try to write XLSX (preferred). If engine not available, fall back to CSV.buffer = BytesIO()dl_filename = "all_extracted_invoices.xlsx"tried_xlsx = False14 unmodified linesdl_filename = "all_extracted_invoices.csv"mime = "text/csv"# Trigger immediate download via a data URI and small HTML snippetimport base64import streamlit.components.v1 as componentsb64 = base64.b64encode(file_bytes).decode()72 unmodified linesst.rerun()except Exception as e:st.error(f"Re-run failed: {e}")tabs = st.tabs(["Invoice Details", "Sender/Recipient info", "Bank Details", "Line Items"])st.markdown(22 unmodified lines# ---------- Invoice Details ----------with tabs[0]:with st.container():data['Invoice Number'] = st.text_input("Invoice Number", value=data.get('Invoice Number', ''), key=f"invoice_number_{selected_hash}")data['Invoice Date'] = st.text_input("Invoice Date",value=str(data.get('Invoice Date', '')).strip(),key=f"invoice_date_text_{selected_hash}")data['Due Date'] = st.text_input("Due Date",value=str(data.get('Due Date', '')).strip(),key=f"due_date_text_{selected_hash}")curr_options = ['USD', 'EUR', 'GBP', 'INR', 'Other']curr_value = data.get('Currency', 'USD')curr_index = curr_options.index(curr_value) if curr_value in curr_options else (len(curr_options) - 1)new_curr = st.selectbox("Currency", options=curr_options, index=curr_index, key=f"currency_select_{selected_hash}")if new_curr == 'Other':new_curr = st.text_input("Specify Currency", value=data.get('Currency', ''), key=f"custom_currency_{selected_hash}")data['Currency'] = new_currdef safe_number_input(label, value, key):try:v = float(value)except Exception:v = 0.0return st.number_input(label, value=v, key=key)data['Subtotal'] = safe_number_input("Subtotal", data.get('Subtotal', 0.0), f"subtotal_{selected_hash}")data['Tax Percentage'] = safe_number_input("Tax Percentage", data.get('Tax Percentage', 0.0), f"tax_pct_{selected_hash}")data['Total Tax'] = safe_number_input("Total Tax", data.get('Total Tax', 0.0), f"total_tax_{selected_hash}")data['Total Amount'] = safe_number_input("Total Amount", data.get('Total Amount', 0.0), f"total_amount_{selected_hash}")# ---------- Sender / Recipient ----------with tabs[1]:1 unmodified linedata['Sender'] = {'Name': '', 'Address': ''}if 'Recipient' not in data:data['Recipient'] = {'Name': '', 'Address': ''}sender_info = data['Sender']recipient_info = data['Recipient']with st.container():sender_info['Name'] = st.text_input("Sender Name*", value=sender_info.get('Name', ''), key=f"sender_name_{selected_hash}")sender_info['Address'] = st.text_area("Sender Address*", value=sender_info.get('Address', ''), key=f"sender_address_{selected_hash}")recipient_info['Name'] = st.text_input("Recipient Name*", value=recipient_info.get('Name', ''), key=f"recipient_name_{selected_hash}")recipient_info['Address'] = st.text_area("Recipient Address*", value=recipient_info.get('Address', ''), key=f"recipient_address_{selected_hash}")if st.button("β Swap", help="Swap sender and recipient information", key=f"swap_{selected_hash}"):data['Sender'], data['Recipient'] = data['Recipient'], data['Sender']st.rerun()# ---------- Bank Details ----------with tabs[2]:bank_info = data.get('Bank Details', {}) or {}with st.container():bank_info['bank_name'] = st.text_input("Bank Name", value=bank_info.get('bank_name', ''), key=f"bank_name_{selected_hash}")bank_info['bank_account_number'] = st.text_input("Account Number", value=bank_info.get('bank_account_number', '') or bank_info.get('bank_acc_no',''), key=f"bank_account_{selected_hash}")bank_info['bank_acc_name'] = st.text_input("Bank Account Name", value=bank_info.get('bank_acc_name', '') or bank_info.get('bank_acc_name', ''), key=f"bank_acc_name_{selected_hash}")bank_info['bank_iban'] = st.text_input("IBAN", value=bank_info.get('bank_iban', ''), key=f"iban_{selected_hash}")bank_info['bank_swift'] = st.text_input("SWIFT Code", value=bank_info.get('bank_swift', ''), key=f"swift_code_{selected_hash}")bank_info['bank_routing'] = st.text_input("Routing Number", value=bank_info.get('bank_routing', ''), key=f"routing_{selected_hash}")bank_info['bank_branch'] = st.text_input("Branch", value=bank_info.get('bank_branch', ''), key=f"branch_{selected_hash}")data['Bank Details'] = bank_info# ---------- Line Items ----------# ---------- Line Items ----------# ---------- Line Items ----------# ---------- Line Items ----------with tabs[3]:editor_key = f"item_editor_{selected_hash}"3 unmodified linesif col not in df.columns:df[col] = ""st.write("βοΈ Edit line items below. Press Enter or click outside a cell to confirm each edit.")# Get the edited DataFrame directly from data_editoredited_df = st.data_editor(df,num_rows="dynamic",key=editor_key,use_container_width=True,on_change=trigger_rerun)if len(edited_df) == 0:st.info("No line items found in the invoice.")# ... (previous code) ...# Save button (per file)if st.button("πΎ Save Edits for This File", key=f"save_{selected_hash}"):# Update line items from the current edited_df (which is a DataFrame)data['Itemized Data'] = edited_df.to_dict('records')# Save the entire data to session statest.session_state.batch_results[selected_hash]["edited_data"] = datast.success(f"β Edits saved for {current['file_name']}")# Download buttons (per file)st.markdown("---")col_a, col_b, col_c = st.columns([1, 1, 1])#with col_a:#jsonl_str = json.dumps(data, ensure_ascii=False, indent=2)#st.download_button(# "π₯ Download JSON",#jsonl_str.encode("utf-8"),#file_name=f"{Path(current['file_name']).stem}_extracted.json",#mime="application/json",#key=f"dl_json_{selected_hash}"#)with col_b:# β Flatten entire invoice into rows (one per line item)rows = flatten_invoice_to_rows(data)23 unmodified linesmime="text/csv",key=f"dl_csv_{selected_hash}")# Global Download All β produce a single Excel file (concatenated rows) and trigger direct download# ---------------------------# PROCESSING STATE# ---------------------------# PROCESSING STATE β Show progress31 unmodified lines323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576561 unmodified lines6386396406416426436446456466476486496506516523 unmodified lines65665765865966066166266366466566666766814 unmodified lines68368468568668768868972 unmodified lines76276376476576676776822 unmodified lines7917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608611 unmodified line8638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819823 unmodified lines986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101223 unmodified lines10361037103810391040104131 unmodified linesfrom PIL import Imagefrom huggingface_hub import login# ---------------------------# Helper: Update session state on widget change# ---------------------------def _update_flat_field(field_name: str, widget_key: str):"""Update a top-level field in edited_data."""current_hash = st.session_state.get("current_file_hash")if not current_hash or current_hash not in st.session_state.batch_results:returnnew_value = st.session_state[widget_key]st.session_state.batch_results[current_hash]["edited_data"][field_name] = new_valuedef _update_nested_field(field_path: str, widget_key: str):"""Update a nested field like 'Sender.Name' or 'Bank Details.bank_name'."""current_hash = st.session_state.get("current_file_hash")if not current_hash or current_hash not in st.session_state.batch_results:returnnew_value = st.session_state[widget_key]data_ref = st.session_state.batch_results[current_hash]["edited_data"]keys = field_path.split(".")d = data_reffor k in keys[:-1]:if k not in d or not isinstance(d[k], dict):d[k] = {}d = d[k]d[keys[-1]] = new_valuedef _update_line_items(widget_key: str):"""Auto-update line items when data_editor changes."""current_hash = st.session_state.get("current_file_hash")if not current_hash or current_hash not in st.session_state.batch_results:returndf = st.session_state[widget_key]records = df.to_dict('records')st.session_state.batch_results[current_hash]["edited_data"]["Itemized Data"] = records# ---------------------------# UI: main561 unmodified lines# RESULTS VIEW β Show selector + editable form# ---------------------------elif len(st.session_state.batch_results) > 0:# ---------------------------# Global Download All β produce a single Excel file (concatenated rows) and trigger direct download# ---------------------------if st.button("π¦ Download All Results (Excel)", key="download_all"):# Collect rows from all invoices and concatenate into one DataFrameall_rows = []for file_hash, result in st.session_state.batch_results.items():rows = flatten_invoice_to_rows(result["edited_data"])# Annotate rows with source file name so user can identify which invoice each row came fromfor r in rows:r["Source File"] = result.get("file_name", file_hash)all_rows.extend(rows)3 unmodified lineselse:full_df = pd.DataFrame(all_rows)# Reorder columns to put Source File firstcols = list(full_df.columns)if "Source File" in cols:cols = ["Source File"] + [c for c in cols if c != "Source File"]full_df = full_df[cols]# Try to write XLSX (preferred). If engine not available, fall back to CSV.buffer = BytesIO()dl_filename = "all_extracted_invoices.xlsx"tried_xlsx = False14 unmodified linesdl_filename = "all_extracted_invoices.csv"mime = "text/csv"# Trigger immediate download via a data URI and small HTML snippetimport base64import streamlit.components.v1 as componentsb64 = base64.b64encode(file_bytes).decode()72 unmodified linesst.rerun()except Exception as e:st.error(f"Re-run failed: {e}")tabs = st.tabs(["Invoice Details", "Sender/Recipient info", "Bank Details", "Line Items"])st.markdown(22 unmodified lines# ---------- Invoice Details ----------with tabs[0]:with st.container():widget_key = f"invoice_number_{selected_hash}"st.text_input("Invoice Number",value=data.get('Invoice Number', ''),key=widget_key,on_change=_update_flat_field,args=("Invoice Number", widget_key))widget_key = f"invoice_date_text_{selected_hash}"st.text_input("Invoice Date",value=str(data.get('Invoice Date', '')).strip(),key=widget_key,on_change=_update_flat_field,args=("Invoice Date", widget_key))widget_key = f"due_date_text_{selected_hash}"st.text_input("Due Date",value=str(data.get('Due Date', '')).strip(),key=widget_key,on_change=_update_flat_field,args=("Due Date", widget_key))curr_options = ['USD', 'EUR', 'GBP', 'INR', 'Other']curr_value = data.get('Currency', 'USD')curr_index = curr_options.index(curr_value) if curr_value in curr_options else (len(curr_options) - 1)new_curr = st.selectbox("Currency",options=curr_options,index=curr_index,key=f"currency_select_{selected_hash}",on_change=_update_flat_field,args=("Currency", f"currency_select_{selected_hash}"))if new_curr == 'Other':widget_key = f"custom_currency_{selected_hash}"st.text_input("Specify Currency",value=data.get('Currency', ''),key=widget_key,on_change=_update_flat_field,args=("Currency", widget_key))def safe_number_input(label, value, key, field_name):try:v = float(value)except Exception:v = 0.0st.number_input(label,value=v,key=key,on_change=_update_flat_field,args=(field_name, key))safe_number_input("Subtotal", data.get('Subtotal', 0.0), f"subtotal_{selected_hash}", "Subtotal")safe_number_input("Tax Percentage", data.get('Tax Percentage', 0.0), f"tax_pct_{selected_hash}", "Tax Percentage")safe_number_input("Total Tax", data.get('Total Tax', 0.0), f"total_tax_{selected_hash}", "Total Tax")safe_number_input("Total Amount", data.get('Total Amount', 0.0), f"total_amount_{selected_hash}", "Total Amount")# ---------- Sender / Recipient ----------with tabs[1]:1 unmodified linedata['Sender'] = {'Name': '', 'Address': ''}if 'Recipient' not in data:data['Recipient'] = {'Name': '', 'Address': ''}sender_info = data['Sender']recipient_info = data['Recipient']with st.container():widget_key = f"sender_name_{selected_hash}"st.text_input("Sender Name*",value=sender_info.get('Name', ''),key=widget_key,on_change=_update_nested_field,args=("Sender.Name", widget_key))widget_key = f"sender_address_{selected_hash}"st.text_area("Sender Address*",value=sender_info.get('Address', ''),key=widget_key,on_change=_update_nested_field,args=("Sender.Address", widget_key))widget_key = f"recipient_name_{selected_hash}"st.text_input("Recipient Name*",value=recipient_info.get('Name', ''),key=widget_key,on_change=_update_nested_field,args=("Recipient.Name", widget_key))widget_key = f"recipient_address_{selected_hash}"st.text_area("Recipient Address*",value=recipient_info.get('Address', ''),key=widget_key,on_change=_update_nested_field,args=("Recipient.Address", widget_key))if st.button("β Swap", help="Swap sender and recipient information", key=f"swap_{selected_hash}"):data['Sender'], data['Recipient'] = data['Recipient'], data['Sender']st.session_state.batch_results[selected_hash]["edited_data"] = datast.rerun()# ---------- Bank Details ----------with tabs[2]:bank_info = data.get('Bank Details', {}) or {}with st.container():widget_key = f"bank_name_{selected_hash}"st.text_input("Bank Name",value=bank_info.get('bank_name', ''),key=widget_key,on_change=_update_nested_field,args=("Bank Details.bank_name", widget_key))widget_key = f"bank_account_{selected_hash}"st.text_input("Account Number",value=bank_info.get('bank_account_number', '') or bank_info.get('bank_acc_no',''),key=widget_key,on_change=_update_nested_field,args=("Bank Details.bank_account_number", widget_key))widget_key = f"bank_acc_name_{selected_hash}"st.text_input("Bank Account Name",value=bank_info.get('bank_acc_name', '') or bank_info.get('bank_acc_name', ''),key=widget_key,on_change=_update_nested_field,args=("Bank Details.bank_acc_name", widget_key))widget_key = f"iban_{selected_hash}"st.text_input("IBAN",value=bank_info.get('bank_iban', ''),key=widget_key,on_change=_update_nested_field,args=("Bank Details.bank_iban", widget_key))widget_key = f"swift_code_{selected_hash}"st.text_input("SWIFT Code",value=bank_info.get('bank_swift', ''),key=widget_key,on_change=_update_nested_field,args=("Bank Details.bank_swift", widget_key))widget_key = f"routing_{selected_hash}"st.text_input("Routing Number",value=bank_info.get('bank_routing', ''),key=widget_key,on_change=_update_nested_field,args=("Bank Details.bank_routing", widget_key))widget_key = f"branch_{selected_hash}"st.text_input("Branch",value=bank_info.get('bank_branch', ''),key=widget_key,on_change=_update_nested_field,args=("Bank Details.bank_branch", widget_key))# ---------- Line Items ----------with tabs[3]:editor_key = f"item_editor_{selected_hash}"3 unmodified linesif col not in df.columns:df[col] = ""st.write("βοΈ Edit line items below. Changes are saved automatically.")st.data_editor(df,num_rows="dynamic",key=editor_key,use_container_width=True,on_change=_update_line_items,args=(editor_key,))if len(df) == 0:st.info("No line items found in the invoice.")# Save button (per file) β now optional since edits auto-saveif st.button("πΎ Save Edits for This File (Optional)", key=f"save_{selected_hash}"):# This is now redundant but kept for user reassurancest.success(f"β Edits already auto-saved for {current['file_name']}")# Download buttons (per file)st.markdown("---")col_a, col_b, col_c = st.columns([1, 1, 1])with col_b:# β Flatten entire invoice into rows (one per line item)rows = flatten_invoice_to_rows(data)23 unmodified linesmime="text/csv",key=f"dl_csv_{selected_hash}")# ---------------------------# PROCESSING STATE β Show progress
src/streamlit_app.py+203-72