marsad-location / code /LOCATION_HANDOFF.md
rafiulbiswas's picture
Upload 3 files
38ac623 verified
|
Raw History Blame Contribute Delete
11.5 kB
# MARSAD location extraction: integration handoff
Prepared by Rafi for integration into `marsad-new`. This file is written so that a developer (or Claude Code)
can integrate the module without the original conversation.
## 1. What it does
For each post (Arabic, English or mixed), it returns every location mentioned, resolved to a place hierarchy:
```
country > state/governorate > county > city > district / landmark
```
It also returns the **role** of each mention (mentioned / author / origin / destination / negated) and,
when the text says it, the **author's location** ("أنا من الزرقاء", "I live in Doha", or a profile location field).
Pipeline inside `marsad_location.py`:
1. **Mention detection:** fine-tuned XLM-R (`models/xlmr_lmr_typed`, trained on IDRISI-LMR, Arabic + English),
plus rules for flags 🇶🇦, coordinates, ISO/US-state/airport codes, stretched words (Doooha) and optional hashtags.
2. **Lookup:** gazetteer of ~450k places / ~1.6M names (GeoNames + world-cities AR/EN + Arabic states/cities +
locations.db + IDRISI OpenStreetMap names), handling Arabic prefixes (بال، وال، لل), spelling errors,
transliteration (Al Qahira, As Sadd), hashtags and CamelCase.
3. **Disambiguation:** other places and countries named in the same post (including hashtags) decide first,
then an optional topic country (`context_countries`), then clear population dominance (at least 10×).
Otherwise the mention is returned as `ambiguous` with ranked candidates. It never silently picks the biggest city.
## 2. Files to receive
Everything needed at runtime is in a **private Hugging Face repo** (ask Rafi for the repo name and read access):
| Path in the HF repo | Content | Size | Needed at runtime |
|---|---|---|---|
| `model/` | fine-tuned XLM-R location-mention model | ~1.1 GB | yes |
| `gazetteer/places.parquet`, `gazetteer/aliases.parquet` | place dictionary | ~100–300 MB | yes |
| `code/marsad_location.py` | the module | ~50 KB | yes |
| `code/LOCATION_HANDOFF.md`, `marsad_location_schema.sql`, `location_enrich_example.py` | this guide, DB schema, job template | small | schema: yes |
| `eval/summary.csv`, `eval/use_cases.csv` | evaluation results | small | no |
Download on the MARSAD server (once, or at container start):
```bash
pip install -U huggingface_hub
export HF_TOKEN=hf_... # read token with access to the private repo
huggingface-cli download <owner>/marsad-location --local-dir /opt/marsad/location
```
```python
from huggingface_hub import snapshot_download
root = snapshot_download('<owner>/marsad-location', local_dir='/opt/marsad/location') # uses HF_TOKEN
# model_dir = f'{root}/model', gazetteer_dir = f'{root}/gazetteer'
```
Copy `code/marsad_location.py` into `engine/marsad_analytics/` (it is small and belongs in git). Keep the model and
gazetteer out of git; load them from `/opt/marsad/location` or a path set in env (`MARSAD_LOC_MODEL`, `MARSAD_LOC_GAZ`).
The build scripts (`step1`–`step4`, for retraining / rebuilding the gazetteer from IDRISI + GeoNames) are in the
handoff zip from Rafi and are not needed for integration.
## 3. Requirements
```
python >= 3.10
torch, transformers # model (GPU optional)
pandas, pyarrow, numpy
scikit-learn # BallTree for coordinates / district linking
rapidfuzz # spelling correction
```
Resource notes (measured on Colab T4 unless marked):
- Load time ~40–55 s (gazetteer index + model). **Load once per process**, never per request.
- Throughput ~90 posts/s on a T4 GPU in batches of 32. On CPU it will be several times slower (not measured).
- RAM: the gazetteer index lives in Python dicts. Plan for roughly 3–4 GB (estimate; measure on the server).
## 4. Usage
```python
from marsad_location import LocationExtractor
ex = LocationExtractor(
model_dir='/opt/marsad/location/model',
gazetteer_dir='/opt/marsad/location/gazetteer', # folder with places.parquet + aliases.parquet
exclude_sources=(), # production: keep the OpenStreetMap names (only excluded for evaluation)
hashtag_mentions='exact', # None | 'exact' (#Gaza) | 'partial' (#PrayForGaza)
)
results = ex.extract(
texts, # list[str]
profile=False, # True / list[bool] when the text is a user's profile location field
context_countries=[['QA'], ['EG'], ...], # optional, per text: country of the monitored topic (breaks ties only)
batch_size=32,
)
```
Each result:
```json
{
"text": "...",
"locations": [{
"original_mention": "بالقاهرة", "start": 18, "end": 26,
"detected_by": "model", "detection_score": 0.98, "predicted_type": "CITY",
"resolution_status": "resolved", // resolved | country_only | ambiguous | unresolved
"decided_by": "context", // single_candidate | context | country_name | population |
// same_country | street_in_context | single_small | contradicts_context
"confidence": 0.93,
"location_role": "mentioned", // mentioned | author | origin | destination | negated
"place_id": "gn:360630", "entity_type": "city",
"normalized_name": "Cairo", "normalized_name_ar": "القاهرة",
"country": "Egypt", "country_ar": "مصر", "country_code": "EG",
"state": "Cairo", "state_ar": "...", "county": null, "city": "Cairo", "city_ar": "القاهرة",
"district": null, "landmark": null,
"latitude": 30.06, "longitude": 31.25,
"country_inferred": true, // country not written in the text, inferred from the city
"spelling_corrected": false, "matched_by": "prefix",
"candidates": [ ... ] // only for ambiguous / country_only / population decisions
}],
"places": [ {"place_id": "...", "name": "...", "country_code": "...", "level": "...", "mentions": [...], "roles": [...]} ],
"author_location": {"country": "Qatar", "country_code": "QA", "city": "Doha", "evidence": "self_statement"} // or null
}
```
`to_rows(results, ids=post_ids)` flattens results into one row per mention (ready for a DB insert).
## 5. How to count for the map (drill-down)
| `resolution_status` | Country level | City level | Notes |
|---|---|---|---|
| `resolved` | ✓ | ✓ if `city` is set | main signal |
| `country_only` | ✓ | – (show under "unknown city") | country certain, city not |
| `ambiguous` | – | – | keep for review; `candidates` lists options |
| `unresolved` | – | – | name not in gazetteer |
- Exclude `location_role = 'negated'` ("not Greece").
- Show **mentioned places** and **author locations** as separate layers. Never mix them.
- Suggested default filter: `confidence >= 0.5`, adjustable in the UI.
- Regions (`entity_type = 'region'`: Africa, Gulf, Levant, Middle East…) have no country. Show them as their own list.
## 6. Integration plan
1. Add `marsad_location.py` to `engine/marsad_analytics/` (same pattern as the Arabic gender model), with
model/gazetteer paths from env/config. Record a version string, e.g. `loc-xlmr-v1+gaz-2026-11-29`.
2. Apply `marsad_location_schema.sql` (Supabase migration). Adapt the `posts` / `topics` / `users` table and column
names to the real MARSAD schema.
3. Enrichment job (`location_enrich_example.py` as template): select posts without locations, call `extract`
in batches of 32–128 with the topic's country as `context_countries`, and insert rows into `post_locations`.
Make it idempotent per `post_id` and `model_version`.
4. Author location: run with `profile=True` on user profile location fields when available, otherwise use
self-statements from posts. Combine per user (strongest evidence wins) into `user_locations`.
5. Refresh `location_daily` (materialized view) on a schedule. The dashboard reads it for country → state →
city counts, and drills down into `post_locations` for the original posts.
6. Regression tests: run the use cases in §8 and the LMD evaluation after any change to the module or gazetteer.
## 7. Evaluation (IDRISI-LMD tweets not seen in training; OpenStreetMap names switched off)
| Metric | Arabic | English |
|---|---|---|
| Mention detection F1 (model spans) | ~0.92 | ~0.89 |
| Country accuracy (resolved + country_only) | 0.95 | 0.97 |
| Within 25 km of the true place (city level) | 0.76 | 0.84 |
| Median distance error | ~7 km | ~1.3 km |
| End-to-end: true mention found **and** country right | 0.80 | 0.80 |
The full numbers are in `pipeline_eval/summary.csv`. The final tuning round was not re-measured when this was written.
Re-run step 4 for the latest figures.
## 8. Behaviour on the requirement use cases (excerpt)
| Input | Output |
|---|---|
| Heavy rainfall in Doha | Qatar > Doha |
| Flooding in Budapest | Hungary > Budapest (country inferred) |
| Earthquake reported in TR / Traveling to the UAE | Türkiye / United Arab Emirates |
| Flooding in Bangaldesh / Istambul | Bangladesh / Istanbul (spelling corrected) |
| Incident at 25.2854, 51.5310 / 25°17′N, 51°32′E | Qatar > Doha (reverse geocoded) |
| Bombay / Constantinople / Al Qahira | Mumbai / Istanbul / Cairo |
| Paris, Texas / Cambridge near Boston | Paris (TX) / Cambridge (MA) |
| Elections in Georgia / Incident in Springfield | **ambiguous** with candidates (by design) |
| Traveling from Dhaka to Doha | Dhaka [origin], Doha [destination] |
| I live in Qatar, but … flooding in Bangladesh | author = Qatar; Bangladesh mentioned |
| …in Türkiye, not Greece | Greece [negated] |
| أنا من الزرقاء وأعيش في عمان | Zarqa [author]; عمان → Amman (context: Jordan) |
| مظاهرات في طرابلس / … طرابلس لبنان | ambiguous (Libya/Lebanon) / Tripoli, Lebanon |
| حريق في المطرية بالقاهرة | Matariya district of Cairo |
| الخبر العاجل من العين | no location (common words, not places) |
## 9. Known limitations
- **No country signal in the text:** "الزرقاء" in an Egyptian storm post goes to Zarqa, Jordan, because it is bigger.
Always pass the topic's country as `context_countries` where MARSAD knows it.
- **Arabic names for Maghreb / Sudan / Somalia small towns** are sparse in GeoNames (big cities are covered).
- **Natural features outside the Arab world** (islands, rivers, mountains) are only partly covered.
- **Event location vs. mentioned location** (UC46) and cross-post inference (UC50) are not modelled. These are
candidates for a later LLM step (e.g. the MARSAD Qwen server), called only for `ambiguous` / low-confidence mentions.
- **Disputed places** follow GeoNames (e.g. Arabic "القدس" → East Jerusalem/PS, English "Jerusalem" → IL). If MARSAD
needs its own convention, add curated aliases in `step3_build_gazetteer.py`.
## 10. Data licences and attribution
| Source | Licence | Obligation |
|---|---|---|
| GeoNames | CC BY 4.0 | attribute GeoNames in the dashboard/about page |
| world-cities-translations (Wikidata-based) | CC BY 4.0 | attribute |
| OpenStreetMap names (from IDRISI-LMD) | ODbL | attribute OSM; derived databases shared under ODbL |
| IDRISI (training data) | check the IDRISI repo terms | cite the IDRISI papers (ACL 2023) |
| countries-states-cities (Arabic) | check repo licence | — |
| locations.db | source unknown | confirm before any public release |