File size: 9,539 Bytes
1a7ee60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

FastAPI Server for IDP System

Provides REST API endpoints for Hugging Face Spaces deployment

CORS-enabled for Next.js frontend integration

"""

# Fix for TensorFlow/PaddlePaddle mutex warnings on macOS
import os
os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'
os.environ['OMP_NUM_THREADS'] = '1'
os.environ['OPENBLAS_NUM_THREADS'] = '1'
os.environ['MKL_NUM_THREADS'] = '1'
os.environ['VECLIB_MAXIMUM_THREADS'] = '1'
os.environ['NUMEXPR_NUM_THREADS'] = '1'
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

import warnings
warnings.filterwarnings('ignore')

from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import uvicorn
import logging
from typing import Optional
import tempfile
from pathlib import Path
import traceback

from inference_pipeline import IDPPipeline

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# Initialize FastAPI app
app = FastAPI(
    title="IDP API",
    description="Intelligent Document Processing API for invoices, receipts, and forms",
    version="1.0.0"
)

# Configure CORS for Next.js frontend
app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "*",  # Allow all origins (for development)
        # For production, specify your Vercel domain:
        # "https://your-app.vercel.app",
        # "https://*.vercel.app",
    ],
    allow_credentials=True,
    allow_methods=["*"],  # Allow all HTTP methods
    allow_headers=["*"],  # Allow all headers
)

# Global pipeline instance (loaded once at startup)
pipeline: Optional[IDPPipeline] = None


@app.on_event("startup")
async def startup_event():
    """Initialize pipeline on server startup"""
    global pipeline
    
    logger.info("Starting IDP API server...")
    logger.info("Initializing inference pipeline...")
    
    try:
        # Initialize with CPU by default (change use_gpu=True if GPU available)
        pipeline = IDPPipeline(
            classifier_model_path="models/classifier/best_classifier.pt",
            ner_model_path="models/ner/best_ner.pt",
            use_gpu=False,  # Set to True if deploying on GPU
            ocr_confidence_threshold=0.5
        )
        logger.info("Pipeline initialized successfully!")
    except Exception as e:
        logger.error(f"Failed to initialize pipeline: {str(e)}")
        logger.error(traceback.format_exc())
        # Continue startup anyway to allow health check


@app.on_event("shutdown")
async def shutdown_event():
    """Cleanup on server shutdown"""
    logger.info("Shutting down IDP API server...")


@app.get("/")
async def root():
    """Root endpoint"""
    return {
        "message": "IDP API is running",
        "version": "1.0.0",
        "endpoints": {
            "health_check": "GET /health",
            "process_document": "POST /process",
        }
    }


@app.get("/health")
async def health_check():
    """

    Health check endpoint

    Returns status and model loading state

    

    Next.js usage:

    ```javascript

    const response = await fetch('https://your-space.hf.space/health');

    const data = await response.json();

    console.log(data.status);  // "ok"

    ```

    """
    models_loaded = pipeline is not None
    
    return {
        "status": "ok",
        "models_loaded": models_loaded,
        "version": "1.0.0"
    }


@app.post("/process")
async def process_document(

    file: UploadFile = File(...),

    adaptive_threshold: bool = False,

    page_number: Optional[int] = None

):
    """

    Process a document (PDF or image) and extract structured data

    

    Args:

        file: Uploaded file (PDF, PNG, JPEG, JPG)

        adaptive_threshold: Apply adaptive thresholding for poor quality scans

        page_number: For PDFs, process specific page (None = all pages)

    

    Returns:

        JSON response with extracted document fields

    

    Next.js usage:

    ```javascript

    const formData = new FormData();

    formData.append('file', fileBlob);  // File from input element

    

    const response = await fetch('https://your-space.hf.space/process', {

      method: 'POST',

      body: formData,

    });

    

    const result = await response.json();

    console.log(result.pages[0].document_type);  // "INVOICE", "RECEIPT", etc.

    console.log(result.pages[0].fields);  // Extracted fields

    ```

    

    Response format:

    ```json

    {

      "file_type": "image" | "pdf",

      "total_pages": 1,

      "processed_pages": 1,

      "pages": [

        {

          "document_type": "INVOICE",

          "classification_confidence": 0.96,

          "fields": {

            "invoice_number": {

              "value": "INV-12345",

              "confidence": 0.92,

              "bbox": [x1, y1, x2, y2],

              "source": "ner"

            },

            "date": {

              "value": "2025-11-28",

              "confidence": 0.88,

              ...

            },

            ...

          },

          "processing_time": {

            "total": 1.23,

            ...

          }

        }

      ]

    }

    ```

    """
    # Check if pipeline is loaded
    if pipeline is None:
        logger.error("Pipeline not initialized")
        raise HTTPException(
            status_code=503,
            detail="Service unavailable: Pipeline not initialized"
        )
    
    # Validate file type
    allowed_extensions = {'.pdf', '.png', '.jpg', '.jpeg', '.bmp', '.tiff'}
    file_ext = Path(file.filename).suffix.lower()
    
    if file_ext not in allowed_extensions:
        raise HTTPException(
            status_code=400,
            detail=f"Unsupported file type: {file_ext}. Allowed: {allowed_extensions}"
        )
    
    # Check file size (limit to 10MB)
    max_size = 10 * 1024 * 1024  # 10 MB
    file_size = 0
    
    # Save uploaded file to temporary location
    try:
        with tempfile.NamedTemporaryFile(delete=False, suffix=file_ext) as tmp:
            # Read and write in chunks to check size
            while True:
                chunk = await file.read(1024 * 1024)  # Read 1MB at a time
                if not chunk:
                    break
                file_size += len(chunk)
                
                if file_size > max_size:
                    os.remove(tmp.name)
                    raise HTTPException(
                        status_code=413,
                        detail=f"File too large: {file_size / (1024*1024):.2f}MB. Max: 10MB"
                    )
                
                tmp.write(chunk)
            
            tmp_path = tmp.name
        
        logger.info(f"Processing file: {file.filename} ({file_size / 1024:.2f}KB)")
        
        # Process document
        result = pipeline.process_document(
            file_path=tmp_path,
            adaptive_threshold=adaptive_threshold,
            page_number=page_number
        )
        
        # Add filename to response
        result['filename'] = file.filename
        result['file_size_kb'] = file_size / 1024
        
        logger.info(f"Successfully processed {file.filename}")
        
        return JSONResponse(content=result)
        
    except HTTPException:
        # Re-raise HTTP exceptions
        raise
    except Exception as e:
        logger.error(f"Error processing document: {str(e)}")
        logger.error(traceback.format_exc())
        raise HTTPException(
            status_code=500,
            detail=f"Error processing document: {str(e)}"
        )
    finally:
        # Clean up temporary file
        if 'tmp_path' in locals() and os.path.exists(tmp_path):
            try:
                os.remove(tmp_path)
            except:
                pass


@app.post("/process/batch")
async def process_batch(

    files: list[UploadFile] = File(...)

):
    """

    Process multiple documents in batch

    

    Args:

        files: List of uploaded files

    

    Returns:

        JSON response with results for each file

    

    Note: For large batches, consider using the single /process endpoint

    in parallel from the client side for better control

    """
    if len(files) > 5:
        raise HTTPException(
            status_code=400,
            detail="Maximum 5 files per batch request"
        )
    
    results = []
    
    for file in files:
        try:
            result = await process_document(file)
            results.append({
                "filename": file.filename,
                "status": "success",
                "data": result
            })
        except Exception as e:
            logger.error(f"Error processing {file.filename}: {str(e)}")
            results.append({
                "filename": file.filename,
                "status": "error",
                "error": str(e)
            })
    
    return JSONResponse(content={"results": results})


if __name__ == "__main__":
    # Run server
    # For development:
    uvicorn.run(
        app,
        host="0.0.0.0",
        port=7860,  # Default Hugging Face Spaces port
        log_level="info"
    )
    
    # For production on Hugging Face Spaces, Dockerfile will handle this