parass13 commited on
Commit
8a63a34
Β·
verified Β·
1 Parent(s): e2d2189

Update dashboard.py

Browse files
Files changed (1) hide show
  1. dashboard.py +74 -154
dashboard.py CHANGED
@@ -17,88 +17,52 @@ os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
17
  warnings.filterwarnings("ignore")
18
  np.seterr(all='ignore')
19
 
20
- MODEL_PATH = "model_15_64.h5"
21
- if not os.path.exists(MODEL_PATH):
22
- print(f"Model file '{MODEL_PATH}' not found. Creating a dummy model for testing.")
23
- dummy_model = tf.keras.Sequential([
24
- tf.keras.layers.Input(shape=(128, 128, 3)),
25
- tf.keras.layers.Flatten(),
26
- tf.keras.layers.Dense(1, activation='sigmoid')
27
- ])
28
- with warnings.catch_warnings():
29
- warnings.simplefilter("ignore")
30
- dummy_model.save(MODEL_PATH)
31
-
32
- with warnings.catch_warnings():
33
- warnings.simplefilter("ignore")
34
- deepfake_model = tf.keras.models.load_model(MODEL_PATH)
35
-
36
- # --- DB ---
37
- DB_PATH = os.path.abspath("users.db")
38
- with sqlite3.connect(DB_PATH) as conn:
39
  cursor = conn.cursor()
40
  cursor.execute('''
41
- CREATE TABLE IF NOT EXISTS user_details (
42
- id INTEGER PRIMARY KEY AUTOINCREMENT,
43
- NAME TEXT NOT NULL,
44
- PHONE TEXT NOT NULL,
45
- EMAIL TEXT UNIQUE NOT NULL,
46
- GENDER TEXT,
47
- PASSWORD BLOB NOT NULL
48
- )
49
  ''')
50
  conn.commit()
 
 
 
51
 
52
- # --- Helpers ---
53
- def is_valid_email(email): return re.match(r"[^@]+@[^@]+\.[^@]+", email)
54
- def is_valid_phone(phone): return re.match(r"^[0-9]{10}$", phone)
55
-
56
- def preprocess_image(image):
57
- if image.mode != 'RGB': image = image.convert('RGB')
58
- image_arr = np.array(image)
59
- image_arr = cv2.resize(image_arr, (128, 128))
60
- image_arr = image_arr.astype(np.float32) / 255.0
61
- return np.expand_dims(image_arr, axis=0)
62
-
63
- def predict_image(image):
64
- if image is None: return "Please upload an image first."
65
- preprocessed = preprocess_image(image)
66
- prediction = deepfake_model.predict(preprocessed)[0][0]
67
- confidence = prediction if prediction >= 0.5 else 1 - prediction
68
- label = "βœ… Real Image" if prediction >= 0.5 else "⚠️ Fake Image"
69
- return f"{label} (Confidence: {confidence:.2%})"
70
-
71
- def register_user(name, phone, email, password):
72
- if not all([name, phone, email, password]): return "❌ All fields are required for signup."
73
- if not is_valid_email(email): return "❌ Invalid email format."
74
- if not is_valid_phone(phone): return "❌ Phone must be 10 digits."
75
  try:
