parass13 commited on
Commit
a2737e5
Β·
verified Β·
1 Parent(s): ddc8227

Update dashboard.py

Browse files
Files changed (1) hide show
  1. dashboard.py +70 -45
dashboard.py CHANGED
@@ -9,10 +9,10 @@ import tensorflow as tf
9
  import os
10
  import warnings
11
 
12
- # Import pages
13
  from pages import about, community, user_guide
14
 
15
- # Suppress logs and warnings
16
  os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
17
  warnings.filterwarnings("ignore")
18
  np.seterr(all='ignore')
@@ -20,12 +20,11 @@ np.seterr(all='ignore')
20
  # Load deepfake model
21
  deepfake_model = tf.keras.models.load_model("model_15_64.h5")
22
 
23
- # SQLite setup
24
  db_path = os.path.abspath("users.db")
25
  print(f"βœ… Using database at: {db_path}")
26
  conn = sqlite3.connect(db_path, check_same_thread=False)
27
  cursor = conn.cursor()
28
-
29
  cursor.execute('''
30
  CREATE TABLE IF NOT EXISTS user_details (
31
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -38,13 +37,14 @@ CREATE TABLE IF NOT EXISTS user_details (
38
  ''')
39
  conn.commit()
40
 
41
- # Utilities
42
  def is_valid_email(email):
43
  return re.match(r"[^@]+@[^@]+\.[^@]+", email)
44
 
45
  def is_valid_phone(phone):
46
  return re.match(r"^[0-9]{10}$", phone)
47
 
 
48
  def preprocess_image(image):
49
  image = np.array(image)
50
  image = cv2.resize(image, (128, 128))
@@ -56,78 +56,55 @@ def predict_image(image):
56
  prediction = deepfake_model.predict(preprocessed)[0][0]
57
  return "βœ… Real Image" if prediction >= 0.5 else "⚠️ Fake Image"
58
 
 
59
  def register_user(name, phone, email, password):
60
  if not is_valid_email(email):
61
- return "❌ Invalid email", False
62
  if not is_valid_phone(phone):
63
- return "❌ Phone must be 10 digits", False
64
-
65
  cursor.execute("SELECT * FROM user_details WHERE EMAIL = ?", (email,))
66
  if cursor.fetchone():
67
- return "⚠️ Email already registered", False
68
-
69
  hashed_pw = bcrypt.hashpw(password.encode(), bcrypt.gensalt())
70
  cursor.execute("INSERT INTO user_details (NAME, PHONE, EMAIL, GENDER, PASSWORD) VALUES (?, ?, ?, ?, ?)",
71
  (name, phone, email, "U", hashed_pw))
72
  conn.commit()
73
  print(f"βœ… Registered new user: {email}")
74
- return "βœ… Registration successful! Please log in.", False
75
 
76
  def login_user(email, password):
77
  cursor.execute("SELECT PASSWORD FROM user_details WHERE EMAIL = ?", (email,))
78
  result = cursor.fetchone()
79
- if result and bcrypt.checkpw(password.encode(), result[0]):
80
- return "βœ… Login successful!", True
81
- return "❌ Invalid credentials", False
82
 
83
-
84
- # Gradio App
85
  with gr.Blocks() as demo:
86
- session = gr.State(value=False) # Stores login state (True/False)
 
87
 
88
  with gr.Tabs() as tabs:
89
  with gr.Tab("πŸ” Login"):
90
  gr.Markdown("### Login or Sign Up")
91
 
92
- status = gr.Textbox(label="Status", interactive=False)
93
  name = gr.Textbox(label="Name (Sign Up Only)")
94
  phone = gr.Textbox(label="Phone (Sign Up Only)")
95
  email = gr.Textbox(label="Email")
96
  password = gr.Textbox(label="Password", type="password")
97
  login_btn = gr.Button("Login")
98
  signup_btn = gr.Button("Sign Up")
 
99
 
