pasiatri commited on
Commit
0a046ac
·
1 Parent(s): 12e115e

Create old.py

Browse files
Files changed (1) hide show
  1. old.py +335 -0
old.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, File, UploadFile, Form, HTTPException, Request
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from fastapi.responses import JSONResponse
4
+ from pydantic import BaseModel
5
+ import tensorflow as tf
6
+ from tensorflow.keras.models import load_model
7
+ import numpy as np
8
+ from PIL import Image
9
+ import requests
10
+ from io import BytesIO
11
+ import os
12
+ import logging
13
+ import uvicorn
14
+ from typing import Optional, Dict, Any, List
15
+
16
+ # Configure logging
17
+ logging.basicConfig(level=logging.INFO,
18
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
19
+ logger = logging.getLogger(__name__)
20
+
21
+ app = FastAPI(title="Felidae Classifier API",
22
+ description="An API for classifying felidae species using a TensorFlow model",
23
+ version="1.0.0")
24
+
25
+ # Enable CORS
26
+ app.add_middleware(
27
+ CORSMiddleware,
28
+ allow_origins=["*"], # Allows all origins
29
+ allow_credentials=True,
30
+ allow_methods=["*"], # Allows all methods
31
+ allow_headers=["*"], # Allows all headers
32
+ )
33
+
34
+ # Model path
35
+ MODEL_PATH = "xception_felidae.h5"
36
+
37
+ current_dir = os.path.abspath(os.path.dirname(__file__))
38
+ model_path = os.path.join(current_dir, MODEL_PATH)
39
+ logger.info(f"Current directory: {current_dir}")
40
+ logger.info(f"Looking for model at: {model_path}")
41
+ logger.info(f"File exists: {os.path.isfile(model_path)}")
42
+
43
+ # Class names (classes trained in the model)
44
+ class_names = [
45
+ 'A_Cheetah',
46
+ 'C_Caracal',
47
+ 'Catopuma_Temminckii',
48
+ 'F_ Bieti_Chinese_Mountain',
49
+ 'F_Catus_Domestic',
50
+ 'F_Margarita_Sand',
51
+ 'F_Nigripes_Blackfoot',
52
+ 'F_Silvestris_European',
53
+ 'F_lybica_African',
54
+ 'H_Jaguarundi',
55
+ 'L_Serval',
56
+ 'L_lynx_Canadensis_Kanada',
57
+ 'L_lynx_Lynx_Eurasia',
58
+ 'L_lynx_Pardinus_Iberia',
59
+ 'L_lynx_Rufus_Bobcat',
60
+ 'Leo_colocola_Pampas',
61
+ 'Leo_pardalis_Oselot',
62
+ 'Leo_wiedii_Margay',
63
+ 'N_Nebulosa_Dahan',
64
+ 'Oto_Manul_Pallas',
65
+ 'P_Jaguar',
66
+ 'P_Leopard',
67
+ 'P_Lion',
68
+ 'P_Macan_Tutul_Salju',
69
+ 'P_Tiger',
70
+ 'Pri_Bengalensis_kuwuk_leopard',
71
+ 'Pri_Planiceps_Datar',
72
+ 'Pri_Rubiginosus_Totol',
73
+ 'Pri_Viverrinus_Bakau',
74
+ 'Pu_Puma_Concolor',
75
+ ]
76
+
77
+ # Define Pydantic models for request/response
78
+ class UrlRequest(BaseModel):
79
+ url: str
80
+ threshold: float = 0.7
81
+
82
+ class PredictionResponse(BaseModel):
83
+ is_felidae: bool
84
+ predicted_class: Optional[str] = None
85
+ confidence: float
86
+ all_classes: List[Dict[str, Any]]
87
+ message: Optional[str] = None
88
+
89
+ class ClassesResponse(BaseModel):
90
+ classes: List[str]
91
+
92
+ # Load model
93
+ try:
94
+ logger.info(f"Loading model from {model_path}")
95
+ model = load_model(model_path)
96
+ logger.info("Model loaded successfully")
97
+ except Exception as e:
98
+ logger.error(f"Error loading model: {e}")
99
+ model = None
100
+
101
+ # Optimized prediction function
102
+ @tf.function
103
+ def predict_image(img_array):
104
+ return model(img_array)
105
+
106
+ def preprocess_image(img):
107
+ """Preprocess image for the model"""
108
+ img = img.resize((224, 224)) # Resize image to match model input size
109
+ img_array = np.array(img)
110
+ img_array = img_array / 255.0 # Normalize
111
+ img_array = np.expand_dims(img_array, axis=0) # Add batch dimension
112
+ return img_array
113
+
114
+ # def get_image_from_url(url):
115
+ # """Get image from URL"""
116
+ # response = requests.get(url)
117
+ # return Image.open(BytesIO(response.content))
118
+
119
+ def get_image_from_url(url):
120
+ """Get image from URL with better error handling"""
121
+ try:
122
+ # Tambahkan headers untuk menghindari blocking
123
+ headers = {
124
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
125
+ }
126
+
127
+ # Request dengan timeout
128
+ response = requests.get(url, headers=headers, timeout=30)
129
+ response.raise_for_status() # Raise exception untuk HTTP errors
130
+
131
+ # Validasi content type
132
+ content_type = response.headers.get('content-type', '').lower()
133
+ if content_type and not any(img_type in content_type for img_type in ['image', 'jpeg', 'jpg', 'png', 'webp', 'gif']):
134
+ logger.warning(f"Content type {content_type} might not be an image, but proceeding")
135
+
136
+ # Validasi ukuran response
137
+ if len(response.content) == 0:
138
+ raise ValueError("Empty response from URL")
139
+
140
+ # Log informasi
141
+ logger.info(f"Downloaded image from URL: {url}, size: {len(response.content)} bytes, content_type: {content_type}")
142
+
143
+ # Buat BytesIO object dan reset posisi
144
+ byte_stream = BytesIO(response.content)
145
+ byte_stream.seek(0)
146
+
147
+ # Coba buka gambar
148
+ img = Image.open(byte_stream)
149
+
150
+ # Konversi ke RGB jika perlu
151
+ if img.mode not in ('RGB', 'L'):
152
+ img = img.convert('RGB')
153
+
154
+ # Verifikasi bahwa gambar bisa di-load
155
+ img.load()
156
+
157
+ return img
158
+
159
+ except requests.exceptions.RequestException as e:
160
+ logger.error(f"Error downloading image from URL {url}: {e}")
161
+ raise ValueError(f"Cannot download image from URL: {str(e)}")
162
+ except Exception as e:
163
+ logger.error(f"Error processing image from URL {url}: {e}")
164
+ raise ValueError(f"Cannot process image from URL: {str(e)}")
165
+
166
+
167
+ def get_image_from_file(file_bytes):
168
+ """Get image from URL"""
169
+ return Image.open(BytesIO(file_bytes))
170
+
171
+
172
+ def classify_image(img, threshold=0.7):
173
+ """Classify image and return prediction results"""
174
+ if model is None:
175
+ logger.error("Model not available")
176
+ raise HTTPException(status_code=500, detail="Model not available")
177
+
178
+ try:
179
+ # Preprocess image
180
+ img_array = preprocess_image(img)
181
+
182
+ # Predict
183
+ predictions = predict_image(img_array)
184
+ predictions_np = predictions.numpy()[0]
185
+
186
+ # Results for all classes
187
+ class_results = []
188
+ for i, class_name in enumerate(class_names):
189
+ class_prob = float(predictions_np[i] * 100)
190
+ class_results.append({
191
+ "class": class_name.replace('_', ' ').capitalize(),
192
+ "probability": round(class_prob, 2)
193
+ })
194
+
195
+ # Sort by highest probability
196
+ class_results.sort(key=lambda x: x["probability"], reverse=True)
197
+
198
+ # Class with highest probability
199
+ predicted_class_index = np.argmax(predictions_np)
200
+ predicted_class = class_names[predicted_class_index]
201
+ predicted_prob = float(np.max(predictions_np))
202
+
203
+ # Check threshold
204
+ if predicted_prob < threshold:
205
+ return {
206
+ "is_felidae": False,
207
+ "message": "This animal is not from the Felidae family",
208
+ "confidence": round(predicted_prob * 100, 2),
209
+ "all_classes": class_results
210
+ }
211
+
212
+ return {
213
+ "is_felidae": True,
214
+ "predicted_class": predicted_class.replace('_', ' ').capitalize(),
215
+ "confidence": round(predicted_prob * 100, 2),
216
+ "all_classes": class_results
217
+ }
218
+
219
+ except Exception as e:
220
+ logger.error(f"Error in classification: {e}")
221
+ raise HTTPException(status_code=500, detail=str(e))
222
+
223
+ @app.get("/health", response_model=Dict[str, str])
224
+ async def health_check():
225
+ """Endpoint for health check"""
226
+ if model is None:
227
+ return JSONResponse(
228
+ status_code=503,
229
+ content={"status": "error", "message": "Model not available"}
230
+ )
231
+ return {"status": "ok", "message": "API running normally"}
232
+
233
+ #@app.post("/predict/url", response_model=PredictionResponse)
234
+ #async def predict_from_url(request: UrlRequest):
235
+ # """Endpoint for prediction from image URL"""
236
+ # try:
237
+ # img = get_image_from_url(request.url)
238
+ # result = classify_image(img, request.threshold)
239
+ # return result
240
+ # except Exception as e:
241
+ # logger.error(f"Error processing URL: {e}")
242
+ # raise HTTPException(status_code=500, detail=str(e))
243
+
244
+ @app.post("/predict/url", response_model=PredictionResponse)
245
+ async def predict_from_url(request: UrlRequest):
246
+ """Endpoint for prediction from image URL"""
247
+ try:
248
+ # Validasi URL
249
+ if not request.url or not request.url.strip():
250
+ raise HTTPException(status_code=400, detail="URL cannot be empty")
251
+
252
+ # Validasi format URL
253
+ if not (request.url.startswith('http://') or request.url.startswith('https://')):
254
+ raise HTTPException(status_code=400, detail="URL must start with http:// or https://")
255
+
256
+ logger.info(f"Processing image from URL: {request.url}")
257
+
258
+ try:
259
+ img = get_image_from_url(request.url)
260
+ except ValueError as ve:
261
+ raise HTTPException(
262
+ status_code=400,
263
+ detail=f"Invalid image URL: {str(ve)}"
264
+ )
265
+ except Exception as e:
266
+ logger.error(f"Unexpected error processing URL: {e}")
267
+ raise HTTPException(
268
+ status_code=400,
269
+ detail="Cannot process the image from URL. Please ensure it's a valid image URL"
270
+ )
271
+
272
+ result = classify_image(img, request.threshold)
273
+ return result
274
+
275
+ except HTTPException:
276
+ # Re-raise HTTP exceptions
277
+ raise
278
+ except Exception as e:
279
+ logger.error(f"Unexpected error in predict_from_url: {e}")
280
+ raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
281
+
282
+ # @app.post("/predict/upload", response_model=PredictionResponse)
283
+ # async def predict_from_upload(
284
+ # image: UploadFile = File(...),
285
+ # threshold: float = Form(0.7)
286
+ # ):
287
+ # """Endpoint for prediction from uploaded file"""
288
+ # try:
289
+ # img = get_image_from_file(await image.read())
290
+ # result = classify_image(img, threshold)
291
+ # return result
292
+ # except Exception as e:
293
+ # logger.error(f"Error processing uploaded file: {e}")
294
+ # raise HTTPException(status_code=500, detail=str(e))
295
+
296
+
297
+ @app.post("/predict/upload", response_model=PredictionResponse)
298
+ async def predict_from_upload(
299
+ image: UploadFile = File(...),
300
+ threshold: float = Form(0.7)
301
+ ):
302
+ """Endpoint for prediction from uploaded file"""
303
+ try:
304
+ # Validasi format file
305
+ allowed_types = ["image/png", "image/jpeg", "image/jpg", "image/webp"]
306
+ if image.content_type not in allowed_types:
307
+ raise HTTPException(
308
+ status_code=400,
309
+ detail=f"Unsupported file type: {image.content_type}. Supported types: PNG, JPG, JPEG, WEBP"
310
+ )
311
+
312
+ # Baca dan proses gambar
313
+ #contents = await image.read()
314
+ #img = Image.open(BytesIO(contents))
315
+ img = get_image_from_file(await image.read())
316
+
317
+ # Jalankan prediksi
318
+ result = classify_image(img, threshold)
319
+ return result
320
+
321
+ except Exception as e:
322
+ logger.error(f"Error processing uploaded file: {e}")
323
+ raise HTTPException(status_code=500, detail=str(e))
324
+
325
+
326
+
327
+ @app.get("/classes", response_model=ClassesResponse)
328
+ async def get_classes():
329
+ """Endpoint to get list of available classes"""
330
+ formatted_classes = [name.replace('_', ' ').capitalize() for name in class_names]
331
+ return {"classes": formatted_classes}
332
+
333
+ if __name__ == '__main__':
334
+ port = int(os.environ.get('PORT', 8000))
335
+ uvicorn.run("main:app", host="0.0.0.0", port=port, reload=False)