rasmodev commited on
Commit
9139789
Β·
verified Β·
1 Parent(s): f4bc948

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +315 -389
app.py CHANGED
@@ -1,5 +1,5 @@
1
  """
2
- ValuationAI OCR β€” Streamlit App
3
  Model: rasmodev/Handwriting_trocr_model
4
  """
5
  import io, time, logging
@@ -17,273 +17,255 @@ logging.basicConfig(level=logging.INFO)
17
 
18
  st.markdown("""
19
  <style>
20
- @import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@600;700&family=Outfit:wght@300;400;500;600&display=swap');
21
 
22
- html, body, [class*="css"] {
23
- font-family: 'Outfit', sans-serif;
24
- background-color: #080D1A;
25
- color: #E2E8F0;
26
  }
27
 
28
- .stApp {
29
- background: #080D1A;
30
- }
31
-
32
- /* Remove default padding */
33
  .block-container {
34
- padding-top: 2rem !important;
35
- padding-bottom: 3rem !important;
36
- max-width: 1200px !important;
37
  }
38
 
39
- /* Hide Streamlit chrome */
40
- #MainMenu, footer { visibility: hidden; }
41
 
42
- /* ── Brand bar ── */
43
- .brand {
44
  display: flex;
45
- align-items: center;
46
  justify-content: space-between;
47
- padding-bottom: 1.5rem;
48
- border-bottom: 1px solid rgba(255,255,255,0.06);
49
- margin-bottom: 2.5rem;
50
- }
51
- .brand-left { display: flex; align-items: center; gap: 10px; }
52
- .brand-dot {
53
- width: 10px; height: 10px; border-radius: 50%;
54
- background: #6366F1;
55
- box-shadow: 0 0 14px rgba(99,102,241,0.9);
56
- animation: glow 2s ease-in-out infinite;
57
- }
58
- @keyframes glow {
59
- 0%,100% { opacity:1; transform:scale(1); }
60
- 50% { opacity:0.5; transform:scale(0.8); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  }
62
- .brand-name {
63
- font-family: 'Playfair Display', serif;
64
- font-size: 1.3rem; font-weight: 700; color: #fff;
65
  }
66
- .brand-tag {
67
- font-size: 0.68rem; color: #4B5563; letter-spacing: 0.1em;
68
- text-transform: uppercase; font-weight: 500;
69
  }
70
- .model-pill {
71
- font-size: 0.7rem; font-weight: 500;
72
- background: rgba(99,102,241,0.12);
73
- border: 1px solid rgba(99,102,241,0.28);
74
- color: #A5B4FC; padding: 0.3rem 0.9rem;
75
- border-radius: 20px; letter-spacing: 0.04em;
76
  }
77
 
78
- /* ── Hero ── */
79
- .hero-eyebrow {
80
- font-size: 0.68rem; font-weight: 600; letter-spacing: 0.2em;
81
- text-transform: uppercase; color: #6366F1; margin-bottom: 0.7rem;
82
- }
83
- .hero-h1 {
84
- font-family: 'Playfair Display', serif;
85
- font-size: 2.8rem; font-weight: 700; line-height: 1.12;
86
- letter-spacing: -0.025em; color: #fff; margin-bottom: 0.8rem;
 
 
 
 
 
 
87
  }
88
- .hero-h1 span {
89
- background: linear-gradient(130deg, #6366F1, #10B981);
90
- -webkit-background-clip: text; -webkit-text-fill-color: transparent;
91
- background-clip: text;
92
  }
93
- .hero-sub {
94
- font-size: 1rem; font-weight: 300; color: #6B7280;
95
- line-height: 1.7; max-width: 460px; margin-bottom: 2.5rem;
 
 
 
96
  }
97
 
98
- /* ── Cards ── */
99
- .card {
100
- background: rgba(255,255,255,0.025);
101
- border: 1px solid rgba(255,255,255,0.065);
102
- border-radius: 18px; padding: 1.8rem;
103
- transition: border-color 0.2s;
104
- }
105
- .card:hover { border-color: rgba(99,102,241,0.28); }
106
- .card-label {
107
- font-size: 0.65rem; font-weight: 600; letter-spacing: 0.15em;
108
- text-transform: uppercase; color: #4B5563; margin-bottom: 1.2rem;
109
- display: flex; align-items: center; gap: 8px;
110
- }
111
- .card-label::before {
112
- content:''; display:inline-block; width:16px; height:2px;
113
- background:#6366F1; border-radius:2px;
114
  }
115
-
116
- /* ── File chips ── */
117
- .chip {
118
- display: inline-flex; align-items: center; gap: 5px;
119
- background: rgba(16,185,129,0.1);
120
- border: 1px solid rgba(16,185,129,0.22);
121
- color: #6EE7B7; padding: 0.25rem 0.7rem;
122
- border-radius: 20px; font-size: 0.72rem; font-weight: 500; margin: 2px;
123
  }
124
 
125
- /* ── Stats ── */
126
- .stat-grid {
127
- display: grid; grid-template-columns: repeat(4,1fr); gap: 1rem;
128
- margin: 1.8rem 0;
129
- }
130
- .stat {
131
- background: rgba(255,255,255,0.025);
132
- border: 1px solid rgba(255,255,255,0.06);
133
- border-radius: 14px; padding: 1.2rem 1.4rem;
134
- position: relative; overflow: hidden;
135
- }
136
- .stat::after {
137
- content:''; position:absolute; top:0; left:0; right:0; height:2px;
138
- background: linear-gradient(90deg,#6366F1,#10B981);
139
- }
 
140
  .stat-n {
141
- font-family: 'Playfair Display', serif;
142
- font-size: 2rem; font-weight: 700; color: #fff; line-height: 1;
 
 
 
 
143
  }
144
  .stat-l {
145
- font-size: 0.68rem; font-weight: 500; letter-spacing: 0.1em;
146
- text-transform: uppercase; color: #4B5563; margin-top: 4px;
147
- }
148
-
149
- /* ── Result header ── */
150
- .result-row {
151
- display: flex; align-items: center;
152
- justify-content: space-between; margin-bottom: 1.2rem;
153
- }
154
- .result-title {
155
- font-family: 'Playfair Display', serif;
156
- font-size: 1.4rem; font-weight: 600; color: #fff;
157
- }
158
- .result-badge {
159
- font-size: 0.68rem; font-weight: 600; letter-spacing: 0.1em;
160
- text-transform: uppercase; color: #10B981;
161
- background: rgba(16,185,129,0.1);
162
- border: 1px solid rgba(16,185,129,0.2);
163
- padding: 0.28rem 0.8rem; border-radius: 20px;
164
- }
165
-
166
- /* ── Divider ── */
167
- .divider {
168
- height: 1px; margin: 2rem 0;
169
- background: linear-gradient(90deg,transparent,rgba(255,255,255,0.07),transparent);
170
  }
171
 
172
- /* ── Empty state boxes ── */
173
- .empty-card {
174
- background: rgba(255,255,255,0.02);
175
- border: 1px solid rgba(255,255,255,0.055);
176
- border-radius: 14px; padding: 2rem 1.5rem; text-align: center;
177
- }
178
- .empty-icon { font-size: 1.8rem; margin-bottom: 0.7rem; }
179
- .empty-title { font-weight: 600; color: #E2E8F0; margin-bottom: 0.4rem; font-size: 0.95rem; }
180
- .empty-desc { font-size: 0.78rem; color: #4B5563; line-height: 1.6; }
181
-
182
- /* ── Streamlit widget overrides ── */
183
- /* File uploader */
184
- [data-testid="stFileUploader"] section {
185
- background: rgba(99,102,241,0.04) !important;
186
- border: 2px dashed rgba(99,102,241,0.3) !important;
187
- border-radius: 14px !important;
188
- transition: all 0.2s !important;
189
- }
190
- [data-testid="stFileUploader"] section:hover {
191
- border-color: rgba(99,102,241,0.6) !important;
192
- background: rgba(99,102,241,0.08) !important;
193
- }
194
- [data-testid="stFileUploader"] label { color: #6B7280 !important; }
195
-
196
- /* Primary button */
197
- .stButton > button[kind="primary"] {
198
- background: linear-gradient(135deg, #6366F1, #4F46E5) !important;
199
- color: white !important; border: none !important;
200
- border-radius: 12px !important; padding: 0.75rem 2rem !important;
201
- font-family: 'Outfit', sans-serif !important;
202
- font-size: 0.9rem !important; font-weight: 600 !important;
203
- box-shadow: 0 4px 20px rgba(99,102,241,0.4) !important;
204
- transition: all 0.2s !important; width: 100% !important;
205
- }
206
- .stButton > button[kind="primary"]:hover {
207
- transform: translateY(-2px) !important;
208
- box-shadow: 0 8px 28px rgba(99,102,241,0.55) !important;
209
  }
210
- .stButton > button:disabled {
211
- background: rgba(255,255,255,0.05) !important;
212
- color: #374151 !important; box-shadow: none !important;
213
- transform: none !important; border: 1px solid rgba(255,255,255,0.06) !important;
 
 
214
  }
215
 
216
- /* Download button */
217
  div[data-testid="stDownloadButton"] > button {
218
- background: rgba(16,185,129,0.1) !important;
219
- border: 1px solid rgba(16,185,129,0.28) !important;
220
- color: #6EE7B7 !important; border-radius: 10px !important;
 
221
  padding: 0.6rem 1.4rem !important;
222
- font-family: 'Outfit', sans-serif !important;
223
- font-weight: 600 !important; font-size: 0.85rem !important;
 
 
 
224
  transition: all 0.2s !important;
 
 
225
  }
226
  div[data-testid="stDownloadButton"] > button:hover {
227
- background: rgba(16,185,129,0.18) !important;
228
- transform: translateY(-1px) !important;
229
- }
230
-
231
- /* Select box */
232
- [data-testid="stSelectbox"] > div > div {
233
- background: rgba(255,255,255,0.04) !important;
234
- border: 1px solid rgba(255,255,255,0.09) !important;
235
- border-radius: 10px !important; color: #E2E8F0 !important;
236
- }
237
-
238
- /* Slider */
239
- [data-testid="stSlider"] > div > div > div > div {
240
- background: #6366F1 !important;
241
- }
242
-
243
- /* Progress bar */
244
- .stProgress > div > div > div {
245
- background: linear-gradient(90deg,#6366F1,#10B981) !important;
246
- border-radius: 4px !important;
247
- }
248
- .stProgress > div > div {
249
- background: rgba(255,255,255,0.06) !important;
250
- border-radius: 4px !important; height: 5px !important;
251
  }
252
 
253
- /* Dataframe */
254
  [data-testid="stDataFrame"] {
255
- border-radius: 14px !important;
256
- border: 1px solid rgba(255,255,255,0.07) !important;
257
  overflow: hidden !important;
 
258
  }
259
 
260
- /* Number input */
261
- [data-testid="stNumberInput"] input {
262
- background: rgba(255,255,255,0.04) !important;
263
- border: 1px solid rgba(255,255,255,0.09) !important;
264
- border-radius: 10px !important; color: #E2E8F0 !important;
 
 
 
 
 
 
265
  }
266
 
267
- /* Expander */
268
- [data-testid="stExpander"] {
269
- background: rgba(255,255,255,0.02) !important;
270
- border: 1px solid rgba(255,255,255,0.06) !important;
271
- border-radius: 12px !important;
 
 
 
272
  }
273
 
274
- /* Alert/success */
275
- [data-testid="stAlert"] {
276
- border-radius: 12px !important;
277
- border: none !important;
278
  }
279
  </style>
280
  """, unsafe_allow_html=True)
