etchmed/chicken_detection
0
1import streamlit as st2from ultralytics import YOLO3from PIL import Image4import tempfile5import os6from huggingface_hub import hf_hub_download7 8# إعدادات الموديل - عدّل هذه القيم حسب ريبو Hugging Face الخاص بك9HF_REPO_ID = os.getenv("HF_MODEL_REPO", "YOUR_USERNAME/chicken-detection-yolov8") # مثال: "medo123/chicken-detection-yolov8"10HF_MODEL_FILENAME = "best_chicken_model.pt"11LOCAL_MODEL_PATH = "best_chicken_model.pt"12 13@st.cache_resource14def load_model():15 """16 يحمّل الموديل من Hugging Face Hub أولاً، وإذا فشل يحاول من ملف محلي17 """18 try:19 # محاولة التحميل من Hugging Face Hub20 if HF_REPO_ID and HF_REPO_ID != "YOUR_USERNAME/chicken-detection-yolov8":21 st.info(f"📥 جاري تحميل الموديل من Hugging Face: {HF_REPO_ID}")22 model_path = hf_hub_download(23 repo_id=HF_REPO_ID,24 filename=HF_MODEL_FILENAME,25 cache_dir="models"26 )27 model = YOLO(model_path)28 st.success("✅ تم تحميل الموديل من Hugging Face بنجاح!")29 return model30 except Exception as e:31 st.warning(f"⚠️ فشل تحميل الموديل من Hugging Face: {e}")32 st.info("🔄 جاري المحاولة من ملف محلي...")33 34 # إذا فشل التحميل من Hugging Face، جرب الملف المحلي35 if os.path.exists(LOCAL_MODEL_PATH):36 model = YOLO(LOCAL_MODEL_PATH)37 st.success("✅ تم تحميل الموديل من ملف محلي!")38 return model39 else:40 st.error(f"❌ لم يتم العثور على الموديل في: {LOCAL_MODEL_PATH}")41 st.info("💡 تأكد من رفع ملف best_chicken_model.pt إلى Space أو ضبط HF_REPO_ID")42 raise FileNotFoundError(f"Model not found: {LOCAL_MODEL_PATH}")43 44model = load_model()45 46st.title("🐓 كشف صحة الدجاج من الصورة")47st.write("ارفع صورة لدجاجة، وسنحدد إذا كانت سليمة أو مريضة.")48 49uploaded = st.file_uploader("اختر صورة...", type=["jpg", "jpeg", "png"])50 51if uploaded:52 image = Image.open(uploaded).convert("RGB")53 st.image(image, caption="الصورة المرفوعة", use_column_width=True)54 55 if st.button("🔍 تحليل الصورة"):56 with st.spinner("جاري التحليل..."):57 # حفظ الصورة مؤقتًا58 with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:59 image.save(tmp.name)60 temp_path = tmp.name61 62 try:63 # تشغيل التنبؤ64 results = model.predict(65 source=temp_path,66 conf=0.25, # حد الثقة67 imgsz=640,68 verbose=False69 )70 71 result = results[0]72 73 # رسم البوكسات على الصورة74 plotted = result.plot()75 plotted_image = Image.fromarray(plotted)76 77 st.subheader("📌 الصورة بعد الكشف")78 st.image(plotted_image, caption="الصورة مع الكشف", use_column_width=True)79 80 # عرض النتائج81 if len(result.boxes) > 0:82 st.subheader("📊 النتائج")83 84 # جمع الإحصائيات لكل فئة85 class_counts = {}86 class_confidences = {}87 88 for box in result.boxes:89 cls_id = int(box.cls.item())90 conf = float(box.conf.item())91 label = result.names[cls_id]92 93 if label not in class_counts:94 class_counts[label] = 095 class_confidences[label] = []96 class_counts[label] += 197 class_confidences[label].append(conf)98 99 # عرض النتائج100 for label, count in class_counts.items():101 avg_conf = sum(class_confidences[label]) / len(class_confidences[label])102 st.success(f"🎯 **{label}**: {count} كائن (ثقة متوسطة: {avg_conf:.2%})")103 104 # عرض أعلى ثقة105 max_conf = max([float(box.conf.item()) for box in result.boxes])106 st.info(f"✨ أعلى نسبة ثقة: {max_conf:.2%}")107 else:108 st.warning("⚠️ لم يتم اكتشاف أي دجاج في الصورة. جرب صورة أخرى.")109 110 except Exception as e:111 st.error(f"❌ حدث خطأ أثناء التحليل: {e}")112 finally:113 # حذف الملف المؤقت114 if os.path.exists(temp_path):115 os.unlink(temp_path)