Spaces:
Runtime error
Runtime error
Update app.py
Browse files2 unmodified lines3456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354552 unmodified linesimport numpy as npfrom PIL import Image# Load the TFLite modelinterpreter = tf.lite.Interpreter(model_path="stool_model.tflite")interpreter.allocate_tensors()input_details = interpreter.get_input_details()output_details = interpreter.get_output_details()# Define label names (adjust if your model uses different ones)labels = ["bloody", "hard stool", "normal", "parasite", "watery"]def preprocess_image(img: Image.Image):img = img.convert("RGB").resize((128, 128))arr = np.asarray(img).astype(np.float32) / 255.0arr = np.expand_dims(arr, axis=0)return arrdef classify_image(image):try:img = image.convert("RGB")arr = np.asarray(img).astype(np.float32)brightness = arr.mean()contrast = arr.std()# ๐ง Simple sanity check for stool-like features (brownish tone + moderate contrast)# You can adjust these thresholds depending on your datasetif brightness > 220 or brightness < 20 or contrast < 25:return {"Not stool image": 1.0}# Normal prediction processinput_data = preprocess_image(image)interpreter.set_tensor(input_details[0]['index'], input_data)interpreter.invoke()output_data = interpreter.get_tensor(output_details[0]['index'])[0]results = {labels[i]: float(output_data[i]) for i in range(len(labels))}sorted_results = dict(sorted(results.items(), key=lambda x: x[1], reverse=True))return sorted_resultsexcept Exception as e:return {"error": str(e)}demo = gr.Interface(fn=classify_image,inputs=gr.Image(type="pil", label="Upload stool image"),outputs=gr.Label(num_top_classes=3, label="Predictions"),title="Stool Diagnosis Model",description="Upload a stool image for classification.")if __name__ == "__main__":2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980812 unmodified linesimport numpy as npfrom PIL import Image# ๐ง Load your TFLite modelinterpreter = tf.lite.Interpreter(model_path="stool_model.tflite")interpreter.allocate_tensors()input_details = interpreter.get_input_details()output_details = interpreter.get_output_details()# ๐ท๏ธ Define your classeslabels = ["bloody", "hard stool", "normal", "parasite", "watery"]# ๐งฉ Image preprocessingdef preprocess_image(img: Image.Image):img = img.convert("RGB").resize((128, 128))arr = np.asarray(img).astype(np.float32) / 255.0arr = np.expand_dims(arr, axis=0)return arr# ๐ซ Detect if the uploaded image is NOT a stool imagedef is_not_stool_image(image):arr = np.asarray(image.convert("RGB")).astype(np.float32)brightness = arr.mean()contrast = arr.std()avg_color = arr.mean(axis=(0, 1))# ๐ง Basic heuristic checks# These values are adjustable based on your datasetif brightness > 220 or brightness < 25:return True # too bright or darkif contrast < 25:return True # too flat / low textureif avg_color[0] > 180 and avg_color[1] < 80 and avg_color[2] < 80:return True # too redif avg_color[0] < 50 and avg_color[1] > 180:return True # too greenishif avg_color[2] > 200:return True # too blueishreturn False# ๐ง Classification functiondef classify_image(image):try:# ๐ซ Check if this is not stoolif is_not_stool_image(image):return {"Not stool image": 1.0}# โ Proceed with model predictioninput_data = preprocess_image(image)interpreter.set_tensor(input_details[0]['index'], input_data)interpreter.invoke()output_data = interpreter.get_tensor(output_details[0]['index'])[0]# Sort predictionsresults = {labels[i]: float(output_data[i]) for i in range(len(labels))}sorted_results = dict(sorted(results.items(), key=lambda x: x[1], reverse=True))# Extra sanity rule: if top score < 0.4, label as uncertaintop_label, top_score = list(sorted_results.items())[0]if top_score < 0.4:return {"Uncertain / unclear stool image": top_score}return sorted_resultsexcept Exception as e:return {"Error": str(e)}# ๐จ Gradio UIdemo = gr.Interface(fn=classify_image,inputs=gr.Image(type="pil", label="๐ธ Upload stool image"),outputs=gr.Label(num_top_classes=3, label="Predicted diagnosis"),title="๐พ Stool Diagnosis AI",description="Upload a stool image for analysis. The model predicts stool type or rejects unrelated photos.")if __name__ == "__main__":
app.py+43-17