parass13 commited on
Commit
6be0e8c
Β·
verified Β·
1 Parent(s): 78f1dba

Update dashboard.py

Browse files
Files changed (1) hide show
  1. dashboard.py +85 -57
dashboard.py CHANGED
@@ -1,4 +1,5 @@
1
  import gradio as gr
 
2
  import re
3
  import bcrypt
4
  import numpy as np
@@ -7,22 +8,9 @@ from PIL import Image
7
  import tensorflow as tf
8
  import os
9
  import warnings
10
- import requests
11
- import json
12
 
13
  from pages import about, community, user_guide
14
 
15
- # --- Config ---
16
- SUPABASE_URL = "https://fpbuhzbdtzwomjwytqul.supabase.co"
17
- SUPABASE_API_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImZwYnVoemJkdHp3b21qd3l0cXVsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTE5NDk3NzYsImV4cCI6MjA2NzUyNTc3Nn0.oAa2TNNPQMyOGk63AOMZ7XKcwYvy5m-xoSWyvMZd6FY"
18
- SUPABASE_TABLE = "user_details"
19
-
20
- headers = {
21
- "apikey": SUPABASE_API_KEY,
22
- "Authorization": f"Bearer {SUPABASE_API_KEY}",
23
- "Content-Type": "application/json"
24
- }
25
-
26
  # --- Setup ---
27
  os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
28
  warnings.filterwarnings("ignore")
@@ -44,6 +32,22 @@ with warnings.catch_warnings():
44
  warnings.simplefilter("ignore")
45
  deepfake_model = tf.keras.models.load_model(MODEL_PATH)
46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  # --- Helpers ---
48
  def is_valid_email(email): return re.match(r"[^@]+@[^@]+\.[^@]+", email)
49
  def is_valid_phone(phone): return re.match(r"^[0-9]{10}$", phone)
@@ -63,43 +67,44 @@ def predict_image(image):
63
  label = "βœ… Real Image" if prediction >= 0.5 else "⚠️ Fake Image"
64
  return f"{label} (Confidence: {confidence:.2%})"
65
 
66
- def register_user(name, phone, email, password):
67
- if not all([name, phone, email, password]): return "❌ All fields are required for signup."
68
  if not is_valid_email(email): return "❌ Invalid email format."
69
  if not is_valid_phone(phone): return "❌ Phone must be 10 digits."
70
-
71
- # Check if user exists
72
- query_url = f"{SUPABASE_URL}/rest/v1/{SUPABASE_TABLE}?email=eq.{email}"
73
- r = requests.get(query_url, headers=headers)
74
- if r.status_code == 200 and len(r.json()) > 0:
75
- return "⚠️ Email already registered."
76
-
77
- hashed_pw = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode()
78
- data = {
79
- "name": name,
80
- "phone": phone,
81
- "email": email,
82
- "gender": "U",
83
- "password": hashed_pw
84
- }
85
- r = requests.post(f"{SUPABASE_URL}/rest/v1/{SUPABASE_TABLE}", headers=headers, data=json.dumps(data))
86
- return "βœ… Registration successful! Please log in." if r.status_code == 201 else "❌ Error during registration."
87
 
88
  def login_user(email, password):
89
- url = f"{SUPABASE_URL}/rest/v1/{SUPABASE_TABLE}?email=eq.{email}"
90
- r = requests.get(url, headers=headers)
91
- if r.status_code == 200 and r.json():
92
- stored_hash = r.json()[0]["password"]
93
- return bcrypt.checkpw(password.encode(), stored_hash.encode())
94
- return False
 
 
 
 
 
95
 
96
  # --- UI ---
97
- with gr.Blocks(theme=gr.themes.Soft(), title="Deepfake Detector") as demo:
98
  is_logged_in = gr.State(False)
99
 
100
- LOGIN_TAB_NAME = "πŸ” Login"
101
- DETECT_TAB_NAME = "πŸ§ͺ Detect Deepfake"
102
- ABOUT_TAB_NAME = "ℹ️ About"
103
  COMMUNITY_TAB_NAME = "🌐 Community"
104
  GUIDE_TAB_NAME = "πŸ“˜ User Guide"
105
 
@@ -107,23 +112,25 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Deepfake Detector") as demo:
107
  with gr.Tab(LOGIN_TAB_NAME) as login_tab:
108
  with gr.Row():
109
  with gr.Column(scale=1):
110
- gr.Markdown("## Welcome!", "Login to access the detector, or sign up for a new account.")
 
111
  with gr.Column(scale=2):
112
- gr.Markdown("### Login or Sign Up")
113
  message_output = gr.Markdown(visible=False)
114
- email_login = gr.Textbox(label="Email")
115
- password_login = gr.Textbox(label="Password", type="password")
116
  login_btn = gr.Button("Login", variant="primary")
117
  with gr.Accordion("New User? Click here to Sign Up", open=False) as signup_accordion:
