banknote / main.py
David2499's picture
Update main.py
04835e2 verified
Raw History Blame Contribute Delete
12.5 kB
import gradio as gr
import cv2
import easyocr
import re
import numpy as np
import tempfile
import os
import psycopg2
from rapidfuzz import fuzz # ✅ Fuzzy matching
from dotenv import load_dotenv
from transformers import pipeline
load_dotenv() # ✅ Add this line after imports
# 🔍 Known countries and banks (used for fuzzy matching)
known_countries = ["India", "USA", "Germany", "Venezuela", "China", "Norway", "Sweden", "Finland", "UAE", "Mexico", "England", "Scotland", "Wales"]
known_banks = [
"Reserve Bank of India", "Federal Reserve", "Banco Central de Venezuela",
"Deutsche Bundesbank", "Bank of China", "Bank of Mexico", "Bank of England", "Sveriges Riksbank"
]
# 🧠 EasyOCR setup
reader = easyocr.Reader(['en'], gpu=False)
# Define the clean_text function
def clean_text(text):
txt = text.lower() # Convert to lowercase
txt = re.sub(r'[^\w\s\.\-]', '', txt) # remove unwanted chars but keep dots/hyphens
return txt.strip() # Remove leading/trailing whitespace
# 🧩 Helper for fuzzy match
def get_best_match(text, choices, threshold=80):
best_match = "Not found"
highest_score = 0
for choice in choices:
score = fuzz.partial_ratio(choice.lower(), text.lower())
if score > threshold and score > highest_score:
best_match = choice
highest_score = score
return best_match
# 🔍 Extract note info using OCR text
def extract_note_info(text):
print("\n=== 🧾 OCR Raw Text Start ===")
print(text)
print("=== 🧾 OCR Raw Text End ===\n")
raw_text = text # original OCR text
cleaned_text = clean_text(text) # used only for country, bank, denomination
print("🧹 Cleaned Text:")
print(cleaned_text)
print()
# Country and Bank
country = "Not found"
bank = "Not found"
for line in cleaned_text.split('\n'):
if country == "Not found":
country = get_best_match(line, known_countries)
if bank == "Not found":
bank = get_best_match(line, known_banks)
if country != "Not found" and bank != "Not found":
break
# Serial number from raw text (case-sensitive)
serial_match = re.search(r'\b[A-Z]{1,3}[-\s]?[0-9]{6,9}\b', raw_text)
if not serial_match:
fallback_match = re.search(r'\b[0-9]{5,10}\b', raw_text) # matches just numeric formats (5 to 10 digits)
if fallback_match:
possible_serial = fallback_match.group()
if possible_serial[0] == '4':
possible_serial = 'A' + possible_serial[1:]
elif possible_serial[0] == '8':
possible_serial = 'B' + possible_serial[1:]
serial = possible_serial.upper()
else:
serial = "Not found"
else:
serial = serial_match.group().replace(" ", "").replace("-", "").upper()
# Denomination
# denom_match = re.search(r'(10|[dD]iez|Bs\.?\s?\d+|\$?\s?10)', cleaned_text)
#denom_match = re.search(r'\b(10|20|50|100|200|500|1000)\s?(kronor|bolivares|euros|dollars)\b', text, re.IGNORECASE)
#denomination = denom_match.group() if denom_match else "Not found"
denomination = extract_denomination(text,cleaned_text)
return country, denomination, serial, bank
def extract_denomination(text, cleaned_text):
# 1. Match "500 kronor", "1000 bolivares", etc.
phrase_match = re.search(r'\b(10|20|50|100|200|500|1000)\s?(kronor|bolivares|euros|dollars)\b', text, re.IGNORECASE)
if phrase_match:
return phrase_match.group().title()
# 2. Match just the number
number_match = re.search(r'\b(10|20|50|100|200|500|1000)\b', cleaned_text)
if number_match:
return number_match.group()
# 3. Match words like "diez", "veinte", etc.
word_match = re.search(r'\b(diez|veinte|cien|mil|kronor|bolivares|euros|dollars)\b', cleaned_text, re.IGNORECASE)
if word_match:
return word_match.group().capitalize()
return "Not found"
# 🔍 OCR + Box Drawing
def detect_banknote(image,flip):
try:
if flip:
image = cv2.flip(image, 1) # Flip horizontally
image_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp_file:
cv2.imwrite(tmp_file.name, image_bgr)
ocr_results = reader.readtext(tmp_file.name)
full_text = " ".join([res[1] for res in ocr_results])
print("OCR TEXT:", full_text)
# Extract info
country, denomination, serial, bank = extract_note_info(full_text)
# Store extracted info
extracted_info["Country"] = country
extracted_info["Value"] = denomination
extracted_info["Serial Number"] = serial
extracted_info["Bank"] = bank
# Draw boxes
for bbox, text, conf in ocr_results:
(top_left, _, bottom_right, _) = bbox
top_left = tuple(map(int, top_left))
bottom_right = tuple(map(int, bottom_right))
cv2.rectangle(image_bgr, top_left, bottom_right, (0, 255, 0), 2)
label = f"{text} ({conf:.1f}%)"
cv2.putText(image_bgr, label, (top_left[0], top_left[1] - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
result_text = (
f"🔹 **Country**: {country}\n"
f"💰 **Denomination**: {denomination}\n"
f"🔢 **Serial Number**: {serial}\n"
f"🏦 **Bank Name**: {bank}"
)
return image_rgb, result_text
except Exception as e:
print("ERROR in detect_banknote:", e)
return None, f"Error: {e}"
# 🗃️ PostgreSQL details
extracted_info = {"Country": "", "Denomination": "", "Serial Number": "", "Bank": ""}
# Tab 1: Detect Banknote
def detect_ui():
with gr.Tab("💵 Detect Banknote"):
gr.Markdown("## 🧾 Banknote Detector")
with gr.Row():
with gr.Column():
mirror_toggle = gr.Checkbox(label="Flip Image Horizontally (Fix Mirror)", value=False) #This line adds a checkbox to your Gradio UI.
image_input = gr.Image(label="Upload Banknote Image", type="numpy")
submit_btn = gr.Button("Submit")
clear_btn = gr.Button("Clear")
with gr.Column():
image_output = gr.Image(label="Annotated Banknote")
text_output = gr.Markdown()
# submit_btn.click(fn=detect_banknote, inputs=image_input, outputs=[image_output, text_output])
submit_btn.click(fn=detect_banknote, inputs=[image_input, mirror_toggle], outputs=[image_output, text_output])
#clear_btn.click(lambda: (None, ""), None, [image_input, image_output, text_output])
clear_btn.click(lambda: (None, "", False), None, [image_input, image_output, text_output, mirror_toggle])
# Tab 2: View Metadata from DB
def metadata_ui():
with gr.Tab("📄 Matched Banknote Metadata"):
gr.Markdown("### 📌 Metadata from Database")
fetch_btn = gr.Button("Fetch Metadata")
metadata_table = gr.Dataframe(
value=[["" for _ in range(9)]], # 9 columns
headers=["Country", "Currency", "Issued by", "Date", "Remark", "Material", "Catalogue Pick", "Sub-Catalogue", "Description"],
label="Metadata Table"
)
def fetch_metadata():
try:
conn = psycopg2.connect(
dbname="AI",
user="postgres",
password="Ikione@123/",
host="123.201.192.233",
port="30432"
)
cursor = conn.cursor()
print("🔍 Fetching Metadata with:")
print("Country:", extracted_info["Country"])
print("Denomination:", extracted_info["Value"])
print("Serial Number:", extracted_info["Serial Number"])
print("Bank:", extracted_info["Bank"])
query = """
SELECT "Country", "Currency", "Issued by", "Date", "Remark", "Material",
"Catalogue Pick", "Sub-Catalogue", "Description"
FROM "AI"."Finland"
WHERE
REPLACE(LOWER("Serial Number"), '-', '') = %s
OR REPLACE(LOWER("Serial Number"), ' ', '') = %s
OR LOWER("Serial Number") ILIKE %s
"""
serial_lower = extracted_info["Serial Number"].lower().replace("-", "").replace(" ", "")
serial_like = f"%{serial_lower}%"
cursor.execute(query, (serial_lower, serial_lower, serial_like))
# extracted_info["Country"].lower(),
# extracted_info["Value"],
# extracted_info["Bank"].lower(),
#extracted_info["Serial Number"]
results = cursor.fetchall()
return results if results else [["No match", "", "", "", "", "", "", "", ""]]
except Exception as e:
return [[f"Error: {e}", "", "", "", "", "", "", "", ""]]
finally:
try:
cursor.close()
conn.close()
except:
pass
fetch_btn.click(fn=fetch_metadata, outputs=metadata_table)
# Optional Tab 3: History
import matplotlib.pyplot as plt
import io
# Simulated detection history for demo (You can load from a file or DB)
detection_history = [
["img1.jpg", "India", "100", "A1234567", "Reserve Bank of India"],
["img2.jpg", "USA", "50", "Not found", "Federal Reserve"],
["img3.jpg", "Germany", "Not found", "C9876543", "Not found"],
["img4.jpg", "Not found", "500", "Not found", "Bank of England"]
]
def history_ui():
with gr.Tab("📖 View History"):
gr.Markdown("## 🕓 Detection History")
history_table = gr.Dataframe(
value=detection_history,
headers=["Image", "Country", "Value", "Serial Number", "Bank"],
label="🔍 All Detected Notes"
)
refresh = gr.Button("🔁 Refresh History")
# 📈 Chart: Match vs Unmatched
def generate_charts():
total = len(detection_history)
matched = sum(1 for note in detection_history if "Not found" not in note)
unmatched = total - matched
# Pie chart
pie_fig, ax1 = plt.subplots()
ax1.pie([matched, unmatched], labels=["Matched", "Unmatched"], autopct='%1.1f%%', colors=["green", "red"])
ax1.set_title("Detection Summary")
# Field-wise bar chart
fields = ["Country", "Value", "Serial Number", "Bank"]
match_counts = []
for i in range(1, 5): # Skip image column
count = sum(1 for note in detection_history if note[i] != "Not found")
match_counts.append(count)
bar_fig, ax2 = plt.subplots()
ax2.bar(fields, match_counts, color='blue')
ax2.set_title("Field Match Count")
ax2.set_ylabel("Detected Count")
return pie_fig, bar_fig
pie_chart = gr.Plot()
bar_chart = gr.Plot()
refresh.click(fn=generate_charts, outputs=[pie_chart, bar_chart])
gr.Markdown("### 📊 Detection Quality Summary")
with gr.Row():
pie_chart = gr.Plot()
bar_chart = gr.Plot()
# pie_chart.render()
# bar_chart.render()
# pie_chart.render()
# bar_chart.render()
#def history_ui():
# with gr.Tab("📖 View History"):
# gr.Markdown("## 🕓 Detection History")
# history_table = gr.Dataframe(headers=["Image", "Country", "Value", "Serial Number", "Bank"])
# refresh = gr.Button("Refresh History")
# def load_history():
# return [["sample.jpg", "UK", "£50", "AA40925300", "Bank of England"]]
# refresh.click(fn=load_history, outputs=history_table)
# 🧷 Launch Gradio App
with gr.Blocks() as demo:
detect_ui()
metadata_ui()
history_ui()
#demo = gr.Interface(fn=detect_ui, inputs="image_input, mirror_toggle", outputs="image_output, text_output")
demo.launch(share=True)