
For a long time, I wanted to build something that would make Moroccan political information easier to explore. I started experimenting with the idea in 2025, set it aside, and returned to it in 2026.
Barlaman comes from برلمان, the Arabic word for parliament. Open Barlaman aims to make Moroccan political information easier to explore, starting with parliamentary activity.
Under the Moroccan constitution, the parliament of Morocco is made up of two houses:
- The House of Representatives (Majlis An-Nuwab - مجلس النواب): Composed of 395 members elected directly by universal suffrage.
- The House of Councillors (Majlis Al-Mustasharin - مجلس المستشارين): Composed of between 90 and 120 members elected indirectly, representing local authorities, professional chambers, professional organisations of employers, and wage-earners.
Parliament passes laws, scrutinises government action, and evaluates public policies. For the beta, I focused on parliamentary questions because the records were accessible and provided a useful foundation for connecting members, ministries, topics, and places.
The information is public, but spread across websites, spreadsheets, and PDFs. Finding a question is often possible. Connecting it to its author, the addressed ministry, an answer, or the places it discusses takes more work.
Open Barlaman brings those records together. It lets people browse representatives and councillors, read their questions, and explore the subjects and places they discuss. The first question archive grew to roughly 72,000 records across both chambers.
This article explains how I built it: designing the database, collecting inconsistent records, extracting Arabic text, using LLMs for classification, and connecting questions to maps. It also covers the approaches that failed and the changes they led to.
Before we proceed, I want to clarify that the built platform here is still in its early stage; Open Barlaman is currently a beta. Its coverage and features are still evolving, and corrections are welcome through the site’s reporting feature.
Table of contents
- Data sources
- Getting the data model right
- Collecting and extracting the data
- Understanding questions with LLMs
- Putting questions on the map
- Making the beta useful
- What comes next
Data sources
There was no single dataset containing everything the project needed. Each source had a different role:
Public sources
Moroccan public institutions already publish substantial parliamentary information, including questions, session reports, and member profiles. The coverage and formats vary, but these sources provided the foundation for the project.
- House of Representatives: It contains key info about member profiles, constituencies, parliamentary groups, and published election results.
- House of Councillors: Member directory, groups, committees, and parliamentary documents.
- Ministry in charge of Relations with Parliament: It acts as a centralised place for most of the parliamentary documented activities; oral and written question listings, authors, ministries, PDFs, and lifecycle events.
- data.gov.ma: an open data platform created by the government which contains some historical data.
- HCP’s RGPH 2024 dashboard: this is the main source for all geographical data, administrative names, codes, population data, and map layers.
The Tafra Project

I also want to highlight a valuable project that was built by a Moroccan association Tafra; an encyclopaedia of Moroccan parties. They have done a lot of valuable work which has helped me and inspired me in this work. In 2025, I spoke with Karim El Hajjaji, one of Tafra’s co-founders, and learned from their experience. They have worked on some remarkable projects, like a historical tree tracing the history of Moroccan parties, SMIG data, and other interesting projects.

Combining these sources required a data model that could connect records while preserving their provenance.
Getting the data model right
I started with six concepts: parties, representatives, questions, regions, provinces, and communes. My two earlier prototypes provided useful data and code, but overlapping models and repeated names made records difficult to connect reliably.
The main decision was to separate people from their parliamentary mandates. A person can serve several terms, leave Parliament, or return later. Their questions stay attached to the mandate during which they asked them, preserving their activity after they leave.
Party affiliations and parliamentary group memberships are also separate, dated relationships. This preserves changes over time. Electoral alliances needed their own records too: being elected through an alliance does not establish membership in one of its parties.
It is important to note, that while this setup exists in the project, the features are not fully used for the beta version. For example, currently the project doesn’t support the political history of a given person, as the project hasn’t backfilled the historical political data.
Each question stores its term, type, subject, date, and addressed ministry. An authorship table connects it to one or more members or a named parliamentary group. Documents are stored separately, while dated events preserve its progress from receipt to a recorded answer.