281
 
282
 
283
  # ═══════════════════════════════════════════════════════════
284
- # MODEL LOADING
285
  # ═══════════════════════════════════════════════════════════
286
- @st.cache_resource(show_spinner="Loading model from HuggingFace Hub…")
287
  def load_model():
288
  import torch
289
  from transformers import TrOCRProcessor, VisionEncoderDecoderModel
@@ -294,16 +276,11 @@ def load_model():
294
  model.to(device).eval()
295
  return processor, model, device
296
 
297
- @st.cache_resource(show_spinner="Loading EasyOCR…")
298
- def load_easyocr():
299
- import easyocr
300
- return easyocr.Reader(["en"], gpu=False)
301
-
302
 
303
  # ═══════════════════════════════════════════════════════════
304
  # HELPERS
305
  # ═══════════════════════════════════════════════════════════
306
- def run_finetuned(img):
307
  import torch
308
  processor, model, device = load_model()
309
  pv = processor(images=img.convert("RGB"), return_tensors="pt").pixel_values.to(device)
@@ -311,67 +288,55 @@ def run_finetuned(img):
311
  gen = model.generate(pv, max_new_tokens=64)
312
  return processor.batch_decode(gen, skip_special_tokens=True)[0].strip()
313
 
314
- def run_easyocr(img):
315
- import numpy as np
316
- results = load_easyocr().readtext(np.array(img.convert("RGB")), detail=0, paragraph=True)
317
- return "\n".join(results).strip()
318
-
319
- def ocr_image(img, engine):
320
- try:
321
- return run_finetuned(img) if engine == "finetuned" else run_easyocr(img)
322
- except:
323
- try: return run_easyocr(img)
324
- except: return ""
325
-
326
- def pdf_to_images(file_bytes, dpi=200, max_pages=None):
327
  import fitz
