Token Classification
Transformers
Safetensors
Arabic
English
location
geoparsing
toponym-recognition
toponym-resolution
named-entity-recognition
arabic
social-media
marsad
Instructions to use rafiulbiswas/marsad-location with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use rafiulbiswas/marsad-location with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("token-classification", model="rafiulbiswas/marsad-location")# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("rafiulbiswas/marsad-location", device_map="auto") - Notebooks
- Google Colab
- Kaggle
File size: 11,487 Bytes
38ac623 | 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 201 202 203 204 205 206 207 | # 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 |
|