meraj12 commited on
Commit
0765475
·
verified ·
1 Parent(s): 6e30ca5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -23
app.py CHANGED
@@ -1,36 +1,101 @@
1
-
2
  import streamlit as st
3
  import torch
4
- from torchvision import transforms
 
5
  from PIL import Image
6
- import torchvision.models as models
 
 
 
 
 
7
 
8
- # ⚠️ Only do this if you trust the file!
9
- model = torch.load("pkr_currency_classifier.pt", map_location=torch.device('cpu'), weights_only=False)
10
- model.eval()
 
 
11
 
 
 
12
 
13
- # Define transform
 
 
 
 
 
 
 
 
 
 
 
14
  transform = transforms.Compose([
15
  transforms.Resize((224, 224)),
16
- transforms.ToTensor(),
17
- transforms.Normalize([0.485, 0.456, 0.406],
18
- [0.229, 0.224, 0.225])
19
  ])
20
 
21
- st.title("💵 PKR Currency Fake vs Real Detector")
22
- st.write("Upload an image of a Pakistani Rupee note to detect if it's **Real or Fake**.")
 
 
 
 
 
23
 
24
- uploaded_file = st.file_uploader("Choose a currency note image...", type=["jpg", "jpeg", "png"])
 
 
 
 
25
 
26
- if uploaded_file:
27
- image = Image.open(uploaded_file).convert("RGB")
28
- st.image(image, caption="Uploaded Image", use_column_width=True)
29
- st.write("Classifying...")
30
 
31
- img = transform(image).unsqueeze(0)
32
- with torch.no_grad():
33
- outputs = model(img)
34
- _, predicted = torch.max(outputs, 1)
35
- label = "Real" if predicted.item() == 0 else "Fake"
36
- st.success(f"This currency note is **{label}**.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  import torch
3
+ import torchvision.transforms as transforms
4
+ from torchvision import models
5
  from PIL import Image
6
+ import numpy as np
7
+ import cv2
8
+ import tempfile
9
+ import pyttsx3
10
+ import os
11
+ from datetime import datetime
12
 
13
+ # ========== TTS ENGINE ==========
14
+ def speak(text):
15
+ engine = pyttsx3.init()
16
+ engine.say(text)
17
+ engine.runAndWait()
18
 
19
+ # ========== CURRENCY TYPE ==========
20
+ currency_type = st.selectbox("Select currency type:", ["PKR (Pakistani Rupees)", "USD (US Dollars)", "INR (Indian Rupees)"])
21
 
22
+ # For now, only PKR model is supported
23
+ if "PKR" not in currency_type:
24
+ st.warning("Currently only Pakistani Rupees (PKR) is supported. Other currencies coming soon!")
25
+ st.stop()
26
+
27
+ # ========== LOAD MODEL ==========
28
+ model = models.mobilenet_v2(pretrained=False)
29
+ model.classifier[1] = torch.nn.Linear(model.classifier[1].in_features, 2)
30
+ model.load_state_dict(torch.load("pkr_currency_classifier.pt", map_location=torch.device('cpu')))
31
+ model.eval()
32
+
33
+ # ========== TRANSFORMS ==========
34
  transform = transforms.Compose([
35
  transforms.Resize((224, 224)),
36
+ transforms.ToTensor()
 
 
37
  ])
38
 
39
+ # ========== PREDICT ==========
40
+ def predict(image):
41
+ image_tensor = transform(image).unsqueeze(0)
42
+ with torch.no_grad():
43
+ output = model(image_tensor)
44
+ _, pred = torch.max(output, 1)
45
+ return "Real Currency" if pred.item() == 1 else "Fake Currency"
46
 
47
+ # ========== SAVE HISTORY ==========
48
+ def save_history(image, result):
49
+ os.makedirs("history", exist_ok=True)
50
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
51
+ image.save(f"history/{timestamp}_{result}.png")
52
 
53
+ # ========== MAIN UI ==========
54
+ st.title("💵 Currency Authenticity Detector")
55
+ st.subheader("Check if your currency is real or fake!")
 
56
 
57
+ option = st.radio("Choose method:", ["Upload Image", "Scan via Camera"])
58
+
59
+ if option == "Upload Image":
60
+ uploaded_file = st.file_uploader("Upload a currency image", type=["jpg", "jpeg", "png"])
61
+ if uploaded_file:
62
+ image = Image.open(uploaded_file).convert("RGB")
63
+ st.image(image, caption="Uploaded Image", use_column_width=True)
64
+ prediction = predict(image)
65
+ st.success(f"Prediction: **{prediction}**")
66
+ speak(f"This is a {prediction}")
67
+ save_history(image, prediction)
68
+
69
+ elif option == "Scan via Camera":
70
+ st.write("Hold currency in front of your webcam and press 'Start Camera'.")
71
+ if st.button("Start Camera"):
72
+ cap = cv2.VideoCapture(0)
73
+ stframe = st.empty()
74
+ result_box = st.empty()
75
+ stop = st.button("Stop Camera")
76
+
77
+ while cap.isOpened() and not stop:
78
+ ret, frame = cap.read()
79
+ if not ret:
80
+ break
81
+ frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
82
+ pil_image = Image.fromarray(frame_rgb)
83
+
84
+ # Show frame
85
+ stframe.image(pil_image, channels="RGB", use_column_width=True)
86
+
87
+ # Predict
88
+ prediction = predict(pil_image)
89
+ result_box.markdown(f"### Prediction: **{prediction}**")
90
+ speak(f"This is a {prediction}")
91
+ save_history(pil_image, prediction)
92
+
93
+ cap.release()
94
+ stframe.empty()
95
+ result_box.empty()
96
+
97
+ # ========== VIEW HISTORY ==========
98
+ if st.checkbox("📁 Show Scan History"):
99
+ st.write("Previously scanned images:")
100
+ for img_file in sorted(os.listdir("history"))[::-1][:5]:
101
+ st.image(f"history/{img_file}", caption=img_file)