Geography follows the hierarchy region → province/prefecture → commune. Electoral constituencies are separate because their boundaries do not always match administrative areas. The places discussed in a question are also separate from its author’s constituency: a member can ask about another area or a national issue.
Source records sit alongside this structure, preserving the original information, its URL, retrieval date, and content hash. This keeps the application’s organised records connected to their supporting evidence and makes later corrections traceable.
Collecting and extracting the data
With the model in place, I collected the data through Python crawlers, spreadsheet imports, and document extraction. Each source supplied a different piece of the platform.
Building the party catalogue from Tafra
Tafra’s encyclopaedia of Moroccan parties provided a valuable starting point. I used it to build the party catalogue, then supplemented the records with names, acronyms, logos, electoral symbols, and information from official party websites.
Some entries needed updating to reflect later political changes. One example was the Federation of the Democratic Left (FGD), which became a unified party following its December 2022 merger congress. I adjusted the catalogue accordingly, taking care to distinguish merged parties from electoral alliances.
I have to mention here that there are still a lot of missing info in the party profile pages.
Extracting parliamentary profiles
I collected published names, constituencies or electoral bodies, parliamentary groups, and available committee memberships, along with the original page URLs for both House of Representatives and House of Councilors.
Collecting questions from both chambers

An early experiment downloaded PDFs by their numeric URLs. The Ministry in charge of Relations with Parliament offered a better starting point: its searchable registry connected questions to their authors, addressed ministries, documents, and dated status changes.
A solution walked through the oral and written question listings, opened detail pages, saved the metadata and lifecycle events, and downloaded the attached PDFs. Identifiers were scoped by chamber, legislative term, and question type because numeric IDs could overlap.
Long crawls needed to survive interruptions. A small SQLite database tracked progress, while PostgreSQL stored the parliamentary records. Retries handled temporary failures, and reruns skipped completed work without duplicating questions. Questions with unmatched authors were still saved for later reconciliation.
Using government open-data spreadsheets

The government’s open-data portal supplied an elected-members spreadsheet and oral and written question workbooks. These complemented the live directories and, for many questions, provided cleaner Arabic text than PDF extraction.
The member spreadsheet required careful reconciliation: its Arabic and French sheets had different row counts. An early positional match assigned some incorrect French names after an extra row shifted the alignment. I corrected the matching logic using shared identifying information.
For question text, I matched rows from the question workbooks to existing records by legislative term, question type, and published number, then checked subject compatibility. Conflicting or ambiguous matches remained unresolved. This supplied usable text for many questions and reduced the work requiring OCR.
Cross-checking also exposed errors in official sources: some PDF links returned unrelated documents, and a spreadsheet body contained #NAME?. I excluded those faulty inputs from analysis while preserving the originals.
Extracting Arabic text from PDFs: extraction and OCR

Some PDFs had an embedded text layer; others were scans. Even selectable Arabic text could contain broken words or scrambled reading order.
I first used PyMuPDF and Poppler for direct extraction, with Tesseract as an OCR fallback. Tesseract struggled on some documents, mixing Latin noise into Arabic, losing words, and extracting incomplete sections. Simple quality scores sometimes still rated the output highly.
I tried DeepSeek, local Qwen2.5-VL through Ollama, and Gemini on sample documents. Gemini 2.5 Flash-Lite became the fallback used in the processing pipeline after a 100-document comparison, with an HTML page for inspecting transcriptions side by side.
The resulting approach was selective:
- Compare PyMuPDF and Poppler output, using an 85% similarity threshold and matching page counts to route direct extraction.
- Keep accepted native text.
- Render fallback documents as page images and transcribe them with Gemini through OpenRouter. The used prompt can be found the open barlaman artefacts repository.
- Store the text, extractor, model, hash, and usage metadata.
This avoided paying to transcribe documents with usable text. OCR and classification stayed separate, so changing the categories would not require processing the images again.
The spreadsheet text described above later reduced the number of documents requiring OCR, particularly for House of Representatives questions.
Gemini 2.5 Flash-Lite was among the cheapest models I tested for this task. At the time, Google restricted access to users who had previously used it. I did not have access, so I used OpenRouter, where the model remained available.
Extracting geographic boundaries from HCP
I first reused OpenStreetMap boundaries from an earlier prototype, but their extraction date was unknown. For a newer reference, I turned to the RGPH 2024 dashboard from HCP, Morocco’s High Commission for Planning. It provides maps and statistics from the 2024 population and housing census.

