File size: 9,374 Bytes
507cd9a
 
 
 
 
 
cf21eaf
33dfaa8
d2a7577
 
fad0036
d2a7577
 
 
927cd70
 
 
 
 
 
 
 
ce0e37a
33dfaa8
 
 
507cd9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33dfaa8
 
 
927cd70
507cd9a
cbc96c3
 
 
507cd9a
cbc96c3
 
507cd9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9cf84ce
507cd9a
5490f47
 
 
 
 
 
cbc96c3
 
 
 
 
 
 
5490f47
cbc96c3
 
 
 
 
5490f47
cbc96c3
 
 
 
 
 
 
 
507cd9a
 
 
 
cbc96c3
507cd9a
 
cbc96c3
 
 
 
 
507cd9a
 
cbc96c3
 
 
 
 
 
507cd9a
 
 
 
 
 
33dfaa8
507cd9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9cf84ce
507cd9a
5490f47
 
 
 
 
 
507cd9a
 
 
 
 
 
5490f47
 
507cd9a
 
 
 
 
5490f47
 
507cd9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33dfaa8
507cd9a
 
 
 
 
 
 
 
 
 
 
8ce60c0
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
import io
import hashlib
import logging
import aiohttp
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import JSONResponse

# import os
# from os import path
# cache_path = path.join(path.dirname(path.abspath(__file__)), "models")

# os.environ["TRANSFORMERS_CACHE"] = cache_path
# os.environ["HF_HUB_CACHE"] = cache_path
# os.environ["HF_HOME"] = cache_path

# PATH = 'huggingface'
# DATASETPATH = '/home/ahmadzen/.cache/huggingface/datasets'
# MODEL_PATH = '/home/ahmadzen/ViT_Deepfake_Detection/SavedModel'
# os.environ['HF_HOME'] = PATH
# os.environ['HF_DATASETS_CACHE'] = DATASETPATH
# os.environ['TORCH_HOME'] = PATH
# os.environ['HF_HUB_CACHE'] = '/home/ahmadzen/.cache/huggingface'

# from transformers import AutoImageProcessor, ViTForImageClassification
from transformers import pipeline
from transformers.pipelines import PipelineException
from PIL import Image
from cachetools import Cache
import torch
import torch.nn.functional as F
from models import (
    FileImageDetectionResponse,
    UrlImageDetectionResponse,
    ImageUrlsRequest,
)

app = FastAPI()
logging.basicConfig(
    level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)

# Initialize Cache with no TTL
cache = Cache(maxsize=1000)

# Load the model using the transformers pipeline
model = pipeline("image-classification", model="Wvolf/ViT_Deepfake_Detection")
# image_processor = AutoImageProcessor.from_pretrained("Wvolf/ViT_Deepfake_Detection")
# model = ViTForImageClassification.from_pretrained("Wvolf/ViT_Deepfake_Detection")
    
# Detect the device used by TensorFlow
# DEVICE = "GPU" if tf.config.list_physical_devices("GPU") else "CPU"
# logging.info("TensorFlow version: %s", tf.__version__)
# logging.info("Model is using: %s", DEVICE)

# if DEVICE == "GPU":
#     logging.info("GPUs available: %d", len(tf.config.list_physical_devices("GPU")))


async def download_image(image_url: str) -> bytes:
    """Download an image from a URL."""
    async with aiohttp.ClientSession() as session:
        async with session.get(image_url) as response:
            if response.status != 200:
                raise HTTPException(
                    status_code=response.status, detail="Image could not be retrieved."
                )
            return await response.read()


def hash_data(data):
    """Function for hashing image data."""
    return hashlib.sha256(data).hexdigest()


