""" 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)