The dashboard let me browse regions, provinces, and communes, but I needed their boundaries for my own maps. Inspecting the browser’s network requests revealed vector tiles: small geographic pieces containing shapes, administrative codes, and Arabic and French names.
A boundary could span several tiles, and its coordinates were relative to each tile. Downloading the files was therefore only the first step. I built a Python extraction pipeline with the help of AI:
- Download and cache the tiles covering the dataset’s geographic extent, at zoom level 7.
- Decode them with mapbox-vector-tile and convert their coordinates to longitude and latitude.
- Group boundary fragments by administrative code and merge them with Shapely.
- Export the reconstructed shapes and their names as GeoJSON, a standard format for geographic data.
The resulting files contained 12 regions, 75 provinces, and 1,540 commune features. I checked unique codes, valid shapes, and the administrative hierarchy before importing them into PostgreSQL.
I also compared the commune names with the dashboard’s population export. Its 1,539 rows matched the extracted Arabic and French names; the additional map feature, Méchouar de Casablanca, had no corresponding population row.
These boundaries support the platform’s region → province → commune navigation. They are simplified shapes reconstructed from the dashboard’s tiles, so I document their source and extraction zoom rather than presenting them as a full-resolution GIS dataset.
The used geospatial data is fully open sourced in this GitHub repository
Understanding questions with LLMs
Extracting text made the questions searchable, but I also wanted to explore what they discussed. I used LLM to identify topics, stated problems, explicit requests, affected populations, and mentioned places or institutions.
I first defined a taxonomy; a fixed list of categories. This separated the subject, such as healthcare, from the problem, such as a staff shortage, and the request, such as providing more doctors. The addressed ministry alone could not reliably establish the topic.
The full list of the used taxonomy can be found in the open repo of open barlaman.
Comparing the models
I built a benchmark of ten questions: four short oral questions and six longer written ones. Within each comparison, the models received identical texts, instructions, and categories. I tested Luna, GPT-4o-mini, DeepSeek, Qwen, and several Gemini versions through OpenRouter, saving their responses, validation results, token usage, and costs.
The comparisons exposed different failures: truncated responses, invented category codes, missing requests, and plausible details unsupported by the text. Gemini’s first responses also contained JSON inside Markdown fences, which the parser initially rejected. That was a formatting failure, separate from classification quality.
Gemini 3.5 Flash-Lite became my choice for bulk processing, balancing cost and useful results. The small benchmark helped identify weaknesses and refine the prompt; it did not establish a definitive accuracy ranking.
Here, I have to admit that I didn’t spend much time thinking about the right model. My choice here can be easily questioned; I’m sure that there might be cheaper and more performant LLM models for this type of task. But Gemini here seemed to did a good job from the simple benchmark and I didn’t want to lock myself in an LLM loop.
Classifying 72,039 questions generated approximately 182.7 million input tokens and 8.4 million output tokens. Using Gemini 3.5 Flash-Lite’s Batch API, this represents an estimated cost of $38, or about $0.53 per 1,000 questions, excluding OCR and earlier experiments.
Choosing a compact output format
The first prompt requested detailed JSON with nested objects, explanations, and supporting quotations. For the filters and charts, I eventually chose a simpler response: one labelled line per field, fixed category codes, and NONE for missing information.
For an illustrative question explicitly requesting more doctors to treat patients at a local hospital:
SUMMARY: نقص الأطباء في مستشفى محلي وطلب تعزيز الأطر الطبية.
SCOPE: LOCAL
TOPICS: HEALTH
PROBLEMS: STAFF_SHORTAGE
REQUESTS: PROVIDE_RESOURCES
POPULATION_CATEGORIES: PATIENTS
PLACES: NONE
PROGRAMS_ENTITIES: NONE
This made responses shorter and straightforward to parse. In an early compact-output trial, the ten responses used about 600 output tokens, compared with roughly 7,500 for the richer JSON version. The saving also came from requesting fewer details: the compact format dropped per-category evidence quotations. It was a practical trade-off for bulk classification.
Python parses these lines, checks category codes against the allowed lists, and stores the fields alongside the model, prompt version, and original response. Format validation remains separate from checking whether the interpretation is correct.
The used prompts can be found in the open barlaman repo.
Processing the archive
I submitted the archive through Google’s Batch API, which processes requests asynchronously at a reduced cost. My pipeline grouped requests into files of 2,000 questions and tracked submission, download, and import progress so interrupted runs could resume.
Those batch files still use JSONL; one JSON request per line. The compact text format applies to the classification generated inside each response.
Putting questions on the map