328
- doc = fitz.open(stream=file_bytes, filetype="pdf")
329
- mat = fitz.Matrix(dpi/72, dpi/72)
330
- limit = min(len(doc), max_pages) if max_pages else len(doc)
331
- pages = []
332
- for i in range(limit):
333
  pix = doc[i].get_pixmap(matrix=mat, alpha=False)
334
- pages.append((i+1, Image.open(io.BytesIO(pix.tobytes("png"))).convert("RGB")))
335
  doc.close()
336
- return pages
337
 
338
- def extract_fields(text, filename):
339
  import re
340
- def find(label):
341
  m = re.search(label + r'[:\s]+([^\|\n]{1,80})', text, re.IGNORECASE)
342
  return m.group(1).strip() if m else ""
343
  amounts = re.findall(r'AMT:\s*([\d,]+)', text)
344
- dates = re.search(r'DATE:\s*(\d{4}-\d{2}-\d{2})', text)
345
  return {
346
- "File": filename,
347
- "Plot Number": find("PLOT"),
348
- "Location": find("LOC"),
349
- "Area": find("AREA"),
350
- "Amount (KES)": int(amounts[0].replace(",","")) if amounts else None,
351
- "Date": dates.group(1) if dates else None,
352
- "VOS": find("VOS"),
353
  }
354
 
355
- def to_excel(records):
356
  from openpyxl import load_workbook
357
  from openpyxl.styles import Font, PatternFill, Alignment
358
  from openpyxl.utils import get_column_letter
359
  buf = io.BytesIO()
360
  pd.DataFrame(records).to_excel(buf, index=False, sheet_name="Valuation Data")
361
  buf.seek(0)
362
- wb = load_workbook(buf)
363
- ws = wb.active
 
364
  for ci, cell in enumerate(ws[1], 1):
365
  cell.font = Font(name="Calibri", bold=True, color="FFFFFF", size=11)
366
- cell.fill = PatternFill("solid", start_color="1E1B4B")
367
  cell.alignment = Alignment(horizontal="center", vertical="center")
368
- ws.column_dimensions[get_column_letter(ci)].width = 22
369
  ws.row_dimensions[1].height = 30
370
  for row in ws.iter_rows(min_row=2):
371
  for cell in row:
372
  cell.alignment = Alignment(vertical="center", wrap_text=True)
373
  if cell.row % 2 == 0:
374
- cell.fill = PatternFill("solid", start_color="F5F4FF")
375
  ws.freeze_panes = "A2"
376
  out = io.BytesIO(); wb.save(out)
377
  return out.getvalue()
@@ -380,211 +345,172 @@ def to_excel(records):
380
  # ═══════════════════════════════════════════════════════════
381
  # SESSION STATE
382
  # ═══════════════════════════════════��═══════════════════════
383
- for k, v in [("records",[]),("errors",[]),("excel_bytes",None),("done",False)]:
384
  if k not in st.session_state:
385
  st.session_state[k] = v
386
 
387
 
388
  # ═══════════════════════════════════════════════════════════
389
- # BRAND BAR
390
  # ═══════════════════════════════════════════════════════════
391
  st.markdown("""
392
- <div class="brand">
393
- <div class="brand-left">
394
- <div class="brand-dot"></div>
395
- <div>
396
- <div class="brand-name">ValuationAI</div>
397
- <div class="brand-tag">Handwriting Recognition System</div>
398
- </div>
 
399
  </div>
400
- <div class="model-pill">rasmodev/Handwriting_trocr_model</div>
401
  </div>
402
  """, unsafe_allow_html=True)
403
 
404
 
405
  # ═══════════════════════════════════════════════════════════
