Spaces:
Runtime error
Runtime error
Update app.py
Browse files12345675 unmodified lines131415161718194 unmodified lines24252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101import gradio as grimport tensorflow as tfimport numpy as npfrom PIL import Image# 🧠 Load your TFLite modelinterpreter = tf.lite.Interpreter(model_path="stool_model.tflite")5 unmodified lines# 🏷️ Labels of your stool modellabels = ["bloody", "hard stool", "normal", "parasite", "watery"]# 💬 Diagnosis summaries for each labeldiagnosis_advice = {"bloody": "Possible hemorrhagic gastroenteritis. ⚠️ Visit a vet immediately as it may indicate internal bleeding or infection.","hard stool": "Your pet may be constipated. 💧 Encourage hydration and increase dietary fiber intake.",4 unmodified lines"Uncertain / unclear stool image": "⚠️ The image is unclear or confidence is low. Try retaking the photo in better lighting."}# 🧩 Preprocess image for TFLitedef 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# 🚫 Detection filter for non-stool imagesdef 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))if brightness > 220 or brightness < 25:return True # too bright or too darkif contrast < 25:return True # too flat / no textureif avg_color[0] > 180 and avg_color[1] < 80 and avg_color[2] < 80:return True # too reddishif avg_color[1] > 200 and avg_color[0] < 100:return True # too greenishif avg_color[2] > 200:return True # too bluishreturn False# 🧠 Main classification logicdef classify_image(image):try:# Step 1: Validate stool imageif is_not_stool_image(image):return {"Not stool image": 1.0}, diagnosis_advice["Not stool image"]# Step 2: Run TFLite modelinput_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]# Step 3: Sort predictions by confidenceresults = {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))top_label, top_score = list(sorted_results.items())[0]# Step 4: Handle low confidenceif top_score < 0.4:return {"Uncertain / unclear stool image": top_score}, diagnosis_advice["Uncertain / unclear stool image"]# Step 5: Add readable confidence percentagesformatted_results = {f"{label} ({score * 100:.2f}%)": score for label, score in sorted_results.items()}# Step 6: Return label + human diagnosisadvice = diagnosis_advice.get(top_label, "No advice available for this diagnosis.")return formatted_results, adviceexcept Exception as e:return {"Error": str(e)}, f"⚠️ Error encountered: {str(e)}"# 🎨 Gradio Interfacedemo = gr.Interface(fn=classify_image,inputs=gr.Image(type="pil", label="📸 Upload stool image"),outputs=[gr.Label(num_top_classes=3, label="Predicted Diagnosis & Confidence"),gr.Textbox(label="💬 Diagnosis Summary", lines=3),],title="🐾 Pet Stool Diagnosis AI (with Confidence & Advice)",description=("Upload a stool image to get an AI-based diagnosis with confidence scores and health advice. ""This tool checks image validity, identifies stool condition, and provides next-step guidance."),)123456785 unmodified lines141516171819204 unmodified lines252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119import gradio as grimport tensorflow as tfimport numpy as npfrom PIL import Image, ImageStatimport cv2# 🧠 Load your TFLite modelinterpreter = tf.lite.Interpreter(model_path="stool_model.tflite")5 unmodified lines# 🏷️ Labels of your stool modellabels = ["bloody", "hard stool", "normal", "parasite", "watery"]# 💬 Diagnosis summariesdiagnosis_advice = {"bloody": "Possible hemorrhagic gastroenteritis. ⚠️ Visit a vet immediately as it may indicate internal bleeding or infection.","hard stool": "Your pet may be constipated. 💧 Encourage hydration and increase dietary fiber intake.",4 unmodified lines"Uncertain / unclear stool image": "⚠️ The image is unclear or confidence is low. Try retaking the photo in better lighting."}# 🧩 Image preprocessing for the TFLite modeldef 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# 🚫 Strict non-stool detectiondef is_not_stool_image(image):"""Multi-layer detection for non-stool photos"""np_img = np.array(image.convert("RGB"))stat = ImageStat.Stat(image)# 🧠 1️⃣ Brightness & contrast checksbrightness = stat.mean[0]contrast = stat.stddev[0]if brightness > 210 or brightness < 30:return True # too bright or darkif contrast < 25:return True # too flat / no texture# 🧠 2️⃣ Dominant color detection (stool tends to be brownish)avg_color = np.mean(np_img.reshape(-1, 3), axis=0)r, g, b = avg_color# Detect unnatural colors (too blue, green, or red)if (r > 200 and g < 100 and b < 100) or (g > 180 and r < 100) or (b > 180):return True# 🧠 3️⃣ Color tone validation — real stool is usually brown (RGB ratios)brownish_score = (r * 0.5 + g * 0.3 + b * 0.2)grayish_score = abs(r - g) + abs(g - b)if brownish_score < 60 or grayish_score > 80:return True# 🧠 4️⃣ Texture detection with OpenCVgray = cv2.cvtColor(np_img, cv2.COLOR_RGB2GRAY)lap_var = cv2.Laplacian(gray, cv2.CV_64F).var() # blur measureif lap_var < 50:return True # image too smooth or blurry (likely not stool)return False # passes all checks, likely stool# 🧠 Main classifierdef classify_image(image):try:# 🧩 Step 1: Reject non-stool images firstif is_not_stool_image(image):return {"Not stool image": 1.0}, diagnosis_advice["Not stool image"]# 🧩 Step 2: Run TFLite modelinput_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]# 🧩 Step 3: 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))top_label, top_score = list(sorted_results.items())[0]# 🧩 Step 4: Handle low-confidence predictionsif top_score < 0.45:return {"Uncertain / unclear stool image": top_score}, diagnosis_advice["Uncertain / unclear stool image"]# 🧩 Step 5: Add readable confidence %formatted_results = {f"{label} ({score * 100:.2f}%)": score for label, score in sorted_results.items()}# 🩺 Step 6: Generate human-readable adviceadvice = diagnosis_advice.get(top_label, "No advice available for this diagnosis.")return formatted_results, adviceexcept Exception as e:return {"Error": 0.0}, f"⚠️ Error: {str(e)}"# 🎨 Gradio Interfacedemo = gr.Interface(fn=classify_image,inputs=gr.Image(type="pil", label="📸 Upload Stool Image"),outputs=[gr.Label(num_top_classes=3, label="Predicted Diagnosis & Confidence"),gr.Textbox(label="💬 Diagnosis Summary", lines=3),],title="🐾 Pet Stool Diagnosis AI (Strict Validation)",description=("Upload a stool image for AI-based diagnosis. The system will first verify if it's a real stool photo, ""then predict the stool type and give a simple health summary."),)
app.py+50-32