siva6106 commited on
Commit
4bd70aa
·
verified ·
1 Parent(s): d0599e0

Upload 7 files

Browse files
Files changed (7) hide show
  1. .gitignore +76 -0
  2. README.md +203 -13
  3. app.py +348 -0
  4. init_db.py +34 -0
  5. models.py +64 -0
  6. requirements.txt +19 -0
  7. schema.sql +49 -0
.gitignore ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ venv*/
2
+ __pycache__/
3
+ *.pyc
4
+ .env
5
+ # Keep uploads and model files in the repo per user request
6
+ # (removed uploads/ and h5 ignores to include all files)
7
+ *.sqlite3
8
+ *.db
9
+ .vscode/
10
+ venv_old_*/
11
+ *.log
12
+ node_modules/
13
+ *.DS_Store
14
+ env/
15
+ /.pytest_cache/
16
+ # Python
17
+ __pycache__/
18
+ *.py[cod]
19
+ *$py.class
20
+ *.so
21
+ .Python
22
+ venv/
23
+ env/
24
+ ENV/
25
+ .venv
26
+
27
+ # Flask
28
+ instance/
29
+ .webassets-cache
30
+
31
+ # Uploads
32
+ uploads/
33
+ *.mp4
34
+ *.avi
35
+ *.mov
36
+ *.mkv
37
+ *.webm
38
+ *.mp3
39
+ *.wav
40
+ *.flac
41
+ *.ogg
42
+ *.m4a
43
+ *.png
44
+ *.jpg
45
+ *.jpeg
46
+ *.gif
47
+ *.bmp
48
+ *.webp
49
+
50
+ # IDE
51
+ .vscode/
52
+ .idea/
53
+ *.swp
54
+ *.swo
55
+ *~
56
+
57
+ # OS
58
+ .DS_Store
59
+ Thumbs.db
60
+
61
+ # Models (if you add trained models)
62
+ models/
63
+ *.h5
64
+ *.pkl
65
+ *.pth
66
+ *.pt
67
+
68
+ # Database
69
+ *.db
70
+ *.sqlite
71
+ *.sqlite3
72
+
73
+ # Logs
74
+ *.log
75
+
76
+
README.md CHANGED
@@ -1,13 +1,203 @@
1
- ---
2
- title: Deepfake Detection
3
- emoji: 📈
4
- colorFrom: pink
5
- colorTo: indigo
6
- sdk: gradio
7
- sdk_version: 6.9.0
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AI Detection System
2
+
3
+ An intelligent AI-based detection system that identifies AI-generated media and fraudulent activity across multiple content types including videos, images, audio files, text content, and emails.
4
+
5
+ ## Features
6
+
7
+ - **User Authentication**: Secure login and signup system with session management
8
+ - **Video Deepfake Detection**: Analyze videos to detect deepfake manipulation using advanced frame analysis, temporal consistency checks, and frequency domain analysis
9
+ - **Image AI Detection**: Detect AI-generated or synthesized images using Error Level Analysis (ELA), frequency domain analysis, and texture pattern detection
10
+ - **Audio Voice Cloning Detection**: Identify voice cloning and AI-generated audio using signal processing
11
+ - **Text AI Detection**: Verify if text content is AI-generated using natural language processing
12
+ - **Email Phishing Detection**: Detect phishing attempts and fraudulent emails using pattern recognition and NLP
13
+ - **Detection History**: Track all detection results with user-specific history
14
+ - **Clear Results Display**: Visual indicators showing REAL or FAKE with authenticity scores
15
+
16
+ ## Technology Stack
17
+
18
+ - **Backend**: Flask (Python) with SQLAlchemy for database
19
+ - **Frontend**: HTML, CSS, JavaScript
20
+ - **Database**: SQLite (can be upgraded to PostgreSQL/MySQL)
21
+ - **Authentication**: Flask sessions with password hashing
22
+ - **Machine Learning**:
23
+ - OpenCV for image/video processing
24
+ - Librosa for audio analysis
25
+ - NumPy for numerical computations
26
+ - Custom detection modules for each content type
27
+
28
+ ## Installation
29
+
30
+ 1. **Clone the repository**
31
+ ```bash
32
+ git clone <repository-url>
33
+ cd clone
34
+ ```
35
+
36
+ 2. **Create a virtual environment** (recommended)
37
+ ```bash
38
+ python -m venv venv
39
+
40
+ # On Windows
41
+ venv\Scripts\activate
42
+
43
+ # On macOS/Linux
44
+ source venv/bin/activate
45
+ ```
46
+
47
+ 3. **Install dependencies**
48
+ ```bash
49
+ pip install -r requirements.txt
50
+ ```
51
+
52
+ ## Usage
53
+
54
+ 1. **Initialize the database** (first time only)
55
+ ```bash
56
+ python init_db.py
57
+ ```
58
+ This will create the database file (`ai_detection.db`) and all necessary tables.
59
+
60
+ 2. **Test database connection** (optional)
61
+ ```bash
62
+ python test_db.py
63
+ ```
64
+ This will verify that the database is working correctly.
65
+
66
+ 3. **Start the Flask server**
67
+ ```bash
68
+ python app.py
69
+ ```
70
+
71
+ 4. **Open your browser**
72
+ Navigate to `http://localhost:5000`
73
+
74
+ 5. **Create an account**
75
+ - Click "Sign Up" to create a new account
76
+ - Or login if you already have an account
77
+
78
+ 6. **Upload and analyze content**
79
+ - Select the appropriate tab (Video, Image, Audio, Text, or Email)
80
+ - Upload your file or paste content
81
+ - Click the analyze button
82
+ - View the results with clear REAL/FAKE indicators and authenticity scores
83
+ - Check your detection history in the History tab
84
+
85
+ ## Database
86
+
87
+ The application uses SQLite database (`ai_detection.db`) which is automatically created when you run the application. The database stores:
88
+ - User accounts (username, email, hashed passwords)
89
+ - Detection history (all detection results for each user)
90
+
91
+ If you encounter database connection issues:
92
+ 1. Make sure you have write permissions in the project directory
93
+ 2. Delete `ai_detection.db` and run `python init_db.py` to recreate it
94
+ 3. Check the console output for any error messages
95
+
96
+ ## API Endpoints
97
+
98
+ ### Video Detection
99
+ - **POST** `/api/detect/video`
100
+ - **Body**: multipart/form-data with `file` field
101
+ - **Response**: JSON with detection results
102
+
103
+ ### Image Detection
104
+ - **POST** `/api/detect/image`
105
+ - **Body**: multipart/form-data with `file` field
106
+ - **Response**: JSON with detection results
107
+
108
+ ### Audio Detection
109
+ - **POST** `/api/detect/audio`
110
+ - **Body**: multipart/form-data with `file` field
111
+ - **Response**: JSON with detection results
112
+
113
+ ### Text Detection
114
+ - **POST** `/api/detect/text`
115
+ - **Body**: JSON with `text` field
116
+ - **Response**: JSON with detection results
117
+
118
+ ### Email Detection
119
+ - **POST** `/api/detect/email`
120
+ - **Body**: JSON with `email` field
121
+ - **Response**: JSON with detection results
122
+
123
+ ## Project Structure
124
+
125
+ ```
126
+ .
127
+ ├── app.py # Main Flask application
128
+ ├── modules/ # Detection modules
129
+ │ ├── __init__.py
130
+ │ ├── video_detector.py # Video deepfake detection
131
+ │ ├── image_detector.py # Image AI detection
132
+ │ ├── audio_detector.py # Audio voice cloning detection
133
+ │ ├── text_detector.py # Text AI generation detection
134
+ │ └── email_detector.py # Email phishing detection
135
+ ├── templates/ # HTML templates
136
+ │ └── index.html
137
+ ├── static/ # Static files
138
+ │ ├── css/
139
+ │ │ └── style.css
140
+ │ └── js/
141
+ │ └── main.js
142
+ ├── uploads/ # Temporary file storage (auto-created)
143
+ ├── requirements.txt # Python dependencies
144
+ └── README.md # This file
145
+ ```
146
+
147
+ ## Model Implementation Notes
148
+
149
+ The current implementation uses heuristic-based detection algorithms as placeholders. For production use, you should:
150
+
151
+ 1. **Train or acquire pre-trained models** for each detection type
152
+ 2. **Replace the placeholder detection methods** in each module with actual model inference
153
+ 3. **Fine-tune models** on your specific datasets
154
+ 4. **Integrate state-of-the-art models** such as:
155
+ - **Deepfake Detection**: FaceForensics++, DeepFake Detection Challenge models
156
+ - **Image AI Detection**: CLIP-based detectors, GAN detection models
157
+ - **Voice Cloning**: ASVspoof models, anti-spoofing systems
158
+ - **Text AI Detection**: RoBERTa/BERT-based classifiers, GPTZero-style detectors
159
+ - **Email Phishing**: NLP-based classifiers, rule-based systems
160
+
161
+ ## Development
162
+
163
+ ### Adding New Detection Methods
164
+
165
+ 1. Create a new detector class in `modules/`
166
+ 2. Implement the `detect()` method
167
+ 3. Add a corresponding API endpoint in `app.py`
168
+ 4. Update the frontend to include the new detection type
169
+
170
+ ### Customizing Detection Models
171
+
172
+ Each detector module has a `_load_model()` method where you can integrate your trained models. The modules are designed to be easily extensible.
173
+
174
+ ## Limitations
175
+
176
+ - Current implementation uses heuristic-based detection (placeholders)
177
+ - File size limit: 500MB per upload
178
+ - Processing time depends on file size and system resources
179
+ - Models need to be trained/acquired for production use
180
+
181
+ ## Security Considerations
182
+
183
+ - All uploaded files are automatically deleted after processing
184
+ - File type validation is enforced
185
+ - Maximum file size limits are set
186
+ - Consider implementing rate limiting for production use
187
+
188
+ ## Contributing
189
+
190
+ Contributions are welcome! Please feel free to submit a Pull Request.
191
+
192
+ ## License
193
+
194
+ [Specify your license here]
195
+
196
+ ## Acknowledgments
197
+
198
+ - OpenCV for image/video processing
199
+ - Librosa for audio analysis
200
+ - Flask for web framework
201
+ - All contributors and the open-source community
202
+
203
+
app.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, render_template, request, jsonify, session, redirect, url_for
2
+ from flask_cors import CORS
3
+ from flask_sqlalchemy import SQLAlchemy
4
+ import os
5
+ import uuid
6
+ from datetime import datetime
7
+ from werkzeug.utils import secure_filename
8
+ from dotenv import load_dotenv
9
+
10
+ # Import detectors
11
+ from modules.video_detector import VideoDeepfakeDetector
12
+ from modules.image_detector import ImageAIDetector
13
+ from modules.audio_detector import AudioVoiceCloneDetector
14
+ from modules.text_detector import TextAIGeneratorDetector
15
+ from modules.plagiarism_checker import PlagiarismChecker
16
+
17
+ # Import database and models
18
+ from models import db, User, DetectionHistory
19
+
20
+ load_dotenv()
21
+
22
+ app = Flask(__name__)
23
+ app.secret_key = os.getenv("SECRET_KEY", "super-secret-key-123")
24
+
25
+ # Database Configuration - Default to SQLite but use MySQL if .env is populated
26
+ def get_db_uri():
27
+ db_user = os.getenv("DB_USER")
28
+ db_pass = os.getenv("DB_PASSWORD")
29
+ db_host = os.getenv("DB_HOST", "localhost")
30
+ db_port = os.getenv("DB_PORT", "3306")
31
+ db_name = os.getenv("DB_NAME", "ai_detection_db")
32
+
33
+ if db_user and db_pass:
34
+ return f"mysql+mysqlconnector://{db_user}:{db_pass}@{db_host}:{db_port}/{db_name}"
35
+ return 'sqlite:///ai_detection.db'
36
+
37
+ app.config['SQLALCHEMY_DATABASE_URI'] = get_db_uri()
38
+ app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
39
+ app.config['UPLOAD_FOLDER'] = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'uploads')
40
+ app.config['MAX_CONTENT_LENGTH'] = 500 * 1024 * 1024 # 500MB
41
+
42
+ # Initialize Database
43
+ db.init_app(app)
44
+
45
+ with app.app_context():
46
+ db_uri = app.config['SQLALCHEMY_DATABASE_URI']
47
+ print(f"\n==========================================")
48
+ print(f"DATABASE CONNECTION: {db_uri}")
49
+ print(f"==========================================\n")
50
+
51
+ # Enable CORS
52
+ CORS(app)
53
+
54
+ # Ensure folders exist
55
+ os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
56
+
57
+ # Initialize Detectors (Lazy loading would be better but let's do it here for now)
58
+ # We handle errors in case models fail to load
59
+ try:
60
+ video_detector = VideoDeepfakeDetector()
61
+ except Exception as e:
62
+ print(f"[ERROR] Failed to load video detector: {e}")
63
+ video_detector = None
64
+
65
+ try:
66
+ image_detector = ImageAIDetector()
67
+ except Exception as e:
68
+ print(f"[ERROR] Failed to load image detector: {e}")
69
+ image_detector = None
70
+
71
+ try:
72
+ audio_detector = AudioVoiceCloneDetector()
73
+ except Exception as e:
74
+ print(f"[ERROR] Failed to load audio detector: {e}")
75
+ audio_detector = None
76
+
77
+ try:
78
+ text_detector = TextAIGeneratorDetector()
79
+ except Exception as e:
80
+ print(f"[ERROR] Failed to load text detector: {e}")
81
+ text_detector = None
82
+
83
+ try:
84
+ plagiarism_checker = PlagiarismChecker()
85
+ except Exception as e:
86
+ print(f"[ERROR] Failed to load plagiarism checker: {e}")
87
+ plagiarism_checker = None
88
+
89
+
90
+ # --- ROUTES ---
91
+
92
+ @app.route('/')
93
+ def index():
94
+ if 'user_id' not in session:
95
+ return redirect(url_for('login'))
96
+ return render_template('index.html')
97
+
98
+ @app.route('/login', methods=['GET', 'POST'])
99
+ def login():
100
+ if request.method == 'POST':
101
+ if request.is_json:
102
+ data = request.json
103
+ else:
104
+ data = request.form
105
+
106
+ username = data.get('username')
107
+ password = data.get('password')
108
+
109
+ user = User.query.filter_by(username=username).first()
110
+ if not user:
111
+ # Also try email if username field was used for email
112
+ user = User.query.filter_by(email=username).first()
113
+
114
+ if user and user.check_password(password):
115
+ session['user_id'] = user.id
116
+ session['username'] = user.username
117
+ if request.is_json:
118
+ return jsonify({"success": True, "redirect": "/"})
119
+ return redirect(url_for('index'))
120
+
121
+ if request.is_json:
122
+ return jsonify({"success": False, "error": "Invalid credentials"}), 401
123
+ return "Invalid username or password", 401
124
+
125
+ return render_template('login.html')
126
+
127
+ @app.route('/signup', methods=['GET', 'POST'])
128
+ def signup():
129
+ if request.method == 'POST':
130
+ if request.is_json:
131
+ data = request.json
132
+ else:
133
+ data = request.form
134
+
135
+ username = data.get('username')
136
+ email = data.get('email')
137
+ password = data.get('password')
138
+
139
+ if User.query.filter_by(username=username).first():
140
+ if request.is_json: return jsonify({"success": False, "error": "Username exists"}), 400
141
+ return "Username already exists", 400
142
+
143
+ if User.query.filter_by(email=email).first():
144
+ if request.is_json: return jsonify({"success": False, "error": "Email exists"}), 400
145
+ return "Email already exists", 400
146
+
147
+ new_user = User(username=username, email=email)
148
+ new_user.set_password(password)
149
+ db.session.add(new_user)
150
+ db.session.commit()
151
+
152
+ session['user_id'] = new_user.id
153
+ session['username'] = new_user.username
154
+
155
+ if request.is_json:
156
+ return jsonify({"success": True, "redirect": "/"})
157
+ return redirect(url_for('index'))
158
+
159
+ return render_template('signup.html')
160
+
161
+ @app.route('/logout', methods=['POST'])
162
+ def logout():
163
+ session.clear()
164
+ return jsonify({"success": True})
165
+
166
+ @app.route('/api/user/profile')
167
+ def user_profile():
168
+ if 'user_id' not in session:
169
+ return jsonify({"error": "Unauthorized"}), 401
170
+
171
+ user = db.session.get(User, session['user_id'])
172
+ if not user:
173
+ return jsonify({"error": "User not found"}), 404
174
+
175
+ return jsonify(user.to_dict())
176
+
177
+ @app.route('/api/user/history', methods=['GET'])
178
+ def user_history():
179
+ if 'user_id' not in session:
180
+ return jsonify({"error": "Unauthorized"}), 401
181
+
182
+ history = DetectionHistory.query.filter_by(user_id=session['user_id']).order_by(DetectionHistory.created_at.desc()).all()
183
+ return jsonify([item.to_dict() for item in history])
184
+
185
+ @app.route('/api/user/history', methods=['DELETE'])
186
+ def clear_history():
187
+ if 'user_id' not in session:
188
+ return jsonify({"error": "Unauthorized"}), 401
189
+
190
+ DetectionHistory.query.filter_by(user_id=session['user_id']).delete()
191
+ db.session.commit()
192
+ return jsonify({"success": True})
193
+
194
+ # --- ANALYSIS ENDPOINTS ---
195
+
196
+ def save_history(detection_type, result, filename=None):
197
+ if 'user_id' in session:
198
+ try:
199
+ # Handle different result keys from different modules
200
+ is_fake = result.get('is_fake') or result.get('is_ai_generated') or result.get('is_voice_cloned') or result.get('is_plagiarized', False)
201
+ auth_score = result.get('authenticity_score', 0.0)
202
+ conf = result.get('confidence', 0.0)
203
+ label = result.get('label', 'Unknown')
204
+
205
+ history = DetectionHistory(
206
+ user_id=session['user_id'],
207
+ detection_type=detection_type,
208
+ model_used=result.get('model_name', result.get('source', 'Default')),
209
+ filename=filename,
210
+ is_fake=bool(is_fake),
211
+ authenticity_score=float(auth_score),
212
+ confidence=float(conf),
213
+ result_label=label,
214
+ full_result=str(result),
215
+ request_ip=request.remote_addr
216
+ )
217
+ db.session.add(history)
218
+ db.session.commit()
219
+ print(f"[OK] Saved detection history for user {session['user_id']}")
220
+ except Exception as e:
221
+ print(f"[ERROR] Failed to save history: {e}")
222
+ db.session.rollback()
223
+
224
+ @app.route('/api/detect/video', methods=['POST'])
225
+ def detect_video():
226
+ if 'user_id' not in session: return jsonify({"error": "Unauthorized"}), 401
227
+ if not video_detector: return jsonify({"error": "Video detector not loaded"}), 500
228
+
229
+ if 'file' not in request.files:
230
+ return jsonify({"error": "No file uploaded"}), 400
231
+
232
+ file = request.files['file']
233
+ if file.filename == '':
234
+ return jsonify({"error": "No file selected"}), 400
235
+
236
+ filename = secure_filename(f"{uuid.uuid4()}_{file.filename}")
237
+ filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
238
+ file.save(filepath)
239
+
240
+ try:
241
+ result = video_detector.detect(filepath)
242
+ save_history('video', result, file.filename)
243
+ return jsonify(result)
244
+ except Exception as e:
245
+ return jsonify({"error": str(e)}), 500
246
+ finally:
247
+ if os.path.exists(filepath):
248
+ os.remove(filepath)
249
+
250
+ @app.route('/api/detect/image', methods=['POST'])
251
+ def detect_image():
252
+ if 'user_id' not in session: return jsonify({"error": "Unauthorized"}), 401
253
+ if not image_detector: return jsonify({"error": "Image detector not loaded"}), 500
254
+
255
+ file = request.files.get('file')
256
+ url = request.form.get('url')
257
+
258
+ if not file and not url:
259
+ return jsonify({"error": "No image provided"}), 400
260
+
261
+ filepath = None
262
+ if file:
263
+ filename = secure_filename(f"{uuid.uuid4()}_{file.filename}")
264
+ filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
265
+ file.save(filepath)
266
+ else:
267
+ # Handling URL would require a downloader, let's just return error for now if not implemented
268
+ return jsonify({"error": "URL detection not implemented yet"}), 400
269
+
270
+ try:
271
+ result = image_detector.detect(filepath)
272
+ save_history('image', result, file.filename if file else 'url')
273
+ return jsonify(result)
274
+ except Exception as e:
275
+ return jsonify({"error": str(e)}), 500
276
+ finally:
277
+ if filepath and os.path.exists(filepath):
278
+ os.remove(filepath)
279
+
280
+ @app.route('/api/detect/audio', methods=['POST'])
281
+ def detect_audio():
282
+ if 'user_id' not in session: return jsonify({"error": "Unauthorized"}), 401
283
+ if not audio_detector: return jsonify({"error": "Audio detector not loaded"}), 500
284
+
285
+ if 'file' not in request.files:
286
+ return jsonify({"error": "No file uploaded"}), 400
287
+
288
+ file = request.files['file']
289
+ filename = secure_filename(f"{uuid.uuid4()}_{file.filename}")
290
+ filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
291
+ file.save(filepath)
292
+
293
+ try:
294
+ result = audio_detector.detect(filepath)
295
+ save_history('audio', result, file.filename)
296
+ return jsonify(result)
297
+ except Exception as e:
298
+ return jsonify({"error": str(e)}), 500
299
+ finally:
300
+ if os.path.exists(filepath):
301
+ os.remove(filepath)
302
+
303
+ @app.route('/api/detect/text', methods=['POST'])
304
+ def detect_text():
305
+ if 'user_id' not in session: return jsonify({"error": "Unauthorized"}), 401
306
+ if not text_detector: return jsonify({"error": "Text detector not loaded"}), 500
307
+
308
+ data = request.json
309
+ text = data.get('text', '')
310
+ if not text:
311
+ return jsonify({"error": "No text provided"}), 400
312
+
313
+ try:
314
+ result = text_detector.detect(text)
315
+ save_history('text', result, 'text_snippet')
316
+ return jsonify(result)
317
+ except Exception as e:
318
+ return jsonify({"error": str(e)}), 500
319
+
320
+ @app.route('/api/detect/plagiarism', methods=['POST'])
321
+ def detect_plagiarism():
322
+ if 'user_id' not in session: return jsonify({"error": "Unauthorized"}), 401
323
+ if not plagiarism_checker: return jsonify({"error": "Plagiarism checker not loaded"}), 500
324
+
325
+ source_file = request.files.get('source_file')
326
+ check_file = request.files.get('check_file')
327
+
328
+ if not source_file or not check_file:
329
+ return jsonify({"error": "Two files are required for plagiarism check"}), 400
330
+
331
+ source_path = os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f"src_{uuid.uuid4()}_{source_file.filename}"))
332
+ check_path = os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f"chk_{uuid.uuid4()}_{check_file.filename}"))
333
+
334
+ source_file.save(source_path)
335
+ check_file.save(check_path)
336
+
337
+ try:
338
+ result = plagiarism_checker.check_two_files(source_path, check_path)
339
+ save_history('plagiarism', result, f"{source_file.filename} vs {check_file.filename}")
340
+ return jsonify(result)
341
+ except Exception as e:
342
+ return jsonify({"error": str(e)}), 500
343
+ finally:
344
+ if os.path.exists(source_path): os.remove(source_path)
345
+ if os.path.exists(check_path): os.remove(check_path)
346
+
347
+ if __name__ == '__main__':
348
+ app.run(debug=True, port=5000)
init_db.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Database initialization script
3
+ Run this script to initialize the database
4
+ """
5
+ from app import app, db
6
+ from models import User, DetectionHistory
7
+
8
+ def init_database():
9
+ """Initialize database and create all tables"""
10
+ with app.app_context():
11
+ try:
12
+ # Create all tables
13
+ db.create_all()
14
+ print("[OK] Database tables created successfully")
15
+
16
+ # Check if tables exist
17
+ from sqlalchemy import inspect
18
+ inspector = inspect(db.engine)
19
+ tables = inspector.get_table_names()
20
+ print(f"[OK] Found {len(tables)} tables: {', '.join(tables)}")
21
+
22
+ # Test database connection
23
+ user_count = User.query.count()
24
+ print(f"[OK] Database connection successful")
25
+ print(f"[OK] Current users in database: {user_count}")
26
+
27
+ except Exception as e:
28
+ print(f"[ERROR] Error initializing database: {e}")
29
+ raise
30
+
31
+ if __name__ == '__main__':
32
+ print("Initializing database...")
33
+ init_database()
34
+
models.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask_sqlalchemy import SQLAlchemy
2
+ from werkzeug.security import generate_password_hash, check_password_hash
3
+ from datetime import datetime
4
+
5
+ db = SQLAlchemy()
6
+
7
+ class User(db.Model):
8
+ __tablename__ = 'users'
9
+
10
+ id = db.Column(db.Integer, primary_key=True)
11
+ username = db.Column(db.String(80), unique=True, nullable=False, index=True)
12
+ email = db.Column(db.String(120), unique=True, nullable=False, index=True)
13
+ password_hash = db.Column(db.String(255), nullable=False)
14
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
15
+
16
+ # Relationship to detection history
17
+ detections = db.relationship('DetectionHistory', backref='user', lazy=True, cascade='all, delete-orphan')
18
+
19
+ def set_password(self, password):
20
+ """Hash and set password"""
21
+ self.password_hash = generate_password_hash(password)
22
+
23
+ def check_password(self, password):
24
+ """Check if provided password matches hash"""
25
+ return check_password_hash(self.password_hash, password)
26
+
27
+ def to_dict(self):
28
+ """Convert user to dictionary"""
29
+ return {
30
+ 'id': self.id,
31
+ 'username': self.username,
32
+ 'email': self.email,
33
+ 'created_at': self.created_at.isoformat()
34
+ }
35
+
36
+ class DetectionHistory(db.Model):
37
+ __tablename__ = 'detection_history'
38
+
39
+ id = db.Column(db.Integer, primary_key=True)
40
+ user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
41
+ detection_type = db.Column(db.String(20), nullable=False) # video, image, audio, text, plagiarism
42
+ model_used = db.Column(db.String(150))
43
+ filename = db.Column(db.String(255))
44
+ is_fake = db.Column(db.Boolean, nullable=False)
45
+ authenticity_score = db.Column(db.Float, nullable=False)
46
+ confidence = db.Column(db.Float)
47
+ result_label = db.Column(db.String(100))
48
+ full_result = db.Column(db.Text)
49
+ request_ip = db.Column(db.String(50))
50
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
51
+
52
+ def to_dict(self):
53
+ """Convert detection to dictionary"""
54
+ return {
55
+ 'id': self.id,
56
+ 'detection_type': self.detection_type,
57
+ 'model_used': self.model_used,
58
+ 'filename': self.filename,
59
+ 'is_fake': self.is_fake,
60
+ 'authenticity_score': self.authenticity_score,
61
+ 'confidence': self.confidence,
62
+ 'result_label': self.result_label,
63
+ 'created_at': self.created_at.isoformat()
64
+ }
requirements.txt ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Flask==3.0.0
2
+ flask-cors==4.0.0
3
+ Flask-SQLAlchemy==3.1.1
4
+ opencv-python==4.8.1.78
5
+ numpy==1.24.3
6
+ librosa==0.10.1
7
+ Werkzeug==3.0.1
8
+ scipy==1.11.4
9
+ pypdf==3.17.1
10
+ python-docx==1.1.0
11
+ scikit-learn==1.3.2
12
+ transformers
13
+ torch
14
+ torchvision
15
+ Pillow
16
+ python-dotenv
17
+ mysql-connector-python
18
+ facenet-pytorch
19
+ tensorflow
schema.sql ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CREATE DATABASE IF NOT EXISTS ai_detection_db;
2
+ USE ai_detection_db;
3
+
4
+ -- =============================================
5
+ -- AI DEEPFAKE DETECTION SYSTEM DATABASE (MySQL)
6
+ -- =============================================
7
+
8
+ -- USERS TABLE
9
+ CREATE TABLE IF NOT EXISTS users (
10
+ id INT AUTO_INCREMENT PRIMARY KEY,
11
+ username VARCHAR(80) NOT NULL UNIQUE,
12
+ email VARCHAR(120) NOT NULL UNIQUE,
13
+ password_hash VARCHAR(255) NOT NULL,
14
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
15
+ );
16
+
17
+ -- DETECTION HISTORY TABLE
18
+ CREATE TABLE IF NOT EXISTS detection_history (
19
+ id INT AUTO_INCREMENT PRIMARY KEY,
20
+ user_id INT NOT NULL,
21
+
22
+ detection_type VARCHAR(20) NOT NULL,
23
+ model_used VARCHAR(150),
24
+
25
+ filename VARCHAR(255),
26
+
27
+ is_fake BOOLEAN NOT NULL,
28
+ authenticity_score FLOAT NOT NULL,
29
+ confidence FLOAT,
30
+ result_label VARCHAR(100),
31
+
32
+ full_result LONGTEXT,
33
+ request_ip VARCHAR(50),
34
+
35
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
36
+
37
+ CONSTRAINT FK_UserDetection
38
+ FOREIGN KEY (user_id) REFERENCES users(id)
39
+ ON DELETE CASCADE
40
+ );
41
+
42
+ -- INDEXES
43
+ CREATE INDEX IX_Users_Username ON users(username);
44
+ CREATE INDEX IX_Users_Email ON users(email);
45
+ CREATE INDEX IX_DetectionHistory_User ON detection_history(user_id);
46
+ CREATE INDEX IX_DetectionHistory_Type ON detection_history(detection_type);
47
+ CREATE INDEX IX_DetectionHistory_Date ON detection_history(created_at);
48
+
49
+ -- SELECT * FROM users; -- Sample query for verification