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/README.md b/README.md
index 46647e5..a2770cd 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[Browser
map, Retrace, voice] -->|HTTPS| EB[Elastic Beanstalk
EC2, nginx, Gunicorn, Flask]
+ EB --> RDS[(RDS PostgreSQL)]
+ EB -->|photos| S3[(S3, private)]
+ S3 -->|new photo| L[Lambda
thumbnails]
+ L --> S3
+ EB -->|labels| RK[Rekognition]
+ EB -->|alerts| SES[SES email]
+ CW[CloudWatch alarm] -.->|status check| EB
+ EB -->|text| GQ[Groq
gpt-oss, Whisper]
+ EB -->|text, audio| GM[Gemini]
+```
## Stack
-- **Backend:** Flask, SQLAlchemy
-- **Frontend:** Jinja templates, plain CSS and JavaScript, no build step
+- **Backend:** Flask, SQLAlchemy, Gunicorn behind nginx
+- **Frontend:** Jinja templates, plain CSS and JavaScript, no build step, no
+ inline scripts (a strict Content-Security-Policy)
- **Database:** SQLite locally, PostgreSQL on RDS in the cloud
-- **Images:** local disk, or S3 with presigned URLs
-- **Deployment:** Elastic Beanstalk with Gunicorn
+- **AWS:** Elastic Beanstalk, EC2, RDS, S3, Lambda, Rekognition, SES, CloudWatch
+- **Models:** Groq (gpt-oss, Whisper) and Google Gemini, all optional
## Run locally
@@ -109,11 +164,8 @@ python -m venv .venv
On macOS or Linux, activate the venv and run `pip install -r requirements.txt`
then `python app.py`. The app starts on http://127.0.0.1:5000 and creates
-`classfind.db` on first run.
-
-To see the admin pages, set `ADMIN_EMAIL` to the address you register with.
-Without `SECRET_KEY` the app generates a random one per process and says so in
-the log, which means sessions end when you restart it.
+`classfind.db` on first run. Set `ADMIN_EMAIL` to the address you register with
+to see the admin pages. The microphone needs HTTPS, except on `localhost`.
## Configuration
@@ -121,29 +173,30 @@ the log, which means sessions end when you restart it.
| --- | --- | --- |
| `CLASSFIND_ENV` | `production` makes `SECRET_KEY` mandatory | `development` |
| `SECRET_KEY` | Signs session cookies | random per process, outside production |
-| `ADMIN_EMAIL` | The one account that gets admin pages | none, so nobody is admin |
-| `STAFF_EMAILS` | Comma-separated accounts that work the security desk; the admin can also grant this from the admin page | none |
-| `SES_SENDER` | Verified Amazon SES address that alert emails come from | unset, no email |
-| `PHOTO_LABELS` | Label uploaded photos with Amazon Rekognition and use the labels in matching | off |
-| `THUMBNAILS` | Show the Lambda-made thumbnails on the home page | off |
-| `GEMINI_API_KEY`, `CEREBRAS_API_KEY` or `GROQ_API_KEY` | Lets an LLM on Gemini, Cerebras or Groq fill the report form from one sentence; keyword rules are used without either | unset |
-| `LLM_MODEL` | Model to ask | `gemini-3.8-flash` on Gemini, `llama-3.3-70b` on Cerebras, `llama-3.3-70b-versatile` on Groq |
-| `GEMINI_MODEL`, `GROQ_MODEL`, `CEREBRAS_MODEL` | Model per provider. If a provider retires its model, the app picks one from the provider's own list | `gemini-3.8-flash`, `llama-3.3-70b-versatile`, `llama-3.3-70b` |
-| `AI_ORDER` | Which text model is asked first. Voice always tries Gemini first, then Groq Whisper | `groq,cerebras,gemini` |
-| `ESCALATE_AFTER_HOURS` | Hours a valuable stays at the desk before moving to the admin office | `72` |
+| `ADMIN_EMAIL` | The one account that gets admin pages | none |
+| `STAFF_EMAILS` | Accounts that work the desk from the start; others are invited from the admin page | none |
| `DATABASE_URL` | SQLite or PostgreSQL connection string | `sqlite:///classfind.db` |
-| `S3_BUCKET` | Bucket for uploaded images | unset, images go to local disk |
-| `AWS_REGION` | Region for that bucket | `ap-south-1` |
-| `FORCE_HTTPS` | Redirect HTTP to HTTPS, and send session cookies only over HTTPS | off |
-| `COOKIE_SECURE` | Send session cookies only over HTTPS, without the redirect | off |
-| `UPLOAD_FOLDER` | Where local images are written | `static/uploads` |
+| `S3_BUCKET`, `AWS_REGION` | Bucket for photos, and its region | unset (local disk), `ap-south-1` |
+| `PHOTO_LABELS` | Label photos with Amazon Rekognition | off |
+| `THUMBNAILS` | Show the Lambda-made thumbnails | off |
+| `SES_SENDER` | Verified Amazon SES address for emails | unset, no email |
+| `GROQ_API_KEY`, `GEMINI_API_KEY`, `CEREBRAS_API_KEY` | Models for sentences and voice; keyword rules without any | unset |
+| `AI_ORDER` | Which text model is asked first | `groq,cerebras,gemini` |
+| `GEMINI_MODEL`, `GROQ_MODEL`, `CEREBRAS_MODEL` | Model per provider; a retired one is replaced from the provider's list | `gemini-3.8-flash`, `llama-3.3-70b-versatile`, `llama-3.3-70b` |
+| `GEMINI_AUDIO_MODEL`, `WHISPER_MODEL` | Models for voice | `GEMINI_MODEL`, `whisper-large-v3` |
+| `ESCALATE_AFTER_HOURS` | Hours a valuable stays at the desk before the admin office | `72` |
+| `FORCE_HTTPS` | Redirect HTTP to HTTPS and keep cookies HTTPS-only | off |
+| `COOKIE_SECURE` | HTTPS-only cookies without the redirect | off |
+| `UPLOAD_FOLDER` | Where local photos are written | `static/uploads` |
## Deployment
-[docs/AWS_SETUP_V2.md](docs/AWS_SETUP_V2.md) walks through SES, Rekognition, the thumbnail Lambda and the CloudWatch alarm. [AWS_DEPLOYMENT.md](AWS_DEPLOYMENT.md) covers the S3 bucket and its policy, the
-IAM permissions the instance role needs, RDS, and the Elastic Beanstalk
-environment. The short version: set the variables above, push the source
-bundle, and check `/health`, which reports the database as well as the app.
+[docs/AWS_SETUP_V2.md](docs/AWS_SETUP_V2.md) walks through SES, Rekognition, the
+thumbnail Lambda and the CloudWatch alarm. [AWS_DEPLOYMENT.md](AWS_DEPLOYMENT.md)
+covers the S3 bucket and its policy, the instance role's permissions, RDS and
+the Elastic Beanstalk environment. Set the variables above, deploy the source
+bundle (`git archive --format=zip -o classfind.zip HEAD`), then run the smoke
+check below.
## Tests
@@ -151,55 +204,64 @@ bundle, and check `/health`, which reports the database as well as the app.
.venv/Scripts/python.exe -m unittest discover -s tests -v
```
-90 tests, no network and no AWS account needed. They cover registration and
-sign-in, reporting, search, the security desk flow from drop-off to handover,
-collection codes that are single use and expire, admin access, CSRF
-rejection and the security headers, image upload, pagination across two pages,
-one account failing to edit another's report, a check that the fast
-matching path returns exactly what a plain double loop returns on the same data,
-place names (aliases, misspellings, Kannada and Hindi words, places that are
-ambiguous on purpose), the road graph being fully connected, Retrace, and
-turning a spoken sentence into a route.
-CI runs them on every push.
+116 tests, with no network or AWS account needed. Besides accounts, reporting,
+the desk flow from drop-off to collection code, admin, CSRF, security headers
+and uploads, they cover place names (aliases, misspellings, Kannada and Hindi,
+places that are ambiguous on purpose), the path graph being fully connected,
+Retrace, voice in each mode, every model fallback (busy, retired, timed out),
+and a check that the fast matching path returns exactly what a plain double
+loop returns.
+
+CI runs the suite twice on every pull request: on SQLite, and on PostgreSQL 16,
+the database the live site uses.
+
+Two more checks live in `tools/`:
+
+- **`tools/smoke.py [URL]`** checks a running site from the outside after a
+ deploy: health and database engine, HTTPS redirect and security headers, the
+ map, place matching, Retrace, and that reporting and admin need a sign-in. It
+ only reads, so it is safe on the live site.
+- **`tools/mutate.py`** is mutation testing for the code where a quiet bug would
+ hurt most: place matching, Retrace, collection codes, escalation and placing
+ reports. It makes one small change at a time (a comparison flipped, `and` for
+ `or`, a number nudged) and checks that the tests notice. Its first run found a
+ real bug ("power bank" matched the bank in the Main Block) and ten untested
+ behaviours, all now covered. What survives now is harmless: timestamp
+ boundaries to the microsecond, rounding, and score weights that do not change
+ the order of results.
## Project structure
```
ClassFind/
-├── app.py config, models, routes, matching, Retrace
+├── app.py config, models, routes, matching, Retrace, voice
├── campus.py place names → places on the map
├── application.py WSGI entry point for Elastic Beanstalk
-├── Procfile Gunicorn command
-├── templates/ Jinja templates, including 400/404/500 pages
-├── static/ style.css, app.js, map.js, picker.js, voice.js,
+├── templates/ Jinja templates
+├── static/ style.css, app.js, map.js (map and Retrace),
+│ picker.js (map on the report form), voice.js,
│ campus.json (the map), logo
-├── tools/build_campus.py writes campus.json: places, roads, road graph
-├── tests/ test_app.py, test_quality.py
-├── aws/ S3 bucket policy
-├── docs/screenshots/ images used in this README
-└── .github/workflows/ CI
+├── lambda/thumbnail/ the S3-triggered thumbnail function
+├── tools/ build_campus.py, smoke.py, mutate.py
+├── tests/ test_app.py, test_campus.py, test_quality.py,
+│ test_thumbnail_lambda.py
+├── docs/ AWS setup and screenshots
+└── .github/workflows/ CI on SQLite and PostgreSQL
```
## Known limits
-- **Email addresses are not verified.** Anyone can register with any address, so
- the contact on a report proves nothing about who posted it.
-- **A claim is a message, not proof.** The finder decides; the app only records
- the exchange.
-- **Matching is a hint.** A percentage points at pairs worth checking. It does
- not establish ownership, and it cannot match a report to an item nobody has
- posted yet.
-- **HTTP still answers unless you turn it off.** The deployment serves HTTPS
- from a Let's Encrypt certificate, but plain HTTP keeps working so the site
- stays up if a certificate cannot be issued. Set `FORCE_HTTPS=true` once HTTPS
- is confirmed.
+- **Email addresses are not verified.** Anyone can register with any address.
+- **A claim is a message, not proof.** Desk staff check the student's ID at
+ handover; the app records who released what.
+- **Matching is a hint.** A percentage points at pairs worth checking; it does
+ not establish ownership.
- **The map is approximate.** It was traced from a sketch, so distances and
- shapes are close, not surveyed. Retrace counts a building as passed when the
- route comes within about 30 map units of it or crosses the road to its door.
-- **Voice needs HTTPS and a Gemini key.** Browsers only allow the microphone
- on secure pages; elsewhere the mic stays hidden and typing works. Clips go to
- Google's Gemini API to be understood. Without `GEMINI_API_KEY`, the
- browser's own captions are used where it has them (Chrome, Edge, Safari).
-- **Schema changes are manual.** `create_all()` makes missing tables, and
- `backfill_item_owners()` adds the one column that arrived later. Anything
- further needs a real migration tool.
+ shapes are close, not surveyed.
+- **Retrace uses when an item was reported,** not when it was found.
+- **Voice quality depends on the provider.** Gemini handles Kannada and mixed
+ speech best but is sometimes slow; Whisper is fast but weaker on Kannada. The
+ microphone needs HTTPS, and audio goes to Google or Groq to be understood.
+- **Schema changes are small hand-written upgrades** (`add_desk_columns`,
+ `add_place_columns`) that run at start-up. Anything bigger needs a real
+ migration tool.
diff --git a/campus.py b/campus.py
index 9f7d87f..dea4553 100644
--- a/campus.py
+++ b/campus.py
@@ -66,6 +66,9 @@ def _aliases():
ALIASES = _aliases()
# A word like this after a place belongs to it: "computer science lab" is one place.
TRAILING = r"(?:\s+(?:lab|labs|department|dept|block|room|building|hall|area|side))?"
+# Things people lose whose names contain a place word.
+NOT_PLACES = ("power bank", "powerbank", "piggy bank", "bank card", "bank passbook", "passbook",
+ "atm card", "atm pin", "debit card", "credit card", "tree charm", "gate pass")
# A loose match may not start or end on one of these, so "near canteen" is not
# read as a misspelt "main canteen".
FILLER = {"the", "a", "an", "near", "at", "in", "on", "by", "to", "and", "of", "my", "i", "inside",
@@ -100,6 +103,10 @@ def find_places(text):
clean = normalise(text)
if not clean:
return []
+ # Item names that contain a place word, like "power bank", are blanked out
+ # (keeping positions) so the bank in the Main Block is not matched.
+ for phrase in NOT_PLACES:
+ clean = re.sub(rf"(? {COMPARE_SWAPS[type(op)].__name__}",
+ node, ("compare", i)))
+ elif isinstance(node, ast.BoolOp):
+ sites.append((f"{path[0]}:{path[1]} {type(node.op).__name__} -> "
+ f"{'Or' if isinstance(node.op, ast.And) else 'And'}", node, ("boolop",)))
+ elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
+ sites.append((f"{path[0]}:{path[1]} drop not", node, ("not",)))
+ elif isinstance(node, ast.Constant) and type(node.value) in (int, float) and not isinstance(node.value, bool):
+ sites.append((f"{path[0]}:{path[1]} {node.value!r} -> {node.value + 1!r}", node, ("number",)))
+ return sites
+
+
+def apply(tree, target, how):
+ """A copy of the tree with the node equal to `target` mutated."""
+ mutated = copy.deepcopy(tree)
+ originals = list(ast.walk(tree))
+ index = next(i for i, node in enumerate(originals) if node is target)
+ node = list(ast.walk(mutated))[index]
+ kind = how[0]
+ if kind == "compare":
+ node.ops[how[1]] = COMPARE_SWAPS[type(node.ops[how[1]])]()
+ elif kind == "boolop":
+ node.op = ast.Or() if isinstance(node.op, ast.And) else ast.And()
+ elif kind == "not":
+ replacement = node.operand
+ for parent in ast.walk(mutated):
+ for field, value in ast.iter_fields(parent):
+ if value is node:
+ setattr(parent, field, replacement)
+ elif isinstance(value, list) and node in value:
+ value[value.index(node)] = replacement
+ elif kind == "number":
+ node.value = node.value + 1
+ return mutated
+
+
+def run_tests(work, patterns):
+ command = [PYTHON, "-m", "unittest", "discover", "-s", "tests"]
+ for pattern in patterns:
+ command += ["-k", pattern]
+ done = subprocess.run(command, cwd=work, capture_output=True, text=True, timeout=600)
+ return done.returncode == 0
+
+
+def main():
+ only = set(sys.argv[sys.argv.index("--only") + 1].split(",")) if "--only" in sys.argv else None
+ work = Path(tempfile.mkdtemp(prefix="classfind-mutants-"))
+ shutil.copytree(ROOT, work, dirs_exist_ok=True, ignore=shutil.ignore_patterns(".git", ".v", "__pycache__", "*.db"))
+ total = killed = 0
+ survivors = []
+ started = time.monotonic()
+ try:
+ for filename, names, patterns in TARGETS:
+ if only:
+ names = names & only
+ if not names:
+ continue
+ source = (ROOT / filename).read_text(encoding="utf-8")
+ tree = ast.parse(source)
+ if not run_tests(work, patterns):
+ print(f"Tests for {sorted(names)} fail before any mutation; fix them first.")
+ return 2
+ for description, node, how in mutation_sites(tree, names):
+ (work / filename).write_text(ast.unparse(apply(tree, node, how)), encoding="utf-8")
+ caught = not run_tests(work, patterns)
+ total += 1
+ killed += caught
+ if not caught:
+ survivors.append(f"{filename} {description}")
+ print(f"{'killed ' if caught else 'SURVIVED'} {filename} {description}", flush=True)
+ (work / filename).write_text(source, encoding="utf-8")
+ finally:
+ shutil.rmtree(work, ignore_errors=True)
+ score = 100 * killed / total if total else 100
+ print(f"\n{killed} of {total} mutants caught ({score:.0f}%) in {(time.monotonic() - started) / 60:.1f} min")
+ if survivors:
+ print("Survivors, each a change no test noticed:")
+ for line in survivors:
+ print(" " + line)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/smoke.py b/tools/smoke.py
new file mode 100644
index 0000000..3b2b210
--- /dev/null
+++ b/tools/smoke.py
@@ -0,0 +1,101 @@
+"""Check a running ClassFind from the outside, after a deploy.
+
+ python tools/smoke.py https://your-environment.elasticbeanstalk.com
+
+Only reads public pages and APIs: it never signs in, reports or changes
+anything, so it is safe to run against the live site. Exits 1 if any check
+fails.
+"""
+import json
+import sys
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+from datetime import datetime, timedelta, timezone
+
+DEFAULT_URL = "https://classfind-prod.eba-ttyqcasp.ap-south-1.elasticbeanstalk.com"
+
+
+class NoRedirect(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self, *args, **kwargs):
+ return None
+
+
+def fetch(url, follow=True):
+ """(status, headers, body, seconds) for a GET, without raising on HTTP errors."""
+ opener = urllib.request.build_opener() if follow else urllib.request.build_opener(NoRedirect)
+ request = urllib.request.Request(url, headers={"User-Agent": "ClassFind-smoke/1.0"})
+ started = time.monotonic()
+ try:
+ with opener.open(request, timeout=20) as response:
+ return response.status, response.headers, response.read(), time.monotonic() - started
+ except urllib.error.HTTPError as exc:
+ return exc.code, exc.headers, exc.read(), time.monotonic() - started
+
+
+def main(base):
+ base = base.rstrip("/")
+ results = []
+
+ def check(name, ok, detail=""):
+ results.append(ok)
+ print(f"{'PASS' if ok else 'FAIL'} {name}{f' ({detail})' if detail else ''}")
+
+ status, _, body, took = fetch(base + "/health")
+ health = json.loads(body or b"{}") if status == 200 else {}
+ check("health answers ok", status == 200 and health.get("status") == "ok", f"{status}, {took:.2f}s")
+ check("database is PostgreSQL", health.get("engine") == "postgresql", health.get("engine", "?"))
+
+ status, headers, body, took = fetch(base + "/")
+ page = body.decode("utf-8", "replace")
+ check("home page loads", status == 200, f"{status}, {took:.2f}s")
+ check("home page draws the campus map", 'data-place="main-block"' in page and "map.js" in page)
+ check("security policy blocks inline scripts", "script-src 'self'" in (headers.get("Content-Security-Policy") or ""))
+ check("microphone allowed for this site only", "microphone=(self)" in (headers.get("Permissions-Policy") or ""))
+ if base.startswith("https://"):
+ check("HSTS is sent over HTTPS", bool(headers.get("Strict-Transport-Security")))
+ status, headers, _, _ = fetch("http://" + base[len("https://"):] + "/", follow=False)
+ check("plain HTTP is sent to HTTPS", status in (301, 308) and (headers.get("Location") or "").startswith("https://"),
+ f"{status}")
+
+ for asset in ("static/campus.json", "static/map.js", "static/picker.js", "static/voice.js", "static/style.css"):
+ status, _, body, _ = fetch(f"{base}/{asset}")
+ check(f"{asset} is served", status == 200 and len(body) > 100, f"{status}, {len(body)} bytes")
+ status, _, body, _ = fetch(base + "/static/campus.json")
+ campus = json.loads(body) if status == 200 else {}
+ check("campus map has every place", len(campus.get("places", [])) >= 29, f"{len(campus.get('places', []))} places")
+
+ status, _, body, took = fetch(base + "/api/map")
+ feed = json.loads(body) if status == 200 else {}
+ check("map feed answers", status == 200 and {"places", "desk", "items"} <= set(feed), f"{took:.2f}s")
+
+ def place(text):
+ status, _, body, _ = fetch(base + "/api/place?" + urllib.parse.urlencode({"q": text}))
+ return json.loads(body) if status == 200 else {}
+
+ check("\"mechanical parking\" is Mech Parking", place("mechanical parking").get("place") == "mech-parking")
+ check("\"CS lab\" is the Main Block", place("CS lab, 3rd floor").get("place") == "main-block")
+ check("\"canteen\" asks which of three", place("near the canteen").get("candidates") == ["canteen", "puff-shop", "nandini"])
+ check("\"Canara ATM\" is the ATM", place("Canara ATM").get("place") == "atm")
+
+ since = (datetime.now(timezone.utc) - timedelta(days=7)).isoformat()
+ query = urllib.parse.urlencode({"stops": "canteen,main-block", "passed": "road-main", "since": since})
+ status, _, body, took = fetch(f"{base}/api/retrace?{query}")
+ check("Retrace answers", status == 200 and "items" in json.loads(body or b"{}"), f"{took:.2f}s")
+
+ for path in ("/login", "/register", "/matches"):
+ status, _, _, _ = fetch(base + path)
+ check(f"{path} loads", status == 200, f"{status}")
+ status, headers, _, _ = fetch(base + "/report", follow=False)
+ check("reporting needs a sign-in", status in (301, 302, 303) and "login" in (headers.get("Location") or ""), f"{status}")
+ status, _, _, _ = fetch(base + "/admin", follow=False)
+ check("admin is not public", status in (301, 302, 303, 403), f"{status}")
+
+ passed = sum(results)
+ print(f"\n{passed} of {len(results)} checks passed")
+ return 0 if passed == len(results) else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else DEFAULT_URL))