Spaces:
Running
Running
Download src/streamlit_app.py from CatapultAI/Remittance-UI: direct link, hf CLI and curl.
- Browser
- Download file 68.5 kB
-
https://huggingface.co/spaces/CatapultAI/Remittance-UI/resolve/main/src/streamlit_app.py
- Command line
-
hf download hf://spaces/CatapultAI/Remittance-UI/src/streamlit_app.py
-
curl -L -o streamlit_app.py https://huggingface.co/spaces/CatapultAI/Remittance-UI/resolve/main/src/streamlit_app.py
68.5 kB
import os
from pathlib import Path
# -----------------------------
# Environment hardening (HF Spaces, /.cache issue)
# -----------------------------
_home = os.environ.get("HOME", "")
if _home in ("", "/", None):
repo_dir = os.getcwd()
safe_home = repo_dir if os.access(repo_dir, os.W_OK) else "/tmp"
os.environ["HOME"] = safe_home
print(f"[startup] HOME not set or unwritable β setting HOME={safe_home}")
streamlit_dir = Path(os.environ["HOME"]) / ".streamlit"
try:
streamlit_dir.mkdir(parents=True, exist_ok=True)
print(f"[startup] ensured {streamlit_dir}")
except Exception as e:
print(f"[startup] WARNING: could not create {streamlit_dir}: {e}")
import streamlit as st
import json
import io
from PIL import Image
import time
import pandas as pd
from streamlit_drawable_canvas import st_canvas
import pytesseract
import numpy as np
from datetime import datetime
import base64
from copy import deepcopy
from typing import List
import requests
import fitz # PyMuPDF: renders PDF pages to images
# Compatibility: streamlit-drawable-canvas 0.9.3 calls streamlit.elements.image.image_to_url,
# which newer Streamlit moved to elements.lib.image_utils (taking a LayoutConfig instead of width).
# (Only used if a background_image is ever passed; this app embeds the image via initial_drawing.)
import streamlit.elements.image as _st_image_module
if not hasattr(_st_image_module, "image_to_url"):
try:
from streamlit.elements.lib.image_utils import image_to_url as _new_image_to_url
from streamlit.elements.lib.layout_utils import LayoutConfig as _LayoutConfig
def _compat_image_to_url(image, width, clamp, channels, output_format, image_id):
return _new_image_to_url(image, _LayoutConfig(width=width), clamp, channels, output_format, image_id)
_st_image_module.image_to_url = _compat_image_to_url
except Exception as _compat_err:
print(f"[startup] WARNING: drawable-canvas compatibility patch failed: {_compat_err}")
def canvas_background_drawing(image, width, height):
"""Starting state for st_canvas with the page image embedded as its background.
st_canvas(background_image=...) makes the browser fetch the image from /media/..., which
fails behind proxies/iframes such as Hugging Face Spaces (blank canvas). Embedding the image
in initial_drawing needs no extra request. Only user-drawn shapes appear in json_data['objects'].
"""
img = image.convert("RGB").resize((int(width), int(height)), Image.Resampling.LANCZOS)
buf = io.BytesIO()
img.save(buf, format="JPEG", quality=92)
data_url = "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode("ascii")
return {
"version": "4.4.0",
"objects": [],
"backgroundImage": {
"type": "image", "version": "4.4.0", "originX": "left", "originY": "top",
"left": 0, "top": 0, "width": int(width), "height": int(height),
"scaleX": 1, "scaleY": 1, "src": data_url, "crossOrigin": None,
},
}
# Set Tesseract path - auto-detect based on OS
if os.name == 'nt': # Windows
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
else: # Linux/Mac (HF Spaces uses Linux)
pass
# Page configuration
st.set_page_config(page_title="Remittance Data Viewer", layout="wide")
# -----------------------------
# API configuration (vLLM pod)
# -----------------------------
POD_URL = os.getenv("POD_URL", "https://zud7ytk3vq1k10-8000.proxy.runpod.net")
VLLM_API_KEY = os.getenv("VLLM_API_KEY", "9386aa7335c2072882ad367791f1dc863c63b4be88eda14c2dea0408f9d0105e")
MODEL_NAME = "Remi-Merged"
MAX_PAGES_PER_REQUEST = 10
MAX_DIMENSION_PER_PAGE = 1560
MAX_TOTAL_PAYLOAD_MB = 40.0
if not POD_URL or not VLLM_API_KEY:
st.error("β οΈ API credentials not configured. Please set POD_URL and VLLM_API_KEY in Space settings.")
st.stop()
# Custom CSS
st.markdown("""
<style>
/* Reduce spacing between form fields */
.stTextInput > div > div > input,
.stTextArea > div > div > textarea,
.stSelectbox > div > div > div {
margin-bottom: 0px !important;
}
div[data-testid="stVerticalBlock"] > div:has(div[data-testid="stTextInput"]),
div[data-testid="stVerticalBlock"] > div:has(div[data-testid="stTextArea"]),
div[data-testid="stVerticalBlock"] > div:has(div[data-testid="stSelectbox"]) {
margin-bottom: 4px !important;
}
.stSelectbox {
margin-bottom: 4px !important;
}
/* Style for OCR buttons - small and compact */
.stButton > button {
padding: 0.25rem 0.5rem !important;
font-size: 0.85rem !important;
line-height: 1 !important;
min-height: 1.8rem !important;
height: 1.8rem !important;
}
/* Active OCR buttons - RED highlight */
.stButton > button[kind="primary"] {
background-color: #FF0000 !important;
border-color: #FF0000 !important;
color: white !important;
}
.stButton > button[kind="primary"]:hover {
background-color: #CC0000 !important;
border-color: #CC0000 !important;
}
[data-testid="stVerticalBlock"] > [data-testid="stVerticalBlock"] {
gap: 0.25rem !important;
}
/* REDUCE GAP BETWEEN COLUMNS */
[data-testid="column"] {
padding-left: 0.5rem !important;
padding-right: 0.5rem !important;
}
[data-testid="stHorizontalBlock"] {
gap: 0.5rem !important;
}
/* Active OCR field highlighting */
.ocr-active {
border: 2px solid #ff4b4b !important;
box-shadow: 0 0 5px rgba(255, 75, 75, 0.5) !important;
}
</style>
""", unsafe_allow_html=True)
def load_jsonl(file):
"""Load JSONL file and return list of records"""
data = []
content = file.getvalue().decode('utf-8')
for line in content.strip().split('\n'):
if line.strip():
data.append(json.loads(line))
return data
def save_to_jsonl(data):
"""Convert data list to JSONL format"""
jsonl_content = '\n'.join([json.dumps(record) for record in data])
return jsonl_content
def perform_ocr(image, bbox):
"""Perform OCR on the selected region of the image"""
try:
x1, y1, x2, y2 = int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])
x1, y1 = max(0, x1), max(0, y1)
x2, y2 = min(image.width, x2), min(image.height, y2)
cropped = image.crop((x1, y1, x2, y2))
text = pytesseract.image_to_string(cropped, config='--psm 6').strip()
return text
except Exception as e:
return f"OCR Error: {str(e)}"
# -----------------------------
# Model extraction (vLLM pod) - same request format as the invoice extractor
# -----------------------------
REMITTANCE_EXTRACTION_PROMPT = """Extract structured data from the provided remittance advice image(s). Return a single JSON object with four sections: Remittance_details, Customer_supplier_details, Bank_details, Line_items.
## Output Schema
Return this exact structure. Use empty string "" for any field not found.
{
"Remittance_details": {
"Remittance_adv_no": "",
"Remittance_adv_date": "",
"Payment_method": "",
"FCY": "",
"Total_payment_amt_FCY": "",
"Payment_date": "",
"Payment_ref_no": ""
},
"Customer_supplier_details": {
"Customer_name": "",
"Customer_address": "",
"Customer_contact_info": "",
"Supplier_name": "",
"Supplier_address": "",
"Supplier_contact_info": ""
},
"Bank_details": {
"Bank_name": "",
"Bank_acc_no": "",
"Bank_routing_no": "",
"Swift_code": ""
},
"Line_items": [
{
"Po_number": "",
"Invoice_no": "",
"Other_doc_ref_no": "",
"Invoice_date": "",
"Invoice_amount_FCY": "",
"Amount_paid_for_each_invoice": "",
"Outstanding_balance_FCY": "",
"Discounts_taken_FCY": "",
"Adjustments(without_holding_tax)_FCY": "",
"Descriptions": ""
}
]
}
## Rules
1. EXTRACT ONLY WHAT IS EXPLICITLY VISIBLE. Never compute, derive or infer values.
2. Return "" for any field not present or not clearly identifiable.
3. Preserve original formatting of numbers (commas, decimals) and dates exactly as printed.
4. Strip currency symbols from amount fields. Put the currency code (USD, EUR, INR, etc.) only in Remittance_details.FCY.
5. Customer = the payer who sends the remittance. Supplier = the payee receiving the payment.
6. Line_items: one entry per invoice/document row in the payment table, in printed order. Include rows with zero or negative amounts. Do not include table header rows or the grand total row. If there are no rows, return "Line_items": [].
7. MULTI-PAGE: merge all pages into one JSON object. Skip rows that only repeat the table column titles.
8. OUTPUT ONLY THE JSON. No preamble, no markdown fences, no explanation."""
def _encode_page(page: Image.Image, page_idx: int, max_dim: int = MAX_DIMENSION_PER_PAGE):
orig_w, orig_h = page.size
api_img = page.convert("RGB")
api_img = api_img.resize((max_dim, max_dim), Image.Resampling.LANCZOS)
buf = io.BytesIO()
api_img.save(buf, format="PNG", optimize=True)
b64 = base64.b64encode(buf.getvalue()).decode("utf-8")
data_url = f"data:image/png;base64,{b64}"
return data_url, (orig_w, orig_h), (max_dim, max_dim)
def run_inference_vllm(images: List[Image.Image]):
"""Send all pages of one document to the vLLM pod in a single request; returns raw text or None."""
if not images:
st.error("No images provided to run_inference_vllm.")
return None
if len(images) > MAX_PAGES_PER_REQUEST:
st.warning(
f"Document has {len(images)} pages β only the first "
f"{MAX_PAGES_PER_REQUEST} will be sent per the request limit."
)
images = images[:MAX_PAGES_PER_REQUEST]
try:
image_content_blocks = []
total_b64_bytes = 0
resize_info = []
for idx, page in enumerate(images):
data_url, orig_size, new_size = _encode_page(page, idx)
total_b64_bytes += len(data_url)
if orig_size != new_size:
resize_info.append(
f"Page {idx+1}: {orig_size[0]}Γ{orig_size[1]} β {new_size[0]}Γ{new_size[1]}"
)
image_content_blocks.append({"type": "image_url", "image_url": {"url": data_url}})
if resize_info:
st.info("Resized for API payload:\n" + "\n".join(resize_info))
total_payload_mb = total_b64_bytes / (1024 * 1024)
if total_payload_mb > MAX_TOTAL_PAYLOAD_MB:
st.warning(
f"Large multi-page payload ({total_payload_mb:.1f} MB across "
f"{len(images)} page(s)). This may be slow or time-out."
)
else:
st.info(f"Sending {len(images)} page(s) in one request (payload β {total_payload_mb:.2f} MB).")
user_content = image_content_blocks + [
{
"type": "text",
"text": (
f"The {len(images)} image(s) above are all pages of the same remittance advice "
f"(page 1 through page {len(images)}).\n"
"Extract remittance data from ALL pages combined into a single JSON object."
)
}
]
payload = {
"model": MODEL_NAME,
"messages": [
{"role": "system", "content": REMITTANCE_EXTRACTION_PROMPT},
{"role": "user", "content": user_content}
],
"temperature": 0,
"max_tokens": 10000
}
headers = {
"Authorization": f"Bearer {VLLM_API_KEY}",
"Content-Type": "application/json"
}
response = requests.post(
f"{POD_URL}/v1/chat/completions",
headers=headers,
json=payload,
timeout=600
)
if response.status_code == 200:
result = response.json()
return result["choices"][0]["message"]["content"]
else:
st.error(f"β API Error {response.status_code}")
try:
st.json(response.json())
except Exception:
st.code(response.text)
return None
except Exception as e:
st.error(f"Error calling vLLM: {str(e)}")
return None
def parse_model_json(raw_text):
"""Parse the model's text into a dict exactly as returned (only markdown fences are stripped)."""
try:
text = raw_text.strip()
if text.startswith("```json"):
text = text[7:]
elif text.startswith("```"):
text = text[3:]
if text.endswith("```"):
text = text[:-3]
parsed = json.loads(text.strip())
# Accept output that is already wrapped as {"gt_parse": {...}}
if isinstance(parsed, dict) and isinstance(parsed.get("gt_parse"), dict):
parsed = parsed["gt_parse"]
return parsed if isinstance(parsed, dict) else None
except Exception as e:
st.error(f"JSON parse error: {str(e)}")
return None
def flatten_remittance_to_rows(record):
"""One row per line item; file_name first, then remittance, party and bank fields repeated on every row."""
gt_parse = record.get('gt_parse', {}) or {}
header = {'file_name': record.get('file_name', '')}
for section in ['Remittance_details', 'Customer_supplier_details', 'Bank_details']:
values = gt_parse.get(section, {})
if isinstance(values, dict):
header.update(values)
items = gt_parse.get('Line_items', []) or []
rows = [{**header, **item} for item in items if isinstance(item, dict)]
return rows if rows else [header]
def build_excel_bytes(df):
buf = io.BytesIO()
with pd.ExcelWriter(buf, engine="openpyxl") as writer:
df.to_excel(writer, index=False, sheet_name="Remittances")
ws = writer.sheets["Remittances"]
for col_cells in ws.columns:
max_len = 0
col_letter = col_cells[0].column_letter
for cell in col_cells:
try:
if cell.value:
max_len = max(max_len, len(str(cell.value)))
except Exception:
pass
ws.column_dimensions[col_letter].width = min(max_len + 3, 50)
return buf.getvalue()
def pdf_to_images(pdf_file, zoom=3):
"""Render every page of an uploaded PDF to a PIL image (zoom 3 β 216 DPI: sharp enough for OCR)."""
pdf_bytes = pdf_file.read()
doc = fitz.open(stream=pdf_bytes, filetype="pdf")
pages = []
try:
for page in doc:
pix = page.get_pixmap(matrix=fitz.Matrix(zoom, zoom), alpha=False)
pages.append(Image.open(io.BytesIO(pix.tobytes("png"))).convert("RGB"))
finally:
doc.close()
return pages
def get_document_pages(file_name):
"""All page images of an uploaded document: every page for a PDF, a single page for an image."""
if file_name in st.session_state.get('pdf_pages', {}):
return st.session_state.pdf_pages[file_name]
if file_name in st.session_state.images:
return [st.session_state.images[file_name]]
return []
def scale_image_to_fixed_size(image, max_width=700, max_height=900):
"""Scale image to fit within max dimensions while maintaining aspect ratio - NO PADDING"""
# Convert to RGB with proper handling
if image.mode not in ('RGB', 'RGBA'):
image = image.convert('RGB')
elif image.mode == 'RGBA':
background = Image.new('RGB', image.size, (255, 255, 255))
background.paste(image, mask=image.split()[3])
image = background
# Calculate scaling ratio
width_ratio = max_width / image.width
height_ratio = max_height / image.height
ratio = min(width_ratio, height_ratio)
new_width = int(image.width * ratio)
new_height = int(image.height * ratio)
# Always use LANCZOS for highest quality resampling
resized_image = image.resize((new_width, new_height), Image.Resampling.LANCZOS)
# Return without padding - image takes only the space it needs
return resized_image, ratio, 0, 0
def refresh_record_widgets(index):
"""Give this record's input widgets new keys so they re-read gt_parse.
Needed after code changes a field (OCR, Re-Run, Swap): otherwise the browser
sends back the old typed text and overwrites the new value."""
st.session_state.widget_version[index] = st.session_state.widget_version.get(index, 0) + 1
def swap_customer_supplier_details(index):
"""Swap customer and supplier details"""
gt_parse = st.session_state.edited_data[index].get('gt_parse', {})
customer_supplier = gt_parse.get('Customer_supplier_details', {})
# Store customer values
temp_customer_name = customer_supplier.get('Customer_name', '')
temp_customer_address = customer_supplier.get('Customer_address', '')
temp_customer_contact = customer_supplier.get('Customer_contact_info', '')
# Swap: Customer β Supplier
customer_supplier['Customer_name'] = customer_supplier.get('Supplier_name', '')
customer_supplier['Customer_address'] = customer_supplier.get('Supplier_address', '')
customer_supplier['Customer_contact_info'] = customer_supplier.get('Supplier_contact_info', '')
# Swap: Supplier β Customer (from temp)
customer_supplier['Supplier_name'] = temp_customer_name
customer_supplier['Supplier_address'] = temp_customer_address
customer_supplier['Supplier_contact_info'] = temp_customer_contact
# Update session state
gt_parse['Customer_supplier_details'] = customer_supplier
st.session_state.edited_data[index]['gt_parse'] = gt_parse
st.session_state.modified_indices.add(index)
refresh_record_widgets(index)
# Initialize session state
if 'data' not in st.session_state:
st.session_state.data = None
if 'current_index' not in st.session_state:
st.session_state.current_index = 0
if 'edited_data' not in st.session_state:
st.session_state.edited_data = None
if 'page' not in st.session_state:
st.session_state.page = 'upload'
if 'images' not in st.session_state:
st.session_state.images = {}
if 'modified_indices' not in st.session_state:
st.session_state.modified_indices = set()
if 'ocr_active_section' not in st.session_state:
st.session_state.ocr_active_section = None
if 'ocr_active_field' not in st.session_state:
st.session_state.ocr_active_field = None
if 'ocr_line_item_row' not in st.session_state:
st.session_state.ocr_line_item_row = None
if 'canvas_key' not in st.session_state:
st.session_state.canvas_key = 0
if 'line_items_temp' not in st.session_state:
st.session_state.line_items_temp = []
if 'button_clicked' not in st.session_state:
st.session_state.button_clicked = False
if 'save_message' not in st.session_state:
st.session_state.save_message = None
if 'save_message_time' not in st.session_state:
st.session_state.save_message_time = None
if 'just_saved' not in st.session_state:
st.session_state.just_saved = False
if 'just_swapped' not in st.session_state:
st.session_state.just_swapped = False
if 'raw_outputs' not in st.session_state:
st.session_state.raw_outputs = {}
if 'widget_version' not in st.session_state:
st.session_state.widget_version = {}
if 'pdf_pages' not in st.session_state:
st.session_state.pdf_pages = {}
if 'current_page_num' not in st.session_state:
st.session_state.current_page_num = {}
def auto_save(index):
"""Automatically save changes to session state and mark as modified"""
if st.session_state.edited_data:
st.session_state.data = st.session_state.edited_data.copy()
st.session_state.modified_indices.add(index)
def activate_ocr_field(section, field, row_idx=None):
"""Activate OCR for a specific field"""
st.session_state.ocr_active_section = section
st.session_state.ocr_active_field = field
st.session_state.ocr_line_item_row = row_idx
st.rerun()
def is_ocr_active(section, field, row_idx=None):
"""Check if this OCR button is currently active"""
return (st.session_state.ocr_active_section == section and
st.session_state.ocr_active_field == field and
st.session_state.ocr_line_item_row == row_idx)
# PAGE 1: Upload Page
if st.session_state.page == 'upload':
st.title("Remittance Extraction")
frame_left, frame_right = st.columns([1, 1], vertical_alignment="top")
with frame_right:
st.caption("Preview & editor will appear here after extraction.")
with frame_left:
st.header("π€ Upload Remittances")
uploaded_images = st.file_uploader(
"Upload remittance images or PDFs β all pages of a PDF are sent in one request",
type=['png', 'jpg', 'jpeg', 'tiff', 'tif', 'bmp', 'pdf'],
accept_multiple_files=True
)
if uploaded_images:
with frame_left:
images_dict = {}
pdf_pages = {}
file_sizes = {}
for img_file in uploaded_images:
try:
file_sizes[img_file.name] = getattr(img_file, 'size', 0)
if img_file.name.lower().endswith('.pdf'):
pages = pdf_to_images(img_file)
if not pages:
st.warning(f"PDF {img_file.name} has no pages.")
continue
pdf_pages[img_file.name] = pages
images_dict[img_file.name] = pages[0]
else:
image = Image.open(img_file)
images_dict[img_file.name] = image
except Exception as e:
st.warning(f"Could not load file {img_file.name}: {str(e)}")
st.session_state.images = images_dict
st.session_state.pdf_pages = pdf_pages
for name in pdf_pages:
st.session_state.current_page_num.setdefault(name, 0)
# Run the model on every image (cached, so going back to this page does not re-send)
if 'extraction_cache' not in st.session_state:
st.session_state.extraction_cache = {}
cache = st.session_state.extraction_cache
raw_outputs = {}
records = []
failed = []
newly_extracted = 0
progress_bar = st.progress(0)
status_text = st.empty()
names = list(images_dict.keys())
for idx, doc_name in enumerate(names):
cache_key = (doc_name, file_sizes.get(doc_name, 0))
if cache_key not in cache:
status_text.text(f"Processing {idx + 1}/{len(names)}: {doc_name}")
doc_pages = pdf_pages.get(doc_name, [images_dict[doc_name]])
if len(doc_pages) > 1:
st.info(f"{doc_name}: {len(doc_pages)} page(s) detected β all sent in one request.")
raw_output = run_inference_vllm(doc_pages)
gt_parse = parse_model_json(raw_output) if raw_output else None
if gt_parse is None:
# Keep the document with empty fields (use π Re-Run in the viewer to retry)
if raw_output is None:
st.warning(f"No response from vLLM for {doc_name}")
else:
st.warning(f"Could not parse model output for {doc_name}")
failed.append(doc_name)
gt_parse = {}
cache[cache_key] = {'gt_parse': gt_parse, 'raw': raw_output}
newly_extracted += 1
records.append({'file_name': doc_name, 'gt_parse': deepcopy(cache[cache_key]['gt_parse'])})
raw_outputs[doc_name] = cache[cache_key]['raw']
progress_bar.progress((idx + 1) / len(names))
status_text.text("β
All files processed!")
if records:
st.session_state.data = records
st.session_state.edited_data = deepcopy(records)
st.session_state.raw_outputs = raw_outputs
st.success(f"β
Processed {len(records)} document(s)!")
else:
st.session_state.data = None
# Go straight to the viewer after a fresh extraction (failed documents open with empty fields)
if records and newly_extracted > 0:
st.session_state.extraction_errors = failed
st.session_state.page = 'viewer'
st.session_state.current_index = 0
st.session_state.modified_indices = set()
st.rerun()
if st.session_state.data is not None and uploaded_images:
with frame_left:
col1, col2, col3 = st.columns([1, 1, 1])
with col2:
if st.button("Continue to Viewer β", type="primary", use_container_width=True):
st.session_state.page = 'viewer'
st.session_state.modified_indices = set()
st.rerun()
# PAGE 2: Viewer Page
elif st.session_state.page == 'viewer':
if st.session_state.save_message_time is not None:
if time.time() - st.session_state.save_message_time > 3:
st.session_state.save_message = None
st.session_state.save_message_time = None
today_date = datetime.now().strftime("%Y-%m-%d")
extraction_errors = st.session_state.get('extraction_errors', [])
if extraction_errors:
st.warning(
f"β οΈ No extraction for {len(extraction_errors)} document(s) β the API gave no usable response. "
f"They are shown with empty fields; use π Re-Run to try again: " + ", ".join(extraction_errors)
)
file_names = [record.get('file_name', f'Record {i}') for i, record in enumerate(st.session_state.data)]
cur_idx = st.session_state.get('current_index', 0)
if not isinstance(cur_idx, int) or cur_idx < 0 or cur_idx >= len(file_names):
cur_idx = 0
left_col, right_col = st.columns([1, 1], gap="medium")
# LEFT: download-all buttons + document selector (image is rendered below)
with left_col:
all_rows = []
for record in st.session_state.edited_data or []:
all_rows.extend(flatten_remittance_to_rows(record))
all_df = pd.DataFrame(all_rows)
dl_cols = st.columns(3)
with dl_cols[0]:
st.download_button(
"π¦ All CSV",
all_df.to_csv(index=False).encode("utf-8"),
file_name=f"all_remittance_data_{today_date}.csv",
mime="text/csv",
key="download_all_csv"
)
with dl_cols[1]:
st.download_button(
"π¦ All Excel",
build_excel_bytes(all_df),
file_name=f"all_remittance_data_{today_date}.xlsx",
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
key="download_all_xlsx"
)
with dl_cols[2]:
st.download_button(
"π¦ All JSONL",
save_to_jsonl(st.session_state.edited_data or []),
file_name=f"all_remittance_data_{today_date}.jsonl",
mime="application/jsonl",
key="download_all_jsonl"
)
selected_file = st.selectbox(
"Select remittance to view/edit:",
options=range(len(file_names)),
format_func=lambda x: f"{'βοΈ ' if x in st.session_state.modified_indices else ''}{file_names[x]}",
index=cur_idx
)
st.session_state.current_index = selected_file
_wv = st.session_state.widget_version.get(selected_file, 0)
current_record = st.session_state.edited_data[selected_file]
# RIGHT: back button + title
with right_col:
if st.button("β¬
οΈ Back to Upload"):
st.session_state.page = 'upload'
st.session_state.ocr_active_section = None
st.session_state.ocr_active_field = None
st.session_state.save_message = None
st.session_state.save_message_time = None
st.rerun()
st.markdown(f"## Editable Remittance: {current_record.get('file_name', '')}")
# LEFT SIDE: Image Display with OCR Canvas
with left_col:
with st.container(height=620, border=False):
file_name = current_record.get('file_name', '')
if file_name:
current_image = None
if file_name in st.session_state.images:
doc_pages = get_document_pages(file_name)
total_pages = len(doc_pages)
cur_page = min(st.session_state.current_page_num.get(file_name, 0), total_pages - 1)
# Page navigation for multi-page PDFs
if total_pages > 1:
col_prev, col_info, col_next = st.columns([1, 2, 1])
with col_prev:
if st.button("β¬
οΈ Previous", key=f"prev_page_{selected_file}_v{_wv}",
disabled=(cur_page == 0), use_container_width=True):
st.session_state.current_page_num[file_name] = cur_page - 1
st.session_state.canvas_key += 1
st.rerun()
with col_info:
st.markdown(
f"<div style='text-align: center; padding: 5px;'><b>π Page {cur_page + 1} of {total_pages}</b></div>",
unsafe_allow_html=True
)
with col_next:
if st.button("Next β‘οΈ", key=f"next_page_{selected_file}_v{_wv}",
disabled=(cur_page >= total_pages - 1), use_container_width=True):
st.session_state.current_page_num[file_name] = cur_page + 1
st.session_state.canvas_key += 1
st.rerun()
current_image = doc_pages[cur_page]
else:
st.error(f"β Image '{file_name}' not found in uploaded images")
st.info("π‘ Available images:")
with st.expander("Show available images"):
for img_name in list(st.session_state.images.keys())[:20]:
st.text(f" β’ {img_name}")
if len(st.session_state.images) > 20:
st.text(f" ... and {len(st.session_state.images) - 20} more")
if current_image:
scaled_image, scale_ratio, paste_x, paste_y = scale_image_to_fixed_size(current_image, max_width=650)
canvas_result = st_canvas(
fill_color="rgba(255, 165, 0, 0.3)",
stroke_width=2,
stroke_color="#FF0000",
initial_drawing=canvas_background_drawing(scaled_image, scaled_image.width, scaled_image.height),
update_streamlit=True,
height=scaled_image.height,
width=scaled_image.width,
drawing_mode="rect",
key=f"canvas_{selected_file}_{st.session_state.canvas_key}",
)
if canvas_result.json_data is not None and st.session_state.ocr_active_field:
objects = canvas_result.json_data["objects"]
if len(objects) > 0:
rect = objects[-1]
bbox = [
(rect["left"] - paste_x) / scale_ratio,
(rect["top"] - paste_y) / scale_ratio,
(rect["left"] + rect["width"] - paste_x) / scale_ratio,
(rect["top"] + rect["height"] - paste_y) / scale_ratio
]
with st.spinner("Performing OCR..."):
ocr_text = perform_ocr(current_image, bbox)
if ocr_text and not ocr_text.startswith("OCR Error"):
st.success(f"β
OCR Result: {ocr_text}")
gt_parse = st.session_state.edited_data[selected_file].get('gt_parse', {})
if st.session_state.ocr_active_section == 'Line_items':
line_items = gt_parse.get('Line_items', [])
row_idx = st.session_state.ocr_line_item_row
if row_idx is not None and row_idx < len(line_items):
line_items[row_idx][st.session_state.ocr_active_field] = ocr_text
gt_parse['Line_items'] = line_items
else:
section = st.session_state.ocr_active_section
field = st.session_state.ocr_active_field
if section not in gt_parse:
gt_parse[section] = {}
gt_parse[section][field] = ocr_text
st.session_state.edited_data[selected_file]['gt_parse'] = gt_parse
st.session_state.modified_indices.add(selected_file)
refresh_record_widgets(selected_file)
# Clear canvas for next OCR
st.session_state.canvas_key += 1
st.rerun()
else:
st.error(ocr_text)
else:
st.warning("No file name specified in record")
# Re-Run + raw model output (below the image, always visible)
if file_name and file_name in st.session_state.images:
rerun_pages = get_document_pages(file_name)
if st.button("π Re-Run (All Pages)", key=f"rerun_all_{selected_file}_v{_wv}",
help=f"Re-send all {len(rerun_pages)} page(s) to the model in one request"):
with st.spinner(f"Re-running inference on all {len(rerun_pages)} page(s)β¦"):
raw_output = run_inference_vllm(rerun_pages)
if raw_output is None:
st.error("No response from vLLM.")
else:
st.session_state.raw_outputs[file_name] = raw_output
new_gt_parse = parse_model_json(raw_output)
if new_gt_parse is None:
st.error("Model output could not be parsed as JSON β see raw model output below.")
else:
st.session_state.edited_data[selected_file]['gt_parse'] = deepcopy(new_gt_parse)
st.session_state.data[selected_file]['gt_parse'] = deepcopy(new_gt_parse)
st.session_state.modified_indices.discard(selected_file)
if file_name in st.session_state.get('extraction_errors', []):
st.session_state.extraction_errors.remove(file_name)
# Fresh widgets so the fields show the new values
refresh_record_widgets(selected_file)
st.session_state.canvas_key += 1
st.rerun()
with st.expander("π Show raw model output"):
raw_pred = st.session_state.raw_outputs.get(file_name)
if raw_pred is None:
st.warning("No raw output available.")
else:
st.code(str(raw_pred), language="json")
# RIGHT SIDE: Editable Details
with right_col:
with st.container(height=620, border=False):
gt_parse = st.session_state.edited_data[selected_file].get('gt_parse', {})
tab1, tab2, tab3, tab4 = st.tabs([
"π Remittance Details",
"π₯ Party Details",
"π¦ Bank Details",
"π Line Items"
])
# TAB 1: Remittance Details
with tab1:
remittance = gt_parse.get('Remittance_details', {})
# Each field with OCR button
col_input, col_btn = st.columns([5, 1])
with col_input:
remittance['Remittance_adv_no'] = st.text_input(
"Remittance Advice No",
value=remittance.get('Remittance_adv_no', ''),
key=f"rem_adv_no_{selected_file}_v{_wv}"
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_rem_adv_no_{selected_file}_v{_wv}",
type="primary" if is_ocr_active('Remittance_details', 'Remittance_adv_no') else "secondary",
help="OCR this field"):
activate_ocr_field('Remittance_details', 'Remittance_adv_no')
col_input, col_btn = st.columns([5, 1])
with col_input:
remittance['Remittance_adv_date'] = st.text_input(
"Remittance Advice Date",
value=remittance.get('Remittance_adv_date', ''),
key=f"rem_adv_date_{selected_file}_v{_wv}"
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_rem_adv_date_{selected_file}_v{_wv}",
type="primary" if is_ocr_active('Remittance_details', 'Remittance_adv_date') else "secondary",
help="OCR this field"):
activate_ocr_field('Remittance_details', 'Remittance_adv_date')
col_input, col_btn = st.columns([5, 1])
with col_input:
remittance['Payment_method'] = st.text_input(
"Payment Method",
value=remittance.get('Payment_method', ''),
key=f"payment_method_{selected_file}_v{_wv}"
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_payment_method_{selected_file}_v{_wv}",
type="primary" if is_ocr_active('Remittance_details', 'Payment_method') else "secondary",
help="OCR this field"):
activate_ocr_field('Remittance_details', 'Payment_method')
col_input, col_btn = st.columns([5, 1])
with col_input:
remittance['FCY'] = st.text_input(
"FCY (Foreign Currency)",
value=remittance.get('FCY', ''),
key=f"fcy_{selected_file}_v{_wv}"
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_fcy_{selected_file}_v{_wv}",
type="primary" if is_ocr_active('Remittance_details', 'FCY') else "secondary",
help="OCR this field"):
activate_ocr_field('Remittance_details', 'FCY')
col_input, col_btn = st.columns([5, 1])
with col_input:
remittance['Total_payment_amt_FCY'] = st.text_input(
"Total Payment Amount (FCY)",
value=remittance.get('Total_payment_amt_FCY', ''),
key=f"total_payment_{selected_file}_v{_wv}"
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_total_payment_{selected_file}_v{_wv}",
type="primary" if is_ocr_active('Remittance_details', 'Total_payment_amt_FCY') else "secondary",
help="OCR this field"):
activate_ocr_field('Remittance_details', 'Total_payment_amt_FCY')
col_input, col_btn = st.columns([5, 1])
with col_input:
remittance['Payment_date'] = st.text_input(
"Payment Date",
value=remittance.get('Payment_date', ''),
key=f"payment_date_{selected_file}_v{_wv}"
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_payment_date_{selected_file}_v{_wv}",
type="primary" if is_ocr_active('Remittance_details', 'Payment_date') else "secondary",
help="OCR this field"):
activate_ocr_field('Remittance_details', 'Payment_date')
col_input, col_btn = st.columns([5, 1])
with col_input:
remittance['Payment_ref_no'] = st.text_input(
"Payment Reference No",
value=remittance.get('Payment_ref_no', ''),
key=f"payment_ref_{selected_file}_v{_wv}"
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_payment_ref_{selected_file}_v{_wv}",
type="primary" if is_ocr_active('Remittance_details', 'Payment_ref_no') else "secondary",
help="OCR this field"):
activate_ocr_field('Remittance_details', 'Payment_ref_no')
gt_parse['Remittance_details'] = remittance
# TAB 2: Customer/Supplier Details with SWAP button
with tab2:
# SWAP BUTTON - Centered and prominent
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
if st.button("π Swap Customer β Supplier", key=f"swap_btn_{selected_file}_v{_wv}",
type="primary", use_container_width=True):
#help="Interchange customer and supplier details"):
if not st.session_state.just_swapped:
st.session_state.just_swapped = True
swap_customer_supplier_details(selected_file)
st.rerun()
# Reset the flag after rerun
if st.session_state.just_swapped:
st.session_state.just_swapped = False
st.markdown("**Customer Details**")
customer_supplier = gt_parse.get('Customer_supplier_details', {})
col_input, col_btn = st.columns([5, 1])
with col_input:
customer_supplier['Customer_name'] = st.text_input(
"Customer Name",
value=customer_supplier.get('Customer_name', ''),
key=f"cust_name_{selected_file}_v{_wv}"
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_cust_name_{selected_file}_v{_wv}",
type="primary" if is_ocr_active('Customer_supplier_details', 'Customer_name') else "secondary",
help="OCR this field"):
activate_ocr_field('Customer_supplier_details', 'Customer_name')
col_input, col_btn = st.columns([5, 1])
with col_input:
customer_supplier['Customer_address'] = st.text_area(
"Customer Address",
value=customer_supplier.get('Customer_address', ''),
key=f"cust_addr_{selected_file}_v{_wv}",
height=60
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_cust_addr_{selected_file}_v{_wv}",
type="primary" if is_ocr_active('Customer_supplier_details', 'Customer_address') else "secondary",
help="OCR this field"):
activate_ocr_field('Customer_supplier_details', 'Customer_address')
col_input, col_btn = st.columns([5, 1])
with col_input:
customer_supplier['Customer_contact_info'] = st.text_input(
"Customer Contact Info",
value=customer_supplier.get('Customer_contact_info', ''),
key=f"cust_contact_{selected_file}_v{_wv}"
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_cust_contact_{selected_file}_v{_wv}",
type="primary" if is_ocr_active('Customer_supplier_details', 'Customer_contact_info') else "secondary",
help="OCR this field"):
activate_ocr_field('Customer_supplier_details', 'Customer_contact_info')
st.markdown("**Supplier Details**")
col_input, col_btn = st.columns([5, 1])
with col_input:
customer_supplier['Supplier_name'] = st.text_input(
"Supplier Name",
value=customer_supplier.get('Supplier_name', ''),
key=f"supp_name_{selected_file}_v{_wv}"
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_supp_name_{selected_file}_v{_wv}",
type="primary" if is_ocr_active('Customer_supplier_details', 'Supplier_name') else "secondary",
help="OCR this field"):
activate_ocr_field('Customer_supplier_details', 'Supplier_name')
col_input, col_btn = st.columns([5, 1])
with col_input:
customer_supplier['Supplier_address'] = st.text_area(
"Supplier Address",
value=customer_supplier.get('Supplier_address', ''),
key=f"supp_addr_{selected_file}_v{_wv}",
height=60
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_supp_addr_{selected_file}_v{_wv}",
type="primary" if is_ocr_active('Customer_supplier_details', 'Supplier_address') else "secondary",
help="OCR this field"):
activate_ocr_field('Customer_supplier_details', 'Supplier_address')
col_input, col_btn = st.columns([5, 1])
with col_input:
customer_supplier['Supplier_contact_info'] = st.text_input(
"Supplier Contact Info",
value=customer_supplier.get('Supplier_contact_info', ''),
key=f"supp_contact_{selected_file}_v{_wv}"
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_supp_contact_{selected_file}_v{_wv}",
type="primary" if is_ocr_active('Customer_supplier_details', 'Supplier_contact_info') else "secondary",
help="OCR this field"):
activate_ocr_field('Customer_supplier_details', 'Supplier_contact_info')
gt_parse['Customer_supplier_details'] = customer_supplier
# TAB 3: Bank Details
with tab3:
bank = gt_parse.get('Bank_details', {})
col_input, col_btn = st.columns([5, 1])
with col_input:
bank['Bank_name'] = st.text_input(
"Bank Name",
value=bank.get('Bank_name', ''),
key=f"bank_name_{selected_file}_v{_wv}"
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_bank_name_{selected_file}_v{_wv}",
type="primary" if is_ocr_active('Bank_details', 'Bank_name') else "secondary",
help="OCR this field"):
activate_ocr_field('Bank_details', 'Bank_name')
col_input, col_btn = st.columns([5, 1])
with col_input:
bank['Bank_acc_no'] = st.text_input(
"Bank Account No",
value=bank.get('Bank_acc_no', ''),
key=f"bank_acc_{selected_file}_v{_wv}"
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_bank_acc_{selected_file}_v{_wv}",
type="primary" if is_ocr_active('Bank_details', 'Bank_acc_no') else "secondary",
help="OCR this field"):
activate_ocr_field('Bank_details', 'Bank_acc_no')
col_input, col_btn = st.columns([5, 1])
with col_input:
bank['Bank_routing_no'] = st.text_input(
"Bank Routing No",
value=bank.get('Bank_routing_no', ''),
key=f"bank_routing_{selected_file}_v{_wv}"
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_bank_routing_{selected_file}_v{_wv}",
type="primary" if is_ocr_active('Bank_details', 'Bank_routing_no') else "secondary",
help="OCR this field"):
activate_ocr_field('Bank_details', 'Bank_routing_no')
col_input, col_btn = st.columns([5, 1])
with col_input:
bank['Swift_code'] = st.text_input(
"SWIFT Code",
value=bank.get('Swift_code', ''),
key=f"swift_{selected_file}_v{_wv}"
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_swift_{selected_file}_v{_wv}",
type="primary" if is_ocr_active('Bank_details', 'Swift_code') else "secondary",
help="OCR this field"):
activate_ocr_field('Bank_details', 'Swift_code')
gt_parse['Bank_details'] = bank
# TAB 4: Line Items
with tab4:
current_gt_parse = st.session_state.edited_data[selected_file].get('gt_parse', {})
line_items = current_gt_parse.get('Line_items', [])
# Add/Remove row buttons
col_add, col_remove = st.columns([1, 1])
with col_add:
if st.button("β Add New Row", key=f"add_row_{selected_file}_v{_wv}", use_container_width=True):
if not st.session_state.button_clicked:
st.session_state.button_clicked = True
new_row = {
"Po_number": "", "Invoice_no": "", "Other_doc_ref_no": "",
"Invoice_date": "", "Invoice_amount_FCY": "",
"Amount_paid_for_each_invoice": "", "Outstanding_balance_FCY": "",
"Discounts_taken_FCY": "", "Adjustments(without_holding_tax)_FCY": "",
"Descriptions": ""
}
current_gt_parse = st.session_state.edited_data[selected_file].get('gt_parse', {})
current_line_items = current_gt_parse.get('Line_items', [])
current_line_items.append(new_row)
current_gt_parse['Line_items'] = current_line_items
st.session_state.edited_data[selected_file]['gt_parse'] = current_gt_parse
st.session_state.modified_indices.add(selected_file)
st.rerun()
with col_remove:
if st.button("β Remove Last Row", key=f"remove_row_{selected_file}_v{_wv}",
disabled=(len(line_items) == 0), use_container_width=True):
if not st.session_state.button_clicked and len(line_items) > 0:
st.session_state.button_clicked = True
current_gt_parse = st.session_state.edited_data[selected_file].get('gt_parse', {})
current_line_items = current_gt_parse.get('Line_items', [])
current_line_items.pop()
current_gt_parse['Line_items'] = current_line_items
st.session_state.edited_data[selected_file]['gt_parse'] = current_gt_parse
st.session_state.modified_indices.add(selected_file)
st.rerun()
if st.session_state.button_clicked:
st.session_state.button_clicked = False
#st.markdown("---")
# Display each row as an expander with OCR buttons
current_gt_parse = st.session_state.edited_data[selected_file].get('gt_parse', {})
line_items = current_gt_parse.get('Line_items', [])
if line_items:
for idx, item in enumerate(line_items):
with st.expander(f"**Row {idx + 1}** - Invoice: {item.get('Invoice_no', 'N/A')}", expanded=(idx == 0)):
# PO Number
col_input, col_btn = st.columns([5, 1])
with col_input:
item['Po_number'] = st.text_input(
"PO Number",
value=item.get('Po_number', ''),
key=f"po_num_{selected_file}_{idx}_v{_wv}"
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_po_{selected_file}_{idx}_v{_wv}",
type="primary" if is_ocr_active('Line_items', 'Po_number', idx) else "secondary",
help="OCR this field"):
activate_ocr_field('Line_items', 'Po_number', idx)
# Invoice No
col_input, col_btn = st.columns([5, 1])
with col_input:
item['Invoice_no'] = st.text_input(
"Invoice No",
value=item.get('Invoice_no', ''),
key=f"inv_no_{selected_file}_{idx}_v{_wv}"
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_inv_{selected_file}_{idx}_v{_wv}",
type="primary" if is_ocr_active('Line_items', 'Invoice_no', idx) else "secondary",
help="OCR this field"):
activate_ocr_field('Line_items', 'Invoice_no', idx)
# Other Doc Ref No
col_input, col_btn = st.columns([5, 1])
with col_input:
item['Other_doc_ref_no'] = st.text_input(
"Other Doc Ref No",
value=item.get('Other_doc_ref_no', ''),
key=f"other_doc_{selected_file}_{idx}_v{_wv}"
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_other_{selected_file}_{idx}_v{_wv}",
type="primary" if is_ocr_active('Line_items', 'Other_doc_ref_no', idx) else "secondary",
help="OCR this field"):
activate_ocr_field('Line_items', 'Other_doc_ref_no', idx)
# Invoice Date
col_input, col_btn = st.columns([5, 1])
with col_input:
item['Invoice_date'] = st.text_input(
"Invoice Date",
value=item.get('Invoice_date', ''),
key=f"inv_date_{selected_file}_{idx}_v{_wv}"
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_inv_date_{selected_file}_{idx}_v{_wv}",
type="primary" if is_ocr_active('Line_items', 'Invoice_date', idx) else "secondary",
help="OCR this field"):
activate_ocr_field('Line_items', 'Invoice_date', idx)
# Invoice Amount FCY
col_input, col_btn = st.columns([5, 1])
with col_input:
item['Invoice_amount_FCY'] = st.text_input(
"Invoice Amount FCY",
value=item.get('Invoice_amount_FCY', ''),
key=f"inv_amt_{selected_file}_{idx}_v{_wv}"
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_inv_amt_{selected_file}_{idx}_v{_wv}",
type="primary" if is_ocr_active('Line_items', 'Invoice_amount_FCY', idx) else "secondary",
help="OCR this field"):
activate_ocr_field('Line_items', 'Invoice_amount_FCY', idx)
# Amount Paid
col_input, col_btn = st.columns([5, 1])
with col_input:
item['Amount_paid_for_each_invoice'] = st.text_input(
"Amount Paid",
value=item.get('Amount_paid_for_each_invoice', ''),
key=f"amt_paid_{selected_file}_{idx}_v{_wv}"
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_amt_paid_{selected_file}_{idx}_v{_wv}",
type="primary" if is_ocr_active('Line_items', 'Amount_paid_for_each_invoice', idx) else "secondary",
help="OCR this field"):
activate_ocr_field('Line_items', 'Amount_paid_for_each_invoice', idx)
# Outstanding Balance
col_input, col_btn = st.columns([5, 1])
with col_input:
item['Outstanding_balance_FCY'] = st.text_input(
"Outstanding Balance FCY",
value=item.get('Outstanding_balance_FCY', ''),
key=f"out_bal_{selected_file}_{idx}_v{_wv}"
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_out_bal_{selected_file}_{idx}_v{_wv}",
type="primary" if is_ocr_active('Line_items', 'Outstanding_balance_FCY', idx) else "secondary",
help="OCR this field"):
activate_ocr_field('Line_items', 'Outstanding_balance_FCY', idx)
# Discounts
col_input, col_btn = st.columns([5, 1])
with col_input:
item['Discounts_taken_FCY'] = st.text_input(
"Discounts Taken FCY",
value=item.get('Discounts_taken_FCY', ''),
key=f"disc_{selected_file}_{idx}_v{_wv}"
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_disc_{selected_file}_{idx}_v{_wv}",
type="primary" if is_ocr_active('Line_items', 'Discounts_taken_FCY', idx) else "secondary",
help="OCR this field"):
activate_ocr_field('Line_items', 'Discounts_taken_FCY', idx)
# Adjustments
col_input, col_btn = st.columns([5, 1])
with col_input:
item['Adjustments(without_holding_tax)_FCY'] = st.text_input(
"Adjustments FCY",
value=item.get('Adjustments(without_holding_tax)_FCY', ''),
key=f"adj_{selected_file}_{idx}_v{_wv}"
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_adj_{selected_file}_{idx}_v{_wv}",
type="primary" if is_ocr_active('Line_items', 'Adjustments(without_holding_tax)_FCY', idx) else "secondary",
help="OCR this field"):
activate_ocr_field('Line_items', 'Adjustments(without_holding_tax)_FCY', idx)
# Descriptions
col_input, col_btn = st.columns([5, 1])
with col_input:
item['Descriptions'] = st.text_area(
"Descriptions",
value=item.get('Descriptions', ''),
key=f"desc_{selected_file}_{idx}_v{_wv}",
height=60
)
with col_btn:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("π", key=f"ocr_desc_{selected_file}_{idx}_v{_wv}",
type="primary" if is_ocr_active('Line_items', 'Descriptions', idx) else "secondary",
help="OCR this field"):
activate_ocr_field('Line_items', 'Descriptions', idx)
# Update line items back to gt_parse
current_gt_parse['Line_items'] = line_items
#st.markdown("---")
st.markdown("**π Line Items Summary Table**")
# Display summary table with index starting from 1
df = pd.DataFrame(line_items)
df.index = df.index + 1 # Start index from 1
df.index.name = 'SL No'
st.dataframe(
df,
use_container_width=True,
height=300
)
else:
st.info("No line items. Click 'β Add New Row' to add a new row.")
st.session_state.edited_data[selected_file]['gt_parse'] = gt_parse
# Save button
#st.markdown("---")
col1, col2 = st.columns([1, 1])
with col1:
if st.button("πΎ Save All Edits", type="primary", use_container_width=True, key=f"save_btn_{selected_file}_v{_wv}"):
if not st.session_state.just_saved:
st.session_state.just_saved = True
auto_save(selected_file)
st.session_state.save_message = "β
Changes saved successfully!"
st.session_state.save_message_time = time.time()
st.rerun()
if st.session_state.just_saved:
st.session_state.just_saved = False
if st.session_state.save_message:
st.success(st.session_state.save_message)
# Per-document downloads (current values of this record)
current_doc = st.session_state.edited_data[selected_file]
file_df = pd.DataFrame(flatten_remittance_to_rows(current_doc))
file_stem = os.path.splitext(current_doc.get('file_name', 'remittance'))[0]
per_dl_cols = st.columns(3)
with per_dl_cols[0]:
st.download_button("π₯ CSV",
file_df.to_csv(index=False).encode("utf-8"),
file_name=f"{file_stem}.csv",
mime="text/csv",
key=f"dl_csv_{selected_file}_v{_wv}",
use_container_width=True)
with per_dl_cols[1]:
st.download_button("π₯ Excel",
build_excel_bytes(file_df),
file_name=f"{file_stem}.xlsx",
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
key=f"dl_xlsx_{selected_file}_v{_wv}",
use_container_width=True)
with per_dl_cols[2]:
st.download_button("π₯ JSONL",
save_to_jsonl([current_doc]),
file_name=f"{file_stem}.jsonl",
mime="application/jsonl",
key=f"dl_jsonl_{selected_file}_v{_wv}",
use_container_width=True)
import os
from pathlib import Path
# -----------------------------
# Environment hardening (HF Spaces, /.cache issue)
# -----------------------------
_home = os.environ.get("HOME", "")
if _home in ("", "/", None):
repo_dir = os.getcwd()
safe_home = repo_dir if os.access(repo_dir, os.W_OK) else "/tmp"
os.environ["HOME"] = safe_home
print(f"[startup] HOME not set or unwritable β setting HOME={safe_home}")
streamlit_dir = Path(os.environ["HOME"]) / ".streamlit"
try:
streamlit_dir.mkdir(parents=True, exist_ok=True)
print(f"[startup] ensured {streamlit_dir}")
except Exception as e:
print(f"[startup] WARNING: could not create {streamlit_dir}: {e}")
import streamlit as st
import json
import io
from PIL import Image
import time
import pandas as pd
from streamlit_drawable_canvas import st_canvas
import pytesseract
import numpy as np
from datetime import datetime
import base64
from copy import deepcopy
from typing import List
import requests
import fitz # PyMuPDF: renders PDF pages to images
# Compatibility: streamlit-drawable-canvas 0.9.3 calls streamlit.elements.image.image_to_url,
# which newer Streamlit moved to elements.lib.image_utils (taking a LayoutConfig instead of width).
# (Only used if a background_image is ever passed; this app embeds the image via initial_drawing.)
import streamlit.elements.image as _st_image_module
if not hasattr(_st_image_module, "image_to_url"):
try:
from streamlit.elements.lib.image_utils import image_to_url as _new_image_to_url
from streamlit.elements.lib.layout_utils import LayoutConfig as _LayoutConfig
def _compat_image_to_url(image, width, clamp, channels, output_format, image_id):
return _new_image_to_url(image, _LayoutConfig(width=width), clamp, channels, output_format, image_id)
_st_image_module.image_to_url = _compat_image_to_url
except Exception as _compat_err:
print(f"[startup] WARNING: drawable-canvas compatibility patch failed: {_compat_err}")
def canvas_background_drawing(image, width, height):
"""Starting state for st_canvas with the page image embedded as its background.
st_canvas(background_image=...) makes the browser fetch the image from /media/..., which
fails behind proxies/iframes such as Hugging Face Spaces (blank canvas). Embedding the image
in initial_drawing needs no extra request. Only user-drawn shapes appear in json_data['objects'].
"""
img = image.convert("RGB").resize((int(width), int(height)), Image.Resampling.LANCZOS)
buf = io.BytesIO()
img.save(buf, format="JPEG", quality=92)
data_url = "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode("ascii")
return {
"version": "4.4.0",
"objects": [],
"backgroundImage": {
"type": "image", "version": "4.4.0", "originX": "left", "originY": "top",
"left": 0, "top": 0, "width": int(width), "height": int(height),
"scaleX": 1, "scaleY": 1, "src": data_url, "crossOrigin": None,
},
}
# Set Tesseract path - auto-detect based on OS
if os.name == 'nt': # Windows
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
else: # Linux/Mac (HF Spaces uses Linux)
pass
# Page configuration
st.set_page_config(page_title="Remittance Data Viewer", layout="wide")
# -----------------------------
# API configuration (vLLM pod)
# -----------------------------
POD_URL = os.getenv("POD_URL", "https://zud7ytk3vq1k10-8000.proxy.runpod.net")
VLLM_API_KEY = os.getenv("VLLM_API_KEY", "9386aa7335c2072882ad367791f1dc863c63b4be88eda14c2dea0408f9d0105e")
MODEL_NAME = "Remi-Merged"
MAX_PAGES_PER_REQUEST = 10
MAX_DIMENSION_PER_PAGE = 1560
MAX_TOTAL_PAYLOAD_MB = 40.0
if not POD_URL or not VLLM_API_KEY:
st.error("β οΈ API credentials not configured. Please set POD_URL and VLLM_API_KEY in Space settings.")
st.stop()
# Custom CSS
st.markdown("""