406
- # HERO
407
  # ═══════════════════════════════════════════════════════════
408
  st.markdown("""
409
- <div class="hero-eyebrow">AI-Powered Document Intelligence</div>
410
- <div class="hero-h1">Extract data from<br><span>handwritten valuations</span></div>
411
- <div class="hero-sub">Upload scanned valuation sheet PDFs and get a clean,
412
- structured Excel export in seconds β€” powered by a fine-tuned TrOCR model.</div>
 
 
 
 
413
  """, unsafe_allow_html=True)
414
 
415
 
416
  # ═══════════════════════════════════════════════════════════
417
- # UPLOAD + SETTINGS (side by side)
418
  # ═══════════════════════════════════════════════════════════
419
- col_up, col_cfg = st.columns([3, 2], gap="large")
420
-
421
- with col_up:
422
- st.markdown('<div class="card"><div class="card-label">Upload Documents</div>', unsafe_allow_html=True)
423
- uploaded_files = st.file_uploader(
424
- "Drag & drop PDF files here",
425
- type=["pdf","png","jpg","jpeg","tiff","tif","bmp"],
426
- accept_multiple_files=True,
427
- label_visibility="collapsed",
428
- )
429
- if uploaded_files:
430
- chips = "".join(
431
- f'<span class="chip">πŸ“„ {f.name[:30]}{"…" if len(f.name)>30 else ""}</span>'
432
- for f in uploaded_files
433
- )
434
- st.markdown(f'<div style="margin-top:0.8rem">{chips}</div>', unsafe_allow_html=True)
435
- st.markdown('</div>', unsafe_allow_html=True)
436
-
437
- with col_cfg:
438
- st.markdown('<div class="card"><div class="card-label">Settings</div>', unsafe_allow_html=True)
439
-
440
- engine_sel = st.selectbox(
441
- "OCR Engine",
442
- ["🟒 Fine-tuned Model (Recommended)", "πŸ”΅ EasyOCR (Fallback)"],
443
- label_visibility="visible",
444
- )
445
- engine = "finetuned" if "Fine-tuned" in engine_sel else "easyocr"
446
 
447
- dpi = st.select_slider("Resolution (DPI)", options=[150, 200, 250, 300], value=200)
 
 
 
 
 
448
 
449
- max_p = st.number_input("Max pages per PDF (0 = all)", 0, 100, 0)
450
- max_pages = None if max_p == 0 else int(max_p)
 
 
 
 
451
 
452
- st.markdown("</div>", unsafe_allow_html=True)
 
453
 
454
- # Run button below settings
455
- _, btn_col, _ = st.columns([3, 2, 0.01])
456
- with btn_col:
457
- run = st.button(
458
- "⚑ Run OCR & Extract Fields",
459
- type="primary",
460
- disabled=not uploaded_files,
461
- use_container_width=True,
462
- )
463
 
464
 
465
  # ═══════════════════════════════════════════════════════════
466
  # PROCESSING
467
  # ═══════════════════════════════════════════════════════════
468
- if run and uploaded_files:
469
  st.session_state.records = []
470
  st.session_state.errors = []
471
  st.session_state.done = False
472
 
473
- st.markdown('<div class="divider"></div>', unsafe_allow_html=True)
474
  bar = st.progress(0.0)
475
  status = st.empty()
476
  t0 = time.time()
477
 
478
- for fi, uf in enumerate(uploaded_files):
479
  fname = uf.name
480
- file_bytes = uf.read()
481
- bar.progress(fi / len(uploaded_files), text=f"Reading {fname}…")
482
 
483
  try:
484
  ext = fname.lower().rsplit(".", 1)[-1]
485
- pages = pdf_to_images(file_bytes, dpi=dpi, max_pages=max_pages) \
486
- if ext == "pdf" \
487
- else [(1, Image.open(io.BytesIO(file_bytes)).convert("RGB"))]
488
 
489
- for page_no, img in pages:
490
- status.caption(f"Processing **{fname}** β€” page {page_no} of {len(pages)}")
491
- text = ocr_image(img, engine)
492
- record = extract_fields(text, fname)
493
- st.session_state.records.append(record)
494
 
495
  except Exception as e:
496
  st.session_state.errors.append(f"{fname}: {e}")
497
 
498
- bar.progress((fi+1)/len(uploaded_files))
499
 
500
  bar.empty(); status.empty()
501
- st.session_state.excel_bytes = to_excel(st.session_state.records) if st.session_state.records else None
502
- st.session_state.done = True
 
503
 
504
  elapsed = time.time() - t0
505
- st.success(f"βœ… Done β€” {len(st.session_state.records)} page(s) from {len(uploaded_files)} file(s) in {elapsed:.1f}s")
 
 
 
506
 
507
 
508
  # ═══════════════════════════════════════════════════════════
509
  # RESULTS
510
  # ═══════════════════════════════════════════════════════════
511
  if st.session_state.done and st.session_state.records:
512
- records = st.session_state.records
513
- df = pd.DataFrame(records)
514
 
515
- st.markdown('<div class="divider"></div>', unsafe_allow_html=True)
516
-
517
- # Stats
518
- n_plots = df["Plot Number"].astype(bool).sum() if "Plot Number" in df else 0
519
- n_amounts = df["Amount (KES)"].notna().sum() if "Amount (KES)" in df else 0
520
- n_dates = df["Date"].astype(bool).sum() if "Date" in df else 0
521
 
