parass13 commited on
Commit
ea96e7c
Β·
verified Β·
1 Parent(s): 5067008

Update dashboard.py

Browse files
Files changed (1) hide show
  1. dashboard.py +25 -64
dashboard.py CHANGED
@@ -4,18 +4,18 @@ import bcrypt
4
  import numpy as np
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.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImZwYnVoemJkdHp3b21qd3l0cXVsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTE5NDk3NzYsImV4cCI6MjA2NzUyNTc3Nn0.oAa2TNNPQMyOGk63AOMZ7XKcwYvy5m-xoSWyvMZd6FY"
19
  SUPABASE_TABLE = "user_details"
20
 
21
  headers = {
@@ -29,39 +29,24 @@ 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):
@@ -69,20 +54,12 @@ def register_user(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
 
@@ -108,7 +85,6 @@ GUIDE_TAB_NAME = "πŸ“˜ User Guide"
108
  with gr.Blocks(theme=gr.themes.Soft(), title="VerifiAI - Deepfake Detector") as demo:
109
  is_logged_in = gr.State(False)
110
 
111
- # --- FIX 1: Set a default selected tab ---
112
  with gr.Tabs(selected=HOME_TAB_NAME) as tabs:
113
  with gr.Tab(HOME_TAB_NAME, id=HOME_TAB_NAME) as home_tab:
114
  with gr.Row():
@@ -166,25 +142,22 @@ with gr.Blocks(theme=gr.themes.Soft(), title="VerifiAI - Deepfake Detector") as
166
  </style>
167
  """)
168
 
169
- # --- FIX 2: Modify the function to also control which tab is selected ---
170
  def update_ui_on_auth_change(logged_in_status):
171
  if logged_in_status:
172
- # On successful login, hide login/home, show detector, and select the detector tab
173
  return (
174
  gr.update(visible=False), # login_tab
175
  gr.update(visible=True), # detect_tab
176
  gr.update(visible=False), # home_tab
177
  gr.update(value="βœ… Login successful!", visible=True),
178
- gr.update(selected=DETECT_TAB_NAME) # This selects the tab
179
  )
180
  else:
181
- # On logout or initial load, show login/home, hide detector, and select the home tab
182
  return (
183
- gr.update(visible=True), # login_tab
184
- gr.update(visible=False), # detect_tab
185
- gr.update(visible=True), # home_tab
186
  gr.update(value="", visible=False),
187
- gr.update(selected=HOME_TAB_NAME) # This selects the tab
188
  )
189
 
190
  def handle_login(email, password):
@@ -194,9 +167,8 @@ with gr.Blocks(theme=gr.themes.Soft(), title="VerifiAI - Deepfake Detector") as
194
  return False, gr.update(value="❌ Invalid email or password.", visible=True)
195
 
196
  def handle_logout():
197
- # Return values for: is_logged_in, email_login, password_login, image_input, result
198
  return False, "", "", None, ""
199
-
200
  def handle_signup(name, phone, email, gender, password):
201
  msg = register_user(name, phone, email, gender, password)
202
  if msg.startswith("βœ…"):
@@ -205,23 +177,12 @@ with gr.Blocks(theme=gr.themes.Soft(), title="VerifiAI - Deepfake Detector") as
205
  return gr.update(value=msg, visible=True), name, phone, email, gender, password, gr.update(open=True)
206
 
207
  login_btn.click(fn=handle_login, inputs=[email_login, password_login], outputs=[is_logged_in, message_output])
208
- logout_btn.click(
209
- fn=handle_logout,
210
- inputs=[],
211
- outputs=[is_logged_in, email_login, password_login, image_input, result]
212
- )
213
-
214
- # --- FIX 3: Add the `tabs` component to the outputs of the change event ---
215
- is_logged_in.change(
216
- fn=update_ui_on_auth_change,
217
- inputs=is_logged_in,
218
- outputs=[login_tab, detect_tab, home_tab, message_output, tabs]
219
- )
220
  signup_btn.click(fn=handle_signup, inputs=[name_signup, phone_signup, email_signup, gender_signup, password_signup],
221
  outputs=[message_output, name_signup, phone_signup, email_signup, gender_signup, password_signup, signup_accordion])
222
  predict_btn.click(fn=predict_image, inputs=image_input, outputs=result)
223
-
224
  demo.load(lambda: False, None, [is_logged_in])
225
 
226
  if __name__ == "__main__":
227
- demo.launch()
 
4
  import numpy as np
5
  import cv2
6
  from PIL import Image
 
 
7
  import os
8
  import warnings
9
  import requests
10
  import json
11
+ import torch
12
+ from transformers import AutoImageProcessor, SiglipForImageClassification
13
 
14
  from pages import about, community, user_guide
15
 
16
  # --- Config ---
17
  SUPABASE_URL = "https://fpbuhzbdtzwomjwytqul.supabase.co"
18
+ SUPABASE_API_KEY = "YOUR_SUPABASE_API_KEY" # Replace with your actual key
19
  SUPABASE_TABLE = "user_details"
20
 
21
  headers = {
 
29
  warnings.filterwarnings("ignore")
30
  np.seterr(all='ignore')
31
 
32
+ # --- Load Hugging Face Model ---
33
+ processor = AutoImageProcessor.from_pretrained("prithivMLmods/deepfake-detector-model-v1")
34
+ hf_model = SiglipForImageClassification.from_pretrained("prithivMLmods/deepfake-detector-model-v1")
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
  # --- Helpers ---
37
  def is_valid_email(email): return re.match(r"[^@]+@[^@]+\.[^@]+", email)
38
  def is_valid_phone(phone): return re.match(r"^[0-9]{10}$", phone)
39
 
 
 
 
 
 
 
 
40
  def predict_image(image):
41
+ if image is None:
42
+ return "Please upload an image first."
43
+ image = image.convert("RGB")
44
+ inputs = processor(images=image, return_tensors="pt")
45
+ with torch.no_grad():
46
+ outputs = hf_model(**inputs)
47
+ probs = torch.nn.functional.softmax(outputs.logits, dim=1).squeeze().tolist()
48
+ label = "βœ… Real Image" if probs[1] >= probs[0] else "⚠️ Fake Image"
49
+ confidence = max(probs)
50
  return f"{label} (Confidence: {confidence:.2%})"
51
 
52
  def register_user(name, phone, email, gender, password):
 
54
  return "❌ All fields are required for signup."
55
  if not is_valid_email(email): return "❌ Invalid email format."
56
  if not is_valid_phone(phone): return "❌ Phone must be 10 digits."
 
57
  query_url = f"{SUPABASE_URL}/rest/v1/{SUPABASE_TABLE}?email=eq.{email}"
58
  r = requests.get(query_url, headers=headers)
59
  if r.status_code == 200 and len(r.json()) > 0:
60
  return "⚠️ Email already registered."
 
61
  hashed_pw = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode()
62
+ data = {"name": name, "phone": phone, "email": email, "gender": gender, "password": hashed_pw}
 
 
 
 
 
 
63
  r = requests.post(f"{SUPABASE_URL}/rest/v1/{SUPABASE_TABLE}", headers=headers, data=json.dumps(data))
64
  return "βœ… Registration successful! Please log in." if r.status_code == 201 else "❌ Error during registration."
65
 
 
85
  with gr.Blocks(theme=gr.themes.Soft(), title="VerifiAI - Deepfake Detector") as demo:
86
  is_logged_in = gr.State(False)
87
 
 
88
  with gr.Tabs(selected=HOME_TAB_NAME) as tabs:
89
  with gr.Tab(HOME_TAB_NAME, id=HOME_TAB_NAME) as home_tab:
90
  with gr.Row():
 
142
  </style>
143
  """)
