Spaces:
Sleeping

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

Upload 5 files

Browse files
Files changed (5) hide show
  1. Dockerfile +21 -0
  2. main.py +413 -0
  3. models.py +136 -0
  4. requirements.txt +16 -0
  5. supabase_client.py +110 -0
Dockerfile ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+
5
+ # Install system deps for UMAP/HDBSCAN/torch
6
+ RUN apt-get update && apt-get install -y \
7
+ build-essential \
8
+ libgomp1 \
9
+ && rm -rf /var/lib/apt/lists/*
10
+
11
+ COPY requirements.txt .
12
+ RUN pip install --no-cache-dir -r requirements.txt
13
+
14
+ # Pre-download models at build time (avoids cold-start delays)
15
+ RUN python -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('all-MiniLM-L6-v2')"
16
+
17
+ COPY . .
18
+
19
+ EXPOSE 7860
20
+
21
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
main.py ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ main.py – FastAPI application entry point
3
+ SmartAid Resource Allocation API
4
+ """
5
+ from __future__ import annotations
6
+ import logging
7
+ import os
8
+ from datetime import datetime, timezone
9
+ from typing import Optional
10
+
11
+ from fastapi import FastAPI, HTTPException, BackgroundTasks
12
+ from fastapi.middleware.cors import CORSMiddleware
13
+ from dotenv import load_dotenv
14
+
15
+ load_dotenv()
16
+
17
+ from models import (
18
+ ProblemCreate, ProblemOut, NGOCreate, NGOOut,
19
+ AnalysisResponse, TypeClusterItem, ClusterItem,
20
+ PriorityProblem, NGOAssignment, NGOProgressUpdate,
21
+ )
22
+ import supabase_client as db
23
+ from ml.embedder import embed_texts, classify_batch
24
+ from ml.clusterer import cluster_geo_semantic, cluster_semantic_only, nearby_problem_count
25
+ from ml.scorer import score_all_problems, apply_flag_logic
26
+ from ml.matcher import match_ngos_to_problems, build_ngo_capability_string
27
+
28
+ logging.basicConfig(level=logging.INFO)
29
+ logger = logging.getLogger(__name__)
30
+
31
+ app = FastAPI(title="SmartAid API", version="1.0.0")
32
+
33
+ # ── CORS ──────────────────────────────────────────────────────
34
+ app.add_middleware(
35
+ CORSMiddleware,
36
+ allow_origins=[
37
+ "http://localhost:5500",
38
+ "http://127.0.0.1:5500",
39
+ "http://localhost:3000",
40
+ "http://127.0.0.1:3000",
41
+ "*", # remove this line before production
42
+ ],
43
+ allow_credentials=False,
44
+ allow_methods=["*"],
45
+ allow_headers=["*"],
46
+ )
47
+
48
+
49
+ # ──────────────────────────────────────────────────────────────
50
+ # Health
51
+ # ──────────────────────────────────────────────────────────────
52
+ @app.get("/health")
53
+ def health():
54
+ return {"status": "ok", "timestamp": datetime.now(timezone.utc).isoformat()}
55
+
56
+
57
+ # ──────────────────────────────────────────────────────────────
58
+ # Problems
59
+ # ──────────────────────────────────────────────────────────────
60
+ @app.post("/api/problems", response_model=dict)
61
+ def create_problem(body: ProblemCreate):
62
+ payload = body.model_dump()
63
+ payload.update({"status": "open", "flag": False, "score": None, "cluster_count": 0})
64
+ row = db.insert_problem(payload)
65
+ return {"id": row.get("id"), "status": "created"}
66
+
67
+
68
+ @app.get("/api/problems", response_model=list[dict])
69
+ def get_problems(limit: int = 100):
70
+ return db.fetch_all_problems()[:limit]
71
+
72
+
73
+ # ──────────────────────────────────────────────────────────────
74
+ # NGOs
75
+ # ──────────────────────────────────────────────────────────────
76
+ @app.post("/api/ngos", response_model=dict)
77
+ def create_ngo(body: NGOCreate):
78
+ payload = body.model_dump()
79
+ payload.update({"status": "available", "pct_done": 0.0, "current_problem_id": None})
80
+ row = db.insert_ngo(payload)
81
+ return {"id": row.get("id"), "status": "created"}
82
+
83
+
84
+ @app.get("/api/ngos", response_model=list[dict])
85
+ def get_ngos():
86
+ return db.fetch_all_ngos()
87
+
88
+
89
+ @app.get("/api/ngo/{ngo_id}", response_model=dict)
90
+ def get_ngo(ngo_id: str):
91
+ ngo = db.fetch_ngo(ngo_id)
92
+ if not ngo:
93
+ raise HTTPException(status_code=404, detail="NGO not found")
94
+ history = db.fetch_ngo_history(ngo_id)
95
+ ngo["history"] = history
96
+ # Join current problem
97
+ if ngo.get("current_problem_id"):
98
+ problem = db.fetch_problem(ngo["current_problem_id"])
99
+ ngo["problems"] = problem
100
+ return ngo
101
+
102
+
103
+ @app.post("/api/ngo/{ngo_id}/progress")
104
+ def update_progress(ngo_id: str, body: NGOProgressUpdate):
105
+ ngo = db.fetch_ngo(ngo_id)
106
+ if not ngo:
107
+ raise HTTPException(status_code=404, detail="NGO not found")
108
+ db.update_ngo(ngo_id, {"pct_done": body.pct_done})
109
+ return {"status": "updated", "pct_done": body.pct_done}
110
+
111
+
112
+ @app.post("/api/ngo/{ngo_id}/resolve")
113
+ def resolve_problem(ngo_id: str, body: dict):
114
+ problem_id = body.get("problem_id")
115
+ ngo = db.fetch_ngo(ngo_id)
116
+ if not ngo:
117
+ raise HTTPException(status_code=404, detail="NGO not found")
118
+
119
+ # Mark problem resolved
120
+ if problem_id:
121
+ db.update_problem(problem_id, {"status": "resolved", "assigned_ngo_id": None})
122
+
123
+ # Mark NGO available
124
+ db.update_ngo(ngo_id, {
125
+ "status": "available", "current_problem_id": None,
126
+ "pct_done": 0.0, "eta_days": None, "assignment_start": None,
127
+ })
128
+
129
+ # Close assignment record
130
+ active = db.fetch_active_assignment(ngo_id)
131
+ if active:
132
+ db.update_assignment(active["id"], {
133
+ "status": "completed",
134
+ "completed_at": datetime.now(timezone.utc).isoformat(),
135
+ })
136
+
137
+ return {"status": "resolved"}
138
+
139
+
140
+ # ──────────────────────────────────────────────────────────────
141
+ # Assignments
142
+ # ──────────────────────────────────────────────────────────────
143
+ @app.get("/api/assignments")
144
+ def get_assignments():
145
+ from ml.matcher import _haversine_km
146
+ ngos = db.fetch_all_ngos()
147
+ busy = [n for n in ngos if n.get("status") == "busy" and n.get("current_problem_id")]
148
+ result = []
149
+ for ngo in busy:
150
+ p = db.fetch_problem(ngo["current_problem_id"])
151
+ if not p: continue
152
+ dist = 0.0
153
+ if "lat" in ngo and "lng" in ngo and "lat" in p and "lng" in p:
154
+ dist = _haversine_km(p["lat"], p["lng"], ngo["lat"], ngo["lng"])
155
+
156
+ result.append({
157
+ "ngo_id": ngo["id"],
158
+ "ngo_name": ngo["name"],
159
+ "problem_id": p["id"],
160
+ "problem_type": p.get("type"),
161
+ "problem_description": p.get("description", ""),
162
+ "match_score": p.get("score", 0.0), # using problem score as a proxy
163
+ "distance_km": dist,
164
+ "preempted": False,
165
+ "eta_days": ngo.get("eta_days") or 0.0,
166
+ "ngo_status": ngo["status"],
167
+ })
168
+ return result
169
+
170
+
171
+ # ──────────────────────────────────────────────────────────────
172
+ # Analysis (Main ML Pipeline)
173
+ # ──────────────────────────────────────────────────────────────
174
+ @app.get("/api/analyze", response_model=AnalysisResponse)
175
+ def analyze(background_tasks: BackgroundTasks):
176
+ """
177
+ Full ML pipeline:
178
+ 1. Fetch problems + NGOs
179
+ 2. Embed descriptions (MiniLM)
180
+ 3. Zero-shot classify types (bart-large-mnli)
181
+ 4. UMAP+HDBSCAN semantic clustering
182
+ 5. UMAP+HDBSCAN geo-semantic clustering
183
+ 6. Score all problems (formula / LightGBM)
184
+ 7. Apply flag logic
185
+ 8. Bi-encoder NGO matching + preemption
186
+ 9. Persist results to Supabase
187
+ 10. Return structured response
188
+ """
189
+ problems = db.fetch_all_problems(status_filter=["open", "assigned", "pending"])
190
+ ngos = db.fetch_all_ngos()
191
+
192
+ if not problems:
193
+ return AnalysisResponse(
194
+ total_problems=0, flagged_count=0,
195
+ type_clusters=[], geo_semantic_clusters=[],
196
+ priority_problem=None, assignments=[],
197
+ analysis_timestamp=datetime.now(timezone.utc),
198
+ )
199
+
200
+ descriptions = [p["description"] for p in problems]
201
+ all_lats = [p["lat"] for p in problems]
202
+ all_lngs = [p["lng"] for p in problems]
203
+ problem_ids = [p["id"] for p in problems]
204
+
205
+ # ── Step 2: Embeddings ────────────────────────────────────
206
+ logger.info("Embedding %d problem descriptions …", len(problems))
207
+ embeddings = embed_texts(descriptions)
208
+
209
+ # ── Step 3: Zero-shot classification ──────────────────────
210
+ logger.info("Zero-shot classifying problem types …")
211
+ zsc_results = classify_batch(descriptions)
212
+ verified_types = [r[0] for r in zsc_results]
213
+ type_confidences = [r[1] for r in zsc_results]
214
+
215
+ # ── Step 4: Semantic clustering ───────────────────────────
216
+ logger.info("Running semantic clustering …")
217
+ sem_clusters = cluster_semantic_only(embeddings, min_cluster_size=2)
218
+
219
+ # ── Step 5: Geo-semantic clustering ───────────────────────
220
+ logger.info("Running geo-semantic clustering …")
221
+ geo_clusters = cluster_geo_semantic(all_lats, all_lngs, embeddings, min_cluster_size=2)
222
+
223
+ # ── Step 6: Score all problems ────────────────────────────
224
+ logger.info("Scoring problems …")
225
+ scores = score_all_problems(problems, embeddings, geo_clusters, all_lats, all_lngs)
226
+
227
+ # ── Step 7: Flag logic ────────────────────────────────────
228
+ type_memberships = [p["type"] for p in problems]
229
+ flags = apply_flag_logic(problem_ids, type_memberships, sem_clusters, geo_clusters)
230
+
231
+ # Count cluster memberships per problem
232
+ cluster_counts = []
233
+ for i in range(len(problems)):
234
+ cnt = 1 # always in a type group
235
+ if sem_clusters[i] >= 0: cnt += 1
236
+ if geo_clusters[i] >= 0: cnt += 1
237
+ cluster_counts.append(cnt)
238
+
239
+ # ── Persist scores + flags + clusters to Supabase (async) ─
240
+ def _persist():
241
+ for i, p in enumerate(problems):
242
+ db.update_problem(p["id"], {
243
+ "score": scores[i],
244
+ "flag": flags[i],
245
+ "semantic_cluster": sem_clusters[i],
246
+ "geo_cluster": geo_clusters[i],
247
+ "cluster_count": cluster_counts[i],
248
+ "verified_type": verified_types[i],
249
+ })
250
+ background_tasks.add_task(_persist)
251
+
252
+ # ── Step 8: NGO matching ──────────────────────────────────
253
+ logger.info("Matching NGOs …")
254
+
255
+ # Embed NGO capability strings
256
+ ngo_cap_strings = [build_ngo_capability_string(n) for n in ngos]
257
+ ngo_embeddings_list = embed_texts(ngo_cap_strings) if ngo_cap_strings else []
258
+ ngo_emb_map = {n["id"]: ngo_embeddings_list[i] for i, n in enumerate(ngos)}
259
+ problem_emb_map = {p["id"]: embeddings[i] for i, p in enumerate(problems)}
260
+
261
+ # Sort problems by score desc (flagged first)
262
+ problems_scored = [
263
+ {**problems[i], "score": scores[i], "flag": flags[i],
264
+ "verified_type": verified_types[i], "type_confidence": type_confidences[i],
265
+ "geo_cluster": geo_clusters[i], "semantic_cluster": sem_clusters[i],
266
+ "cluster_count": cluster_counts[i]}
267
+ for i in range(len(problems))
268
+ ]
269
+ problems_scored.sort(key=lambda p: (p["flag"], p["score"]), reverse=True)
270
+
271
+ assignments_raw = match_ngos_to_problems(
272
+ problems_scored, ngos, problem_emb_map, ngo_emb_map
273
+ )
274
+
275
+ # ── Persist assignments to Supabase (async) ───────────────
276
+ def _persist_assignments():
277
+ for a in assignments_raw:
278
+ if not a.get("ngo_id"):
279
+ db.update_problem(a["problem_id"], {"status": "pending"})
280
+ continue
281
+ action = a.get("action", "ASSIGN")
282
+ ngo_id = a["ngo_id"]
283
+ pid = a["problem_id"]
284
+
285
+ if action in ("ASSIGN", "ASSIGN_2ND", "PREEMPT"):
286
+ # Handle preemption
287
+ if action == "PREEMPT":
288
+ ngo = db.fetch_ngo(ngo_id)
289
+ old_pid = ngo.get("current_problem_id")
290
+ if old_pid:
291
+ active = db.fetch_active_assignment(ngo_id)
292
+ if active:
293
+ db.update_assignment(active["id"], {
294
+ "status": "interrupted",
295
+ "completed_at": datetime.now(timezone.utc).isoformat(),
296
+ "pct_done_at_interrupt": ngo.get("pct_done", 0),
297
+ "preemption_reason": a.get("preemption_reason"),
298
+ })
299
+ db.update_problem(old_pid, {"status": "open", "assigned_ngo_id": None})
300
+
301
+ # Assign NGO to new problem
302
+ db.update_ngo(ngo_id, {
303
+ "status": "busy",
304
+ "current_problem_id": pid,
305
+ "pct_done": 0.0,
306
+ "eta_days": a["eta_days"],
307
+ "assignment_start": datetime.now(timezone.utc).isoformat(),
308
+ "available_workforce": max(0, (db.fetch_ngo(ngo_id) or {}).get("available_workforce", 0) - 1),
309
+ })
310
+ db.update_problem(pid, {"status": "assigned", "assigned_ngo_id": ngo_id})
311
+ db.insert_assignment({
312
+ "ngo_id": ngo_id, "problem_id": pid,
313
+ "status": "active",
314
+ "started_at": datetime.now(timezone.utc).isoformat(),
315
+ })
316
+
317
+ background_tasks.add_task(_persist_assignments)
318
+
319
+ # ── Step 10: Build response ───────────────────────────────
320
+ # Type cluster items
321
+ type_cluster_items = [
322
+ TypeClusterItem(
323
+ problem_id=p["id"],
324
+ type=p["type"],
325
+ description=p["description"],
326
+ score=p["score"],
327
+ flag=p["flag"],
328
+ people_affected=p.get("people_affected", 0),
329
+ delay_days=p.get("delay_days", 0),
330
+ status=p.get("status", "open"),
331
+ verified_type=p["verified_type"],
332
+ type_confidence=p["type_confidence"],
333
+ )
334
+ for p in problems_scored
335
+ ]
336
+
337
+ # Geo semantic cluster items
338
+ geo_cluster_items = [
339
+ ClusterItem(
340
+ problem_id=p["id"],
341
+ type=p["type"],
342
+ description=p["description"],
343
+ score=p["score"],
344
+ flag=p["flag"],
345
+ lat=p["lat"],
346
+ lng=p["lng"],
347
+ people_affected=p.get("people_affected", 0),
348
+ delay_days=p.get("delay_days", 0),
349
+ status=p.get("status", "open"),
350
+ cluster_id=p["geo_cluster"],
351
+ )
352
+ for p in problems_scored
353
+ ]
354
+
355
+ # Priority problem
356
+ priority = problems_scored[0] if problems_scored else None
357
+ priority_out = None
358
+ if priority:
359
+ # Check if newly assigned in this run
360
+ top_assignment = next((a for a in assignments_raw if a["problem_id"] == priority["id"]), {})
361
+ ngo_id = top_assignment.get("ngo_id") or priority.get("assigned_ngo_id")
362
+
363
+ ngo_name = top_assignment.get("ngo_name")
364
+ if not ngo_name and ngo_id:
365
+ # If already assigned from a previous run, look up name
366
+ n_data = db.fetch_ngo(ngo_id)
367
+ if n_data: ngo_name = n_data.get("name")
368
+
369
+ priority_out = PriorityProblem(
370
+ problem_id=priority["id"],
371
+ type=priority["type"],
372
+ description=priority["description"],
373
+ score=priority["score"],
374
+ flag=priority["flag"],
375
+ lat=priority["lat"],
376
+ lng=priority["lng"],
377
+ address=priority.get("address"),
378
+ people_affected=priority.get("people_affected", 0),
379
+ delay_days=priority.get("delay_days", 0),
380
+ cluster_count=priority["cluster_count"],
381
+ assigned_ngo_id=ngo_id,
382
+ assigned_ngo_name=ngo_name,
383
+ )
384
+
385
+ # Assignments output
386
+ assignments_out = [
387
+ NGOAssignment(
388
+ ngo_id=a["ngo_id"] or "",
389
+ ngo_name=a["ngo_name"],
390
+ problem_id=a["problem_id"],
391
+ problem_type=a["problem_type"],
392
+ problem_description=a["problem_description"],
393
+ match_score=a["match_score"],
394
+ distance_km=a["distance_km"],
395
+ preempted=a["preempted"],
396
+ preemption_reason=a.get("preemption_reason"),
397
+ eta_days=a["eta_days"],
398
+ ngo_status=a["ngo_status"],
399
+ )
400
+ for a in assignments_raw if a.get("ngo_id")
401
+ ]
402
+
403
+ flagged_count = sum(1 for p in problems_scored if p["flag"])
404
+
405
+ return AnalysisResponse(
406
+ total_problems=len(problems),
407
+ flagged_count=flagged_count,
408
+ type_clusters=type_cluster_items,
409
+ geo_semantic_clusters=geo_cluster_items,
410
+ priority_problem=priority_out,
411
+ assignments=assignments_out,
412
+ analysis_timestamp=datetime.now(timezone.utc),
413
+ )
models.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel, Field
2
+ from typing import Optional, List
3
+ from datetime import datetime
4
+
5
+
6
+ # ── Problem ───────────────────────────────────────────────────
7
+ class ProblemCreate(BaseModel):
8
+ type: str
9
+ description: str
10
+ delay_days: int = Field(ge=0)
11
+ people_affected: int = Field(ge=1)
12
+ lat: float
13
+ lng: float
14
+ address: Optional[str] = None
15
+
16
+
17
+ class ProblemOut(BaseModel):
18
+ id: str
19
+ type: str
20
+ description: str
21
+ delay_days: int
22
+ people_affected: int
23
+ lat: float
24
+ lng: float
25
+ address: Optional[str]
26
+ status: str
27
+ score: Optional[float]
28
+ flag: bool
29
+ type_cluster: Optional[str]
30
+ semantic_cluster: Optional[int]
31
+ geo_cluster: Optional[int]
32
+ cluster_count: int
33
+ assigned_ngo_id: Optional[str]
34
+ created_at: datetime
35
+
36
+
37
+ # ── NGO ───────────────────────────────────────────────────────
38
+ class NGOCreate(BaseModel):
39
+ name: str
40
+ lat: float
41
+ lng: float
42
+ address: Optional[str] = None
43
+ total_members: int = Field(ge=1)
44
+ available_workforce: int = Field(ge=0)
45
+ work_types: List[str]
46
+
47
+
48
+ class NGOOut(BaseModel):
49
+ id: str
50
+ name: str
51
+ lat: float
52
+ lng: float
53
+ address: Optional[str]
54
+ total_members: int
55
+ available_workforce: int
56
+ work_types: List[str]
57
+ status: str
58
+ current_problem_id: Optional[str]
59
+ pct_done: float
60
+ eta_days: Optional[float]
61
+ assignment_start: Optional[datetime]
62
+ created_at: datetime
63
+
64
+
65
+ # ── Analysis Response ─────────────────────────────────────────
66
+ class ClusterItem(BaseModel):
67
+ problem_id: str
68
+ type: str
69
+ description: str
70
+ score: float
71
+ flag: bool
72
+ lat: float
73
+ lng: float
74
+ people_affected: int
75
+ delay_days: int
76
+ status: str
77
+ cluster_id: int
78
+
79
+
80
+ class TypeClusterItem(BaseModel):
81
+ problem_id: str
82
+ type: str
83
+ description: str
84
+ score: float
85
+ flag: bool
86
+ people_affected: int
87
+ delay_days: int
88
+ status: str
89
+ verified_type: Optional[str]
90
+ type_confidence: Optional[float]
91
+
92
+
93
+ class PriorityProblem(BaseModel):
94
+ problem_id: str
95
+ type: str
96
+ description: str
97
+ score: float
98
+ flag: bool
99
+ lat: float
100
+ lng: float
101
+ address: Optional[str]
102
+ people_affected: int
103
+ delay_days: int
104
+ cluster_count: int
105
+ assigned_ngo_id: Optional[str]
106
+ assigned_ngo_name: Optional[str]
107
+
108
+
109
+ class NGOAssignment(BaseModel):
110
+ ngo_id: str
111
+ ngo_name: str
112
+ problem_id: str
113
+ problem_type: str
114
+ problem_description: str
115
+ match_score: float
116
+ distance_km: float
117
+ preempted: bool
118
+ preemption_reason: Optional[str]
119
+ eta_days: float
120
+ ngo_status: str
121
+
122
+
123
+ class AnalysisResponse(BaseModel):
124
+ total_problems: int
125
+ flagged_count: int
126
+ type_clusters: List[TypeClusterItem]
127
+ geo_semantic_clusters: List[ClusterItem]
128
+ priority_problem: Optional[PriorityProblem]
129
+ assignments: List[NGOAssignment]
130
+ analysis_timestamp: datetime
131
+
132
+
133
+ # ── Assignment Update ─────────────────────────────────────────
134
+ class NGOProgressUpdate(BaseModel):
135
+ pct_done: float = Field(ge=0, le=100)
136
+ notes: Optional[str] = None
requirements.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi==0.111.0
2
+ uvicorn[standard]==0.29.0
3
+ pydantic==2.7.1
4
+ python-dotenv==1.0.1
5
+ httpx==0.27.0
6
+ requests==2.31.0
7
+ numpy==1.26.4
8
+ scikit-learn==1.4.2
9
+ lightgbm==4.3.0
10
+ sentence-transformers==2.7.0
11
+ transformers==4.40.1
12
+ torch==2.3.0
13
+ umap-learn==0.5.6
14
+ hdbscan==0.8.38.post1
15
+ supabase==2.4.3
16
+ python-multipart==0.0.9
supabase_client.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+ from dotenv import load_dotenv
4
+ from supabase import create_client, Client
5
+
6
+ # Load .env from the backend directory (works regardless of CWD)
7
+ _env_path = Path(__file__).parent / ".env"
8
+ load_dotenv(dotenv_path=_env_path, override=True)
9
+
10
+ _client: Client | None = None
11
+
12
+
13
+ def get_client() -> Client:
14
+ global _client
15
+ if _client is None:
16
+ url = os.getenv("SUPABASE_URL", "")
17
+ key = os.getenv("SUPABASE_SERVICE_KEY", "")
18
+ if not url or not key:
19
+ raise RuntimeError(
20
+ "SUPABASE_URL and SUPABASE_SERVICE_KEY must be set in "
21
+ f"{_env_path} (file exists: {_env_path.exists()})"
22
+ )
23
+ _client = create_client(url, key)
24
+ return _client
25
+
26
+
27
+ # ── Problems ──────────────────────────────────────────────────
28
+ def fetch_all_problems(status_filter: list[str] | None = None) -> list[dict]:
29
+ db = get_client()
30
+ q = db.table("problems").select("*").order("created_at", desc=False)
31
+ if status_filter:
32
+ q = q.in_("status", status_filter)
33
+ return q.execute().data or []
34
+
35
+
36
+ def fetch_problem(problem_id: str) -> dict | None:
37
+ db = get_client()
38
+ r = db.table("problems").select("*").eq("id", problem_id).single().execute()
39
+ return r.data
40
+
41
+
42
+ def update_problem(problem_id: str, payload: dict) -> dict:
43
+ db = get_client()
44
+ r = db.table("problems").update(payload).eq("id", problem_id).execute()
45
+ return r.data[0] if r.data else {}
46
+
47
+
48
+ def insert_problem(payload: dict) -> dict:
49
+ db = get_client()
50
+ r = db.table("problems").insert(payload).execute()
51
+ return r.data[0] if r.data else {}
52
+
53
+
54
+ # ── NGOs ──────────────────────────────────────────────────────
55
+ def fetch_all_ngos() -> list[dict]:
56
+ db = get_client()
57
+ return db.table("ngos").select("*").order("created_at", desc=False).execute().data or []
58
+
59
+
60
+ def fetch_ngo(ngo_id: str) -> dict | None:
61
+ db = get_client()
62
+ r = db.table("ngos").select("*").eq("id", ngo_id).single().execute()
63
+ return r.data
64
+
65
+
66
+ def update_ngo(ngo_id: str, payload: dict) -> dict:
67
+ db = get_client()
68
+ r = db.table("ngos").update(payload).eq("id", ngo_id).execute()
69
+ return r.data[0] if r.data else {}
70
+
71
+
72
+ def insert_ngo(payload: dict) -> dict:
73
+ db = get_client()
74
+ r = db.table("ngos").insert(payload).execute()
75
+ return r.data[0] if r.data else {}
76
+
77
+
78
+ # ── Assignments ───────────────────────────────────────────────
79
+ def insert_assignment(payload: dict) -> dict:
80
+ db = get_client()
81
+ r = db.table("assignments").insert(payload).execute()
82
+ return r.data[0] if r.data else {}
83
+
84
+
85
+ def update_assignment(assignment_id: str, payload: dict) -> dict:
86
+ db = get_client()
87
+ r = db.table("assignments").update(payload).eq("id", assignment_id).execute()
88
+ return r.data[0] if r.data else {}
89
+
90
+
91
+ def fetch_active_assignment(ngo_id: str) -> dict | None:
92
+ db = get_client()
93
+ r = (db.table("assignments")
94
+ .select("*")
95
+ .eq("ngo_id", ngo_id)
96
+ .eq("status", "active")
97
+ .order("started_at", desc=True)
98
+ .limit(1)
99
+ .execute())
100
+ return r.data[0] if r.data else None
101
+
102
+
103
+ def fetch_ngo_history(ngo_id: str) -> list[dict]:
104
+ db = get_client()
105
+ r = (db.table("assignments")
106
+ .select("*, problems:problem_id(type, description, people_affected)")
107
+ .eq("ngo_id", ngo_id)
108
+ .order("started_at", desc=True)
109
+ .execute())
110
+ return r.data or []