File size: 12,456 Bytes
d688754
 
 
 
 
 
 
 
 
 
ab80c01
d688754
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04835e2
 
 
 
 
 
d688754
04835e2
d688754
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4e4e22
 
 
 
469a3b2
d4e4e22
d688754
a6ccfb0
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
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)