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
Download code/location_enrich_example.py from rafiulbiswas/marsad-location: direct link, hf CLI and curl.
- Browser
- Download file 4.22 kB
-
https://huggingface.co/rafiulbiswas/marsad-location/resolve/main/code/location_enrich_example.py
- Command line
-
hf download hf://rafiulbiswas/marsad-location/code/location_enrich_example.py
-
curl -L -o location_enrich_example.py https://huggingface.co/rafiulbiswas/marsad-location/resolve/main/code/location_enrich_example.py
4.22 kB
| """ | |
| Template: enrich MARSAD posts with locations. ADAPT the three marked functions to MARSAD's DB layer. | |
| MARSAD_LOC_MODEL=/opt/marsad/location/model MARSAD_LOC_GAZ=/opt/marsad/location/gazetteer python location_enrich_example.py | |
| """ | |
| import os, json, math | |
| from marsad_location import LocationExtractor, to_rows | |
| MODEL_VERSION = 'loc-xlmr-v1+gaz-2026-11-29' | |
| BATCH = 64 | |
| # ---------------------------------------------------------------- ADAPT: database access | |
| def fetch_unprocessed_posts(limit): | |
| """return list of dicts: {id, text, topic_id, topic_countries (list of ISO codes or []), user_id}""" | |
| raise NotImplementedError | |
| def save_rows(table, rows): | |
| """bulk upsert rows (list of dicts) into a table, e.g. supabase.table(table).upsert(rows).execute()""" | |
| raise NotImplementedError | |
| def place_exists(place_id): | |
| raise NotImplementedError | |
| # ---------------------------------------------------------------- | |
| ex = LocationExtractor(model_dir=os.environ['MARSAD_LOC_MODEL'], gazetteer_dir=os.environ['MARSAD_LOC_GAZ'], | |
| exclude_sources=(), hashtag_mentions='exact') | |
| gz = ex.gz | |
| def place_row(pid): | |
| i = gz.idx[pid] | |
| h = gz.hierarchy(i) | |
| clean = lambda v: None if (isinstance(v, float) and math.isnan(v)) else v | |
| return dict(place_id=pid, level=gz.level[i], name_en=gz.name_en[i], name_ar=gz.name_ar[i], | |
| country_code=h['country_code'], country_name=h['country'], state_name=h['state'], city_name=h['city'], | |
| parent_id=gz.ids[gz.parent[i]] if gz.parent[i] is not None else None, | |
| lat=clean(gz.lat[i]), lon=clean(gz.lon[i]), population=int(gz.pop[i])) | |
| def run_once(): | |
| posts = fetch_unprocessed_posts(BATCH) | |
| if not posts: | |
| return 0 | |
| res = ex.extract([p['text'] for p in posts], batch_size=32, | |
| context_countries=[p.get('topic_countries') or [] for p in posts]) | |
| loc_rows, user_rows, new_places = [], [], {} | |
| for p, r in zip(posts, res): | |
| for l in r['locations']: | |
| if l.get('place_id') and l['place_id'] not in new_places and not place_exists(l['place_id']): | |
| new_places[l['place_id']] = place_row(l['place_id']) | |
| loc_rows.append(dict( | |
| post_id=p['id'], topic_id=p.get('topic_id'), mention=l['original_mention'], | |
| start_char=l['start'], end_char=l['end'], detected_by=l['detected_by'], | |
| detection_score=l['detection_score'], predicted_type=l['predicted_type'], | |
| resolution_status=l['resolution_status'], decided_by=l.get('decided_by'), | |
| confidence=l['confidence'], location_role=l['location_role'], place_id=l.get('place_id'), | |
| entity_type=l.get('entity_type'), country_code=l.get('country_code'), country=l.get('country'), | |
| state=l.get('state'), county=l.get('county'), city=l.get('city'), district=l.get('district'), | |
| landmark=l.get('landmark'), name_ar=l.get('normalized_name_ar'), | |
| latitude=l.get('latitude'), longitude=l.get('longitude'), | |
| country_inferred=l.get('country_inferred'), spelling_corrected=l.get('spelling_corrected'), | |
| candidates=json.loads(json.dumps(l.get('candidates'), ensure_ascii=False)) if l.get('candidates') else None, | |
| model_version=MODEL_VERSION)) | |
| a = r['author_location'] | |
| if a and p.get('user_id'): | |
| user_rows.append(dict(user_id=p['user_id'], country_code=a['country_code'], country=a['country'], | |
| city=a['city'], evidence=a['evidence'], | |
| confidence=0.9 if a['evidence'] == 'self_statement' else 0.85, | |
| model_version=MODEL_VERSION)) | |
| if new_places: | |
| save_rows('geo_places', list(new_places.values())) | |
| if loc_rows: | |
| save_rows('post_locations', loc_rows) | |
| if user_rows: | |
| save_rows('user_locations', user_rows) # ADAPT: keep the strongest evidence per user | |
| # also mark these posts as processed for MODEL_VERSION (ADAPT) | |
| return len(posts) | |
| if __name__ == '__main__': | |
| total = 0 | |
| while (n := run_once()): | |
| total += n | |
| print('processed', total) | |