522
  st.markdown(f"""
523
- <div class="stat-grid">
524
- <div class="stat">
525
- <div class="stat-n">{len(records)}</div>
526
- <div class="stat-l">Pages Processed</div>
527
  </div>
528
- <div class="stat">
529
  <div class="stat-n">{n_plots}</div>
530
- <div class="stat-l">Plot Numbers</div>
531
  </div>
532
- <div class="stat">
533
  <div class="stat-n">{n_amounts}</div>
534
- <div class="stat-l">Amounts Found</div>
535
  </div>
536
- <div class="stat">
537
  <div class="stat-n">{n_dates}</div>
538
- <div class="stat-l">Dates Captured</div>
539
  </div>
540
  </div>
541
  """, unsafe_allow_html=True)
542
 
543
- # Title + download
544
- hdr_l, hdr_r = st.columns([4, 1])
545
- with hdr_l:
546
- st.markdown('<div class="result-row"><div class="result-title">Extracted Data</div><div class="result-badge">βœ“ Ready to export</div></div>', unsafe_allow_html=True)
547
- with hdr_r:
548
- if st.session_state.excel_bytes:
 
 
 
 
 
549
  st.download_button(
550
- "⬇ Download Excel",
551
- data=st.session_state.excel_bytes,
552
- file_name="valuation_extracted.xlsx",
553
  mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
554
  )
555
 
556
- # Dataframe
557
  st.dataframe(df, use_container_width=True,
558
- height=min(80 + len(df)*38, 520), hide_index=True)
559
 
560
  # Errors
561
  if st.session_state.errors:
562
- with st.expander(f"⚠ {len(st.session_state.errors)} file(s) had errors"):
563
  for e in st.session_state.errors:
564
- st.markdown(f'<span style="color:#F87171;font-size:0.85rem">{e}</span>', unsafe_allow_html=True)
565
-
566
-
567
- # ═══════════════════════════════════════════════════════════
568
- # EMPTY STATE
569
- # ═══════════════════════════════════════════════════════════
570
- if not st.session_state.done and not uploaded_files:
571
- st.markdown('<div class="divider"></div>', unsafe_allow_html=True)
572
- c1, c2, c3 = st.columns(3, gap="medium")
573
- with c1:
574
- st.markdown("""<div class="empty-card">
575
- <div class="empty-icon">πŸ“„</div>
576
- <div class="empty-title">Upload PDFs</div>
577
- <div class="empty-desc">Drag in one or multiple scanned valuation sheet PDFs</div>
578
- </div>""", unsafe_allow_html=True)
579
- with c2:
580
- st.markdown("""<div class="empty-card">
581
- <div class="empty-icon">πŸ€–</div>
582
- <div class="empty-title">AI Reads Fields</div>
583
- <div class="empty-desc">Fine-tuned TrOCR extracts plot numbers, amounts, dates and locations</div>
584
- </div>""", unsafe_allow_html=True)
585
- with c3:
586
- st.markdown("""<div class="empty-card">
587
- <div class="empty-icon">πŸ“Š</div>
588
- <div class="empty-title">Download Excel</div>
589
- <div class="empty-desc">Get a clean formatted spreadsheet ready for data entry</div>
590
- </div>""", unsafe_allow_html=True)
 
1
  """
2
+ ValuationAI β€” Nairobi Valuation Sheet OCR
3
  Model: rasmodev/Handwriting_trocr_model
4
  """
5
  import io, time, logging
 
17
 
