| |
| import requests |
| import os |
| from fastapi import HTTPException |
| from IPython.display import display |
| import tensorflow |
| import numpy as np |
| from numpy.linalg import norm |
| from tensorflow.keras.preprocessing import image |
| from tensorflow.keras.layers import GlobalMaxPooling2D |
| from tensorflow.keras.applications.efficientnet_v2 import preprocess_input as EFpreprocess_input |
| from fastapi import FastAPI, File, UploadFile |
| from fastapi.responses import JSONResponse |
| from PIL import Image |
| import numpy as np |
| import io |
| from tensorflow.keras.models import load_model |
| from tensorflow.keras.preprocessing.image import img_to_array |
| import cv2 |
| import pandas as pd |
| import tensorflow as tf |
| from numpy.linalg import norm |
| from tensorflow.keras.preprocessing import image |
| from tensorflow.keras.layers import GlobalMaxPooling2D |
| from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input as REpreprocess_input |
| from sklearn.neighbors import NearestNeighbors |
| import pickle |
| from keras.models import load_model |
| loaded_model = load_model("weights-improvement-11-0.98.keras") |
| |
| model = ResNet50(weights='imagenet',include_top=False,input_shape=(224,224,3)) |
| model.trainable = False |
|
|
| model = tensorflow.keras.Sequential([ |
| model, |
| GlobalMaxPooling2D() |
| ]) |
|
|
| |
| image_feature_list = pickle.load(open('embeddings.pkl', 'rb')) |
| image_ids = pickle.load(open('filenames.pkl', 'rb')) |
| |
| img_size = (224, 224) |
| |
| benign_tumors = [ |
| "Astrocitoma", |
| "Ganglioglioma", |
| "Granuloma", |
| "Meningioma", |
| "Neurocitoma", |
| "Papiloma", |
| "Schwannoma", |
| "Tuberculoma", |
| ] |
|
|
| |
| malignant_tumors = [ |
| "Carcinoma", |
| "Ependimoma", |
| "Germinoma", |
| "Glioblastoma", |
| "Meduloblastoma", |
| "Oligodendroglioma" |
| ] |
|
|
|
|
| class_names = ['Astrocitoma', 'Carcinoma', 'Ependimoma', 'Ganglioglioma', 'Germinoma', 'Glioblastoma', 'Granuloma', 'Meduloblastoma', 'Meningioma', 'Neurocitoma', 'Oligodendroglioma', 'Papiloma', 'Schwannoma', 'Tuberculoma', '_NORMAL'] |
| |
| def preprocess_image(file_bytes: bytes) -> np.ndarray: |
| """تحويل الصورة إلى مصفوفة بعد تطبيق preprocessing الخاص بـ EfficientNetV2""" |
| image = Image.open(io.BytesIO(file_bytes)).convert("RGB") |
| image = image.resize(img_size) |
| image_array = img_to_array(image) |
| image_array = np.expand_dims(image_array, axis=0) |
| image_array = EFpreprocess_input(image_array) |
| return image_array |
|
|
| |
| def predict_disease(image_array: np.ndarray) -> dict: |
| """تنبؤ بالمرض والـ confidence""" |
| predictions = loaded_model.predict(image_array) |
| predicted_class = np.argmax(predictions[0]) |
| label = class_names[predicted_class] |
| if label in benign_tumors: |
| predicted_type = "Benign tumor" |
| elif label in malignant_tumors: |
| predicted_type = "Malignant tumor" |
| else: |
| predicted_type = "Normal" |
| |
| confidence = float(np.max(predictions[0])) |
| return { |
| "prediction": class_names[predicted_class], |
| "predicted_type": predicted_type, |
| "confidence": round(confidence * 100, 2) |
| } |
| |
| |
| |
| def extract_features(img_array): |
| |
| preprocessed_img = REpreprocess_input(img_array) |
| result = model.predict(preprocessed_img).flatten() |
| normalized_result = result / norm(result) |
|
|
| return normalized_result |
|
|
|
|
| from sklearn.neighbors import NearestNeighbors |
|
|
| def check_similar_image(image_array, threshold=0.55): |
| """التحقق من الصور المتشابهة باستخدام NearestNeighbors والتشابه بين الصور.""" |
| |
| |
| features = extract_features(image_array) |
| |
| |
| knn = NearestNeighbors(n_neighbors=1, metric='euclidean') |
| knn.fit(image_feature_list) |
|
|
| |
| distances, indices = knn.kneighbors([features]) |
| |
| |
| distance = distances[0][0] |
| |
| |
| similarity = 1 / (1 + distance) |
| |
| |
| if similarity >= threshold: |
| return {"similarity_score": similarity, "is_similar": True} |
| else: |
| return {"similarity_score": similarity, "is_similar": False} |