meraj12 commited on
Commit
0515ad4
·
verified ·
1 Parent(s): a612cca

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -53
app.py CHANGED
@@ -5,112 +5,113 @@ 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
- import torch
13
- from torchvision.models.mobilenetv2 import MobileNetV2
14
  from gtts import gTTS
15
  import os
16
 
17
- # Create history folder if it doesn't exist
18
  os.makedirs("history", exist_ok=True)
19
-
20
- # ========== TTS ENGINE ==========
21
-
22
- def speak_streamlit(text):
23
- tts = gTTS(text=text, lang='en')
24
- tts.save("temp.mp3")
25
- st.audio("temp.mp3", format="audio/mp3")
26
-
27
-
28
- # ========== CURRENCY TYPE ==========
29
- currency_type = st.selectbox("Select currency type:", ["PKR (Pakistani Rupees)", "USD (US Dollars)", "INR (Indian Rupees)"])
30
-
31
- # For now, only PKR model is supported
32
- if "PKR" not in currency_type:
33
- st.warning("Currently only Pakistani Rupees (PKR) is supported. Other currencies coming soon!")
34
- st.stop()
35
-
36
- # ========== LOAD MODEL ==========
37
-
38
  torch.serialization.add_safe_globals({'MobileNetV2': MobileNetV2})
39
 
 
40
  model = torch.load("pkr_currency_classifier.pt", map_location='cpu', weights_only=False)
41
  model.eval()
 
42
 
43
-
44
- # ========== TRANSFORMS ==========
45
  transform = transforms.Compose([
46
  transforms.Resize((224, 224)),
47
  transforms.ToTensor()
48
  ])
49
 
50
- # ========== PREDICT ==========
51
- prediction = predict(image)
 
 
 
52
 
53
- if prediction.lower() == "not currency":
54
- st.warning("This image does not appear to be a currency note.")
55
- speak("This is not a currency note.")
56
- else:
57
- st.success(f"Prediction: **{prediction}**")
58
- speak(f"This is a {prediction} currency note.")
59
- save_history(image, prediction) # Only save if it's currency
60
 
61
- # ========== SAVE HISTORY ==========
62
  def save_history(image, result):
63
- os.makedirs("history", exist_ok=True)
64
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
65
  image.save(f"history/{timestamp}_{result}.png")
66
 
67
- # ========== MAIN UI ==========
 
68
  st.title("💵 Currency Authenticity Detector")
69
  st.subheader("Check if your currency is real or fake!")
70
 
 
 
 
 
 
 
71
  option = st.radio("Choose method:", ["Upload Image", "Scan via Camera"])
72
 
 
73
  if option == "Upload Image":
74
  uploaded_file = st.file_uploader("Upload a currency image", type=["jpg", "jpeg", "png"])
75
  if uploaded_file:
76
  image = Image.open(uploaded_file).convert("RGB")
77
  st.image(image, caption="Uploaded Image", use_column_width=True)
78
  prediction = predict(image)
79
- st.success(f"Prediction: **{prediction}**")
80
- speak_streamlit(f"This is a {prediction}")
81
- save_history(image, prediction)
82
 
 
 
 
 
 
 
 
 
 
83
  elif option == "Scan via Camera":
84
- st.write("Hold currency in front of your webcam and press 'Start Camera'.")
85
  if st.button("Start Camera"):
86
  cap = cv2.VideoCapture(0)
87
  stframe = st.empty()
88
  result_box = st.empty()
89
- stop = st.button("Stop Camera")
90
 
91
- while cap.isOpened() and not stop:
 
 
92
  ret, frame = cap.read()
93
  if not ret:
94
  break
95
  frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
96
  pil_image = Image.fromarray(frame_rgb)
97
-
98
- # Show frame
99
  stframe.image(pil_image, channels="RGB", use_column_width=True)
100
 
101
- # Predict
102
  prediction = predict(pil_image)
103
  result_box.markdown(f"### Prediction: **{prediction}**")
104
- speak(f"This is a {prediction}")
105
- save_history(pil_image, prediction)
 
 
 
 
 
 
 
106
 
107
  cap.release()
108
  stframe.empty()
109
  result_box.empty()
110
 
111
- # ========== VIEW HISTORY ==========
112
  if st.checkbox("📁 Show Scan History"):
113
  st.write("Previously scanned images:")
114
  for img_file in sorted(os.listdir("history"))[::-1][:5]:
115
- st.image(f"history/{img_file}", caption=img_file)
116
- st.write("Design by MERAJ GRAPHICS")
 
 
 
5
  from PIL import Image