18
  st.markdown("""
19
  <style>
20
+ @import url('https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@400;600;700&family=Inter:wght@300;400;500;600&display=swap');
21
 
22
+ html, body, [class*="css"], .stApp {
23
+ font-family: 'Inter', sans-serif;
24
+ background: #F8F7F4;
25
+ color: #1A1A2E;
26
  }
27
 
 
 
 
 
 
28
  .block-container {
29
+ padding: 3rem 4rem !important;
30
+ max-width: 1100px !important;
 
31
  }
32
 
33
+ #MainMenu, footer, header { visibility: hidden; }
 
34
 
35
+ /* ── Top bar ── */
36
+ .topbar {
37
  display: flex;
38
+ align-items: flex-end;
39
  justify-content: space-between;
40
+ padding-bottom: 2rem;
41
+ margin-bottom: 3rem;
42
+ border-bottom: 2px solid #1A1A2E;
43
+ }
44
+ .logo {
45
+ font-family: 'Cormorant Garamond', serif;
46
+ font-size: 1.8rem;
47
+ font-weight: 700;
48
+ color: #1A1A2E;
49
+ letter-spacing: -0.02em;
50
+ line-height: 1;
51
+ }
52
+ .logo span { color: #2563EB; }
53
+ .logo-sub {
54
+ font-size: 0.68rem;
55
+ font-weight: 500;
56
+ letter-spacing: 0.15em;
57
+ text-transform: uppercase;
58
+ color: #9CA3AF;
59
+ margin-top: 0.3rem;
60
+ }
61
+ .model-ref {
62
+ font-size: 0.7rem;
63
+ color: #9CA3AF;
64
+ font-weight: 400;
65
+ letter-spacing: 0.04em;
66
+ text-align: right;
67
+ }
68
+ .model-ref strong { color: #2563EB; font-weight: 600; }
69
+
70
+ /* ── Hero headline ── */
71
+ .headline {
72
+ font-family: 'Cormorant Garamond', serif;
73
+ font-size: 3.4rem;
74
+ font-weight: 700;
75
+ line-height: 1.08;
76
+ letter-spacing: -0.03em;
77
+ color: #1A1A2E;
78
+ margin-bottom: 1rem;
79
+ max-width: 700px;
80
+ }
81
+ .headline em {
82
+ font-style: italic;
83
+ color: #2563EB;
84
+ }
85
+ .subline {
86
+ font-size: 0.95rem;
87
+ font-weight: 300;
88
+ color: #6B7280;
89
+ line-height: 1.7;
90
+ max-width: 500px;
91
+ margin-bottom: 3rem;
92
+ }
93
+
94
+ /* ── Upload area ── */
95
+ [data-testid="stFileUploader"] section {
96
+ background: #fff !important;
97
+ border: 2px dashed #D1D5DB !important;
98
+ border-radius: 12px !important;
99
+ padding: 2.5rem !important;
100
+ transition: all 0.2s ease !important;
101
+ box-shadow: 0 1px 3px rgba(0,0,0,0.04) !important;
102
  }
103
+ [data-testid="stFileUploader"] section:hover {
104
+ border-color: #2563EB !important;
105
+ box-shadow: 0 0 0 4px rgba(37,99,235,0.06) !important;
106
  }
107
+ [data-testid="stFileUploader"] label {
108
+ color: #6B7280 !important;
109
+ font-size: 0.9rem !important;
110
  }
111
+ [data-testid="stFileUploadDropzone"] p {
112
+ color: #6B7280 !important;
 
 
 
 
113
  }
114
 
115
+ /* ── Run button ── */
116
+ .stButton > button {
117
+ background: #1A1A2E !important;
118
+ color: #fff !important;
119
+ border: none !important;
120
+ border-radius: 8px !important;
121
+ padding: 0.85rem 2.5rem !important;
122
+ font-family: 'Inter', sans-serif !important;
123
+ font-size: 0.88rem !important;
124
+ font-weight: 600 !important;
125
+ letter-spacing: 0.04em !important;
126
+ text-transform: uppercase !important;
127
+ transition: all 0.2s !important;
128
+ box-shadow: 0 2px 8px rgba(26,26,46,0.2) !important;
129
+ width: 100% !important;
130
  }
131
+ .stButton > button:hover {
132
+ background: #2563EB !important;
133
+ box-shadow: 0 4px 16px rgba(37,99,235,0.3) !important;
134
+ transform: translateY(-1px) !important;
135
  }
136
+ .stButton > button:disabled {
137
+ background: #E5E7EB !important;
138
+ color: #9CA3AF !important;
139
+ box-shadow: none !important;
140
+ transform: none !important;
141
+ cursor: not-allowed !important;
142
  }
143
 
144
+ /* ── Progress ── */
145
+ .stProgress > div > div > div {
146
+ background: #2563EB !important;
147
+ border-radius: 4px !important;
 
 
 
 
 
 
 
 
 
 
 
 
148
  }
149
+ .stProgress > div > div {
150
+ background: #E5E7EB !important;
151
+ border-radius: 4px !important;
152
+ height: 4px !important;
 
 
 
 
153
  }
154
 
155
+ /* ── Stats strip ── */
156
+ .stats-strip {
157
+ display: flex;
158
+ gap: 0;
159
+ background: #1A1A2E;
160
+ border-radius: 12px;
161
+ overflow: hidden;
162
+ margin: 2.5rem 0 2rem;
163
+ }
164
+ .stat-item {
165
+ flex: 1;
166
+ padding: 1.6rem 2rem;
167
+ border-right: 1px solid rgba(255,255,255,0.08);
168
+ text-align: left;
169
+ }
170
+ .stat-item:last-child { border-right: none; }
171
  .stat-n {
172
+ font-family: 'Cormorant Garamond', serif;
173
+ font-size: 2.6rem;
174
+ font-weight: 700;
175
+ color: #fff;
176
+ line-height: 1;
177
+ margin-bottom: 0.3rem;
178
  }
179
  .stat-l {
180
+ font-size: 0.68rem;
181
+ font-weight: 500;
182
+ letter-spacing: 0.12em;
183
+ text-transform: uppercase;
184
+ color: #6B7280;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
  }
186
 
187
+ /* ── Section heading ── */
188
+ .section-head {
189
+ display: flex;
190
+ align-items: center;
191
+ justify-content: space-between;
192
+ margin-bottom: 1rem;
193
+ padding-bottom: 0.75rem;
194
+ border-bottom: 1px solid #E5E7EB;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
  }
196
+ .section-title {
197
+ font-family: 'Cormorant Garamond', serif;
198
+ font-size: 1.5rem;
199
+ font-weight: 600;
200
+ color: #1A1A2E;
201
+ letter-spacing: -0.01em;
202
  }
203
 
204
+ /* ── Download button ── */
205
  div[data-testid="stDownloadButton"] > button {
206
+ background: #fff !important;
207
+ border: 1.5px solid #1A1A2E !important;
208
+ color: #1A1A2E !important;
209
+ border-radius: 8px !important;
210
  padding: 0.6rem 1.4rem !important;
211
+ font-family: 'Inter', sans-serif !important;
212
+ font-weight: 600 !important;
213
+ font-size: 0.82rem !important;
214
+ letter-spacing: 0.04em !important;
215
+ text-transform: uppercase !important;
216
  transition: all 0.2s !important;
217
+ box-shadow: none !important;
218
+ width: auto !important;
219
  }
220
  div[data-testid="stDownloadButton"] > button:hover {
221
+ background: #1A1A2E !important;
222
+ color: #fff !important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  }
224
 
225
+ /* ── Dataframe ── */
226
  [data-testid="stDataFrame"] {
227
+ border-radius: 10px !important;
228
+ border: 1px solid #E5E7EB !important;
229
  overflow: hidden !important;
230
+ box-shadow: 0 1px 4px rgba(0,0,0,0.05) !important;
231
  }
232
 
233
+ /* ── File chip ── */
234
+ .fchip {
235
+ display: inline-flex; align-items: center; gap: 5px;
236
+ background: #EFF6FF;
237
+ border: 1px solid #BFDBFE;
238
+ color: #1D4ED8;
239
+ padding: 0.25rem 0.7rem;
240
+ border-radius: 6px;
241
+ font-size: 0.73rem;
242
+ font-weight: 500;
243
+ margin: 2px;
244
  }
245
 
246
+ /* ── Divider ── */
247
+ .rule { height:1px; background:#E5E7EB; margin: 2.5rem 0; }
248
+
249
+ /* ── Step tag ── */
250
+ .step {
251
+ font-size: 0.65rem; font-weight: 700;
252
+ letter-spacing: 0.18em; text-transform: uppercase;
253
+ color: #2563EB; margin-bottom: 0.5rem;
254
  }
255
 
256
+ /* ── Success alert ── */
257
+ [data-testid="stAlert"][data-baseweb="notification"] {
258
+ border-radius: 10px !important;
259
+ border-left: 3px solid #2563EB !important;
260
  }
261
  </style>
262
  """, unsafe_allow_html=True)
