This repository was archived by the owner on May 3, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
321 lines (248 loc) · 9.18 KB
/
api.py
File metadata and controls
321 lines (248 loc) · 9.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
"""
Flask API for Image Detection
This module provides a Flask web server with endpoints for detecting images
using pre-trained models and for receiving user feedback on the detection
results.
"""
import os
import uuid
import tempfile
from time import time
from datetime import datetime
from flask_cors import CORS
from waitress import serve
from flask import Flask, request, jsonify
from dotenv import load_dotenv
import torch
from pymongo import MongoClient
from utils.general import (
setup_logger,
get_memory_usage,
validate_image_file,
compress_and_resize_image,
)
from utils.aws import (
upload_image_to_s3
)
from utils.aws import (
get_secret
)
from models.dmdetector import (
process_image as dm_process_image,
load_model as load_dm_model,
models_config as dm_models_config,
)
from models.gandetector import (
process_image as gan_process_image,
load_model as load_gan_model,
models_config as gan_models_config,
)
from models.exifdetector import (
process_image as exif_process_image,
)
from models.explainability import (
craft_explanation
)
logger = setup_logger(__name__)
# Load environment variables from .env file
load_dotenv()
app = Flask(__name__)
CORS(app)
# Global variables to store loaded models
dm_loaded_models = {}
gan_loaded_models = {}
def preload_models():
"""
Preloads models into memory for faster inference.
"""
logger.info("Starting model preloading...")
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Preload DM models
for model_name in dm_models_config:
dm_loaded_models[model_name] = load_dm_model(model_name, device)
logger.info("Loaded DM model: %s", model_name)
logger.info("Memory usage: %s", get_memory_usage())
# Preload GAN models
for model_name in gan_models_config:
gan_loaded_models[model_name] = load_gan_model(model_name, device)
logger.info("Loaded GAN model: %s", model_name)
logger.info("Memory usage: %s", get_memory_usage())
logger.info("Model preloading complete!")
def save_to_mongodb(image_path, inference_results):
"""
Save results to MongoDB
"""
mongodb_url = os.getenv("MONGODB_URL")
if mongodb_url:
pass
else:
mongodb_url = get_secret("MONGODB_URL")
logger.info("MONGODB_URL is: ", mongodb_url)
try:
with MongoClient(mongodb_url) as client:
db = client['test']
collection = db['aidetectorresults']
timestamp = datetime.now()
document = {
"image_path": image_path,
"inference_results": inference_results,
"created_at": timestamp,
}
result = collection.insert_one(document)
if result.inserted_id:
response = {"message": "Saved successfully"}
logger.info("Saved successfully to mongodb: %s", result.inserted_id)
else:
response = {"message": "The document could not be inserted"}
return jsonify(response)
except Exception as e:
logger.error("Error to save to MongoDB: %s", e)
@app.route("/debug/preload_models", methods=["GET"])
def debug_preload_models():
"""
Responds with a list of preloaded models.
"""
dm_models_loaded = list(dm_loaded_models.keys())
gan_models_loaded = list(gan_loaded_models.keys())
return (
jsonify(
{
"DM_Models_Loaded": dm_models_loaded,
"GAN_Models_Loaded": gan_models_loaded,
}
),
200,
)
@app.route("/", methods=["GET"])
def hello_world():
"""
Responds with a 'Hello world' message.
"""
return jsonify({"message": "Hello world!"}), 200
def update_feedback_in_mongodb(image_path, feedback):
"""
Update feedback in MongoDB
"""
mongodb_url = os.getenv("MONGODB_URL")
if mongodb_url:
pass
else:
mongodb_url = get_secret("MONGODB_URL")
logger.info("MONGODB_URL is: %s", mongodb_url)
try:
with MongoClient(mongodb_url) as client:
db = client['test']
collection = db['aidetectorresults']
existing_document = collection.find_one({"image_path": image_path})
if existing_document:
collection.update_one(
{"image_path": image_path},
{"$set": {"feedback": feedback}}
)
logger.info("MongoDB document updated")
else:
logger.warning("Document not found for image_path: %s", image_path)
except Exception as e:
logger.error("Error updating feedback in MongoDB: %s", e)
@app.route("/feedback", methods=["POST"])
def feedback():
"""
Receives user feedback for an image detection.
Expects a JSON payload with 'image_path' and 'feedback' keys.
Prints the received data and returns a confirmation message.
"""
logger.debug("Received feedback data: %s", request.data)
data = request.json
if not data or "image_path" not in data or "feedback" not in data:
return jsonify({"error": "Missing image_path or feedback"}), 400
image_path = data["image_path"]
feedback_text = data["feedback"]
update_feedback_in_mongodb(image_path, feedback_text)
return jsonify({"message": "Feedback received and updated successfully"})
@app.route("/detect", methods=["POST"])
def detect():
"""
Detects images using DM and GAN detectors.
Expects a multipart/form-data request with a file.
Saves the file to a temporary location and runs detection models on it.
Returns the combined results of the detections.
"""
if "file" not in request.files:
return jsonify({"error": "No file part"}), 400
file = request.files["file"]
if file.filename == "":
return jsonify({"error": "No selected image"}), 400
logger.info("Received the image %s", file.filename)
# Generate a random mnemonic filename with the original file extension
_, ext = os.path.splitext(file.filename)
random_name = f"{uuid.uuid4()}{ext}"
# Save the file to a temporary location
temp_dir = tempfile.gettempdir()
image_path = os.path.join(temp_dir, random_name)
file.save(image_path)
logger.info("Image saved in temporal the location: %s", image_path)
# Validate the image file
try:
validate_image_file(image_path)
processed_image_path = compress_and_resize_image(image_path)
logger.info("Image %s validated, resized and compressed", image_path)
except ValueError as e:
logger.error("Image %s is not valid: %s", image_path, e)
return jsonify({"error": "The provided image format is not valid"}), 400
logger.info("Uploading images to S3")
# Upload original image
upload_success, error_message = upload_image_to_s3(image_path, "aidetector-results")
if not upload_success:
logger.error("Error upload image to AWS: %s", error_message)
return jsonify({"error": "There was an issue processing your image"}), 400
# Upload processed image
upload_success, error_message = upload_image_to_s3(processed_image_path, "aidetector-results")
if not upload_success:
logger.error("Error upload image to AWS: %s", error_message)
return jsonify({"error": "There was an issue processing your image"}), 400
# Start timing
start_time = time()
logger.info("Starting DM detection on %s", processed_image_path)
# Run DM Detector
dm_results = dm_process_image(processed_image_path, preloaded_models=dm_loaded_models)
logger.info("Starting GAN detection on %s", processed_image_path)
# Run GAN Detector
gan_results = gan_process_image(processed_image_path, preloaded_models=gan_loaded_models)
# Run EXIF detector
original_filename = os.path.basename(file.filename)
exif_results = exif_process_image(image_path, original_filename)
# Run explainability generator
preliminary_results = {
"dMDetectorResults": dm_results,
"gANDetectorResults": gan_results,
"exifDetectorResults": exif_results,
}
logger.info("Starting explainability generator on %s", processed_image_path)
craft_results = craft_explanation(processed_image_path, preliminary_results)
# End timing
end_time = time()
total_execution_time = end_time - start_time
# Combine results
results = {
"imagePath": image_path,
"dMDetectorResults": dm_results,
"gANDetectorResults": gan_results,
"exifDetectorResults": exif_results,
"explainabilityResults": craft_results,
"totalExecutionTime": total_execution_time,
}
save_to_mongodb(image_path, results)
return jsonify(results)
if __name__ == "__main__":
preload_models()
logger.info("Running on environment: %s", os.environ.get('DEV_ENV'))
# Check if the 'DEV_ENV' environment variable is set to 'true'
if os.environ.get('DEV_ENV') == 'true':
# Run on port 8080 for development environment
port = 8080
else:
# Run on port 80 otherwise
port = 80
# Log the port number
logger.info("Successfully running the API on port %s", port)
serve(app, host="0.0.0.0", port=port)