-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
1966 lines (1654 loc) · 69.3 KB
/
api.py
File metadata and controls
1966 lines (1654 loc) · 69.3 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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
DTAT OCR - Ducktape and Twine OCR
REST API + Web UI for Document Processing Pipeline
Drop-in replacement for AWS Textract, Google Cloud Vision, and Azure Computer Vision
with multi-format output support.
API Endpoints:
- POST /process - Upload and process a document (sync)
- POST /process/async - Upload and queue for processing (async)
- GET /documents/{id} - Get processing result
- GET /documents/{id}/content?format= - Get extracted content in specified format
- GET /documents - List all documents
- GET /health - Health check
- GET /stats - Processing statistics
Output Formats:
- textract (default) - AWS Textract-compatible
- google - Google Cloud Vision-compatible
- azure - Azure Computer Vision-compatible
- dtat - DTAT native format
Web UI:
- GET / - Process documents
- GET /ui/documents - View all documents
- GET /ui/settings - Configuration
"""
import os
import sys
import base64
import tempfile
import platform
from pathlib import Path
from datetime import datetime
from typing import Optional, Dict, Any
import json
from fastapi import FastAPI, File, UploadFile, HTTPException, BackgroundTasks, Query, Request, Depends, Form, Body
from fastapi.responses import JSONResponse, HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from pydantic import BaseModel
import secrets
from config import config
from database import (
init_database, DocumentRecord, ProcessingStatus,
create_document_record, save_document, get_document,
get_pending_documents, get_failed_documents, update_document,
get_session,
# Profile management functions (TASK-002)
create_profile, get_profile_by_id, get_profile_by_name, list_profiles,
update_profile, delete_profile, create_profile_version,
get_profile_versions, get_profile_version, get_profile_usage_stats
)
from extraction_pipeline import ExtractionPipeline
from formatters import get_formatter
from enum import Enum
# Profile management models (TASK-002)
from profiles import (
ExtractionProfile, FieldDefinition, ProfileVersion,
ExtractionStrategy, FieldType
)
# ==================== Helper Functions (TASK-002 Code Quality) ====================
def record_to_profile(record) -> ExtractionProfile:
"""
Convert database record to ExtractionProfile model.
Eliminates code duplication across 8 endpoints.
Args:
record: ExtractionProfileRecord from database
Returns:
ExtractionProfile with ID and timestamps populated
"""
schema = record.get_schema()
schema['id'] = record.id
schema['created_at'] = record.created_at
schema['updated_at'] = record.updated_at
return ExtractionProfile(**schema)
def records_to_profiles(records: list) -> list[ExtractionProfile]:
"""
Convert list of records to ExtractionProfile models.
Args:
records: List of ExtractionProfileRecord from database
Returns:
List of ExtractionProfile models
"""
return [record_to_profile(record) for record in records]
# Output format enum
class OutputFormat(str, Enum):
"""Supported output formats for OCR results"""
TEXTRACT = "textract" # AWS Textract-compatible
GOOGLE = "google" # Google Cloud Vision-compatible
AZURE = "azure" # Azure Computer Vision-compatible
DTAT = "dtat" # DTAT native format
# Initialize
app = FastAPI(
title="DTAT OCR",
description="""
**Ducktape and Twine OCR** - Swiss Army Knife document processing
Drop-in replacement for AWS Textract, Google Cloud Vision, and Azure Computer Vision.
**Features:**
- Multi-format OCR output (Textract, Google Vision, Azure OCR, DTAT native)
- AWS Textract integration (~1-3s per page, 90%+ confidence)
- Intelligent extraction ladder with retry logic
- Quality scoring and automatic escalation
- Support for PDF, Excel, CSV, Word, images
- Multi-page PDF support via async Textract API
- Boomi integration via /ocr raw binary endpoint
**Output Formats:**
- `textract` - AWS Textract-compatible (default)
- `google` - Google Cloud Vision-compatible
- `azure` - Azure Computer Vision-compatible
- `dtat` - DTAT native format
""",
version="2.1.0",
contact={
"name": "DTAT OCR",
"url": "https://github.com/MrGriff-Boomi/DTAT-OCR"
},
license_info={
"name": "MIT",
"url": "https://opensource.org/licenses/MIT"
},
swagger_ui_parameters={
"defaultModelsExpandDepth": -1,
},
docs_url=None,
)
from fastapi.openapi.docs import get_swagger_ui_html
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui():
"""Serve Swagger UI with a version that supports OpenAPI 3.1."""
return get_swagger_ui_html(
openapi_url="/openapi.json",
title="DTAT OCR - API Docs",
swagger_ui_parameters={"defaultModelsExpandDepth": -1},
swagger_css_url="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css",
swagger_js_url="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js",
)
# Templates
templates = Jinja2Templates(directory="templates")
# Security
security = HTTPBasic()
# Get credentials from environment variables (with defaults for development)
API_USERNAME = os.getenv("DTAT_USERNAME", "admin")
API_PASSWORD = os.getenv("DTAT_PASSWORD", "changeme123")
def verify_credentials(credentials: HTTPBasicCredentials = Depends(security)):
"""Verify HTTP Basic Auth credentials"""
correct_username = secrets.compare_digest(credentials.username.encode("utf8"), API_USERNAME.encode("utf8"))
correct_password = secrets.compare_digest(credentials.password.encode("utf8"), API_PASSWORD.encode("utf8"))
if not (correct_username and correct_password):
raise HTTPException(
status_code=401,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Basic"},
)
return credentials.username
# Initialize database on startup
@app.on_event("startup")
async def startup():
init_database()
print("DTAT OCR started. Database initialized.")
# =============================================================================
# MODELS
# =============================================================================
class ProcessingResponse(BaseModel):
document_id: int
status: str
message: str
class DocumentResponse(BaseModel):
id: int
source_filename: str
file_type: Optional[str]
status: str
extraction_method: Optional[str]
confidence_score: Optional[float]
page_count: Optional[int]
char_count: Optional[int]
table_count: Optional[int]
processing_time_ms: Optional[int]
created_at: Optional[str]
completed_at: Optional[str]
error_message: Optional[str]
extracted_content_b64: Optional[str] = None
class DocumentContentResponse(BaseModel):
id: int
source_filename: str
status: str
extracted_text: Optional[str]
extracted_tables: Optional[list]
metadata: Optional[dict]
class StatsResponse(BaseModel):
total_documents: int
completed: int
failed: int
needs_review: int
pending: int
processing: int
avg_processing_time_ms: Optional[float]
by_method: dict
class HealthResponse(BaseModel):
status: str
database: str
ocr_model: str
textract_enabled: bool
offline_mode: bool
class SettingsUpdate(BaseModel):
enable_local_ocr: Optional[bool] = None
enable_textract: Optional[bool] = None
min_confidence_score: Optional[int] = None
max_retries_per_level: Optional[int] = None
force_cpu: Optional[bool] = None
# =============================================================================
# WEB UI ROUTES
# =============================================================================
@app.get("/", response_class=HTMLResponse)
async def ui_home(request: Request, username: str = Depends(verify_credentials)):
"""Main processing page."""
return templates.TemplateResponse(request, "index.html", context={
"active_page": "home"
})
@app.get("/ui/documents", response_class=HTMLResponse)
async def ui_documents(request: Request, username: str = Depends(verify_credentials)):
"""Documents list page."""
return templates.TemplateResponse(request, "documents.html", context={
"active_page": "documents"
})
@app.get("/ui/settings", response_class=HTMLResponse)
async def ui_settings(request: Request, username: str = Depends(verify_credentials)):
"""Settings page."""
def mask_value(val, show_chars=4):
if not val:
return ""
if len(val) <= show_chars:
return "*" * len(val)
return val[:show_chars] + "*" * (len(val) - show_chars)
aws_key = os.getenv("AWS_ACCESS_KEY_ID", "")
aws_secret = os.getenv("AWS_SECRET_ACCESS_KEY", "")
db_url = config.database_url
return templates.TemplateResponse(request, "settings.html", context={
"active_page": "settings",
"config": config,
"aws_access_key_masked": mask_value(aws_key, 4) if aws_key else "",
"aws_secret_key_masked": mask_value(aws_secret, 4) if aws_secret else "",
"aws_region": config.aws_region,
"auth_username": API_USERNAME,
"auth_password_masked": "*" * len(API_PASSWORD) if API_PASSWORD else "",
"database_url_masked": mask_value(db_url, 15) if db_url else "",
})
# =============================================================================
# UI API ENDPOINTS (for HTMX)
# =============================================================================
@app.get("/api/health-badge", response_class=HTMLResponse)
async def health_badge(username: str = Depends(verify_credentials)):
"""Health check badge for navbar."""
try:
from sqlalchemy import text
session = get_session()
session.execute(text("SELECT 1"))
session.close()
status = "healthy"
color = "green"
except Exception:
status = "error"
color = "red"
return f'''
<span class="inline-flex items-center rounded-full bg-{color}-100 px-2.5 py-0.5 text-xs font-medium text-{color}-800">
<span class="mr-1 h-2 w-2 rounded-full bg-{color}-500"></span>
{status}
</span>
'''
@app.get("/api/stats-cards", response_class=HTMLResponse)
async def stats_cards(username: str = Depends(verify_credentials)):
"""Stats cards for dashboard."""
from sqlalchemy import func
session = get_session()
try:
total = session.query(DocumentRecord).count()
completed = session.query(DocumentRecord).filter_by(status=ProcessingStatus.COMPLETED.value).count()
failed = session.query(DocumentRecord).filter(
DocumentRecord.status.in_([ProcessingStatus.FAILED.value, ProcessingStatus.NEEDS_REVIEW.value])
).count()
pending = session.query(DocumentRecord).filter_by(status=ProcessingStatus.PENDING.value).count()
avg_time = session.query(func.avg(DocumentRecord.processing_time_ms))\
.filter_by(status=ProcessingStatus.COMPLETED.value).scalar() or 0
return f'''
<div class="bg-white shadow rounded-lg p-4">
<p class="text-sm text-gray-500">Total Documents</p>
<p class="text-2xl font-bold text-gray-900">{total}</p>
</div>
<div class="bg-white shadow rounded-lg p-4">
<p class="text-sm text-gray-500">Completed</p>
<p class="text-2xl font-bold text-green-600">{completed}</p>
</div>
<div class="bg-white shadow rounded-lg p-4">
<p class="text-sm text-gray-500">Failed / Review</p>
<p class="text-2xl font-bold text-red-600">{failed}</p>
</div>
<div class="bg-white shadow rounded-lg p-4">
<p class="text-sm text-gray-500">Avg Processing</p>
<p class="text-2xl font-bold text-gray-900">{avg_time/1000:.1f}s</p>
</div>
'''
finally:
session.close()
@app.get("/api/recent-documents", response_class=HTMLResponse)
async def recent_documents(username: str = Depends(verify_credentials)):
"""Recent documents table for dashboard."""
from html import escape
session = get_session()
try:
records = session.query(DocumentRecord)\
.order_by(DocumentRecord.created_at.desc())\
.limit(10).all()
if not records:
return '<p class="text-gray-500 text-center py-4">No documents yet</p>'
rows = ""
for r in records:
status_color = "green" if r.status == "completed" else ("yellow" if r.status == "pending" else "red")
# Escape all user-provided data to prevent XSS
safe_filename = escape(r.source_filename[:30]) + ('...' if len(r.source_filename) > 30 else '')
safe_file_type = escape(r.file_type) if r.file_type else 'N/A'
safe_status = escape(r.status)
safe_method = escape(r.extraction_method) if r.extraction_method else 'N/A'
rows += f'''
<tr class="hover:bg-gray-50">
<td class="px-4 py-3 text-sm text-gray-900">{r.id}</td>
<td class="px-4 py-3 text-sm text-gray-900">{safe_filename}</td>
<td class="px-4 py-3 text-sm text-gray-500">{safe_file_type}</td>
<td class="px-4 py-3">
<span class="inline-flex items-center rounded-full bg-{status_color}-100 px-2 py-0.5 text-xs font-medium text-{status_color}-800">
{safe_status}
</span>
</td>
<td class="px-4 py-3 text-sm text-gray-500">{safe_method}</td>
<td class="px-4 py-3 text-sm text-gray-500">{r.confidence_score:.0f}%</td>
</tr>
'''
return f'''
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">ID</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Filename</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Type</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Method</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Confidence</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
{rows}
</tbody>
</table>
'''
finally:
session.close()
@app.get("/api/documents-table", response_class=HTMLResponse)
async def documents_table(status: Optional[str] = None, username: str = Depends(verify_credentials)):
"""Full documents table."""
from html import escape
session = get_session()
try:
query = session.query(DocumentRecord)
if status:
query = query.filter_by(status=status)
records = query.order_by(DocumentRecord.created_at.desc()).limit(100).all()
if not records:
return '<p class="text-gray-500 text-center py-8">No documents found</p>'
rows = ""
for r in records:
status_color = "green" if r.status == "completed" else ("yellow" if r.status in ["pending", "processing"] else "red")
can_retry = r.status in ["failed", "needs_review"]
# Escape all user-provided data to prevent XSS
safe_filename = escape(r.source_filename[:40]) + ('...' if len(r.source_filename) > 40 else '')
safe_file_type = escape(r.file_type) if r.file_type else 'N/A'
safe_status = escape(r.status)
safe_method = escape(r.extraction_method) if r.extraction_method else 'N/A'
rows += f'''
<tr class="hover:bg-gray-50">
<td class="px-4 py-3 text-sm text-gray-900">{r.id}</td>
<td class="px-4 py-3 text-sm text-gray-900">{safe_filename}</td>
<td class="px-4 py-3 text-sm text-gray-500">{safe_file_type}</td>
<td class="px-4 py-3">
<span class="inline-flex items-center rounded-full bg-{status_color}-100 px-2 py-0.5 text-xs font-medium text-{status_color}-800">
{safe_status}
</span>
</td>
<td class="px-4 py-3 text-sm text-gray-500">{safe_method}</td>
<td class="px-4 py-3 text-sm text-gray-500">{f'{r.confidence_score:.0f}%' if r.confidence_score else 'N/A'}</td>
<td class="px-4 py-3 text-sm text-gray-500">{r.processing_time_ms // 1000 if r.processing_time_ms else 0}s</td>
<td class="px-4 py-3 text-sm text-gray-500">{r.created_at.strftime('%Y-%m-%d %H:%M') if r.created_at else 'N/A'}</td>
<td class="px-4 py-3 text-sm">
<button onclick="viewDocument({r.id})" class="text-blue-600 hover:text-blue-800 mr-2">View</button>
{'<button onclick="retryDocument(' + str(r.id) + ')" class="text-yellow-600 hover:text-yellow-800">Retry</button>' if can_retry else ''}
</td>
</tr>
'''
return f'''
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">ID</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Filename</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Type</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Method</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Confidence</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Time</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Created</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Actions</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
{rows}
</tbody>
</table>
'''
finally:
session.close()
@app.get("/api/system-info", response_class=HTMLResponse)
async def system_info(username: str = Depends(verify_credentials)):
"""System information for settings page."""
from html import escape
import torch
gpu_available = torch.cuda.is_available()
mps_available = torch.backends.mps.is_available()
gpu_name = torch.cuda.get_device_name(0) if gpu_available else "N/A"
if config.force_cpu:
active_device = "CPU (GPU disabled by config)"
device_badge = "bg-yellow-100 text-yellow-800"
elif gpu_available:
active_device = f"CUDA — {gpu_name}"
device_badge = "bg-green-100 text-green-800"
elif mps_available:
active_device = "Apple MPS"
device_badge = "bg-green-100 text-green-800"
else:
active_device = "CPU (no GPU detected)"
device_badge = "bg-gray-100 text-gray-800"
safe_gpu_name = escape(gpu_name)
safe_db_url = escape(config.database_url[:50])
return f'''
<div class="grid grid-cols-2 gap-4 text-sm">
<div><span class="text-gray-500">Platform:</span> <span class="font-medium">{platform.system()} {platform.release()}</span></div>
<div><span class="text-gray-500">Python:</span> <span class="font-medium">{platform.python_version()}</span></div>
<div>
<span class="text-gray-500">Compute Device:</span>
<span class="inline-flex items-center rounded-full {device_badge} px-2 py-0.5 text-xs font-medium ml-1">{escape(active_device)}</span>
</div>
<div><span class="text-gray-500">GPU Available:</span> <span class="font-medium">{"Yes — " + safe_gpu_name if gpu_available else "No"}</span></div>
<div><span class="text-gray-500">Force CPU:</span> <span class="font-medium">{"Yes" if config.force_cpu else "No (auto-detect)"}</span></div>
<div><span class="text-gray-500">Max File Size:</span> <span class="font-medium">{config.max_file_size_mb} MB</span></div>
</div>
'''
@app.post("/api/settings")
async def update_settings(settings: SettingsUpdate, username: str = Depends(verify_credentials)):
"""Update configuration settings."""
if settings.enable_local_ocr is not None:
config.enable_local_ocr = settings.enable_local_ocr
if settings.enable_textract is not None:
config.enable_textract = settings.enable_textract
if settings.min_confidence_score is not None:
config.min_confidence_score = settings.min_confidence_score
if settings.max_retries_per_level is not None:
config.max_retries_per_level = settings.max_retries_per_level
if settings.force_cpu is not None:
config.force_cpu = settings.force_cpu
# Reset model so it reloads on next request with new device setting
from extraction_pipeline import LocalOCRExtractor
LocalOCRExtractor._model = None
LocalOCRExtractor._processor = None
LocalOCRExtractor._device = None
return {"status": "ok", "message": "Settings updated"}
# =============================================================================
# API ENDPOINTS
# =============================================================================
@app.get("/health", response_model=HealthResponse)
async def health_check():
"""Health check endpoint."""
try:
from sqlalchemy import text
session = get_session()
session.execute(text("SELECT 1"))
session.close()
db_status = "connected"
except Exception as e:
db_status = f"error: {str(e)}"
return HealthResponse(
status="healthy" if db_status == "connected" else "degraded",
database=db_status,
ocr_model=config.ocr_model_name,
textract_enabled=config.enable_textract,
offline_mode=config.ocr_offline_mode
)
@app.post("/process", response_model=DocumentResponse)
async def process_document_sync(
file: UploadFile = File(...),
include_content: bool = Query(False, description="Include extracted content in response"),
username: str = Depends(verify_credentials)
):
"""
Upload and process a document synchronously.
Returns when processing is complete.
"""
contents = await file.read()
if len(contents) > config.max_file_size_mb * 1024 * 1024:
raise HTTPException(
status_code=413,
detail=f"File too large. Max size: {config.max_file_size_mb}MB"
)
filename = file.filename or "unknown"
file_type = Path(filename).suffix.lower().lstrip('.')
if not file_type:
raise HTTPException(status_code=400, detail="Could not determine file type")
record = create_document_record(
filename=filename,
file_bytes=contents,
file_type=file_type,
)
doc_id = save_document(record)
record.id = doc_id
with tempfile.NamedTemporaryFile(delete=False, suffix=f".{file_type}") as tmp:
tmp.write(contents)
tmp_path = Path(tmp.name)
try:
pipeline = ExtractionPipeline()
result = pipeline.process(record, tmp_path)
finally:
tmp_path.unlink(missing_ok=True)
response = DocumentResponse(
id=result.id,
source_filename=result.source_filename,
file_type=result.file_type,
status=result.status,
extraction_method=result.extraction_method,
confidence_score=result.confidence_score,
page_count=result.page_count,
char_count=result.char_count,
table_count=result.table_count,
processing_time_ms=result.processing_time_ms,
created_at=result.created_at.isoformat() if result.created_at else None,
completed_at=result.completed_at.isoformat() if result.completed_at else None,
error_message=result.error_message,
)
if include_content:
response.extracted_content_b64 = result.extracted_content_b64
return response
@app.post("/ocr")
async def ocr_raw_binary(
request: Request,
format: str = Query("text", description="Output format: text, json, textract, google, azure"),
username: str = Depends(verify_credentials)
):
"""
Simple OCR endpoint that accepts raw image binary in the request body.
Returns extracted text directly. Designed for Boomi HTTP Client passthrough.
Usage: POST raw image bytes with Content-Type: image/png (or image/jpeg)
"""
from fastapi.responses import PlainTextResponse, JSONResponse
from validators import validate_file
content_type = request.headers.get("content-type", "image/png")
contents = await request.body()
if not contents:
raise HTTPException(status_code=400, detail="Empty request body")
if len(contents) > config.max_file_size_mb * 1024 * 1024:
raise HTTPException(
status_code=413,
detail=f"File too large. Max size: {config.max_file_size_mb}MB"
)
# Determine file type early for validation
ext_map = {
"image/png": "png", "image/jpeg": "jpg", "image/jpg": "jpg",
"image/tiff": "tiff", "image/bmp": "bmp", "image/gif": "gif",
"application/pdf": "pdf", "application/octet-stream": "png",
}
file_type = ext_map.get(content_type.split(";")[0].strip().lower(), "png")
# Validate file before processing
validation_error = validate_file(contents, file_type)
if validation_error:
raise HTTPException(status_code=400, detail=validation_error.message)
filename = f"boomi_upload.{file_type}"
# Dedup check — return cached result if same file was already processed
if config.enable_dedup:
from database import compute_content_hash, find_duplicate
content_hash = compute_content_hash(contents)
existing = find_duplicate(content_hash)
if existing:
doc = existing
def _extract_text(doc_record):
content = doc_record.get_extracted_content()
if isinstance(content, dict) and "blocks" in content:
return "\n".join(b.get("text", "") for b in content["blocks"] if b.get("text"))
if isinstance(content, dict):
return content.get("text", content.get("extracted_text", ""))
return str(content) if content else ""
if format == "text":
return PlainTextResponse(content=_extract_text(doc))
elif format == "json":
return JSONResponse(content={
"id": doc.id, "status": "completed", "text": _extract_text(doc),
"confidence": doc.confidence_score, "processing_time_ms": 0,
"cached": True, "duplicate_of": doc.id,
})
else:
normalized_result = doc.get_normalized_content()
if normalized_result:
formatter = get_formatter(format)
return JSONResponse(content=formatter.format(normalized_result))
record = create_document_record(
filename=filename,
file_bytes=contents,
file_type=file_type,
)
doc_id = save_document(record)
record.id = doc_id
with tempfile.NamedTemporaryFile(delete=False, suffix=f".{file_type}") as tmp:
tmp.write(contents)
tmp_path = Path(tmp.name)
try:
pipeline = ExtractionPipeline()
result = pipeline.process(record, tmp_path)
finally:
tmp_path.unlink(missing_ok=True)
# Get the text from the processed record
doc = get_document(result.id)
if not doc:
raise HTTPException(status_code=500, detail="Processing failed")
if result.status != "completed":
raise HTTPException(status_code=422, detail=f"OCR failed: {result.error_message}")
# Extract text from normalized block storage
def _extract_text_from_doc(doc_record):
content = doc_record.get_extracted_content()
if isinstance(content, dict):
# Normalized format: extract text from blocks
if "blocks" in content:
lines = [b.get("text", "") for b in content["blocks"] if b.get("text")]
return "\n".join(lines)
return content.get("text", content.get("extracted_text", str(content)))
return str(content) if content else ""
# Return based on requested format
if format == "text":
return PlainTextResponse(content=_extract_text_from_doc(doc))
elif format == "json":
return JSONResponse(content={
"id": result.id,
"status": result.status,
"text": _extract_text_from_doc(doc),
"confidence": result.confidence_score,
"processing_time_ms": result.processing_time_ms,
})
else:
# Use the formatters for textract/google/azure
normalized_result = doc.get_normalized_content()
if normalized_result:
formatter = get_formatter(format)
return JSONResponse(content=formatter.format(normalized_result))
raise HTTPException(status_code=500, detail="No normalized content available")
# =============================================================================
# ASYNC OCR JOB SYSTEM (PostgreSQL-backed, works across workers)
# =============================================================================
import uuid as _uuid
from sqlalchemy import text as sa_text
def _create_job(job_id: str):
"""Insert a new job into PostgreSQL."""
session = get_session()
try:
session.execute(sa_text(
"INSERT INTO ocr_jobs (job_id, status) VALUES (:jid, 'processing')"
), {"jid": job_id})
session.commit()
finally:
session.close()
def _complete_job(job_id: str, document_id: int, text: str, confidence: float, processing_time_ms: int):
"""Mark a job as completed in PostgreSQL."""
session = get_session()
try:
session.execute(sa_text(
"UPDATE ocr_jobs SET status='completed', document_id=:did, extracted_text=:txt, "
"confidence=:conf, processing_time_ms=:ptms, completed_at=NOW() WHERE job_id=:jid"
), {"jid": job_id, "did": document_id, "txt": text, "conf": confidence, "ptms": processing_time_ms})
session.commit()
finally:
session.close()
def _fail_job(job_id: str, error: str):
"""Mark a job as failed in PostgreSQL."""
session = get_session()
try:
session.execute(sa_text(
"UPDATE ocr_jobs SET status='failed', error_message=:err, completed_at=NOW() WHERE job_id=:jid"
), {"jid": job_id, "err": error})
session.commit()
finally:
session.close()
def _get_job(job_id: str):
"""Get job from PostgreSQL."""
session = get_session()
try:
row = session.execute(sa_text("SELECT * FROM ocr_jobs WHERE job_id=:jid"), {"jid": job_id}).mappings().first()
if not row:
return None
return dict(row)
finally:
session.close()
def _process_ocr_job(job_id: str, contents: bytes, file_type: str, filename: str):
"""Process an OCR job synchronously (called from background task)."""
try:
record = create_document_record(filename=filename, file_bytes=contents, file_type=file_type)
doc_id = save_document(record)
record.id = doc_id
with tempfile.NamedTemporaryFile(delete=False, suffix=f".{file_type}") as tmp:
tmp.write(contents)
tmp_path = Path(tmp.name)
try:
pipeline = ExtractionPipeline()
result = pipeline.process(record, tmp_path)
finally:
tmp_path.unlink(missing_ok=True)
doc = get_document(result.id)
text = ""
if doc:
content = doc.get_extracted_content()
if isinstance(content, dict) and "blocks" in content:
text = "\n".join(b.get("text", "") for b in content["blocks"] if b.get("text"))
elif isinstance(content, dict):
text = content.get("text", content.get("extracted_text", ""))
_complete_job(job_id, result.id, text, result.confidence_score or 0, result.processing_time_ms or 0)
except Exception as e:
_fail_job(job_id, str(e))
@app.post("/ocr/async")
async def ocr_async(
request: Request,
background_tasks: BackgroundTasks,
username: str = Depends(verify_credentials)
):
"""
Fire-and-forget OCR. Returns job ID immediately, poll /ocr/jobs/{job_id} for result.
Accepts raw image binary in request body. Works across all workers (PostgreSQL-backed).
"""
from fastapi.responses import JSONResponse
content_type = request.headers.get("content-type", "image/png")
contents = await request.body()
if not contents:
raise HTTPException(status_code=400, detail="Empty request body")
if len(contents) > config.max_file_size_mb * 1024 * 1024:
raise HTTPException(status_code=413, detail=f"File too large. Max: {config.max_file_size_mb}MB")
ext_map = {
"image/png": "png", "image/jpeg": "jpg", "image/jpg": "jpg",
"image/tiff": "tiff", "image/bmp": "bmp", "application/pdf": "pdf",
"application/octet-stream": "png",
}
file_type = ext_map.get(content_type.split(";")[0].strip().lower(), "png")
filename = f"async_upload.{file_type}"
job_id = str(_uuid.uuid4())
_create_job(job_id)
background_tasks.add_task(_process_ocr_job, job_id, contents, file_type, filename)
return JSONResponse(content={"job_id": job_id, "status": "processing"})
@app.get("/ocr/jobs/{job_id}")
async def ocr_job_status(
job_id: str,
username: str = Depends(verify_credentials)
):
"""Poll for async OCR job result. Works across all workers (PostgreSQL-backed)."""
from fastapi.responses import JSONResponse
job = _get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
result = {
"job_id": job["job_id"],
"status": job["status"],
"created_at": job["created_at"].isoformat() if job["created_at"] else None,
}
if job["status"] == "completed":
result.update({
"document_id": job["document_id"],
"text": job["extracted_text"],
"confidence": float(job["confidence"]) if job["confidence"] else None,
"processing_time_ms": job["processing_time_ms"],
"completed_at": job["completed_at"].isoformat() if job["completed_at"] else None,
})
elif job["status"] == "failed":
result["error"] = job["error_message"]
return JSONResponse(content=result)
@app.get("/queue/status")
async def queue_status(username: str = Depends(verify_credentials)):
"""Current job queue status from PostgreSQL."""
from fastapi.responses import JSONResponse
session = get_session()
try:
row = session.execute(sa_text(
"SELECT "
"COUNT(*) as total, "
"COUNT(*) FILTER (WHERE status='processing') as processing, "
"COUNT(*) FILTER (WHERE status='completed') as completed, "
"COUNT(*) FILTER (WHERE status='failed') as failed, "
"AVG(processing_time_ms) FILTER (WHERE status='completed') as avg_time_ms, "
"PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY processing_time_ms) FILTER (WHERE status='completed') as p95_time_ms "
"FROM ocr_jobs"
)).mappings().first()
return JSONResponse(content={
"total_jobs": row["total"],
"processing": row["processing"],
"completed": row["completed"],
"failed": row["failed"],
"avg_processing_time_ms": round(float(row["avg_time_ms"])) if row["avg_time_ms"] else None,
"p95_processing_time_ms": round(float(row["p95_time_ms"])) if row["p95_time_ms"] else None,
})
finally:
session.close()
@app.post("/process/async", response_model=ProcessingResponse)
async def process_document_async(
file: UploadFile = File(...),
username: str = Depends(verify_credentials)
):
"""
Upload a document for async processing.
Document is saved to database with status=pending.
Use 'python worker.py worker' to process pending documents.
Poll GET /documents/{id} to check status.
"""
contents = await file.read()
if len(contents) > config.max_file_size_mb * 1024 * 1024:
raise HTTPException(status_code=413, detail=f"File too large. Max: {config.max_file_size_mb}MB")
filename = file.filename or "unknown"
file_type = Path(filename).suffix.lower().lstrip('.')
if not file_type:
raise HTTPException(status_code=400, detail="Could not determine file type")
# Save to database with status=pending (persistent queue)
# Worker process will pick this up and process it
record = create_document_record(filename=filename, file_bytes=contents, file_type=file_type)
doc_id = save_document(record)
return ProcessingResponse(
document_id=doc_id,
status="pending",
message="Document saved to queue. Run 'python worker.py worker' to process. Poll GET /documents/{id} for results."
)
def process_document_background(doc_id: int, file_bytes: bytes, file_type: str):
"""Background task to process a document."""