263
 
264
 
265
  # ═══════════════════════════════════════════════════════════
266
+ # MODEL (cached β€” loads once)
267
  # ═══════════════════════════════════════════════════════════
268
+ @st.cache_resource(show_spinner="Loading recognition model…")
269
  def load_model():
270
  import torch
271
  from transformers import TrOCRProcessor, VisionEncoderDecoderModel
 
276
  model.to(device).eval()
277
  return processor, model, device
278
 
 
 
 
 
 
279
 
280
  # ═══════════════════════════════════════════════════════════
281
  # HELPERS
282
  # ═══════════════════════════════════════════════════════════
283
+ def ocr(img: Image.Image) -> str:
284
  import torch
285
  processor, model, device = load_model()
286
  pv = processor(images=img.convert("RGB"), return_tensors="pt").pixel_values.to(device)
 
288
  gen = model.generate(pv, max_new_tokens=64)
289
  return processor.batch_decode(gen, skip_special_tokens=True)[0].strip()
290
 
291
+ def pdf_pages(file_bytes: bytes) -> list:
 
 
 
 
 
 
 
 
 
 
 
 
292
  import fitz
293
+ doc = fitz.open(stream=file_bytes, filetype="pdf")
294
+ mat = fitz.Matrix(200/72, 200/72)
295
+ out = []
296
+ for i in range(len(doc)):
 
297
  pix = doc[i].get_pixmap(matrix=mat, alpha=False)
298
+ out.append(Image.open(io.BytesIO(pix.tobytes("png"))).convert("RGB"))
299
  doc.close()
300
+ return out
301
 
302
+ def extract(text: str, filename: str) -> dict:
303
  import re
304
+ def g(label):
305
  m = re.search(label + r'[:\s]+([^\|\n]{1,80})', text, re.IGNORECASE)
306
  return m.group(1).strip() if m else ""
307
  amounts = re.findall(r'AMT:\s*([\d,]+)', text)
308
+ date_m = re.search(r'DATE:\s*(\d{4}-\d{2}-\d{2})', text)
309
  return {
310
+ "File": filename,
311
+ "Plot Number": g("PLOT"),
312
+ "Location": g("LOC"),
313
+ "Area": g("AREA"),
314
+ "Amount (KES)": int(amounts[0].replace(",","")) if amounts else None,
315
+ "Date": date_m.group(1) if date_m else None,
316
+ "VOS": g("VOS"),
317
  }
318
 
319
+ def make_excel(records: list) -> bytes:
320
  from openpyxl import load_workbook
321
  from openpyxl.styles import Font, PatternFill, Alignment
322
  from openpyxl.utils import get_column_letter
323
  buf = io.BytesIO()
324
  pd.DataFrame(records).to_excel(buf, index=False, sheet_name="Valuation Data")
325
  buf.seek(0)
326
+ wb = load_workbook(buf)
327
+ ws = wb.active
328
+ hdr_fill = PatternFill("solid", start_color="1A1A2E")
329
  for ci, cell in enumerate(ws[1], 1):
330
  cell.font = Font(name="Calibri", bold=True, color="FFFFFF", size=11)
331
+ cell.fill = hdr_fill
332
  cell.alignment = Alignment(horizontal="center", vertical="center")
333
+ ws.column_dimensions[get_column_letter(ci)].width = 24
334
  ws.row_dimensions[1].height = 30
335
  for row in ws.iter_rows(min_row=2):
336
  for cell in row:
337
  cell.alignment = Alignment(vertical="center", wrap_text=True)
338
  if cell.row % 2 == 0:
339
+ cell.fill = PatternFill("solid", start_color="F0F4FF")
340
  ws.freeze_panes = "A2"
341
  out = io.BytesIO(); wb.save(out)
342
  return out.getvalue()
 
345
  # ═══════════════════════════════════════════════════════════
346
  # SESSION STATE
347
  # ═══════════════════════════════════��═══════════════════════
348
+ for k, v in [("records",[]),("excel",None),("done",False),("errors",[])]:
349
  if k not in st.session_state:
350
  st.session_state[k] = v
351
 
352
 
353
  # ═══════════════════════════════════════════════════════════
354
+ # TOP BAR
355
  # ═══════════════════════════════════════════════════════════
356
  st.markdown("""
357
+ <div class="topbar">
358
+ <div>
359
+ <div class="logo">Valuation<span>AI</span></div>
360
+ <div class="logo-sub">Nairobi City County β€” Document Intelligence</div>
361
+ </div>
362
+ <div class="model-ref">
363
+ Recognition model<br>
364
+ <strong>rasmodev/Handwriting_trocr_model</strong>
365
  </div>
 
366
  </div>
367
  """, unsafe_allow_html=True)
368
 
369
 
370
  # ═══════════════════════════════════════════════════════════
371
+ # HEADLINE
372
  # ═══════════════════════════════════════════════════════════
