Bidhanshala

Bidhanshala (বিধানশালা) - Bangladesh law, in one place

Bidhanshala answers questions about Bangladesh law using retrieval-augmented generation. Law documents (PDF/CSV) from the Data/ folder are embedded into Pinecone, and an Ollama model answers from the retrieved passages, with the source shown for every answer.

Features

Project structure

app.py              Flask JSON API + serves the built React app
src/helper.py       document loading, Pinecone and Ollama helpers
src/prompt.py       prompts for chat and the legal tools
src/ocr.py          reads scanned PDFs and photos with Tesseract
store_index.py      builds the Pinecone index from Data/
sync_laws.py        checks the official website for new and amended laws
src/law_sync.py     official website sync logic
src/database.py     SQLite schema and connection
frontend/           React + Vite + Tailwind user interface
Data/               law documents (PDF/CSV)

Configuration

Create a .env file in the project root (never commit it):

SECRET_KEY=replace-with-a-long-random-value
PINECONE_API_KEY=your-pinecone-key
PINECONE_INDEX_NAME=lawbot-multi
OLLAMA_MODEL=gemma3:12b
OLLAMA_BASE_URL=http://localhost:11434
OLLAMA_TEMPERATURE=0.2

Optional: DATA_DIR, DATABASE_PATH, FRONTEND_DIST, RETRIEVAL_K, MAX_TEXT_LENGTH, OLLAMA_MAX_TOKENS, EMBEDDING_MODEL (default paraphrase-multilingual-MiniLM-L12-v2, so Bangla questions match English law text), LAW_SYNC_DELAY (seconds between requests to the official site, default 2), LAW_SYNC_RECENT_YEARS (default 1), LAW_SYNC_AUTO=0 (turn off the automatic check; it runs when no check has succeeded for LAW_SYNC_DAYS, default 30, and waits LAW_SYNC_RETRY_HOURS, default 24, after a failed one), SESSION_COOKIE_SECURE=1 (when served over HTTPS).

