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
MARSAD Location: Arabic & English location extraction and resolution
Finds every place mentioned in a post (Arabic, English or mixed) and resolves it to a real-world hierarchy:
country > state / governorate > county > city > district / landmark
It also returns what role each place plays (mentioned, author's location, origin, destination, negated), and it marks a name as ambiguous, with ranked candidates, when the text does not say which place is meant. It never silently picks the biggest city.
Built for MARSAD, a real-time social-media observatory, to power a country → region → city map drill-down.
| Input | Output |
|---|---|
حريق في المطرية بالقاهرة |
المطرية → Egypt › Cairo › Al Matariyah (district); بالقاهرة → Egypt › Cairo |
أنا من الزرقاء وأعيش في عمان |
Zarqa, Jordan [author]; عمان → Amman (not Oman, because Zarqa puts the text in Jordan) |
Traveling from Dhaka to Doha |
Dhaka, Bangladesh [origin]; Doha, Qatar [destination] |
The earthquake occurred in Türkiye, not Greece |
Türkiye; Greece [negated] |
مظاهرات في طرابلس |
ambiguous: Tripoli, Libya / Tripoli, Lebanon |
Flooding in Bangaldesh |
Bangladesh (spelling corrected) |
Incident at 25.2854, 51.5310 |
Qatar › Doha (from coordinates) |
Quick start
pip install torch transformers huggingface_hub pandas pyarrow scikit-learn rapidfuzz
import sys
from huggingface_hub import snapshot_download
root = snapshot_download("rafiulbiswas/marsad-location")
sys.path.insert(0, f"{root}/code")
from marsad_location import LocationExtractor
ex = LocationExtractor(
model_dir=f"{root}/model",
gazetteer_dir=f"{root}/gazetteer",
)
for r in ex.extract(["وصلت الدوحة قادماً من الرياض", "Flooding in Budapest"]):
for loc in r["locations"]:
print(loc["original_mention"], "→", loc["country"], "/", loc["city"],
"|", loc["resolution_status"], "|", loc["location_role"])
الدوحة → Qatar / Doha | resolved | mentioned
الرياض → Saudi Arabia / Riyadh | resolved | origin
Budapest → Hungary / Budapest | resolved | mentioned
Load the extractor once per process. Building the gazetteer index and loading the model takes about 40–55 s. After that, batches run at about 90 posts/s on a T4 GPU.
Options
ex = LocationExtractor(
model_dir=..., gazetteer_dir=...,
hashtag_mentions=None, # None (default) | "exact" (#Gaza) | "partial" (#PrayForGaza too)
min_model_score=0.5, # drop low-confidence mention spans
dominance_ratio=10.0, # choose by population only if 10x bigger than every alternative ...
min_dominant_pop=20_000, # ... and at least this many people
)
ex.extract(
texts, # list[str]
profile=False, # True (or list[bool]) when the text is a user's profile location field
context_countries=None, # per text, e.g. [["EG"], ["QA"]]: country of the monitored topic (breaks ties only)
batch_size=32,
)
Output
extract() returns one dict per text:
{
"text": "حريق في المطرية بالقاهرة",
"locations": [
{
"original_mention": "المطرية", "start": 8, "end": 15,
"detected_by": "model", "detection_score": 0.97, "predicted_type": "DISTRICT",
"resolution_status": "resolved",
"decided_by": "context",
"confidence": 0.92,
"location_role": "mentioned",
"place_id": "gn:360985", "entity_type": "district",
"normalized_name": "Al Matariyah", "normalized_name_ar": "المطرية",
"country": "Egypt", "country_ar": "مصر", "country_code": "EG",
"state": "Cairo", "county": null, "city": "Cairo", "city_ar": "القاهرة",
"district": "Al Matariyah", "landmark": null,
"latitude": 30.13, "longitude": 31.31,
"country_inferred": true, "spelling_corrected": false, "matched_by": "exact"
}
],
"places": [{"place_id": "gn:360985", "name": "Al Matariyah", "country_code": "EG", "level": "district",
"mentions": ["المطرية"], "roles": ["mentioned"]}],
"author_location": null
}
(Values are illustrative.)
| Field | Values |
|---|---|
resolution_status |
resolved · country_only (country certain, city not) · ambiguous (see candidates) · unresolved (not in gazetteer) |
decided_by |
single_candidate · context (other places in the text) · country_name · population (one candidate ≥10× bigger) · same_country · street_in_context · single_small · contradicts_context |
location_role |
mentioned · author ("أنا من…", "I live in…") · origin (from / من) · destination (to / إلى) · negated ("not Greece") |
detected_by |
model · flag (🇶🇦) · coordinates · country_code (TR, KSA) · abbreviation · stretched_word (Doooha) · hashtag |
entity_type |
region · country · state · county · city · district · street · poi · natural |
candidates |
ranked alternatives (name, level, country, population, score) for ambiguous / population / country-only decisions |
places |
one record per real place: "Doha, Qatar, الدوحة" counts Doha once |
author_location |
from a self-statement, or from a profile field when profile=True |
to_rows(results, ids=post_ids) flattens the output to one row per mention, ready to insert into a database.
For maps: count resolved and country_only at country level, and resolved with a city at city level. Exclude negated.
Keep mentioned places and author locations as separate layers.
How it works
Mention detection. A fine-tuned XLM-RoBERTa base token classifier (Arabic + English, 8 location types), plus rules for flag emoji, decimal and degree coordinates, ISO and US-state codes, common city and airport codes (NYC, LA, DXB, DOH, RUH, JED, CAI…), stretched words, and optionally hashtags.
Lookup. A gazetteer of place names in Arabic and English. Lookup handles:
- Arabic clitics: بالقاهرة، وللدوحة، لل…
- hashtags and CamelCase:
#PuertoRico,حفر_الباطن - transliteration: Al Qahira ↔ Al Qahirah, Al Sadd ↔ As Sadd
- possessives: "Greece's"
- careful spelling correction: Istambul → Istanbul
- generic words: منطقة، محافظة، City, Street
Disambiguation, in this order:
- countries and places named elsewhere in the same text, including hashtags and the states/cities of already-resolved places;
- an optional topic country (
context_countries); - a country's own name (قطر, Italy);
- clear population dominance (≥10×).
If none of these decides, the mention is ambiguous, with candidates. If all close candidates are in one country, the result is country only. A small place that contradicts the text's countries is not accepted.
Hierarchy. Each resolved place is expanded to country / state / county / city / district / landmark in English and Arabic. City districts are linked to the largest city around them.
Repository layout
model/ fine-tuned XLM-R location-mention model (transformers format)
gazetteer/ places.parquet, aliases.parquet, LICENSE.md (ODbL)
code/ marsad_location.py the library (LocationExtractor, Gazetteer, to_rows)
LOCATION_HANDOFF.md integration guide (MARSAD / any backend)
marsad_location_schema.sql PostgreSQL / Supabase tables + map queries
location_enrich_example.py template batch job
eval/ summary.csv, use_cases.csv evaluation results
scripts/ step1 → step4 Colab cells to rebuild everything (see below)
Training
| Base model | FacebookAI/xlm-roberta-base |
| Task | token classification, BIO tags, 8 types: country, state, city, district, street, POI, continent, other |
| Data | IDRISI-R / IDRISI-RA gold LMR (time-based split): 3,696 Arabic + 16,448 English disaster tweets (7 Arabic and 19 English events), 21,719 location mentions |
| Splits | official dev → test; new dev = 10% of train per event; duplicates and train/test overlaps removed |
| Settings | 6 epochs (early stopping), lr 3e-5, batch 16, max length 256, Arabic training tweets repeated ×3, best epoch by the mean of Arabic and English dev F1 |
Mention detection (LMR test set, span F1)
| Exact, typed | Exact, untyped | Partial overlap | |
|---|---|---|---|
| Arabic | 0.804 | 0.841 | 0.919 |
| English | 0.807 | 0.868 | 0.906 |
An Arabic-only MARBERTv2 model scored the same on Arabic (0.804 / 0.837 / 0.908), so one multilingual model is used.
Full-pipeline evaluation
Tested on IDRISI-LMD tweets not used in training (744 Arabic, 1,261 English), whose gold places are OpenStreetMap points. For a fair test, the OpenStreetMap names harvested from LMD were switched off in the gazetteer.
| Metric | Arabic | English |
|---|---|---|
| Model span precision | 0.907 | 0.857 |
| Mentions found (recall) | 0.94 | 0.93 |
| Country correct (resolved + country only) | 0.952 | 0.967 |
| Within 25 km of the true place (city level) | 0.755 | 0.840 |
| Within 161 km | 0.931 | 0.887 |
| Median distance error | 7.2 km | 1.3 km |
| Unresolved | 6.2% | 8.2% |
| End-to-end: mention found and country correct | 0.803 | 0.799 |
Measured before the last tuning round. See eval/summary.csv for the latest run.
The requirement use cases (country/city/code recognition, spelling, coordinates, Arabic, transliteration,
ambiguity, roles, negation…) are in eval/use_cases.csv.
Limitations
- No country signal in the text. "الزرقاء" in an Egyptian storm post resolves to Zarqa, Jordan, because it is
the bigger place. Pass the topic's country through
context_countrieswhen it is known. - Arabic names for small towns in the Maghreb, Sudan and Somalia are sparse in GeoNames. Big cities are covered.
- Natural features and landmarks outside the Arab world (islands, rivers, buildings) are only partly covered.
- Event location vs. mentioned location ("BBC reports flooding in Pakistan") and cross-post inference are not modelled. A later LLM step for ambiguous / low-confidence cases is the natural extension.
- Training domain: disaster tweets. Expect some drop on other topics and dialects.
- Disputed places follow GeoNames, e.g. Arabic "القدس" → East Jerusalem (PS), English "Jerusalem" → IL.
- Author location comes only from explicit self-statements or profile fields. It is not inferred from dialect or writing style.
Rebuilding (scripts/)
Colab cells, run in order (paths point to a Google Drive folder; adjust ROOT):
step1_prepare_idrisi.py: clean, de-duplicate and split IDRISI-LMR (Arabic + English) into BIO files.step2_train_lmr.py: train XLM-R (and the MARBERTv2 comparison) and report span F1.step3_build_gazetteer.py: build the gazetteer from GeoNames (countries, admin1/admin2, towns ≥1,000 people, full Arab-country files with landmarks), world-cities-translations, curated aliases and IDRISI-LMD OpenStreetMap names.step4_evaluate_pipeline.py: full-pipeline evaluation and use cases.
Step 3 can optionally use two extra Arabic name sources. Neither is included in the published gazetteer (see licences below):
locations.dbfrom AbdelrahmanBayoumi/LocationsDB (GPL-3.0, data from MuslimMateAndroid)- an Arabic countries-states-cities JSON (licence not confirmed)
Licences
| Part | Licence |
|---|---|
code/, scripts/ |
MIT |
model/ |
CC BY 4.0 (fine-tuned from XLM-R base, MIT; trained on IDRISI, CC BY 4.0) |
gazetteer/ |
ODbL 1.0, because it contains OpenStreetMap-derived names. See gazetteer/LICENSE.md |
Data attribution: GeoNames (CC BY 4.0) · © OpenStreetMap contributors (ODbL) · world-cities-translations / Wikidata (CC BY 4.0) · IDRISI-R / IDRISI-RA (CC BY 4.0). Not included: LocationsDB (GPL-3.0) and the Arabic countries-states-cities JSON (licence unconfirmed).
Citation
If you use this work, please cite the training data and base model:
@inproceedings{suwaileh-etal-2023-idrisi,
title = {{IDRISI}-{RA}: The First {A}rabic Location Mention Recognition Dataset of Disaster Tweets},
author = {Suwaileh, Reem and Elsayed, Tamer and Imran, Muhammad},
booktitle = {Proceedings of the 61st Annual Meeting of the Association for Computational Linguistics (ACL)},
year = {2023},
url = {https://aclanthology.org/2023.acl-long.901}
}
@inproceedings{conneau-etal-2020-unsupervised,
title = {Unsupervised Cross-lingual Representation Learning at Scale},
author = {Conneau, Alexis and Khandelwal, Kartikay and Goyal, Naman and Chaudhary, Vishrav and Wenzek, Guillaume and
Guzm{\'a}n, Francisco and Grave, Edouard and Ott, Myle and Zettlemoyer, Luke and Stoyanov, Veselin},
booktitle = {Proceedings of ACL},
year = {2020}
}
The English IDRISI-R dataset paper is listed in the IDRISI repository.
Author
Md. Rafiul Biswas, Hamad Bin Khalifa University (HBKU), Qatar. Part of the MARSAD social-media observatory.
Model tree for rafiulbiswas/marsad-location
Base model
FacebookAI/xlm-roberta-base