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
|
| 4 |
+
import re
|
| 5 |
+
import numpy as np
|
| 6 |
+
import tempfile
|
| 7 |
+
import os
|
| 8 |
+
import psycopg2
|
| 9 |
+
from rapidfuzz import fuzz # ✅ Fuzzy matching
|
| 10 |
+
from dotenv import load_dotenv
|
| 11 |
+
load_dotenv() # ✅ Add this line after imports
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# 🔍 Known countries and banks (used for fuzzy matching)
|
| 15 |
+
known_countries = ["India", "USA", "Germany", "Venezuela", "China", "Norway", "Sweden", "Finland", "UAE", "Mexico", "England", "Scotland", "Wales"]
|
| 16 |
+
known_banks = [
|
| 17 |
+
"Reserve Bank of India", "Federal Reserve", "Banco Central de Venezuela",
|
| 18 |
+
"Deutsche Bundesbank", "Bank of China", "Bank of Mexico", "Bank of England", "Sveriges Riksbank"
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
# 🧠 EasyOCR setup
|
| 22 |
+
reader = easyocr.Reader(['en'], gpu=False)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# Define the clean_text function
|
| 26 |
+
def clean_text(text):
|
| 27 |
+
txt = text.lower() # Convert to lowercase
|
| 28 |
+
txt = re.sub(r'[^\w\s\.\-]', '', txt) # remove unwanted chars but keep dots/hyphens
|
| 29 |
+
return txt.strip() # Remove leading/trailing whitespace
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
# 🧩 Helper for fuzzy match
|
| 33 |
+
def get_best_match(text, choices, threshold=80):
|
| 34 |
+
best_match = "Not found"
|
| 35 |
+
highest_score = 0
|
| 36 |
+
for choice in choices:
|
| 37 |
+
score = fuzz.partial_ratio(choice.lower(), text.lower())
|
| 38 |
+
if score > threshold and score > highest_score:
|
| 39 |
+
best_match = choice
|
| 40 |
+
highest_score = score
|
| 41 |
+
return best_match
|
| 42 |
+
|
| 43 |
+
# 🔍 Extract note info using OCR text
|
| 44 |
+
def extract_note_info(text):
|
| 45 |
+
print("\n=== 🧾 OCR Raw Text Start ===")
|
| 46 |
+
print(text)
|
| 47 |
+
print("=== 🧾 OCR Raw Text End ===\n")
|
| 48 |
+
|
| 49 |
+
raw_text = text # original OCR text
|
| 50 |
+
cleaned_text = clean_text(text) # used only for country, bank, denomination
|
| 51 |
+
|
| 52 |
+
print("🧹 Cleaned Text:")
|
| 53 |
+
print(cleaned_text)
|
| 54 |
+
print()
|
| 55 |
+
|
| 56 |
+
# Country and Bank
|
| 57 |
+
country = "Not found"
|
| 58 |
+
bank = "Not found"
|
| 59 |
+
for line in cleaned_text.split('\n'):
|
| 60 |
+
if country == "Not found":
|
| 61 |
+
country = get_best_match(line, known_countries)
|
| 62 |
+
if bank == "Not found":
|
| 63 |
+
bank = get_best_match(line, known_banks)
|
| 64 |
+
if country != "Not found" and bank != "Not found":
|
| 65 |
+
break
|
| 66 |
+
|
| 67 |
+
# Serial number from raw text (case-sensitive)
|
| 68 |
+
serial_match = re.search(r'\b[A-Z]{1,3}[-\s]?[0-9]{6,9}\b', raw_text)
|
| 69 |
+
|
| 70 |
+
if not serial_match:
|
| 71 |
+
fallback_match = re.search(r'\b[0-9]{5,10}\b', raw_text) # matches just numeric formats (5 to 10 digits)
|
| 72 |
+
if fallback_match:
|
| 73 |
+
possible_serial = fallback_match.group()
|
| 74 |
+
if possible_serial[0] == '4':
|
| 75 |
+
possible_serial = 'A' + possible_serial[1:]
|
| 76 |
+
elif possible_serial[0] == '8':
|
| 77 |
+
possible_serial = 'B' + possible_serial[1:]
|
| 78 |
+
serial = possible_serial.upper()
|
| 79 |
+
else:
|
| 80 |
+
serial = "Not found"
|
| 81 |
+
else:
|
| 82 |
+
serial = serial_match.group().replace(" ", "").replace("-", "").upper()
|
| 83 |
+
|
| 84 |
+
# Denomination
|
| 85 |
+
# denom_match = re.search(r'(10|[dD]iez|Bs\.?\s?\d+|\$?\s?10)', cleaned_text)
|
| 86 |
+
#denom_match = re.search(r'\b(10|20|50|100|200|500|1000)\s?(kronor|bolivares|euros|dollars)\b', text, re.IGNORECASE)
|
| 87 |
+
|
| 88 |
+
#denomination = denom_match.group() if denom_match else "Not found"
|
| 89 |
+
denomination = extract_denomination(text,cleaned_text)
|
| 90 |
+
return country, denomination, serial, bank
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def extract_denomination(text, cleaned_text):
|
| 94 |
+
# 1. Match "500 kronor", "1000 bolivares", etc.
|
| 95 |
+
phrase_match = re.search(r'\b(10|20|50|100|200|500|1000)\s?(kronor|bolivares|euros|dollars)\b', text, re.IGNORECASE)
|
| 96 |
+
if phrase_match:
|
| 97 |
+
return phrase_match.group().title()
|
| 98 |
+
|
| 99 |
+
# 2. Match just the number
|
| 100 |
+
number_match = re.search(r'\b(10|20|50|100|200|500|1000)\b', cleaned_text)
|
| 101 |
+
if number_match:
|
| 102 |
+
return number_match.group()
|
| 103 |
+
|
| 104 |
+
# 3. Match words like "diez", "veinte", etc.
|
| 105 |
+
word_match = re.search(r'\b(diez|veinte|cien|mil|kronor|bolivares|euros|dollars)\b', cleaned_text, re.IGNORECASE)
|
| 106 |
+
if word_match:
|
| 107 |
+
return word_match.group().capitalize()
|
| 108 |
+
|
| 109 |
+
return "Not found"
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# 🔍 OCR + Box Drawing
|
| 113 |
+
def detect_banknote(image,flip):
|
| 114 |
+
|
| 115 |
+
try:
|
| 116 |
+
if flip:
|
| 117 |
+
image = cv2.flip(image, 1) # Flip horizontally
|
| 118 |
+
image_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
|
| 119 |
+
|
| 120 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp_file:
|
| 121 |
+
cv2.imwrite(tmp_file.name, image_bgr)
|
| 122 |
+
ocr_results = reader.readtext(tmp_file.name)
|
| 123 |
+
|
| 124 |
+
full_text = " ".join([res[1] for res in ocr_results])
|
| 125 |
+
print("OCR TEXT:", full_text)
|
| 126 |
+
|
| 127 |
+
# Extract info
|
| 128 |
+
country, denomination, serial, bank = extract_note_info(full_text)
|
| 129 |
+
|
| 130 |
+
# Store extracted info
|
| 131 |
+
extracted_info["Country"] = country
|
| 132 |
+
extracted_info["Value"] = denomination
|
| 133 |
+
extracted_info["Serial Number"] = serial
|
| 134 |
+
extracted_info["Bank"] = bank
|
| 135 |
+
|
| 136 |
+
# Draw boxes
|
| 137 |
+
for bbox, text, conf in ocr_results:
|
| 138 |
+
(top_left, _, bottom_right, _) = bbox
|
| 139 |
+
top_left = tuple(map(int, top_left))
|
| 140 |
+
bottom_right = tuple(map(int, bottom_right))
|
| 141 |
+
cv2.rectangle(image_bgr, top_left, bottom_right, (0, 255, 0), 2)
|
| 142 |
+
label = f"{text} ({conf:.1f}%)"
|
| 143 |
+
cv2.putText(image_bgr, label, (top_left[0], top_left[1] - 10),
|
| 144 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
|
| 145 |
+
|
| 146 |
+
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
|
| 147 |
+
|
| 148 |
+
result_text = (
|
| 149 |
+
f"🔹 **Country**: {country}\n"
|
| 150 |
+
f"💰 **Denomination**: {denomination}\n"
|
| 151 |
+
f"🔢 **Serial Number**: {serial}\n"
|
| 152 |
+
f"🏦 **Bank Name**: {bank}"
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
return image_rgb, result_text
|
| 156 |
+
|
| 157 |
+
except Exception as e:
|
| 158 |
+
print("ERROR in detect_banknote:", e)
|
| 159 |
+
return None, f"Error: {e}"
|
| 160 |
+
|
| 161 |
+
# 🗃️ PostgreSQL details
|
| 162 |
+
extracted_info = {"Country": "", "Denomination": "", "Serial Number": "", "Bank": ""}
|
| 163 |
+
|
| 164 |
+
# Tab 1: Detect Banknote
|
| 165 |
+
def detect_ui():
|
| 166 |
+
with gr.Tab("💵 Detect Banknote"):
|
| 167 |
+
gr.Markdown("## 🧾 Banknote Detector")
|
| 168 |
+
with gr.Row():
|
| 169 |
+
with gr.Column():
|
| 170 |
+
mirror_toggle = gr.Checkbox(label="Flip Image Horizontally (Fix Mirror)", value=False) #This line adds a checkbox to your Gradio UI.
|
| 171 |
+
|
| 172 |
+
image_input = gr.Image(label="Upload Banknote Image", type="numpy")
|
| 173 |
+
submit_btn = gr.Button("Submit")
|
| 174 |
+
clear_btn = gr.Button("Clear")
|
| 175 |
+
with gr.Column():
|
| 176 |
+
image_output = gr.Image(label="Annotated Banknote")
|
| 177 |
+
text_output = gr.Markdown()
|
| 178 |
+
|
| 179 |
+
# submit_btn.click(fn=detect_banknote, inputs=image_input, outputs=[image_output, text_output])
|
| 180 |
+
submit_btn.click(fn=detect_banknote, inputs=[image_input, mirror_toggle], outputs=[image_output, text_output])
|
| 181 |
+
|
| 182 |
+
#clear_btn.click(lambda: (None, ""), None, [image_input, image_output, text_output])
|
| 183 |
+
clear_btn.click(lambda: (None, "", False), None, [image_input, image_output, text_output, mirror_toggle])
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
# Tab 2: View Metadata from DB
|
| 187 |
+
def metadata_ui():
|
| 188 |
+
with gr.Tab("📄 Matched Banknote Metadata"):
|
| 189 |
+
gr.Markdown("### 📌 Metadata from Database")
|
| 190 |
+
fetch_btn = gr.Button("Fetch Metadata")
|
| 191 |
+
metadata_table = gr.Dataframe(
|
| 192 |
+
value=[["" for _ in range(9)]], # 9 columns
|
| 193 |
+
headers=["Country", "Currency", "Issued by", "Date", "Remark", "Material", "Catalogue Pick", "Sub-Catalogue", "Description"],
|
| 194 |
+
label="Metadata Table"
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
def fetch_metadata():
|
| 198 |
+
try:
|
| 199 |
+
conn = psycopg2.connect(
|
| 200 |
+
dbname=os.getenv("DB_NAME"),
|
| 201 |
+
user=os.getenv("DB_USER"),
|
| 202 |
+
password=os.getenv("DB_PASSWORD"),
|
| 203 |
+
host=os.getenv("DB_HOST"),
|
| 204 |
+
port=os.getenv("DB_PORT")
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
cursor = conn.cursor()
|
| 208 |
+
|
| 209 |
+
print("🔍 Fetching Metadata with:")
|
| 210 |
+
print("Country:", extracted_info["Country"])
|
| 211 |
+
print("Denomination:", extracted_info["Value"])
|
| 212 |
+
print("Serial Number:", extracted_info["Serial Number"])
|
| 213 |
+
print("Bank:", extracted_info["Bank"])
|
| 214 |
+
query = """
|
| 215 |
+
SELECT "Country", "Currency", "Issued by", "Date", "Remark", "Material",
|
| 216 |
+
"Catalogue Pick", "Sub-Catalogue", "Description"
|
| 217 |
+
FROM "AI"."Finland"
|
| 218 |
+
WHERE
|
| 219 |
+
REPLACE(LOWER("Serial Number"), '-', '') = %s
|
| 220 |
+
OR REPLACE(LOWER("Serial Number"), ' ', '') = %s
|
| 221 |
+
OR LOWER("Serial Number") ILIKE %s
|
| 222 |
+
"""
|
| 223 |
+
serial_lower = extracted_info["Serial Number"].lower().replace("-", "").replace(" ", "")
|
| 224 |
+
serial_like = f"%{serial_lower}%"
|
| 225 |
+
cursor.execute(query, (serial_lower, serial_lower, serial_like))
|
| 226 |
+
|
| 227 |
+
# extracted_info["Country"].lower(),
|
| 228 |
+
# extracted_info["Value"],
|
| 229 |
+
# extracted_info["Bank"].lower(),
|
| 230 |
+
#extracted_info["Serial Number"]
|
| 231 |
+
|
| 232 |
+
results = cursor.fetchall()
|
| 233 |
+
return results if results else [["No match", "", "", "", "", "", "", "", ""]]
|
| 234 |
+
except Exception as e:
|
| 235 |
+
return [[f"Error: {e}", "", "", "", "", "", "", "", ""]]
|
| 236 |
+
finally:
|
| 237 |
+
try:
|
| 238 |
+
cursor.close()
|
| 239 |
+
conn.close()
|
| 240 |
+
except:
|
| 241 |
+
pass
|
| 242 |
+
|
| 243 |
+
fetch_btn.click(fn=fetch_metadata, outputs=metadata_table)
|
| 244 |
+
|
| 245 |
+
# Optional Tab 3: History
|
| 246 |
+
import matplotlib.pyplot as plt
|
| 247 |
+
import io
|
| 248 |
+
|
| 249 |
+
# Simulated detection history for demo (You can load from a file or DB)
|
| 250 |
+
detection_history = [
|
| 251 |
+
["img1.jpg", "India", "100", "A1234567", "Reserve Bank of India"],
|
| 252 |
+
["img2.jpg", "USA", "50", "Not found", "Federal Reserve"],
|
| 253 |
+
["img3.jpg", "Germany", "Not found", "C9876543", "Not found"],
|
| 254 |
+
["img4.jpg", "Not found", "500", "Not found", "Bank of England"]
|
| 255 |
+
]
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def history_ui():
|
| 259 |
+
with gr.Tab("📖 View History"):
|
| 260 |
+
gr.Markdown("## 🕓 Detection History")
|
| 261 |
+
|
| 262 |
+
history_table = gr.Dataframe(
|
| 263 |
+
value=detection_history,
|
| 264 |
+
headers=["Image", "Country", "Value", "Serial Number", "Bank"],
|
| 265 |
+
label="🔍 All Detected Notes"
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
refresh = gr.Button("🔁 Refresh History")
|
| 269 |
+
|
| 270 |
+
# 📈 Chart: Match vs Unmatched
|
| 271 |
+
def generate_charts():
|
| 272 |
+
total = len(detection_history)
|
| 273 |
+
matched = sum(1 for note in detection_history if "Not found" not in note)
|
| 274 |
+
unmatched = total - matched
|
| 275 |
+
|
| 276 |
+
# Pie chart
|
| 277 |
+
pie_fig, ax1 = plt.subplots()
|
| 278 |
+
ax1.pie([matched, unmatched], labels=["Matched", "Unmatched"], autopct='%1.1f%%', colors=["green", "red"])
|
| 279 |
+
ax1.set_title("Detection Summary")
|
| 280 |
+
|
| 281 |
+
# Field-wise bar chart
|
| 282 |
+
fields = ["Country", "Value", "Serial Number", "Bank"]
|
| 283 |
+
match_counts = []
|
| 284 |
+
for i in range(1, 5): # Skip image column
|
| 285 |
+
count = sum(1 for note in detection_history if note[i] != "Not found")
|
| 286 |
+
match_counts.append(count)
|
| 287 |
+
|
| 288 |
+
bar_fig, ax2 = plt.subplots()
|
| 289 |
+
ax2.bar(fields, match_counts, color='blue')
|
| 290 |
+
ax2.set_title("Field Match Count")
|
| 291 |
+
ax2.set_ylabel("Detected Count")
|
| 292 |
+
|
| 293 |
+
return pie_fig, bar_fig
|
| 294 |
+
|
| 295 |
+
pie_chart = gr.Plot()
|
| 296 |
+
bar_chart = gr.Plot()
|
| 297 |
+
|
| 298 |
+
refresh.click(fn=generate_charts, outputs=[pie_chart, bar_chart])
|
| 299 |
+
|
| 300 |
+
gr.Markdown("### 📊 Detection Quality Summary")
|
| 301 |
+
with gr.Row():
|
| 302 |
+
pie_chart = gr.Plot()
|
| 303 |
+
bar_chart = gr.Plot()
|
| 304 |
+
# pie_chart.render()
|
| 305 |
+
# bar_chart.render()
|
| 306 |
+
# pie_chart.render()
|
| 307 |
+
# bar_chart.render()
|
| 308 |
+
|
| 309 |
+
#def history_ui():
|
| 310 |
+
# with gr.Tab("📖 View History"):
|
| 311 |
+
# gr.Markdown("## 🕓 Detection History")
|
| 312 |
+
# history_table = gr.Dataframe(headers=["Image", "Country", "Value", "Serial Number", "Bank"])
|
| 313 |
+
# refresh = gr.Button("Refresh History")
|
| 314 |
+
|
| 315 |
+
# def load_history():
|
| 316 |
+
# return [["sample.jpg", "UK", "£50", "AA40925300", "Bank of England"]]
|
| 317 |
+
|
| 318 |
+
# refresh.click(fn=load_history, outputs=history_table)
|
| 319 |
+
|
| 320 |
+
# 🧷 Launch Gradio App
|
| 321 |
+
with gr.Blocks() as demo:
|
| 322 |
+
detect_ui()
|
| 323 |
+
metadata_ui()
|
| 324 |
+
history_ui()
|
| 325 |
+
|
| 326 |
+
demo.launch()
|