File size: 5,463 Bytes
fd7d432
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9ca3d0
 
fd7d432
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9ca3d0
 
fd7d432
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
import torch.nn as nn
from torchvision import transforms, models
from huggingface_hub import hf_hub_download
from PIL import Image
import torch.nn.functional as F
from MTL import MTL

transform = transforms.Compose([
    transforms.Resize((224, 224)),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

def load_model_resnet50_semart():
    num_classes_school = 26
    num_classes_type = 10

    model_path = hf_hub_download(
        repo_id="Irina1402/resnet50-semart", 
        filename="model.pth",
        cache_dir="/tmp"
    )

    # Load the updated MTL model
    model = MTL(num_classes_school, num_classes_type)
    model.load_state_dict(torch.load(model_path, map_location=device))
    model = model.to(device)
    model.eval()

    school_labels = sorted([
        "American", "Austrian", "Belgian", "Bohemian", "Catalan", "Danish", "Dutch", "English", "Finnish",
        "Flemish", "French", "German", "Greek", "Hungarian", "Irish", "Italian", "Netherlandish", "Norwegian",
        "Other", "Polish", "Portuguese", "Russian", "Scottish", "Spanish", "Swedish", "Swiss"
    ])

    type_labels = sorted([
        "genre", "historical", "interior", "landscape", "mythological", "other",
        "portrait", "religious", "still-life", "study"
    ])

    return {
        "model": model,
        "school_labels": school_labels,
        "type_labels": type_labels,
        "num_classes_school": num_classes_school
    }


def load_model_resnet50_balanced():
    num_classes_school = 8
    num_classes_type = 8

    model_path = hf_hub_download(
        repo_id="Irina1402/resnet50-balanced", 
        filename="model.pth",
        cache_dir="/tmp"
    )

    model = models.resnet50(weights=models.ResNet50_Weights.DEFAULT)
    num_features = model.fc.in_features
    model.fc = nn.Sequential(
        nn.Linear(num_features, 512),
        nn.ReLU(),
        nn.Dropout(0.4),
        nn.Linear(512, num_classes_school + num_classes_type)
    )

    model.load_state_dict(torch.load(model_path, map_location=device))
    model = model.to(device)
    model.eval()

    school_labels = sorted([
        "French", "American", "Russian", "British", "Italian", "Spanish", "German", "Dutch"
    ])

    type_labels = sorted([
        "portrait", "landscape", "abstract", "genre painting", "religious painting",
        "cityscape", "sketch and study", "still life"
    ])


    return {
        "model": model,
        "school_labels": school_labels,
        "type_labels": type_labels,
        "num_classes_school": num_classes_school
    }


models_registry = {
    "model_semart": load_model_resnet50_semart(),
    "model_balanced": load_model_resnet50_balanced()
}


def classify_image(image: Image.Image, model_name, confidence_threshold=0.20, strong_threshold=0.80, topk=3):
    if model_name not in models_registry:
        return {"error": f"Modelul '{model_name}' nu este disponibil."}

    model_data = models_registry[model_name]
    model = model_data["model"]
    school_labels = model_data["school_labels"]
    type_labels = model_data["type_labels"]
    num_classes_school = model_data["num_classes_school"]

    input_tensor = transform(image).unsqueeze(0).to(device)

    with torch.no_grad():
        if model_name == "model_semart":
            # Two outputs directly
            school_output, type_output = model(input_tensor)
        else:
            # Single output to split manually
            output = model(input_tensor)
            school_output = output[:, :num_classes_school]
            type_output = output[:, num_classes_school:]

    school_probs = F.softmax(school_output, dim=1).squeeze()
    type_probs = F.softmax(type_output, dim=1).squeeze()

    # SCHOOL
    topk_school = torch.topk(school_probs, k=topk)
    school_top1_idx = topk_school.indices[0].item()
    school_top1_prob = school_probs[school_top1_idx].item()

    if school_top1_prob >= strong_threshold:
        school_predictions = [{
            "label": school_labels[school_top1_idx],
            "score": round(school_top1_prob * 100, 1)  # procent
        }]
    else:
        school_predictions = [
            {
                "label": school_labels[i.item()],
                "score": round(school_probs[i].item() * 100, 1)
            }
            for i in topk_school.indices
            if school_probs[i].item() >= confidence_threshold
        ]
        if not school_predictions:
            school_predictions = [{"label": "Unknown", "score": None}]

    # TYPE 
    topk_type = torch.topk(type_probs, k=topk)
    type_top1_idx = topk_type.indices[0].item()
    type_top1_prob = type_probs[type_top1_idx].item()

    if type_top1_prob >= strong_threshold:
        type_predictions = [{
            "label": type_labels[type_top1_idx],
            "score": round(type_top1_prob * 100, 1)
        }]
    else:
        type_predictions = [
            {
                "label": type_labels[i.item()],
                "score": round(type_probs[i].item() * 100, 1)
            }
            for i in topk_type.indices
            if type_probs[i].item() >= confidence_threshold
        ]
        if not type_predictions:
            type_predictions = [{"label": "Unknown", "score": None}]

    return {
        "school_prediction": school_predictions,
        "type_prediction": type_predictions
    }