@app.post("/v1/detect", response_model=FileImageDetectionResponse)
async def classify_image(file: UploadFile = File(None)):
    """Function analyzing image."""
    if file is None:
        raise HTTPException(
            status_code=400,
            detail="An image file must be provided.",
        )

    try:
        logging.info("Processing %s", file.filename)

        # Read the image file
        image_data = await file.read()
        image_hash = hash_data(image_data)

        if image_hash in cache:
            # Return cached entry
            logging.info("Returning cached entry for %s", file.filename)

            cached_response = cache[image_hash]
            response_data = {**cached_response, "file_name": file.filename}

            return FileImageDetectionResponse(**response_data)

        image = Image.open(io.BytesIO(image_data))

        inputs = model(image)

        # with torch.no_grad():
        #     logits = model(**inputs).logits
        #     probs = F.softmax(logits, dim=-1)
        #     predicted_label_id = probs.argmax(-1).item()
        #     predicted_label = model.config.id2label[predicted_label_id]
        #     confidence = probs.max().item()

    # model predicts one of the 1000 ImageNet classes
    #     predicted_label = logits.argmax(-1).item()
    #     logging.info("predicted_label", predicted_label)
    #     logging.info("model.config.id2label[predicted_label] %s", model.config.id2label[predicted_label])
    # # print(model.config.id2label[predicted_label])
    # Find the prediction with the highest confidence using the max() function
        predicted_label = max(inputs, key=lambda x: x["score"])
    # logging.info("best_prediction %s", best_prediction)
    # best_prediction2 = results[1]["label"]
    # logging.info("best_prediction2 %s", best_prediction2)

    # # Calculate the confidence score, rounded to the nearest tenth and as a percentage
        confidence = round(predicted_label["score"] * 100, 1)

    # # Prepare the custom response data
        detection_result = {
            "prediction": predicted_label,
            "confidence_percentage":confidence,
        }
        # Use the model to classify the image
        # results = model(image)

        # Find the prediction with the highest confidence using the max() function
        # best_prediction = max(results, key=lambda x: x["score"])

        # Calculate the confidence score, rounded to the nearest tenth and as a percentage
        # confidence_percentage = round(best_prediction["score"] * 100, 1)

        # Prepare the custom response data
        # detection_result = {
        #     "is_nsfw": best_prediction["label"] == "nsfw",
        #     "confidence_percentage": confidence_percentage,
        # }

        # Populate hash
        cache[image_hash] = detection_result.copy()

        # Add url to the API response
        detection_result["file_name"] = file.filename

        response_data.append(detection_result)

        # Add file_name to the API response
        response_data["file_name"] = file.filename

        return FileImageDetectionResponse(**response_data)

    except PipelineException as e:
        logging.error("Error processing image: %s", str(e))
        raise HTTPException(
            status_code=500, detail=f"Error processing image: {str(e)}"
        ) from e


@app.post("/v1/detect/urls", response_model=list[UrlImageDetectionResponse])
async def classify_images(request: ImageUrlsRequest):
    """Function analyzing images from URLs."""
    response_data = []

    for image_url in request.urls:
        try:
            logging.info("Downloading image from URL: %s", image_url)
            image_data = await download_image(image_url)
            image_hash = hash_data(image_data)

            if image_hash in cache:
                # Return cached entry
                logging.info("Returning cached entry for %s", image_url)

                cached_response = cache[image_hash]
                response = {**cached_response, "url": image_url}

                response_data.append(response)
                continue

            image = Image.open(io.BytesIO(image_data))
            inputs = model(image)

            # with torch.no_grad():
            #     logits = model(**inputs).logits
            #     probs = F.softmax(logits, dim=-1)
            #     predicted_label_id = probs.argmax(-1).item()
            #     predicted_label = model.config.id2label[predicted_label_id]
            #     confidence = probs.max().item()

        # model predicts one of the 1000 ImageNet classes
        #     predicted_label = logits.argmax(-1).item()
        #     logging.info("predicted_label", predicted_label)
        #     logging.info("model.config.id2label[predicted_label] %s", model.config.id2label[predicted_label])
        # # print(model.config.id2label[predicted_label])
            predicted_label = max(inputs, key=lambda x: x["score"])
    # best_prediction = max(results, key=lambda x: x["score"])
        # logging.info("best_prediction %s", best_prediction)
        # best_prediction2 = results[1]["label"]
        # logging.info("best_prediction2 %s", best_prediction2)

        # # Calculate the confidence score, rounded to the nearest tenth and as a percentage
            # confidence_percentage = round(best_prediction["score"] * 100, 1)
            confidence = round(predicted_label["score"] * 100, 1)

        # # Prepare the custom response data
            detection_result = {
                "prediction": predicted_label,
                "confidence_percentage":confidence,
            }
            # Use the model to classify the image
            # results = model(image)

            # Find the prediction with the highest confidence using the max() function
            # best_prediction = max(results, key=lambda x: x["score"])

            # Calculate the confidence score, rounded to the nearest tenth and as a percentage
            # confidence_percentage = round(best_prediction["score"] * 100, 1)

            # Prepare the custom response data
            # detection_result = {
            #     "is_nsfw": best_prediction["label"] == "nsfw",
            #     "confidence_percentage": confidence_percentage,
            # }

            # Populate hash
            cache[image_hash] = detection_result.copy()

            # Add url to the API response
            detection_result["url"] = image_url

            response_data.append(detection_result)

        except PipelineException as e:
            logging.error("Error processing image from %s: %s", image_url, str(e))
            raise HTTPException(
                status_code=500,
                detail=f"Error processing image from {image_url}: {str(e)}",
            ) from e

    return JSONResponse(status_code=200, content=response_data)

if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=7860)