373
  st.markdown("""
374
+ <div class="headline">
375
+ Digitise handwritten<br>valuation sheets <em>instantly.</em>
376
+ </div>
377
+ <div class="subline">
378
+ Upload one or more scanned PDF valuation sheets.
379
+ The system reads every handwritten field and delivers
380
+ a structured Excel file β€” ready for records management.
381
+ </div>
382
  """, unsafe_allow_html=True)
383
 
384
 
385
  # ═══════════════════════════════════════════════════════════
386
+ # UPLOAD
387
  # ═══════════════════════════════════════════════════════════
388
+ st.markdown('<div class="step">Step 1 β€” Upload Documents</div>', unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
389
 
390
+ uploaded = st.file_uploader(
391
+ "Drag and drop valuation sheet PDFs here, or click to browse",
392
+ type=["pdf", "png", "jpg", "jpeg", "tiff", "bmp"],
393
+ accept_multiple_files=True,
394
+ label_visibility="collapsed",
395
+ )
396
 
397
+ if uploaded:
398
+ chips = "".join(
399
+ f'<span class="fchip">πŸ“„ {f.name[:35]}{"…" if len(f.name)>35 else ""}</span>'
400
+ for f in uploaded
401
+ )
402
+ st.markdown(f'<div style="margin-top:0.6rem">{chips}</div>', unsafe_allow_html=True)
403
 
404
+ st.markdown('<div style="height:1.2rem"></div>', unsafe_allow_html=True)
405
+ st.markdown('<div class="step">Step 2 β€” Extract & Download</div>', unsafe_allow_html=True)
406
 
407
+ run = st.button(
408
+ "Extract Data from Documents",
409
+ disabled=not uploaded,
410
+ use_container_width=True,
411
+ )
 
 
 
 
412
 
413
 
414
  # ═══════════════════════════════════════════════════════════
415
  # PROCESSING
416
  # ═══════════════════════════════════════════════════════════
417
+ if run and uploaded:
418
  st.session_state.records = []
419
  st.session_state.errors = []
420
  st.session_state.done = False
421
 
 
422
  bar = st.progress(0.0)
423
  status = st.empty()
424
  t0 = time.time()
425
 
426
+ for fi, uf in enumerate(uploaded):
427
  fname = uf.name
428
+ raw = uf.read()
429
+ bar.progress(fi / len(uploaded), text=f"Reading {fname}…")
430
 
431
  try:
432
  ext = fname.lower().rsplit(".", 1)[-1]
433
+ imgs = pdf_pages(raw) if ext == "pdf" \
434
+ else [Image.open(io.BytesIO(raw)).convert("RGB")]
 
435
 
436
+ for pi, img in enumerate(imgs, 1):
437
+ status.caption(f"Processing **{fname}** β€” page {pi} of {len(imgs)}")
438
+ text = ocr(img)
439
+ st.session_state.records.append(extract(text, fname))
 
440
 
441
  except Exception as e:
442
  st.session_state.errors.append(f"{fname}: {e}")
443
 
444
+ bar.progress((fi+1) / len(uploaded))
445
 
446
  bar.empty(); status.empty()
447
+ st.session_state.excel = make_excel(st.session_state.records) \
448
+ if st.session_state.records else None
449
+ st.session_state.done = True
450
 
451
  elapsed = time.time() - t0
452
+ st.success(
453
+ f"Processed {len(st.session_state.records)} page(s) "
454
+ f"from {len(uploaded)} document(s) in {elapsed:.1f}s."
455
+ )
456
 
457
 
458
  # ═══════════════════════════════════════════════════════════
459
  # RESULTS
460
  # ═══════════════════════════════════════════════════════════
461
  if st.session_state.done and st.session_state.records:
462
+ df = pd.DataFrame(st.session_state.records)
 
463
 
464
+ # Stats strip
465
+ n_plots = df["Plot Number"].astype(bool).sum()
466
+ n_amounts = df["Amount (KES)"].notna().sum()
467
+ n_dates = df["Date"].astype(bool).sum()
 
 
468
 
469
  st.markdown(f"""
470
+ <div class="stats-strip">
471
+ <div class="stat-item">
472
+ <div class="stat-n">{len(df)}</div>
473
+ <div class="stat-l">Pages processed</div>
474
  </div>
475
+ <div class="stat-item">
476
  <div class="stat-n">{n_plots}</div>
477
+ <div class="stat-l">Plot numbers</div>
478
  </div>
479
+ <div class="stat-item">
480
  <div class="stat-n">{n_amounts}</div>
481
+ <div class="stat-l">Amounts extracted</div>
482
  </div>
483
+ <div class="stat-item">
484
  <div class="stat-n">{n_dates}</div>
485
+ <div class="stat-l">Dates captured</div>
486
  </div>
487
  </div>
488
  """, unsafe_allow_html=True)
489
 
490
+ # Table header + download
491
+ col_t, col_d = st.columns([5, 1])
492
+ with col_t:
493
+ st.markdown("""
494
+ <div class="section-head">
495
+ <div class="section-title">Extracted Records</div>
496
+ </div>
497
+ """, unsafe_allow_html=True)
498
+ with col_d:
499
+ st.markdown('<div style="padding-top:0.3rem"></div>', unsafe_allow_html=True)
500
+ if st.session_state.excel:
501
  st.download_button(
502
+ "⬇ Export Excel",
503
+ data=st.session_state.excel,
504
+ file_name="valuation_records.xlsx",
505
  mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
506
  )
507
 
508
+ # Table
509
  st.dataframe(df, use_container_width=True,
510
+ height=min(80 + len(df)*38, 560), hide_index=True)
511
 
512
  # Errors
513
  if st.session_state.errors:
514
+ with st.expander(f"⚠ {len(st.session_state.errors)} file(s) could not be processed"):
515
  for e in st.session_state.errors:
516
+ st.caption(e)