118
  name_signup = gr.Textbox(label="Name")
119
  phone_signup = gr.Textbox(label="Phone (10 digits)")
120
  email_signup = gr.Textbox(label="Email")
 
121
  password_signup = gr.Textbox(label="Create Password", type="password")
122
  signup_btn = gr.Button("Sign Up")
123
 
124
  with gr.Tab(DETECT_TAB_NAME, visible=False) as detect_tab:
125
  with gr.Row():
126
- gr.Markdown("## Deepfake Detector")
127
  logout_btn = gr.Button("Logout")
128
  with gr.Row():
129
  image_input = gr.Image(type="pil", label="Upload Image", scale=1)
@@ -135,6 +142,7 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Deepfake Detector") as demo:
135
  with gr.Tab(COMMUNITY_TAB_NAME): community.layout()
136
  with gr.Tab(GUIDE_TAB_NAME): user_guide.layout()
137
 
 
138
  def update_ui_on_auth_change(logged_in_status):
139
  if logged_in_status:
140
  return (
@@ -158,20 +166,40 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Deepfake Detector") as demo:
158
  return False, gr.update(value="❌ Invalid email or password.", visible=True)
159
 
160
  def handle_logout():
161
- return False, "", ""
162
 
163
- def handle_signup(name, phone, email, password):
164
- msg = register_user(name, phone, email, password)
165
  if msg.startswith("βœ…"):
166
- return gr.update(value=msg, visible=True), "", "", "", "", gr.update(open=False)
167
  else:
168
- return gr.update(value=msg, visible=True), name, phone, email, password, gr.update(open=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
 
170
- login_btn.click(fn=handle_login, inputs=[email_login, password_login], outputs=[is_logged_in, message_output])
171
- logout_btn.click(fn=handle_logout, inputs=[], outputs=[is_logged_in, email_login, password_login])
172
- is_logged_in.change(fn=update_ui_on_auth_change, inputs=is_logged_in, outputs=[login_tab, detect_tab, tabs, message_output])
173
- signup_btn.click(fn=handle_signup, inputs=[name_signup, phone_signup, email_signup, password_signup],
174
- outputs=[message_output, name_signup, phone_signup, email_signup, password_signup, signup_accordion])
175
  predict_btn.click(fn=predict_image, inputs=image_input, outputs=result)
176
 
177
  if __name__ == "__main__":
 
1
  import gradio as gr
2
+ import sqlite3
3
  import re
4
  import bcrypt
5
  import numpy as np
 
8
  import tensorflow as tf
9
  import os
10
  import warnings
 
 
11
 
12
  from pages import about, community, user_guide
13
 
 
 
 
 
 
 
 
 
 
 
 
14
  # --- Setup ---
15
  os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
16
  warnings.filterwarnings("ignore")
 
32
  warnings.simplefilter("ignore")
33
  deepfake_model = tf.keras.models.load_model(MODEL_PATH)
34
 
35
+ # --- DB ---
36
+ DB_PATH = os.path.abspath("users.db")
37
+ with sqlite3.connect(DB_PATH) as conn:
38
+ cursor = conn.cursor()
39
+ cursor.execute('''
40
+ CREATE TABLE IF NOT EXISTS user_details (
41
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
42
+ NAME TEXT NOT NULL,
43
+ PHONE TEXT NOT NULL,
44
+ EMAIL TEXT UNIQUE NOT NULL,
45
+ GENDER TEXT,
46
+ PASSWORD BLOB NOT NULL
47
+ )
48
+ ''')
49
+ conn.commit()
50
+
51
  # --- Helpers ---
52
  def is_valid_email(email): return re.match(r"[^@]+@[^@]+\.[^@]+", email)
53
  def is_valid_phone(phone): return re.match(r"^[0-9]{10}$", phone)
 
67
  label = "βœ… Real Image" if prediction >= 0.5 else "⚠️ Fake Image"
68
  return f"{label} (Confidence: {confidence:.2%})"
69
 
70
+ def register_user(name, phone, email, gender, password):
71
+ if not all([name, phone, email, gender, password]): return "❌ All fields are required for signup."
72
  if not is_valid_email(email): return "❌ Invalid email format."
73
  if not is_valid_phone(phone): return "❌ Phone must be 10 digits."
74
+ try:
75
+ with sqlite3.connect(DB_PATH) as conn:
76
+ cursor = conn.cursor()
77
+ cursor.execute("SELECT * FROM user_details WHERE EMAIL = ?", (email,))
78
+ if cursor.fetchone(): return "⚠️ Email already registered."
79
+ hashed_pw = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
80
+ cursor.execute("INSERT INTO user_details (NAME, PHONE, EMAIL, GENDER, PASSWORD) VALUES (?, ?, ?, ?, ?)",
81
+ (name, phone, email, gender, hashed_pw))
82
+ conn.commit()
83
+ return "βœ… Registration successful! Please log in."
84
+ except sqlite3.Error as e:
85
+ print(f"Database error: {e}")
86
+ return "❌ A database error occurred."
 
 
 
 
87
 
88
  def login_user(email, password):
89
+ if not email or not password: return False
90
+ try:
91
+ with sqlite3.connect(DB_PATH) as conn:
92
+ cursor = conn.cursor()
93
+ cursor.execute("SELECT PASSWORD FROM user_details WHERE EMAIL = ?", (email,))
94
+ result = cursor.fetchone()
95
+ if result and bcrypt.checkpw(password.encode('utf-8'), result[0]): return True
96
+ return False
97
+ except sqlite3.Error as e:
98
+ print(f"Database error during login: {e}")
99
+ return False
100
 
101
  # --- UI ---
102
+ with gr.Blocks(theme=gr.themes.Soft(), title="VerifiAI - Deepfake Detection") as demo:
103
  is_logged_in = gr.State(False)
104
 
105
+ LOGIN_TAB_NAME = "πŸ” VerifiAI Login"
106
+ DETECT_TAB_NAME = "πŸ§ͺ Run Detection"
107
+ ABOUT_TAB_NAME = "ℹ️ About VerifiAI"
108
  COMMUNITY_TAB_NAME = "🌐 Community"
109
  GUIDE_TAB_NAME = "πŸ“˜ User Guide"
110
 
 
112
  with gr.Tab(LOGIN_TAB_NAME) as login_tab:
113
  with gr.Row():
114
  with gr.Column(scale=1):
115
+ gr.Markdown("## Welcome to VerifiAI!")
116
+ gr.Markdown("*AI-powered truth detection for the digital age.*")
117
  with gr.Column(scale=2):
118
+ gr.Markdown("### Access VerifiAI")
119
  message_output = gr.Markdown(visible=False)
120
+ email_login = gr.Textbox(label="Email", elem_id="login_email")
121
+ password_login = gr.Textbox(label="Password", type="password", elem_id="login_pass")
122
  login_btn = gr.Button("Login", variant="primary")
123
  with gr.Accordion("New User? Click here to Sign Up", open=False) as signup_accordion:
124
  name_signup = gr.Textbox(label="Name")
125
  phone_signup = gr.Textbox(label="Phone (10 digits)")
126
  email_signup = gr.Textbox(label="Email")
127
+ gender_signup = gr.Dropdown(label="Gender", choices=["Male", "Female", "Other"])
128
  password_signup = gr.Textbox(label="Create Password", type="password")
129
  signup_btn = gr.Button("Sign Up")
130
 
131
  with gr.Tab(DETECT_TAB_NAME, visible=False) as detect_tab:
132
  with gr.Row():
133
+ gr.Markdown("## VerifiAI Deepfake Detector")
134
  logout_btn = gr.Button("Logout")
135
  with gr.Row():
136
  image_input = gr.Image(type="pil", label="Upload Image", scale=1)
 
142
  with gr.Tab(COMMUNITY_TAB_NAME): community.layout()
143
  with gr.Tab(GUIDE_TAB_NAME): user_guide.layout()
144
 
145
+ # --- Events ---
146
  def update_ui_on_auth_change(logged_in_status):
147
  if logged_in_status:
148
  return (
 
166
  return False, gr.update(value="❌ Invalid email or password.", visible=True)
167
 
168
  def handle_logout():
169
+ return False, "", "" # logged_in=False, clear email/pass fields
170
 
171
+ def handle_signup(name, phone, email, gender, password):
172
+ msg = register_user(name, phone, email, gender, password)
173
  if msg.startswith("βœ…"):
174
+ return gr.update(value=msg, visible=True), "", "", "", "", "", gr.update(open=False)
175
  else:
176
+ return gr.update(value=msg, visible=True), name, phone, email, gender, password, gr.update(open=True)
177
+
178
+ # --- Event Listeners Wiring ---
179
+ login_btn.click(
180
+ fn=handle_login,
181
+ inputs=[email_login, password_login],
182
+ outputs=[is_logged_in, message_output]
183
+ )
184
+
185
+ logout_btn.click(
186
+ fn=handle_logout,
187
+ inputs=[],
188
+ outputs=[is_logged_in, email_login, password_login]
189
+ )
190
+
191
+ is_logged_in.change(
192
+ fn=update_ui_on_auth_change,
193
+ inputs=is_logged_in,
194
+ outputs=[login_tab, detect_tab, tabs, message_output]
195
+ )
196
+
197
+ signup_btn.click(
198
+ fn=handle_signup,
199
+ inputs=[name_signup, phone_signup, email_signup, gender_signup, password_signup],
200
+ outputs=[message_output, name_signup, phone_signup, email_signup, gender_signup, password_signup, signup_accordion]
201
+ )
202
 
 
 
 
 
 
203
  predict_btn.click(fn=predict_image, inputs=image_input, outputs=result)
204
 
205
  if __name__ == "__main__":