144
 
 
145
  def update_ui_on_auth_change(logged_in_status):
146
  if logged_in_status:
 
147
  return (
148
  gr.update(visible=False), # login_tab
149
  gr.update(visible=True), # detect_tab
150
  gr.update(visible=False), # home_tab
151
  gr.update(value="βœ… Login successful!", visible=True),
152
+ gr.update(selected=DETECT_TAB_NAME)
153
  )
154
  else:
 
155
  return (
156
+ gr.update(visible=True),
157
+ gr.update(visible=False),
158
+ gr.update(visible=True),
159
  gr.update(value="", visible=False),
160
+ gr.update(selected=HOME_TAB_NAME)
161
  )
162
 
163
  def handle_login(email, password):
 
167
  return False, gr.update(value="❌ Invalid email or password.", visible=True)
168
 
169
  def handle_logout():
 
170
  return False, "", "", None, ""
171
+
172
  def handle_signup(name, phone, email, gender, password):
173
  msg = register_user(name, phone, email, gender, password)
174
  if msg.startswith("βœ…"):
 
177
  return gr.update(value=msg, visible=True), name, phone, email, gender, password, gr.update(open=True)
178
 
179
  login_btn.click(fn=handle_login, inputs=[email_login, password_login], outputs=[is_logged_in, message_output])
180
+ logout_btn.click(fn=handle_logout, inputs=[], outputs=[is_logged_in, email_login, password_login, image_input, result])
181
+ is_logged_in.change(fn=update_ui_on_auth_change, inputs=is_logged_in, outputs=[login_tab, detect_tab, home_tab, message_output, tabs])
 
 
 
 
 
 
 
 
 
 
182
  signup_btn.click(fn=handle_signup, inputs=[name_signup, phone_signup, email_signup, gender_signup, password_signup],
183
  outputs=[message_output, name_signup, phone_signup, email_signup, gender_signup, password_signup, signup_accordion])
184
  predict_btn.click(fn=predict_image, inputs=image_input, outputs=result)
 
185
  demo.load(lambda: False, None, [is_logged_in])
186
 
187
  if __name__ == "__main__":
188
+ demo.launch()