Bitirme commited on
Commit
fc741f1
1 Parent(s): 49a8630

düzenleme

Browse files
Files changed (1) hide show
  1. api.py +57 -60
api.py CHANGED
@@ -1,76 +1,73 @@
1
- from fastapi import FastAPI, File, UploadFile, HTTPException
2
- import numpy as np
3
- from io import BytesIO
4
- from PIL import Image, UnidentifiedImageError
5
  import tensorflow as tf
6
- from fastapi.middleware.cors import CORSMiddleware
 
 
 
7
 
8
  app = FastAPI()
9
 
10
- # CORS yapılandırması
11
- origins = ["*"]
12
-
13
- app.add_middleware(
14
- CORSMiddleware,
15
- allow_origins=origins,
16
- allow_credentials=True,
17
- allow_methods=["*"],
18
- allow_headers=["*"],
19
- )
20
 
21
- MODEL = tf.keras.models.load_model("CLAHE_ODIR-ORJ-512_inception_v3.h5")
 
 
 
 
 
 
 
22
 
23
- # Sınıf isimleri
24
- class_names = [
25
- 'Age related Macular Degeneration', 'Cataract', 'Diabetes', 'Glaucoma',
26
- 'Hypertension', 'Normal', 'Others', 'Pathological Myopia'
27
- ]
28
 
29
- @app.get("/ping")
30
- async def ping():
31
- return {"message": "Hello, I am alive"}
 
32
 
33
- def read_file_as_image(data) -> np.ndarray:
34
- try:
35
- image = Image.open(BytesIO(data))
36
- return np.array(image)
37
- except UnidentifiedImageError:
38
- raise HTTPException(status_code=400, detail="Invalid image format")
39
- except Exception as e:
40
- raise HTTPException(status_code=400, detail=f"Image processing error: {str(e)}")
41
 
 
 
 
 
 
 
42
 
43
- @app.post("/predict")
44
- async def predict(file: UploadFile = File(...)):
45
- image_data = await file.read()
46
 
47
- # Dosya tipini kontrol et
48
- if file.content_type not in ["image/jpeg", "image/png", "image/jpg"]:
49
- raise HTTPException(status_code=400, detail="Invalid file type")
50
 
51
- # Dosya boyutunu kontrol et (örneğin, 5MB'den büyük dosyaları reddet)
52
- max_file_size = 5 * 1024 * 1024 # 5MB
53
- if len(image_data) > max_file_size:
54
- raise HTTPException(status_code=400, detail="File size exceeds limit")
55
 
56
- try:
57
- image = read_file_as_image(image_data)
58
- except HTTPException as e:
59
- return e
60
 
61
- # Görüntüyü modelin beklediği boyuta getirme
62
- image = tf.image.resize(image, (299, 299)) # InceptionV3 için 299x299 olmalı
63
- # Görüntüyü normalize etme
64
- image = tf.cast(image, tf.float32) / 255.0
65
- # Batch haline getirme
66
- img_batch = np.expand_dims(image, 0)
67
 
68
- # Model üzerinde tahmin yapma
69
- predictions = MODEL.predict(img_batch)
70
- predicted_class = class_names[np.argmax(predictions[0])]
71
- confidence = np.max(predictions[0])
 
72
 
73
- return {
74
- 'class': predicted_class,
75
- 'confidence': float(confidence)
76
- }
 
1
+ import cv2
 
 
 
2
  import tensorflow as tf
3
+ import numpy as np
4
+ from fastapi import FastAPI, UploadFile, File
5
+ from pydantic import BaseModel
6
+ from huggingface_hub import from_pretrained_keras
7
 
8
  app = FastAPI()
9
 
10
+ def load_ben_color(image, sigmaX=10):
11
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
12
+ image = cv2.resize(image, (224, 224))
13
+ image = cv2.addWeighted(image, 4, cv2.GaussianBlur(image, (0, 0), sigmaX), -4, 128)
14
+ return image
 
 
 
 
 
15
 
16
+ def clahe(image):
17
+ clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
18
+ r, g, b = cv2.split(image)
19
+ r = clahe.apply(r)
20
+ g = clahe.apply(g)
21
+ b = clahe.apply(b)
22
+ result = cv2.merge((r, g, b))
23
+ return result
24
 
25
+ def filter1(image):
26
+ image = load_ben_color(image)
27
+ return image
 
 
28
 
29
+ def filter2(image):
30
+ image = clahe(image)
31
+ image = cv2.resize(image, (224, 224))
32
+ return image
33
 
34
+ def predict(image, model, filter_func):
35
+ model_image = filter_func(image)
36
+ model_image = np.array([model_image], dtype=np.float32) / 255.0
37
+ predictions = model(tf.constant(model_image))
38
+ return predictions.numpy()
 
 
 
39
 
40
+ def result(predictions):
41
+ class_labels = ["Age related Macular Degeneration", "Cataract", "Diabetes", "Glaucoma", "Hypertension", "Normal", "Others", "Pathological Myopia"]
42
+ predictions = np.array(predictions)
43
+ predictions = predictions.tolist()[0]
44
+ predictions_index = np.argmax(predictions)
45
+ return class_labels[predictions_index]
46
 
47
+ # Model tanımlamaları
48
+ models_names = ["ODIR-B-2K-5Class-LastTrain-Xception", "ODIR-B-2K-6Class-LastTrain-Xception"]
49
+ model_paths = ["ODIR-B-2K-5Class-LastTrain-Xception", "ODIR-B-2K-6Class-LastTrain-Xception"]
50
 
51
+ filters = [filter1, filter2] # İhtiyacınıza göre filtre fonksiyonları burada tanımlandı
 
 
52
 
53
+ models = []
54
+ for model_path in model_paths:
55
+ model = tf.saved_model.load(model_path)
56
+ models.append(model)
57
 
58
+ class PredictionResponse(BaseModel):
59
+ predictions: dict
 
 
60
 
61
+ @app.post("/predict", response_model=PredictionResponse)
62
+ async def predict_endpoint(file: UploadFile = File(...)):
63
+ contents = await file.read()
64
+ nparr = np.frombuffer(contents, np.uint8)
65
+ image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
 
66
 
67
+ result_json = {}
68
+ for i in range(len(models)):
69
+ model = models[i]
70
+ prediction = predict(image, model, filters[i])
71
+ result_json[models_names[i]] = result(prediction)
72
 
73
+ return {"predictions": result_json}