parass13 commited on
Commit
ea2016f
Β·
verified Β·
1 Parent(s): 7e1d568

Update dashboard.py

Browse files
Files changed (1) hide show
  1. dashboard.py +130 -98
dashboard.py CHANGED
@@ -5,14 +5,17 @@ import numpy as np
5
  import cv2
6
  from PIL import Image
7
  import tensorflow as tf
 
8
  import os
9
  import warnings
10
  import requests
11
  import json
12
 
13
- # --- Supabase Configuration ---
 
 
14
  SUPABASE_URL = "https://fpbuhzbdtzwomjwytqul.supabase.co"
15
- SUPABASE_API_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImZwYnVoemJkdHp3b21qd3l0cXVsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTE5NDk3NzYsImV4cCI6MjA2NzUyNTc3Nn0.oAa2TNNPQMyOGk63AOMZ7XKcwYvy5m-xoSWyvMZd6FY"
16
  SUPABASE_TABLE = "user_details"
17
 
18
  headers = {
@@ -21,58 +24,67 @@ headers = {
21
  "Content-Type": "application/json"
22
  }
23
 
 
24
  os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
25
  warnings.filterwarnings("ignore")
26
  np.seterr(all='ignore')
27
 
28
- # --- Model Loading ---
29
  MODEL_PATH = "model_15_64.h5"
30
  if not os.path.exists(MODEL_PATH):
 
31
  dummy_model = tf.keras.Sequential([
32
  tf.keras.layers.Input(shape=(128, 128, 3)),
33
  tf.keras.layers.Flatten(),
34
  tf.keras.layers.Dense(1, activation='sigmoid')
35
  ])
36
- dummy_model.save(MODEL_PATH)
 
 
37
 
38
- deepfake_model = tf.keras.models.load_model(MODEL_PATH)
 
 
39
 
40
- # --- Utils ---
41
  def is_valid_email(email): return re.match(r"[^@]+@[^@]+\.[^@]+", email)
42
  def is_valid_phone(phone): return re.match(r"^[0-9]{10}$", phone)
43
 
44
  def preprocess_image(image):
45
- if image.mode != 'RGB':
46
- image = image.convert('RGB')
47
- img = cv2.resize(np.array(image), (128, 128)).astype(np.float32) / 255.0
48
- return np.expand_dims(img, axis=0)
 
49
 
50
  def predict_image(image):
51
- if image is None: return "❌ Please upload an image."
52
- processed = preprocess_image(image)
53
- prediction = deepfake_model.predict(processed)[0][0]
54
  confidence = prediction if prediction >= 0.5 else 1 - prediction
55
  label = "βœ… Real Image" if prediction >= 0.5 else "⚠️ Fake Image"
56
  return f"{label} (Confidence: {confidence:.2%})"
57
 
58
  def register_user(name, phone, email, gender, password):
59
  if not all([name, phone, email, gender, password]):
60
- return "❌ All fields are required."
61
- if not is_valid_email(email): return "❌ Invalid email."
62
  if not is_valid_phone(phone): return "❌ Phone must be 10 digits."
63
 
64
- query = f"{SUPABASE_URL}/rest/v1/{SUPABASE_TABLE}?email=eq.{email}"
65
- r = requests.get(query, headers=headers)
66
- if r.status_code == 200 and r.json(): return "⚠️ Email already exists."
 
67
 
68
- hashed_pw = bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
69
  data = {
70
- "name": name, "phone": phone, "email": email,
71
- "gender": gender, "password": hashed_pw
 
 
 
72
  }
73
- r = requests.post(f"{SUPABASE_URL}/rest/v1/{SUPABASE_TABLE}",
74
- headers=headers, data=json.dumps(data))
75
- return "βœ… Registration successful!" if r.status_code == 201 else "❌ Registration failed."
76
 
77
  def login_user(email, password):
78
  url = f"{SUPABASE_URL}/rest/v1/{SUPABASE_TABLE}?email=eq.{email}"
@@ -82,98 +94,118 @@ def login_user(email, password):
82
  return bcrypt.checkpw(password.encode(), stored_hash.encode())
83
  return False
84
 
85
- # --- Tab Labels ---
86
  HOME_TAB_NAME = "🏠 Home"
87
  LOGIN_TAB_NAME = "πŸ” Login"
88
- DETECT_TAB_NAME = "πŸ§ͺ Detect"
89
  ABOUT_TAB_NAME = "ℹ️ About"
90
  COMMUNITY_TAB_NAME = "🌐 Community"
91
  GUIDE_TAB_NAME = "πŸ“˜ User Guide"
92
 
93
- # --- App UI ---
94
- with gr.Blocks(title="VerifiAI") as demo:
95
  is_logged_in = gr.State(False)
96
- selected_tab = gr.State(HOME_TAB_NAME)
97
-
98
- # Each tab is a virtual view
99
- with gr.Column(visible=True) as home_view:
100
- gr.Markdown("# πŸ‘οΈβ€πŸ—¨οΈ Welcome to VerifiAI")
101
- gr.Markdown("Upload images to detect deepfakes using AI.")
102
- gr.Button("Go to Login").click(fn=lambda: LOGIN_TAB_NAME, outputs=selected_tab)
103
-
104
- with gr.Column(visible=False) as login_view:
105
- gr.Markdown("## Login")
106
- message_output = gr.Markdown(visible=False)
107
- email_login = gr.Textbox(label="Email")
108
- password_login = gr.Textbox(label="Password", type="password")
109
- login_btn = gr.Button("Login", variant="primary")
110
-
111
- with gr.Accordion("New User? Sign Up", open=False) as signup_accordion:
112
- name_signup = gr.Textbox(label="Name")
113
- phone_signup = gr.Textbox(label="Phone")
114
- email_signup = gr.Textbox(label="Email")
115
- gender_signup = gr.Dropdown(label="Gender", choices=["Male", "Female", "Other"])
116
- password_signup = gr.Textbox(label="Password", type="password")
117
- signup_btn = gr.Button("Sign Up")
118
-
119
- with gr.Column(visible=False) as detect_view:
120
- gr.Markdown("## Deepfake Detector")
121
- logout_btn = gr.Button("Logout")
122
- image_input = gr.Image(type="pil", label="Upload Image")
123
- result = gr.Textbox(label="Result", interactive=False)
124
- predict_btn = gr.Button("Predict")
125
-
126
- with gr.Column(visible=False) as about_view:
127
- gr.Markdown("## ℹ️ About VerifiAI")
128
- gr.Markdown("VerifiAI helps detect deepfake images using AI models.")
129
-
130
- with gr.Column(visible=False) as community_view:
131
- gr.Markdown("## 🌐 Community")
132
- gr.Markdown("Join our research and discussions on AI and ethics.")
133
-
134
- with gr.Column(visible=False) as guide_view:
135
- gr.Markdown("## πŸ“˜ User Guide")
136
- gr.Markdown("1. Login or Sign Up\n2. Upload an image\n3. Click Predict")
137
-
138
- # --- Tab Switching Logic
139
- def switch_tab(tab):
140
- return [gr.update(visible=(tab == t)) for t in [
141
- HOME_TAB_NAME, LOGIN_TAB_NAME, DETECT_TAB_NAME,
142
- ABOUT_TAB_NAME, COMMUNITY_TAB_NAME, GUIDE_TAB_NAME
143
- ]]
144
-
145
- selected_tab.change(fn=switch_tab, inputs=selected_tab,
146
- outputs=[home_view, login_view, detect_view,
147
- about_view, community_view, guide_view])
148
-
149
- # --- Login & Logout
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  def handle_login(email, password):
151
  if login_user(email, password):
152
- return True, gr.update(value="βœ… Login successful!", visible=True), DETECT_TAB_NAME
153
- return False, gr.update(value="❌ Invalid credentials", visible=True), LOGIN_TAB_NAME
154
-
155
- login_btn.click(fn=handle_login, inputs=[email_login, password_login],
156
- outputs=[is_logged_in, message_output, selected_tab])
157
 
158
- logout_btn.click(fn=lambda: (False, "", "", HOME_TAB_NAME),
159
- outputs=[is_logged_in, email_login, password_login, selected_tab])
160
 
161
- # --- Signup
162
  def handle_signup(name, phone, email, gender, password):
163
  msg = register_user(name, phone, email, gender, password)
164
  if msg.startswith("βœ…"):
165
  return gr.update(value=msg, visible=True), "", "", "", "", "", gr.update(open=False)
166
- return gr.update(value=msg, visible=True), name, phone, email, gender, password, gr.update(open=True)
167
-
168
- signup_btn.click(fn=handle_signup,
169
- inputs=[name_signup, phone_signup, email_signup, gender_signup, password_signup],
 
 
 
 
 
 
 
170
  outputs=[message_output, name_signup, phone_signup, email_signup, gender_signup, password_signup, signup_accordion])
171
-
172
- # --- Prediction
173
  predict_btn.click(fn=predict_image, inputs=image_input, outputs=result)
174
 
175
- # --- On load
176
- demo.load(fn=lambda: (False, HOME_TAB_NAME), outputs=[is_logged_in, selected_tab])
177
 
178
  if __name__ == "__main__":
179
  demo.launch()
 
5
  import cv2
6
  from PIL import Image
7
  import tensorflow as tf
8
+
9
  import os
10
  import warnings
11
  import requests
12
  import json
13
 
14
+ from pages import about, community, user_guide
15
+
16
+ # --- Config ---
17
  SUPABASE_URL = "https://fpbuhzbdtzwomjwytqul.supabase.co"
18
+ SUPABASE_API_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
19
  SUPABASE_TABLE = "user_details"
20
 
21
  headers = {
 
24
  "Content-Type": "application/json"
25
  }
26
 
27
+ # --- Setup ---
28
  os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
29
  warnings.filterwarnings("ignore")
30
  np.seterr(all='ignore')
31
 
 
32
  MODEL_PATH = "model_15_64.h5"
33
  if not os.path.exists(MODEL_PATH):
34
+ print(f"Model file '{MODEL_PATH}' not found. Creating a dummy model for testing.")
35
  dummy_model = tf.keras.Sequential([
36
  tf.keras.layers.Input(shape=(128, 128, 3)),
37
  tf.keras.layers.Flatten(),
38
  tf.keras.layers.Dense(1, activation='sigmoid')
39
  ])
40
+ with warnings.catch_warnings():
41
+ warnings.simplefilter("ignore")
42
+ dummy_model.save(MODEL_PATH)
43
 
44
+ with warnings.catch_warnings():
45
+ warnings.simplefilter("ignore")
46
+ deepfake_model = tf.keras.models.load_model(MODEL_PATH)
47
 
48
+ # --- Helpers ---
49
  def is_valid_email(email): return re.match(r"[^@]+@[^@]+\.[^@]+", email)
50
  def is_valid_phone(phone): return re.match(r"^[0-9]{10}$", phone)
51
 
52
  def preprocess_image(image):
53
+ if image.mode != 'RGB': image = image.convert('RGB')
54
+ image_arr = np.array(image)
55
+ image_arr = cv2.resize(image_arr, (128, 128))
56
+ image_arr = image_arr.astype(np.float32) / 255.0
57
+ return np.expand_dims(image_arr, axis=0)
58
 
59
  def predict_image(image):
60
+ if image is None: return "Please upload an image first."
61
+ preprocessed = preprocess_image(image)
62
+ prediction = deepfake_model.predict(preprocessed)[0][0]
63
  confidence = prediction if prediction >= 0.5 else 1 - prediction
64
  label = "βœ… Real Image" if prediction >= 0.5 else "⚠️ Fake Image"
65
  return f"{label} (Confidence: {confidence:.2%})"
66
 
67
  def register_user(name, phone, email, gender, password):
68
  if not all([name, phone, email, gender, password]):
69
+ return "❌ All fields are required for signup."
70
+ if not is_valid_email(email): return "❌ Invalid email format."
71
  if not is_valid_phone(phone): return "❌ Phone must be 10 digits."
72
 
73
+ query_url = f"{SUPABASE_URL}/rest/v1/{SUPABASE_TABLE}?email=eq.{email}"
74
+ r = requests.get(query_url, headers=headers)
75
+ if r.status_code == 200 and len(r.json()) > 0:
76
+ return "⚠️ Email already registered."
77
 
78
+ hashed_pw = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode()
79
  data = {
80
+ "name": name,
81
+ "phone": phone,
82
+ "email": email,
83
+ "gender": gender,
84
+ "password": hashed_pw
85
  }
86
+ r = requests.post(f"{SUPABASE_URL}/rest/v1/{SUPABASE_TABLE}", headers=headers, data=json.dumps(data))
87
+ return "βœ… Registration successful! Please log in." if r.status_code == 201 else "❌ Error during registration."
 
88
 
89
  def login_user(email, password):
90
  url = f"{SUPABASE_URL}/rest/v1/{SUPABASE_TABLE}?email=eq.{email}"
 
94
  return bcrypt.checkpw(password.encode(), stored_hash.encode())
95
  return False
96
 
97
+ # --- UI ---
98
  HOME_TAB_NAME = "🏠 Home"
99
  LOGIN_TAB_NAME = "πŸ” Login"
100
+ DETECT_TAB_NAME = "πŸ§ͺ Detect Deepfake"
101
  ABOUT_TAB_NAME = "ℹ️ About"
102
  COMMUNITY_TAB_NAME = "🌐 Community"
103
  GUIDE_TAB_NAME = "πŸ“˜ User Guide"
104
 
105
+ with gr.Blocks(theme=gr.themes.Soft(), title="VerifiAI - Deepfake Detector") as demo:
 
106
  is_logged_in = gr.State(False)
107
+
108
+ with gr.Tabs() as tabs:
109
+ with gr.Tab(HOME_TAB_NAME, visible=True) as home_tab:
110
+ with gr.Row():
111
+ with gr.Column():
112
+ gr.Markdown("""
113
+ <div class="home-content">
114
+ <h1>πŸ‘οΈβ€πŸ—¨οΈ Welcome to VerifiAI</h1>
115
+ <p>Your trusted assistant for detecting deepfakes in images using AI.</p>
116
+ <p>πŸ” Upload images, analyze authenticity, and learn how deepfakes work.</p>
117
+ <p>πŸ‘‰ Use the tabs above to get started.</p>
118
+ </div>
119
+ """, elem_id="home-markdown")
120
+
121
+ with gr.Tab(LOGIN_TAB_NAME, visible=True) as login_tab:
122
+ with gr.Row():
123
+ with gr.Column(scale=1):
124
+ gr.Markdown("## Welcome!", "Login to access the detector, or sign up for a new account.")
125
+ with gr.Column(scale=2):
126
+ gr.Markdown("### Login or Sign Up")
127
+ message_output = gr.Markdown(visible=False)
128
+ email_login = gr.Textbox(label="Email")
129
+ password_login = gr.Textbox(label="Password", type="password")
130
+ login_btn = gr.Button("Login", variant="primary")
131
+ with gr.Accordion("New User? Click here to Sign Up", open=False) as signup_accordion:
132
+ name_signup = gr.Textbox(label="Name")
133
+ phone_signup = gr.Textbox(label="Phone (10 digits)")
134
+ email_signup = gr.Textbox(label="Email")
135
+ gender_signup = gr.Dropdown(label="Gender", choices=["Male", "Female", "Other"])
136
+ password_signup = gr.Textbox(label="Create Password", type="password")
137
+ signup_btn = gr.Button("Sign Up")
138
+
139
+ with gr.Tab(DETECT_TAB_NAME, visible=False) as detect_tab:
140
+ with gr.Row():
141
+ gr.Markdown("## Deepfake Detector")
142
+ logout_btn = gr.Button("Logout")
143
+ with gr.Row():
144
+ image_input = gr.Image(type="pil", label="Upload Image", scale=1)
145
+ with gr.Column(scale=1):
146
+ result = gr.Textbox(label="Prediction Result", interactive=False)
147
+ predict_btn = gr.Button("Predict", variant="primary")
148
+
149
+ with gr.Tab(ABOUT_TAB_NAME): about.layout()
150
+ with gr.Tab(COMMUNITY_TAB_NAME): community.layout()
151
+ with gr.Tab(GUIDE_TAB_NAME): user_guide.layout()
152
+
153
+ gr.HTML("""
154
+ <style>
155
+ #home-markdown {
156
+ display: flex;
157
+ justify-content: center;
158
+ align-items: center;
159
+ height: 70vh;
160
+ text-align: center;
161
+ }
162
+ </style>
163
+ """)
164
+
165
+ def update_ui_on_auth_change(logged_in_status):
166
+ if logged_in_status:
167
+ return (
168
+ gr.update(visible=False), # login_tab
169
+ gr.update(visible=True), # detect_tab
170
+ gr.update(visible=False), # home_tab
171
+ gr.update(value="βœ… Login successful!", visible=True)
172
+ )
173
+ else:
174
+ return (
175
+ gr.update(visible=True), # login_tab
176
+ gr.update(visible=False), # detect_tab
177
+ gr.update(visible=True), # home_tab
178
+ gr.update(value="", visible=False)
179
+ )
180
+
181
  def handle_login(email, password):
182
  if login_user(email, password):
183
+ return True, gr.update(value="βœ… Login successful!", visible=True)
184
+ else:
185
+ return False, gr.update(value="❌ Invalid email or password.", visible=True)
 
 
186
 
187
+ def handle_logout():
188
+ return False, "", ""
189
 
 
190
  def handle_signup(name, phone, email, gender, password):
191
  msg = register_user(name, phone, email, gender, password)
192
  if msg.startswith("βœ…"):
193
  return gr.update(value=msg, visible=True), "", "", "", "", "", gr.update(open=False)
194
+ else:
195
+ return gr.update(value=msg, visible=True), name, phone, email, gender, password, gr.update(open=True)
196
+
197
+ login_btn.click(fn=handle_login, inputs=[email_login, password_login], outputs=[is_logged_in, message_output])
198
+ logout_btn.click(fn=handle_logout, inputs=[], outputs=[is_logged_in, email_login, password_login])
199
+ is_logged_in.change(
200
+ fn=update_ui_on_auth_change,
201
+ inputs=is_logged_in,
202
+ outputs=[login_tab, detect_tab, home_tab, message_output]
203
+ )
204
+ signup_btn.click(fn=handle_signup, inputs=[name_signup, phone_signup, email_signup, gender_signup, password_signup],
205
  outputs=[message_output, name_signup, phone_signup, email_signup, gender_signup, password_signup, signup_accordion])
 
 
206
  predict_btn.click(fn=predict_image, inputs=image_input, outputs=result)
207
 
208
+ demo.load(lambda: False, None, [is_logged_in])
 
209
 
210
  if __name__ == "__main__":
211
  demo.launch()