File size: 8,163 Bytes
3343c55
 
66d71ff
3343c55
 
8db4042
3343c55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66d71ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3343c55
 
8db4042
3343c55
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, File, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
import numpy as np
from PIL import Image
from tensorflow.keras.models import load_model
import os
os.environ["KERAS_BACKEND"] = "tensorflow"
	

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

ANIMALS = ['Cat', 'Dog', 'Panda'] # Animal names here, these represent the labels of the images that we trained our model on.


@app.get("/", response_class=HTMLResponse)
def test_upload():
    html_content = """
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Animal Image Classifier</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                max-width: 800px;
                margin: 50px auto;
                padding: 20px;
                background-color: #f5f5f5;
            }
            .container {
                background-color: white;
                padding: 30px;
                border-radius: 10px;
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            }
            h1 {
                color: #333;
                text-align: center;
            }
            .upload-section {
                margin: 20px 0;
                padding: 20px;
                border: 2px dashed #ccc;
                border-radius: 5px;
                text-align: center;
            }
            input[type="file"] {
                margin: 10px 0;
            }
            button {
                background-color: #4CAF50;
                color: white;
                padding: 10px 20px;
                border: none;
                border-radius: 5px;
                cursor: pointer;
                font-size: 16px;
            }
            button:hover {
                background-color: #45a049;
            }
            button:disabled {
                background-color: #cccccc;
                cursor: not-allowed;
            }
            .preview {
                margin: 20px 0;
                text-align: center;
            }
            .preview img {
                max-width: 300px;
                max-height: 300px;
                border-radius: 5px;
                box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            }
            .result {
                margin-top: 20px;
                padding: 20px;
                background-color: #e8f5e9;
                border-radius: 5px;
                text-align: center;
                font-size: 20px;
                font-weight: bold;
                color: #2e7d32;
            }
            .error {
                background-color: #ffebee;
                color: #c62828;
            }
            .loading {
                display: none;
                margin: 20px 0;
                text-align: center;
            }
            .spinner {
                border: 4px solid #f3f3f3;
                border-top: 4px solid #4CAF50;
                border-radius: 50%;
                width: 40px;
                height: 40px;
                animation: spin 1s linear infinite;
                margin: 0 auto;
            }
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
        </style>
    </head>
    <body>
        <div class="container">
            <h1>๐Ÿพ Animal Image Classifier</h1>
            <p style="text-align: center; color: #666;">Upload an image of a Cat, Dog, or Panda to classify it!</p>
            
            <div class="upload-section">
                <input type="file" id="imageInput" accept="image/*">
                <br>
                <button onclick="uploadImage()" id="uploadBtn">Classify Image</button>
            </div>
            
            <div class="loading" id="loading">
                <div class="spinner"></div>
                <p>Classifying...</p>
            </div>
            
            <div class="preview" id="preview"></div>
            
            <div id="result"></div>
        </div>

        <script>
            let selectedFile = null;

            document.getElementById('imageInput').addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (file) {
                    selectedFile = file;
                    // Show preview
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        document.getElementById('preview').innerHTML = 
                            '<img src="' + e.target.result + '" alt="Preview">';
                    }
                    reader.readAsDataURL(file);
                    document.getElementById('result').innerHTML = '';
                }
            });

            async function uploadImage() {
                if (!selectedFile) {
                    alert('Please select an image first!');
                    return;
                }

                const uploadBtn = document.getElementById('uploadBtn');
                const loading = document.getElementById('loading');
                const resultDiv = document.getElementById('result');

                // Show loading, disable button
                uploadBtn.disabled = true;
                loading.style.display = 'block';
                resultDiv.innerHTML = '';

                const formData = new FormData();
                formData.append('img', selectedFile);

                try {
                    const response = await fetch('/upload/image', {
                        method: 'POST',
                        body: formData
                    });

                    if (response.ok) {
                        const result = await response.text();
                        const animal = result.replace(/"/g, ''); // Remove quotes if present
                        
                        // Display result with emoji
                        const emojis = {
                            'Cat': '๐Ÿฑ',
                            'Dog': '๐Ÿถ',
                            'Panda': '๐Ÿผ'
                        };
                        
                        resultDiv.innerHTML = 
                            '<div class="result">Prediction: ' + 
                            (emojis[animal] || '') + ' ' + animal + '</div>';
                    } else {
                        resultDiv.innerHTML = 
                            '<div class="result error">Error: ' + response.status + '</div>';
                    }
                } catch (error) {
                    resultDiv.innerHTML = 
                        '<div class="result error">Error: ' + error.message + '</div>';
                } finally {
                    // Hide loading, enable button
                    loading.style.display = 'none';
                    uploadBtn.disabled = false;
                }
            }
        </script>
    </body>
    </html>
    """
    return HTMLResponse(content=html_content)


model = load_model("hf://nathansegers/masterclass-2025")

@app.post('/upload/image')
async def uploadImage(img: UploadFile = File(...)):
    original_image = Image.open(img.file) # Read the bytes and process as an image
    resized_image = original_image.resize((64, 64)) # Resize
    images_to_predict = np.expand_dims(np.array(resized_image), axis=0) # Our AI Model wanted a list of images, but we only have one, so we expand it's dimension
    predictions = model.predict(images_to_predict) # The result will be a list with predictions in the one-hot encoded format: [ [0 1 0] ]
    prediction_probabilities = predictions
    classifications = prediction_probabilities.argmax(axis=1) # We try to fetch the index of the highest value in this list [ [1] ]

    return ANIMALS[classifications.tolist()[0]] # Fetch the first item in our classifications array, format it as a list first, result will be e.g.: "Dog"