Hosted LLM (for servers that cannot run Ollama): set LLM_PROVIDER=openai, LLM_API_KEY and LLM_MODEL (default gpt-4o-mini). Any service with an OpenAI-style API works through LLM_BASE_URL, for example Gemini (https://generativelanguage.googleapis.com/v1beta/openai/) or Groq (https://api.groq.com/openai/v1). Without LLM_PROVIDER the app uses Ollama.

Rate limits: login 10 per 15 minutes and registration 5 per hour for each IP address, the contact form 5 per hour, and chat plus the AI tools AI_REQUESTS_PER_10_MIN (default 30) for each user. Set TRUST_PROXY=1 behind a proxy that sends X-Forwarded-For (PythonAnywhere does) and RATE_LIMITS=0 to switch them off.

OCR: a PDF with almost no text layer, or an image upload, is read with Tesseract. TESSDATA_DIR points at a folder with ben.traineddata and eng.traineddata, TESSERACT_CMD at the binary if it is not on PATH. OCR_LANGUAGES (default ben+eng) and OCR_MAX_PAGES (default 20) are optional. Without Tesseract the rest of the app works and scanned uploads get a clear error.

Running locally

  1. Backend (Python 3.10+):

    python -m venv .venv
    source .venv/bin/activate        # Windows: .venv\Scripts\activate
    pip install -r requirements.txt
    python store_index.py            # first time only, builds the Pinecone index
    python app.py                    # http://localhost:8080
    
  2. Ollama must be running with the model pulled: ollama pull gemma3:12b (about 8 GB; llama3.2 works on smaller machines but its Bangla is weak).

    Optional, for scanned files: install Tesseract (Windows: winget install UB-Mannheim.TesseractOCR, Linux: apt install tesseract-ocr), then put the Bangla model in a folder with the English one and set TESSDATA_DIR to it:

    mkdir -p instance/tessdata
    curl -L -o instance/tessdata/ben.traineddata https://raw.githubusercontent.com/tesseract-ocr/tessdata_best/main/ben.traineddata
    curl -L -o instance/tessdata/eng.traineddata https://raw.githubusercontent.com/tesseract-ocr/tessdata_best/main/eng.traineddata
    
  3. Frontend:

    cd frontend
    npm install
    npm run dev                      # http://localhost:5173, /api is proxied to Flask
    

    For production run npm run build; Flask then serves frontend/dist at /.

Tests

The API tests use a temporary database and stand-ins for the LLM and Pinecone, so they run offline in a few seconds:

pip install -r requirements-dev.txt
python -m pytest

Deploying for free (Render)

The Dockerfile builds the frontend, installs Tesseract (Bangla and English), builds a slim copy of the search model and runs the app with Gunicorn. The answers come from a hosted LLM; Gemini’s free tier is the default.

Render’s free plan gives 512 MB of memory. The full multilingual search model needs about 800 MB, so the image uses a slim ONNX copy (src/slim_model.py, about 150 MB) that keeps only the Bangla, ASCII and law-library pieces of its vocabulary. Library text, Bangla and English give the same vectors as before, so the existing Pinecone index still works. After adding many new laws to Data/, refresh the list with python -m src.slim_model scan Data.

  1. Sign up at render.com with GitHub and create an API key (Account settings > API keys). Create a Hugging Face write token for the database backup and a Gemini API key from Google AI Studio.
  2. Add to .env:

    RENDER_API_KEY=...
    HF_TOKEN=...
    SPACE_LLM_API_KEY=...            # the Gemini key
    SPACE_ADMIN_USERNAMES=your-name  # these accounts become admins when they register
    

    SPACE_LLM_MODEL (default gemini-3.5-flash-lite) and SPACE_LLM_BASE_URL switch to another provider. Pinecone settings are read from the same file.

  3. Push to GitHub, then run python deploy_render.py. It creates the private backup dataset and a free Docker web service in Singapore, sets its settings and starts a build, which takes about 10 minutes. Later pushes to main redeploy on their own.
  4. Open the onrender.com address it prints and register the admin account.

Limits of the free plan: the site sleeps after 15 minutes without visitors and takes about a minute to wake, and 0.1 CPU makes large uploads slow to index. It has no persistent disk, so the database (accounts, chats, lawyers, messages, law-update list) is kept in a private Hugging Face dataset, <HF_SPACE>-data or <your-name>/bidhanshala-data by default. The app restores it on start and uploads a copy every DB_BACKUP_MINUTES (default 10) when something changed, and once more on shutdown; changes made in the last few minutes before a crash can be lost. The deploy script creates the dataset as private and stops if it is public. For a narrower key, set SPACE_BACKUP_TOKEN to a fine-grained token that can only write that dataset. The law library itself lives in Pinecone.

deploy_space.py puts the same image on Hugging Face Spaces instead, but Docker Spaces need a Hugging Face PRO plan.

To try the image locally: docker build -t bidhanshala . then docker run -p 7860:7860 --env-file .env bidhanshala. Docker reads .env literally: write NAME=value with no spaces or quotes, and point LLM_BASE_URL at a hosted LLM (or at http://host.docker.internal:11434/v1 for Ollama on the same machine).

Deploying (PythonAnywhere)

Needs a paid plan: the free one has too little disk for the embedding model and blocks Pinecone and the official law site.

  1. In a Bash console: clone the repository, create a virtualenv and install the packages. Install CPU-only PyTorch first to save disk space:

    pip install torch --index-url https://download.pytorch.org/whl/cpu
    pip install -r requirements.txt
    
  2. Run npm run build on your own machine and upload frontend/dist (it is not in git).
  3. Create .env in the project folder with SECRET_KEY, PINECONE_API_KEY, PINECONE_INDEX_NAME, the hosted LLM settings above, SESSION_COOKIE_SECURE=1 and TRUST_PROXY=1. Keep DATABASE_PATH and DATA_DIR under /home/<username>/. For OCR, check tesseract --version in a Bash console, download the two .traineddata files as in “Running locally” into ~/tessdata and set TESSDATA_DIR=/home/<username>/tessdata.
  4. Web tab: add a web app with manual configuration, set the virtualenv, and make the WSGI file import application from this project’s wsgi.py. Turn on “Force HTTPS”.
  5. Tasks tab: add a daily task that only does the law check on the first of the month:

    [ "$(date +\%d)" = "01" ] && cd ~/Law-Assistant && .venv/bin/python sync_laws.py
    
  6. Open the site and try sign-up, a chat question and each tool.

Keeping laws up to date

python sync_laws.py              # check the official site now
python sync_laws.py --limit 3    # quick test with 3 acts

The first run tracks the core acts (Penal Code, CrPC, Evidence Act, Negotiable Instruments Act, Special Powers Act, Arms Act, Dowry Prohibition Act, Artha Rin Adalat Ain, Anti-Corruption Commission Act) plus every act published this year. Later runs track any act that appears on the site for the first time. Changed sections are re-embedded and listed on /LawUpdates. Schedule it monthly, for example as a PythonAnywhere scheduled task, or press Check now in the admin panel.

Making an admin

Register normally, then set is_admin to 1 for that user:

sqlite3 instance/law_assistant.db "UPDATE users SET is_admin = 1 WHERE username = 'your-name';"

Disclaimer

Bidhanshala provides legal information, not legal advice. Consult a qualified lawyer for your specific situation.