76
- with sqlite3.connect(DB_PATH) as conn:
77
- cursor = conn.cursor()
78
- cursor.execute("SELECT * FROM user_details WHERE EMAIL = ?", (email,))
79
- if cursor.fetchone(): return "⚠️ Email already registered."
80
- hashed_pw = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
81
- cursor.execute("INSERT INTO user_details (NAME, PHONE, EMAIL, GENDER, PASSWORD) VALUES (?, ?, ?, ?, ?)", (name, phone, email, "U", 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="Deepfake Detector") as demo:
103
  is_logged_in = gr.State(False)
104
 
@@ -113,105 +77,61 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Deepfake Detector") as demo:
113
  with gr.Row():
114
  with gr.Column(scale=1):
115
  gr.Markdown("## Welcome!", "Login to access the detector, or sign up for a new account.")
 
116
  with gr.Column(scale=2):
117
  gr.Markdown("### Login or Sign Up")
118
  message_output = gr.Markdown(visible=False)
119
- email_login = gr.Textbox(label="Email", elem_id="login_email")
120
- password_login = gr.Textbox(label="Password", type="password", elem_id="login_pass")
121
  login_btn = gr.Button("Login", variant="primary")
122
- with gr.Accordion("New User? Click here to Sign Up", open=False) as signup_accordion:
123
- name_signup = gr.Textbox(label="Name")
124
- phone_signup = gr.Textbox(label="Phone (10 digits)")
125
- email_signup = gr.Textbox(label="Email")
126
- password_signup = gr.Textbox(label="Create Password", type="password")
127
- signup_btn = gr.Button("Sign Up")
 
 
128
 
129
  with gr.Tab(DETECT_TAB_NAME, visible=False) as detect_tab:
130
  with gr.Row():
131
  gr.Markdown("## Deepfake Detector")
132
  logout_btn = gr.Button("Logout")
 
133
  with gr.Row():
134
- image_input = gr.Image(type="pil", label="Upload Image", scale=1)
135
- with gr.Column(scale=1):
136
- result = gr.Textbox(label="Prediction Result", interactive=False)
137
  predict_btn = gr.Button("Predict", variant="primary")
 
 
138
 
139
- with gr.Tab(ABOUT_TAB_NAME): about.layout()
140
- with gr.Tab(COMMUNITY_TAB_NAME): community.layout()
141
- with gr.Tab(GUIDE_TAB_NAME): user_guide.layout()
142
-
143
- # --- Events ---
144
-
145
- # This function is now the single point for UI changes based on login state
146
- def update_ui_on_auth_change(logged_in_status):
147
- if logged_in_status:
148
- # User has logged in
149
- return (
150
- gr.update(visible=False), # Hide login tab
151
- gr.update(visible=True), # Show detect tab
152
- gr.update(selected=DETECT_TAB_NAME), # Switch to detect tab
153
- gr.update(value="βœ… Login successful!", visible=True)
154
- )
155
- else:
156
- # User has logged out
157
- return (
158
- gr.update(visible=True), # Show login tab
159
- gr.update(visible=False), # Hide detect tab
160
- gr.update(selected=LOGIN_TAB_NAME), # Go back to login tab
161
- gr.update(value="", visible=False)
162
- )
163
-
164
- # Login button now only updates the login state and provides a message
165
- def handle_login(email, password):
166
- if login_user(email, password):
167
- return True, gr.update(value="βœ… Login successful!", visible=True)
168
- else:
169
- return False, gr.update(value="❌ Invalid email or password.", visible=True)
170
-
171
- # Logout button only needs to set the state to False
172
- def handle_logout():
173
- return False, "", "" # logged_in=False, clear email/pass fields
174
-
175
- # Signup remains mostly the same, but can clear inputs and close accordion
176
- def handle_signup(name, phone, email, password):
177
- msg = register_user(name, phone, email, password)
178
- if msg.startswith("βœ…"):
179
- # On success, clear inputs and close the accordion
180
- return gr.update(value=msg, visible=True), "", "", "", "", gr.update(open=False)
181
- else:
182
- # On failure, show message but don't clear or close
183
- return gr.update(value=msg, visible=True), name, phone, email, password, gr.update(open=True)
184
-
185
-
186
- # --- Event Listeners Wiring ---
187
-
188
- # 1. Login/Logout buttons update the `is_logged_in` state.
189
- login_btn.click(
190
- fn=handle_login,
191
- inputs=[email_login, password_login],
192
- outputs=[is_logged_in, message_output]
193
- )
194
 
195
- logout_btn.click(
196
- fn=handle_logout,
197
- inputs=[],
198
- outputs=[is_logged_in, email_login, password_login]
199
- )
200
 
201
- # 2. A change in `is_logged_in` triggers the main UI update. THIS IS THE KEY.
202
- is_logged_in.change(
203
- fn=update_ui_on_auth_change,
204
- inputs=is_logged_in,
205
- outputs=[login_tab, detect_tab, tabs, message_output]
206
  )
207
 
208
  signup_btn.click(
209
- fn=handle_signup,
210
  inputs=[name_signup, phone_signup, email_signup, password_signup],
211
- outputs=[message_output, name_signup, phone_signup, email_signup, password_signup, signup_accordion]
212
  )
213
 
214
- predict_btn.click(fn=predict_image, inputs=image_input, outputs=result)
 
 
 
 
215
 
216
  if __name__ == "__main__":
217
- demo.launch()
 
17
  warnings.filterwarnings("ignore")
18
  np.seterr(all='ignore')
19
 
20
+ # Database path and setup
21
+ DB_PATH = os.path.abspath("deepfake_users.db")
22
+
23
+ def init_db():
24
+ conn = sqlite3.connect(DB_PATH)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  cursor = conn.cursor()
26
  cursor.execute('''
27
+ CREATE TABLE IF NOT EXISTS accounts (
28
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
29
+ name TEXT NOT NULL,
30
+ phone TEXT NOT NULL,
31
+ email TEXT UNIQUE NOT NULL,
32
+ gender TEXT DEFAULT 'U',
33
+ password TEXT NOT NULL
34
+ )
35
  ''')
36
  conn.commit()
37
+ conn.close()
38
+
39
+ init_db()
40
 
41
+ # --- Authentication Functions ---
42
+ def signup_user(name, phone, email, password):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  try:
44
+ conn = sqlite3.connect(DB_PATH)
45
+ cursor = conn.cursor()
46
+ cursor.execute("INSERT INTO accounts (name, phone, email, password) VALUES (?, ?, ?, ?)",
47
+ (name, phone, email, password))
48
+ conn.commit()
49
+ conn.close()
50
+ return "βœ… Signup successful. Please log in.", False
51
+ except sqlite3.IntegrityError:
52
+ return "❌ Email already registered.", False
 
 
53
 
54
  def login_user(email, password):
55
+ conn = sqlite3.connect(DB_PATH)
56
+ cursor = conn.cursor()
57
+ cursor.execute("SELECT * FROM accounts WHERE email=? AND password=?", (email, password))
58
+ user = cursor.fetchone()
59
+ conn.close()
60
+ if user:
61
+ return "βœ… Login successful!", True, gr.Tabs.update(selected="πŸ§ͺ Detect Deepfake"), True
62
+ else:
63
+ return "❌ Invalid credentials.", False, gr.Tabs.update(selected="πŸ” Login"), False
64
+
65
+ # --- Layout ---
 
 
66
  with gr.Blocks(theme=gr.themes.Soft(), title="Deepfake Detector") as demo:
67
  is_logged_in = gr.State(False)
68
 
 
77
  with gr.Row():
78
  with gr.Column(scale=1):
79
  gr.Markdown("## Welcome!", "Login to access the detector, or sign up for a new account.")
80
+ gr.Markdown("Our tool uses advanced AI to analyze images and determine their authenticity, helping you combat misinformation.")
81
  with gr.Column(scale=2):
82
  gr.Markdown("### Login or Sign Up")
83
  message_output = gr.Markdown(visible=False)
84
+ email_login = gr.Textbox(label="Email")
85
+ password_login = gr.Textbox(label="Password", type="password")
86
  login_btn = gr.Button("Login", variant="primary")
87
+
88
+ with gr.Accordion("New User? Click here to Sign Up", open=False):
89
+ with gr.Group(visible=True) as signup_group:
90
+ name_signup = gr.Textbox(label="Name")
91
+ phone_signup = gr.Textbox(label="Phone (10 digits)")
92
+ email_signup = gr.Textbox(label="Email")
93
+ password_signup = gr.Textbox(label="Create Password", type="password")
94
+ signup_btn = gr.Button("Sign Up")
95
 
96
  with gr.Tab(DETECT_TAB_NAME, visible=False) as detect_tab:
97
  with gr.Row():
98
  gr.Markdown("## Deepfake Detector")
99
  logout_btn = gr.Button("Logout")
100
+ gr.Markdown("Upload an image to check if it's a real photograph or an AI-generated deepfake.")
101
  with gr.Row():
102
+ with gr.Column():
103
+ image_input = gr.Image(type="pil", label="Upload Image")
 
104
  predict_btn = gr.Button("Predict", variant="primary")
105
+ with gr.Column():
106
+ result = gr.Textbox(label="Prediction Result", interactive=False)
107
 
108
+ with gr.Tab(ABOUT_TAB_NAME):
109
+ gr.Markdown("### About\nThis tool detects deepfakes using AI models. Built for research and awareness.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
 
111
+ with gr.Tab(COMMUNITY_TAB_NAME):
112
+ gr.Markdown("### Community\nJoin our community forum to discuss and share insights.")
113
+
114
+ with gr.Tab(GUIDE_TAB_NAME):
115
+ gr.Markdown("### User Guide\nStep-by-step instructions for using the deepfake detector.")
116
 
117
+ # --- Function Bindings ---
118
+ login_btn.click(
119
+ fn=login_user,
120
+ inputs=[email_login, password_login],
121
+ outputs=[message_output, is_logged_in, tabs, detect_tab]
122
  )
123
 
124
  signup_btn.click(
125
+ fn=signup_user,
126
  inputs=[name_signup, phone_signup, email_signup, password_signup],
127
+ outputs=[message_output, signup_group]
128
  )
129
 
130
+ logout_btn.click(
131
+ fn=lambda: (False, gr.Tabs.update(selected=LOGIN_TAB_NAME)),
132
+ inputs=None,
133
+ outputs=[is_logged_in, tabs]
134
+ )
135
 
136
  if __name__ == "__main__":
137
+ demo.launch()