Spaces:
Sleeping
Sleeping
Update app/main.py
Browse files- app/main.py +147 -150
app/main.py
CHANGED
|
@@ -1,150 +1,147 @@
|
|
| 1 |
-
from fastapi import FastAPI, UploadFile, File
|
| 2 |
-
from app.ocr import extract_text
|
| 3 |
-
from app.face import get_face_embedding, cosine
|
| 4 |
-
from app.rules import extract_name, name_similarity, calculate_pairwise_scores, decide, fix_name_format
|
| 5 |
-
from app.utils import read_image
|
| 6 |
-
from app.models import VerificationResponse
|
| 7 |
-
|
| 8 |
-
app = FastAPI(title="Document Verifier - Aadhar, College ID, Concession")
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
def is_valid_name(name):
|
| 12 |
-
"""Check if extracted name is valid (not garbage OCR)."""
|
| 13 |
-
if not name:
|
| 14 |
-
return False
|
| 15 |
-
|
| 16 |
-
# Must have at least 2 parts (first + last)
|
| 17 |
-
parts = name.split()
|
| 18 |
-
if len(parts) < 2:
|
| 19 |
-
return False
|
| 20 |
-
|
| 21 |
-
# Each part should be at least 2 characters
|
| 22 |
-
if any(len(p) < 2 for p in parts):
|
| 23 |
-
return False
|
| 24 |
-
|
| 25 |
-
# Should look like a name (mostly letters)
|
| 26 |
-
alpha_count = sum(c.isalpha() for c in name)
|
| 27 |
-
if alpha_count < len(name) * 0.8:
|
| 28 |
-
return False
|
| 29 |
-
|
| 30 |
-
return True
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
@app.post("/verify", response_model=VerificationResponse)
|
| 34 |
-
async def verify(
|
| 35 |
-
aadhar: UploadFile = File(..., description="Aadhar Card Image"),
|
| 36 |
-
college_id: UploadFile = File(..., description="College ID Card Image"),
|
| 37 |
-
concession: UploadFile = File(..., description="Concession Form Image (can be handwritten)")
|
| 38 |
-
):
|
| 39 |
-
"""
|
| 40 |
-
Verify documents by comparing:
|
| 41 |
-
- Aadhar Card
|
| 42 |
-
- College ID
|
| 43 |
-
- Concession Form (handwritten or printed)
|
| 44 |
-
"""
|
| 45 |
-
docs = [aadhar, college_id, concession]
|
| 46 |
-
doc_names = ["Aadhar", "College ID", "Concession"]
|
| 47 |
-
|
| 48 |
-
imgs = []
|
| 49 |
-
names = []
|
| 50 |
-
embeddings = []
|
| 51 |
-
all_ocr_lines = {}
|
| 52 |
-
|
| 53 |
-
for i, doc in enumerate(docs):
|
| 54 |
-
img = read_image(await doc.read())
|
| 55 |
-
imgs.append(img)
|
| 56 |
-
|
| 57 |
-
is_handwritten = (i == 2)
|
| 58 |
-
extracted_lines = extract_text(img, is_handwritten=is_handwritten)
|
| 59 |
-
all_ocr_lines[doc_names[i]] = extracted_lines
|
| 60 |
-
|
| 61 |
-
name = extract_name(extracted_lines)
|
| 62 |
-
|
| 63 |
-
# Fix format issues
|
| 64 |
-
if name:
|
| 65 |
-
name = fix_name_format(name)
|
| 66 |
-
|
| 67 |
-
# Validate name quality
|
| 68 |
-
if not is_valid_name(name):
|
| 69 |
-
name = None
|
| 70 |
-
|
| 71 |
-
names.append(name)
|
| 72 |
-
|
| 73 |
-
embedding = get_face_embedding(img)
|
| 74 |
-
embeddings.append(embedding)
|
| 75 |
-
|
| 76 |
-
# Calculate pairwise scores
|
| 77 |
-
face_scores, name_scores = calculate_pairwise_scores(embeddings, names)
|
| 78 |
-
|
| 79 |
-
# Build pairwise details
|
| 80 |
-
pair_labels = ["Aadhar-CollegeID", "Aadhar-Concession", "CollegeID-Concession"]
|
| 81 |
-
pair_indices = [(0, 1), (0, 2), (1, 2)]
|
| 82 |
-
pairwise_details = {}
|
| 83 |
-
|
| 84 |
-
for k, (i, j) in enumerate(pair_indices):
|
| 85 |
-
label = pair_labels[k]
|
| 86 |
-
|
| 87 |
-
# Face score
|
| 88 |
-
f_score = None
|
| 89 |
-
if embeddings[i] is not None and embeddings[j] is not None:
|
| 90 |
-
f_score = cosine(embeddings[i], embeddings[j])
|
| 91 |
-
|
| 92 |
-
# Name score
|
| 93 |
-
n_score = None
|
| 94 |
-
if names[i] and names[j]:
|
| 95 |
-
n_score = name_similarity(names[i], names[j])
|
| 96 |
-
|
| 97 |
-
pairwise_details[label] = {
|
| 98 |
-
"face_score": round(f_score, 4) if f_score is not None else None,
|
| 99 |
-
"name_score": round(n_score, 2) if n_score is not None else None
|
| 100 |
-
}
|
| 101 |
-
|
| 102 |
-
# If concession name failed, focus on Aadhar-CollegeID comparison
|
| 103 |
-
valid_name_scores = []
|
| 104 |
-
valid_face_scores = []
|
| 105 |
-
|
| 106 |
-
# Aadhar-CollegeID (most reliable)
|
| 107 |
-
if names[0] and names[1]:
|
| 108 |
-
valid_name_scores.append(name_similarity(names[0], names[1]))
|
| 109 |
-
if embeddings[0] is not None and embeddings[1] is not None:
|
| 110 |
-
valid_face_scores.append(cosine(embeddings[0], embeddings[1]))
|
| 111 |
-
|
| 112 |
-
# Aadhar-Concession
|
| 113 |
-
if names[0] and names[2]:
|
| 114 |
-
valid_name_scores.append(name_similarity(names[0], names[2]))
|
| 115 |
-
if embeddings[0] is not None and embeddings[2] is not None:
|
| 116 |
-
valid_face_scores.append(cosine(embeddings[0], embeddings[2]))
|
| 117 |
-
|
| 118 |
-
# CollegeID-Concession
|
| 119 |
-
if names[1] and names[2]:
|
| 120 |
-
valid_name_scores.append(name_similarity(names[1], names[2]))
|
| 121 |
-
if embeddings[1] is not None and embeddings[2] is not None:
|
| 122 |
-
valid_face_scores.append(cosine(embeddings[1], embeddings[2]))
|
| 123 |
-
|
| 124 |
-
# Make decision based on valid scores only
|
| 125 |
-
decision, confidence, reasons = decide(valid_name_scores, valid_face_scores)
|
| 126 |
-
|
| 127 |
-
# Add note if concession name couldn't be extracted
|
| 128 |
-
if names[2] is None:
|
| 129 |
-
reasons.append("Could not extract name from Concession form (handwritten)")
|
| 130 |
-
|
| 131 |
-
# Calculate averages
|
| 132 |
-
avg_face = sum(valid_face_scores) / len(valid_face_scores) if valid_face_scores else None
|
| 133 |
-
avg_name = sum(valid_name_scores) / len(valid_name_scores) if valid_name_scores else 0
|
| 134 |
-
|
| 135 |
-
return {
|
| 136 |
-
"
|
| 137 |
-
"
|
| 138 |
-
"
|
| 139 |
-
"
|
| 140 |
-
"
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
async def health():
|
| 149 |
-
"""Health check endpoint."""
|
| 150 |
-
return {"status": "healthy"}
|
|
|
|
| 1 |
+
from fastapi import FastAPI, UploadFile, File
|
| 2 |
+
from app.ocr import extract_text
|
| 3 |
+
from app.face import get_face_embedding, cosine
|
| 4 |
+
from app.rules import extract_name, name_similarity, calculate_pairwise_scores, decide, fix_name_format
|
| 5 |
+
from app.utils import read_image
|
| 6 |
+
from app.models import VerificationResponse
|
| 7 |
+
|
| 8 |
+
app = FastAPI(title="Document Verifier - Aadhar, College ID, Concession")
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def is_valid_name(name):
|
| 12 |
+
"""Check if extracted name is valid (not garbage OCR)."""
|
| 13 |
+
if not name:
|
| 14 |
+
return False
|
| 15 |
+
|
| 16 |
+
# Must have at least 2 parts (first + last)
|
| 17 |
+
parts = name.split()
|
| 18 |
+
if len(parts) < 2:
|
| 19 |
+
return False
|
| 20 |
+
|
| 21 |
+
# Each part should be at least 2 characters
|
| 22 |
+
if any(len(p) < 2 for p in parts):
|
| 23 |
+
return False
|
| 24 |
+
|
| 25 |
+
# Should look like a name (mostly letters)
|
| 26 |
+
alpha_count = sum(c.isalpha() for c in name)
|
| 27 |
+
if alpha_count < len(name) * 0.8:
|
| 28 |
+
return False
|
| 29 |
+
|
| 30 |
+
return True
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@app.post("/verify", response_model=VerificationResponse)
|
| 34 |
+
async def verify(
|
| 35 |
+
aadhar: UploadFile = File(..., description="Aadhar Card Image"),
|
| 36 |
+
college_id: UploadFile = File(..., description="College ID Card Image"),
|
| 37 |
+
concession: UploadFile = File(..., description="Concession Form Image (can be handwritten)")
|
| 38 |
+
):
|
| 39 |
+
"""
|
| 40 |
+
Verify documents by comparing:
|
| 41 |
+
- Aadhar Card
|
| 42 |
+
- College ID
|
| 43 |
+
- Concession Form (handwritten or printed)
|
| 44 |
+
"""
|
| 45 |
+
docs = [aadhar, college_id, concession]
|
| 46 |
+
doc_names = ["Aadhar", "College ID", "Concession"]
|
| 47 |
+
|
| 48 |
+
imgs = []
|
| 49 |
+
names = []
|
| 50 |
+
embeddings = []
|
| 51 |
+
all_ocr_lines = {}
|
| 52 |
+
|
| 53 |
+
for i, doc in enumerate(docs):
|
| 54 |
+
img = read_image(await doc.read())
|
| 55 |
+
imgs.append(img)
|
| 56 |
+
|
| 57 |
+
is_handwritten = (i == 2)
|
| 58 |
+
extracted_lines = extract_text(img, is_handwritten=is_handwritten)
|
| 59 |
+
all_ocr_lines[doc_names[i]] = extracted_lines
|
| 60 |
+
|
| 61 |
+
name = extract_name(extracted_lines)
|
| 62 |
+
|
| 63 |
+
# Fix format issues
|
| 64 |
+
if name:
|
| 65 |
+
name = fix_name_format(name)
|
| 66 |
+
|
| 67 |
+
# Validate name quality
|
| 68 |
+
if not is_valid_name(name):
|
| 69 |
+
name = None
|
| 70 |
+
|
| 71 |
+
names.append(name)
|
| 72 |
+
|
| 73 |
+
embedding = get_face_embedding(img)
|
| 74 |
+
embeddings.append(embedding)
|
| 75 |
+
|
| 76 |
+
# Calculate pairwise scores
|
| 77 |
+
face_scores, name_scores = calculate_pairwise_scores(embeddings, names)
|
| 78 |
+
|
| 79 |
+
# Build pairwise details
|
| 80 |
+
pair_labels = ["Aadhar-CollegeID", "Aadhar-Concession", "CollegeID-Concession"]
|
| 81 |
+
pair_indices = [(0, 1), (0, 2), (1, 2)]
|
| 82 |
+
pairwise_details = {}
|
| 83 |
+
|
| 84 |
+
for k, (i, j) in enumerate(pair_indices):
|
| 85 |
+
label = pair_labels[k]
|
| 86 |
+
|
| 87 |
+
# Face score
|
| 88 |
+
f_score = None
|
| 89 |
+
if embeddings[i] is not None and embeddings[j] is not None:
|
| 90 |
+
f_score = cosine(embeddings[i], embeddings[j])
|
| 91 |
+
|
| 92 |
+
# Name score
|
| 93 |
+
n_score = None
|
| 94 |
+
if names[i] and names[j]:
|
| 95 |
+
n_score = name_similarity(names[i], names[j])
|
| 96 |
+
|
| 97 |
+
pairwise_details[label] = {
|
| 98 |
+
"face_score": round(f_score, 4) if f_score is not None else None,
|
| 99 |
+
"name_score": round(n_score, 2) if n_score is not None else None
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
# If concession name failed, focus on Aadhar-CollegeID comparison
|
| 103 |
+
valid_name_scores = []
|
| 104 |
+
valid_face_scores = []
|
| 105 |
+
|
| 106 |
+
# Aadhar-CollegeID (most reliable)
|
| 107 |
+
if names[0] and names[1]:
|
| 108 |
+
valid_name_scores.append(name_similarity(names[0], names[1]))
|
| 109 |
+
if embeddings[0] is not None and embeddings[1] is not None:
|
| 110 |
+
valid_face_scores.append(cosine(embeddings[0], embeddings[1]))
|
| 111 |
+
|
| 112 |
+
# Aadhar-Concession
|
| 113 |
+
if names[0] and names[2]:
|
| 114 |
+
valid_name_scores.append(name_similarity(names[0], names[2]))
|
| 115 |
+
if embeddings[0] is not None and embeddings[2] is not None:
|
| 116 |
+
valid_face_scores.append(cosine(embeddings[0], embeddings[2]))
|
| 117 |
+
|
| 118 |
+
# CollegeID-Concession
|
| 119 |
+
if names[1] and names[2]:
|
| 120 |
+
valid_name_scores.append(name_similarity(names[1], names[2]))
|
| 121 |
+
if embeddings[1] is not None and embeddings[2] is not None:
|
| 122 |
+
valid_face_scores.append(cosine(embeddings[1], embeddings[2]))
|
| 123 |
+
|
| 124 |
+
# Make decision based on valid scores only
|
| 125 |
+
decision, confidence, reasons = decide(valid_name_scores, valid_face_scores)
|
| 126 |
+
|
| 127 |
+
# Add note if concession name couldn't be extracted
|
| 128 |
+
if names[2] is None:
|
| 129 |
+
reasons.append("Could not extract name from Concession form (handwritten)")
|
| 130 |
+
|
| 131 |
+
# Calculate averages
|
| 132 |
+
avg_face = sum(valid_face_scores) / len(valid_face_scores) if valid_face_scores else None
|
| 133 |
+
avg_name = sum(valid_name_scores) / len(valid_name_scores) if valid_name_scores else 0
|
| 134 |
+
|
| 135 |
+
return {
|
| 136 |
+
"confidence": confidence,
|
| 137 |
+
"name_similarity": round(avg_name, 2),
|
| 138 |
+
"face_similarity": round(avg_face, 4) if avg_face else None,
|
| 139 |
+
"extracted_names": names,
|
| 140 |
+
"reasons": reasons,
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@app.get("/health")
|
| 145 |
+
async def health():
|
| 146 |
+
"""Health check endpoint."""
|
| 147 |
+
return {"status": "healthy"}
|
|
|
|
|
|
|
|
|