From 3ed090e53a91a5a882af53d2c0d28926dfe41292 Mon Sep 17 00:00:00 2001 From: vidit choudhary <153429790+vidit-16@users.noreply.github.com> Date: Wed, 7 Oct 2026 20:30:29 +0530 Subject: [PATCH 1/3] Run the test suite on PostgreSQL in CI as well as SQLite The live site runs on PostgreSQL, so schema upgrades, case-insensitive search and dates are now tested on it too. The tests take the database from TEST_DATABASE_URL, and the one test that builds an old schema by hand uses SQL both databases accept. --- .github/workflows/ci.yml | 38 ++++++++++++++++++++++++++++++++++++++ tests/test_app.py | 20 ++++++++++++-------- tests/test_quality.py | 2 +- 3 files changed, 51 insertions(+), 9 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 57fe3e3..c1a4ff1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,3 +24,41 @@ jobs: - name: Run application tests run: python -m unittest discover -s tests -v + + # The same tests on PostgreSQL, which the live site uses: schema upgrades, + # case-insensitive search and date handling can differ from SQLite. + postgres: + runs-on: ubuntu-latest + + services: + postgres: + image: postgres:16 + env: + POSTGRES_USER: classfind + POSTGRES_PASSWORD: classfind + POSTGRES_DB: classfind_test + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U classfind" + --health-interval 5s + --health-timeout 5s + --health-retries 10 + + env: + TEST_DATABASE_URL: postgresql://classfind:classfind@localhost:5432/classfind_test + + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Install dependencies + run: pip install -r requirements.txt + + - name: Run application tests on PostgreSQL + run: python -m unittest discover -s tests -v diff --git a/tests/test_app.py b/tests/test_app.py index af5bf0b..90da4b6 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -10,7 +10,8 @@ from datetime import datetime, timedelta from io import BytesIO -os.environ["DATABASE_URL"] = "sqlite:///:memory:" +# CI also runs these against PostgreSQL, the database the live site uses. +os.environ["DATABASE_URL"] = os.environ.get("TEST_DATABASE_URL", "sqlite:///:memory:") os.environ["SECRET_KEY"] = "test-secret" import app as app_module @@ -118,7 +119,8 @@ def test_csrf_protection_and_security_headers(self): response = self.client.get("/health") self.assertEqual(response.status_code, 200) self.assertEqual(response.get_json()["database"], "ok") - self.assertEqual(response.get_json()["engine"], "sqlite") + with app.app_context(): + self.assertEqual(response.get_json()["engine"], db.engine.dialect.name) self.assertEqual(response.headers["X-Content-Type-Options"], "nosniff") self.assertEqual(response.headers["X-Frame-Options"], "DENY") self.assertIn("frame-ancestors 'none'", response.headers["Content-Security-Policy"]) @@ -1047,16 +1049,18 @@ def test_desk_columns_are_added_to_an_older_database(self): """A database from before the desk gets its columns, and found items count as held.""" with app.app_context(): db.drop_all() + # Both databases accept this; INTEGER PRIMARY KEY only numbers rows by itself in SQLite. + key = "INTEGER PRIMARY KEY" if db.engine.dialect.name == "sqlite" else "SERIAL PRIMARY KEY" for statement in ( - 'CREATE TABLE "user" (id INTEGER PRIMARY KEY, name VARCHAR(100) NOT NULL, ' + f'CREATE TABLE "user" (id {key}, name VARCHAR(100) NOT NULL, ' "email VARCHAR(160) NOT NULL, password_hash VARCHAR(255) NOT NULL, " - "is_admin BOOLEAN NOT NULL, created_at DATETIME NOT NULL)", - "CREATE TABLE item (id INTEGER PRIMARY KEY, title VARCHAR(120) NOT NULL, " + "is_admin BOOLEAN NOT NULL, created_at TIMESTAMP NOT NULL)", + f"CREATE TABLE item (id {key}, title VARCHAR(120) NOT NULL, " "description TEXT NOT NULL, category VARCHAR(60) NOT NULL, location VARCHAR(120) NOT NULL, " "status VARCHAR(20) NOT NULL, reporter_name VARCHAR(100) NOT NULL, contact VARCHAR(160) NOT NULL, " - "image_url VARCHAR(500), owner_id INTEGER, created_at DATETIME NOT NULL)", - "CREATE TABLE claim (id INTEGER PRIMARY KEY, item_id INTEGER NOT NULL, claimant_id INTEGER NOT NULL, " - "message TEXT NOT NULL, status VARCHAR(20) NOT NULL, created_at DATETIME NOT NULL, decided_at DATETIME)", + "image_url VARCHAR(500), owner_id INTEGER, created_at TIMESTAMP NOT NULL)", + f"CREATE TABLE claim (id {key}, item_id INTEGER NOT NULL, claimant_id INTEGER NOT NULL, " + "message TEXT NOT NULL, status VARCHAR(20) NOT NULL, created_at TIMESTAMP NOT NULL, decided_at TIMESTAMP)", "INSERT INTO item (title, description, category, location, status, reporter_name, contact, created_at) " "VALUES ('Old bottle', 'Steel bottle', 'Other', 'Gym', 'Found', 'X', 'x@example.com', '2026-09-01')", ): diff --git a/tests/test_quality.py b/tests/test_quality.py index 5b38d97..529d06c 100644 --- a/tests/test_quality.py +++ b/tests/test_quality.py @@ -2,7 +2,7 @@ import unittest from pathlib import Path -os.environ.setdefault("DATABASE_URL", "sqlite:///:memory:") +os.environ.setdefault("DATABASE_URL", os.environ.get("TEST_DATABASE_URL", "sqlite:///:memory:")) os.environ.setdefault("SECRET_KEY", "test-secret") from app import app From 84b22f2fa03aa38bf2c454f4866ab6ceb8a18de3 Mon Sep 17 00:00:00 2001 From: vidit choudhary <153429790+vidit-16@users.noreply.github.com> Date: Wed, 7 Oct 2026 20:38:41 +0530 Subject: [PATCH 2/3] Live smoke check, mutation testing, and what they found - tools/smoke.py checks a running site from outside after a deploy: health and database, HTTPS redirect and headers, map, place matching, Retrace, and that reporting and admin need a sign-in. Read-only. 25 of 25 pass on the live site. - tools/mutate.py makes one small change at a time to place matching, Retrace, collection codes, escalation and report placing, and checks the tests notice. - It found "power bank" matching the bank in the Main Block (and "ATM card" the ATM). Item names containing a place word are now set aside before matching. - It found untested loose matching of one- and three-word misspellings and where a loose match sits in the sentence; tests added. - Tests now clear every AI key and outside setting, so a developer's own GROQ_API_KEY can never make a test call the real service. - README rewritten for the map, Retrace, voice and its fallbacks, the architecture, configuration and the test tools, with new screenshots. --- README.md | 310 +++++++++++++++---------- campus.py | 7 + docs/screenshots/classfind_home.png | Bin 534262 -> 145595 bytes docs/screenshots/classfind_item.png | Bin 225818 -> 0 bytes docs/screenshots/classfind_matches.png | Bin 245622 -> 0 bytes docs/screenshots/classfind_place.png | Bin 0 -> 147736 bytes tests/test_app.py | 10 + tests/test_campus.py | 25 ++ tools/mutate.py | 133 +++++++++++ tools/smoke.py | 101 ++++++++ 10 files changed, 460 insertions(+), 126 deletions(-) delete mode 100644 docs/screenshots/classfind_item.png delete mode 100644 docs/screenshots/classfind_matches.png create mode 100644 docs/screenshots/classfind_place.png create mode 100644 tools/mutate.py create mode 100644 tools/smoke.py diff --git a/README.md b/README.md index 46647e5..d371a55 100644 --- a/README.md +++ b/README.md @@ -4,98 +4,153 @@ [](LICENSE) [](https://www.python.org/) -A lost-and-found board for a campus. Students report what they lost or found, -search what others have reported, and claim an item that looks like theirs. The -app compares active Lost and Found reports and shows which pairs look like the -same object, with the reasons for each score. +A lost-and-found for the BIT campus, built around a live map. Students report +what they lost or found by tapping where it was, search by place in whatever +words they use, or **retrace their day**: tap or say the places they went and +the app walks that route and shows what was found along it. Found items go to +the security desk, and owners collect them with a one-time code. -**Live app:** http://classfind-prod.eba-ttyqcasp.ap-south-1.elasticbeanstalk.com/ +**Live app:** https://classfind-prod.eba-ttyqcasp.ap-south-1.elasticbeanstalk.com/
-
+
The board: every active report, searchable by keyword, category and status.
+The home page. Each building shows how many found items are there; the desk shows what it holds.
-
-
+
Potential Lost/Found pairs with the reasons behind each percentage (left). A single report, where the owner can open a claim (right).
+Tapping a building filters the list to it and drops its reports onto the map. Screenshots use local demo data.
## What it does -- **Campus map.** The home page opens on a map of BIT: 28 buildings and the - roads between them, traced from a hand-drawn sketch. Each building shows how - many found items were reported there, the security desk shows how many it - holds, and the counts update every 20 seconds. Tapping a building filters the - list to it and spreads its reports out as pins. -- **Retrace.** "Retrace my day" asks where you went, in order. Tap the places - (or roads) and the app draws your walk along the campus roads, runs along it, - and shows what was found on the way: anything at the places you went into, - and whatever was found outside the places you only walked past. -- **Voice.** Say it instead: "I lost my black wallet, I was in P1, then the - canteen, then workshops." The page records the clip and Gemini listens to it, - so English, Hindi, Kannada, Hinglish or a mix all work without picking a - language. A spoken sentence fills in Retrace, the search box, or the report - form, with an English item name and description. +**Finding things** + +- **Campus map.** The home page opens on a map of BIT: 29 places and the paths + between them, traced from a hand-drawn sketch. Buildings show how many found + items were reported there, the security desk shows how many it holds, and the + counts refresh every 20 seconds. The map turns dark in the evening and zooms + to the building you tap on a phone. +- **Retrace.** "Retrace my day" asks where you went, in order. Tap the places or + paths and the app draws your walk along the campus paths (shortest route over + a graph of the paths, preferring paths to cutting through buildings), also + searches the other likely way, and runs along the route showing what was + found: anything at the places you went into, and what was found outside the + places you only walked past. +- **Voice, in any mix of languages.** Say "I lost my black wallet, I was in P1, + then the canteen, then workshops", in English, Hindi, Kannada, Hinglish or a + mix. The sentence fills in Retrace, the search box, or the report form, with + an English item name and a written description. - **Places from words.** "mech parking", "mechanical parking" and "garage" are - the same place; "CS lab" is the Main Block; "canteen" could be three places, so - the report form asks which. Misheard words like "mesh parking" still match. -- **Report** a lost or found item, with category, location and an optional photo. - The reporter's name and contact come from the signed-in account rather than a - form field, so they cannot be spoofed by whoever fills the form. -- **Search and filter** by keyword, category and status, 24 reports to a page. -- **Security desk.** Every found item goes to the campus security desk. A - student's found report shows as awaiting drop-off until staff mark it - received; staff can also log items handed in directly. Each found item keeps - a chain of custody: reported, received, claim approved, released, with who - did each and when. -- **Claim** a found item with proof only the owner would know. Electronics, - wallets and ID, and keys count as valuable and need a longer proof that names - something like a serial number or IMEI. Desk staff, not the finder, approve - or reject claims; the claimant can withdraw one while it waits. -- **Collect with a code.** Approving a claim issues a six-digit collection code, - shown only to the claimant and valid for 48 hours. Staff enter it at the desk - to release the item, after checking the student's ID. A code works once, - expired codes can be reissued, and an item is only released once it has - actually reached the desk. + the same place; "CS lab", "library" and "Canara bank" are the Main Block; the + ATM outside it is its own place. Misheard words like "mesh parking" or ಕೆಂಟಿನ್ + still match. "Canteen" could be three places, so the app asks which. +- **Search and filter** by keyword, place, category and status, 24 reports to a + page, updating as you type. - **Matches** compares every active Lost report against every active Found one and lists the pairs worth a look, each with the reasons behind its score. -- **Admin** view over all reports and accounts, for one account named by - `ADMIN_EMAIL`. -- **Images** go to S3 when a bucket is configured, served through presigned URLs - so the bucket stays private, and to local disk otherwise. + +**Reporting and returning** + +- **Report** a lost or found item by typing, by one sentence, or by voice, and + pick where it was on the map. A place that could be several has to be picked + before the report is published. +- **Photos** go to S3 through presigned URLs. Amazon Rekognition labels them + ("Bottle", "Backpack") and the labels count in matching and Retrace. A Lambda + function makes thumbnails for the home page. +- **Security desk.** Every found item goes to the desk. A student's found report + shows as awaiting drop-off until staff mark it received. Each item keeps a + chain of custody: reported, received, claim approved, released, with who did + each and when. Valuables left unclaimed for 72 hours move to the admin office. +- **Claim** with proof only the owner would know; electronics, wallets and keys + need a longer proof such as a serial number. Desk staff, not the finder, + approve or reject claims. +- **Collect with a code.** Approval issues a six-digit code, shown only to the + claimant and valid for 48 hours. Staff enter it at the desk to release the + item. It works once, and an item is only released once it has reached the desk. +- **QR tags.** Students print a QR sticker for their things; whoever finds one + scans it and reports it found in one click, and the owner is emailed. +- **Email alerts** through Amazon SES when a found item looks like your lost one, + and when a claim is approved or the item is collected. + +**Running it** + +- **Admin** for the account named by `ADMIN_EMAIL`: every report, insight + charts, and desk staff. Staff are added by email invitation, which the person + accepts from their own account within 7 days. +- **AI check.** One button on the admin page tries every configured model and + shows "working" or the provider's exact error, never the key. + +## How sentences and voice are understood + +Nothing depends on one provider. Each step has a fallback, and a provider that +is busy or times out is skipped for 3 minutes so requests go straight to the +next one. + +| Input | First | Then | Last resort | +| --- | --- | --- | --- | +| Typed sentence | Groq (`gpt-oss-120b`, under a second) | Gemini | Keyword rules, which also read common Hinglish, Kanglish, Devanagari and Kannada | +| Voice clip | Gemini hears the audio itself, best for Kannada and code-mixed speech | Groq Whisper writes it down (prompted with campus names and both scripts), then the text model reads it | The browser's own captions | + +The models are given the list of campus places and their other names, and +return the exact spot ("CS lab, 3rd floor") separately from the campus place. +Their output is checked before it reaches the form: categories must be one of +the eight, and an item whose name says its category plainly ("purse") gets it. +If a provider retires its model, the app reads the provider's model list, picks +a current chat model and remembers it. + +## How places are matched + +`static/campus.json` holds the places, their outlines, about 300 other names, +the paths, and a graph of the paths with the door where each building meets +one. `campus.py` turns text into a place: longest name first, a trailing "lab" +or "block" belongs to the name before it, words like "near" or "outside" mark +the item as outdoors, and loose matching catches typos and misheard speech. +Words that fit several places are never guessed. ## How matching works -There is no model here. Each active Lost report is compared with each active -Found report on four signals, and the score is a weighted sum: +Each active Lost report is compared with each active Found report, and the +score is a weighted sum: | Signal | Weight | How it is measured | | --- | ---: | --- | | Shared words in title and description | 0.40 | Jaccard overlap of tokens, stop words removed | | Title similarity | 0.25 | `difflib.SequenceMatcher` ratio | -| Same place | 0.15 | 1 when both are on the same building or road of the map, else Jaccard overlap of the location words | +| Same place | 0.15 | 1 on the same building or path of the map, else overlap of the location words | | Reported close together | 0.10 | Falls from 1 to 0 over 14 days | | Same category | 0.10 | Exact match | +| Photos show the same thing | up to 0.10 | Overlap of the Rekognition labels | -Pairs below 25% are dropped, the rest are shown with their reasons, and equal -scores are ordered by report id so the page does not reshuffle between visits. +Pairs below 25% are dropped. Each report is tokenised once, `SequenceMatcher`'s +cheap upper bounds skip pairs that cannot reach the cut-off, and the result is +cached until a report changes; on 600 reports a side that took 31.3s down to +19.1s with identical output. -Comparing every pair is quadratic, so three things keep the page usable: each -report is tokenised once rather than once per comparison, `SequenceMatcher`'s -own cheap upper bounds skip pairs that cannot reach the cut-off before the -expensive comparison runs, and the result is cached until a report changes. On -seeded data, 600 reports a side went from 31.3s to 19.1s with identical output. -Beyond `MATCH_SCAN_LIMIT` (500 a side) only the newest reports are compared. +## Architecture + +```mermaid +flowchart LR + B[BrowserVm~m7ak~|HZ^_riVix2|Pv_dD+8)Yj-X9vcE<
ztHvmbN%i$Qpi?8WCYur$Dqk%9__P(`)iOy%vH3(4Ze#9sh>GF<-o8}f3)Jl9lWWq|
z2qk7(HUUmSphlC;h{a5)Ubf3uhwo}?c-aF5@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