6
  import numpy as np
7
  import cv2
 
 
 
8
  from datetime import datetime
9
+ from torchvision.models.mobilenetv2 import MobileNetV2
 
10
  from gtts import gTTS
11
  import os
12
 
13
+ # ====== Setup ======
14
  os.makedirs("history", exist_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  torch.serialization.add_safe_globals({'MobileNetV2': MobileNetV2})
16
 
17
+ # Load model
18
  model = torch.load("pkr_currency_classifier.pt", map_location='cpu', weights_only=False)
19
  model.eval()
20
+ class_names = ['Fake', 'Not Currency', 'Real']
21
 
22
+ # Transforms
 
23
  transform = transforms.Compose([
24
  transforms.Resize((224, 224)),
25
  transforms.ToTensor()
26
  ])
27
 
28
+ # Text-to-speech
29
+ def speak_streamlit(text):
30
+ tts = gTTS(text=text, lang='en')
31
+ tts.save("temp.mp3")
32
+ st.audio("temp.mp3", format="audio/mp3")
33
 
34
+ # Prediction function
35
+ def predict(image):
36
+ img = transform(image).unsqueeze(0)
37
+ with torch.no_grad():
38
+ outputs = model(img)
39
+ _, predicted = torch.max(outputs, 1)
40
+ return class_names[predicted.item()]
41
 
42
+ # Save history
43
  def save_history(image, result):
 
44
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
45
  image.save(f"history/{timestamp}_{result}.png")
46
 
47
+ # ====== UI ======
48
+ st.set_page_config(page_title="Currency Detector", page_icon="💵")
49
  st.title("💵 Currency Authenticity Detector")
50
  st.subheader("Check if your currency is real or fake!")
51
 
52
+ currency_type = st.selectbox("Select currency type:", ["PKR (Pakistani Rupees)", "USD (US Dollars)", "INR (Indian Rupees)"])
53
+ if "PKR" not in currency_type:
54
+ st.warning("Currently only Pakistani Rupees (PKR) is supported. Other currencies coming soon!")
55
+ st.stop()
56
+
57
+ # Choose input method
58
  option = st.radio("Choose method:", ["Upload Image", "Scan via Camera"])
59
 
60
+ # ===== Upload Mode =====
61
  if option == "Upload Image":
62
  uploaded_file = st.file_uploader("Upload a currency image", type=["jpg", "jpeg", "png"])
63
  if uploaded_file:
64
  image = Image.open(uploaded_file).convert("RGB")
65
  st.image(image, caption="Uploaded Image", use_column_width=True)
66
  prediction = predict(image)
 
 
 
67
 
68
+ if prediction == "Not Currency":
69
+ st.warning("⚠️ This image does not appear to be a currency note.")
70
+ speak_streamlit("This is not a currency note.")
71
+ else:
72
+ st.success(f"Prediction: **{prediction}**")
73
+ speak_streamlit(f"This is a {prediction} currency note.")
74
+ save_history(image, prediction)
75
+
76
+ # ===== Camera Mode =====
77
  elif option == "Scan via Camera":
78
+ st.write("Hold the currency in front of your webcam and press Start.")
79
  if st.button("Start Camera"):
80
  cap = cv2.VideoCapture(0)
81
  stframe = st.empty()
82
  result_box = st.empty()
 
83
 
84
+ stop_button = st.button("Stop Camera")
85
+
86
+ while cap.isOpened():
87
  ret, frame = cap.read()
88
  if not ret:
89
  break
90
  frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
91
  pil_image = Image.fromarray(frame_rgb)
 
 
92
  stframe.image(pil_image, channels="RGB", use_column_width=True)
93
 
 
94
  prediction = predict(pil_image)
95
  result_box.markdown(f"### Prediction: **{prediction}**")
96
+
97
+ if prediction != "Not Currency":
98
+ speak_streamlit(f"This is a {prediction} currency note.")
99
+ save_history(pil_image, prediction)
100
+ else:
101
+ speak_streamlit("This is not a currency note.")
102
+
103
+ if stop_button:
104
+ break
105
 
106
  cap.release()
107
  stframe.empty()
108
  result_box.empty()
109
 
110
+ # ===== History =====
111
  if st.checkbox("📁 Show Scan History"):
112
  st.write("Previously scanned images:")
113
  for img_file in sorted(os.listdir("history"))[::-1][:5]:
114
+ st.image(f"history/{img_file}", caption=img_file, width=200)
115
+
116
+ st.markdown("---")
117
+ st.markdown("👨‍💻 Designed by MERAJ GRAPHICS")