Spaces:
Sleeping
Sleeping
File size: 10,223 Bytes
097ded7 bec01ad | 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 | #!/usr/bin/env python
# coding: utf-8
# =========================================================
# 1. IMPORTS & ENV
# =========================================================
import os
import json
import re
import hashlib
from dotenv import load_dotenv
from PIL import Image
import gradio as gr
import pytesseract
from pdf2image import convert_from_path
from groq import Groq
load_dotenv()
# =========================================================
# 2. LOAD FDIC SECTION 3.2 ONCE (GLOBAL)
# =========================================================
with open("data/fdic_section_3_2_chunks_refined.json") as f:
FDIC_CHUNKS = json.load(f)
# =========================================================
# 3. GROQ CLIENT & MODELS
# =========================================================
client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
MODEL_LLM1 = "llama-3.1-8b-instant" # OCR β loan summary
MODEL_LLM2 = "llama-3.1-8b-instant" # topic indexing
MODEL_LLM4 = "meta-llama/llama-4-scout-17b-16e-instruct" # reasoning
# =========================================================
# 4. SESSION STATE
# =========================================================
SESSION_STATE = {
"ocr_text": "",
"loan_summary": None
}
OCR_CACHE = {}
# =========================================================
# 5. GUARDRAILS
# =========================================================
NON_LOAN_KEYWORDS = [
"movie", "music", "sports", "weather", "joke", "recipe",
"health", "cold", "fever", "doctor", "medicine",
"politics", "election"
]
def sanitize_user_input(text):
return text.strip()[:5000] if text else ""
def is_non_loan_question(text):
return any(k in text.lower() for k in NON_LOAN_KEYWORDS)
# =========================================================
# 6. SAFE JSON PARSER
# =========================================================
def safe_json_loads(text, stage):
if not text:
raise ValueError(f"{stage} returned empty response")
text = re.sub(r"```json|```", "", text).strip()
match = re.search(r"\{.*\}", text, re.DOTALL)
if not match:
raise ValueError(f"{stage} returned no JSON:\n{text}")
return json.loads(match.group())
# =========================================================
# 7. OCR HELPERS
# =========================================================
MAX_PAGES = 5
def file_hash(path, max_bytes=1024 * 1024):
h = hashlib.md5()
with open(path, "rb") as f:
h.update(f.read(max_bytes))
return h.hexdigest()
def ocr_file(path):
if path.lower().endswith(".pdf"):
text = ""
pages = convert_from_path(path, dpi=200)[:MAX_PAGES]
for p in pages:
text += pytesseract.image_to_string(p.convert("L")) + "\n"
return text.strip()
else:
img = Image.open(path).convert("L")
return pytesseract.image_to_string(img).strip()
def run_ocr_pipeline(uploaded_files):
texts = []
for f in uploaded_files:
path = str(f)
key = file_hash(path)
if key not in OCR_CACHE:
OCR_CACHE[key] = ocr_file(path)
texts.append(OCR_CACHE[key])
return "\n".join(texts)
# =========================================================
# 8. LOAN SCHEMA
# =========================================================
LOAN_SCHEMA = """<same as your original schema>"""
# =========================================================
# 9. SYSTEM PROMPTS
# =========================================================
LLM1_SYSTEM_PROMPT = f"""
You are an information extraction engine for bank loan documents.
Task:
- Extract ONLY facts that are explicitly stated in the text.
- Do NOT infer, assume, normalize, or calculate anything.
- If a value is missing or unclear, use null or "unknown".
Rules:
- Use ONLY the provided OCR text.
- Do NOT add explanations.
- Do NOT reference regulations.
- Output MUST strictly match the schema below.
- Return ONLY valid JSON.
Schema:
{LOAN_SCHEMA}
"""
LLM2_SYSTEM_PROMPT = """
You are a regulatory topic indexing assistant.
Inputs:
- A user question
- A list of FDIC RMS Manual Section 3.2 headings with chunk_ids
Task:
- Select ONLY the chunk_ids whose headings are directly relevant
to answering the user question.
- Base your decision ONLY on the heading titles.
- Do NOT interpret or summarize policy text.
Rules:
- Select between 1 and 6 chunk_ids.
- If no headings are relevant, return an empty list.
- Do NOT explain your reasoning.
- Return ONLY valid JSON.
Output format:
{
"selected_chunk_ids": ["string"]
}
"""
LLM4_SYSTEM_PROMPT = """
You are a regulatory-aligned loan evaluation assistant.
You are given TWO authoritative sources:
SOURCE A β Loan Summary
β’ Structured facts extracted from uploaded loan documents
β’ This is the ONLY source for borrower name, loan type, interest rate,
amounts, collateral, and other loan-specific details
SOURCE B β FDIC RMS Manual Section 3.2 (Loans)
β’ This is the ONLY source for regulatory objectives, examiner expectations,
loan review systems, risk management, and policy intent
RULES (STRICT):
1. If the user asks for loan details β answer ONLY from SOURCE A
2. If the user asks regulatory or examiner questions β answer ONLY from SOURCE B
3. If the user asks a mixed question β clearly separate:
β’ factual loan details (SOURCE A)
β’ regulatory interpretation (SOURCE B)
4. Do NOT infer or assume missing facts
5. Do NOT use general banking knowledge
6. Do NOT approve, reject, or predict loan outcomes
7. If required information is missing, explicitly state that it is not available
Tone:
Professional, neutral, examiner-style.
No markdown. No speculation.
"""
NO_DOC_PROMPT = f"""
You are creating a placeholder loan summary.
Rules:
- Use ONLY the schema provided.
- Do NOT infer or fabricate details.
- Populate fields only if explicitly stated in the user input.
- Otherwise, use null or "unknown".
- Return ONLY valid JSON.
Schema:
{LOAN_SCHEMA}
"""
# =========================================================
# 10. LLM CALL
# =========================================================
def call_llm(system_prompt, user_prompt, model, temperature=0):
r = client.chat.completions.create(
model=model,
temperature=temperature,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}
]
)
return r.choices[0].message.content.strip()
# =========================================================
# 11. MAIN LOGIC (FINAL)
# =========================================================
def process_request(user_text, uploaded_files):
user_text = sanitize_user_input(user_text)
# π« NON-LOAN GUARDRAIL
if is_non_loan_question(user_text):
return "", "β οΈ Only FDIC Section 3.2 loan and regulatory questions are supported."
# ======================================================
# LLM-1: OCR β Loan Summary (ONLY if files exist)
# ======================================================
if uploaded_files:
ocr_text = run_ocr_pipeline(uploaded_files)
loan_summary = safe_json_loads(
call_llm(
LLM1_SYSTEM_PROMPT,
ocr_text,
MODEL_LLM1
),
"LLM-1"
)
SESSION_STATE["ocr_text"] = ocr_text
SESSION_STATE["loan_summary"] = loan_summary
else:
# Follow-up or regulatory-only question
ocr_text = SESSION_STATE.get("ocr_text", "")
loan_summary = SESSION_STATE.get("loan_summary")
# β Do NOT force NO-DOC extraction for regulatory questions
if loan_summary is None:
loan_summary = {
"note": "No loan documents uploaded. Loan-specific facts unavailable."
}
# ======================================================
# LLM-2: FDIC Section 3.2 Topic Indexing (HEADINGS ONLY)
# ======================================================
headings_payload = {
"user_question": user_text,
"fdic_headings": [
{
"chunk_id": c["chunk_id"],
"heading": c.get("subtopic") or c.get("title")
}
for c in FDIC_CHUNKS
]
}
selected_ids = safe_json_loads(
call_llm(
LLM2_SYSTEM_PROMPT,
json.dumps(headings_payload),
MODEL_LLM2
),
"LLM-2"
).get("selected_chunk_ids", [])
selected_chunks = [
{
"chunk_id": c["chunk_id"],
"heading": c.get("subtopic") or c.get("title")
}
for c in FDIC_CHUNKS
if c["chunk_id"] in set(selected_ids)
][:6] # π HARD CAP (very important)
# ======================================================
# LLM-4: FINAL REGULATORY + FACTUAL ANSWER
# ======================================================
llm4_payload = {
"loan_summary": loan_summary,
"fdic_section_3_2": selected_chunks,
"user_question": user_text
}
answer = call_llm(
LLM4_SYSTEM_PROMPT,
json.dumps(llm4_payload),
MODEL_LLM4,
temperature=0.2
)
return ocr_text, answer
# =========================================================
# 12. GRADIO UI
# =========================================================
def chat_handler(user_text, uploaded_files, chat_history):
chat_history = chat_history or []
_, answer = process_request(user_text, uploaded_files)
chat_history.append({"role": "user", "content": user_text})
chat_history.append({"role": "assistant", "content": answer})
return chat_history
with gr.Blocks(title="Regulatory Loan Evaluation Assistant") as demo:
gr.Markdown("## π Regulatory Loan Evaluation Assistant")
chat = gr.Chatbot(height=450)
files = gr.File(
label="Upload Loan Documents (Optional)",
file_types=[".pdf", ".png", ".jpg", ".jpeg"],
file_count="multiple"
)
user_input = gr.Textbox(placeholder="Ask a regulatory or loan question")
gr.Button("Send").click(
fn=chat_handler,
inputs=[user_input, files, chat],
outputs=[chat]
)
demo.launch(show_api=False)
|