File size: 2,304 Bytes
5bf30ef
 
 
 
10412fe
5bf30ef
 
10412fe
 
dead143
10412fe
 
 
 
 
8199893
 
 
10412fe
 
5bf30ef
10412fe
5bf30ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5ec00a
5bf30ef
 
a5ec00a
 
 
 
 
 
 
 
 
5bf30ef
 
 
 
 
a5ec00a
5bf30ef
 
dead143
5bf30ef
 
 
 
 
 
dead143
 
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
import cv2
import numpy as np
import os
import csv
import uuid
from datetime import datetime

ALLOWED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".tif"}

def save_uploaded_file(save_dir, file):
    # Validate file extension
    _, ext = os.path.splitext(file.filename or "")
    if ext.lower() not in ALLOWED_EXTENSIONS:
        raise ValueError(f"Unsupported file type '{ext}'. Allowed: {ALLOWED_EXTENSIONS}")

    # Ensure upload directory exists
    os.makedirs(save_dir, exist_ok=True)

    # Generate unique ID (date prefix + uuid4) to avoid race condition
    image_id = datetime.now().strftime("%Y%m%d_%H%M%S") + "_" + uuid.uuid4().hex[:8]
    saved_path = os.path.join(save_dir, f"{image_id}.jpg")

    # Save file
    with open(saved_path, "wb") as f:
        f.write(file.file.read())
    return saved_path, image_id

def is_valid_image(file_path):
    try:
        image = cv2.imread(file_path)
        if image is None:
            return False
        return True
    except Exception:
        return False
    
def preprocess_image(image_path):
    # Read image — Resize(256) + CenterCrop(224) to match training val_transform
    image = cv2.imread(image_path)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    h, w = image.shape[:2]
    if h < w:
        new_h, new_w = 256, int(w * 256 / h)
    else:
        new_h, new_w = int(h * 256 / w), 256
    image = cv2.resize(image, (new_w, new_h))
    y0 = (new_h - 224) // 2
    x0 = (new_w - 224) // 2
    image = image[y0:y0+224, x0:x0+224]
    image = image / 255.0
    mean = np.array([0.485, 0.456, 0.406])
    std = np.array([0.229, 0.224, 0.225])
    image = (image - mean) / std
    image = np.transpose(image, (2, 0, 1))  # HWC -> CHW
    input_tensor = np.expand_dims(image, axis=0).astype(np.float32)
    return input_tensor

def append_to_csv(csv_path, image_id, prediction, probability, similarity):
    # Ensure CSV file exists
    os.makedirs(os.path.dirname(csv_path), exist_ok=True)
    file_exists = os.path.isfile(csv_path)
    with open(csv_path, mode="a", newline="") as f:
        writer = csv.writer(f)
        if not file_exists:
            writer.writerow(["ID", "Prediction", "Probability", "Similarity"])
        writer.writerow([image_id, prediction, probability, round(float(similarity), 3)])