100
- def handle_login(e, p):
101
- msg, ok = login_user(e, p)
102
- return msg, ok
103
-
104
- def handle_signup(n, ph, e, p):
105
- msg, ok = register_user(n, ph, e, p)
106
- return msg, ok
107
-
108
- login_btn.click(handle_login, [email, password], [status, session])
109
- signup_btn.click(handle_signup, [name, phone, email, password], [status, session])
110
-
111
- with gr.Tab("πŸ§ͺ Detect Deepfake") as detect_tab:
112
- with gr.Column(visible=False) as detection_content:
113
  gr.Markdown("### Upload an Image to Detect Deepfake")
114
  image_input = gr.Image(type="pil")
115
  result = gr.Textbox(label="Prediction Result")
116
  predict_btn = gr.Button("Predict")
117
  predict_btn.click(fn=predict_image, inputs=image_input, outputs=result)
118
-
119
- # Show warning if not logged in
120
- with gr.Column(visible=True) as login_prompt:
121
- warning_text = gr.Markdown("⚠️ Please login or sign up to access deepfake detection.")
122
-
123
- def toggle_tab(logged_in):
124
- return (
125
- gr.update(visible=logged_in), # detection_content
126
- gr.update(visible=not logged_in), # login_prompt
127
- )
128
-
129
- # Toggle detection tab visibility based on login state
130
- session.change(fn=toggle_tab, inputs=session, outputs=[detection_content, login_prompt])
131
 
132
  with gr.Tab("ℹ️ About"):
133
  about.layout()
@@ -138,6 +115,54 @@ with gr.Blocks() as demo:
138
  with gr.Tab("πŸ“˜ User Guide"):
139
  user_guide.layout()
140
 
141
- # Launch App
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  if __name__ == "__main__":
143
  demo.launch()
 
9
  import os
10
  import warnings
11
 
12
+ # Import content pages
13
  from pages import about, community, user_guide
14
 
15
+ # Suppress TensorFlow and warning logs
16
  os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
17
  warnings.filterwarnings("ignore")
18
  np.seterr(all='ignore')
 
20
  # Load deepfake model
21
  deepfake_model = tf.keras.models.load_model("model_15_64.h5")
22
 
23
+ # Database setup
24
  db_path = os.path.abspath("users.db")
25
  print(f"βœ… Using database at: {db_path}")
26
  conn = sqlite3.connect(db_path, check_same_thread=False)
27
  cursor = conn.cursor()
 
28
  cursor.execute('''
29
  CREATE TABLE IF NOT EXISTS user_details (
30
  id INTEGER PRIMARY KEY AUTOINCREMENT,
 
37
  ''')
38
  conn.commit()
39
 
40
+ # Validators
41
  def is_valid_email(email):
42
  return re.match(r"[^@]+@[^@]+\.[^@]+", email)
43
 
44
  def is_valid_phone(phone):
45
  return re.match(r"^[0-9]{10}$", phone)
46
 
47
+ # Image preprocessing
48
  def preprocess_image(image):
49
  image = np.array(image)
50
  image = cv2.resize(image, (128, 128))
 
56
  prediction = deepfake_model.predict(preprocessed)[0][0]
57
  return "βœ… Real Image" if prediction >= 0.5 else "⚠️ Fake Image"
58
 
59
+ # Auth logic
60
  def register_user(name, phone, email, password):
61
  if not is_valid_email(email):
62
+ return "❌ Invalid email"
63
  if not is_valid_phone(phone):
64
+ return "❌ Phone must be 10 digits"
 
65
  cursor.execute("SELECT * FROM user_details WHERE EMAIL = ?", (email,))
66
  if cursor.fetchone():
67
+ return "⚠️ Email already registered"
 
68
  hashed_pw = bcrypt.hashpw(password.encode(), bcrypt.gensalt())
69
  cursor.execute("INSERT INTO user_details (NAME, PHONE, EMAIL, GENDER, PASSWORD) VALUES (?, ?, ?, ?, ?)",
70
  (name, phone, email, "U", hashed_pw))
