File size: 7,271 Bytes
c018f5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# main.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import pandas as pd
import numpy as np
import joblib, json, os
from math import radians, cos, sin, asin, sqrt

# =========================
# تحميل الموديل والـ artifacts
# =========================
MODEL_DIR = os.path.join(os.path.dirname(__file__), "..", "models")
MODEL_PATH = os.path.join(MODEL_DIR, "model.pkl")
PREPROCESSOR_PATH = os.path.join(MODEL_DIR, "preprocessor.pkl")
FEATURES_PATH = os.path.join(MODEL_DIR, "feature_names.json")

model = joblib.load(MODEL_PATH)
preprocessor = joblib.load(PREPROCESSOR_PATH)
with open(FEATURES_PATH) as f:
    feature_names = json.load(f)

# =========================
# تحميل البيانات من CSV
# =========================
DATA_PATH = os.path.join(os.path.dirname(__file__), "..", "data", "features_data.csv")
features_df = pd.read_csv(DATA_PATH)

# =========================
# Feature Engineering
# =========================
def get_season(month: int) -> str:
    if month in [12, 1, 2]:
        return "Winter"
    elif month in [3, 4, 5]:
        return "Spring"
    elif month in [6, 7, 8]:
        return "Summer"
    return "Autumn"

def feature_engineering(df: pd.DataFrame) -> pd.DataFrame:
    df = df.copy()
    df["season"] = df["month"].apply(get_season)

    soil_total = df[["sand", "silt", "clay"]].sum(axis=1).replace(0, np.nan)
    df["sand_ratio"] = (df["sand"] / soil_total).fillna(0.0)
    df["silt_ratio"] = (df["silt"] / soil_total).fillna(0.0)
    df["clay_ratio"] = (df["clay"] / soil_total).fillna(0.0)

    df["soc_cec"] = df["soc"] * df["cec"]

    return df

# =========================
# Input Schema
# =========================
class MapClick(BaseModel):
    lat: float
    lon: float

# =========================
# Helpers
# =========================
def haversine(lat1, lon1, lat2, lon2):
    """حساب المسافة بين نقطتين (كم)"""
    R = 6371.0
    dlat = radians(lat2 - lat1)
    dlon = radians(lon2 - lon1)
    a = sin(dlat/2)**2 + cos(radians(lat1)) * cos(radians(lat2)) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a))
    return R * c

def fetch_nearest_features(lat: float, lon: float, max_km=15):
    """إرجاع أقرب نقطة من CSV"""
    best = None
    best_dist = 1e9

    for _, row in features_df.iterrows():
        d = haversine(lat, lon, row["latitude"], row["longitude"])
        if d < best_dist:
            best_dist = d
            best = row.to_dict()
            best["distance_km"] = d

    if best and best_dist <= max_km:
        return best
    return None

def classify_desertification(ndvi: float) -> str:
    if ndvi < 0.2:
        return "شديد"
    elif ndvi < 0.5:
        return "متوسط"
    return "منخفض"

# =========================
# توصيات ديناميكية
# =========================
def recommend_actions(severity: str, row: dict) -> list:
    recs = []

    if severity == "شديد":
        recs.extend([
            "التشجير وزراعة أحزمة خضراء",
            "استخدام تقنيات حصاد المياه",
            "منع الرعي الجائر وتنظيمه",
            "تطبيق أنظمة ري حديثة (تنقيط/رش)"
        ])
    elif severity == "متوسط":
        recs.extend([
            "إدارة التربة وتحسين خصوبتها (إضافة مواد عضوية)",
            "تنويع المحاصيل واستخدام محاصيل تغطية",
            "تحسين ممارسات الري",
            "الحد من إزالة الغطاء النباتي"
        ])
    else:  # منخفض
        recs.extend([
            "المحافظة على الغطاء النباتي الحالي",
            "المتابعة والرصد الدوري للتغيرات",
            "التوسع في الزراعة المستدامة",
            "التوعية المجتمعية لمنع الممارسات الضارة"
        ])

    # توصيات إضافية مبنية على الـ features
    rainfall = row.get("tp_m", 0)
    temp = row.get("t2m_c", 0)
    sand_ratio = row.get("sand_ratio", 0)
    clay_ratio = row.get("clay_ratio", 0)
    soc_cec = row.get("soc_cec", 0)

    if rainfall > 200 and sand_ratio > 0.6 and severity == "منخفض":
        recs.append("تشجيع الزراعات الاقتصادية سريعة النمو لاستغلال الموارد المائية")

    if rainfall < 50 and clay_ratio > 0.4 and severity != "منخفض":
        recs.append("إنشاء سدود صغيرة أو خزانات لتخزين مياه الأمطار")

    if temp > 35 and severity == "شديد":
        recs.append("زراعة محاصيل مقاومة للجفاف والحرارة (مثل الشعير والدخن)")

    if sand_ratio > 0.7:
        recs.append("إضافة مواد عضوية أو طينية للتربة الرملية لزيادة قدرتها على الاحتفاظ بالماء")

    if clay_ratio > 0.5:
        recs.append("تجهيز أنظمة صرف زراعي لمنع تملح التربة الثقيلة")

    if soc_cec < 0.2 and severity != "منخفض":
        recs.append("إضافة محسنات للتربة (كمبوست/سماد عضوي) لرفع خصوبة التربة")

    return recs

# =========================
# FastAPI app
# =========================
app = FastAPI(title="Desertification Prediction API")

# ----- Root route -----
@app.get("/")
def root():
    return {"message": "Welcome to the Desertification Prediction API. Use /predict-by-location to get predictions."}

# ----- Prediction route -----
@app.post("/predict-by-location")
def predict_by_location(click: MapClick):
    try:
        # 1. دور على أقرب نقطة من CSV
        row = fetch_nearest_features(click.lat, click.lon, max_km=15)
        if not row:
            raise HTTPException(status_code=404, detail="لا توجد بيانات قريبة لهذه الإحداثيات")

        # 2. حوّل النقطة DataFrame
        df = pd.DataFrame([row])

        # 3. Feature engineering
        df = feature_engineering(df)

        # 4. تأكد إن الأعمدة مرتبة حسب feature_names
        df = df[feature_names]

        # 5. Prediction
        X_trans = preprocessor.transform(df)
        ndvi_pred = float(model.predict(X_trans)[0])

        # 6. تقييم التصحر + توصيات
        severity = classify_desertification(ndvi_pred)
        recs = recommend_actions(severity, df.iloc[0].to_dict())

        return {
            "clicked_point": {"lat": click.lat, "lon": click.lon},
            "nearest_data_point": {
                "lat": row["latitude"],
                "lon": row["longitude"],
                "distance_km": round(row["distance_km"], 2)
            },
            "predicted_ndvi": round(ndvi_pred, 3),
            "desertification_level": severity,
            "recommendations": recs
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))