Spaces:
Sleeping
Sleeping
okara chidera
commited on
feat: credit copilot
Browse files- README.md +24 -14
- app.py +243 -0
- requirements.txt +5 -0
README.md
CHANGED
|
@@ -1,14 +1,24 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CreditCopilot — KYC Manager
|
| 2 |
+
|
| 3 |
+
CreditCopilot automates Know Your Customer (KYC) checks by analyzing uploaded documents and producing structured compliance reports.
|
| 4 |
+
|
| 5 |
+
**Features**
|
| 6 |
+
- Upload ID, selfie, and address proofs (PDF or images)
|
| 7 |
+
- Extract text and data automatically using OCR
|
| 8 |
+
- Parse name, DOB, ID number, expiry date, email, phone, and address
|
| 9 |
+
- Validate document completeness and consistency
|
| 10 |
+
- Highlight missing or expired documents
|
| 11 |
+
- Generate both human-readable summaries and downloadable JSON reports
|
| 12 |
+
- Optional AI refinement via Hugging Face Inference API
|
| 13 |
+
|
| 14 |
+
**Built with:** Python · Gradio · pdfplumber · pytesseract · Hugging Face Hub
|
| 15 |
+
|
| 16 |
+
### Optional Variables
|
| 17 |
+
Add these under **Settings → Variables and secrets**:
|
| 18 |
+
- `HF_TOKEN`: Hugging Face token for AI summarization
|
| 19 |
+
- `HF_MODEL`: Optional model (default: `mistralai/Mistral-7B-Instruct-v0.2`)
|
| 20 |
+
|
| 21 |
+
### Run locally
|
| 22 |
+
```bash
|
| 23 |
+
pip install -r requirements.txt
|
| 24 |
+
python app.py
|
app.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os, re, json, base64
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
from dataclasses import dataclass, asdict
|
| 5 |
+
from typing import List, Optional, Dict, Any
|
| 6 |
+
|
| 7 |
+
# Optional LLM summary (set HF_TOKEN in Space secrets)
|
| 8 |
+
HF_TOKEN = os.getenv("HF_TOKEN", "")
|
| 9 |
+
HF_MODEL = os.getenv("HF_MODEL", "mistralai/Mistral-7B-Instruct-v0.2")
|
| 10 |
+
USE_LLM = bool(HF_TOKEN)
|
| 11 |
+
|
| 12 |
+
if USE_LLM:
|
| 13 |
+
from huggingface_hub import InferenceClient
|
| 14 |
+
client = InferenceClient(token=HF_TOKEN)
|
| 15 |
+
|
| 16 |
+
# PDF & image parsing
|
| 17 |
+
import pdfplumber
|
| 18 |
+
from PIL import Image
|
| 19 |
+
try:
|
| 20 |
+
import pytesseract
|
| 21 |
+
OCR_AVAILABLE = True
|
| 22 |
+
except Exception:
|
| 23 |
+
OCR_AVAILABLE = False
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# ---------- CONFIG ----------
|
| 27 |
+
REQUIRED_DOCS = ["Government ID", "Selfie / Liveness", "Proof of Address"]
|
| 28 |
+
DATE_PAT = r"(?:\b(20\d{2}|19\d{2})[-/.](0?[1-9]|1[0-2])[-/.](0?[1-9]|[12]\d|3[01])\b)"
|
| 29 |
+
EMAIL_PAT = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b"
|
| 30 |
+
PHONE_PAT = r"(?:\+?\d{1,3})?[\s-]?\d{6,14}"
|
| 31 |
+
ID_PAT = r"\b([A-Z]{1,3}\d{6,12}|[0-9]{8,14})\b"
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@dataclass
|
| 35 |
+
class KYCSummary:
|
| 36 |
+
applicant_name: Optional[str]
|
| 37 |
+
dob: Optional[str]
|
| 38 |
+
doc_id_number: Optional[str]
|
| 39 |
+
doc_type: Optional[str]
|
| 40 |
+
doc_expiry: Optional[str]
|
| 41 |
+
email: Optional[str]
|
| 42 |
+
phone: Optional[str]
|
| 43 |
+
address_snippet: Optional[str]
|
| 44 |
+
required_docs: List[str]
|
| 45 |
+
provided_docs: List[str]
|
| 46 |
+
missing_docs: List[str]
|
| 47 |
+
red_flags: List[str]
|
| 48 |
+
extracted_text_preview: str
|
| 49 |
+
generated_at: str
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# ---------- HELPERS ----------
|
| 53 |
+
def read_pdf(file_path: str) -> str:
|
| 54 |
+
text_chunks = []
|
| 55 |
+
with pdfplumber.open(file_path) as pdf:
|
| 56 |
+
for page in pdf.pages:
|
| 57 |
+
t = page.extract_text() or ""
|
| 58 |
+
if not t and OCR_AVAILABLE:
|
| 59 |
+
img = page.to_image(resolution=200).original
|
| 60 |
+
t = pytesseract.image_to_string(img)
|
| 61 |
+
text_chunks.append(t)
|
| 62 |
+
return "\n".join(text_chunks)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def read_image(file_path: str) -> str:
|
| 66 |
+
if not OCR_AVAILABLE:
|
| 67 |
+
return ""
|
| 68 |
+
img = Image.open(file_path).convert("RGB")
|
| 69 |
+
return pytesseract.image_to_string(img)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def extract_text(file) -> str:
|
| 73 |
+
if not file:
|
| 74 |
+
return ""
|
| 75 |
+
_, ext = os.path.splitext(file.name)
|
| 76 |
+
ext = ext.lower()
|
| 77 |
+
try:
|
| 78 |
+
if ext == ".pdf":
|
| 79 |
+
return read_pdf(file.name)
|
| 80 |
+
elif ext in [".png", ".jpg", ".jpeg", ".webp"]:
|
| 81 |
+
return read_image(file.name)
|
| 82 |
+
return ""
|
| 83 |
+
except Exception:
|
| 84 |
+
return ""
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def parse_fields(text: str) -> Dict[str, Optional[str]]:
|
| 88 |
+
if not text:
|
| 89 |
+
return {k: None for k in ["name", "dob", "id_number", "doc_type", "doc_expiry", "email", "phone", "address"]}
|
| 90 |
+
|
| 91 |
+
name = None
|
| 92 |
+
for line in text.splitlines():
|
| 93 |
+
if "name" in line.lower() and ":" in line:
|
| 94 |
+
name = line.split(":", 1)[1].strip()
|
| 95 |
+
break
|
| 96 |
+
if not name:
|
| 97 |
+
m = re.search(r"\b([A-Z][a-z]+(?:\s[A-Z][a-z]+){1,3})\b", text)
|
| 98 |
+
name = m.group(1) if m else None
|
| 99 |
+
|
| 100 |
+
dob = (re.search(DATE_PAT, text) or [None])
|
| 101 |
+
dob = dob.group(0) if hasattr(dob, "group") else None
|
| 102 |
+
email = (re.search(EMAIL_PAT, text) or [None])
|
| 103 |
+
email = email.group(0) if hasattr(email, "group") else None
|
| 104 |
+
phone = (re.search(PHONE_PAT, text) or [None])
|
| 105 |
+
phone = phone.group(0) if hasattr(phone, "group") else None
|
| 106 |
+
id_number = (re.search(ID_PAT, text) or [None])
|
| 107 |
+
id_number = id_number.group(1) if hasattr(id_number, "group") else None
|
| 108 |
+
|
| 109 |
+
doc_expiry = None
|
| 110 |
+
mexp = re.search(r"(exp.*?:?\s*)(%s)" % DATE_PAT, text, flags=re.I)
|
| 111 |
+
if mexp:
|
| 112 |
+
doc_expiry = mexp.group(2) or mexp.group(0).split()[-1]
|
| 113 |
+
|
| 114 |
+
address = None
|
| 115 |
+
for line in text.splitlines():
|
| 116 |
+
if re.search(r"\b(road|street|st\.|rd\.|avenue|estate|close)\b", line, re.I):
|
| 117 |
+
address = line.strip()
|
| 118 |
+
break
|
| 119 |
+
|
| 120 |
+
doc_type = None
|
| 121 |
+
for label in ["Passport", "Driver", "Voter", "National ID"]:
|
| 122 |
+
if re.search(label, text, re.I):
|
| 123 |
+
doc_type = label
|
| 124 |
+
break
|
| 125 |
+
|
| 126 |
+
return {
|
| 127 |
+
"name": name,
|
| 128 |
+
"dob": dob,
|
| 129 |
+
"id_number": id_number,
|
| 130 |
+
"doc_type": doc_type,
|
| 131 |
+
"doc_expiry": doc_expiry,
|
| 132 |
+
"email": email,
|
| 133 |
+
"phone": phone,
|
| 134 |
+
"address": address,
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def evaluate_rules(parsed: Dict[str, Optional[str]], expected_name: str, provided_docs: List[str]) -> Dict[str, Any]:
|
| 139 |
+
missing = [d for d in REQUIRED_DOCS if d not in provided_docs]
|
| 140 |
+
red_flags = []
|
| 141 |
+
|
| 142 |
+
if expected_name and parsed.get("name") and expected_name.lower() not in parsed["name"].lower():
|
| 143 |
+
red_flags.append("Name mismatch between input and document.")
|
| 144 |
+
if not parsed.get("dob"):
|
| 145 |
+
red_flags.append("Date of birth not found.")
|
| 146 |
+
if parsed.get("doc_expiry"):
|
| 147 |
+
try:
|
| 148 |
+
year = int(re.search(r"\d{4}", parsed["doc_expiry"]).group(0))
|
| 149 |
+
if year < datetime.now().year:
|
| 150 |
+
red_flags.append("Document may be expired.")
|
| 151 |
+
except Exception:
|
| 152 |
+
pass
|
| 153 |
+
if not parsed.get("address"):
|
| 154 |
+
red_flags.append("Address not detected.")
|
| 155 |
+
return {"missing_docs": missing, "red_flags": red_flags}
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def summarize(summary: KYCSummary) -> str:
|
| 159 |
+
lines = [
|
| 160 |
+
f"Applicant: **{summary.applicant_name or 'Unknown'}**",
|
| 161 |
+
f"DOB: {summary.dob or 'N/A'}",
|
| 162 |
+
f"ID: {summary.doc_type or 'Document'} — {summary.doc_id_number or 'N/A'}",
|
| 163 |
+
f"Expiry: {summary.doc_expiry or 'N/A'}",
|
| 164 |
+
f"Email: {summary.email or 'N/A'}",
|
| 165 |
+
f"Phone: {summary.phone or 'N/A'}",
|
| 166 |
+
f"Address: {summary.address_snippet or 'N/A'}",
|
| 167 |
+
f"Provided: {', '.join(summary.provided_docs) or 'None'}",
|
| 168 |
+
f"Missing: {', '.join(summary.missing_docs) or 'None'}",
|
| 169 |
+
f"Red Flags: {', '.join(summary.red_flags) or 'None'}",
|
| 170 |
+
]
|
| 171 |
+
return "\n".join(lines)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def llm_refine(text: str) -> str:
|
| 175 |
+
if not USE_LLM:
|
| 176 |
+
return text
|
| 177 |
+
try:
|
| 178 |
+
result = client.text_generation(
|
| 179 |
+
f"Rewrite this KYC review more clearly:\n\n{text}",
|
| 180 |
+
max_new_tokens=180,
|
| 181 |
+
temperature=0.2
|
| 182 |
+
)
|
| 183 |
+
return result.strip()
|
| 184 |
+
except Exception:
|
| 185 |
+
return text
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def run_kyc(name, provided_docs, id_doc, selfie_doc, address_doc):
|
| 189 |
+
docs = [id_doc, selfie_doc, address_doc]
|
| 190 |
+
text = "\n\n".join([extract_text(d) for d in docs if d])
|
| 191 |
+
parsed = parse_fields(text)
|
| 192 |
+
evals = evaluate_rules(parsed, name, provided_docs)
|
| 193 |
+
|
| 194 |
+
summary = KYCSummary(
|
| 195 |
+
applicant_name=parsed["name"] or name,
|
| 196 |
+
dob=parsed["dob"],
|
| 197 |
+
doc_id_number=parsed["id_number"],
|
| 198 |
+
doc_type=parsed["doc_type"],
|
| 199 |
+
doc_expiry=parsed["doc_expiry"],
|
| 200 |
+
email=parsed["email"],
|
| 201 |
+
phone=parsed["phone"],
|
| 202 |
+
address_snippet=parsed["address"],
|
| 203 |
+
required_docs=REQUIRED_DOCS,
|
| 204 |
+
provided_docs=provided_docs,
|
| 205 |
+
missing_docs=evals["missing_docs"],
|
| 206 |
+
red_flags=evals["red_flags"],
|
| 207 |
+
extracted_text_preview=text[:800],
|
| 208 |
+
generated_at=datetime.utcnow().isoformat() + "Z",
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
human = summarize(summary)
|
| 212 |
+
human_refined = llm_refine(human)
|
| 213 |
+
json_report = json.dumps(asdict(summary), indent=2)
|
| 214 |
+
download = f'<a href="data:application/json;base64,{base64.b64encode(json_report.encode()).decode()}" download="kyc_report.json">Download JSON report</a>'
|
| 215 |
+
return human_refined, json_report, download
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
# ---------- UI ----------
|
| 219 |
+
with gr.Blocks(title="CreditCopilot — KYC Manager") as demo:
|
| 220 |
+
gr.Markdown("## 🧠 CreditCopilot — KYC Management\nUpload KYC documents, extract details, and generate a compliance summary.")
|
| 221 |
+
with gr.Row():
|
| 222 |
+
with gr.Column(scale=1):
|
| 223 |
+
name = gr.Textbox(label="Applicant Name", placeholder="Enter applicant full name")
|
| 224 |
+
provided_docs = gr.CheckboxGroup(
|
| 225 |
+
choices=REQUIRED_DOCS, value=["Government ID"], label="Provided Documents"
|
| 226 |
+
)
|
| 227 |
+
id_doc = gr.File(label="Government ID (PDF or image)")
|
| 228 |
+
selfie_doc = gr.File(label="Selfie / Liveness (optional)")
|
| 229 |
+
address_doc = gr.File(label="Proof of Address (optional)")
|
| 230 |
+
run_btn = gr.Button("Run KYC Analysis", variant="primary")
|
| 231 |
+
with gr.Column(scale=2):
|
| 232 |
+
summary_out = gr.Markdown()
|
| 233 |
+
json_out = gr.Code(language="json")
|
| 234 |
+
download_link = gr.HTML()
|
| 235 |
+
|
| 236 |
+
run_btn.click(
|
| 237 |
+
fn=run_kyc,
|
| 238 |
+
inputs=[name, provided_docs, id_doc, selfie_doc, address_doc],
|
| 239 |
+
outputs=[summary_out, json_out, download_link],
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
if __name__ == "__main__":
|
| 243 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==4.44.0
|
| 2 |
+
pdfplumber==0.11.4
|
| 3 |
+
Pillow==10.4.0
|
| 4 |
+
pytesseract==0.3.13
|
| 5 |
+
huggingface_hub==0.24.6
|