pitcserverbilal commited on
Commit
27153e2
Β·
verified Β·
1 Parent(s): d7a17bc

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +2179 -0
app.py ADDED
@@ -0,0 +1,2179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py - Complete OCR Dashboard for Hugging Face Spaces
2
+ import os
3
+ import sys
4
+ import streamlit as st
5
+ import pandas as pd
6
+ import oracledb
7
+ import plotly.express as px
8
+ import plotly.graph_objects as go
9
+ from io import BytesIO
10
+ import numpy as np
11
+ from datetime import datetime, timedelta
12
+ import json
13
+ import time
14
+ import logging
15
+
16
+ # =========================
17
+ # LOGGING SETUP
18
+ # =========================
19
+ logging.basicConfig(level=logging.INFO)
20
+ logger = logging.getLogger(__name__)
21
+
22
+ # =========================
23
+ # ENVIRONMENT VARIABLES FOR HUGGING FACE
24
+ # =========================
25
+ # Use environment variables for security
26
+ DB_HOST = os.environ.get("DB_HOST", "128.101.23.130")
27
+ DB_PORT = int(os.environ.get("DB_PORT", "1521"))
28
+ DB_SID = os.environ.get("DB_SID", "theftdb")
29
+ DB_USER = os.environ.get("DB_USER", "theft_data")
30
+ DB_PWD = os.environ.get("DB_PWD", "theft_data")
31
+
32
+ # =========================
33
+ # PAGE CONFIG
34
+ # =========================
35
+ st.set_page_config(
36
+ page_title="OCR Batch Intelligence Dashboard",
37
+ page_icon="πŸ“Š",
38
+ layout="wide",
39
+ initial_sidebar_state="expanded"
40
+ )
41
+
42
+ # =========================
43
+ # DISCO MAPPING
44
+ # =========================
45
+ DISCO_MAP = {
46
+ "11": "LESCO",
47
+ "12": "GEPCO",
48
+ "13": "FESCO",
49
+ "14": "IESCO",
50
+ "15": "MEPCO",
51
+ "26": "PESCO",
52
+ "27": "HAZECO",
53
+ "37": "HESCO",
54
+ "38": "SEPCO",
55
+ "48": "QESCO",
56
+ "59": "TESCO"
57
+ }
58
+
59
+ # =========================
60
+ # POWER BI MODERN STYLING - PERFECT CARD SIZING
61
+ # =========================
62
+ st.markdown("""
63
+ <style>
64
+ /* Power BI Enhanced Theme */
65
+ :root {
66
+ --primary-blue: #0078D4;
67
+ --secondary-blue: #50E6FF;
68
+ --accent-blue: #1890FF;
69
+ --dark-blue: #005A9E;
70
+ --light-blue: #E6F7FF;
71
+ --dark-gray: #2C2C2C;
72
+ --medium-gray: #4A4A4A;
73
+ --light-gray: #F3F2F1;
74
+ --white: #FFFFFF;
75
+ --success-green: #107C10;
76
+ --light-green: #DFF6DD;
77
+ --warning-orange: #FFB900;
78
+ --light-orange: #FFF4CE;
79
+ --danger-red: #D13438;
80
+ --light-red: #FDE7E9;
81
+ --accent-purple: #8661C5;
82
+ --light-purple: #F3F0FF;
83
+ }
84
+
85
+ /* Modern Dashboard Container */
86
+ .main-container {
87
+ background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
88
+ min-height: 100vh;
89
+ padding: 20px;
90
+ }
91
+
92
+ /* Enhanced Header */
93
+ .enhanced-header {
94
+ background: linear-gradient(135deg, var(--dark-blue), var(--primary-blue));
95
+ padding: 30px;
96
+ border-radius: 16px;
97
+ margin-bottom: 30px;
98
+ text-align: center;
99
+ color: white;
100
+ box-shadow: 0 10px 40px rgba(0, 120, 212, 0.2);
101
+ border: 1px solid rgba(255, 255, 255, 0.15);
102
+ position: relative;
103
+ overflow: hidden;
104
+ }
105
+
106
+ .enhanced-header::before {
107
+ content: '';
108
+ position: absolute;
109
+ top: -50%;
110
+ right: -50%;
111
+ width: 200%;
112
+ height: 200%;
113
+ background: radial-gradient(circle, rgba(255,255,255,0.1) 1px, transparent 1px);
114
+ background-size: 30px 30px;
115
+ opacity: 0.3;
116
+ }
117
+
118
+ /* PERFECT KPI Cards - LARGER AND BETTER */
119
+ .enhanced-kpi {
120
+ background: var(--white);
121
+ border-radius: 16px;
122
+ padding: 25px 15px;
123
+ color: var(--dark-gray);
124
+ text-align: center;
125
+ position: relative;
126
+ overflow: hidden;
127
+ height: 200px;
128
+ width: 100%;
129
+ display: flex;
130
+ flex-direction: column;
131
+ justify-content: center;
132
+ align-items: center;
133
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
134
+ border: none;
135
+ transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
136
+ margin: 0 5px 15px 5px;
137
+ }
138
+
139
+ .enhanced-kpi:hover {
140
+ transform: translateY(-5px);
141
+ box-shadow: 0 16px 48px rgba(0, 0, 0, 0.12);
142
+ }
143
+
144
+ .enhanced-kpi.blue {
145
+ background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
146
+ color: white;
147
+ }
148
+ .enhanced-kpi.green {
149
+ background: linear-gradient(135deg, var(--success-green), #0D5C0D);
150
+ color: white;
151
+ }
152
+ .enhanced-kpi.orange {
153
+ background: linear-gradient(135deg, var(--warning-orange), #D69C00);
154
+ color: white;
155
+ }
156
+ .enhanced-kpi.red {
157
+ background: linear-gradient(135deg, var(--danger-red), #B02A30);
158
+ color: white;
159
+ }
160
+ .enhanced-kpi.purple {
161
+ background: linear-gradient(135deg, var(--accent-purple), #6A4CA6);
162
+ color: white;
163
+ }
164
+
165
+ .enhanced-kpi .kpi-icon {
166
+ font-size: 30px;
167
+ margin-bottom: 5px;
168
+ opacity: 0.9;
169
+ }
170
+
171
+ .enhanced-kpi .kpi-value {
172
+ font-size: 48px;
173
+ font-weight: 800;
174
+ line-height: 1;
175
+ margin: 15px 0;
176
+ text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.2);
177
+ }
178
+
179
+ .enhanced-kpi .kpi-label {
180
+ font-size: 15px;
181
+ opacity: 0.9;
182
+ text-transform: uppercase;
183
+ letter-spacing: 1.2px;
184
+ font-weight: 600;
185
+ margin-top: 5px;
186
+ padding: 0 20px;
187
+ text-align: center;
188
+ line-height: 1.2;
189
+ }
190
+
191
+ .enhanced-kpi .kpi-trend {
192
+ font-size: 14px;
193
+ margin-top: 5px;
194
+ opacity: 0.8;
195
+ display: flex;
196
+ align-items: center;
197
+ justify-content: center;
198
+ gap: 5px;
199
+ padding: 0 20px;
200
+ }
201
+
202
+ /* Enhanced Cards */
203
+ .enhanced-card {
204
+ background: var(--white);
205
+ border-radius: 16px;
206
+ padding: 25px;
207
+ margin-bottom: 25px;
208
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
209
+ border: 1px solid rgba(0, 0, 0, 0.06);
210
+ transition: all 0.3s ease;
211
+ }
212
+
213
+ .enhanced-card:hover {
214
+ box-shadow: 0 12px 48px rgba(0, 0, 0, 0.12);
215
+ }
216
+
217
+ .enhanced-card .card-header {
218
+ display: flex;
219
+ justify-content: space-between;
220
+ align-items: center;
221
+ margin-bottom: 20px;
222
+ padding-bottom: 15px;
223
+ border-bottom: 2px solid var(--light-gray);
224
+ }
225
+
226
+ .enhanced-card .card-title {
227
+ font-size: 20px;
228
+ font-weight: 700;
229
+ color: var(--dark-gray);
230
+ display: flex;
231
+ align-items: center;
232
+ gap: 10px;
233
+ }
234
+
235
+ .enhanced-card .card-actions {
236
+ display: flex;
237
+ gap: 10px;
238
+ }
239
+
240
+ /* Enhanced Tabs */
241
+ .stTabs [data-baseweb="tab-list"] {
242
+ gap: 0;
243
+ background-color: transparent;
244
+ padding: 0;
245
+ border-bottom: 2px solid var(--light-gray);
246
+ }
247
+
248
+ .stTabs [data-baseweb="tab"] {
249
+ border-radius: 8px 8px 0 0;
250
+ padding: 15px 30px;
251
+ background-color: transparent;
252
+ font-weight: 600;
253
+ color: var(--medium-gray);
254
+ border: none;
255
+ margin-right: 5px;
256
+ transition: all 0.3s ease;
257
+ position: relative;
258
+ }
259
+
260
+ .stTabs [data-baseweb="tab"]:hover {
261
+ background-color: var(--light-blue);
262
+ color: var(--primary-blue);
263
+ }
264
+
265
+ .stTabs [aria-selected="true"] {
266
+ background-color: var(--primary-blue);
267
+ color: white;
268
+ box-shadow: 0 -4px 12px rgba(0, 120, 212, 0.2);
269
+ }
270
+
271
+ .stTabs [aria-selected="true"]::after {
272
+ content: '';
273
+ position: absolute;
274
+ bottom: -2px;
275
+ left: 0;
276
+ right: 0;
277
+ height: 3px;
278
+ background: var(--white);
279
+ border-radius: 2px;
280
+ }
281
+
282
+ /* Status Indicators */
283
+ .status-indicator {
284
+ display: inline-flex;
285
+ align-items: center;
286
+ padding: 8px 14px;
287
+ border-radius: 20px;
288
+ font-size: 14px;
289
+ font-weight: 600;
290
+ margin: 2px;
291
+ }
292
+
293
+ .status-success {
294
+ background: var(--light-green);
295
+ color: var(--success-green);
296
+ }
297
+
298
+ .status-warning {
299
+ background: var(--light-orange);
300
+ color: var(--warning-orange);
301
+ }
302
+
303
+ .status-error {
304
+ background: var(--light-red);
305
+ color: var(--danger-red);
306
+ }
307
+
308
+ .status-info {
309
+ background: var(--light-blue);
310
+ color: var(--primary-blue);
311
+ }
312
+
313
+ /* PERFECT Flag Cards */
314
+ .flag-card {
315
+ border-radius: 12px;
316
+ padding: 25px 15px;
317
+ text-align: center;
318
+ margin: 5px;
319
+ transition: all 0.3s ease;
320
+ height: 200px;
321
+ width: 100%;
322
+ display: flex;
323
+ flex-direction: column;
324
+ justify-content: center;
325
+ align-items: center;
326
+ }
327
+
328
+ .flag-A {
329
+ background: linear-gradient(135deg, rgba(16, 124, 16, 0.1), rgba(16, 124, 16, 0.05));
330
+ border: 5px solid var(--success-green);
331
+ color: var(--success-green);
332
+ }
333
+
334
+ .flag-C {
335
+ background: linear-gradient(135deg, rgba(255, 185, 0, 0.1), rgba(255, 185, 0, 0.05));
336
+ border: 5px solid var(--warning-orange);
337
+ color: var(--warning-orange);
338
+ }
339
+
340
+ .flag-D {
341
+ background: linear-gradient(135deg, rgba(253, 126, 20, 0.1), rgba(253, 126, 20, 0.05));
342
+ border: 5px solid #fd7e14;
343
+ color: #fd7e14;
344
+ }
345
+
346
+ .flag-E {
347
+ background: linear-gradient(135deg, rgba(220, 53, 69, 0.1), rgba(220, 53, 69, 0.05));
348
+ border: 5px solid var(--danger-red);
349
+ color: var(--danger-red);
350
+ }
351
+
352
+ .flag-N {
353
+ background: linear-gradient(135deg, rgba(108, 117, 125, 0.1), rgba(108, 117, 125, 0.05));
354
+ border: 5px solid #6c757d;
355
+ color: #6c757d;
356
+ }
357
+
358
+ .flag-card .flag-icon {
359
+ font-size: 32px;
360
+ font-weight: 800;
361
+ margin-bottom: 2px;
362
+ }
363
+
364
+ .flag-card .flag-value {
365
+ font-size: 28px;
366
+ font-weight: 900;
367
+ margin: 2px 0;
368
+ }
369
+
370
+ .flag-card .flag-label {
371
+ font-size: 12px;
372
+ font-weight: 600;
373
+ margin-bottom: 8px;
374
+ padding: 0 10px;
375
+ text-align: center;
376
+ line-height: 1.2;
377
+ }
378
+
379
+ .flag-card .flag-percentage {
380
+ font-size: 14px;
381
+ color: #666;
382
+ margin: 8px 0;
383
+ }
384
+
385
+ .flag-card .flag-desc {
386
+ font-size: 12px;
387
+ color: #888;
388
+ font-style: italic;
389
+ padding: 0 10px;
390
+ text-align: center;
391
+ line-height: 1.3;
392
+ }
393
+
394
+ /* Progress Indicators */
395
+ .progress-container {
396
+ height: 10px;
397
+ background: var(--light-gray);
398
+ border-radius: 4px;
399
+ margin: 10px 0;
400
+ overflow: hidden;
401
+ width: 100%;
402
+ }
403
+
404
+ .progress-bar {
405
+ height: 100%;
406
+ border-radius: 4px;
407
+ background: linear-gradient(90deg, var(--primary-blue), var(--secondary-blue));
408
+ }
409
+
410
+ /* Data Table Enhancements */
411
+ .dataframe {
412
+ border-radius: 12px !important;
413
+ overflow: hidden !important;
414
+ border: none !important;
415
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05) !important;
416
+ }
417
+
418
+ .dataframe th {
419
+ background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue)) !important;
420
+ color: white !important;
421
+ font-weight: 700 !important;
422
+ text-transform: uppercase;
423
+ font-size: 13px;
424
+ letter-spacing: 0.8px;
425
+ padding: 18px 14px !important;
426
+ border: none !important;
427
+ }
428
+
429
+ .dataframe td {
430
+ padding: 16px 14px !important;
431
+ border-bottom: 1px solid var(--light-gray) !important;
432
+ transition: background-color 0.2s ease;
433
+ }
434
+
435
+ .dataframe tr:hover td {
436
+ background-color: var(--light-blue) !important;
437
+ }
438
+
439
+ /* Animation Classes */
440
+ @keyframes fadeIn {
441
+ from { opacity: 0; transform: translateY(10px); }
442
+ to { opacity: 1; transform: translateY(0); }
443
+ }
444
+
445
+ .fade-in {
446
+ animation: fadeIn 0.5s ease-out;
447
+ }
448
+
449
+ /* Metric Enhancements */
450
+ .stMetric {
451
+ padding: 20px !important;
452
+ border-radius: 12px !important;
453
+ }
454
+
455
+ .stMetric [data-testid="stMetricLabel"] {
456
+ font-size: 16px !important;
457
+ }
458
+
459
+ .stMetric [data-testid="stMetricValue"] {
460
+ font-size: 32px !important;
461
+ }
462
+
463
+ /* Adjust column spacing for perfect cards */
464
+ [data-testid="column"] {
465
+ padding: 0 8px !important;
466
+ }
467
+
468
+ /* Ensure cards take full width of their container */
469
+ .st-emotion-cache-1v0mbdj {
470
+ width: 100% !important;
471
+ }
472
+
473
+ /* OCR Model Accuracy Cards - PERFECT SIZING */
474
+ .ocr-model-card {
475
+ border-radius: 16px;
476
+ padding: 30px 20px;
477
+ color: white;
478
+ text-align: center;
479
+ height: 220px;
480
+ width: 100%;
481
+ display: flex;
482
+ flex-direction: column;
483
+ justify-content: center;
484
+ align-items: center;
485
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
486
+ margin: 5px 0 15px 0;
487
+ }
488
+
489
+ .ocr-model-card .ocr-icon {
490
+ font-size: 44px;
491
+ margin-bottom: 15px;
492
+ opacity: 0.9;
493
+ }
494
+
495
+ .ocr-model-card .ocr-value {
496
+ font-size: 56px;
497
+ font-weight: 800;
498
+ line-height: 1;
499
+ margin: 10px 0;
500
+ text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.2);
501
+ }
502
+
503
+ .ocr-model-card .ocr-label {
504
+ font-size: 18px;
505
+ opacity: 0.9;
506
+ font-weight: 600;
507
+ margin-top: 10px;
508
+ padding: 0 15px;
509
+ text-align: center;
510
+ line-height: 1.2;
511
+ }
512
+
513
+ .ocr-model-card .ocr-desc {
514
+ font-size: 14px;
515
+ opacity: 0.8;
516
+ margin-top: 8px;
517
+ padding: 0 10px;
518
+ text-align: center;
519
+ line-height: 1.3;
520
+ }
521
+
522
+ /* Force proper column width distribution */
523
+ div[data-testid="column"] > div {
524
+ width: 100% !important;
525
+ }
526
+
527
+ /* Make sure cards don't overflow */
528
+ div[data-testid="column"] {
529
+ min-width: 0 !important;
530
+ }
531
+
532
+ /* Connection Status Indicator */
533
+ .connection-status {
534
+ position: fixed;
535
+ bottom: 20px;
536
+ right: 20px;
537
+ padding: 10px 15px;
538
+ border-radius: 20px;
539
+ font-size: 12px;
540
+ font-weight: 600;
541
+ z-index: 9999;
542
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
543
+ }
544
+
545
+ .connection-live {
546
+ background: var(--success-green);
547
+ color: white;
548
+ }
549
+
550
+ .connection-error {
551
+ background: var(--danger-red);
552
+ color: white;
553
+ }
554
+
555
+ .connection-sample {
556
+ background: var(--warning-orange);
557
+ color: white;
558
+ }
559
+ </style>
560
+ """, unsafe_allow_html=True)
561
+
562
+ # =========================
563
+ # ORACLE CONNECTION HELPER
564
+ # =========================
565
+ def get_oracle_connection():
566
+ """Create Oracle connection optimized for Hugging Face"""
567
+ try:
568
+ # Try thin mode first (no Oracle client needed)
569
+ # This is the default in oracledb 2.0+ and works on Hugging Face
570
+ connection = None
571
+
572
+ # Method 1: Using easy connect syntax (recommended for Hugging Face)
573
+ # Format: //host:port/service_name
574
+ try:
575
+ dsn = f"{DB_HOST}:{DB_PORT}/{DB_SID}"
576
+ logger.info(f"Attempting connection to: {DB_HOST}:{DB_PORT}/{DB_SID}")
577
+
578
+ # For Hugging Face, try different connection methods
579
+ connection = oracledb.connect(
580
+ user=DB_USER,
581
+ password=DB_PWD,
582
+ dsn=dsn,
583
+ encoding="UTF-8"
584
+ )
585
+ logger.info("βœ… Connected using thin mode")
586
+ return connection
587
+
588
+ except Exception as e:
589
+ logger.warning(f"Method 1 failed: {str(e)}")
590
+
591
+ # Method 2: Using makedsn
592
+ try:
593
+ dsn = oracledb.makedsn(DB_HOST, DB_PORT, service_name=DB_SID)
594
+ connection = oracledb.connect(
595
+ user=DB_USER,
596
+ password=DB_PWD,
597
+ dsn=dsn,
598
+ encoding="UTF-8"
599
+ )
600
+ logger.info("βœ… Connected using makedsn")
601
+ return connection
602
+
603
+ except Exception as e2:
604
+ logger.warning(f"Method 2 failed: {str(e2)}")
605
+
606
+ # Method 3: Try different connection string formats
607
+ try:
608
+ # Try with // prefix
609
+ dsn = f"//{DB_HOST}:{DB_PORT}/{DB_SID}"
610
+ connection = oracledb.connect(
611
+ user=DB_USER,
612
+ password=DB_PWD,
613
+ dsn=dsn,
614
+ encoding="UTF-8"
615
+ )
616
+ logger.info("βœ… Connected using // format")
617
+ return connection
618
+
619
+ except Exception as e3:
620
+ logger.error(f"All connection methods failed: {str(e3)}")
621
+ return None
622
+
623
+ except Exception as e:
624
+ logger.error(f"Oracle connection error: {str(e)}")
625
+ return None
626
+
627
+ # =========================
628
+ # DATA LOADER WITH RETRY MECHANISM
629
+ # =========================
630
+ @st.cache_data(ttl=600, show_spinner=False) # Cache for 10 minutes
631
+ def load_all_disco_data(disco_code=None):
632
+ """Load ALL data for specific DISCO or all DISCOS with retry mechanism"""
633
+
634
+ def try_database_query():
635
+ """Try to get data from database with timeout"""
636
+ conn = None
637
+ try:
638
+ # Get connection
639
+ conn = get_oracle_connection()
640
+ if conn is None:
641
+ raise Exception("Failed to establish database connection")
642
+
643
+ # Build query
644
+ if disco_code:
645
+ query = f"""
646
+ SELECT
647
+ REF_DIGITS,
648
+ SUBSTR(REF_DIGITS, 3, 2) AS DISCO_CODE,
649
+ BILMONTH,
650
+ IMAGE_VERIFY_CODE_PITC
651
+ FROM TBL_GENERAL_BILL_PRINT_AUDIT
652
+ WHERE SUBSTR(REF_DIGITS, 3, 2) = '{disco_code}'
653
+ AND ROWNUM <= 100000 -- Limit for performance on Hugging Face
654
+ """
655
+ else:
656
+ query = """
657
+ SELECT
658
+ REF_DIGITS,
659
+ SUBSTR(REF_DIGITS, 3, 2) AS DISCO_CODE,
660
+ BILMONTH,
661
+ IMAGE_VERIFY_CODE_PITC
662
+ FROM TBL_GENERAL_BILL_PRINT_AUDIT
663
+ WHERE ROWNUM <= 100000 -- Limit for performance on Hugging Face
664
+ """
665
+
666
+ # Execute query with timeout
667
+ start_time = time.time()
668
+ df = pd.read_sql(query, conn)
669
+ query_time = time.time() - start_time
670
+
671
+ logger.info(f"Query executed in {query_time:.2f} seconds, fetched {len(df)} rows")
672
+
673
+ # Close connection
674
+ conn.close()
675
+
676
+ # Process data
677
+ if not df.empty:
678
+ df["DISCO_NAME"] = df["DISCO_CODE"].map(DISCO_MAP).fillna("UNKNOWN")
679
+ df["BATCH_NO"] = df["REF_DIGITS"].str[:2]
680
+ df["SUB_DIV"] = df["REF_DIGITS"].str[:5]
681
+ df["BATCH_ID"] = df["BATCH_NO"] + "-" + df["DISCO_CODE"]
682
+ df["PROCESSING_STATUS"] = df["IMAGE_VERIFY_CODE_PITC"].apply(
683
+ lambda x: "Processed" if pd.notna(x) else "Pending"
684
+ )
685
+ df["ACCURACY_CATEGORY"] = df["IMAGE_VERIFY_CODE_PITC"].apply(
686
+ lambda x: "Success (A,C,D)" if x in ['A', 'C', 'D'] else
687
+ "Images Not Available (E)" if x == 'E' else
688
+ "Reading Not Matched (N)" if x == 'N' else
689
+ "Not Processed" if pd.isna(x) else "Other"
690
+ )
691
+
692
+ return df
693
+
694
+ except Exception as e:
695
+ if conn:
696
+ try:
697
+ conn.close()
698
+ except:
699
+ pass
700
+ raise e
701
+
702
+ # Try database query with retries
703
+ max_retries = 2
704
+ for attempt in range(max_retries):
705
+ try:
706
+ logger.info(f"Attempting database query (attempt {attempt + 1}/{max_retries})")
707
+ df = try_database_query()
708
+
709
+ if df is not None and not df.empty:
710
+ logger.info(f"Successfully loaded {len(df)} records from database")
711
+ return df
712
+
713
+ except Exception as e:
714
+ logger.warning(f"Database attempt {attempt + 1} failed: {str(e)}")
715
+
716
+ if attempt == max_retries - 1:
717
+ logger.error("All database attempts failed, using sample data")
718
+ break
719
+
720
+ # Wait before retry
721
+ time.sleep(2 ** attempt) # Exponential backoff
722
+
723
+ # Fallback to sample data if database fails
724
+ logger.info("Creating sample data for demonstration")
725
+
726
+ # Create comprehensive sample data (smaller for Hugging Face)
727
+ sample_size = 5000
728
+
729
+ codes = [disco_code] if disco_code else list(DISCO_MAP.keys())[:5]
730
+
731
+ data = {
732
+ 'REF_DIGITS': [],
733
+ 'DISCO_CODE': [],
734
+ 'BILMONTH': [],
735
+ 'IMAGE_VERIFY_CODE_PITC': []
736
+ }
737
+
738
+ for i in range(sample_size):
739
+ disco = np.random.choice(codes)
740
+ batch_no = f"{np.random.randint(1, 50):02d}"
741
+ sub_div = f"{batch_no}{disco}{np.random.randint(1, 5)}"
742
+ ref_digits = f"{sub_div}{np.random.randint(100000000, 999999999)}"
743
+
744
+ data['REF_DIGITS'].append(ref_digits)
745
+ data['DISCO_CODE'].append(disco)
746
+ data['BILMONTH'].append(np.random.choice(pd.date_range('2024-01-01', periods=6, freq='MS')))
747
+ data['IMAGE_VERIFY_CODE_PITC'].append(np.random.choice(['A', 'C', 'D', 'E', 'N', None],
748
+ p=[0.35, 0.2, 0.15, 0.1, 0.05, 0.15]))
749
+
750
+ df = pd.DataFrame(data)
751
+ df["DISCO_NAME"] = df["DISCO_CODE"].map(DISCO_MAP)
752
+ df["BATCH_NO"] = df["REF_DIGITS"].str[:2]
753
+ df["SUB_DIV"] = df["REF_DIGITS"].str[:5]
754
+ df["BATCH_ID"] = df["BATCH_NO"] + "-" + df["DISCO_CODE"]
755
+ df["PROCESSING_STATUS"] = df["IMAGE_VERIFY_CODE_PITC"].apply(
756
+ lambda x: "Processed" if pd.notna(x) else "Pending"
757
+ )
758
+ df["ACCURACY_CATEGORY"] = df["IMAGE_VERIFY_CODE_PITC"].apply(
759
+ lambda x: "Success (A,C,D)" if x in ['A', 'C', 'D'] else
760
+ "Images Not Available (E)" if x == 'E' else
761
+ "Reading Not Matched (N)" if x == 'N' else
762
+ "Not Processed" if pd.isna(x) else "Other"
763
+ )
764
+
765
+ return df
766
+
767
+ # =========================
768
+ # BATCH PROCESSING FUNCTIONS WITH UPDATED LOGIC
769
+ # =========================
770
+ def get_batch_statistics(df):
771
+ """Get statistics for all batches with updated success/accuracy logic"""
772
+ batch_stats = []
773
+
774
+ for batch_id in sorted(df["BATCH_ID"].unique()):
775
+ batch_df = df[df["BATCH_ID"] == batch_id]
776
+
777
+ total_records = len(batch_df)
778
+ processed_records = batch_df["IMAGE_VERIFY_CODE_PITC"].notna().sum()
779
+
780
+ # Count each flag type
781
+ flag_counts = {}
782
+ for flag in ['A', 'C', 'D', 'E', 'N']:
783
+ flag_counts[flag] = (batch_df["IMAGE_VERIFY_CODE_PITC"] == flag).sum()
784
+
785
+ # UPDATED: A, C, D are considered successful
786
+ successful = flag_counts['A'] + flag_counts['C'] + flag_counts['D']
787
+
788
+ # Calculate OCR Model Accuracy (A vs N only)
789
+ total_an = flag_counts['A'] + flag_counts['N']
790
+ ocr_accuracy = (flag_counts['A'] / total_an * 100) if total_an > 0 else 0
791
+
792
+ # Calculate rates
793
+ processing_rate = (processed_records / total_records * 100) if total_records > 0 else 0
794
+ success_rate = (successful / processed_records * 100) if processed_records > 0 else 0
795
+
796
+ # Accuracy rate
797
+ accurate_records = processed_records - flag_counts['E'] - flag_counts['N']
798
+ accuracy_rate = (accurate_records / processed_records * 100) if processed_records > 0 else 0
799
+
800
+ # Quality score
801
+ quality_score = (flag_counts['A'] / processed_records * 100) if processed_records > 0 else 0
802
+
803
+ batch_stats.append({
804
+ "Batch ID": batch_id,
805
+ "Batch No": batch_df["BATCH_NO"].iloc[0],
806
+ "DISCO": batch_df["DISCO_NAME"].iloc[0],
807
+ "Total Records": total_records,
808
+ "Processed": processed_records,
809
+ "Not Processed": total_records - processed_records,
810
+ "Successful (A,C,D)": successful,
811
+ "Images Not Available (E)": flag_counts['E'],
812
+ "Reading Not Matched (N)": flag_counts['N'],
813
+ "Success Rate (A,C,D)": success_rate,
814
+ "Processing Rate": processing_rate,
815
+ "Accuracy Rate (A,C,D)": accuracy_rate,
816
+ "Perfect Match Rate (A)": quality_score,
817
+ "OCR Model Accuracy (A vs N)": ocr_accuracy,
818
+ "Flag A": flag_counts['A'],
819
+ "Flag C": flag_counts['C'],
820
+ "Flag D": flag_counts['D'],
821
+ "Flag E": flag_counts['E'],
822
+ "Flag N": flag_counts['N'],
823
+ "Total A+N": total_an
824
+ })
825
+
826
+ return pd.DataFrame(batch_stats)
827
+
828
+ def calculate_ocr_model_accuracy(df):
829
+ """Calculate OCR model accuracy based on A vs N flags only"""
830
+ # Count A and N flags
831
+ count_a = (df["IMAGE_VERIFY_CODE_PITC"] == 'A').sum()
832
+ count_n = (df["IMAGE_VERIFY_CODE_PITC"] == 'N').sum()
833
+
834
+ total_an = count_a + count_n
835
+
836
+ if total_an > 0:
837
+ accuracy = (count_a / total_an * 100)
838
+ else:
839
+ accuracy = 0
840
+
841
+ return {
842
+ "count_a": count_a,
843
+ "count_n": count_n,
844
+ "total_an": total_an,
845
+ "accuracy": accuracy
846
+ }
847
+
848
+ def create_insights(df, batch_stats):
849
+ """Create business insights from data with updated logic"""
850
+ insights = []
851
+
852
+ # Overall metrics
853
+ total_records = len(df)
854
+ processed_records = df["IMAGE_VERIFY_CODE_PITC"].notna().sum()
855
+
856
+ # Count successful (A, C, D)
857
+ successful_records = df["IMAGE_VERIFY_CODE_PITC"].isin(['A', 'C', 'D']).sum()
858
+
859
+ # Count issues
860
+ image_issues = (df["IMAGE_VERIFY_CODE_PITC"] == 'E').sum()
861
+ reading_issues = (df["IMAGE_VERIFY_CODE_PITC"] == 'N').sum()
862
+
863
+ # Calculate OCR Model Accuracy
864
+ ocr_accuracy = calculate_ocr_model_accuracy(df)
865
+
866
+ # Calculate rates
867
+ processing_rate = (processed_records / total_records * 100) if total_records > 0 else 0
868
+ success_rate = (successful_records / processed_records * 100) if processed_records > 0 else 0
869
+
870
+ # Insight 1: Processing Efficiency
871
+ if processing_rate < 80:
872
+ insights.append({
873
+ "title": "⚠️ Processing Bottleneck",
874
+ "description": f"Only {processing_rate:.1f}% records processed. Consider increasing processing capacity.",
875
+ "severity": "warning",
876
+ "metric": f"{processing_rate:.1f}%"
877
+ })
878
+ elif processing_rate > 95:
879
+ insights.append({
880
+ "title": "βœ… Excellent Processing",
881
+ "description": f"High processing rate of {processing_rate:.1f}%. Maintain this efficiency.",
882
+ "severity": "success",
883
+ "metric": f"{processing_rate:.1f}%"
884
+ })
885
+
886
+ # Insight 2: OCR Model Accuracy
887
+ if ocr_accuracy['accuracy'] > 0:
888
+ if ocr_accuracy['accuracy'] < 70:
889
+ insights.append({
890
+ "title": "πŸ€– Low OCR Model Accuracy",
891
+ "description": f"OCR model accuracy (A vs N) is {ocr_accuracy['accuracy']:.1f}%. Consider improving OCR algorithms.",
892
+ "severity": "warning",
893
+ "metric": f"{ocr_accuracy['accuracy']:.1f}%"
894
+ })
895
+ elif ocr_accuracy['accuracy'] > 90:
896
+ insights.append({
897
+ "title": "πŸ€– High OCR Model Accuracy",
898
+ "description": f"Excellent OCR model accuracy of {ocr_accuracy['accuracy']:.1f}% (A vs N).",
899
+ "severity": "success",
900
+ "metric": f"{ocr_accuracy['accuracy']:.1f}%"
901
+ })
902
+
903
+ # Insight 3: Image Availability Issues
904
+ if image_issues > 0:
905
+ image_issue_rate = (image_issues / processed_records * 100) if processed_records > 0 else 0
906
+ if image_issue_rate > 15:
907
+ insights.append({
908
+ "title": "πŸ–ΌοΈ High Image Unavailability",
909
+ "description": f"{image_issue_rate:.1f}% records have image issues (Flag E). Check image capture process.",
910
+ "severity": "error",
911
+ "metric": f"{image_issue_rate:.1f}%"
912
+ })
913
+
914
+ return insights
915
+
916
+ # =========================
917
+ # CONNECTION TEST FUNCTION
918
+ # =========================
919
+ def test_database_connection():
920
+ """Test if database connection is working"""
921
+ try:
922
+ conn = get_oracle_connection()
923
+ if conn:
924
+ conn.close()
925
+ return True
926
+ return False
927
+ except:
928
+ return False
929
+
930
+ # =========================
931
+ # MAIN APP STARTS HERE
932
+ # =========================
933
+
934
+ # Test connection at startup
935
+ connection_status = test_database_connection()
936
+
937
+ # =========================
938
+ # SIDEBAR - ENHANCED
939
+ # =========================
940
+ with st.sidebar:
941
+ st.markdown('<div class="enhanced-card">', unsafe_allow_html=True)
942
+ st.markdown("### 🎯 ANALYSIS SETTINGS")
943
+
944
+ # Show connection status
945
+ if connection_status:
946
+ st.success("βœ… Database Connected")
947
+ else:
948
+ st.warning("⚠️ Using Sample Data")
949
+
950
+ # DISCO selection mode
951
+ selection_mode = st.radio(
952
+ "Analysis Mode:",
953
+ ["Single DISCO", "All DISCOS"],
954
+ index=0,
955
+ horizontal=True,
956
+ label_visibility="collapsed"
957
+ )
958
+
959
+ if selection_mode == "Single DISCO":
960
+ disco_choice = st.selectbox(
961
+ "Select DISCO:",
962
+ options=list(DISCO_MAP.values()),
963
+ index=4 # Default to MEPCO
964
+ )
965
+
966
+ # Get DISCO code from name
967
+ disco_code = None
968
+ for code, name in DISCO_MAP.items():
969
+ if name == disco_choice:
970
+ disco_code = code
971
+ break
972
+ else:
973
+ disco_code = None
974
+ disco_choice = "ALL DISCOS"
975
+
976
+ st.markdown('</div>', unsafe_allow_html=True)
977
+
978
+ st.markdown('<div class="enhanced-card">', unsafe_allow_html=True)
979
+ st.markdown("### βš™οΈ FILTERS")
980
+
981
+ # Date range filter
982
+ date_filter = st.checkbox("Apply Date Filter", value=False)
983
+ if date_filter:
984
+ start_date, end_date = st.date_input(
985
+ "Select Date Range:",
986
+ value=(datetime.now() - timedelta(days=30), datetime.now())
987
+ )
988
+
989
+ # Show only processed records
990
+ show_only_processed = st.checkbox("Show only processed records", value=False)
991
+
992
+ # Flag filters
993
+ st.markdown("**Flag Filters:**")
994
+ selected_flags = st.multiselect(
995
+ "Select flags to include:",
996
+ ["A", "C", "D", "E", "N", "Unprocessed"],
997
+ default=["A", "C", "D", "E", "N", "Unprocessed"],
998
+ label_visibility="collapsed"
999
+ )
1000
+
1001
+ # Batch filter
1002
+ batch_filter = st.text_input(
1003
+ "Filter by Batch ID:",
1004
+ placeholder="e.g., 01-15, 02-15",
1005
+ help="Enter batch ID (Format: BatchNo-DISCOCode)"
1006
+ )
1007
+
1008
+ st.markdown('</div>', unsafe_allow_html=True)
1009
+
1010
+ st.markdown('<div class="enhanced-card">', unsafe_allow_html=True)
1011
+ st.markdown("### πŸ“Š QUICK METRICS")
1012
+
1013
+ # Load data for quick stats
1014
+ with st.spinner("Loading..."):
1015
+ df_temp = load_all_disco_data(disco_code)
1016
+ processed_temp = df_temp[df_temp["IMAGE_VERIFY_CODE_PITC"].notna()]
1017
+
1018
+ # Calculate OCR model accuracy
1019
+ ocr_temp = calculate_ocr_model_accuracy(df_temp)
1020
+
1021
+ col1, col2 = st.columns(2)
1022
+ with col1:
1023
+ st.metric("Total", f"{len(df_temp):,}", delta=None)
1024
+ with col2:
1025
+ st.metric("OCR Accuracy", f"{ocr_temp['accuracy']:.1f}%")
1026
+
1027
+ st.progress(len(processed_temp) / len(df_temp))
1028
+ st.caption(f"Showing data for: {disco_choice}")
1029
+
1030
+ st.markdown('</div>', unsafe_allow_html=True)
1031
+
1032
+ # Refresh button
1033
+ if st.button("πŸ”„ Refresh Dashboard", use_container_width=True, type="primary"):
1034
+ st.cache_data.clear()
1035
+ st.rerun()
1036
+
1037
+ # =========================
1038
+ # LOAD ALL DATA
1039
+ # =========================
1040
+ with st.spinner(f"πŸš€ Loading data for {disco_choice}..."):
1041
+ df = load_all_disco_data(disco_code)
1042
+
1043
+ # Apply filters
1044
+ if date_filter:
1045
+ df = df[(df["BILMONTH"] >= pd.Timestamp(start_date)) &
1046
+ (df["BILMONTH"] <= pd.Timestamp(end_date))]
1047
+
1048
+ if show_only_processed:
1049
+ df = df[df["IMAGE_VERIFY_CODE_PITC"].notna()]
1050
+
1051
+ if selected_flags:
1052
+ if "Unprocessed" in selected_flags:
1053
+ flag_filter = df["IMAGE_VERIFY_CODE_PITC"].isna()
1054
+ else:
1055
+ flag_filter = df["IMAGE_VERIFY_CODE_PITC"].isin([f for f in selected_flags if f != "Unprocessed"])
1056
+
1057
+ if "Unprocessed" in selected_flags and len(selected_flags) > 1:
1058
+ flag_filter = flag_filter | df["IMAGE_VERIFY_CODE_PITC"].isin([f for f in selected_flags if f != "Unprocessed"])
1059
+
1060
+ df = df[flag_filter]
1061
+
1062
+ if batch_filter:
1063
+ df = df[df["BATCH_ID"].str.contains(batch_filter, case=False, na=False)]
1064
+
1065
+ # Get batch statistics
1066
+ batch_stats = get_batch_statistics(df)
1067
+
1068
+ # Calculate OCR Model Accuracy
1069
+ ocr_accuracy = calculate_ocr_model_accuracy(df)
1070
+
1071
+ # Create insights
1072
+ insights = create_insights(df, batch_stats)
1073
+
1074
+ # =========================
1075
+ # CONNECTION STATUS INDICATOR
1076
+ # =========================
1077
+ if connection_status:
1078
+ st.markdown('<div class="connection-status connection-live">🟒 Live Database Connection</div>', unsafe_allow_html=True)
1079
+ else:
1080
+ st.markdown('<div class="connection-status connection-sample">⚠️ Sample Data Mode</div>', unsafe_allow_html=True)
1081
+
1082
+ # =========================
1083
+ # ENHANCED HEADER
1084
+ # =========================
1085
+ st.markdown(f"""
1086
+ <div class="enhanced-header fade-in">
1087
+ <h1 style="margin: 0; font-size: 42px; font-weight: 800; letter-spacing: 0.5px;">
1088
+ πŸ“Š OCR BATCH INTELLIGENCE DASHBOARD
1089
+ </h1>
1090
+ <p style="margin: 10px 0 0 0; font-size: 18px; opacity: 0.95; font-weight: 400;">
1091
+ Advanced Analytics | A,C,D Success Classification | OCR Model Performance
1092
+ </p>
1093
+ <div style="margin-top: 20px; display: flex; justify-content: center; gap: 20px;">
1094
+ <span class="status-indicator status-{'success' if connection_status else 'warning'}">{'🟒 Live Data' if connection_status else '⚠️ Sample Data'}</span>
1095
+ <span class="status-indicator status-info">πŸ“… {datetime.now().strftime('%Y-%m-%d')}</span>
1096
+ <span class="status-indicator status-info">🏒 {disco_choice}</span>
1097
+ <span class="status-indicator status-info">πŸ“Š {len(df):,} Records</span>
1098
+ </div>
1099
+ </div>
1100
+ """, unsafe_allow_html=True)
1101
+
1102
+ # =========================
1103
+ # EXECUTIVE KPIs - WITH PERFECT CARD SIZING
1104
+ # =========================
1105
+ st.markdown('<div class="enhanced-card fade-in">', unsafe_allow_html=True)
1106
+ st.markdown("### πŸ“ˆ EXECUTIVE DASHBOARD")
1107
+
1108
+ # Calculate KPI metrics
1109
+ total_records = len(df)
1110
+ processed_records = df["IMAGE_VERIFY_CODE_PITC"].notna().sum()
1111
+
1112
+ # Success = A, C, D
1113
+ successful_records = df["IMAGE_VERIFY_CODE_PITC"].isin(['A', 'C', 'D']).sum()
1114
+
1115
+ # Issues
1116
+ image_issues = (df["IMAGE_VERIFY_CODE_PITC"] == 'E').sum()
1117
+ reading_issues = (df["IMAGE_VERIFY_CODE_PITC"] == 'N').sum()
1118
+ perfect_matches = (df["IMAGE_VERIFY_CODE_PITC"] == 'A').sum()
1119
+
1120
+ # Rates
1121
+ processing_rate = (processed_records / total_records * 100) if total_records > 0 else 0
1122
+ success_rate = (successful_records / processed_records * 100) if processed_records > 0 else 0
1123
+ perfect_match_rate = (perfect_matches / processed_records * 100) if processed_records > 0 else 0
1124
+ image_issue_rate = (image_issues / processed_records * 100) if processed_records > 0 else 0
1125
+ reading_issue_rate = (reading_issues / processed_records * 100) if processed_records > 0 else 0
1126
+
1127
+ # Create 5 equal columns for KPIs
1128
+ kpi_cols = st.columns(5)
1129
+
1130
+ with kpi_cols[0]:
1131
+ st.markdown(f"""
1132
+ <div class="enhanced-kpi blue">
1133
+ <div class="kpi-icon">πŸ“Š</div>
1134
+ <div class="kpi-value">{total_records:,}</div>
1135
+ <div class="kpi-label">Total Records</div>
1136
+ <div class="kpi-trend">
1137
+ <span>⚑</span>
1138
+ <span>{processing_rate:.1f}% processed</span>
1139
+ </div>
1140
+ </div>
1141
+ """, unsafe_allow_html=True)
1142
+
1143
+ with kpi_cols[1]:
1144
+ st.markdown(f"""
1145
+ <div class="enhanced-kpi green">
1146
+ <div class="kpi-icon">βœ…</div>
1147
+ <div class="kpi-value">{success_rate:.1f}%</div>
1148
+ <div class="kpi-label">Success Rate (A,C,D)</div>
1149
+ <div class="kpi-trend">
1150
+ <span>πŸ“ˆ</span>
1151
+ <span>{successful_records:,} successful</span>
1152
+ </div>
1153
+ </div>
1154
+ """, unsafe_allow_html=True)
1155
+
1156
+ with kpi_cols[2]:
1157
+ # OCR Model Accuracy (A vs N)
1158
+ ocr_accuracy_rate = ocr_accuracy['accuracy']
1159
+ st.markdown(f"""
1160
+ <div class="enhanced-kpi purple">
1161
+ <div class="kpi-icon">οΏ½οΏ½</div>
1162
+ <div class="kpi-value">{ocr_accuracy_rate:.1f}%</div>
1163
+ <div class="kpi-label">OCR Model Accuracy</div>
1164
+ <div class="kpi-trend">
1165
+ <span>🎯</span>
1166
+ <span>A vs N only</span>
1167
+ </div>
1168
+ </div>
1169
+ """, unsafe_allow_html=True)
1170
+
1171
+ with kpi_cols[3]:
1172
+ st.markdown(f"""
1173
+ <div class="enhanced-kpi orange">
1174
+ <div class="kpi-icon">⭐</div>
1175
+ <div class="kpi-value">{perfect_match_rate:.1f}%</div>
1176
+ <div class="kpi-label">Perfect Match (A)</div>
1177
+ <div class="kpi-trend">
1178
+ <span>🎯</span>
1179
+ <span>{perfect_matches:,} perfect</span>
1180
+ </div>
1181
+ </div>
1182
+ """, unsafe_allow_html=True)
1183
+
1184
+ with kpi_cols[4]:
1185
+ st.markdown(f"""
1186
+ <div class="enhanced-kpi red">
1187
+ <div class="kpi-icon">πŸ–ΌοΈ</div>
1188
+ <div class="kpi-value">{image_issue_rate:.1f}%</div>
1189
+ <div class="kpi-label">Image Issues (E)</div>
1190
+ <div class="kpi-trend">
1191
+ <span>⚠️</span>
1192
+ <span>{image_issues:,} records</span>
1193
+ </div>
1194
+ </div>
1195
+ """, unsafe_allow_html=True)
1196
+
1197
+ st.markdown('</div>', unsafe_allow_html=True)
1198
+
1199
+ # =========================
1200
+ # OCR MODEL ACCURACY SECTION WITH PERFECT CARDS
1201
+ # =========================
1202
+ st.markdown('<div class="enhanced-card fade-in">', unsafe_allow_html=True)
1203
+ st.markdown("### πŸ€– OCR MODEL ACCURACY ANALYSIS")
1204
+
1205
+ ocr_col1, ocr_col2, ocr_col3 = st.columns(3)
1206
+
1207
+ with ocr_col1:
1208
+ st.markdown(f"""
1209
+ <div class="ocr-model-card" style="background: linear-gradient(135deg, var(--accent-purple), #6A4CA6);">
1210
+ <div class="ocr-icon">🎯</div>
1211
+ <div class="ocr-value">{ocr_accuracy['accuracy']:.1f}%</div>
1212
+ <div class="ocr-label">OCR MODEL ACCURACY</div>
1213
+ <div class="ocr-desc">Based on A vs N flags only</div>
1214
+ </div>
1215
+ """, unsafe_allow_html=True)
1216
+
1217
+ with ocr_col2:
1218
+ st.markdown(f"""
1219
+ <div class="ocr-model-card" style="background: linear-gradient(135deg, var(--success-green), #0D5C0D);">
1220
+ <div class="ocr-icon">βœ…</div>
1221
+ <div class="ocr-value">{ocr_accuracy['count_a']:,}</div>
1222
+ <div class="ocr-label">PERFECT MATCHES (A)</div>
1223
+ <div class="ocr-desc">OCR readings with 80%+ confidence</div>
1224
+ </div>
1225
+ """, unsafe_allow_html=True)
1226
+
1227
+ with ocr_col3:
1228
+ st.markdown(f"""
1229
+ <div class="ocr-model-card" style="background: linear-gradient(135deg, #6c757d, #495057);">
1230
+ <div class="ocr-icon">πŸ“„</div>
1231
+ <div class="ocr-value">{ocr_accuracy['count_n']:,}</div>
1232
+ <div class="ocr-label">READING MISMATCHES (N)</div>
1233
+ <div class="ocr-desc">OCR readings below 80% confidence</div>
1234
+ </div>
1235
+ """, unsafe_allow_html=True)
1236
+
1237
+ # OCR Accuracy Explanation
1238
+ st.markdown("""
1239
+ <div style="
1240
+ background: var(--light-purple);
1241
+ border-radius: 12px;
1242
+ padding: 20px;
1243
+ margin-top: 20px;
1244
+ border-left: 4px solid var(--accent-purple);
1245
+ ">
1246
+ <h4 style="margin: 0 0 10px 0; color: var(--accent-purple);">πŸ“ OCR Model Accuracy Calculation</h4>
1247
+ <p style="margin: 0; color: var(--medium-gray); font-size: 14px;">
1248
+ <strong>Formula:</strong> OCR Accuracy = (Flag A Count) / (Flag A Count + Flag N Count) Γ— 100%<br>
1249
+ <strong>Interpretation:</strong> Measures the OCR model's ability to correctly read images when they are available.<br>
1250
+ <strong>Excludes:</strong> Flags C, D, E (processed with issues) and unprocessed records.<br>
1251
+ <strong>Threshold:</strong> Flag A = Perfect match (80%+ confidence), Flag N = Reading mismatch (<80% confidence)
1252
+ </p>
1253
+ </div>
1254
+ """, unsafe_allow_html=True)
1255
+
1256
+ st.markdown('</div>', unsafe_allow_html=True)
1257
+
1258
+ # =========================
1259
+ # FLAG DISTRIBUTION - WITH PERFECT CARD SIZING
1260
+ # =========================
1261
+ st.markdown('<div class="enhanced-card fade-in">', unsafe_allow_html=True)
1262
+ st.markdown("### 🏷️ FLAG CLASSIFICATION DISTRIBUTION")
1263
+
1264
+ flag_counts = df["IMAGE_VERIFY_CODE_PITC"].value_counts()
1265
+
1266
+ flag_cols = st.columns(5)
1267
+ flag_info = {
1268
+ 'A': {'label': 'βœ… PERFECT MATCH', 'color': 'success', 'desc': 'Successful with perfect reading (80%+)'},
1269
+ 'C': {'label': '⚠️ FLAG C', 'color': 'warning', 'desc': 'Successful with minor issues'},
1270
+ 'D': {'label': '⚠️ FLAG D', 'color': 'warning', 'desc': 'Successful but needs review'},
1271
+ 'E': {'label': '❌ IMAGE ISSUE', 'color': 'danger', 'desc': 'Image not available'},
1272
+ 'N': {'label': '❌ READING ISSUE', 'color': 'danger', 'desc': 'Reading not matched (<80%)'}
1273
+ }
1274
+
1275
+ for idx, flag in enumerate(['A', 'C', 'D', 'E', 'N']):
1276
+ count = flag_counts.get(flag, 0)
1277
+ with flag_cols[idx]:
1278
+ if processed_records > 0:
1279
+ percentage = (count / processed_records * 100)
1280
+ else:
1281
+ percentage = 0
1282
+
1283
+ flag_data = flag_info.get(flag, {'label': f'FLAG {flag}', 'color': 'info', 'desc': 'Unknown flag'})
1284
+
1285
+ st.markdown(f"""
1286
+ <div class="flag-card flag-{flag}">
1287
+ <div class="flag-icon">{flag}</div>
1288
+ <div class="flag-value">{count:,}</div>
1289
+ <div class="flag-label">{flag_data['label']}</div>
1290
+ <div class="flag-percentage">{percentage:.1f}% of processed</div>
1291
+ <div class="flag-desc">{flag_data['desc']}</div>
1292
+ </div>
1293
+ """, unsafe_allow_html=True)
1294
+
1295
+ st.markdown('</div>', unsafe_allow_html=True)
1296
+
1297
+ # =========================
1298
+ # INSIGHTS CARDS
1299
+ # =========================
1300
+ st.markdown('<div class="enhanced-card fade-in">', unsafe_allow_html=True)
1301
+ st.markdown("### 🎯 BUSINESS INSIGHTS & RECOMMENDATIONS")
1302
+
1303
+ if insights:
1304
+ # Group insights by severity
1305
+ success_insights = [i for i in insights if i["severity"] == "success"]
1306
+ warning_insights = [i for i in insights if i["severity"] == "warning"]
1307
+ error_insights = [i for i in insights if i["severity"] == "error"]
1308
+
1309
+ tab_insights1, tab_insights2, tab_insights3 = st.tabs([
1310
+ f"βœ… Success ({len(success_insights)})",
1311
+ f"⚠️ Warnings ({len(warning_insights)})",
1312
+ f"❌ Issues ({len(error_insights)})"
1313
+ ])
1314
+
1315
+ with tab_insights1:
1316
+ for insight in success_insights:
1317
+ st.markdown(f"""
1318
+ <div style="
1319
+ background: linear-gradient(135deg, var(--success-green)15, transparent);
1320
+ border-radius: 12px;
1321
+ padding: 15px;
1322
+ margin: 10px 0;
1323
+ border-left: 4px solid var(--success-green);
1324
+ ">
1325
+ <div style="display: flex; justify-content: space-between; align-items: center;">
1326
+ <div style="font-weight: 700; color: var(--success-green);">
1327
+ {insight['title']}
1328
+ </div>
1329
+ <div style="background: var(--success-green); color: white; padding: 5px 12px; border-radius: 15px; font-weight: 700;">
1330
+ {insight['metric']}
1331
+ </div>
1332
+ </div>
1333
+ <div style="margin-top: 8px; font-size: 14px; color: var(--medium-gray);">
1334
+ {insight['description']}
1335
+ </div>
1336
+ </div>
1337
+ """, unsafe_allow_html=True)
1338
+
1339
+ with tab_insights2:
1340
+ for insight in warning_insights:
1341
+ st.markdown(f"""
1342
+ <div style="
1343
+ background: linear-gradient(135deg, var(--warning-orange)15, transparent);
1344
+ border-radius: 12px;
1345
+ padding: 15px;
1346
+ margin: 10px 0;
1347
+ border-left: 4px solid var(--warning-orange);
1348
+ ">
1349
+ <div style="display: flex; justify-content: space-between; align-items: center;">
1350
+ <div style="font-weight: 700; color: var(--warning-orange);">
1351
+ {insight['title']}
1352
+ </div>
1353
+ <div style="background: var(--warning-orange); color: white; padding: 5px 12px; border-radius: 15px; font-weight: 700;">
1354
+ {insight['metric']}
1355
+ </div>
1356
+ </div>
1357
+ <div style="margin-top: 8px; font-size: 14px; color: var(--medium-gray);">
1358
+ {insight['description']}
1359
+ </div>
1360
+ </div>
1361
+ """, unsafe_allow_html=True)
1362
+
1363
+ with tab_insights3:
1364
+ for insight in error_insights:
1365
+ st.markdown(f"""
1366
+ <div style="
1367
+ background: linear-gradient(135deg, var(--danger-red)15, transparent);
1368
+ border-radius: 12px;
1369
+ padding: 15px;
1370
+ margin: 10px 0;
1371
+ border-left: 4px solid var(--danger-red);
1372
+ ">
1373
+ <div style="display: flex; justify-content: space-between; align-items: center;">
1374
+ <div style="font-weight: 700; color: var(--danger-red);">
1375
+ {insight['title']}
1376
+ </div>
1377
+ <div style="background: var(--danger-red); color: white; padding: 5px 12px; border-radius: 15px; font-weight: 700;">
1378
+ {insight['metric']}
1379
+ </div>
1380
+ </div>
1381
+ <div style="margin-top: 8px; font-size: 14px; color: var(--medium-gray);">
1382
+ {insight['description']}
1383
+ </div>
1384
+ </div>
1385
+ """, unsafe_allow_html=True)
1386
+ else:
1387
+ st.info("All systems are operating within optimal parameters. No significant insights to display.")
1388
+
1389
+ # Add recommendations based on data
1390
+ st.markdown("#### 🎯 RECOMMENDATIONS")
1391
+
1392
+ recommendations = []
1393
+
1394
+ if ocr_accuracy['accuracy'] < 70:
1395
+ recommendations.append("πŸ€– **Improve OCR Algorithms**: Low OCR accuracy suggests algorithm improvements needed. Consider retraining with more diverse data.")
1396
+
1397
+ if image_issue_rate > 10:
1398
+ recommendations.append("πŸ”§ **Improve Image Capture Process**: High rate of Flag E suggests issues with image availability. Review image capture and storage systems.")
1399
+
1400
+ if perfect_match_rate < 30:
1401
+ recommendations.append("🎯 **Enhance OCR Training**: Low perfect match rate (Flag A) suggests OCR model needs better training data or parameter tuning.")
1402
+
1403
+ if processing_rate < 80:
1404
+ recommendations.append("⚑ **Increase Processing Capacity**: Low processing rate indicates system bottlenecks. Consider scaling up processing resources.")
1405
+
1406
+ if len(recommendations) > 0:
1407
+ for rec in recommendations:
1408
+ st.markdown(f"- {rec}")
1409
+ else:
1410
+ st.success("All key metrics are within optimal ranges. Maintain current processes.")
1411
+
1412
+ st.markdown('</div>', unsafe_allow_html=True)
1413
+
1414
+ # =========================
1415
+ # MAIN DASHBOARD TABS
1416
+ # =========================
1417
+ tab1, tab2, tab3 = st.tabs(["πŸ“¦ BATCH ANALYTICS", "πŸ” RECORD EXPLORER", "πŸ“Š PERFORMANCE DASHBOARD"])
1418
+
1419
+ with tab1:
1420
+ # BATCH ANALYTICS TAB
1421
+ col1, col2 = st.columns([3, 2])
1422
+
1423
+ with col1:
1424
+ st.markdown('<div class="enhanced-card">', unsafe_allow_html=True)
1425
+ st.markdown("### πŸ“Š BATCH PERFORMANCE OVERVIEW")
1426
+
1427
+ # Interactive batch selection
1428
+ selected_batch = st.selectbox(
1429
+ "Select Batch for Detailed Analysis:",
1430
+ options=["All Batches"] + sorted(batch_stats["Batch ID"].tolist()),
1431
+ help="Choose a batch to view detailed analytics"
1432
+ )
1433
+
1434
+ if selected_batch != "All Batches":
1435
+ batch_data = batch_stats[batch_stats["Batch ID"] == selected_batch].iloc[0]
1436
+
1437
+ # Batch metrics in columns
1438
+ metric_cols = st.columns(4)
1439
+ with metric_cols[0]:
1440
+ st.metric("Total Records", f"{batch_data['Total Records']:,}")
1441
+ with metric_cols[1]:
1442
+ st.metric("Processed", f"{batch_data['Processed']:,}")
1443
+ with metric_cols[2]:
1444
+ st.metric("Success Rate", f"{batch_data['Success Rate (A,C,D)']:.1f}%")
1445
+ with metric_cols[3]:
1446
+ st.metric("OCR Accuracy", f"{batch_data['OCR Model Accuracy (A vs N)']:.1f}%")
1447
+
1448
+ # Flag distribution chart
1449
+ flag_data = {
1450
+ 'A (Perfect)': batch_data['Flag A'],
1451
+ 'C (Minor)': batch_data['Flag C'],
1452
+ 'D (Review)': batch_data['Flag D'],
1453
+ 'E (Image Issue)': batch_data['Flag E'],
1454
+ 'N (Reading Issue)': batch_data['Flag N']
1455
+ }
1456
+
1457
+ colors = ['var(--success-green)', 'var(--warning-orange)', '#fd7e14',
1458
+ 'var(--danger-red)', '#6c757d']
1459
+
1460
+ fig = go.Figure(data=[
1461
+ go.Bar(
1462
+ x=list(flag_data.keys()),
1463
+ y=list(flag_data.values()),
1464
+ marker_color=colors,
1465
+ text=list(flag_data.values()),
1466
+ textposition='auto',
1467
+ hovertemplate="%{x}: %{y} records<br>%{customdata:.1f}% of processed<extra></extra>",
1468
+ customdata=[(v / batch_data['Processed'] * 100) if batch_data['Processed'] > 0 else 0
1469
+ for v in flag_data.values()]
1470
+ )
1471
+ ])
1472
+
1473
+ fig.update_layout(
1474
+ height=300,
1475
+ xaxis_title="Flag Category",
1476
+ yaxis_title="Number of Records",
1477
+ showlegend=False,
1478
+ hovermode="x unified"
1479
+ )
1480
+
1481
+ st.plotly_chart(fig, use_container_width=True)
1482
+
1483
+ # Detailed batch metrics
1484
+ st.markdown("##### πŸ“ˆ Detailed Batch Metrics")
1485
+
1486
+ detail_cols = st.columns(3)
1487
+ with detail_cols[0]:
1488
+ st.markdown(f"""
1489
+ <div style="text-align: center; padding: 15px; background: var(--light-blue); border-radius: 10px;">
1490
+ <div style="font-size: 12px; color: var(--medium-gray);">Processing Rate</div>
1491
+ <div style="font-size: 24px; font-weight: 700; color: var(--primary-blue);">
1492
+ {batch_data['Processing Rate']:.1f}%
1493
+ </div>
1494
+ </div>
1495
+ """, unsafe_allow_html=True)
1496
+
1497
+ with detail_cols[1]:
1498
+ st.markdown(f"""
1499
+ <div style="text-align: center; padding: 15px; background: var(--light-green); border-radius: 10px;">
1500
+ <div style="font-size: 12px; color: var(--medium-gray);">Accuracy Rate</div>
1501
+ <div style="font-size: 24px; font-weight: 700; color: var(--success-green);">
1502
+ {batch_data['Accuracy Rate (A,C,D)']:.1f}%
1503
+ </div>
1504
+ </div>
1505
+ """, unsafe_allow_html=True)
1506
+
1507
+ with detail_cols[2]:
1508
+ st.markdown(f"""
1509
+ <div style="text-align: center; padding: 15px; background: var(--light-purple); border-radius: 10px;">
1510
+ <div style="font-size: 12px; color: var(--medium-gray);">OCR Accuracy</div>
1511
+ <div style="font-size: 24px; font-weight: 700; color: var(--accent-purple);">
1512
+ {batch_data['OCR Model Accuracy (A vs N)']:.1f}%
1513
+ </div>
1514
+ </div>
1515
+ """, unsafe_allow_html=True)
1516
+
1517
+ st.markdown('</div>', unsafe_allow_html=True)
1518
+
1519
+ # Batch Comparison Chart
1520
+ st.markdown('<div class="enhanced-card">', unsafe_allow_html=True)
1521
+ st.markdown("### πŸ“ˆ BATCH SUCCESS RATE COMPARISON")
1522
+
1523
+ fig = go.Figure(data=[
1524
+ go.Bar(
1525
+ x=batch_stats["Batch ID"],
1526
+ y=batch_stats["Success Rate (A,C,D)"],
1527
+ name='Success Rate',
1528
+ marker_color=batch_stats["Success Rate (A,C,D)"].apply(
1529
+ lambda x: 'var(--success-green)' if x >= 70 else
1530
+ 'var(--warning-orange)' if x >= 50 else 'var(--danger-red)'
1531
+ ),
1532
+ hovertemplate="Batch: %{x}<br>Success Rate: %{y:.1f}%<br>Total: %{customdata:,} records<extra></extra>",
1533
+ customdata=batch_stats["Total Records"]
1534
+ )
1535
+ ])
1536
+
1537
+ fig.update_layout(
1538
+ height=400,
1539
+ xaxis_title="Batch ID",
1540
+ yaxis_title="Success Rate (%)",
1541
+ hovermode="x unified",
1542
+ showlegend=False
1543
+ )
1544
+
1545
+ st.plotly_chart(fig, use_container_width=True)
1546
+
1547
+ # Legend for success rates
1548
+ col_legend1, col_legend2, col_legend3 = st.columns(3)
1549
+ with col_legend1:
1550
+ st.markdown('<div style="display: flex; align-items: center; gap: 8px;"><div style="width: 20px; height: 20px; background: var(--success-green); border-radius: 4px;"></div><span>β‰₯ 70% (Good)</span></div>', unsafe_allow_html=True)
1551
+ with col_legend2:
1552
+ st.markdown('<div style="display: flex; align-items: center; gap: 8px;"><div style="width: 20px; height: 20px; background: var(--warning-orange); border-radius: 4px;"></div><span>50-70% (Needs Attention)</span></div>', unsafe_allow_html=True)
1553
+ with col_legend3:
1554
+ st.markdown('<div style="display: flex; align-items: center; gap: 8px;"><div style="width: 20px; height: 20px; background: var(--danger-red); border-radius: 4px;"></div><span>&lt; 50% (Critical)</span></div>', unsafe_allow_html=True)
1555
+
1556
+ st.markdown('</div>', unsafe_allow_html=True)
1557
+
1558
+ with col2:
1559
+ # Top Performers
1560
+ st.markdown('<div class="enhanced-card">', unsafe_allow_html=True)
1561
+ st.markdown("### πŸ† TOP 5 PERFORMING BATCHES")
1562
+
1563
+ top_batches = batch_stats.nlargest(5, 'Success Rate (A,C,D)')
1564
+
1565
+ for idx, (_, batch) in enumerate(top_batches.iterrows(), 1):
1566
+ medal = ["πŸ₯‡", "πŸ₯ˆ", "πŸ₯‰", "4️⃣", "5️⃣"][idx-1]
1567
+
1568
+ st.markdown(f"""
1569
+ <div style="
1570
+ background: linear-gradient(135deg, var(--success-green)15, transparent);
1571
+ border-radius: 10px;
1572
+ padding: 15px;
1573
+ margin: 10px 0;
1574
+ border-left: 4px solid var(--success-green);
1575
+ ">
1576
+ <div style="display: flex; justify-content: space-between; align-items: center;">
1577
+ <div style="display: flex; align-items: center; gap: 10px;">
1578
+ <span style="font-size: 20px;">{medal}</span>
1579
+ <div>
1580
+ <strong>{batch['Batch ID']}</strong><br>
1581
+ <small style="color: var(--medium-gray);">{batch['DISCO']}</small>
1582
+ </div>
1583
+ </div>
1584
+ <div style="
1585
+ background: var(--success-green);
1586
+ color: white;
1587
+ padding: 6px 12px;
1588
+ border-radius: 15px;
1589
+ font-weight: 700;
1590
+ ">
1591
+ {batch['Success Rate (A,C,D)']:.1f}%
1592
+ </div>
1593
+ </div>
1594
+ <div style="margin-top: 10px; font-size: 12px; color: var(--medium-gray);">
1595
+ πŸ“Š {batch['Total Records']:,} records |
1596
+ βœ… {batch['Successful (A,C,D)']:,} successful |
1597
+ πŸ€– {batch['OCR Model Accuracy (A vs N)']:.1f}% OCR
1598
+ </div>
1599
+ </div>
1600
+ """, unsafe_allow_html=True)
1601
+
1602
+ st.markdown('</div>', unsafe_allow_html=True)
1603
+
1604
+ # Batch OCR Accuracy Rankings
1605
+ st.markdown('<div class="enhanced-card">', unsafe_allow_html=True)
1606
+ st.markdown("### πŸ€– TOP OCR ACCURACY BATCHES")
1607
+
1608
+ # Filter batches with A+N > 0
1609
+ ocr_batches = batch_stats[batch_stats["Total A+N"] > 0].nlargest(5, 'OCR Model Accuracy (A vs N)')
1610
+
1611
+ if len(ocr_batches) > 0:
1612
+ for idx, (_, batch) in enumerate(ocr_batches.iterrows(), 1):
1613
+ medal = ["πŸ₯‡", "πŸ₯ˆ", "πŸ₯‰", "4️⃣", "5️⃣"][idx-1]
1614
+
1615
+ st.markdown(f"""
1616
+ <div style="
1617
+ background: linear-gradient(135deg, var(--accent-purple)15, transparent);
1618
+ border-radius: 10px;
1619
+ padding: 15px;
1620
+ margin: 10px 0;
1621
+ border-left: 4px solid var(--accent-purple);
1622
+ ">
1623
+ <div style="display: flex; justify-content: space-between; align-items: center;">
1624
+ <div style="display: flex; align-items: center; gap: 10px;">
1625
+ <span style="font-size: 20px;">{medal}</span>
1626
+ <div>
1627
+ <strong>{batch['Batch ID']}</strong><br>
1628
+ <small style="color: var(--medium-gray);">{batch['DISCO']}</small>
1629
+ </div>
1630
+ </div>
1631
+ <div style="
1632
+ background: var(--accent-purple);
1633
+ color: white;
1634
+ padding: 6px 12px;
1635
+ border-radius: 15px;
1636
+ font-weight: 700;
1637
+ ">
1638
+ {batch['OCR Model Accuracy (A vs N)']:.1f}%
1639
+ </div>
1640
+ </div>
1641
+ <div style="margin-top: 10px; font-size: 12px; color: var(--medium-gray);">
1642
+ πŸ€– A: {batch['Flag A']:,} | N: {batch['Flag N']:,} |
1643
+ Total A+N: {batch['Total A+N']:,}
1644
+ </div>
1645
+ </div>
1646
+ """, unsafe_allow_html=True)
1647
+ else:
1648
+ st.info("No batches with sufficient A+N records for OCR accuracy calculation.")
1649
+
1650
+ st.markdown('</div>', unsafe_allow_html=True)
1651
+
1652
+ # Batch Statistics Table
1653
+ st.markdown('<div class="enhanced-card">', unsafe_allow_html=True)
1654
+ st.markdown("### πŸ“‹ ALL BATCHES SUMMARY")
1655
+
1656
+ display_stats = batch_stats[["Batch ID", "DISCO", "Total Records", "Processed",
1657
+ "Success Rate (A,C,D)", "OCR Model Accuracy (A vs N)"]].copy()
1658
+ display_stats["Success Rate (A,C,D)"] = display_stats["Success Rate (A,C,D)"].round(1)
1659
+ display_stats["OCR Model Accuracy (A vs N)"] = display_stats["OCR Model Accuracy (A vs N)"].round(1)
1660
+
1661
+ st.dataframe(
1662
+ display_stats,
1663
+ use_container_width=True,
1664
+ height=300,
1665
+ column_config={
1666
+ "Success Rate (A,C,D)": st.column_config.ProgressColumn(
1667
+ format="%.1f%%",
1668
+ min_value=0,
1669
+ max_value=100,
1670
+ width="medium"
1671
+ ),
1672
+ "OCR Model Accuracy (A vs N)": st.column_config.ProgressColumn(
1673
+ format="%.1f%%",
1674
+ min_value=0,
1675
+ max_value=100,
1676
+ width="medium"
1677
+ )
1678
+ }
1679
+ )
1680
+
1681
+ # Export button
1682
+ batch_csv_data = batch_stats.to_csv(index=False).encode('utf-8')
1683
+ st.download_button(
1684
+ label="πŸ“₯ Download Batch Report",
1685
+ data=batch_csv_data,
1686
+ file_name="batch_performance_report.csv",
1687
+ mime="text/csv",
1688
+ use_container_width=True
1689
+ )
1690
+
1691
+ st.markdown('</div>', unsafe_allow_html=True)
1692
+
1693
+ with tab2:
1694
+ # RECORD EXPLORER TAB
1695
+ st.markdown('<div class="enhanced-card">', unsafe_allow_html=True)
1696
+ st.markdown("### πŸ” ADVANCED RECORD EXPLORER")
1697
+
1698
+ # Search and filter controls
1699
+ search_col1, search_col2, search_col3 = st.columns([2, 1, 1])
1700
+
1701
+ with search_col1:
1702
+ search_query = st.text_input(
1703
+ "Search records:",
1704
+ placeholder="Search by REF_DIGITS, DISCO, BATCH...",
1705
+ help="Search across all record fields"
1706
+ )
1707
+
1708
+ with search_col2:
1709
+ filter_disco = st.selectbox(
1710
+ "Filter by DISCO:",
1711
+ ["All"] + sorted(df["DISCO_NAME"].unique().tolist())
1712
+ )
1713
+
1714
+ with search_col3:
1715
+ filter_flag = st.selectbox(
1716
+ "Filter by Flag:",
1717
+ ["All", "A", "C", "D", "E", "N", "Unprocessed"]
1718
+ )
1719
+
1720
+ # Apply filters
1721
+ filtered_df = df.copy()
1722
+
1723
+ if search_query:
1724
+ filtered_df = filtered_df[
1725
+ filtered_df["REF_DIGITS"].str.contains(search_query, case=False, na=False) |
1726
+ filtered_df["DISCO_NAME"].str.contains(search_query, case=False, na=False) |
1727
+ filtered_df["BATCH_ID"].str.contains(search_query, case=False, na=False)
1728
+ ]
1729
+
1730
+ if filter_disco != "All":
1731
+ filtered_df = filtered_df[filtered_df["DISCO_NAME"] == filter_disco]
1732
+
1733
+ if filter_flag != "All":
1734
+ if filter_flag == "Unprocessed":
1735
+ filtered_df = filtered_df[filtered_df["IMAGE_VERIFY_CODE_PITC"].isna()]
1736
+ else:
1737
+ filtered_df = filtered_df[filtered_df["IMAGE_VERIFY_CODE_PITC"] == filter_flag]
1738
+
1739
+ # Display results
1740
+ st.metric("Found Records", f"{len(filtered_df):,}",
1741
+ delta=f"{len(filtered_df)/len(df)*100:.1f}% of total" if len(df) > 0 else "0%")
1742
+
1743
+ # Enhanced data table
1744
+ display_columns = ["REF_DIGITS", "DISCO_NAME", "BATCH_ID", "SUB_DIV",
1745
+ "IMAGE_VERIFY_CODE_PITC", "ACCURACY_CATEGORY", "BILMONTH"]
1746
+
1747
+ st.dataframe(
1748
+ filtered_df[display_columns],
1749
+ use_container_width=True,
1750
+ height=400,
1751
+ column_config={
1752
+ "IMAGE_VERIFY_CODE_PITC": st.column_config.TextColumn(
1753
+ "Flag",
1754
+ help="Processing flag",
1755
+ width="small"
1756
+ ),
1757
+ "ACCURACY_CATEGORY": st.column_config.TextColumn(
1758
+ "Category",
1759
+ help="Accuracy classification",
1760
+ width="medium"
1761
+ )
1762
+ }
1763
+ )
1764
+
1765
+ # Export options
1766
+ col_exp1, col_exp2 = st.columns(2)
1767
+
1768
+ with col_exp1:
1769
+ filtered_csv_data = filtered_df.to_csv(index=False).encode('utf-8')
1770
+ st.download_button(
1771
+ label="πŸ“₯ Download Filtered Data",
1772
+ data=filtered_csv_data,
1773
+ file_name="ocr_filtered_records.csv",
1774
+ mime="text/csv",
1775
+ use_container_width=True
1776
+ )
1777
+
1778
+ with col_exp2:
1779
+ if st.button("πŸ”„ Clear Filters", use_container_width=True):
1780
+ st.rerun()
1781
+
1782
+ st.markdown('</div>', unsafe_allow_html=True)
1783
+
1784
+ # Record Details View
1785
+ st.markdown('<div class="enhanced-card">', unsafe_allow_html=True)
1786
+ st.markdown("### πŸ“„ RECORD DETAIL VIEW")
1787
+
1788
+ if not filtered_df.empty:
1789
+ record_options = filtered_df["REF_DIGITS"].head(500).tolist()
1790
+ selected_record = st.selectbox(
1791
+ "Select a record for detailed view:",
1792
+ record_options,
1793
+ help="Choose a record to see detailed information"
1794
+ )
1795
+
1796
+ if selected_record:
1797
+ record_data = filtered_df[filtered_df["REF_DIGITS"] == selected_record].iloc[0]
1798
+
1799
+ col1, col2 = st.columns(2)
1800
+
1801
+ with col1:
1802
+ st.markdown("##### πŸ“‹ Basic Information")
1803
+
1804
+ info_items = [
1805
+ ("REF_DIGITS", record_data["REF_DIGITS"]),
1806
+ ("DISCO", f"{record_data['DISCO_NAME']} ({record_data['DISCO_CODE']})"),
1807
+ ("Batch", f"{record_data['BATCH_NO']} (ID: {record_data['BATCH_ID']})"),
1808
+ ("SUB_DIV", record_data["SUB_DIV"]),
1809
+ ("Bill Month", record_data["BILMONTH"].strftime("%B %Y") if pd.notna(record_data["BILMONTH"]) else "N/A")
1810
+ ]
1811
+
1812
+ for label, value in info_items:
1813
+ st.markdown(f"""
1814
+ <div style="
1815
+ background: var(--light-gray);
1816
+ border-radius: 8px;
1817
+ padding: 12px;
1818
+ margin: 5px 0;
1819
+ ">
1820
+ <div style="font-size: 12px; color: var(--medium-gray); font-weight: 600;">{label}</div>
1821
+ <div style="font-size: 14px; font-weight: 700; margin-top: 5px;">{value}</div>
1822
+ </div>
1823
+ """, unsafe_allow_html=True)
1824
+
1825
+ with col2:
1826
+ st.markdown("##### 🏷️ Processing Information")
1827
+
1828
+ flag_value = record_data["IMAGE_VERIFY_CODE_PITC"]
1829
+ flag_map = {
1830
+ 'A': ("Perfect Match", "βœ…", "var(--success-green)", "Successful with perfect reading (80%+ confidence)"),
1831
+ 'C': ("Flag C", "⚠️", "var(--warning-orange)", "Successful with minor issues"),
1832
+ 'D': ("Flag D", "⚠️", "#fd7e14", "Successful but needs review"),
1833
+ 'E': ("Image Not Available", "❌", "var(--danger-red)", "Image could not be processed"),
1834
+ 'N': ("Reading Not Matched", "❌", "#6c757d", "Reading confidence < 80%"),
1835
+ None: ("Pending Processing", "⏳", "#6c757d", "Waiting for processing")
1836
+ }
1837
+
1838
+ status_text, status_icon, status_color, status_desc = flag_map.get(
1839
+ flag_value, ("Unknown", "❓", "#6c757d", "Unknown status")
1840
+ )
1841
+
1842
+ st.markdown(f"""
1843
+ <div style="
1844
+ background: {status_color}15;
1845
+ border-radius: 12px;
1846
+ padding: 20px;
1847
+ text-align: center;
1848
+ border: 2px solid {status_color};
1849
+ margin-bottom: 20px;
1850
+ ">
1851
+ <div style="font-size: 48px; margin-bottom: 10px;">
1852
+ {status_icon}
1853
+ </div>
1854
+ <div style="font-size: 18px; font-weight: 700; color: {status_color};">
1855
+ {status_text}
1856
+ </div>
1857
+ <div style="margin-top: 10px; font-size: 14px; color: var(--medium-gray);">
1858
+ {status_desc}
1859
+ </div>
1860
+ </div>
1861
+ """, unsafe_allow_html=True)
1862
+
1863
+ # Accuracy category
1864
+ st.markdown(f"""
1865
+ <div style="
1866
+ background: var(--light-blue);
1867
+ border-radius: 8px;
1868
+ padding: 15px;
1869
+ text-align: center;
1870
+ ">
1871
+ <div style="font-size: 12px; color: var(--medium-gray);">Accuracy Category</div>
1872
+ <div style="font-size: 16px; font-weight: 700; color: var(--primary-blue); margin-top: 5px;">
1873
+ {record_data['ACCURACY_CATEGORY']}
1874
+ </div>
1875
+ </div>
1876
+ """, unsafe_allow_html=True)
1877
+ else:
1878
+ st.info("No records found with current filters.")
1879
+
1880
+ st.markdown('</div>', unsafe_allow_html=True)
1881
+
1882
+ with tab3:
1883
+ # PERFORMANCE DASHBOARD TAB
1884
+ col1, col2 = st.columns(2)
1885
+
1886
+ with col1:
1887
+ # Processing Trend by Month
1888
+ st.markdown('<div class="enhanced-card">', unsafe_allow_html=True)
1889
+ st.markdown("### πŸ“ˆ MONTHLY PERFORMANCE TREND")
1890
+
1891
+ monthly_data = df.copy()
1892
+ monthly_data["MONTH"] = pd.to_datetime(monthly_data["BILMONTH"]).dt.strftime("%Y-%m")
1893
+
1894
+ monthly_stats = monthly_data.groupby("MONTH").agg({
1895
+ "REF_DIGITS": "count",
1896
+ "IMAGE_VERIFY_CODE_PITC": lambda x: x.notna().sum(),
1897
+ "ACCURACY_CATEGORY": lambda x: (x == "Success (A,C,D)").sum()
1898
+ }).reset_index()
1899
+
1900
+ monthly_stats.columns = ["Month", "Total Records", "Processed", "Successful (A,C,D)"]
1901
+ monthly_stats["Processing Rate"] = (monthly_stats["Processed"] / monthly_stats["Total Records"] * 100).round(1)
1902
+ monthly_stats["Success Rate"] = (monthly_stats["Successful (A,C,D)"] / monthly_stats["Processed"] * 100).round(1)
1903
+
1904
+ # Calculate OCR accuracy per month
1905
+ monthly_ocr = []
1906
+ for month in monthly_stats["Month"]:
1907
+ month_df = monthly_data[monthly_data["MONTH"] == month]
1908
+ ocr_month = calculate_ocr_model_accuracy(month_df)
1909
+ monthly_ocr.append(ocr_month['accuracy'])
1910
+
1911
+ monthly_stats["OCR Accuracy"] = monthly_ocr
1912
+
1913
+ fig_trend = go.Figure()
1914
+
1915
+ fig_trend.add_trace(go.Scatter(
1916
+ x=monthly_stats["Month"],
1917
+ y=monthly_stats["Processing Rate"],
1918
+ mode='lines+markers',
1919
+ name='Processing Rate',
1920
+ line=dict(color='var(--primary-blue)', width=3),
1921
+ marker=dict(size=8)
1922
+ ))
1923
+
1924
+ fig_trend.add_trace(go.Scatter(
1925
+ x=monthly_stats["Month"],
1926
+ y=monthly_stats["OCR Accuracy"],
1927
+ mode='lines+markers',
1928
+ name='OCR Accuracy',
1929
+ line=dict(color='var(--accent-purple)', width=3),
1930
+ marker=dict(size=8)
1931
+ ))
1932
+
1933
+ fig_trend.update_layout(
1934
+ height=400,
1935
+ xaxis_title="Month",
1936
+ yaxis_title="Rate (%)",
1937
+ hovermode="x unified",
1938
+ legend=dict(
1939
+ orientation="h",
1940
+ yanchor="bottom",
1941
+ y=1.02,
1942
+ xanchor="right",
1943
+ x=1
1944
+ )
1945
+ )
1946
+
1947
+ st.plotly_chart(fig_trend, use_container_width=True)
1948
+
1949
+ # Monthly statistics table
1950
+ st.dataframe(
1951
+ monthly_stats[["Month", "Total Records", "Processed", "Processing Rate", "OCR Accuracy"]],
1952
+ use_container_width=True,
1953
+ height=200
1954
+ )
1955
+
1956
+ st.markdown('</div>', unsafe_allow_html=True)
1957
+
1958
+ # DISCO Performance Comparison
1959
+ st.markdown('<div class="enhanced-card">', unsafe_allow_html=True)
1960
+ st.markdown("### 🏒 DISCO PERFORMANCE COMPARISON")
1961
+
1962
+ disco_perf = df.groupby("DISCO_NAME").agg({
1963
+ "REF_DIGITS": "count",
1964
+ "IMAGE_VERIFY_CODE_PITC": lambda x: x.notna().sum(),
1965
+ "ACCURACY_CATEGORY": lambda x: (x == "Success (A,C,D)").sum()
1966
+ }).reset_index()
1967
+
1968
+ disco_perf.columns = ["DISCO", "Total Records", "Processed", "Successful (A,C,D)"]
1969
+ disco_perf["Processing Rate"] = (disco_perf["Processed"] / disco_perf["Total Records"] * 100).round(1)
1970
+ disco_perf["Success Rate"] = (disco_perf["Successful (A,C,D)"] / disco_perf["Processed"] * 100).round(1)
1971
+
1972
+ # Calculate OCR accuracy per DISCO
1973
+ disco_ocr = []
1974
+ for disco in disco_perf["DISCO"]:
1975
+ disco_df = df[df["DISCO_NAME"] == disco]
1976
+ ocr_disco = calculate_ocr_model_accuracy(disco_df)
1977
+ disco_ocr.append(ocr_disco['accuracy'])
1978
+
1979
+ disco_perf["OCR Accuracy"] = disco_ocr
1980
+
1981
+ fig_disco = go.Figure(data=[
1982
+ go.Bar(
1983
+ name='Processing Rate',
1984
+ x=disco_perf["DISCO"],
1985
+ y=disco_perf["Processing Rate"],
1986
+ marker_color='var(--primary-blue)',
1987
+ hovertemplate="DISCO: %{x}<br>Processing Rate: %{y:.1f}%<extra></extra>"
1988
+ ),
1989
+ go.Bar(
1990
+ name='OCR Accuracy',
1991
+ x=disco_perf["DISCO"],
1992
+ y=disco_perf["OCR Accuracy"],
1993
+ marker_color='var(--accent-purple)',
1994
+ hovertemplate="DISCO: %{x}<br>OCR Accuracy: %{y:.1f}%<extra></extra>"
1995
+ )
1996
+ ])
1997
+
1998
+ fig_disco.update_layout(
1999
+ height=400,
2000
+ barmode='group',
2001
+ xaxis_title="DISCO",
2002
+ yaxis_title="Rate (%)",
2003
+ hovermode="x unified"
2004
+ )
2005
+
2006
+ st.plotly_chart(fig_disco, use_container_width=True)
2007
+
2008
+ st.markdown('</div>', unsafe_allow_html=True)
2009
+
2010
+ with col2:
2011
+ # OCR Model Performance Analysis
2012
+ st.markdown('<div class="enhanced-card">', unsafe_allow_html=True)
2013
+ st.markdown("### πŸ€– OCR MODEL PERFORMANCE ANALYSIS")
2014
+
2015
+ # A vs N Distribution
2016
+ an_counts = {
2017
+ 'A (Perfect Match)': ocr_accuracy['count_a'],
2018
+ 'N (Reading Mismatch)': ocr_accuracy['count_n']
2019
+ }
2020
+
2021
+ fig_an = go.Figure(data=[
2022
+ go.Pie(
2023
+ labels=list(an_counts.keys()),
2024
+ values=list(an_counts.values()),
2025
+ hole=.3,
2026
+ marker_colors=['var(--success-green)', '#6c757d'],
2027
+ textinfo='percent+label',
2028
+ hovertemplate="<b>%{label}</b><br>Count: %{value}<br>Percentage: %{percent}<extra></extra>"
2029
+ )
2030
+ ])
2031
+
2032
+ fig_an.update_layout(
2033
+ height=400,
2034
+ showlegend=True,
2035
+ legend=dict(
2036
+ orientation="h",
2037
+ yanchor="bottom",
2038
+ y=-0.2,
2039
+ xanchor="center",
2040
+ x=0.5
2041
+ ),
2042
+ title="A vs N Distribution for OCR Model Evaluation"
2043
+ )
2044
+
2045
+ st.plotly_chart(fig_an, use_container_width=True)
2046
+
2047
+ # OCR Performance Metrics
2048
+ ocr_metrics_cols = st.columns(3)
2049
+ with ocr_metrics_cols[0]:
2050
+ st.metric("OCR Accuracy", f"{ocr_accuracy['accuracy']:.1f}%")
2051
+ with ocr_metrics_cols[1]:
2052
+ st.metric("Perfect Matches (A)", f"{ocr_accuracy['count_a']:,}")
2053
+ with ocr_metrics_cols[2]:
2054
+ st.metric("Reading Issues (N)", f"{ocr_accuracy['count_n']:,}")
2055
+
2056
+ st.markdown('</div>', unsafe_allow_html=True)
2057
+
2058
+ # Batch OCR Accuracy Heatmap
2059
+ st.markdown('<div class="enhanced-card">', unsafe_allow_html=True)
2060
+ st.markdown("### πŸ”₯ BATCH OCR ACCURACY HEATMAP")
2061
+
2062
+ # Prepare heatmap data for batches with A+N > 0
2063
+ ocr_batches = batch_stats[batch_stats["Total A+N"] > 0]
2064
+
2065
+ if len(ocr_batches) > 0:
2066
+ heatmap_data = ocr_batches.pivot_table(
2067
+ index='DISCO',
2068
+ columns='Batch No',
2069
+ values='OCR Model Accuracy (A vs N)',
2070
+ aggfunc='mean'
2071
+ ).fillna(0)
2072
+
2073
+ fig_heatmap = go.Figure(data=go.Heatmap(
2074
+ z=heatmap_data.values,
2075
+ x=heatmap_data.columns,
2076
+ y=heatmap_data.index,
2077
+ colorscale='RdYlGn',
2078
+ zmin=0,
2079
+ zmax=100,
2080
+ text=np.round(heatmap_data.values, 1),
2081
+ texttemplate='%{text}%',
2082
+ textfont={"size": 10},
2083
+ hovertemplate="DISCO: %{y}<br>Batch: %{x}<br>OCR Accuracy: %{z:.1f}%<extra></extra>"
2084
+ ))
2085
+
2086
+ fig_heatmap.update_layout(
2087
+ height=400,
2088
+ xaxis_title="Batch Number",
2089
+ yaxis_title="DISCO",
2090
+ showlegend=False
2091
+ )
2092
+
2093
+ st.plotly_chart(fig_heatmap, use_container_width=True)
2094
+ else:
2095
+ st.info("No batches with sufficient A+N records for OCR accuracy heatmap.")
2096
+
2097
+ st.markdown('</div>', unsafe_allow_html=True)
2098
+
2099
+ # Export Analytics Section
2100
+ st.markdown('<div class="enhanced-card">', unsafe_allow_html=True)
2101
+ st.markdown("### πŸ“€ EXPORT ANALYTICS REPORTS")
2102
+
2103
+ exp_col1, exp_col2, exp_col3 = st.columns(3)
2104
+
2105
+ with exp_col1:
2106
+ # Monthly Report
2107
+ monthly_csv_data = monthly_stats.to_csv(index=False).encode('utf-8')
2108
+ st.download_button(
2109
+ label="πŸ“₯ Download Monthly Report",
2110
+ data=monthly_csv_data,
2111
+ file_name="monthly_performance_report.csv",
2112
+ mime="text/csv",
2113
+ use_container_width=True
2114
+ )
2115
+
2116
+ with exp_col2:
2117
+ # DISCO Report
2118
+ disco_csv_data = disco_perf.to_csv(index=False).encode('utf-8')
2119
+ st.download_button(
2120
+ label="πŸ“₯ Download DISCO Report",
2121
+ data=disco_csv_data,
2122
+ file_name="disco_performance_report.csv",
2123
+ mime="text/csv",
2124
+ use_container_width=True
2125
+ )
2126
+
2127
+ with exp_col3:
2128
+ # OCR Accuracy Report
2129
+ ocr_report = pd.DataFrame({
2130
+ 'Metric': ['OCR Model Accuracy', 'Perfect Matches (A)', 'Reading Mismatches (N)', 'Total A+N'],
2131
+ 'Value': [f"{ocr_accuracy['accuracy']:.2f}%",
2132
+ f"{ocr_accuracy['count_a']:,}",
2133
+ f"{ocr_accuracy['count_n']:,}",
2134
+ f"{ocr_accuracy['total_an']:,}"]
2135
+ })
2136
+ ocr_csv_data = ocr_report.to_csv(index=False).encode('utf-8')
2137
+ st.download_button(
2138
+ label="πŸ“₯ Download OCR Report",
2139
+ data=ocr_csv_data,
2140
+ file_name="ocr_model_accuracy_report.csv",
2141
+ mime="text/csv",
2142
+ use_container_width=True
2143
+ )
2144
+
2145
+ st.markdown('</div>', unsafe_allow_html=True)
2146
+
2147
+ # =========================
2148
+ # FOOTER
2149
+ # =========================
2150
+ st.markdown(f"""
2151
+ <div style="
2152
+ background: linear-gradient(135deg, var(--dark-gray), #1a1a1a);
2153
+ color: white;
2154
+ padding: 20px;
2155
+ border-radius: 12px;
2156
+ margin-top: 30px;
2157
+ text-align: center;
2158
+ font-size: 12px;
2159
+ opacity: 0.9;
2160
+ ">
2161
+ <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;">
2162
+ <div>
2163
+ πŸ“… <strong>Last Updated:</strong> {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} |
2164
+ 🏒 <strong>DISCO:</strong> {disco_choice}
2165
+ </div>
2166
+ <div>
2167
+ πŸ“Š <strong>Records:</strong> {len(df):,} |
2168
+ ⚑ <strong>Processed:</strong> {processed_records:,} ({processing_rate:.1f}%)
2169
+ </div>
2170
+ <div>
2171
+ βœ… <strong>Success (A,C,D):</strong> {successful_records:,} ({success_rate:.1f}%) |
2172
+ πŸ€– <strong>OCR Accuracy:</strong> {ocr_accuracy['accuracy']:.1f}%
2173
+ </div>
2174
+ </div>
2175
+ <div style="margin-top: 10px; font-size: 11px; opacity: 0.7;">
2176
+ πŸš€ OCR Intelligence Dashboard v2.1 | Hugging Face Optimized | Data: {'Live Database' if connection_status else 'Sample Mode'}
2177
+ </div>
2178
+ </div>
2179
+ """, unsafe_allow_html=True)