-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmodels.py
More file actions
446 lines (361 loc) · 16.6 KB
/
models.py
File metadata and controls
446 lines (361 loc) · 16.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
"""
models.py — SQLAlchemy models for the Flask PDF-Manager application.
Models
------
* User — application users with RBAC roles
* Document — uploaded PDF files
* ExtractedField — individual fields parsed from a Document
* FieldEditHistory — history of field edits
* OCRCharacterData — per-character OCR confidence + bounding boxes
* RAGEmbedding — vector embeddings for RAG search
* AuditLog — immutable audit trail for all user actions
* ValidationLog — audit trail for Train Me validation runs
* FieldCorrection — per-field corrections applied by Train Me
* TrainingExample — labeled training examples for RAG confidence boosting
* TrainingExample — labeled field values used by TrainingService
"""
from __future__ import annotations
from datetime import datetime
from flask_bcrypt import Bcrypt
from flask_login import UserMixin
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
bcrypt = Bcrypt()
# ---------------------------------------------------------------------------
# User
# ---------------------------------------------------------------------------
class User(UserMixin, db.Model):
"""Application user with role-based access control."""
__tablename__ = "users"
ROLES = ("Admin", "Verifier", "Viewer")
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password_hash = db.Column(db.String(256), nullable=False)
role = db.Column(db.String(20), nullable=False, default="Viewer")
is_active = db.Column(db.Boolean, nullable=False, default=True)
created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
documents = db.relationship("Document", backref="uploader", lazy="dynamic")
audit_logs = db.relationship("AuditLog", backref="user", lazy="dynamic",
foreign_keys="AuditLog.user_id")
def set_password(self, password: str) -> None:
"""Hash *password* (minimum 8 characters) and store it."""
if len(password) < 8:
raise ValueError("Password must be at least 8 characters long.")
self.password_hash = bcrypt.generate_password_hash(password).decode("utf-8")
def check_password(self, password: str) -> bool:
"""Return *True* if *password* matches the stored hash."""
return bcrypt.check_password_hash(self.password_hash, password)
def __repr__(self) -> str:
return f"<User {self.username!r} role={self.role!r}>"
# ---------------------------------------------------------------------------
# Document
# ---------------------------------------------------------------------------
class Document(db.Model):
"""An uploaded PDF file and its processing status."""
__tablename__ = "documents"
STATUSES = ("uploaded", "extracted", "edited", "approved", "rejected")
id = db.Column(db.Integer, primary_key=True)
filename = db.Column(db.String(255), nullable=False)
file_path = db.Column(db.String(512), nullable=False)
status = db.Column(db.String(20), nullable=False, default="uploaded")
uploaded_by = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=True)
created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
page_count = db.Column(db.Integer, nullable=True)
file_size = db.Column(db.Integer, nullable=True) # bytes
fields = db.relationship(
"ExtractedField",
backref="document",
lazy="dynamic",
cascade="all, delete-orphan",
)
def __repr__(self) -> str:
return f"<Document id={self.id} filename={self.filename!r} status={self.status!r}>"
# ---------------------------------------------------------------------------
# ExtractedField
# ---------------------------------------------------------------------------
class ExtractedField(db.Model):
"""A single field extracted from a Document."""
__tablename__ = "extracted_fields"
id = db.Column(db.Integer, primary_key=True)
document_id = db.Column(
db.Integer, db.ForeignKey("documents.id"), nullable=False
)
field_name = db.Column(db.String(100), nullable=False)
value = db.Column(db.Text, nullable=True)
confidence = db.Column(db.Float, nullable=False, default=1.0)
is_edited = db.Column(db.Boolean, nullable=False, default=False)
original_value = db.Column(db.Text, nullable=True)
# Bounding box coordinates (PDF point units)
bbox_x = db.Column(db.Float, nullable=True)
bbox_y = db.Column(db.Float, nullable=True)
bbox_width = db.Column(db.Float, nullable=True)
bbox_height = db.Column(db.Float, nullable=True)
page_number = db.Column(db.Integer, nullable=True, default=1)
version = db.Column(db.Integer, nullable=False, default=1)
edit_history = db.relationship(
"FieldEditHistory",
backref="field",
lazy="dynamic",
cascade="all, delete-orphan",
)
def to_dict(self) -> dict:
"""Return a JSON-serialisable representation."""
return {
"id": self.id,
"document_id": self.document_id,
"field_name": self.field_name,
"value": self.value,
"confidence": self.confidence,
"is_edited": self.is_edited,
"original_value": self.original_value,
"bbox": {
"x": self.bbox_x,
"y": self.bbox_y,
"width": self.bbox_width,
"height": self.bbox_height,
} if self.bbox_x is not None else None,
"page_number": self.page_number,
"version": self.version,
}
def __repr__(self) -> str:
return f"<ExtractedField {self.field_name!r}={self.value!r}>"
# ---------------------------------------------------------------------------
# FieldEditHistory
# ---------------------------------------------------------------------------
class FieldEditHistory(db.Model):
"""Tracks every edit made to an ExtractedField."""
__tablename__ = "field_edit_history"
id = db.Column(db.Integer, primary_key=True)
field_id = db.Column(
db.Integer, db.ForeignKey("extracted_fields.id"), nullable=False
)
old_value = db.Column(db.Text, nullable=True)
new_value = db.Column(db.Text, nullable=True)
edited_by = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=True)
edited_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
def to_dict(self) -> dict:
return {
"id": self.id,
"field_id": self.field_id,
"old_value": self.old_value,
"new_value": self.new_value,
"edited_by": self.edited_by,
"edited_at": self.edited_at.isoformat(),
}
def __repr__(self) -> str:
return f"<FieldEditHistory field_id={self.field_id} at={self.edited_at}>"
# ---------------------------------------------------------------------------
# OCRCharacterData
# ---------------------------------------------------------------------------
class OCRCharacterData(db.Model):
"""Per-character OCR output with bounding box and confidence."""
__tablename__ = "ocr_character_data"
id = db.Column(db.Integer, primary_key=True)
document_id = db.Column(
db.Integer, db.ForeignKey("documents.id"), nullable=False
)
page_number = db.Column(db.Integer, nullable=False, default=1)
character = db.Column(db.String(10), nullable=False)
confidence = db.Column(db.Float, nullable=False, default=0.0)
# Bounding box in PDF point units
x = db.Column(db.Float, nullable=True)
y = db.Column(db.Float, nullable=True)
width = db.Column(db.Float, nullable=True)
height = db.Column(db.Float, nullable=True)
ocr_engine = db.Column(db.String(50), nullable=True) # tesseract/easyocr/paddleocr
def to_dict(self) -> dict:
return {
"id": self.id,
"document_id": self.document_id,
"page_number": self.page_number,
"character": self.character,
"confidence": self.confidence,
"x": self.x,
"y": self.y,
"width": self.width,
"height": self.height,
"ocr_engine": self.ocr_engine,
}
def __repr__(self) -> str:
return f"<OCRCharacterData char={self.character!r} conf={self.confidence:.2f}>"
# ---------------------------------------------------------------------------
# RAGEmbedding
# ---------------------------------------------------------------------------
class RAGEmbedding(db.Model):
"""Vector embedding for a field/chunk used by the RAG system."""
__tablename__ = "rag_embeddings"
id = db.Column(db.Integer, primary_key=True)
document_id = db.Column(
db.Integer, db.ForeignKey("documents.id"), nullable=False
)
field_name = db.Column(db.String(100), nullable=True)
text_content = db.Column(db.Text, nullable=False)
# Serialised embedding vector (JSON list of floats)
embedding = db.Column(db.Text, nullable=True)
created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
def to_dict(self) -> dict:
return {
"id": self.id,
"document_id": self.document_id,
"field_name": self.field_name,
"text_content": self.text_content,
"created_at": self.created_at.isoformat(),
}
def __repr__(self) -> str:
return f"<RAGEmbedding doc={self.document_id} field={self.field_name!r}>"
# ---------------------------------------------------------------------------
# AuditLog
# ---------------------------------------------------------------------------
class AuditLog(db.Model):
"""Immutable audit trail for all user actions."""
__tablename__ = "audit_logs"
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=True)
action = db.Column(db.String(100), nullable=False)
resource_type = db.Column(db.String(50), nullable=True)
resource_id = db.Column(db.String(100), nullable=True)
details = db.Column(db.Text, nullable=True)
timestamp = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
def __repr__(self) -> str:
return f"<AuditLog action={self.action!r} at={self.timestamp}>"
# ---------------------------------------------------------------------------
# ValidationLog
# ---------------------------------------------------------------------------
class ValidationLog(db.Model):
"""Audit trail for each Train Me validation run."""
__tablename__ = "validation_logs"
id = db.Column(db.Integer, primary_key=True)
document_id = db.Column(
db.Integer, db.ForeignKey("documents.id"), nullable=False
)
reference_set = db.Column(db.String(100), nullable=False)
validation_timestamp = db.Column(
db.DateTime, nullable=False, default=datetime.utcnow
)
total_fields = db.Column(db.Integer, nullable=False, default=0)
validated_count = db.Column(db.Integer, nullable=False, default=0)
accuracy_score = db.Column(db.Float, nullable=False, default=0.0)
results_json = db.Column(db.Text, nullable=True) # JSON field-by-field details
created_by = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=True)
created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
corrections = db.relationship(
"FieldCorrection",
backref="validation_log",
lazy="dynamic",
cascade="all, delete-orphan",
)
def to_dict(self) -> dict:
return {
"id": self.id,
"document_id": self.document_id,
"reference_set": self.reference_set,
"validation_timestamp": self.validation_timestamp.isoformat(),
"total_fields": self.total_fields,
"validated_count": self.validated_count,
"accuracy_score": self.accuracy_score,
"created_by": self.created_by,
"created_at": self.created_at.isoformat(),
}
def __repr__(self) -> str:
return (
f"<ValidationLog doc={self.document_id} ref={self.reference_set!r}"
f" acc={self.accuracy_score:.2f}>"
)
# ---------------------------------------------------------------------------
# FieldCorrection
# ---------------------------------------------------------------------------
class FieldCorrection(db.Model):
"""Records a single field correction applied during a Train Me run."""
__tablename__ = "field_corrections"
CORRECTION_SOURCES = ("train_me", "manual", "rag")
id = db.Column(db.Integer, primary_key=True)
validation_log_id = db.Column(
db.Integer, db.ForeignKey("validation_logs.id"), nullable=False
)
field_id = db.Column(
db.Integer, db.ForeignKey("extracted_fields.id"), nullable=True
)
field_name = db.Column(db.String(100), nullable=False)
original_value = db.Column(db.Text, nullable=True)
corrected_value = db.Column(db.Text, nullable=True)
correction_source = db.Column(
db.String(20), nullable=False, default="train_me"
)
validated_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
def to_dict(self) -> dict:
return {
"id": self.id,
"validation_log_id": self.validation_log_id,
"field_id": self.field_id,
"field_name": self.field_name,
"original_value": self.original_value,
"corrected_value": self.corrected_value,
"correction_source": self.correction_source,
"validated_at": self.validated_at.isoformat(),
"created_at": self.created_at.isoformat(),
}
def __repr__(self) -> str:
return (
f"<FieldCorrection field={self.field_name!r}"
f" {self.original_value!r} → {self.corrected_value!r}>"
)
# ---------------------------------------------------------------------------
# TrainingExample
# ---------------------------------------------------------------------------
class TrainingExample(db.Model):
"""A labeled training example for improving RAG extraction confidence.
Users upload and manually correct address book PDFs, then mark them as
training examples. The RAG extractor uses these examples to boost
confidence scores for fields that match training data.
Each row stores one field_name / field_value pair drawn from a confirmed
document. The TrainingService queries these rows to:
* detect email-domain patterns across all Email examples
* auto-generate missing emails using ``firstname@domain``
* fill blank fields using the most recent matching value
* correct mismatched values when training data disagrees with RAG output
Each row stores one field_name / field_value pair drawn from a confirmed
document. The TrainingService queries these rows to fill blank fields and
correct incorrect extraction results.
"""
__tablename__ = "training_examples"
id = db.Column(db.Integer, primary_key=True)
document_id = db.Column(
db.Integer, db.ForeignKey("documents.id"), nullable=False
)
field_name = db.Column(db.String(255), nullable=False)
correct_value = db.Column(db.Text, nullable=False)
field_value = db.Column(db.Text, nullable=True)
created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
created_by = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=True)
# ROI metadata — populated by the per-document "all fields at once" trainer
page_number = db.Column(db.Integer, nullable=True, default=1)
x0 = db.Column(db.Float, nullable=True)
y0 = db.Column(db.Float, nullable=True)
x1 = db.Column(db.Float, nullable=True)
y1 = db.Column(db.Float, nullable=True)
engine = db.Column(db.String(64), nullable=True)
anchor_text = db.Column(db.Text, nullable=True)
def to_dict(self) -> dict:
return {
"id": self.id,
"document_id": self.document_id,
"field_name": self.field_name,
"correct_value": self.correct_value,
"field_value": self.field_value,
"created_at": self.created_at.isoformat(),
"created_by": self.created_by,
"page_number": self.page_number,
"x0": self.x0,
"y0": self.y0,
"x1": self.x1,
"y1": self.y1,
"engine": self.engine,
"anchor_text": self.anchor_text,
}
def __repr__(self) -> str:
return (
f"<TrainingExample doc={self.document_id}"
f" field={self.field_name!r} value={self.correct_value!r}>"
)