Spaces:
Runtime error
Runtime error
Download src/backend/services/crowd_verification.py from HAK-Tech/ciro-backend: direct link, hf CLI and curl.
- Browser
- Download file 7.59 kB
-
https://huggingface.co/spaces/HAK-Tech/ciro-backend/resolve/main/src/backend/services/crowd_verification.py
- Command line
-
hf download hf://spaces/HAK-Tech/ciro-backend/src/backend/services/crowd_verification.py
-
curl -L -o crowd_verification.py https://huggingface.co/spaces/HAK-Tech/ciro-backend/resolve/main/src/backend/services/crowd_verification.py
7.59 kB
| """ | |
| Crowd verification orchestrator β Phase 10. | |
| Owns: | |
| - Sending FCM verification prompts to nearby users (via radius query) | |
| - Storing crowd responses on the crisis Firestore document | |
| - Evaluating confirmation/denial counts to produce a verdict | |
| - Calling record_false_report() on the original reporter for denied verdicts | |
| - Dispatching FCM warning/blacklist notices when those strikes land | |
| Does NOT own: | |
| - Strike rules (services/cnic.py β Phase 9) | |
| - NGO escalation (Phase 11) | |
| - Map display of helper locations (mobile Phase 5) | |
| """ | |
| from __future__ import annotations | |
| import logging | |
| from google.cloud.firestore import SERVER_TIMESTAMP | |
| from backend.core.firebase import get_async_db | |
| from backend.services.cnic import record_false_report | |
| from backend.services.fcm import send_blacklist_notice, send_strike_warning, send_verification_prompt | |
| from backend.services.radius_query import DEFAULT_RADIUS_KM, get_users_within_radius | |
| logger = logging.getLogger(__name__) | |
| CONFIRMATION_THRESHOLD: float = 0.6 | |
| DENIAL_THRESHOLD: float = 0.3 | |
| # ββ Pure decision function (no I/O β fully unit-testable) ββββββββββββββββββββ | |
| def evaluate_verification(confirmations: int, denials: int) -> str: | |
| """Return the crowd verification verdict from raw response counts. | |
| Rules (single source of truth): | |
| total == 0 β "inconclusive" | |
| confirmation_rate >= 0.6 β "confirmed" | |
| confirmation_rate <= 0.3 β "denied" | |
| between thresholds β "inconclusive" | |
| Args: | |
| confirmations: Count of "confirm" + "help" responses received. | |
| denials: Count of "deny" responses received. | |
| Returns: | |
| One of: "confirmed", "denied", "inconclusive". | |
| """ | |
| total = confirmations + denials | |
| if total == 0: | |
| return "inconclusive" | |
| rate = confirmations / total | |
| if rate >= CONFIRMATION_THRESHOLD: | |
| return "confirmed" | |
| if rate <= DENIAL_THRESHOLD: | |
| return "denied" | |
| return "inconclusive" | |
| # ββ Outbound: fan out prompts to nearby users βββββββββββββββββββββββββββββββββ | |
| async def send_verification_prompts( | |
| crisis_id: str, | |
| crisis_type: str, | |
| location_label: str, | |
| lat: float, | |
| lon: float, | |
| radius_km: float = DEFAULT_RADIUS_KM, | |
| ) -> dict: | |
| """Query users within radius and fire FCM verification prompts to each one. | |
| Initialises the crisis document's verification counters on Firestore so | |
| the verify endpoint can do atomic increments against a known baseline. | |
| Args: | |
| crisis_id: Firestore document ID of the crisis. | |
| crisis_type: Human-readable crisis label (e.g. "flood"). | |
| location_label: Human-readable area name shown in the notification. | |
| lat: Crisis latitude. | |
| lon: Crisis longitude. | |
| radius_km: Search radius. Defaults to DEFAULT_RADIUS_KM (1 km). | |
| Returns: | |
| {"users_found": int, "users_notified": int} | |
| """ | |
| nearby = await get_users_within_radius(lat, lon, radius_km) | |
| notified = 0 | |
| for user in nearby: | |
| ok = await send_verification_prompt( | |
| token=user.fcm_token, | |
| crisis_id=crisis_id, | |
| crisis_type=crisis_type, | |
| location=location_label, | |
| ) | |
| if ok: | |
| notified += 1 | |
| db = get_async_db() | |
| await db.collection("crises").document(crisis_id).update({ | |
| "verification_status": "pending", | |
| "users_notified": notified, | |
| "confirmations": 0, | |
| "denials": 0, | |
| "helpers": [], | |
| "verification_sent_at": SERVER_TIMESTAMP, | |
| }) | |
| logger.info( | |
| "Crowd verification: notified %d/%d users near crisis %s", | |
| notified, len(nearby), crisis_id, | |
| ) | |
| return {"users_found": len(nearby), "users_notified": notified} | |
| # ββ Inbound: handle a user's verification response ββββββββββββββββββββββββββββ | |
| async def process_verification_response( | |
| crisis_id: str, | |
| cnic: str, | |
| response: str, | |
| ) -> dict: | |
| """Store a crowd verification response and re-evaluate the verdict. | |
| Args: | |
| crisis_id: Firestore document ID of the crisis being verified. | |
| cnic: Responding user's CNIC (resolved server-side from JWT). | |
| response: One of "confirm", "deny", "help". | |
| "help" = confirm + volunteer to assist on-ground. | |
| Returns: | |
| {"verdict": str, "confirmations": int, "denials": int} | |
| Side effects: | |
| - Updates crisis.confirmations / crisis.denials / crisis.helpers | |
| - Updates crisis.verification_result | |
| - On "denied" verdict: calls record_false_report() on the original | |
| reporter and dispatches the appropriate FCM notice (warning or | |
| blacklist) if a state transition occurs. | |
| Raises: | |
| ValueError: If no crisis document exists for `crisis_id`. | |
| """ | |
| db = get_async_db() | |
| crisis_ref = db.collection("crises").document(crisis_id) | |
| doc = await crisis_ref.get() | |
| if not doc.exists: | |
| raise ValueError(f"Crisis {crisis_id!r} not found in Firestore") | |
| data = doc.to_dict() | |
| confirmations: int = data.get("confirmations", 0) | |
| denials: int = data.get("denials", 0) | |
| helpers: list[str] = list(data.get("helpers", [])) | |
| reporter_cnic: str | None = data.get("reporter_cnic") | |
| if response == "confirm": | |
| confirmations += 1 | |
| await crisis_ref.update({"confirmations": confirmations}) | |
| elif response == "deny": | |
| denials += 1 | |
| await crisis_ref.update({"denials": denials}) | |
| elif response == "help": | |
| confirmations += 1 | |
| if cnic not in helpers: | |
| helpers.append(cnic) | |
| await crisis_ref.update({"confirmations": confirmations, "helpers": helpers}) | |
| verdict = evaluate_verification(confirmations, denials) | |
| await crisis_ref.update({ | |
| "verification_result": verdict, | |
| "verification_updated_at": SERVER_TIMESTAMP, | |
| }) | |
| if verdict == "denied" and reporter_cnic: | |
| await _handle_denied_verdict(reporter_cnic) | |
| return {"verdict": verdict, "confirmations": confirmations, "denials": denials} | |
| async def _handle_denied_verdict(reporter_cnic: str) -> None: | |
| """Record a false report strike and dispatch FCM notice if warranted. | |
| Only sends a notification when the strike causes a state transition | |
| (warned or blacklisted). Silent strikes (1 and 2) produce no FCM. | |
| """ | |
| try: | |
| strike_result = await record_false_report(reporter_cnic) | |
| except ValueError as exc: | |
| logger.warning("record_false_report failed for %s: %s", reporter_cnic, exc) | |
| return | |
| action = strike_result.get("action") | |
| logger.info("False report strike for %s: %s (count=%s)", reporter_cnic, action, strike_result.get("strike_count")) | |
| if action not in ("warned", "blacklisted"): | |
| return | |
| db = get_async_db() | |
| user_doc = await db.collection("users").document(reporter_cnic).get() | |
| if not user_doc.exists: | |
| return | |
| token: str | None = user_doc.to_dict().get("fcm_token") | |
| if not token: | |
| return | |
| if action == "warned": | |
| # strikes_remaining = how many more before blacklist (always 1 at count=3) | |
| strikes_remaining = 4 - strike_result["strike_count"] | |
| await send_strike_warning(token=token, strikes_remaining=strikes_remaining) | |
| elif action == "blacklisted": | |
| await send_blacklist_notice(token=token) | |