71
  conn.commit()
72
  print(f"βœ… Registered new user: {email}")
73
+ return "βœ… Registration successful! Please log in."
74
 
75
  def login_user(email, password):
76
  cursor.execute("SELECT PASSWORD FROM user_details WHERE EMAIL = ?", (email,))
77
  result = cursor.fetchone()
78
+ if result and bcrypt.checkpw(password.encode(), result[0] if isinstance(result[0], bytes) else result[0].encode()):
79
+ return True
80
+ return False
81
 
82
+ # Gradio UI
 
83
  with gr.Blocks() as demo:
84
+ is_logged_in = gr.State(False)
85
+ tab_index = gr.State(0)
86
 
87
  with gr.Tabs() as tabs:
88
  with gr.Tab("πŸ” Login"):
89
  gr.Markdown("### Login or Sign Up")
90
 
 
91
  name = gr.Textbox(label="Name (Sign Up Only)")
92
  phone = gr.Textbox(label="Phone (Sign Up Only)")
93
  email = gr.Textbox(label="Email")
94
  password = gr.Textbox(label="Password", type="password")
95
  login_btn = gr.Button("Login")
96
  signup_btn = gr.Button("Sign Up")
97
+ message_output = gr.Markdown("", visible=False)
98
 
99
+ with gr.Tab("πŸ§ͺ Detect Deepfake", visible=False) as detect_tab:
100
+ detect_area = gr.Column(visible=True)
101
+ with detect_area:
 
 
 
 
 
 
 
 
 
 
102
  gr.Markdown("### Upload an Image to Detect Deepfake")
103
  image_input = gr.Image(type="pil")
104
  result = gr.Textbox(label="Prediction Result")
105
  predict_btn = gr.Button("Predict")
106
  predict_btn.click(fn=predict_image, inputs=image_input, outputs=result)
107
+ detect_warning = gr.Markdown("❌ Please log in to use this feature.", visible=False)
 
 
 
 
 
 
 
 
 
 
 
 
108
 
109
  with gr.Tab("ℹ️ About"):
110
  about.layout()
 
115
  with gr.Tab("πŸ“˜ User Guide"):
116
  user_guide.layout()
117
 
118
+ with gr.Tab("πŸšͺ Logout", visible=False) as logout_tab:
119
+ gr.Markdown("You are logged in.")
120
+ logout_btn = gr.Button("Logout")
121
+
122
+ # Handlers
123
+ def handle_login(email, password):
124
+ success = login_user(email, password)
125
+ return (
126
+ "βœ… Login successful!" if success else "❌ Invalid credentials",
127
+ success,
128
+ 1 if success else 0,
129
+ gr.update(visible=success),
130
+ gr.update(visible=not success),
131
+ gr.update(visible=success),
132
+ gr.update(visible=True)
133
+ )
134
+
135
+ def handle_signup(name, phone, email, password):
136
+ msg = register_user(name, phone, email, password)
137
+ return gr.update(value=msg, visible=True)
138
+
139
+ def handle_logout():
140
+ return (
141
+ False,
142
+ 0,
143
+ gr.update(visible=False),
144
+ gr.update(visible=True),
145
+ gr.update(visible=False),
146
+ gr.update(visible=False)
147
+ )
148
+
149
+ login_btn.click(
150
+ fn=handle_login,
151
+ inputs=[email, password],
152
+ outputs=[message_output, is_logged_in, tab_index, detect_area, detect_warning, logout_tab, message_output]
153
+ )
154
+
155
+ signup_btn.click(
156
+ fn=handle_signup,
157
+ inputs=[name, phone, email, password],
158
+ outputs=[message_output]
159
+ )
160
+
161
+ logout_btn.click(
162
+ fn=handle_logout,
163
+ inputs=[],
164
+ outputs=[is_logged_in, tab_index, detect_area, detect_warning, logout_tab, message_output]
165
+ )
166
+
167
  if __name__ == "__main__":
168
  demo.launch()