Spaces:
Sleeping

Codeitnow commited on
Commit
03ecd82
·
verified ·
1 Parent(s): e7c56f3

Upload 10 files

Browse files
ml/__init__.py ADDED
File without changes
ml/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (141 Bytes). View file
 
ml/__pycache__/clusterer.cpython-312.pyc ADDED
Binary file (6.18 kB). View file
 
ml/__pycache__/embedder.cpython-312.pyc ADDED
Binary file (3.3 kB). View file
 
ml/__pycache__/matcher.cpython-312.pyc ADDED
Binary file (13.1 kB). View file
 
ml/__pycache__/scorer.cpython-312.pyc ADDED
Binary file (7.3 kB). View file
 
ml/clusterer.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ clusterer.py – UMAP + HDBSCAN geo-semantic clustering
3
+ """
4
+ from __future__ import annotations
5
+ import logging
6
+ import math
7
+ import numpy as np
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+ GEO_WEIGHT = 0.55 # weight for geographic component in composite space
12
+ SEM_WEIGHT = 0.45 # weight for semantic embedding component
13
+
14
+
15
+ def _haversine_km(lat1: float, lng1: float, lat2: float, lng2: float) -> float:
16
+ """Straight-line distance in km."""
17
+ R = 6371.0
18
+ dlat = math.radians(lat2 - lat1)
19
+ dlng = math.radians(lng2 - lng1)
20
+ a = math.sin(dlat/2)**2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlng/2)**2
21
+ return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
22
+
23
+
24
+ def road_distance_matrix(origins: list[tuple[float,float]], destinations: list[tuple[float,float]]) -> list[list[float]]:
25
+ """Returns distance matrix in km using Haversine (free, no API key required)."""
26
+ return [[_haversine_km(o[0], o[1], d[0], d[1]) for d in destinations] for o in origins]
27
+
28
+ # Alias used in main.py
29
+ geo_distance_matrix_api = road_distance_matrix
30
+
31
+
32
+ def _normalise(arr: np.ndarray) -> np.ndarray:
33
+ """Min-max normalise to [0, 1]."""
34
+ mn, mx = arr.min(axis=0), arr.max(axis=0)
35
+ rng = mx - mn
36
+ rng[rng == 0] = 1
37
+ return (arr - mn) / rng
38
+
39
+
40
+ def cluster_geo_semantic(
41
+ lat_list: list[float],
42
+ lng_list: list[float],
43
+ embeddings: list[list[float]],
44
+ min_cluster_size: int = 2,
45
+ ) -> list[int]:
46
+ """
47
+ Geo-semantic clustering:
48
+ 1. Normalise lat/lng → [0,1]
49
+ 2. UMAP on (weighted_geo | weighted_sem) composite feature space
50
+ 3. HDBSCAN with min_cluster_size
51
+ Returns list of cluster IDs per problem (-1 = noise).
52
+ """
53
+ try:
54
+ import umap
55
+ import hdbscan as hdbscan_lib
56
+
57
+ if len(lat_list) < min_cluster_size:
58
+ return [-1] * len(lat_list)
59
+
60
+ coords = np.array(list(zip(lat_list, lng_list)), dtype=np.float32)
61
+ norm_coords = _normalise(coords) * GEO_WEIGHT
62
+
63
+ emb = np.array(embeddings, dtype=np.float32) * SEM_WEIGHT
64
+ composite = np.hstack([norm_coords, emb])
65
+
66
+ # UMAP: reduce to 8 dims for HDBSCAN
67
+ n_neighbors = min(15, len(lat_list) - 1)
68
+ reducer = umap.UMAP(n_components=8, n_neighbors=n_neighbors, metric='euclidean', random_state=42)
69
+ reduced = reducer.fit_transform(composite)
70
+
71
+ clusterer = hdbscan_lib.HDBSCAN(min_cluster_size=min_cluster_size, gen_min_span_tree=True)
72
+ labels = clusterer.fit_predict(reduced)
73
+ return labels.tolist()
74
+
75
+ except Exception as e:
76
+ logger.error(f"Geo-semantic clustering failed: {e}")
77
+ return [-1] * len(lat_list)
78
+
79
+
80
+ def cluster_semantic_only(
81
+ embeddings: list[list[float]],
82
+ min_cluster_size: int = 2,
83
+ ) -> list[int]:
84
+ """
85
+ Pure semantic clustering on description embeddings.
86
+ UMAP (cosine) → HDBSCAN.
87
+ """
88
+ try:
89
+ import umap
90
+ import hdbscan as hdbscan_lib
91
+
92
+ if len(embeddings) < min_cluster_size:
93
+ return [-1] * len(embeddings)
94
+
95
+ emb = np.array(embeddings, dtype=np.float32)
96
+ n_neighbors = min(10, len(embeddings) - 1)
97
+ reducer = umap.UMAP(n_components=6, n_neighbors=n_neighbors, metric='cosine', random_state=42)
98
+ reduced = reducer.fit_transform(emb)
99
+
100
+ clusterer = hdbscan_lib.HDBSCAN(min_cluster_size=min_cluster_size)
101
+ return clusterer.fit_predict(reduced).tolist()
102
+
103
+ except Exception as e:
104
+ logger.error(f"Semantic clustering failed: {e}")
105
+ return [-1] * len(embeddings)
106
+
107
+
108
+ def nearby_problem_count(lat: float, lng: float, all_lats: list[float], all_lngs: list[float], radius_km: float = 7.5) -> int:
109
+ """Count problems within radius_km of a given point."""
110
+ count = 0
111
+ for lo, ln in zip(all_lats, all_lngs):
112
+ if _haversine_km(lat, lng, lo, ln) <= radius_km:
113
+ count += 1
114
+ return max(0, count - 1) # exclude self
ml/embedder.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ embedder.py – Sentence-Transformer embedding + Zero-Shot type classification
3
+ """
4
+ from __future__ import annotations
5
+ import logging
6
+ from functools import lru_cache
7
+ from sentence_transformers import SentenceTransformer
8
+ from transformers import pipeline
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ EMBED_MODEL = "all-MiniLM-L6-v2"
13
+ ZSC_MODEL = "facebook/bart-large-mnli"
14
+
15
+ CANDIDATE_LABELS = [
16
+ "death or mass casualty",
17
+ "pandemic or disease outbreak",
18
+ "flood or natural disaster",
19
+ "shelter or housing crisis",
20
+ "food or water scarcity",
21
+ "medical or health emergency",
22
+ "education disruption",
23
+ "infrastructure damage",
24
+ ]
25
+ LABEL_TO_TYPE = {
26
+ "death or mass casualty": "death_casualty",
27
+ "pandemic or disease outbreak": "pandemic",
28
+ "flood or natural disaster": "flood_disaster",
29
+ "shelter or housing crisis": "shelter",
30
+ "food or water scarcity": "food_water",
31
+ "medical or health emergency": "medical",
32
+ "education disruption": "education",
33
+ "infrastructure damage": "infrastructure",
34
+ }
35
+
36
+
37
+ @lru_cache(maxsize=1)
38
+ def _get_embedder() -> SentenceTransformer:
39
+ logger.info("Loading sentence-transformer model …")
40
+ return SentenceTransformer(EMBED_MODEL)
41
+
42
+
43
+ @lru_cache(maxsize=1)
44
+ def _get_zsc():
45
+ logger.info("Loading zero-shot classifier …")
46
+ return pipeline("zero-shot-classification", model=ZSC_MODEL)
47
+
48
+
49
+ def embed_texts(texts: list[str]) -> list[list[float]]:
50
+ """Return a list of 384-dim embeddings for each text."""
51
+ embedder = _get_embedder()
52
+ vecs = embedder.encode(texts, show_progress_bar=False, batch_size=32, normalize_embeddings=True)
53
+ return vecs.tolist()
54
+
55
+
56
+ def classify_type(description: str, top_k: int = 1) -> tuple[str, float]:
57
+ """
58
+ Zero-shot classify a problem description into one of 8 types.
59
+ Returns (type_key, confidence_score).
60
+ """
61
+ try:
62
+ zsc = _get_zsc()
63
+ result = zsc(description, CANDIDATE_LABELS, multi_label=False)
64
+ best_label = result["labels"][0]
65
+ best_score = float(result["scores"][0])
66
+ return LABEL_TO_TYPE.get(best_label, "infrastructure"), best_score
67
+ except Exception as e:
68
+ logger.warning(f"ZSC failed: {e}")
69
+ return "infrastructure", 0.0
70
+
71
+
72
+ def classify_batch(descriptions: list[str]) -> list[tuple[str, float]]:
73
+ """Batch zero-shot classification."""
74
+ return [classify_type(d) for d in descriptions]
ml/matcher.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ matcher.py – Bi-encoder NGO matching + Preemption Decision
3
+ """
4
+ from __future__ import annotations
5
+ import logging
6
+ import math
7
+ import os
8
+ import pickle
9
+ from datetime import datetime, timezone
10
+
11
+ import numpy as np
12
+ from sklearn.linear_model import LogisticRegression
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ PREEMPT_MODEL_PATH = os.path.join(os.path.dirname(__file__), "preempt_lr.pkl")
17
+
18
+ # Distance threshold — NGOs further than this are not considered
19
+ MAX_DISTANCE_KM = 30.0
20
+ W_TEXT = 0.40
21
+ W_GEO = 0.35
22
+ W_WORK = 0.25
23
+
24
+ MAX_DISTANCE_KM = 30.0 # NGOs further than this won't be considered
25
+
26
+ _preempt_model: LogisticRegression | None = None
27
+
28
+
29
+ # ── Scoring helpers ───────────────────────────────────────────
30
+
31
+ def _haversine_km(lat1, lng1, lat2, lng2) -> float:
32
+ R = 6371.0
33
+ dlat = math.radians(lat2 - lat1)
34
+ dlng = math.radians(lng2 - lng1)
35
+ a = math.sin(dlat/2)**2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlng/2)**2
36
+ return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
37
+
38
+
39
+ def _cosine_sim(a: list[float], b: list[float]) -> float:
40
+ va, vb = np.array(a), np.array(b)
41
+ denom = np.linalg.norm(va) * np.linalg.norm(vb)
42
+ return float(np.dot(va, vb) / denom) if denom > 0 else 0.0
43
+
44
+
45
+ def _geo_score(dist_km: float) -> float:
46
+ """Inverse-distance score → [0, 1], clamped at MAX_DISTANCE_KM."""
47
+ if dist_km >= MAX_DISTANCE_KM:
48
+ return 0.0
49
+ return 1 - (dist_km / MAX_DISTANCE_KM)
50
+
51
+
52
+ def _workforce_ratio(ngo: dict) -> float:
53
+ total = ngo.get("total_members", 1)
54
+ avail = ngo.get("available_workforce", 0)
55
+ return min(1.0, avail / max(1, total))
56
+
57
+
58
+ def composite_match_score(
59
+ problem_emb: list[float],
60
+ ngo_capability_emb: list[float],
61
+ dist_km: float,
62
+ ngo: dict,
63
+ ) -> float:
64
+ text_sim = _cosine_sim(problem_emb, ngo_capability_emb)
65
+ geo_s = _geo_score(dist_km)
66
+ work_s = _workforce_ratio(ngo)
67
+ return (W_TEXT * text_sim) + (W_GEO * geo_s) + (W_WORK * work_s)
68
+
69
+
70
+ # ── NGO capability string ─────────────────────────────────────
71
+
72
+ TYPE_DESCRIPTIONS = {
73
+ "death_casualty": "mass casualty rescue emergency response mortality",
74
+ "pandemic": "disease outbreak pandemic medical public health epidemiology",
75
+ "flood_disaster": "flood natural disaster rescue relief evacuation",
76
+ "shelter": "shelter housing accommodation homeless crisis",
77
+ "food_water": "food water nutrition scarcity hunger relief distribution",
78
+ "medical": "medical health first aid hospital care",
79
+ "education": "education school children learning disruption",
80
+ "infrastructure": "infrastructure repair damage construction debris",
81
+ }
82
+
83
+ def build_ngo_capability_string(ngo: dict) -> str:
84
+ parts = [ngo.get("name", ""), ngo.get("address", "")]
85
+ for wt in ngo.get("work_types", []):
86
+ parts.append(TYPE_DESCRIPTIONS.get(wt, wt))
87
+ return " ".join(filter(None, parts))
88
+
89
+
90
+ # ── Preemption Decision ───────────────────────────────────────
91
+
92
+ def _load_preempt_model():
93
+ global _preempt_model
94
+ if _preempt_model is None and os.path.exists(PREEMPT_MODEL_PATH):
95
+ try:
96
+ with open(PREEMPT_MODEL_PATH, "rb") as f:
97
+ _preempt_model = pickle.load(f)
98
+ logger.info("Preemption LR model loaded.")
99
+ except Exception as e:
100
+ logger.warning(f"Could not load preemption model: {e}")
101
+ return _preempt_model
102
+
103
+
104
+ def decide_preemption(
105
+ current_problem_score: float,
106
+ pct_done: float,
107
+ new_problem_score: float,
108
+ type_match: bool,
109
+ dist_km_to_new: float,
110
+ eta_days_remaining: float,
111
+ ) -> tuple[bool, str]:
112
+ """
113
+ Returns (should_preempt: bool, reason: str).
114
+ Uses LR model if available, else rule-based fallback.
115
+ """
116
+ remaining_value = current_problem_score * (1 - pct_done / 100.0)
117
+ features = np.array([[remaining_value, new_problem_score,
118
+ float(type_match), dist_km_to_new, eta_days_remaining]])
119
+
120
+ model = _load_preempt_model()
121
+ if model is not None:
122
+ try:
123
+ pred = bool(model.predict(features)[0])
124
+ prob = float(model.predict_proba(features)[0][1])
125
+ reason = f"Model confidence: {prob:.0%}"
126
+ return pred, reason
127
+ except Exception as e:
128
+ logger.warning(f"Preemption model failed: {e}")
129
+
130
+ # ── Fallback rule-based logic ─────────────────────────────
131
+ if (new_problem_score > remaining_value * 1.3
132
+ and type_match
133
+ and dist_km_to_new < 15.0):
134
+ return True, f"New score ({new_problem_score:.1f}) is >130% of remaining value ({remaining_value:.1f})"
135
+
136
+ if new_problem_score > remaining_value * 2.0:
137
+ return True, f"New score ({new_problem_score:.1f}) is more than double remaining value ({remaining_value:.1f})"
138
+
139
+ return False, f"Current task more valuable (remaining_value={remaining_value:.1f})"
140
+
141
+
142
+ def eta_from_score(problem_score: float, workforce: int) -> float:
143
+ """Rough ETA estimate in days based on score and workforce."""
144
+ if workforce <= 0:
145
+ workforce = 1
146
+ base_days = max(0.5, problem_score / (workforce * 20))
147
+ return round(base_days, 1)
148
+
149
+
150
+ # ── Main Matching Function ─────────────────────────────────────
151
+
152
+ def match_ngos_to_problems(
153
+ ranked_problems: list[dict], # sorted by score desc, includes score/flag/lat/lng/type
154
+ ngos: list[dict],
155
+ problem_embeddings: dict[str, list[float]], # {problem_id: embedding}
156
+ ngo_embeddings: dict[str, list[float]], # {ngo_id: embedding}
157
+ ) -> list[dict]:
158
+ """
159
+ For each problem (in priority order):
160
+ 1. Filter NGOs by distance and work type
161
+ 2. Rank by composite match score
162
+ 3. If best NGO is busy → run preemption check
163
+ 4. Assign or queue
164
+
165
+ Returns list of assignment dicts.
166
+ """
167
+ assigned_ngo_ids: set[str] = set() # track newly assigned in this run
168
+ assignments: list[dict] = []
169
+
170
+ for problem in ranked_problems:
171
+ pid = problem["id"]
172
+ p_emb = problem_embeddings.get(pid, [])
173
+ p_score = problem.get("score", 0.0)
174
+ p_type = problem.get("type", "")
175
+ p_lat, p_lng = problem.get("lat", 0), problem.get("lng", 0)
176
+
177
+ # Already assigned in DB - skip unless score warrants check
178
+ if problem.get("status") == "assigned" and not problem.get("flag", False):
179
+ continue
180
+
181
+ # ── Candidate NGOs ────────────────────────────────────
182
+ candidates = []
183
+ for ngo in ngos:
184
+ # Work-type filter
185
+ if p_type not in (ngo.get("work_types") or []):
186
+ continue
187
+ # Workforce filter
188
+ if (ngo.get("available_workforce") or 0) <= 0 and ngo.get("status") == "available":
189
+ continue
190
+ # Distance
191
+ dist = _haversine_km(p_lat, p_lng, ngo.get("lat", 0), ngo.get("lng", 0))
192
+ if dist > MAX_DISTANCE_KM:
193
+ continue
194
+ n_emb = ngo_embeddings.get(ngo["id"], [])
195
+ ms = composite_match_score(p_emb, n_emb, dist, ngo)
196
+ candidates.append({"ngo": ngo, "dist": dist, "match_score": ms})
197
+
198
+ if not candidates:
199
+ # No NGO available → mark pending
200
+ assignments.append({
201
+ "problem_id": pid, "problem_type": p_type,
202
+ "problem_description": problem.get("description", ""),
203
+ "ngo_id": None, "ngo_name": "No NGO Available",
204
+ "match_score": 0.0, "distance_km": 0.0,
205
+ "preempted": False, "preemption_reason": "No matching NGO within 30 km",
206
+ "eta_days": 0.0, "ngo_status": "pending",
207
+ "action": "HOLD",
208
+ })
209
+ continue
210
+
211
+ # Sort by match_score desc
212
+ candidates.sort(key=lambda x: x["match_score"], reverse=True)
213
+ best = candidates[0]
214
+ best_ngo = best["ngo"]
215
+ ngo_id = best_ngo["id"]
216
+ dist_km = best["dist"]
217
+ match_score = best["match_score"]
218
+
219
+ preempted = False
220
+ preemption_reason = None
221
+ action = "ASSIGN"
222
+
223
+ if best_ngo.get("status") == "busy" and ngo_id not in assigned_ngo_ids:
224
+ # Preemption check
225
+ cur_score = 0.0
226
+ if best_ngo.get("current_problem_id"):
227
+ cur_prob = next(
228
+ (p for p in ranked_problems if p["id"] == best_ngo["current_problem_id"]), None
229
+ )
230
+ cur_score = cur_prob["score"] if cur_prob else 0.0
231
+
232
+ pct = best_ngo.get("pct_done", 0.0) or 0.0
233
+ eta_rem = best_ngo.get("eta_days") or 1.0
234
+ type_match_flag = p_type in (best_ngo.get("work_types") or [])
235
+
236
+ should_preempt, reason = decide_preemption(
237
+ cur_score, pct, p_score, type_match_flag, dist_km, eta_rem
238
+ )
239
+
240
+ if should_preempt:
241
+ preempted = True
242
+ preemption_reason = reason
243
+ action = "PREEMPT"
244
+ else:
245
+ # Try second-best candidate
246
+ if len(candidates) > 1:
247
+ best = candidates[1]
248
+ best_ngo = best["ngo"]
249
+ ngo_id = best_ngo["id"]
250
+ dist_km = best["dist"]
251
+ match_score = best["match_score"]
252
+ action = "ASSIGN_2ND"
253
+ else:
254
+ action = "QUEUE"
255
+
256
+ assigned_ngo_ids.add(ngo_id)
257
+ eta_days = eta_from_score(p_score, best_ngo.get("available_workforce", 1))
258
+
259
+ assignments.append({
260
+ "problem_id": pid,
261
+ "problem_type": p_type,
262
+ "problem_description": problem.get("description", ""),
263
+ "ngo_id": ngo_id,
264
+ "ngo_name": best_ngo.get("name", "Unknown"),
265
+ "match_score": match_score,
266
+ "distance_km": dist_km,
267
+ "preempted": preempted,
268
+ "preemption_reason": preemption_reason,
269
+ "eta_days": eta_days,
270
+ "ngo_status": best_ngo.get("status", "available"),
271
+ "action": action,
272
+ })
273
+
274
+ return assignments
275
+
276
+
277
+ def save_preempt_model(model) -> None:
278
+ with open(PREEMPT_MODEL_PATH, "wb") as f:
279
+ pickle.dump(model, f)
280
+
281
+
282
+ def train_preempt_model(X: list[list[float]], y: list[int]) -> None:
283
+ if len(X) < 10:
284
+ return
285
+ try:
286
+ lr = LogisticRegression(max_iter=500)
287
+ lr.fit(np.array(X), np.array(y))
288
+ save_preempt_model(lr)
289
+ logger.info("Preemption model trained.")
290
+ except Exception as e:
291
+ logger.error(f"Preemption model training failed: {e}")
ml/scorer.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ scorer.py – Problem scoring: formula baseline + LightGBM ranker + flag logic
3
+ """
4
+ from __future__ import annotations
5
+ import logging
6
+ import pickle
7
+ import os
8
+ import numpy as np
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ # Priority weights per problem type
13
+ TYPE_WEIGHTS: dict[str, float] = {
14
+ "death_casualty": 100, "pandemic": 90, "flood_disaster": 80,
15
+ "shelter": 70, "food_water": 60, "medical": 50,
16
+ "education": 40, "infrastructure": 30,
17
+ }
18
+
19
+ MODEL_PATH = os.path.join(os.path.dirname(__file__), "lgbm_ranker.pkl")
20
+ _lgbm_model = None
21
+
22
+
23
+ def _load_lgbm():
24
+ global _lgbm_model
25
+ if _lgbm_model is None and os.path.exists(MODEL_PATH):
26
+ try:
27
+ with open(MODEL_PATH, "rb") as f:
28
+ _lgbm_model = pickle.load(f)
29
+ logger.info("LightGBM ranker loaded.")
30
+ except Exception as e:
31
+ logger.warning(f"Could not load LightGBM: {e}")
32
+ return _lgbm_model
33
+
34
+
35
+ def formula_score(
36
+ problem_type: str,
37
+ people_affected: int,
38
+ delay_days: int,
39
+ nearby_count: int,
40
+ embedding_norm: float = 1.0,
41
+ ) -> float:
42
+ """
43
+ Baseline formula:
44
+ score = type_weight * 0.90
45
+ + people_affected * 0.80
46
+ + delay_days * 0.70
47
+ + nearby_count * 10
48
+ """
49
+ tw = TYPE_WEIGHTS.get(problem_type, 30)
50
+ return (tw * 0.90) + (people_affected * 0.80) + (delay_days * 0.70) + (nearby_count * 10)
51
+
52
+
53
+ def build_features(
54
+ problem_type: str,
55
+ people_affected: int,
56
+ delay_days: int,
57
+ nearby_count: int,
58
+ embedding_norm: float,
59
+ geo_cluster_id: int,
60
+ ) -> list[float]:
61
+ return [
62
+ TYPE_WEIGHTS.get(problem_type, 30),
63
+ float(people_affected),
64
+ float(delay_days),
65
+ float(nearby_count),
66
+ float(embedding_norm),
67
+ float(max(geo_cluster_id, -1)),
68
+ ]
69
+
70
+
71
+ def score_problem(
72
+ problem_type: str,
73
+ people_affected: int,
74
+ delay_days: int,
75
+ nearby_count: int,
76
+ embedding: list[float],
77
+ geo_cluster_id: int,
78
+ ) -> float:
79
+ """Score a single problem. Uses LightGBM if trained, else formula."""
80
+ emb_norm = float(np.linalg.norm(embedding)) if embedding else 1.0
81
+ model = _load_lgbm()
82
+ if model is not None:
83
+ try:
84
+ feats = np.array([build_features(problem_type, people_affected, delay_days,
85
+ nearby_count, emb_norm, geo_cluster_id)])
86
+ return float(model.predict(feats)[0])
87
+ except Exception as e:
88
+ logger.warning(f"LightGBM predict failed: {e}")
89
+ return formula_score(problem_type, people_affected, delay_days, nearby_count, emb_norm)
90
+
91
+
92
+ def score_all_problems(problems: list[dict], embeddings: list[list[float]],
93
+ geo_clusters: list[int], all_lats: list[float], all_lngs: list[float]) -> list[float]:
94
+ """Score all problems and update 'score' field."""
95
+ from .clusterer import nearby_problem_count
96
+ scores = []
97
+ for i, p in enumerate(problems):
98
+ nc = nearby_problem_count(p["lat"], p["lng"], all_lats, all_lngs)
99
+ s = score_problem(
100
+ p["type"], p.get("people_affected", 1), p.get("delay_days", 0),
101
+ nc, embeddings[i] if embeddings else [], geo_clusters[i] if geo_clusters else -1,
102
+ )
103
+ scores.append(s)
104
+ return scores
105
+
106
+
107
+ def apply_flag_logic(
108
+ problem_ids: list[str],
109
+ type_cluster_membership: list[str], # type key per problem
110
+ semantic_cluster_membership: list[int], # semantic cluster id
111
+ geo_cluster_membership: list[int], # geo cluster id
112
+ ) -> list[bool]:
113
+ """
114
+ Flag rule: if a problem appears in >= 2 distinct clustering tables
115
+ with non-noise cluster id, flag = True.
116
+ """
117
+ flags = []
118
+ for i in range(len(problem_ids)):
119
+ count = 0
120
+ # Type cluster: always in a type cluster (count +1 if not isolated)
121
+ count += 1 # every problem belongs to a type group
122
+ # Semantic cluster
123
+ if semantic_cluster_membership[i] >= 0:
124
+ count += 1
125
+ # Geo cluster
126
+ if geo_cluster_membership[i] >= 0:
127
+ count += 1
128
+ flags.append(count >= 2)
129
+ return flags
130
+
131
+
132
+ def save_lgbm_model(model) -> None:
133
+ with open(MODEL_PATH, "wb") as f:
134
+ pickle.dump(model, f)
135
+ logger.info("LightGBM ranker saved.")
136
+
137
+
138
+ def train_or_update_lgbm(X: list[list[float]], y: list[float]) -> None:
139
+ """Train/retrain LightGBM ranker when >= 10 labelled samples available."""
140
+ if len(X) < 10:
141
+ logger.info("Not enough samples for LightGBM training yet.")
142
+ return
143
+ try:
144
+ import lightgbm as lgb
145
+ model = lgb.LGBMRegressor(n_estimators=100, learning_rate=0.05, num_leaves=15, verbose=-1)
146
+ model.fit(np.array(X), np.array(y))
147
+ save_lgbm_model(model)
148
+ logger.info(f"LightGBM trained on {len(X)} samples.")
149
+ except Exception as e:
150
+ logger.error(f"LightGBM training failed: {e}")