With the boundaries ready, the next step was to identify the places mentioned in each question and link them to the geographic catalogue.
Python scans the question text for administrative names introduced by words such as جماعة (commune), إقليم (province), or جهة (region). Arabic normalisation handles spelling and spacing variations, while verified aliases connect alternative names to the geographic catalogue.
Matched places become stored links between questions and geographic records. These links power the maps rendered with D3 and let readers explore questions through the region → province → commune hierarchy.
When matching went wrong
A question about road safety in Tata appeared under Marrakech-Safi. It mentioned جماعة سيدي عبد الله بن مبارك, but the matcher selected جماعة سيدي عبد الله, a different commune in Rehamna. The shorter name matched exactly, but it was only the beginning of the place actually mentioned.
I tightened the rules to prefer the longest complete name and check the province associated with each mention. This matters because some communes share names, and a question can discuss several provinces. A province mentioned elsewhere in the text cannot automatically resolve every commune.
The broader correction process used complete names and verified aliases rather than fuzzy guesses. I also reviewed existing links and rebuilt the map counts: fixing the matcher alone would have left earlier mistakes in the database. Rejected links remained stored for traceability.
The approach favours precision over coverage. Unfamiliar names, and missing context can leave places unresolved. The maps therefore show the geographic mentions the pipeline can identify, rather than every place a question might concern.
Making the beta useful

The beta connects the data through member profiles, searchable questions, topic exploration, and maps. A reader can start with a representative, browse their questions, explore a subject, or find questions mentioning a particular place.
Question counts describe activity in the collected records. They do not, on their own, measure a member’s effectiveness or the importance of an issue. Topic classifications are machine-generated, and geographic counts include only places the matching pipeline could identify.
The interface uses Darija; Moroccan Arabic, and RTL layouts. Question pages link back to their sources, and a correction-reporting feature lets readers flag mistakes.
The frontend uses Next.js and TypeScript, while FastAPI and SQLAlchemy provide access to PostgreSQL. Python handles collection and processing, and Alembic manages database schema changes.
As the archive grew, performance became another challenge. Recalculating statistics on every visit and making repeated database queries for each member slowed browsing. I changed the dashboards to read previously calculated snapshots stored in PostgreSQL and made directory queries fetch related records together.
Question lists filter and paginate directly in SQL, returning only the requested page. Maps reuse stored geographic links and counts. After data changes, processing steps rebuild these results; transactional updates keep the previous results available if a rebuild fails.
I checked repeat imports, matching rules, and aggregate consistency alongside frontend type checks and builds. These checks helped ensure that profiles, question lists, and maps presented consistent results as the pipeline evolved.
I used Codex extensively for implementation, especially the frontend, while making the architectural and design decisions myself.
What comes next

The beta is a starting point. I hope to build a community that can maintain the platform and extend its coverage. The roadmap outlines the next steps and longer-term ambitions:
- Fully automating the extractions: right now, the beta contains snapshotted data up till the end of September 2026.
- Track legislation: Connect bills and proposals to their versions, amendments, committee reviews, and recorded votes.
- Follow committee work: Organise meetings, reports, amendments, and documented member participation.
- Analyse debates and voting: Explore discussed topics, member interventions, and parliamentary group voting patterns.
- Expand historical coverage: Integrate earlier elections, mandates, questions, and parliamentary records, including Tafra datasets.
- Cover local elections: Prepare coverage for 2027, connecting results to candidate lists, parties, and communes.
- Explore political journalism: Track coverage of topics and parties, distinguishing reporting from opinion through documented methods.
- Publish reusable datasets: Release extracted records and analyses with sources, processing methods, update dates, and limitations.
- Build a community: Establish an organisation in Morocco to support contributions, partnerships, and activities.
The project at this stage might look too optimistic, but I have a strong belief that there are a lot of passionate Moroccans that are eager to contribute to such a project and help it to grow further. If you’re one of them, feel free to join us!