PrathameshRaut commited on
Commit
86131c1
·
verified ·
1 Parent(s): fddfb40

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +28 -30
main.py CHANGED
@@ -1,22 +1,22 @@
1
  import os
2
  import json
 
3
  import numpy as np
4
  import tensorflow as tf
5
  from tensorflow.keras.preprocessing import image
6
  from pdf2image import convert_from_path
7
- from fastapi import FastAPI, UploadFile, File, HTTPException, Query
8
  from fastapi.responses import JSONResponse
9
- import uvicorn
10
 
11
  # -----------------------------
12
  # CONFIG
13
  # -----------------------------
14
  IMG_SIZE = (224, 224)
15
- MODEL_PATH = "final_model.keras" # Updated to relative path for Docker
16
  class_names = ['Other', 'Aadhar Card', 'Pan Card', 'Voter Id']
17
 
18
- # Mapping for expected_type input (normalize to match class_names)
19
- EXPECTED_TYPE_MAPPING = {
20
  "aadhar_card": "Aadhar Card",
21
  "pan_card": "Pan Card",
22
  "voter_id": "Voter Id"
@@ -111,42 +111,40 @@ def predict_file(path):
111
  # -----------------------------
112
  # FastAPI App
113
  # -----------------------------
114
- app = FastAPI(title="ID Document Validator", description="Predict document type and optionally validate against expected type.")
115
 
116
  @app.post("/predict")
117
  async def predict(
118
- file: UploadFile = File(...),
119
- expected_type: str = Query(None, description="Optional: Expected document type ('aadhar_card', 'pan_card', 'voter_id'). If provided, adds 'Authentication' to response.")
120
  ):
 
 
 
 
121
  # Save uploaded file temporarily
122
- temp_path = f"/tmp/{file.filename}"
123
- with open(temp_path, "wb") as f:
124
- f.write(await file.read())
125
 
126
  try:
127
- # Get prediction result
128
  result = predict_file(temp_path)
129
 
130
- # If there's an error in result, return it as-is
131
- if "error" in result:
132
- return JSONResponse(status_code=400, content=result)
133
-
134
- # If expected_type is provided and valid, add Authentication
135
- if expected_type and expected_type in EXPECTED_TYPE_MAPPING:
136
- expected_label = EXPECTED_TYPE_MAPPING[expected_type]
137
- predicted_label = result["type"]
138
- authentication = "Valid" if predicted_label == expected_label else "Not Valid"
139
- result["Authentication"] = authentication
140
- elif expected_type and expected_type not in EXPECTED_TYPE_MAPPING:
141
- # Invalid expected_type, but still return prediction without Authentication
142
- pass # Just proceed without adding Authentication
143
 
144
- return result
145
  finally:
146
  # Clean up temp file
147
  if os.path.exists(temp_path):
148
- os.remove(temp_path)
149
 
150
- # For local testing
151
- if __name__ == "__main__":
152
- uvicorn.run(app, host="0.0.0.0", port=8000)
 
 
1
  import os
2
  import json
3
+ import tempfile
4
  import numpy as np
5
  import tensorflow as tf
6
  from tensorflow.keras.preprocessing import image
7
  from pdf2image import convert_from_path
8
+ from fastapi import FastAPI, UploadFile, Form, HTTPException
9
  from fastapi.responses import JSONResponse
 
10
 
11
  # -----------------------------
12
  # CONFIG
13
  # -----------------------------
14
  IMG_SIZE = (224, 224)
15
+ MODEL_PATH = "./final_model.keras" # Relative path for deployment
16
  class_names = ['Other', 'Aadhar Card', 'Pan Card', 'Voter Id']
17
 
18
+ # Mapping for expected_type input to class names
19
+ type_mapping = {
20
  "aadhar_card": "Aadhar Card",
21
  "pan_card": "Pan Card",
22
  "voter_id": "Voter Id"
 
111
  # -----------------------------
112
  # FastAPI App
113
  # -----------------------------
114
+ app = FastAPI(title="ID Document Validator", description="Predict document type and authenticate based on expected type.")
115
 
116
  @app.post("/predict")
117
  async def predict(
118
+ file: UploadFile,
119
+ expected_type: str = Form(None) # Optional form field
120
  ):
121
+ # Validate file
122
+ if not file.filename:
123
+ raise HTTPException(status_code=400, detail="No file provided")
124
+
125
  # Save uploaded file temporarily
126
+ with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(file.filename)[1]) as temp_file:
127
+ temp_path = temp_file.name
128
+ temp_file.write(await file.read())
129
 
130
  try:
131
+ # Predict
132
  result = predict_file(temp_path)
133
 
134
+ # Add authentication if expected_type is provided and no error
135
+ if expected_type and expected_type in type_mapping and "type" in result:
136
+ if result["type"] == type_mapping[expected_type]:
137
+ result["Authentication"] = "Valid"
138
+ else:
139
+ result["Authentication"] = "Not valid"
 
 
 
 
 
 
 
140
 
141
+ return JSONResponse(content=result)
142
  finally:
143
  # Clean up temp file
144
  if os.path.exists(temp_path):
145
+ os.unlink(temp_path)
146
 
147
+ # Health check endpoint
148
+ @app.get("/")
149
+ def read_root():
150
+ return {"message": "ID Validator API is running"}