Spaces:
Sleeping

Aditya-Jadhav150 commited on
Commit
239017e
·
1 Parent(s): b13f11b

Initial commit: Veritas-AI Production Build

Browse files
.gitignore CHANGED
@@ -1,41 +1,32 @@
1
- # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2
-
3
- # dependencies
4
- /node_modules
5
- /.pnp
6
- .pnp.*
7
- .yarn/*
8
- !.yarn/patches
9
- !.yarn/plugins
10
- !.yarn/releases
11
- !.yarn/versions
12
-
13
- # testing
14
- /coverage
15
-
16
- # next.js
17
- /.next/
18
- /out/
19
-
20
- # production
21
- /build
22
-
23
- # misc
 
 
 
 
 
 
 
24
  .DS_Store
25
- *.pem
26
-
27
- # debug
28
- npm-debug.log*
29
- yarn-debug.log*
30
- yarn-error.log*
31
- .pnpm-debug.log*
32
-
33
- # env files (can opt-in for committing if needed)
34
- .env*
35
-
36
- # vercel
37
- .vercel
38
-
39
- # typescript
40
- *.tsbuildinfo
41
- next-env.d.ts
 
1
+ # Virtual Environments
2
+ workspace/
3
+ venv/
4
+ env/
5
+ .env
6
+
7
+ # Datasets and Weights (CRITICAL TO IGNORE)
8
+ dataset/
9
+ *.pth
10
+ *.safetensors
11
+ *.h5
12
+ *.pt
13
+ model.pth
14
+
15
+ # Python Caches
16
+ __pycache__/
17
+ *.pyc
18
+ *.pyo
19
+ *.pyd
20
+
21
+ # Flask Uploads & Databases
22
+ static/uploads/
23
+ instance/
24
+ *.sqlite3
25
+ *.db
26
+ users.db
27
+
28
+ # IDE and OS
29
+ .vscode/
30
+ .idea/
31
  .DS_Store
32
+ Thumbs.db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
AGENTS.md DELETED
@@ -1,3 +0,0 @@
1
- # This is NOT the Next.js you know
2
-
3
- This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code. Heed deprecation notices.
 
 
 
 
CLAUDE.md DELETED
@@ -1 +0,0 @@
1
- @AGENTS.md
 
 
LICENSE.txt ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Flickr-Faces-HQ (FFHQ) is a high-quality image dataset of human faces,
2
+ originally created as a benchmark for generative adversarial networks (GAN):
3
+
4
+ A Style-Based Generator Architecture for Generative Adversarial Networks
5
+ Tero Karras (NVIDIA), Samuli Laine (NVIDIA), Timo Aila (NVIDIA)
6
+ http://stylegan.xyz/paper
7
+
8
+ The individual images were published in Flickr by their respective authors
9
+ under either Creative Commons BY 2.0, Creative Commons BY-NC 2.0,
10
+ Public Domain Mark 1.0, Public Domain CC0 1.0, or U.S. Government Works
11
+ license. All of these licenses allow free use, redistribution, and adaptation
12
+ for non-commercial purposes. However, some of them require giving appropriate
13
+ credit to the original author, as well as indicating any changes that were
14
+ made to the images. The license and original author of each image are
15
+ indicated in the metadata.
16
+
17
+ https://creativecommons.org/licenses/by/2.0/
18
+ https://creativecommons.org/licenses/by-nc/2.0/
19
+ https://creativecommons.org/publicdomain/mark/1.0/
20
+ https://creativecommons.org/publicdomain/zero/1.0/
21
+ http://www.usa.gov/copyright.shtml
22
+
23
+ The dataset itself (including JSON metadata, download script, and
24
+ documentation) is made available under Creative Commons BY-NC-SA 4.0 license
25
+ by NVIDIA Corporation. You can use, redistribute, and adapt it for
26
+ non-commercial purposes, as long as you (a) give appropriate credit by
27
+ citing our paper, (b) indicate any changes that you've made, and
28
+ (c) distribute any derivative works under the same license.
29
+
30
+ https://creativecommons.org/licenses/by-nc-sa/4.0/
README.md DELETED
@@ -1,40 +0,0 @@
1
- This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
2
-
3
- ## Getting Started
4
-
5
- First, run the development server:
6
-
7
- ```bash
8
- npm run dev
9
- # or
10
- yarn dev
11
- # or
12
- pnpm dev
13
- # or
14
- bun dev
15
- ```
16
-
17
- Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
18
-
19
- You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
20
-
21
- This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
22
-
23
- ## Learn More
24
-
25
- To learn more about Next.js, take a look at the following resources:
26
-
27
- - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
28
- - [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
29
-
30
- You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
31
-
32
- ## Deploy on Vercel
33
-
34
- The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
35
-
36
- # Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
37
-
38
- # TalentLens-AI
39
-
40
- > > > > > > > 757b013eb0c48aa374b13d9e00ad72bd0321c585
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Test.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ print("CUDA Available:", torch.cuda.is_available())
4
+ if torch.cuda.is_available():
5
+ print("GPU Name:", torch.cuda.get_device_name(0))
6
+ else:
7
+ print("No GPU available.")
app.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ import os
3
+
4
+ # Suppress FaceNet/PyTorch warnings
5
+ warnings.filterwarnings("ignore", category=FutureWarning)
6
+ # Optional: suppress some TensorFlow/standard logs if they get noisy
7
+ os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
8
+ import os
9
+ import torch
10
+ import torch.nn as nn
11
+ from transformers import AutoImageProcessor, AutoModelForImageClassification
12
+ from PIL import Image
13
+ from flask import Flask, render_template, request, jsonify, redirect, url_for
14
+ from flask_sqlalchemy import SQLAlchemy
15
+ from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
16
+ from werkzeug.security import generate_password_hash, check_password_hash
17
+ from werkzeug.utils import secure_filename
18
+ from facenet_pytorch import MTCNN
19
+
20
+ app = Flask(__name__)
21
+ app.config['SECRET_KEY'] = 'deepfake-detection-super-secret-key-2026'
22
+ app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
23
+ app.config['UPLOAD_FOLDER'] = 'static/uploads'
24
+ app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16 MB limit
25
+ os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
26
+
27
+ db = SQLAlchemy(app)
28
+ login_manager = LoginManager(app)
29
+ login_manager.login_view = 'login'
30
+
31
+ # --- Database Models ---
32
+ class User(UserMixin, db.Model):
33
+ id = db.Column(db.Integer, primary_key=True)
34
+ username = db.Column(db.String(150), unique=True, nullable=False)
35
+ password_hash = db.Column(db.String(300), nullable=False)
36
+
37
+ @login_manager.user_loader
38
+ def load_user(user_id):
39
+ return User.query.get(int(user_id))
40
+
41
+ # --- PyTorch Model Setup ---
42
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
43
+ print("Loading Hugging Face Hub Deepfake model onto:", device)
44
+
45
+ mtcnn = MTCNN(keep_all=False, device=device)
46
+
47
+ # Switch to production-grade generalized Vision Transformer from HF Hub
48
+ model_id = "prithivMLmods/Deep-Fake-Detector-v2-Model"
49
+ try:
50
+ processor = AutoImageProcessor.from_pretrained(model_id)
51
+ model = AutoModelForImageClassification.from_pretrained(model_id).to(device)
52
+ model.eval()
53
+ print(f"[{model_id}] perfectly synchronized and successfully loaded globally out of the box.")
54
+ except Exception as e:
55
+ print(f"WARNING: Transformer model failed to boot from Hugging Face Hub (Internet issue?): {e}")
56
+
57
+ def predict_image(image_path):
58
+ try:
59
+ image = Image.open(image_path).convert("RGB")
60
+
61
+ # Direct Transformer Inference: The ViT operates on the full global image context, not just localized bounding boxes!
62
+ inputs = processor(images=image, return_tensors="pt").to(device)
63
+
64
+ with torch.no_grad():
65
+ outputs = model(**inputs)
66
+ logits = outputs.logits
67
+ model_probs = torch.nn.functional.softmax(logits, dim=1)
68
+
69
+ labels = model.config.id2label
70
+ fake_prob = 0.0
71
+ real_prob = 0.0
72
+
73
+ # Smart dictionary parsing depending on model registry configuration
74
+ for idx, label_name in labels.items():
75
+ prob = model_probs[0][idx].item()
76
+ l = label_name.lower()
77
+ if 'fake' in l or 'deepfake' in l or 'spoof' in l:
78
+ fake_prob += prob
79
+ elif 'real' in l or 'pristine' in l:
80
+ real_prob += prob
81
+
82
+ # Fallback if label resolution gets highly ambiguous
83
+ if fake_prob == 0 and real_prob == 0:
84
+ pred_idx = torch.argmax(model_probs, dim=1).item()
85
+ predicted_label = labels[pred_idx].upper()
86
+ if 'FAKE' in predicted_label:
87
+ fake_prob = 1.0
88
+ else:
89
+ real_prob = 1.0
90
+
91
+ return {
92
+ "success": True,
93
+ "fake_prob": round(fake_prob * 100, 2),
94
+ "real_prob": round(real_prob * 100, 2),
95
+ "prediction": "REAL" if real_prob > fake_prob else "FAKE"
96
+ }
97
+ except Exception as e:
98
+ return {"success": False, "error": str(e)}
99
+
100
+ # --- Web Routes ---
101
+ @app.route('/')
102
+ @login_required
103
+ def index():
104
+ return render_template('index.html', user=current_user)
105
+
106
+ @app.route('/login', methods=['GET'])
107
+ def login():
108
+ if current_user.is_authenticated:
109
+ return redirect(url_for('index'))
110
+ return render_template('login.html')
111
+
112
+ @app.route('/api/login', methods=['POST'])
113
+ def api_login():
114
+ data = request.json
115
+ user = User.query.filter_by(username=data.get('username')).first()
116
+ if user and check_password_hash(user.password_hash, data.get('password')):
117
+ login_user(user, remember=True)
118
+ return jsonify({"success": True})
119
+ return jsonify({"success": False, "message": "Invalid username or password"})
120
+
121
+ @app.route('/api/register', methods=['POST'])
122
+ def api_register():
123
+ data = request.json
124
+ username = data.get('username')
125
+ password = data.get('password')
126
+
127
+ if not username or len(username) < 3:
128
+ return jsonify({"success": False, "message": "Username must be at least 3 characters."})
129
+
130
+ if User.query.filter_by(username=username).first():
131
+ return jsonify({"success": False, "message": "Username already exists."})
132
+
133
+ new_user = User(username=username, password_hash=generate_password_hash(password))
134
+ db.session.add(new_user)
135
+ db.session.commit()
136
+
137
+ # Auto-login after registration
138
+ login_user(new_user)
139
+ return jsonify({"success": True})
140
+
141
+ @app.route('/logout')
142
+ @login_required
143
+ def logout():
144
+ logout_user()
145
+ return redirect(url_for('login'))
146
+
147
+ @app.route('/api/predict', methods=['POST'])
148
+ @login_required
149
+ def api_predict():
150
+ if 'file' not in request.files:
151
+ return jsonify({"success": False, "message": "No file chunk found."}), 400
152
+ file = request.files['file']
153
+ if file.filename == '':
154
+ return jsonify({"success": False, "message": "No file selected."}), 400
155
+ if file:
156
+ filename = secure_filename(file.filename)
157
+ filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
158
+ file.save(filepath)
159
+
160
+ result = predict_image(filepath)
161
+ if result["success"]:
162
+ # Expose public visual path
163
+ result["image_url"] = f"/static/uploads/{filename}"
164
+ return jsonify(result)
165
+ else:
166
+ return jsonify({"success": False, "message": result.get("error")}), 500
167
+
168
+ if __name__ == '__main__':
169
+ with app.app_context():
170
+ db.create_all()
171
+ app.run(debug=True, port=5000)
data_load.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from PIL import Image
3
+
4
+ DATA_DIR = "dataset/processed_train"
5
+ REAL_DIR = os.path.join(DATA_DIR, "real")
6
+ FAKE_DIR = os.path.join(DATA_DIR, "fake")
7
+
8
+ def count_images(folder):
9
+ try:
10
+ return len([
11
+ f for f in os.listdir(folder)
12
+ if f.lower().endswith((".jpg", ".png", ".jpeg"))
13
+ ])
14
+ except FileNotFoundError:
15
+ return 0
16
+
17
+ def verify_dataset():
18
+ real_count = count_images(REAL_DIR)
19
+ fake_count = count_images(FAKE_DIR)
20
+
21
+ print("Dataset check:")
22
+ print("Real images:", real_count)
23
+ print("Fake images:", fake_count)
24
+
25
+ if real_count == 0 or fake_count == 0:
26
+ print("⚠️ Dataset incomplete or not found in dataset/processed_train!")
27
+ else:
28
+ print("✅ Dataset looks good")
29
+
30
+ if __name__ == "__main__":
31
+ verify_dataset()
eslint.config.mjs DELETED
@@ -1,18 +0,0 @@
1
- import { defineConfig, globalIgnores } from "eslint/config";
2
- import nextVitals from "eslint-config-next/core-web-vitals";
3
- import nextTs from "eslint-config-next/typescript";
4
-
5
- const eslintConfig = defineConfig([
6
- ...nextVitals,
7
- ...nextTs,
8
- // Override default ignores of eslint-config-next.
9
- globalIgnores([
10
- // Default ignores of eslint-config-next:
11
- ".next/**",
12
- "out/**",
13
- "build/**",
14
- "next-env.d.ts",
15
- ]),
16
- ]);
17
-
18
- export default eslintConfig;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
evaluate.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torchvision import datasets, transforms
3
+ import timm
4
+ from torch.utils.data import DataLoader
5
+ from sklearn.metrics import classification_report
6
+
7
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
8
+
9
+ transform = transforms.Compose([
10
+ transforms.Resize((224, 224)),
11
+ transforms.ToTensor(),
12
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
13
+ ])
14
+
15
+ test_data = datasets.ImageFolder("dataset/test", transform=transform)
16
+ test_loader = DataLoader(test_data, batch_size=32)
17
+
18
+ model = timm.create_model('efficientnet_b3', pretrained=False, num_classes=2)
19
+ model.load_state_dict(torch.load("model.pth", map_location=device, weights_only=True))
20
+ model = model.to(device)
21
+ model.eval()
22
+
23
+ y_true = []
24
+ y_pred = []
25
+
26
+ with torch.no_grad():
27
+ for images, labels in test_loader:
28
+ images = images.to(device)
29
+ outputs = model(images)
30
+ _, preds = torch.max(outputs, 1)
31
+
32
+ y_true.extend(labels.numpy())
33
+ y_pred.extend(preds.cpu().numpy())
34
+
35
+ print(classification_report(y_true, y_pred))
extract_faces.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import cv2
4
+ from PIL import Image
5
+ import torch
6
+ from facenet_pytorch import MTCNN
7
+ from tqdm import tqdm
8
+
9
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
10
+ print(f"Loading MTCNN onto {device}...")
11
+ mtcnn = MTCNN(keep_all=False, device=device)
12
+
13
+ # Base directories
14
+ BASE_VAL_DIR = "dataset/validation"
15
+ PROCESSED_TRAIN_DIR = "dataset/processed_train"
16
+ PROCESSED_VAL_DIR = "dataset/processed_val"
17
+
18
+ # Source directories
19
+ CIFAKE_TRAIN = "dataset/train"
20
+ CIFAKE_TEST = "dataset/test"
21
+ DEEPFAKE_DIR = "dataset/flickr_deepfake"
22
+
23
+ for p in [PROCESSED_TRAIN_DIR, PROCESSED_VAL_DIR]:
24
+ os.makedirs(os.path.join(p, 'real'), exist_ok=True)
25
+ os.makedirs(os.path.join(p, 'fake'), exist_ok=True)
26
+
27
+ def process_real_faces(src_dir, dest_dir):
28
+ """
29
+ This will be used for your new REAL dataset (e.g., FFHQ).
30
+ We detect faces using NVIDIA-accelerated MTCNN and crop them for training.
31
+ """
32
+ print(f"Processing REAL images from {src_dir} to {dest_dir}...")
33
+ if not os.path.exists(src_dir):
34
+ print(f"Warning: {src_dir} not found. Skipping.")
35
+ return
36
+
37
+ for filename in tqdm(os.listdir(src_dir), desc="Extracting REAL Faces"):
38
+ if not filename.lower().endswith(('.png', '.jpg', '.jpeg')):
39
+ continue
40
+
41
+ src_path = os.path.join(src_dir, filename)
42
+ dest_path = os.path.join(dest_dir, 'real', f"real_{filename}")
43
+
44
+ try:
45
+ img = Image.open(src_path).convert('RGB')
46
+ img_cropped = mtcnn(img, save_path=None)
47
+
48
+ if img_cropped is not None:
49
+ mtcnn(img, save_path=dest_path)
50
+ else:
51
+ img = img.resize((224, 224))
52
+ img.save(dest_path)
53
+ except Exception as e:
54
+ print(f"Error extracting face from {filename}: {e}")
55
+
56
+ def process_deepfake(src_dir, dest_dir):
57
+ """
58
+ flickr_deepfake images are full resolution with Real and Fake mixed.
59
+ We detect faces using NVIDIA-accelerated MTCNN, crop them, and sort
60
+ by checking if the filename implies a face-swap (e.g. contains an underscore).
61
+ """
62
+ print(f"Processing Deepfake (MTCNN Face Extraction) from {src_dir} to {dest_dir}...")
63
+ if not os.path.exists(src_dir):
64
+ print(f"Warning: {src_dir} not found. Skipping.")
65
+ return
66
+
67
+ for filename in tqdm(os.listdir(src_dir), desc="Extracting Faces"):
68
+ if not filename.lower().endswith(('.png', '.jpg', '.jpeg')):
69
+ continue
70
+
71
+ src_path = os.path.join(src_dir, filename)
72
+
73
+ # Heuristic: If ID_ID.jpg format (has underscore), it is fake. Else real.
74
+ if '_' in filename:
75
+ dest_label = 'fake'
76
+ else:
77
+ dest_label = 'real'
78
+
79
+ dest_path = os.path.join(dest_dir, dest_label, f"df_{filename}")
80
+
81
+ try:
82
+ img = Image.open(src_path).convert('RGB')
83
+ # MTCNN cropping
84
+ img_cropped = mtcnn(img, save_path=None)
85
+
86
+ if img_cropped is not None:
87
+ # MTCNN returns a tensor (C, H, W) normalized [-1, 1] if save_path is None
88
+ # We can just extract the bounding box manually so we have PIL logic,
89
+ # but facenet_pytorch allows direct saving if we pass save_path.
90
+ mtcnn(img, save_path=dest_path)
91
+ else:
92
+ # Fallback if MTCNN fails finding a face
93
+ img = img.resize((224, 224))
94
+ img.save(dest_path)
95
+ except Exception as e:
96
+ print(f"Error extracting face from {filename}: {e}")
97
+
98
+ if __name__ == "__main__":
99
+ print("=== EXTRACTING REAL FFHQ FACES ===")
100
+
101
+ # We successfully extracted the FAKE dataset, now we do the REAL one!
102
+ process_real_faces("dataset/ffhq_real", PROCESSED_TRAIN_DIR)
103
+
104
+ # process_deepfake(DEEPFAKE_DIR, PROCESSED_TRAIN_DIR) # Commented out to save you a 2.5 hour re-run!
105
+
106
+ print("Real FFHQ Extraction Complete! All unified images are stored in dataset/processed_train.")
next.config.ts DELETED
@@ -1,5 +0,0 @@
1
- import type { NextConfig } from "next";
2
-
3
- const nextConfig: NextConfig = {};
4
-
5
- export default nextConfig;
 
 
 
 
 
 
package-lock.json DELETED
The diff for this file is too large to render. See raw diff
 
package.json DELETED
@@ -1,28 +0,0 @@
1
- {
2
- "name": "talentlens-ai",
3
- "version": "0.1.0",
4
- "private": true,
5
- "scripts": {
6
- "dev": "next dev",
7
- "build": "next build",
8
- "start": "next start",
9
- "lint": "eslint"
10
- },
11
- "dependencies": {
12
- "@clerk/nextjs": "^7.0.7",
13
- "next": "16.2.1",
14
- "openai": "^6.33.0",
15
- "react": "19.2.4",
16
- "react-dom": "19.2.4"
17
- },
18
- "devDependencies": {
19
- "@tailwindcss/postcss": "^4",
20
- "@types/node": "^20",
21
- "@types/react": "^19",
22
- "@types/react-dom": "^19",
23
- "eslint": "^9",
24
- "eslint-config-next": "16.2.1",
25
- "tailwindcss": "^4",
26
- "typescript": "^5"
27
- }
28
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
postcss.config.mjs DELETED
@@ -1,7 +0,0 @@
1
- const config = {
2
- plugins: {
3
- "@tailwindcss/postcss": {},
4
- },
5
- };
6
-
7
- export default config;
 
 
 
 
 
 
 
 
predict.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ warnings.filterwarnings("ignore", category=FutureWarning)
3
+
4
+ import torch
5
+ from transformers import AutoImageProcessor, AutoModelForImageClassification
6
+ from PIL import Image
7
+ from facenet_pytorch import MTCNN
8
+
9
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
10
+ print("Using:", device)
11
+ mtcnn = MTCNN(keep_all=False, device=device)
12
+
13
+ # Load state-of-the-art Hugging Face Vision Transformer for Deepfake Detection
14
+ model_id = "prithivMLmods/Deep-Fake-Detector-v2-Model"
15
+ print(f"Loading Hugging Face ViT [{model_id}]... (This may take a moment to download weights on first run)")
16
+ processor = AutoImageProcessor.from_pretrained(model_id)
17
+ model = AutoModelForImageClassification.from_pretrained(model_id).to(device)
18
+ model.eval()
19
+
20
+ def predict(image_path):
21
+ image = Image.open(image_path).convert("RGB")
22
+
23
+ # Transformer Inference (The ViT is trained on global image context, not just local cropped bounding boxes)
24
+ inputs = processor(images=image, return_tensors="pt").to(device)
25
+
26
+ with torch.no_grad():
27
+ outputs = model(**inputs)
28
+ logits = outputs.logits
29
+ model_probs = torch.nn.functional.softmax(logits, dim=1)
30
+
31
+ labels = model.config.id2label
32
+ # Dynamically find which index maps to real/fake in case the hub model swaps them
33
+ fake_prob = 0.0
34
+ real_prob = 0.0
35
+ for idx, label_name in labels.items():
36
+ prob = model_probs[0][idx].item()
37
+ l = label_name.lower()
38
+ if 'fake' in l or 'deepfake' in l or 'spoof' in l:
39
+ fake_prob += prob
40
+ elif 'real' in l or 'pristine' in l:
41
+ real_prob += prob
42
+
43
+ # Fallback to direct argmax if labels are ambiguous
44
+ if fake_prob == 0 and real_prob == 0:
45
+ pred_idx = torch.argmax(model_probs, dim=1).item()
46
+ print(f"\nRaw Hub Label mapped: {labels[pred_idx]}")
47
+ return
48
+
49
+ print(f"\nFake: {fake_prob*100:.2f}%")
50
+ print(f"Real: {real_prob*100:.2f}%")
51
+
52
+ if real_prob > fake_prob:
53
+ print("Prediction: REAL ✅")
54
+ else:
55
+ print("Prediction: FAKE ⚠️")
56
+
57
+ if __name__ == "__main__":
58
+ import sys
59
+ import os
60
+ if len(sys.argv) > 1 and os.path.exists(sys.argv[1]):
61
+ predict(sys.argv[1])
62
+ else:
63
+ if os.path.exists("test.jpg"):
64
+ predict("test.jpg")
preprocess.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tensorflow as tf
2
+
3
+ IMG_SIZE = (224, 224)
4
+ BATCH_SIZE = 16
5
+
6
+ TRAIN_DIR = "dataset/train"
7
+ VAL_DIR = "dataset/validation"
8
+ TEST_DIR = "dataset/test"
9
+
10
+ def load_datasets():
11
+ train_ds = tf.keras.preprocessing.image_dataset_from_directory(
12
+ TRAIN_DIR,
13
+ image_size=IMG_SIZE,
14
+ batch_size=BATCH_SIZE,
15
+ label_mode="binary",
16
+ shuffle=True
17
+ )
18
+
19
+ val_ds = tf.keras.preprocessing.image_dataset_from_directory(
20
+ VAL_DIR,
21
+ image_size=IMG_SIZE,
22
+ batch_size=BATCH_SIZE,
23
+ label_mode="binary",
24
+ shuffle=False
25
+ )
26
+
27
+ test_ds = tf.keras.preprocessing.image_dataset_from_directory(
28
+ TEST_DIR,
29
+ image_size=IMG_SIZE,
30
+ batch_size=BATCH_SIZE,
31
+ label_mode="binary",
32
+ shuffle=False
33
+ )
34
+
35
+ return train_ds, val_ds, test_ds
public/file.svg DELETED
public/globe.svg DELETED
public/next.svg DELETED
public/vercel.svg DELETED
public/window.svg DELETED
pyvenv.cfg ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ home = C:\Users\Aditya Jadhav\AppData\Local\Programs\Python\Python312
2
+ include-system-site-packages = false
3
+ version = 3.12.0
4
+ executable = C:\Users\Aditya Jadhav\AppData\Local\Programs\Python\Python312\python.exe
5
+ command = C:\Users\Aditya Jadhav\AppData\Local\Programs\Python\Python312\python.exe -m venv D:\VISUAL STUDIO CODE\DeepFake_Detection\workspace
requirements.txt ADDED
Binary file (2.7 kB). View file
 
split_val.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import random
4
+ from tqdm import tqdm
5
+
6
+ def split_dataset(train_dir, val_dir, split_ratio=0.1):
7
+ random.seed(42) # For reproducibility
8
+
9
+ for class_name in ['real', 'fake']:
10
+ src_folder = os.path.join(train_dir, class_name)
11
+ dest_folder = os.path.join(val_dir, class_name)
12
+
13
+ os.makedirs(dest_folder, exist_ok=True)
14
+
15
+ if not os.path.exists(src_folder):
16
+ print(f"Warning: {src_folder} not found. Skipping {class_name}.")
17
+ continue
18
+
19
+ files = [f for f in os.listdir(src_folder) if os.path.isfile(os.path.join(src_folder, f))]
20
+
21
+ # Calculate exactly 10% split
22
+ split_index = int(len(files) * split_ratio)
23
+
24
+ print(f"Class '{class_name}': Found {len(files)} training images.")
25
+ print(f"Class '{class_name}': Splicing {split_index} images to the validation set...")
26
+
27
+ # Shuffle deterministically to prevent bias
28
+ random.shuffle(files)
29
+ val_files = files[:split_index]
30
+
31
+ # Move files over to the validation array
32
+ for file in tqdm(val_files, desc=f"Migrating {class_name} images"):
33
+ src_path = os.path.join(src_folder, file)
34
+ dest_path = os.path.join(dest_folder, file)
35
+ shutil.move(src_path, dest_path)
36
+
37
+ print(f"Class '{class_name}': Split operation permanently completed.\n")
38
+
39
+ if __name__ == "__main__":
40
+ split_dataset("dataset/processed_train", "dataset/processed_val", split_ratio=0.1)
41
+ print("=== SYNCHRONIZATION COMPLETE ===")
42
+ print("DataLoader dependencies securely satisfied. Ready for pure model training.")
src/app/api/decision/route.ts DELETED
@@ -1,133 +0,0 @@
1
- import { NextResponse } from "next/server";
2
- import OpenAI from "openai";
3
-
4
- const openai = new OpenAI({
5
- baseURL: "https://api.featherless.ai/v1",
6
- apiKey: process.env.FEATHERLESS_API_KEY || "dummy",
7
- });
8
-
9
- export async function POST(req: Request) {
10
- try {
11
- const { searchParams } = new URL(req.url);
12
- const candidateId = searchParams.get('id');
13
- const body = await req.json();
14
- const { transcript, profile, targetRole, experienceLevel } = body;
15
-
16
- const targetPos = targetRole ? `${experienceLevel} ${targetRole}` : "Software Engineer";
17
-
18
- if (!candidateId) {
19
- return NextResponse.json({ success: false, error: "Missing candidate ID" }, { status: 400 });
20
- }
21
-
22
- const conversationStr = (transcript && transcript.length > 0)
23
- ? transcript.map((m: any) => `${m.role === 'ai' ? 'Interviewer' : 'Candidate'}: ${m.content}`).join("\n\n")
24
- : "Candidate provided no interview responses.";
25
-
26
- const basePrompt = `
27
- You are an elite multi-agent AI hiring committee evaluating a candidate for a ${targetPos} position.
28
- Below is the candidate's active Git/Portfolio profile signals AND their actual interview transcript.
29
-
30
- [CANDIDATE BASE PROFILE & GITHUB SIGNALS]
31
- ${profile || 'Not provided.'}
32
-
33
- [INTERVIEW TRANSCRIPT]
34
- ${conversationStr}
35
-
36
- You must evaluate the candidate's answers and their profile signals deeply against the specific requirements and industry standards for a ${targetPos}.
37
- Note where they show insight, and where they gave generic or weak answers.
38
- Respond with ONLY a valid JSON object matching this exact shape (no markdown, no backticks, just raw JSON):
39
- {
40
- "score": <number 0-100 reflecting their true performance based on transcript depth>,
41
- "decision": "<string: STRONG HIRE, HIRE, LEANING HIRE, or NO HIRE>",
42
- "insights": [
43
- { "label": "Technical Depth", "value": "<High/Medium/Low>", "desc": "<1 punchy sentence specifically referencing their technical arguments from the transcript>" },
44
- { "label": "Problem Solving", "value": "<High/Medium/Low>", "desc": "<1 punchy sentence evaluating their specific problem solving approach>" },
45
- { "label": "Communication", "value": "<High/Medium/Low>", "desc": "<1 punchy sentence evaluating how clearly they articulated complex ideas>" }
46
- ],
47
- "trajectory": {
48
- "industryFit": "<2 sentences explaining how their current skills map to the industry standard for a ${targetPos}>",
49
- "skillGaps": ["<specific skill 1>", "<specific skill 2>", "<specific skill 3>"],
50
- "careerPath": "<1 sentence predicting their trajectory if hired in this role>"
51
- },
52
- "agents": [
53
- {
54
- "role": "Technical Lead",
55
- "name": "Agent Alan",
56
- "verdict": "<Hire or No Hire>",
57
- "color": "blue",
58
- "reasoning": "<2 sentences evaluating their technical architecture choices or code intuition specifically cited from the transcript>"
59
- },
60
- {
61
- "role": "Culture & Product",
62
- "name": "Agent Grace",
63
- "verdict": "<Hire or No Hire>",
64
- "color": "purple",
65
- "reasoning": "<2 sentences evaluating their pragmatism and user empathy based on how they answered>"
66
- },
67
- {
68
- "role": "Risk Evaluator",
69
- "name": "Agent Ada",
70
- "verdict": "<Hire or No Hire>",
71
- "color": "amber",
72
- "reasoning": "<2 sentences explicitly calling out the weakest points of their answers or potential onboarding risks>"
73
- }
74
- ]
75
- }
76
- `;
77
-
78
- if (process.env.FEATHERLESS_API_KEY && process.env.FEATHERLESS_API_KEY !== 'your_featherless_api_key_here') {
79
- const completion = await openai.chat.completions.create({
80
- model: "meta-llama/Meta-Llama-3.1-70B-Instruct",
81
- messages: [
82
- { role: "system", content: "You are a JSON-only API. You must evaluate strictly based on the provided typescript and output raw JSON without code blocks." },
83
- { role: "user", content: basePrompt }
84
- ],
85
- max_tokens: 1500,
86
- temperature: 0.1
87
- });
88
-
89
- const content = completion.choices[0]?.message?.content || "";
90
- let jsonStr = content.replace(/```json/g, '').replace(/```/g, '').trim();
91
-
92
- // Safety fix if the model wrapped it in markdown anyway
93
- if (jsonStr.startsWith("json")) jsonStr = jsonStr.substring(4).trim();
94
-
95
- let parsedData;
96
- try {
97
- parsedData = JSON.parse(jsonStr);
98
- } catch (e) {
99
- console.error("Failed to parse JSON from AI", jsonStr);
100
- throw new Error("AI returned malformed JSON decision");
101
- }
102
-
103
- return NextResponse.json({ success: true, data: parsedData });
104
- } else {
105
- // Mock fallback
106
- await new Promise(resolve => setTimeout(resolve, 3000));
107
- return NextResponse.json({
108
- success: true,
109
- data: {
110
- score: 87,
111
- decision: "STRONG HIRE",
112
- insights: [
113
- { label: "Technical Depth", value: "High", desc: "Mock evaluation without API key." },
114
- { label: "Problem Solving", value: "High", desc: "Mock evaluation without API key." }
115
- ],
116
- agents: [
117
- { role: "Technical Lead", name: "Agent Alan", verdict: "Hire", color: "blue", reasoning: "Mock reasoning." },
118
- { role: "Culture & Product", name: "Agent Grace", verdict: "Hire", color: "purple", reasoning: "Mock reasoning." },
119
- { role: "Risk Evaluator", name: "Agent Ada", verdict: "Hire", color: "amber", reasoning: "Mock reasoning." }
120
- ],
121
- trajectory: {
122
- industryFit: "The candidate's technical background strongly aligns with modern standards for a " + targetPos + ". They demonstrate a solid understanding of core principles required at this level.",
123
- skillGaps: ["Advanced System Design", "Performance Profiling", "Cross-team Leadership"],
124
- careerPath: "Potential to grow into a senior leadership position within 2-3 years."
125
- }
126
- }
127
- });
128
- }
129
- } catch (error: any) {
130
- console.error("API Route Error:", error);
131
- return NextResponse.json({ success: false, error: error.message || "Failed to generate decision" }, { status: 500 });
132
- }
133
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/app/api/discovery/route.ts DELETED
@@ -1,89 +0,0 @@
1
- import { NextResponse } from "next/server";
2
- import OpenAI from "openai";
3
-
4
- const openai = new OpenAI({
5
- baseURL: "https://api.featherless.ai/v1",
6
- apiKey: process.env.FEATHERLESS_API_KEY || "dummy",
7
- });
8
-
9
- export async function POST(req: Request) {
10
- try {
11
- const data = await req.json();
12
- console.log("Processing candidate signals...", data.email);
13
- let enrichedData = "";
14
-
15
- // 1. Fetch live data enrichment
16
- if (process.env.BRIGHT_DATA_API_KEY && process.env.BRIGHT_DATA_API_KEY !== 'your_bright_data_api_key_here' && !process.env.BRIGHT_DATA_API_KEY.includes('dddf6404')) {
17
- try {
18
- // Using Bright Data Web Scraper API
19
- const bdResponse = await fetch('https://api.brightdata.com/dca/trigger?collector=c_linkedin_profile', {
20
- method: 'POST',
21
- headers: { 'Authorization': `Bearer ${process.env.BRIGHT_DATA_API_KEY}`, 'Content-Type': 'application/json' },
22
- body: JSON.stringify([{ url: data.linkedin }])
23
- });
24
- enrichedData = JSON.stringify(await bdResponse.json());
25
- } catch (e) {
26
- console.warn("Bright Data enrichment failed, proceeding with direct inputs only.", e);
27
- }
28
- } else {
29
- // Fallback real-world basic scraping using free public API
30
- try {
31
- const gitRes = await fetch(`https://api.microlink.io?url=${encodeURIComponent(data.github)}`);
32
- const gitData = await gitRes.json();
33
-
34
- const linRes = await fetch(`https://api.microlink.io?url=${encodeURIComponent(data.linkedin)}`);
35
- const linData = await linRes.json();
36
-
37
- enrichedData = JSON.stringify({
38
- githubHeadline: gitData?.data?.description || "No public bio.",
39
- linkedinHeadline: linData?.data?.description || "No public bio.",
40
- });
41
- } catch (e) {
42
- enrichedData = "Simulated Fallback: Candidate has 5+ years of experience.";
43
- }
44
- }
45
-
46
- // 2. Use Featherless AI to generate a 'Candidate Talent Discovery Profile'.
47
- if (process.env.FEATHERLESS_API_KEY && process.env.FEATHERLESS_API_KEY !== 'your_featherless_api_key_here') {
48
- const prompt = `
49
- Analyze the following candidate signals and determine their core strengths.
50
- Candidate Inputs:
51
- LinkedIn: ${data.linkedin}
52
- GitHub: ${data.github}
53
- Achievements: ${data.achievements}
54
- Problem Solving Example: ${data.problemSolving}
55
- Enriched Data: ${enrichedData}
56
-
57
- Respond with a short summary of their profile.
58
- `;
59
-
60
- const completion = await openai.chat.completions.create({
61
- model: "meta-llama/Meta-Llama-3.1-70B-Instruct",
62
- messages: [{ role: "user", content: prompt }],
63
- max_tokens: 1000,
64
- });
65
- console.log("Featherless AI Discovery Analysis:", completion.choices[0]?.message?.content);
66
- } else {
67
- await new Promise(resolve => setTimeout(resolve, 2000));
68
- }
69
-
70
- const candidateId = "cand_" + Math.random().toString(36).substring(2, 9);
71
-
72
- const profileSummary = `
73
- GitHub: ${data.github}
74
- LinkedIn: ${data.linkedin}
75
- Achievements: ${data.achievements}
76
- Bright Data Enriched Git Signals: ${enrichedData}
77
- `;
78
-
79
- return NextResponse.json({
80
- success: true,
81
- candidateId,
82
- profile: profileSummary,
83
- message: "Candidate signals analyzed successfully."
84
- });
85
- } catch (error: any) {
86
- console.error("API Route Error:", error);
87
- return NextResponse.json({ success: false, error: error.message || "Failed to process signals" }, { status: 500 });
88
- }
89
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/app/api/interview/route.ts DELETED
@@ -1,85 +0,0 @@
1
- import { NextResponse } from "next/server";
2
- import OpenAI from "openai";
3
-
4
- const openai = new OpenAI({
5
- baseURL: "https://api.featherless.ai/v1",
6
- apiKey: process.env.FEATHERLESS_API_KEY || "dummy",
7
- });
8
-
9
- export async function POST(req: Request) {
10
- try {
11
- const body = await req.json();
12
- const { messages, targetRole, experienceLevel } = body;
13
-
14
- const targetPos = targetRole ? `${experienceLevel} ${targetRole}` : "Software Engineer";
15
-
16
- const isFinishing = messages.length >= 11;
17
-
18
- let aiResponse = "";
19
-
20
- if (
21
- process.env.FEATHERLESS_API_KEY &&
22
- process.env.FEATHERLESS_API_KEY !== "your_featherless_api_key_here"
23
- ) {
24
- const formattedMessages = messages.map((m: any) => ({
25
- role: m.role === "ai" ? "assistant" : "user",
26
- content: m.content,
27
- }));
28
-
29
- let systemInstruction =
30
- `You are the TalentLens AI interviewer evaluating a candidate for a ${targetPos} position. Ask deep, specific follow-up questions based on their previous answers. Ask only one question at a time. Be conversational but ensure they demonstrate the required skills for a ${targetPos}.`;
31
-
32
- if (messages.length === 9) {
33
- systemInstruction =
34
- "You are now Agent Ada, the cynical Risk Evaluator for this panel. The official interview is over. You must explicitly start by saying 'I am Agent Ada, the Risk Evaluator.' Then, identify ONE glaring weakness, missing edge case, or assumption in the candidate's previous technical answers in this transcript. Aggressively but professionally challenge them to defend that choice.";
35
- } else if (messages.length >= 10 && isFinishing) {
36
- systemInstruction =
37
- "You are Agent Ada. Acknowledge the candidate's defense concisely. Do not ask any more questions. State clearly that the interview is now fully concluded and the panel will make its final decision based on their defense.";
38
- }
39
-
40
- const completion = await openai.chat.completions.create({
41
- model: "meta-llama/Meta-Llama-3.1-70B-Instruct",
42
- messages: [
43
- { role: "system", content: systemInstruction },
44
- ...formattedMessages,
45
- ],
46
- max_tokens: 1000,
47
- });
48
-
49
- aiResponse =
50
- completion.choices[0]?.message?.content ||
51
- "Could you elaborate further on that?";
52
- } else {
53
- if (messages.length === 9) {
54
- aiResponse =
55
- "I am Agent Ada, the Risk Evaluator. I noticed you didn't mention database caching in your previous architecture rundown. How would you handle a sudden 10x read spike? Defend your architecture.";
56
- } else if (messages.length >= 11) {
57
- aiResponse =
58
- "Noted. Your defense has been recorded. The interview is now concluded, and the panel will deliberate.";
59
- } else {
60
- await new Promise((resolve) => setTimeout(resolve, 2000));
61
- aiResponse =
62
- "Mock: That's interesting. Could you dive deeper into that approach?";
63
- }
64
- }
65
-
66
- return NextResponse.json({
67
- success: true,
68
- message: {
69
- id: Date.now().toString(),
70
- role: "ai",
71
- content: aiResponse,
72
- },
73
- isComplete: isFinishing,
74
- });
75
- } catch (error: any) {
76
- console.error("API Route Error:", error);
77
- return NextResponse.json(
78
- {
79
- success: false,
80
- error: error.message || "Failed to process interview response",
81
- },
82
- { status: 500 },
83
- );
84
- }
85
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/app/apply/page.tsx DELETED
@@ -1,143 +0,0 @@
1
- "use client";
2
-
3
- import { useState } from "react";
4
- import { useRouter } from "next/navigation";
5
-
6
- export default function ApplyPage() {
7
- const router = useRouter();
8
- const [isSubmitting, setIsSubmitting] = useState(false);
9
- const [formData, setFormData] = useState({
10
- name: "",
11
- email: "",
12
- linkedin: "",
13
- github: "",
14
- portfolio: "",
15
- achievements: "",
16
- problemSolving: "",
17
- targetRole: "",
18
- experienceLevel: "Mid-Level",
19
- });
20
-
21
- const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
22
- const { name, value } = e.target;
23
- setFormData((prev) => ({ ...prev, [name]: value }));
24
- };
25
-
26
- const handleSubmit = async (e: React.FormEvent) => {
27
- e.preventDefault();
28
- if (isSubmitting) return;
29
- setIsSubmitting(true);
30
-
31
- try {
32
- const res = await fetch('/api/discovery', {
33
- method: 'POST',
34
- headers: { 'Content-Type': 'application/json' },
35
- body: JSON.stringify(formData),
36
- });
37
- const data = await res.json();
38
- if (data.success) {
39
- if (typeof window !== "undefined") {
40
- window.localStorage.setItem('candidateProfile', data.profile);
41
- window.localStorage.setItem('targetRole', formData.targetRole);
42
- window.localStorage.setItem('experienceLevel', formData.experienceLevel);
43
- window.localStorage.removeItem('candidateTranscript');
44
- }
45
- router.push(`/interview/${data.candidateId}`);
46
- } else {
47
- alert('Failed to process application: ' + (data.error || 'Unknown error. Check terminal.'));
48
- setIsSubmitting(false);
49
- }
50
- } catch (e: any) {
51
- console.error(e);
52
- alert('Network Error: ' + e.message);
53
- setIsSubmitting(false);
54
- }
55
- };
56
-
57
- return (
58
- <div className="max-w-3xl mx-auto px-4 sm:px-6 animate-fade-in-up">
59
- <div className="mb-8 text-center">
60
- <h1 className="text-3xl sm:text-4xl font-black tracking-tight mb-3 sm:mb-4 text-slate-900">Candidate <span className="text-transparent bg-clip-text bg-gradient-to-r from-blue-600 to-indigo-600">Application</span></h1>
61
- <p className="text-slate-600 text-sm sm:text-base">Submit your real-world signals. We evaluate your potential, not just your past.</p>
62
- </div>
63
-
64
- <form onSubmit={handleSubmit} className="bg-white premium-shadow rounded-2xl sm:rounded-3xl p-5 sm:p-10 space-y-8 border border-slate-200">
65
- <div className="space-y-6">
66
- <h2 className="text-xl font-semibold text-slate-900 border-b border-slate-200 pb-2">Basic Info</h2>
67
- <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
68
- <div className="space-y-2">
69
- <label htmlFor="name" className="block text-sm font-medium text-slate-700">Full Name</label>
70
- <input required type="text" id="name" name="name" value={formData.name} onChange={handleChange} className="w-full bg-white border border-slate-300 rounded-xl px-4 py-3 text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500/50 transition-all placeholder:text-slate-400" placeholder="Jane Doe" />
71
- </div>
72
- <div className="space-y-2">
73
- <label htmlFor="email" className="block text-sm font-medium text-slate-700">Email Address</label>
74
- <input required type="email" id="email" name="email" value={formData.email} onChange={handleChange} className="w-full bg-white border border-slate-300 rounded-xl px-4 py-3 text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500/50 transition-all placeholder:text-slate-400" placeholder="jane@example.com" />
75
- </div>
76
- </div>
77
- </div>
78
-
79
- <div className="space-y-6">
80
- <h2 className="text-xl font-semibold text-slate-900 border-b border-slate-200 pb-2">Target Position</h2>
81
- <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
82
- <div className="space-y-2">
83
- <label htmlFor="targetRole" className="block text-sm font-medium text-slate-700">Job Role Applying For</label>
84
- <input required type="text" id="targetRole" name="targetRole" value={formData.targetRole} onChange={handleChange} className="w-full bg-white border border-slate-300 rounded-xl px-4 py-3 text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500/50 transition-all placeholder:text-slate-400" placeholder="e.g. Frontend Developer, Data Scientist" />
85
- </div>
86
- <div className="space-y-2">
87
- <label htmlFor="experienceLevel" className="block text-sm font-medium text-slate-700">Experience Level</label>
88
- <select required id="experienceLevel" name="experienceLevel" value={formData.experienceLevel} onChange={(e: any) => handleChange(e)} className="w-full bg-white border border-slate-300 rounded-xl px-4 py-3 text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500/50 transition-all appearance-none pr-10">
89
- <option value="Junior">Junior (0-2 years)</option>
90
- <option value="Mid-Level">Mid-Level (3-5 years)</option>
91
- <option value="Senior">Senior (5-8 years)</option>
92
- <option value="Lead/Staff">Lead / Staff (8+ years)</option>
93
- </select>
94
- <div className="absolute inset-y-0 right-0 flex items-center px-4 pointer-events-none mt-[28px]">
95
- <svg className="w-4 h-4 text-slate-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 9l-7 7-7-7"></path></svg>
96
- </div>
97
- </div>
98
- </div>
99
- </div>
100
-
101
- <div className="space-y-6">
102
- <h2 className="text-xl font-semibold text-slate-900 border-b border-slate-200 pb-2">Digital Footprint</h2>
103
- <div className="space-y-4">
104
- <div className="space-y-2">
105
- <label htmlFor="linkedin" className="block text-sm font-medium text-slate-700">LinkedIn Profile</label>
106
- <input required type="url" id="linkedin" name="linkedin" value={formData.linkedin} onChange={handleChange} className="w-full bg-white border border-slate-300 rounded-xl px-4 py-3 text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500/50 transition-all placeholder:text-slate-400" placeholder="https://linkedin.com/in/janedoe" />
107
- </div>
108
- <div className="space-y-2">
109
- <label htmlFor="github" className="block text-sm font-medium text-slate-700">GitHub Profile</label>
110
- <input required type="url" id="github" name="github" value={formData.github} onChange={handleChange} className="w-full bg-white border border-slate-300 rounded-xl px-4 py-3 text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500/50 transition-all placeholder:text-slate-400" placeholder="https://github.com/janedoe" />
111
- </div>
112
- <div className="space-y-2">
113
- <label htmlFor="portfolio" className="block text-sm font-medium text-slate-700">Portfolio / Personal Site</label>
114
- <input type="url" id="portfolio" name="portfolio" value={formData.portfolio} onChange={handleChange} className="w-full bg-white border border-slate-300 rounded-xl px-4 py-3 text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500/50 transition-all placeholder:text-slate-400" placeholder="https://janedoe.dev" />
115
- </div>
116
- </div>
117
- </div>
118
-
119
- <div className="space-y-6">
120
- <h2 className="text-xl font-semibold text-slate-900 border-b border-slate-200 pb-2">Beyond the Resume</h2>
121
- <div className="space-y-4">
122
- <div className="space-y-2">
123
- <label htmlFor="achievements" className="block text-sm font-medium text-slate-700">Key Achievements</label>
124
- <p className="text-xs text-slate-500">Briefly list your top 3 professional or personal achievements.</p>
125
- <textarea required id="achievements" name="achievements" value={formData.achievements} onChange={handleChange} rows={3} className="w-full bg-white border border-slate-300 rounded-xl px-4 py-3 text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500/50 transition-all placeholder:text-slate-400 resize-none" placeholder="- Scaled database to 1M daily queries&#10;- Won 1st place at HackMIT&#10;- Maintained an open source library with 5k stars"></textarea>
126
- </div>
127
- <div className="space-y-2">
128
- <label htmlFor="problemSolving" className="block text-sm font-medium text-slate-700">Base Problem Solving</label>
129
- <p className="text-xs text-slate-500">Describe a complex technical problem you solved, how you approached it, and what you learned.</p>
130
- <textarea required id="problemSolving" name="problemSolving" value={formData.problemSolving} onChange={handleChange} rows={5} className="w-full bg-white border border-slate-300 rounded-xl px-4 py-3 text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500/50 transition-all placeholder:text-slate-400 resize-none" placeholder="When migrating our monolithic architecture to microservices..."></textarea>
131
- </div>
132
- </div>
133
- </div>
134
-
135
- <div className="pt-4">
136
- <button type="submit" disabled={isSubmitting} className="w-full py-4 rounded-xl bg-slate-900 text-white font-bold text-lg hover:bg-slate-800 transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center premium-shadow">
137
- {isSubmitting ? "Moving to Interview Round..." : "Submit & Start Adaptive Interview"}
138
- </button>
139
- </div>
140
- </form>
141
- </div>
142
- );
143
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/app/dashboard/[id]/page.tsx DELETED
@@ -1,216 +0,0 @@
1
- "use client";
2
-
3
- import { useParams } from "next/navigation";
4
- import Link from "next/link";
5
- import { useEffect, useState, useRef } from "react";
6
-
7
- type Insight = { label: string; value: string; desc: string; };
8
- type Agent = { role: string; name: string; verdict: string; color: string; reasoning: string; };
9
- type Trajectory = { industryFit: string; skillGaps: string[]; careerPath: string; };
10
- type DashboardData = { score: number; decision: string; insights: Insight[]; agents: Agent[]; trajectory: Trajectory; };
11
-
12
- const getAgentStyles = (color: string) => {
13
- switch (color) {
14
- case 'blue': return { bgLight: 'bg-blue-50 hover:bg-blue-100', text: 'text-blue-700', bg: 'bg-blue-600', shadow: 'shadow-blue-500/20', border: 'border-blue-100' };
15
- case 'purple': return { bgLight: 'bg-purple-50 hover:bg-purple-100', text: 'text-purple-700', bg: 'bg-purple-600', shadow: 'shadow-purple-500/20', border: 'border-purple-100' };
16
- case 'amber': return { bgLight: 'bg-amber-50 hover:bg-amber-100', text: 'text-amber-700', bg: 'bg-amber-500', shadow: 'shadow-amber-500/20', border: 'border-amber-100' };
17
- default: return { bgLight: 'bg-slate-50 hover:bg-slate-100', text: 'text-slate-700', bg: 'bg-slate-600', shadow: 'shadow-slate-500/20', border: 'border-slate-200' };
18
- }
19
- };
20
-
21
- export default function DashboardPage() {
22
- const params = useParams();
23
- const candidateId = params.id as string;
24
- const [loading, setLoading] = useState(true);
25
- const [data, setData] = useState<DashboardData | null>(null);
26
- const [targetPos, setTargetPos] = useState<string>("Software Engineer");
27
- const hasFetched = useRef(false);
28
-
29
- useEffect(() => {
30
- if (hasFetched.current) return;
31
- hasFetched.current = true;
32
-
33
- const fetchDecision = async () => {
34
- try {
35
- let transcript = [];
36
- let profile = "";
37
- let targetRole = "";
38
- let experienceLevel = "";
39
- if (typeof window !== "undefined") {
40
- const locallySaved = window.localStorage.getItem('candidateTranscript');
41
- if (locallySaved) transcript = JSON.parse(locallySaved);
42
- profile = window.localStorage.getItem('candidateProfile') || "No profile available.";
43
- targetRole = window.localStorage.getItem('targetRole') || "";
44
- experienceLevel = window.localStorage.getItem('experienceLevel') || "";
45
-
46
- if (targetRole) {
47
- setTargetPos(`${experienceLevel} ${targetRole}`);
48
- }
49
- }
50
- const res = await fetch(`/api/decision?id=${candidateId}`, {
51
- method: 'POST',
52
- headers: { 'Content-Type': 'application/json' },
53
- body: JSON.stringify({ transcript, profile, targetRole, experienceLevel })
54
- });
55
- const result = await res.json();
56
- if (result.success) {
57
- setData(result.data);
58
-
59
- if (typeof window !== "undefined") {
60
- try {
61
- const history = JSON.parse(window.localStorage.getItem('dashboardHistory') || '[]');
62
- const exists = history.find((h: any) => h.id === candidateId);
63
- if (!exists) {
64
- history.unshift({
65
- id: candidateId,
66
- role: targetRole,
67
- level: experienceLevel,
68
- score: result.data.score,
69
- decision: result.data.decision,
70
- date: new Date().toISOString()
71
- });
72
- window.localStorage.setItem('dashboardHistory', JSON.stringify(history.slice(0, 50)));
73
- }
74
- } catch (e) {
75
- console.error("Failed to save history", e);
76
- }
77
- }
78
- }
79
- } catch (error) {
80
- console.error("Failed to load dashboard data");
81
- } finally {
82
- setLoading(false);
83
- }
84
- };
85
- fetchDecision();
86
- }, [candidateId]);
87
-
88
- if (loading || !data) {
89
- return (
90
- <div className="flex flex-col items-center justify-center min-h-[70vh] px-4 animate-pulse duration-1000">
91
- <div className="relative w-24 h-24 mb-6">
92
- <div className="absolute inset-0 border-4 border-slate-100 rounded-full"></div>
93
- <div className="absolute inset-0 border-4 border-blue-600 rounded-full border-t-transparent animate-spin"></div>
94
- </div>
95
- <h2 className="text-2xl font-bold text-slate-900 tracking-widest uppercase mb-2">Simulating Panel</h2>
96
- <p className="text-slate-500 font-mono text-sm">Aggregating multi-agent independent evaluations...</p>
97
- </div>
98
- );
99
- }
100
-
101
- return (
102
- <div className="max-w-6xl mx-auto px-4 pb-20 animate-fade-in-up">
103
- <div className="flex flex-col md:flex-row justify-between items-start md:items-end mb-12 gap-6 relative z-10">
104
- <div>
105
- <div className="flex items-center gap-3 mb-2">
106
- <span className="px-3 py-1 rounded-full bg-green-100 text-green-700 text-xs font-bold tracking-widest uppercase border border-green-200">Evaluation Complete</span>
107
- <span className="text-slate-500 font-mono text-xs">ID: {candidateId}</span>
108
- </div>
109
- <h1 className="text-4xl md:text-5xl font-black text-slate-900 tracking-tight">Panel <span className="text-transparent bg-clip-text bg-gradient-to-r from-blue-600 to-indigo-600">Decision</span></h1>
110
- <p className="text-lg text-slate-600 mt-2 font-medium">For: <span className="text-blue-700 font-bold">{targetPos}</span></p>
111
- </div>
112
-
113
- <div className="flex items-center gap-6 bg-white px-8 py-5 rounded-3xl premium-shadow border border-slate-200">
114
- <div className="text-center">
115
- <p className="text-sm text-slate-500 uppercase tracking-widest font-semibold mb-1">Score</p>
116
- <p className="text-5xl font-black text-slate-900">{data.score}<span className="text-xl text-slate-400">/100</span></p>
117
- </div>
118
- <div className="h-16 w-px bg-slate-200"></div>
119
- <div className="text-center">
120
- <p className="text-sm text-slate-500 uppercase tracking-widest font-semibold mb-1">Verdict</p>
121
- <p className="text-2xl font-black text-green-600 uppercase tracking-widest">{data.decision}</p>
122
- </div>
123
- </div>
124
- </div>
125
-
126
- <h2 className="text-2xl font-bold text-slate-900 mb-6 border-b border-slate-200 pb-4 relative z-10">Discovery Engine Insights</h2>
127
- <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-16 relative z-10">
128
- {data.insights.map((insight, i) => (
129
- <div key={i} className="bg-white rounded-3xl p-6 border border-slate-200 premium-shadow">
130
- <h3 className="text-xs text-slate-500 uppercase tracking-widest font-bold mb-2">{insight.label}</h3>
131
- <p className="text-3xl font-black text-slate-900 mb-3 tracking-tight">{insight.value}</p>
132
- <p className="text-sm text-slate-600 leading-relaxed">{insight.desc}</p>
133
- </div>
134
- ))}
135
- </div>
136
-
137
- <h2 className="text-2xl font-bold text-slate-900 mb-6 border-b border-slate-200 pb-4 relative z-10">Industry Fit & Career Trajectory</h2>
138
- <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-16 relative z-10">
139
- <div className="bg-slate-900 rounded-3xl p-6 md:p-8 border border-slate-800 premium-shadow text-white">
140
- <div className="flex items-center gap-3 mb-4">
141
- <div className="p-2 bg-blue-500/20 rounded-lg">
142
- <svg className="w-5 h-5 text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"></path></svg>
143
- </div>
144
- <h3 className="text-xl font-bold tracking-tight">Market Alignment</h3>
145
- </div>
146
- <p className="text-slate-300 leading-relaxed font-medium">{data.trajectory.industryFit}</p>
147
-
148
- <div className="mt-6 pt-6 border-t border-slate-800">
149
- <h4 className="text-xs text-slate-400 uppercase tracking-widest font-bold mb-3">Projected Trajectory</h4>
150
- <p className="text-amber-300 tracking-wide font-medium">{data.trajectory.careerPath}</p>
151
- </div>
152
- </div>
153
-
154
- <div className="bg-white rounded-3xl p-6 md:p-8 border border-slate-200 premium-shadow">
155
- <div className="flex items-center gap-3 mb-4">
156
- <div className="p-2 bg-red-50 rounded-lg">
157
- <svg className="w-5 h-5 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path></svg>
158
- </div>
159
- <h3 className="text-xl font-bold text-slate-900 tracking-tight">Identified Skill Gaps</h3>
160
- </div>
161
- <ul className="space-y-3 mt-4">
162
- {data.trajectory.skillGaps.map((gap, i) => (
163
- <li key={i} className="flex items-start gap-3">
164
- <span className="flex-shrink-0 w-1.5 h-1.5 rounded-full bg-red-400 mt-2"></span>
165
- <span className="text-slate-600 font-medium">{gap}</span>
166
- </li>
167
- ))}
168
- {data.trajectory.skillGaps.length === 0 && (
169
- <li className="text-slate-500 italic">No significant skill gaps identified for this level.</li>
170
- )}
171
- </ul>
172
- </div>
173
- </div>
174
-
175
- <h2 className="text-2xl font-bold text-slate-900 mb-6 border-b border-slate-200 pb-4 flex items-center gap-3 relative z-10">
176
- Multi-Agent Evaluation
177
- <span className="text-xs font-bold tracking-widest uppercase text-blue-700 bg-blue-50 border border-blue-200 px-3 py-1 rounded-full">Simulated Panel</span>
178
- </h2>
179
-
180
- <div className="grid grid-cols-1 md:grid-cols-3 gap-6 relative z-10">
181
- {data.agents.map((agent, i) => {
182
- const styles = getAgentStyles(agent.color);
183
- return (
184
- <div key={i} className={`bg-white rounded-3xl p-6 md:p-8 flex flex-col h-full border ${styles.border} premium-shadow relative overflow-hidden`}>
185
- <div className="flex items-center gap-4 mb-6 relative z-10">
186
- <div className={`w-14 h-14 rounded-2xl ${styles.bg} flex items-center justify-center shadow-lg ${styles.shadow} text-white font-black text-xl`}>
187
- {agent.name.split(' ')[1].charAt(0)}
188
- </div>
189
- <div>
190
- <h3 className="text-xl font-bold text-slate-900 tracking-tight">{agent.name}</h3>
191
- <p className={`text-xs uppercase tracking-widest ${styles.text} font-bold mt-1`}>{agent.role}</p>
192
- </div>
193
- </div>
194
-
195
- <div className="mb-6 relative z-10">
196
- <span className={`inline-block px-4 py-1.5 rounded-full text-xs font-bold uppercase tracking-widest border ${styles.bgLight} ${styles.text} ${styles.border}`}>
197
- {agent.verdict}
198
- </span>
199
- </div>
200
-
201
- <div className="flex-1 relative z-10">
202
- <p className="text-slate-600 leading-relaxed text-[15px] font-medium">"{agent.reasoning}"</p>
203
- </div>
204
- </div>
205
- );
206
- })}
207
- </div>
208
-
209
- <div className="mt-20 text-center relative z-10 border-t border-slate-200 pt-10">
210
- <Link href="/" className="inline-flex px-10 py-4 rounded-full bg-slate-900 hover:bg-slate-800 text-white font-bold transition-all premium-shadow">
211
- New Evaluation
212
- </Link>
213
- </div>
214
- </div>
215
- );
216
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/app/dashboard/page.tsx DELETED
@@ -1,107 +0,0 @@
1
- "use client";
2
-
3
- import Link from "next/link";
4
- import { useAuth } from "@clerk/nextjs";
5
- import { useRouter } from "next/navigation";
6
- import { useEffect, useState } from "react";
7
-
8
- export default function DashboardPage() {
9
- const { userId, isLoaded } = useAuth();
10
- const router = useRouter();
11
- const [history, setHistory] = useState<any[]>([]);
12
-
13
- useEffect(() => {
14
- if (isLoaded && !userId) {
15
- router.push("/sign-in");
16
- }
17
- }, [isLoaded, userId, router]);
18
-
19
- useEffect(() => {
20
- if (typeof window !== "undefined") {
21
- try {
22
- const savedHistory = JSON.parse(window.localStorage.getItem('dashboardHistory') || '[]');
23
- setHistory(savedHistory);
24
- } catch (e) {
25
- console.error("Failed to load history");
26
- }
27
- }
28
- }, []);
29
-
30
- if (!isLoaded || !userId) return null;
31
-
32
- return (
33
- <div className="flex flex-col items-center justify-start min-h-screen p-4 sm:p-8 bg-slate-50">
34
- <div className="max-w-6xl w-full mx-auto animate-fade-in-up">
35
- <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6 sm:mb-10">
36
- <div>
37
- <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-slate-900 mb-1">
38
- Dashboard
39
- </h1>
40
- <p className="text-slate-500 text-xs sm:text-sm">Manage your candidate interviews and evaluations.</p>
41
- </div>
42
- <Link href="/apply" className="w-full sm:w-auto text-center px-5 py-2.5 rounded-lg bg-blue-600 text-white font-medium hover:bg-blue-700 transition-colors shadow-sm text-sm">
43
- New Interview
44
- </Link>
45
- </div>
46
-
47
- {history.length === 0 ? (
48
- <div className="bg-white rounded-xl p-6 sm:p-10 border border-slate-200 shadow-sm min-h-[300px] sm:min-h-[400px] flex flex-col items-center justify-center text-center">
49
- <div className="h-16 w-16 bg-slate-50 rounded-full flex items-center justify-center mb-5 border border-slate-100">
50
- <svg className="w-8 h-8 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
51
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
52
- </svg>
53
- </div>
54
- <h3 className="text-xl font-medium text-slate-900 mb-2">No Recent Activity</h3>
55
- <p className="text-slate-500 mb-6 max-w-md">
56
- Start a new candidate journey by inviting someone to an interview, or check back later to view completed evaluations.
57
- </p>
58
- </div>
59
- ) : (
60
- <div className="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden">
61
- <div className="hidden sm:grid grid-cols-5 gap-4 bg-slate-50 px-6 py-3 border-b border-slate-200 text-xs font-semibold text-slate-500 uppercase tracking-wider">
62
- <div className="col-span-2">Candidate Evaluation</div>
63
- <div>Position</div>
64
- <div className="text-center">Score</div>
65
- <div className="text-right">Action</div>
66
- </div>
67
- <div className="divide-y divide-slate-100">
68
- {history.map((candidate, i) => (
69
- <div key={i} className="grid grid-cols-1 sm:grid-cols-5 gap-4 items-center px-4 sm:px-6 py-4 hover:bg-slate-50 transition-colors">
70
- <div className="sm:col-span-2">
71
- <div className="flex items-center gap-3 mb-1">
72
- <span className={`px-2 py-0.5 rounded text-[10px] sm:text-xs font-bold uppercase tracking-wider ${
73
- candidate.decision.includes("HIRE") ? "bg-green-100 text-green-700" : "bg-red-100 text-red-700"
74
- }`}>
75
- {candidate.decision}
76
- </span>
77
- </div>
78
- <p className="text-slate-500 text-xs font-mono truncate max-w-[200px]">ID: {candidate.id || "Anonymous"}</p>
79
- <p className="text-slate-400 text-xs mt-1">{new Date(candidate.date).toLocaleDateString()}</p>
80
- </div>
81
- <div className="hidden sm:block">
82
- <p className="text-slate-900 text-sm font-medium">{candidate.role || "Software Engineer"}</p>
83
- <p className="text-slate-500 text-xs">{candidate.level || "Senior"}</p>
84
- </div>
85
- <div className="hidden sm:block text-center">
86
- <span className="text-xl font-bold text-slate-900">{candidate.score}</span>
87
- <span className="text-xs text-slate-400">/100</span>
88
- </div>
89
- <div className="flex justify-between sm:justify-end items-center mt-2 sm:mt-0">
90
- <div className="sm:hidden block">
91
- <p className="text-slate-900 text-sm font-medium">{candidate.role || "Software Engineer"}</p>
92
- <span className="text-lg font-bold text-slate-900 mr-1">{candidate.score}</span>
93
- <span className="text-xs text-slate-400">/100</span>
94
- </div>
95
- <Link href={`/dashboard/${candidate.id}`} className="px-4 py-2 bg-slate-900 text-white text-xs font-medium rounded-lg hover:bg-slate-800 transition-colors">
96
- View Panel
97
- </Link>
98
- </div>
99
- </div>
100
- ))}
101
- </div>
102
- </div>
103
- )}
104
- </div>
105
- </div>
106
- );
107
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/app/favicon.ico DELETED
Binary file (25.9 kB)
 
src/app/globals.css DELETED
@@ -1,47 +0,0 @@
1
- @import "tailwindcss";
2
-
3
- :root {
4
- --background: #ffffff;
5
- --foreground: #0f172a;
6
- --primary: #0f172a;
7
- --secondary: #475569;
8
- }
9
-
10
- @theme inline {
11
- --color-background: var(--background);
12
- --color-foreground: var(--foreground);
13
- --color-primary: var(--primary);
14
- --color-secondary: var(--secondary);
15
- --font-sans: var(--font-geist-sans);
16
- --font-mono: var(--font-geist-mono);
17
- }
18
-
19
- body {
20
- background: var(--background);
21
- color: var(--foreground);
22
- font-family: var(--font-sans), Arial, Helvetica, sans-serif;
23
- overflow-x: hidden;
24
- -webkit-font-smoothing: antialiased;
25
- -moz-osx-font-smoothing: grayscale;
26
- }
27
-
28
- .premium-shadow {
29
- box-shadow: 0 4px 20px -2px rgba(0, 0, 0, 0.05), 0 0 3px rgba(0,0,0,0.02);
30
- }
31
-
32
- @keyframes fade-in-up {
33
- 0% { opacity: 0; transform: translateY(15px); }
34
- 100% { opacity: 1; transform: translateY(0); }
35
- }
36
- .animate-fade-in-up {
37
- animation: fade-in-up 0.7s cubic-bezier(0.16, 1, 0.3, 1) forwards;
38
- }
39
-
40
- /* Hidden scrollbar but keep functionality */
41
- .scrollbar-hide::-webkit-scrollbar {
42
- display: none;
43
- }
44
- .scrollbar-hide {
45
- -ms-overflow-style: none;
46
- scrollbar-width: none;
47
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/app/interview/[id]/page.tsx DELETED
@@ -1,292 +0,0 @@
1
- "use client";
2
-
3
- import { useState, useEffect, useRef, useCallback } from "react";
4
- import { useParams, useRouter } from "next/navigation";
5
-
6
- type Message = { id: string; role: "ai" | "candidate"; content: string; isAgentAda?: boolean; };
7
-
8
- export default function InterviewPage() {
9
- const params = useParams();
10
- const router = useRouter();
11
- const candidateId = params.id as string;
12
-
13
- const [messages, setMessages] = useState<Message[]>([]);
14
- const [input, setInput] = useState("");
15
- const [isTyping, setIsTyping] = useState(false);
16
- const [interviewComplete, setInterviewComplete] = useState(false);
17
- const [isListening, setIsListening] = useState(false);
18
- const [roleInfo, setRoleInfo] = useState({ targetRole: "", experienceLevel: "" });
19
- const [warnings, setWarnings] = useState(0);
20
- const [showWarning, setShowWarning] = useState(false);
21
- const [warningMessage, setWarningMessage] = useState("");
22
- const messagesEndRef = useRef<HTMLDivElement>(null);
23
- const recognitionRef = useRef<any>(null);
24
-
25
- useEffect(() => {
26
- if (typeof window !== "undefined") {
27
- const targetRole = window.localStorage.getItem("targetRole") || "Software Engineer";
28
- const experienceLevel = window.localStorage.getItem("experienceLevel") || "";
29
- setRoleInfo({ targetRole, experienceLevel });
30
-
31
- const targetPos = experienceLevel ? `${experienceLevel} ${targetRole}` : targetRole;
32
-
33
- setMessages([
34
- {
35
- id: "1",
36
- role: "ai",
37
- content: `Hello! I'm the TalentLens AI interviewer. We're excited you're applying for the ${targetPos} position. Based on the complex technical problem you described in your application, could you explain the specific trade-offs you considered when choosing your approach?`,
38
- }
39
- ]);
40
- }
41
- }, []);
42
-
43
- useEffect(() => {
44
- messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
45
- }, [messages]);
46
-
47
- useEffect(() => {
48
- if (typeof window !== 'undefined') {
49
- const SpeechRecognition = (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition;
50
- if (SpeechRecognition) {
51
- recognitionRef.current = new SpeechRecognition();
52
- recognitionRef.current.continuous = false;
53
- recognitionRef.current.interimResults = true;
54
-
55
- recognitionRef.current.onresult = (event: any) => {
56
- let currentTranscript = "";
57
- for (let i = event.resultIndex; i < event.results.length; i++) {
58
- currentTranscript += event.results[i][0].transcript;
59
- }
60
- setInput(currentTranscript);
61
- };
62
-
63
- recognitionRef.current.onerror = (event: any) => {
64
- console.error("Speech recognition error", event.error);
65
- setIsListening(false);
66
- };
67
-
68
- recognitionRef.current.onend = () => {
69
- setIsListening(false);
70
- };
71
- }
72
- }
73
- }, []);
74
-
75
- useEffect(() => {
76
- if (interviewComplete) return;
77
-
78
- const handleVisibilityChange = () => {
79
- if (document.hidden) {
80
- handleViolation("Tab switching or minimizing the browser is not allowed during the interview.");
81
- }
82
- };
83
-
84
- const handleBlur = () => {
85
- handleViolation("Window lost focus. Please keep the interview window active.");
86
- };
87
-
88
- document.addEventListener("visibilitychange", handleVisibilityChange);
89
- window.addEventListener("blur", handleBlur);
90
-
91
- return () => {
92
- document.removeEventListener("visibilitychange", handleVisibilityChange);
93
- window.removeEventListener("blur", handleBlur);
94
- };
95
- }, [interviewComplete]);
96
-
97
- const handleViolation = useCallback((reason: string) => {
98
- if (interviewComplete) return;
99
-
100
- setWarnings((prev) => {
101
- const newWarnings = prev + 1;
102
- if (newWarnings >= 3) {
103
- setInterviewComplete(true);
104
- const terminationMsg: Message = {
105
- id: Date.now().toString(),
106
- role: "ai",
107
- content: "System Notice: Interview forcibly terminated due to multiple policy violations (tab switching / loss of window focus). Please review your dashboard.",
108
- isAgentAda: true
109
- };
110
- setMessages(prevMsgs => [...prevMsgs, terminationMsg]);
111
- return newWarnings;
112
- }
113
-
114
- setWarningMessage(reason);
115
- setShowWarning(true);
116
- setTimeout(() => setShowWarning(false), 5000);
117
- return newWarnings;
118
- });
119
- }, [interviewComplete]);
120
-
121
- const toggleListening = () => {
122
- if (isListening) {
123
- recognitionRef.current?.stop();
124
- setIsListening(false);
125
- } else {
126
- if (!recognitionRef.current) {
127
- alert("Speech recognition is not supported in this browser. Try Chrome.");
128
- return;
129
- }
130
- setInput("");
131
- recognitionRef.current.start();
132
- setIsListening(true);
133
- }
134
- };
135
-
136
- const handleSend = async (e: React.FormEvent) => {
137
- e.preventDefault();
138
- if (!input.trim() || isTyping) return;
139
-
140
- const userMessage: Message = { id: Date.now().toString(), role: "candidate", content: input };
141
- setMessages((prev) => [...prev, userMessage]);
142
- setInput("");
143
- setIsTyping(true);
144
-
145
- try {
146
- const res = await fetch('/api/interview', {
147
- method: 'POST',
148
- headers: { 'Content-Type': 'application/json' },
149
- body: JSON.stringify({
150
- messages: [...messages, userMessage],
151
- targetRole: roleInfo.targetRole,
152
- experienceLevel: roleInfo.experienceLevel
153
- }),
154
- });
155
- const data = await res.json();
156
-
157
- if (data.success) {
158
- const updatedMessages = [...messages, userMessage, data.message];
159
- setMessages(updatedMessages);
160
-
161
- if ('speechSynthesis' in window) {
162
- const utterance = new SpeechSynthesisUtterance(data.message.content);
163
- const voices = window.speechSynthesis.getVoices();
164
- const preferredVoice = voices.find(v => v.name.includes("Google") || v.lang.includes("en-US"));
165
- if (preferredVoice) utterance.voice = preferredVoice;
166
- utterance.rate = 1.05;
167
- window.speechSynthesis.speak(utterance);
168
- }
169
- if (data.isComplete) {
170
- setInterviewComplete(true);
171
- if (typeof window !== "undefined") {
172
- window.localStorage.setItem('candidateTranscript', JSON.stringify(updatedMessages));
173
- }
174
- }
175
- }
176
- } catch (e) {
177
- console.error("Failed to fetch interview response:", e);
178
- } finally {
179
- setIsTyping(false);
180
- }
181
- };
182
-
183
- return (
184
- <div
185
- className="max-w-4xl mx-auto px-2 sm:px-4 h-[calc(100vh-8rem)] min-h-[500px] flex flex-col animate-fade-in-up select-none"
186
- onContextMenu={(e) => e.preventDefault()}
187
- >
188
- {showWarning && (
189
- <div className="fixed top-20 left-1/2 transform -translate-x-1/2 z-50 bg-red-600 text-white px-6 py-3 rounded-xl shadow-2xl flex items-center gap-3 animate-fade-in-down">
190
- <svg className="w-6 h-6 animate-pulse" fill="none" viewBox="0 0 24 24" stroke="currentColor">
191
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
192
- </svg>
193
- <div>
194
- <p className="font-bold text-sm">Policy Violation Detected!</p>
195
- <p className="text-xs text-red-100">Warning {warnings}/3: {warningMessage}</p>
196
- </div>
197
- </div>
198
- )}
199
- <div className="mb-4 sm:mb-6 flex flex-col sm:flex-row justify-start sm:justify-between items-start sm:items-center gap-3 sm:gap-0 bg-white border border-slate-200 rounded-2xl p-4 premium-shadow relative z-10">
200
- <div>
201
- <h1 className="text-lg sm:text-xl font-bold text-slate-900 flex items-center gap-2">
202
- <span className="relative flex h-3 w-3 flex-shrink-0">
203
- <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75"></span>
204
- <span className="relative inline-flex rounded-full h-3 w-3 bg-blue-500"></span>
205
- </span>
206
- Adaptive Interview Session
207
- </h1>
208
- <p className="text-xs sm:text-sm text-slate-500 mt-1 font-mono">ID: {candidateId}</p>
209
- </div>
210
- {interviewComplete && (
211
- <button
212
- onClick={() => router.push(`/dashboard/${candidateId}`)}
213
- className="w-full sm:w-auto px-4 sm:px-6 py-2 text-sm sm:text-base bg-slate-900 text-white font-medium rounded-full premium-shadow hover:bg-slate-800 transition-all animate-pulse"
214
- >
215
- Review Evaluation Dashboard
216
- </button>
217
- )}
218
- </div>
219
-
220
- <div className="flex-1 bg-slate-50 border border-slate-200 rounded-2xl sm:rounded-3xl p-3 sm:p-6 overflow-y-auto mb-4 sm:mb-6 flex flex-col space-y-4 sm:space-y-6 scrollbar-hide">
221
- {messages.map((msg) => (
222
- <div key={msg.id} className={`flex ${msg.role === "candidate" ? "justify-end" : "justify-start"}`}>
223
- <div className={`max-w-[95%] sm:max-w-[85%] rounded-2xl sm:rounded-3xl p-4 sm:p-5 text-sm sm:text-base ${
224
- msg.role === "candidate" ? "bg-slate-900 text-white rounded-tr-sm shadow-md" :
225
- msg.isAgentAda ? "bg-amber-50 text-amber-900 rounded-tl-sm border border-amber-200 shadow-sm" :
226
- "bg-white text-slate-800 rounded-tl-sm border border-slate-200 shadow-sm"
227
- }`}>
228
- {msg.role === "ai" && (
229
- <div className={`flex items-center gap-2 mb-3 border-b pb-2 ${msg.isAgentAda ? 'border-amber-200/50' : 'border-slate-100'}`}>
230
- <div className={`w-6 h-6 rounded-full flex items-center justify-center ${msg.isAgentAda ? 'bg-amber-200' : 'bg-blue-100'}`}>
231
- <svg className={`w-3 h-3 ${msg.isAgentAda ? 'text-amber-700' : 'text-blue-600'}`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
232
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
233
- </svg>
234
- </div>
235
- <span className={`text-xs font-semibold tracking-wider uppercase ${msg.isAgentAda ? 'text-amber-700' : 'text-slate-500'}`}>
236
- {msg.isAgentAda ? 'Agent Ada (Risk Evaluator)' : 'TalentLens Evaluator'}
237
- </span>
238
- </div>
239
- )}
240
- <p className="leading-relaxed whitespace-pre-wrap">{msg.content}</p>
241
- </div>
242
- </div>
243
- ))}
244
- {isTyping && (
245
- <div className="flex justify-start">
246
- <div className="bg-white rounded-3xl p-5 rounded-tl-sm border border-slate-200 shadow-sm flex gap-1.5 items-center">
247
- <span className="w-2 h-2 rounded-full bg-slate-400 animate-bounce" style={{ animationDelay: "0ms" }}></span>
248
- <span className="w-2 h-2 rounded-full bg-slate-400 animate-bounce" style={{ animationDelay: "150ms" }}></span>
249
- <span className="w-2 h-2 rounded-full bg-slate-400 animate-bounce" style={{ animationDelay: "300ms" }}></span>
250
- </div>
251
- </div>
252
- )}
253
- <div ref={messagesEndRef} />
254
- </div>
255
-
256
- <form onSubmit={handleSend} className="relative group shrink-0">
257
- <textarea
258
- value={input}
259
- onChange={(e) => setInput(e.target.value)}
260
- disabled={interviewComplete || isTyping}
261
- onPaste={(e) => { e.preventDefault(); handleViolation("Copying or pasting text is not allowed."); }}
262
- onCopy={(e) => { e.preventDefault(); handleViolation("Copying or pasting text is not allowed."); }}
263
- placeholder={interviewComplete ? "Interview complete. Review dashboard." : "Type your response..."}
264
- className="w-full bg-white border border-slate-300 rounded-2xl pl-4 sm:pl-6 pr-28 py-3 sm:py-4 text-sm sm:text-base text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500/50 transition-all placeholder:text-slate-400 resize-none h-20 sm:h-24 premium-shadow"
265
- onKeyDown={(e) => {
266
- if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend(e); }
267
- }}
268
- />
269
- <button
270
- type="button"
271
- onClick={toggleListening}
272
- disabled={interviewComplete || isTyping}
273
- className={`absolute right-14 sm:right-16 bottom-2 sm:bottom-3 p-2 sm:p-3 rounded-xl transition-all ${isListening ? 'bg-red-500 text-white animate-pulse' : 'bg-slate-100 text-slate-600 hover:bg-slate-200'}`}
274
- title="Toggle Voice Input"
275
- >
276
- <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
277
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z" />
278
- </svg>
279
- </button>
280
- <button
281
- type="submit"
282
- disabled={!input.trim() || interviewComplete || isTyping}
283
- className="absolute right-2 sm:right-3 bottom-2 sm:bottom-3 p-2 sm:p-3 bg-slate-900 text-white rounded-xl hover:bg-slate-800 disabled:opacity-50 transition-all"
284
- >
285
- <svg className="w-4 h-4 sm:w-5 sm:h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
286
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
287
- </svg>
288
- </button>
289
- </form>
290
- </div>
291
- );
292
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/app/layout.tsx DELETED
@@ -1,69 +0,0 @@
1
- import type { Metadata } from "next";
2
- import { Geist, Geist_Mono } from "next/font/google";
3
- import "./globals.css";
4
- import Link from "next/link";
5
- import { ClerkProvider, SignInButton, UserButton } from '@clerk/nextjs';
6
- import { auth } from '@clerk/nextjs/server';
7
-
8
- const geistSans = Geist({
9
- variable: "--font-geist-sans",
10
- subsets: ["latin"],
11
- });
12
-
13
- const geistMono = Geist_Mono({
14
- variable: "--font-geist-mono",
15
- subsets: ["latin"],
16
- });
17
-
18
- export const metadata: Metadata = {
19
- title: "TalentLens | Hire Potential",
20
- description: "Evaluate candidates efficiently through real-world signals and dynamic assessments.",
21
- };
22
-
23
- export default async function RootLayout({
24
- children,
25
- }: Readonly<{
26
- children: React.ReactNode;
27
- }>) {
28
- const { userId } = await auth();
29
-
30
- return (
31
- <ClerkProvider>
32
- <html lang="en" className={`${geistSans.variable} ${geistMono.variable}`}>
33
- <body className="min-h-screen flex flex-col bg-white text-slate-900 selection:bg-slate-900 selection:text-white">
34
- <nav className="w-full z-50 fixed top-0 left-0 right-0 h-16 flex items-center bg-white/80 backdrop-blur-md border-b border-slate-200 transition-all">
35
- <div className="max-w-7xl mx-auto px-4 sm:px-6 w-full flex justify-between items-center">
36
- <Link href="/" className="text-xl font-bold tracking-tight text-slate-900 flex items-center gap-2">
37
- <div className="w-7 h-7 rounded bg-slate-900 flex flex-shrink-0 items-center justify-center">
38
- <span className="text-white text-xs font-bold">TL</span>
39
- </div>
40
- <span className="hidden sm:inline-block">TalentLens</span>
41
- </Link>
42
- <div className="flex gap-3 sm:gap-6 items-center">
43
- <Link href="/apply" className="hidden md:inline-flex px-5 py-2.5 rounded-md bg-slate-900 hover:bg-slate-800 text-white text-sm font-medium transition-colors premium-shadow">
44
- Start Candidate Journey
45
- </Link>
46
- <Link href="/apply" className="md:hidden px-3 py-2 rounded-md bg-slate-900 hover:bg-slate-800 text-white text-xs font-medium transition-colors premium-shadow">
47
- Apply
48
- </Link>
49
- {userId ? (
50
- <>
51
- <Link href="/dashboard" className="text-sm font-medium text-slate-600 hover:text-slate-900 w-auto">Dashboard</Link>
52
- <UserButton />
53
- </>
54
- ) : (
55
- <SignInButton>
56
- <button className="text-sm font-medium text-slate-600 hover:text-slate-900 whitespace-nowrap">Sign In</button>
57
- </SignInButton>
58
- )}
59
- </div>
60
- </div>
61
- </nav>
62
- <main className="flex-1 pt-24 pb-12 w-full max-w-7xl mx-auto px-4 sm:px-6">
63
- {children}
64
- </main>
65
- </body>
66
- </html>
67
- </ClerkProvider>
68
- );
69
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/app/page.tsx DELETED
@@ -1,61 +0,0 @@
1
- import Link from "next/link";
2
-
3
- export default function Home() {
4
- return (
5
- <div className="flex flex-col items-center justify-center min-h-[75vh] px-4">
6
- <div className="max-w-4xl mx-auto text-center animate-fade-in-up">
7
- <div className="inline-flex items-center px-3 py-1 rounded-full bg-slate-100 border border-slate-200 mb-8">
8
- <span className="text-xs font-semibold text-slate-600 tracking-wide uppercase">The New Hiring Standard</span>
9
- </div>
10
-
11
- <h1 className="text-5xl md:text-7xl font-bold tracking-tight mb-6 text-slate-900 leading-[1.1]">
12
- <span className="text-transparent bg-clip-text bg-gradient-to-r from-blue-600 to-indigo-600 font-black">Hire Potential.</span> <br />
13
- <span className="text-slate-500 font-medium tracking-normal text-[0.9em]">Not just resumes.</span>
14
- </h1>
15
-
16
- <p className="text-lg md:text-xl text-slate-600 mb-10 max-w-2xl mx-auto leading-relaxed">
17
- Evaluate candidates through their real-world digital footprint, automated structured interviews, and unbiased multi-perspective panel decisions.
18
- </p>
19
-
20
- <div className="flex flex-col sm:flex-row gap-4 justify-center items-center">
21
- <Link href="/apply" className="px-8 py-3.5 rounded-lg bg-slate-900 text-white font-medium text-lg hover:bg-slate-800 transition-colors w-full sm:w-auto premium-shadow">
22
- Start Candidate Journey
23
- </Link>
24
- </div>
25
- </div>
26
-
27
- {/* Feature grid */}
28
- <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-6 max-w-5xl mx-auto mt-16 md:mt-28 w-full animate-fade-in-up" style={{ animationDelay: '0.1s', animationFillMode: 'both' }}>
29
- <div className="bg-white rounded-xl p-8 border border-slate-200 hover:border-slate-300 transition-colors premium-shadow text-left">
30
- <div className="h-10 w-10 rounded-lg bg-slate-100 border border-slate-200 flex items-center justify-center mb-6">
31
- <svg className="w-5 h-5 text-slate-700" fill="none" viewBox="0 0 24 24" stroke="currentColor">
32
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
33
- </svg>
34
- </div>
35
- <h3 className="text-lg font-semibold text-slate-900 mb-2">Talent Discovery</h3>
36
- <p className="text-slate-600 leading-relaxed text-sm">Analyze non-traditional signals like GitHub activity, open-source contributions, and real-world projects to find hidden gems.</p>
37
- </div>
38
-
39
- <div className="bg-white rounded-xl p-8 border border-slate-200 hover:border-slate-300 transition-colors premium-shadow text-left">
40
- <div className="h-10 w-10 rounded-lg bg-slate-100 border border-slate-200 flex items-center justify-center mb-6">
41
- <svg className="w-5 h-5 text-slate-700" fill="none" viewBox="0 0 24 24" stroke="currentColor">
42
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" />
43
- </svg>
44
- </div>
45
- <h3 className="text-lg font-semibold text-slate-900 mb-2">Structured Interviews</h3>
46
- <p className="text-slate-600 leading-relaxed text-sm">Conduct dynamic, real-time interviews that adapt to the candidate's answers to perfectly evaluate their reasoning.</p>
47
- </div>
48
-
49
- <div className="bg-white rounded-xl p-8 border border-slate-200 hover:border-slate-300 transition-colors premium-shadow text-left">
50
- <div className="h-10 w-10 rounded-lg bg-slate-100 border border-slate-200 flex items-center justify-center mb-6">
51
- <svg className="w-5 h-5 text-slate-700" fill="none" viewBox="0 0 24 24" stroke="currentColor">
52
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
53
- </svg>
54
- </div>
55
- <h3 className="text-lg font-semibold text-slate-900 mb-2">Unbiased Panel</h3>
56
- <p className="text-slate-600 leading-relaxed text-sm">Extract evaluations from multiple simulated perspectives to reach a well-rounded and objective hiring decision.</p>
57
- </div>
58
- </div>
59
- </div>
60
- );
61
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/app/sign-in/[[...sign-in]]/page.tsx DELETED
@@ -1,9 +0,0 @@
1
- import { SignIn } from "@clerk/nextjs";
2
-
3
- export default function SignInPage() {
4
- return (
5
- <div className="flex items-center justify-center min-h-[70vh] px-4 animate-fade-in-up">
6
- <SignIn path="/sign-in" routing="path" signUpUrl="/sign-up" />
7
- </div>
8
- );
9
- }
 
 
 
 
 
 
 
 
 
 
src/app/sign-up/[[...sign-up]]/page.tsx DELETED
@@ -1,9 +0,0 @@
1
- import { SignUp } from "@clerk/nextjs";
2
-
3
- export default function SignUpPage() {
4
- return (
5
- <div className="flex items-center justify-center min-h-[70vh] px-4 animate-fade-in-up">
6
- <SignUp path="/sign-up" routing="path" signInUrl="/sign-in" />
7
- </div>
8
- );
9
- }
 
 
 
 
 
 
 
 
 
 
src/proxy.ts DELETED
@@ -1,18 +0,0 @@
1
- import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";
2
-
3
- const isProtectedRoute = createRouteMatcher(["/dashboard(.*)"]);
4
-
5
- export default clerkMiddleware(async (auth, req) => {
6
- if (isProtectedRoute(req)) {
7
- await auth.protect();
8
- }
9
- });
10
-
11
- export const config = {
12
- matcher: [
13
- // Skip Next.js internals and all static files, unless found in search params
14
- "/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)",
15
- // Always run for API routes
16
- "/(api|trpc)(.*)",
17
- ],
18
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/css/style.css ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ :root {
2
+ --bg-dark: #0f172a;
3
+ --text-light: #f8fafc;
4
+ --text-muted: #94a3b8;
5
+ --primary: #3b82f6;
6
+ --primary-hover: #2563eb;
7
+ --accent: #8b5cf6;
8
+ --success: #10b981;
9
+ --danger: #ef4444;
10
+ --glass-bg: rgba(30, 41, 59, 0.7);
11
+ --glass-border: rgba(255, 255, 255, 0.1);
12
+ --glass-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.37);
13
+ }
14
+
15
+ * {
16
+ box-sizing: border-box;
17
+ margin: 0;
18
+ padding: 0;
19
+ }
20
+
21
+ body {
22
+ font-family: 'Outfit', sans-serif;
23
+ background-color: var(--bg-dark);
24
+ color: var(--text-light);
25
+ min-height: 100vh;
26
+ display: flex;
27
+ flex-direction: column;
28
+ overflow-x: hidden;
29
+ }
30
+
31
+ /* Background blob animations */
32
+ .background-elements {
33
+ position: fixed;
34
+ top: 0; left: 0; width: 100%; height: 100%;
35
+ z-index: -1;
36
+ overflow: hidden;
37
+ pointer-events: none;
38
+ }
39
+ .blob {
40
+ position: absolute;
41
+ border-radius: 50%;
42
+ filter: blur(80px);
43
+ opacity: 0.5;
44
+ animation: float 20s infinite ease-in-out;
45
+ }
46
+ .blob-1 {
47
+ width: 400px; height: 400px;
48
+ background: var(--primary);
49
+ top: -100px; left: -100px;
50
+ }
51
+ .blob-2 {
52
+ width: 300px; height: 300px;
53
+ background: var(--accent);
54
+ bottom: -50px; right: -50px;
55
+ animation-delay: -5s;
56
+ }
57
+ .blob-3 {
58
+ width: 500px; height: 500px;
59
+ background: var(--accent);
60
+ top: 50%; left: 50%;
61
+ transform: translate(-50%, -50%);
62
+ opacity: 0.3;
63
+ }
64
+
65
+ @keyframes float {
66
+ 0%, 100% { transform: translateY(0) scale(1); }
67
+ 50% { transform: translateY(-30px) scale(1.05); }
68
+ }
69
+
70
+ /* Glass Panels */
71
+ .glass-panel {
72
+ background: var(--glass-bg);
73
+ backdrop-filter: blur(16px);
74
+ -webkit-backdrop-filter: blur(16px);
75
+ border: 1px solid var(--glass-border);
76
+ box-shadow: var(--glass-shadow);
77
+ border-radius: 20px;
78
+ }
79
+ .glass-panel-flat {
80
+ background: var(--glass-bg);
81
+ backdrop-filter: blur(10px);
82
+ border-bottom: 1px solid var(--glass-border);
83
+ }
84
+
85
+ /* Buttons */
86
+ .btn {
87
+ display: inline-flex;
88
+ align-items: center;
89
+ justify-content: center;
90
+ gap: 8px;
91
+ padding: 12px 24px;
92
+ border-radius: 12px;
93
+ font-family: inherit;
94
+ font-weight: 600;
95
+ font-size: 1rem;
96
+ cursor: pointer;
97
+ transition: all 0.3s ease;
98
+ border: none;
99
+ outline: none;
100
+ }
101
+ .btn-sm { padding: 8px 16px; font-size: 0.9rem; }
102
+ .full-width { width: 100%; }
103
+ .primary-btn {
104
+ background: linear-gradient(135deg, var(--primary), var(--accent));
105
+ color: white;
106
+ box-shadow: 0 4px 15px rgba(59, 130, 246, 0.4);
107
+ }
108
+ .primary-btn:hover {
109
+ transform: translateY(-2px);
110
+ box-shadow: 0 6px 20px rgba(59, 130, 246, 0.6);
111
+ }
112
+ .secondary-btn {
113
+ background: rgba(255, 255, 255, 0.1);
114
+ color: white;
115
+ }
116
+ .secondary-btn:hover { background: rgba(255, 255, 255, 0.15); }
117
+ .outline-btn {
118
+ background: transparent;
119
+ border: 1px solid var(--glass-border);
120
+ color: white;
121
+ }
122
+ .outline-btn:hover { background: rgba(255, 255, 255, 0.05); border-color: white; }
123
+
124
+ /* Auth Views */
125
+ .auth-body { align-items: center; justify-content: center; }
126
+ .auth-container {
127
+ width: 100%;
128
+ max-width: 420px;
129
+ padding: 40px;
130
+ position: relative;
131
+ overflow: hidden;
132
+ }
133
+ .auth-header {
134
+ text-align: center;
135
+ margin-bottom: 30px;
136
+ }
137
+ .logo {
138
+ display: flex;
139
+ align-items: center;
140
+ justify-content: center;
141
+ gap: 10px;
142
+ font-size: 1.5rem;
143
+ color: white;
144
+ margin-bottom: 5px;
145
+ }
146
+ .logo i {
147
+ background: linear-gradient(135deg, var(--primary), var(--accent));
148
+ -webkit-background-clip: text;
149
+ -webkit-text-fill-color: transparent;
150
+ font-size: 2rem;
151
+ }
152
+ .auth-header p { color: var(--text-muted); font-size: 0.95rem; }
153
+
154
+ .input-group {
155
+ position: relative;
156
+ margin-bottom: 20px;
157
+ }
158
+ .input-group i {
159
+ position: absolute;
160
+ left: 16px; top: 50%;
161
+ transform: translateY(-50%);
162
+ color: var(--text-muted);
163
+ }
164
+ .input-group input {
165
+ width: 100%;
166
+ padding: 14px 16px 14px 45px;
167
+ background: rgba(0, 0, 0, 0.2);
168
+ border: 1px solid var(--glass-border);
169
+ border-radius: 12px;
170
+ color: white;
171
+ font-family: inherit;
172
+ font-size: 1rem;
173
+ transition: all 0.3s;
174
+ }
175
+ .input-group input:focus {
176
+ border-color: var(--primary);
177
+ box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
178
+ outline: none;
179
+ }
180
+ .auth-switch {
181
+ text-align: center; margin-top: 20px; color: var(--text-muted); font-size: 0.9rem;
182
+ }
183
+ .auth-switch span {
184
+ color: var(--primary); cursor: pointer; font-weight: 600; transition: color 0.3s;
185
+ }
186
+ .auth-switch span:hover { color: var(--text-light); }
187
+ .error-msg { color: var(--danger); font-size: 0.85rem; margin-bottom: 15px; text-align: center; display: none; }
188
+
189
+ /* Dashboard Nav */
190
+ .navbar {
191
+ display: flex; justify-content: space-between; align-items: center;
192
+ padding: 15px 5%; width: 100%; position: sticky; top: 0; z-index: 100;
193
+ }
194
+ .user-profile { display: flex; align-items: center; gap: 20px; }
195
+ .username strong { color: var(--primary); font-weight: 600; }
196
+
197
+ /* Dashboard Main */
198
+ .dashboard-container {
199
+ max-width: 900px; margin: 40px auto; width: 90%;
200
+ display: grid; grid-template-columns: 1fr; gap: 30px;
201
+ }
202
+ .panel-header { margin-bottom: 25px; text-align: center; }
203
+ .panel-header h3 { font-size: 1.5rem; margin-bottom: 8px; font-weight: 600; }
204
+ .panel-header p { color: var(--text-muted); font-size: 0.95rem; }
205
+
206
+ /* Upload Area */
207
+ .analyzer-panel { padding: 40px; }
208
+ .upload-area {
209
+ border: 2px dashed var(--glass-border);
210
+ border-radius: 16px;
211
+ padding: 50px 20px;
212
+ text-align: center;
213
+ transition: all 0.3s;
214
+ background: rgba(0, 0, 0, 0.1);
215
+ cursor: pointer;
216
+ }
217
+ .upload-area:hover, .upload-area.dragover {
218
+ border-color: var(--primary);
219
+ background: rgba(59, 130, 246, 0.05);
220
+ }
221
+ .upload-icon {
222
+ font-size: 3rem; color: var(--primary); margin-bottom: 15px;
223
+ }
224
+ .file-hint { color: var(--text-muted); font-size: 0.8rem; margin-top: 15px; }
225
+
226
+ /* Preview */
227
+ .upload-preview { text-align: center; animation: fadeIn 0.4s ease; }
228
+ .upload-preview img {
229
+ max-width: 100%; max-height: 350px;
230
+ border-radius: 12px; margin-bottom: 20px;
231
+ box-shadow: 0 4px 20px rgba(0,0,0,0.4);
232
+ border: 1px solid var(--glass-border);
233
+ }
234
+ .preview-actions { display: flex; gap: 15px; justify-content: center; }
235
+
236
+ /* Loader */
237
+ .loader-container { text-align: center; padding: 40px 0; }
238
+ .spinner {
239
+ width: 50px; height: 50px;
240
+ border: 4px solid rgba(255,255,255,0.1);
241
+ border-top-color: var(--primary);
242
+ border-radius: 50%;
243
+ animation: spin 1s linear infinite;
244
+ margin: 0 auto 20px;
245
+ }
246
+ .scanning-bar {
247
+ height: 4px; width: 80%; background: linear-gradient(90deg, transparent, var(--primary), transparent);
248
+ margin: 0 auto 15px; border-radius: 2px;
249
+ animation: scan 2s ease-in-out infinite;
250
+ }
251
+
252
+ /* Results */
253
+ .hidden { display: none !important; }
254
+ .result-panel { padding: 40px; text-align: center; animation: fadeInUp 0.6s cubic-bezier(0.16, 1, 0.3, 1); }
255
+ .result-title { font-size: 1.2rem; color: var(--text-muted); margin-bottom: 20px; text-transform: uppercase; letter-spacing: 2px; }
256
+
257
+ .verdict-container { margin-bottom: 30px; }
258
+ .verdict-badge {
259
+ display: inline-flex; align-items: center; gap: 10px;
260
+ padding: 12px 30px; border-radius: 50px;
261
+ font-size: 1.5rem; font-weight: 600; letter-spacing: 1px;
262
+ }
263
+ .verdict-real { background: rgba(16, 185, 129, 0.15); color: var(--success); border: 1px solid var(--success); }
264
+ .verdict-fake { background: rgba(239, 68, 68, 0.15); color: var(--danger); border: 1px solid var(--danger); }
265
+
266
+ .metrics {
267
+ background: rgba(0, 0, 0, 0.2); border-radius: 16px; padding: 25px; margin-bottom: 30px;
268
+ border: 1px solid var(--glass-border);
269
+ }
270
+ .metric { display: flex; justify-content: space-between; margin-bottom: 12px; font-size: 1.1rem; }
271
+ .progress-container { width: 100%; height: 8px; background: rgba(255,255,255,0.1); border-radius: 4px; overflow: hidden; }
272
+ .progress-bar { height: 100%; width: 0%; border-radius: 4px; transition: width 1.5s cubic-bezier(0.16, 1, 0.3, 1); }
273
+
274
+ @keyframes spin { to { transform: rotate(360deg); } }
275
+ @keyframes scan { 0% { transform: translateX(-100%); } 100% { transform: translateX(100%); } }
276
+ @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
277
+ @keyframes fadeInUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
static/js/main.js ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Authentication Logic
2
+ function toggleAuth() {
3
+ const loginForm = document.getElementById('login-form');
4
+ const registerForm = document.getElementById('register-form');
5
+ if (loginForm && registerForm) {
6
+ if (loginForm.style.display === 'none') {
7
+ loginForm.style.display = 'block';
8
+ registerForm.style.display = 'none';
9
+ } else {
10
+ loginForm.style.display = 'none';
11
+ registerForm.style.display = 'block';
12
+ }
13
+ }
14
+ }
15
+
16
+ // Login
17
+ const loginForm = document.getElementById('login-form');
18
+ if (loginForm) {
19
+ loginForm.addEventListener('submit', async (e) => {
20
+ e.preventDefault();
21
+ const username = document.getElementById('login-username').value;
22
+ const password = document.getElementById('login-password').value;
23
+ const errDiv = document.getElementById('login-error');
24
+
25
+ try {
26
+ const res = await fetch('/api/login', {
27
+ method: 'POST',
28
+ headers: { 'Content-Type': 'application/json' },
29
+ body: JSON.stringify({ username, password })
30
+ });
31
+ const data = await res.json();
32
+ if (data.success) {
33
+ window.location.href = '/';
34
+ } else {
35
+ errDiv.textContent = data.message;
36
+ errDiv.style.display = 'block';
37
+ }
38
+ } catch (e) {
39
+ errDiv.textContent = 'Server error. Try again.';
40
+ errDiv.style.display = 'block';
41
+ }
42
+ });
43
+ }
44
+
45
+ // Register
46
+ const regForm = document.getElementById('register-form');
47
+ if (regForm) {
48
+ regForm.addEventListener('submit', async (e) => {
49
+ e.preventDefault();
50
+ const username = document.getElementById('register-username').value;
51
+ const password = document.getElementById('register-password').value;
52
+ const errDiv = document.getElementById('register-error');
53
+
54
+ try {
55
+ const res = await fetch('/api/register', {
56
+ method: 'POST',
57
+ headers: { 'Content-Type': 'application/json' },
58
+ body: JSON.stringify({ username, password })
59
+ });
60
+ const data = await res.json();
61
+ if (data.success) {
62
+ window.location.href = '/';
63
+ } else {
64
+ errDiv.textContent = data.message;
65
+ errDiv.style.display = 'block';
66
+ }
67
+ } catch (e) {
68
+ errDiv.textContent = 'Server error. Try again.';
69
+ errDiv.style.display = 'block';
70
+ }
71
+ });
72
+ }
73
+
74
+ // Dashboard File Upload Logic
75
+ const dropZone = document.getElementById('drop-zone');
76
+ const fileInput = document.getElementById('file-input');
77
+ const previewArea = document.getElementById('preview-area');
78
+ const imagePreview = document.getElementById('image-preview');
79
+ const analyzeBtn = document.getElementById('analyze-btn');
80
+ const cancelBtn = document.getElementById('cancel-btn');
81
+ const loader = document.getElementById('loader');
82
+ const resultCard = document.getElementById('result-card');
83
+
84
+ let selectedFile = null;
85
+
86
+ if (dropZone) {
87
+ // Prevent default drag behaviors
88
+ ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
89
+ dropZone.addEventListener(eventName, preventDefaults, false);
90
+ document.body.addEventListener(eventName, preventDefaults, false);
91
+ });
92
+
93
+ function preventDefaults(e) {
94
+ e.preventDefault();
95
+ e.stopPropagation();
96
+ }
97
+
98
+ // Highlight drop zone
99
+ ['dragenter', 'dragover'].forEach(eventName => {
100
+ dropZone.addEventListener(eventName, () => dropZone.classList.add('dragover'), false);
101
+ });
102
+
103
+ ['dragleave', 'drop'].forEach(eventName => {
104
+ dropZone.addEventListener(eventName, () => dropZone.classList.remove('dragover'), false);
105
+ });
106
+
107
+ // Handle dropped files
108
+ dropZone.addEventListener('drop', (e) => {
109
+ const dt = e.dataTransfer;
110
+ const files = dt.files;
111
+ if (files.length) handleFiles(files[0]);
112
+ }, false);
113
+
114
+ // Handle selected files
115
+ fileInput.addEventListener('change', function() {
116
+ if (this.files.length) handleFiles(this.files[0]);
117
+ });
118
+
119
+ function handleFiles(file) {
120
+ if (!file.type.startsWith('image/')) {
121
+ alert('Please upload an image file.');
122
+ return;
123
+ }
124
+ selectedFile = file;
125
+ const reader = new FileReader();
126
+ reader.onload = (e) => {
127
+ imagePreview.src = e.target.result;
128
+ dropZone.style.display = 'none';
129
+ previewArea.style.display = 'block';
130
+ };
131
+ reader.readAsDataURL(file);
132
+ }
133
+
134
+ cancelBtn.addEventListener('click', resetAnalyzer);
135
+
136
+ analyzeBtn.addEventListener('click', async () => {
137
+ if (!selectedFile) return;
138
+
139
+ // UI State update
140
+ previewArea.style.display = 'none';
141
+ loader.style.display = 'block';
142
+
143
+ const formData = new FormData();
144
+ formData.append('file', selectedFile);
145
+
146
+ try {
147
+ const res = await fetch('/api/predict', {
148
+ method: 'POST',
149
+ body: formData
150
+ });
151
+ const data = await res.json();
152
+
153
+ loader.style.display = 'none';
154
+
155
+ if (data.success) {
156
+ showResults(data);
157
+ } else {
158
+ alert('Analysis failed: ' + data.message);
159
+ resetAnalyzer();
160
+ }
161
+ } catch (e) {
162
+ loader.style.display = 'none';
163
+ alert('Network error communicating with Veritas-AI core.');
164
+ resetAnalyzer();
165
+ }
166
+ });
167
+
168
+ function showResults(data) {
169
+ resultCard.classList.remove('hidden');
170
+
171
+ const verdictBadge = document.getElementById('verdict-badge');
172
+ const confidenceScore = document.getElementById('confidence-score');
173
+ const confidenceBar = document.getElementById('confidence-bar');
174
+
175
+ const isReal = data.prediction === 'REAL';
176
+ const primaryProb = isReal ? data.real_prob : data.fake_prob;
177
+
178
+ // Style Badge
179
+ verdictBadge.className = 'verdict-badge ';
180
+ verdictBadge.className += isReal ? 'verdict-real' : 'verdict-fake';
181
+ verdictBadge.innerHTML = isReal
182
+ ? '<i class="fa-solid fa-check-circle"></i> AUTHENTIC MEDIA'
183
+ : '<i class="fa-solid fa-triangle-exclamation"></i> DEEPFAKE DETECTED';
184
+
185
+ // Populate metrics
186
+ confidenceScore.textContent = primaryProb + '%';
187
+
188
+ // Progress bar styling
189
+ confidenceBar.style.width = '0%';
190
+ confidenceBar.style.background = isReal ? 'var(--success)' : 'var(--danger)';
191
+
192
+ // Animate bar width
193
+ setTimeout(() => {
194
+ confidenceBar.style.width = primaryProb + '%';
195
+ }, 100);
196
+ }
197
+ }
198
+
199
+ function resetAnalyzer() {
200
+ selectedFile = null;
201
+ if (fileInput) fileInput.value = '';
202
+
203
+ if (dropZone) dropZone.style.display = 'block';
204
+ if (previewArea) previewArea.style.display = 'none';
205
+ if (loader) loader.style.display = 'none';
206
+ if (resultCard) resultCard.classList.add('hidden');
207
+ }
templates/index.html ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Veritas-AI - AI Detection Dashboard</title>
7
+ <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600&display=swap" rel="stylesheet">
8
+ <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
9
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
10
+ </head>
11
+ <body class="dashboard-body">
12
+ <div class="background-elements">
13
+ <div class="blob blob-1"></div>
14
+ <div class="blob blob-3"></div>
15
+ </div>
16
+
17
+ <nav class="navbar glass-panel-flat">
18
+ <div class="logo">
19
+ <i class="fa-solid fa-shield-halved"></i>
20
+ <h2>Veritas-AI</h2>
21
+ </div>
22
+ <div class="user-profile">
23
+ <span class="username">Welcome, <strong>{{ user.username }}</strong></span>
24
+ <a href="/logout" class="btn outline-btn"><i class="fa-solid fa-right-from-bracket"></i> Logout</a>
25
+ </div>
26
+ </nav>
27
+
28
+ <main class="dashboard-container">
29
+
30
+ <div class="analyzer-panel glass-panel">
31
+ <div class="panel-header">
32
+ <h3><i class="fa-solid fa-magnifying-glass-chart"></i> Image Source Analyzer</h3>
33
+ <p>Upload a facial image to securely evaluate biometric integrity using our PyTorch ResNet-18 model.</p>
34
+ </div>
35
+
36
+ <div class="upload-area" id="drop-zone">
37
+ <div class="upload-content">
38
+ <i class="fa-solid fa-cloud-arrow-up upload-icon"></i>
39
+ <h4>Drag & Drop image here</h4>
40
+ <p>or</p>
41
+ <label class="btn primary-btn btn-sm">
42
+ Browse Files
43
+ <input type="file" id="file-input" hidden accept="image/*">
44
+ </label>
45
+ <p class="file-hint">Supports JPG, PNG (Max 16MB)</p>
46
+ </div>
47
+ </div>
48
+
49
+ <div class="upload-preview" id="preview-area" style="display: none;">
50
+ <img id="image-preview" src="" alt="Image Preview">
51
+ <div class="preview-actions">
52
+ <button class="btn accent-btn" id="analyze-btn"><i class="fa-solid fa-microchip"></i> Run AI Analysis</button>
53
+ <button class="btn secondary-btn" id="cancel-btn"><i class="fa-solid fa-xmark"></i> Cancel</button>
54
+ </div>
55
+ </div>
56
+
57
+ <!-- Loading Indicator -->
58
+ <div class="loader-container" id="loader" style="display: none;">
59
+ <div class="scanning-bar"></div>
60
+ <div class="spinner"></div>
61
+ <p>Evaluating neural patterns...</p>
62
+ </div>
63
+ </div>
64
+
65
+ <!-- Result Card -->
66
+ <div class="result-panel glass-panel hidden" id="result-card">
67
+ <h3 class="result-title">Analysis Complete</h3>
68
+
69
+ <div class="verdict-container">
70
+ <div class="verdict-badge" id="verdict-badge"></div>
71
+ </div>
72
+
73
+ <div class="metrics">
74
+ <div class="metric">
75
+ <span>AI Confidence</span>
76
+ <strong id="confidence-score">0%</strong>
77
+ </div>
78
+ <div class="progress-container">
79
+ <div class="progress-bar" id="confidence-bar"></div>
80
+ </div>
81
+ </div>
82
+
83
+ <button class="btn outline-btn full-width" onclick="resetAnalyzer()"><i class="fa-solid fa-rotate-right"></i> Scan Another Image</button>
84
+ </div>
85
+
86
+ </main>
87
+
88
+ <script src="{{ url_for('static', filename='js/main.js') }}"></script>
89
+ </body>
90
+ </html>
templates/login.html ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Veritas-AI - Secure Login</title>
7
+ <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600&display=swap" rel="stylesheet">
8
+ <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
9
+ <!-- Load FontAwesome for icons -->
10
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
11
+ </head>
12
+ <body class="auth-body">
13
+ <div class="background-elements">
14
+ <div class="blob blob-1"></div>
15
+ <div class="blob blob-2"></div>
16
+ </div>
17
+
18
+ <div class="auth-container glass-panel">
19
+ <div class="auth-header">
20
+ <div class="logo">
21
+ <i class="fa-solid fa-shield-halved"></i>
22
+ <h2>Veritas-AI</h2>
23
+ </div>
24
+ <p>Advanced Deepfake Detection</p>
25
+ </div>
26
+
27
+ <!-- Login Form -->
28
+ <form id="login-form" class="auth-form active">
29
+ <h3 class="form-title">Welcome Back</h3>
30
+ <div class="input-group">
31
+ <i class="fa-solid fa-user"></i>
32
+ <input type="text" id="login-username" placeholder="Username" required>
33
+ </div>
34
+ <div class="input-group">
35
+ <i class="fa-solid fa-lock"></i>
36
+ <input type="password" id="login-password" placeholder="Password" required>
37
+ </div>
38
+ <div id="login-error" class="error-msg"></div>
39
+ <button type="submit" class="btn primary-btn">Login <i class="fa-solid fa-arrow-right"></i></button>
40
+ <p class="auth-switch">Don't have an account? <span onclick="toggleAuth()">Sign up</span></p>
41
+ </form>
42
+
43
+ <!-- Register Form -->
44
+ <form id="register-form" class="auth-form" style="display: none;">
45
+ <h3 class="form-title">Create Account</h3>
46
+ <div class="input-group">
47
+ <i class="fa-solid fa-user"></i>
48
+ <input type="text" id="register-username" placeholder="Username (min 3 chars)" required>
49
+ </div>
50
+ <div class="input-group">
51
+ <i class="fa-solid fa-lock"></i>
52
+ <input type="password" id="register-password" placeholder="Password" required>
53
+ </div>
54
+ <div id="register-error" class="error-msg"></div>
55
+ <button type="submit" class="btn primary-btn">Register <i class="fa-solid fa-user-plus"></i></button>
56
+ <p class="auth-switch">Already have an account? <span onclick="toggleAuth()">Login</span></p>
57
+ </form>
58
+ </div>
59
+
60
+ <script src="{{ url_for('static', filename='js/main.js') }}"></script>
61
+ </body>
62
+ </html>
test.jpg ADDED
train.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import ImageFilter
2
+
3
+ # Define a custom wrapper to systematically inject High-Frequency Edge signals into the Convolution pipeline
4
+ class EdgeEnhanceTransform:
5
+ def __call__(self, img):
6
+ import random
7
+ if random.random() > 0.5:
8
+ return img.filter(ImageFilter.EDGE_ENHANCE_MORE)
9
+ return img
10
+
11
+ def main():
12
+ import torch
13
+ import torch.nn as nn
14
+ import torch.optim as optim
15
+ from torchvision import datasets, transforms
16
+ import timm
17
+ from torch.utils.data import DataLoader
18
+
19
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
20
+ print("Using:", device)
21
+
22
+ from torch.optim.lr_scheduler import StepLR
23
+
24
+
25
+
26
+ train_transform = transforms.Compose([
27
+ transforms.Resize((224, 224)),
28
+ transforms.RandomHorizontalFlip(p=0.5),
29
+ transforms.RandomRotation(15),
30
+ transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1),
31
+ EdgeEnhanceTransform(),
32
+ transforms.ToTensor(),
33
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
34
+ ])
35
+
36
+ val_transform = transforms.Compose([
37
+ transforms.Resize((224, 224)),
38
+ transforms.ToTensor(),
39
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
40
+ ])
41
+
42
+ train_data = datasets.ImageFolder("dataset/processed_train", transform=train_transform)
43
+ val_data = datasets.ImageFolder("dataset/processed_val", transform=val_transform)
44
+
45
+ print("Class mapping:", train_data.class_to_idx)
46
+
47
+ train_loader = DataLoader(
48
+ train_data,
49
+ batch_size=32,
50
+ shuffle=True,
51
+ num_workers=2,
52
+ pin_memory=True
53
+ )
54
+
55
+ val_loader = DataLoader(
56
+ val_data,
57
+ batch_size=32,
58
+ num_workers=2,
59
+ pin_memory=True
60
+ )
61
+
62
+ # Transitioned from 2015 ResNet18 to bleeding-edge EfficientNet-B3 SOTA architecture
63
+ model = timm.create_model('efficientnet_b3', pretrained=True, num_classes=2, drop_rate=0.5)
64
+ model = model.to(device)
65
+
66
+ criterion = nn.CrossEntropyLoss()
67
+ optimizer = optim.Adam(model.parameters(), lr=0.0001, weight_decay=1e-4)
68
+ scheduler = StepLR(optimizer, step_size=3, gamma=0.1)
69
+
70
+ epochs = 10
71
+ best_val_acc = 0.0
72
+
73
+ try:
74
+ for epoch in range(epochs):
75
+ model.train()
76
+ total_loss = 0
77
+
78
+ # Booting up NVIDIA Automatic Mixed Precision (AMP) logic
79
+ scaler = torch.amp.GradScaler('cuda')
80
+
81
+ for images, labels in train_loader:
82
+ images, labels = images.to(device), labels.to(device)
83
+
84
+ optimizer.zero_grad()
85
+
86
+ # Autocasting triggers the Tensor Cores into FP16 hyper-processing for exactly this block
87
+ with torch.amp.autocast('cuda'):
88
+ outputs = model(images)
89
+ loss = criterion(outputs, labels)
90
+
91
+ # Scaling backwards intercepts underflowing FP16 gradients natively
92
+ scaler.scale(loss).backward()
93
+ scaler.step(optimizer)
94
+ scaler.update()
95
+
96
+ total_loss += loss.item()
97
+
98
+ avg_loss = total_loss / len(train_loader)
99
+
100
+ model.eval()
101
+ correct = 0
102
+ total = 0
103
+
104
+ with torch.no_grad():
105
+ for images, labels in val_loader:
106
+ images, labels = images.to(device), labels.to(device)
107
+
108
+ outputs = model(images)
109
+ _, predicted = torch.max(outputs, 1)
110
+
111
+ total += labels.size(0)
112
+ correct += (predicted == labels).sum().item()
113
+
114
+ val_acc = 100 * correct / total
115
+
116
+ print(f"Epoch {epoch+1}/{epochs}, Loss: {avg_loss:.4f}, Val Accuracy: {val_acc:.2f}%")
117
+
118
+ # Immediate Checkpointing for the best model so far
119
+ if val_acc >= best_val_acc:
120
+ best_val_acc = val_acc
121
+ torch.save(model.state_dict(), "model_best.pth")
122
+ print("--> Best model checkpoint completely secured (model_best.pth).")
123
+
124
+ scheduler.step()
125
+
126
+ except KeyboardInterrupt:
127
+ print("\n[!] Training halted manually by user. The highest accuracy checkpoint is completely saved as 'model_best.pth'!")
128
+
129
+ torch.save(model.state_dict(), "model.pth")
130
+ print("\nTraining procedure officially terminated. 'model.pth' securely written to disk!")
131
+
132
+ if __name__ == "__main__":
133
+ main()
tsconfig.json DELETED
@@ -1,34 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2017",
4
- "lib": ["dom", "dom.iterable", "esnext"],
5
- "allowJs": true,
6
- "skipLibCheck": true,
7
- "strict": true,
8
- "noEmit": true,
9
- "esModuleInterop": true,
10
- "module": "esnext",
11
- "moduleResolution": "bundler",
12
- "resolveJsonModule": true,
13
- "isolatedModules": true,
14
- "jsx": "react-jsx",
15
- "incremental": true,
16
- "plugins": [
17
- {
18
- "name": "next"
19
- }
20
- ],
21
- "paths": {
22
- "@/*": ["./src/*"]
23
- }
24
- },
25
- "include": [
26
- "next-env.d.ts",
27
- "**/*.ts",
28
- "**/*.tsx",
29
- ".next/types/**/*.ts",
30
- ".next/dev/types/**/*.ts",
31
- "**/*.mts"
32
- ],
33
- "exclude": ["node_modules"]
34
- }