From 014d158d46cb1183a920e46a25bd644438759088 Mon Sep 17 00:00:00 2001 From: vidit choudhary <153429790+vidit-16@users.noreply.github.com> Date: Wed, 7 Oct 2026 22:49:50 +0530 Subject: [PATCH] Tidy the repo: lint in CI, complete project tree, deployment guide in docs ruff runs in CI and the code passes it; every text file ends with a newline; AWS_DEPLOYMENT.md moves into docs/; the README tree lists Procfile, requirements.txt, aws/, .platform/ and .ebextensions/. --- .github/workflows/ci.yml | 3 +++ README.md | 12 ++++++--- app.py | 20 +++++++++------ AWS_DEPLOYMENT.md => docs/AWS_DEPLOYMENT.md | 2 +- pyproject.toml | 6 +++++ static/app.js | 2 +- templates/400.html | 2 +- templates/500.html | 2 +- templates/admin.html | 2 +- templates/base.html | 2 +- templates/item.html | 2 +- templates/matches.html | 2 +- templates/report.html | 2 +- tests/test_app.py | 28 +++++++++++++-------- tools/build_campus.py | 13 +++++----- tools/mutate.py | 3 ++- tools/smoke.py | 9 ++++--- 17 files changed, 72 insertions(+), 40 deletions(-) rename AWS_DEPLOYMENT.md => docs/AWS_DEPLOYMENT.md (99%) create mode 100644 pyproject.toml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c1a4ff1..c1ffdfa 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,6 +22,9 @@ jobs: - name: Install dependencies run: pip install -r requirements.txt + - name: Lint + run: pip install ruff && ruff check . + - name: Run application tests run: python -m unittest discover -s tests -v diff --git a/README.md b/README.md index e8fe0de..b068261 100644 --- a/README.md +++ b/README.md @@ -205,7 +205,7 @@ to see the admin pages. The microphone needs HTTPS, except on `localhost`. ## 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) +thumbnail Lambda and the CloudWatch alarm. [docs/AWS_DEPLOYMENT.md](docs/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 @@ -226,7 +226,7 @@ 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, +CI lints the code with ruff and 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/`: @@ -252,6 +252,9 @@ ClassFind/ ├── 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 +├── requirements.txt Python dependencies +├── pyproject.toml lint settings (ruff) ├── templates/ Jinja templates ├── static/ style.css, app.js, map.js (map and Retrace), │ picker.js (map on the report form), voice.js, @@ -260,7 +263,10 @@ ClassFind/ ├── 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, campus map image, screenshots +├── docs/ AWS setup and deployment guides, campus map, screenshots +├── aws/ S3 bucket policy +├── .platform/ nginx settings and the HTTPS certificate hooks +├── .ebextensions/ Elastic Beanstalk port settings for HTTPS └── .github/workflows/ CI on SQLite and PostgreSQL ``` diff --git a/app.py b/app.py index b41f2ae..052a1f0 100644 --- a/app.py +++ b/app.py @@ -1511,10 +1511,11 @@ def reject_claim(claim_id): # Words that mark a Hinglish or Kanglish sentence and carry no item details. MIXED_WORDS = { "mujhe", "mera", "meri", "mere", "maine", "humne", "ek", "mein", "me", "hai", "tha", "thi", "ho", - "mil", "mila", "mili", "mile", "gaya", "gayi", "gya", "gyi", "hogaya", "hogya", "raha", "rahi", "diya", "liya", "kho", "gum", "ko", "ka", "ki", "ke", "se", "par", "pe", "aaj", + "mil", "mila", "mili", "mile", "gaya", "gayi", "gya", "gyi", "hogaya", "hogya", "raha", "rahi", "diya", + "liya", "kho", "gum", "ko", "ka", "ki", "ke", "se", "par", "pe", "aaj", "kal", "yeh", "ye", "woh", "wo", "nanna", "nange", "nanu", "ondu", "alli", "sikkitu", "sikkide", "hoyitu", "kaledu", "kalkonde", "ivattu", "ninne", "hatra", "hathra", "andar", "bahar", "paas", - "nanagai", "nannagai", "nanngai", "nanage", "nangai", "nanna", "undu", "sikkida", "sikkidu", "sikkithu", "aytu", + "nanagai", "nannagai", "nanngai", "nanage", "nangai", "undu", "sikkida", "sikkidu", "sikkithu", "aytu", # The same words in Devanagari and Kannada script. "मुझे", "मेरा", "मेरी", "मेरे", "मैंने", "एक", "में", "है", "था", "थी", "मिल", "मिला", "मिली", "मिले", "गया", "गयी", "गई", "खो", "गुम", "को", "का", "की", "के", "से", "पर", "आज", "कल", "यह", "वह", "पास", @@ -1631,7 +1632,8 @@ def parse_report_rules(text): preposition become the location. """ lowered = text.lower() - found_words = r"\b(found|picked up|someone left|left behind|mila|mili|mile|mil gaya|mil gayi|milgaya|sikkitu|sikkide|sikkid[ae])\b" + found_words = (r"\b(found|picked up|someone left|left behind|mila|mili|mile|mil gaya|mil gayi|milgaya" + r"|sikkitu|sikkide|sikkid[ae])\b") status = "Found" if re.search(found_words, lowered) else "Lost" if any(w in text for w in FOUND_SCRIPT_WORDS) and not any(w in text for w in LOST_SCRIPT_WORDS): status = "Found" @@ -2089,15 +2091,16 @@ def ai_check(): started = time.monotonic() ok = ask_provider(provider, "Found a black notebook in the library", REPORT_PROMPT) is not None model = _found_models.get(provider[0], provider[2]) - parts.append(f"Text via {key_name} ({model}): " - + (f"working, {time.monotonic() - started:.1f}s." if ok else f"failed. {LAST_MODEL_ERROR['text']}")) + result = f"working, {time.monotonic() - started:.1f}s." if ok else f"failed. {LAST_MODEL_ERROR['text']}" + parts.append(f"Text via {key_name} ({model}): {result}") text_ok = text_ok or ok LAST_MODEL_ERROR["audio"] = "" if os.getenv("GEMINI_API_KEY", "").strip(): started = time.monotonic() audio_ok = hear_with_gemini(silent_wav()) is not None - parts.append("Voice via Gemini: " - + (f"working, {time.monotonic() - started:.1f}s." if audio_ok else f"failed. {LAST_MODEL_ERROR['audio']}")) + result = (f"working, {time.monotonic() - started:.1f}s." if audio_ok + else f"failed. {LAST_MODEL_ERROR['audio']}") + parts.append(f"Voice via Gemini: {result}") else: parts.append("Voice via Gemini: GEMINI_API_KEY is not set.") if os.getenv("GROQ_API_KEY", "").strip(): @@ -2656,7 +2659,8 @@ def prepared(items): lost_prepared = prepared(lost_items) pairs = [] - for found, found_text, found_location, found_place, found_title, found_category, found_labels in prepared(found_items): + for (found, found_text, found_location, found_place, found_title, + found_category, found_labels) in prepared(found_items): # One matcher per found title: its index of that string is built once # and reused against every lost title. matcher = SequenceMatcher(None, "", found_title) diff --git a/AWS_DEPLOYMENT.md b/docs/AWS_DEPLOYMENT.md similarity index 99% rename from AWS_DEPLOYMENT.md rename to docs/AWS_DEPLOYMENT.md index 78d279f..6e4b407 100644 --- a/AWS_DEPLOYMENT.md +++ b/docs/AWS_DEPLOYMENT.md @@ -86,4 +86,4 @@ Also demonstrate My Reports, Edit, image upload, Search/Filters, Resolve, and Ad ## Cleanup -When testing is finished, review the Elastic Beanstalk environment, RDS instance and S3 bucket so unused resources do not remain active. \ No newline at end of file +When testing is finished, review the Elastic Beanstalk environment, RDS instance and S3 bucket so unused resources do not remain active. diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..79287fe --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,6 @@ +[tool.ruff] +line-length = 120 +extend-exclude = [".v", ".venv"] + +[tool.ruff.lint] +select = ["E", "F", "W", "B"] diff --git a/static/app.js b/static/app.js index f43d992..26d32c7 100644 --- a/static/app.js +++ b/static/app.js @@ -245,4 +245,4 @@ document.addEventListener("DOMContentLoaded", () => { }, 8000); }); }); -}); \ No newline at end of file +}); diff --git a/templates/400.html b/templates/400.html index 0273492..c5b964a 100644 --- a/templates/400.html +++ b/templates/400.html @@ -8,4 +8,4 @@

That request couldn't be processed.

{{ message }}

Back to ClassFind -{% endblock %} \ No newline at end of file +{% endblock %} diff --git a/templates/500.html b/templates/500.html index 9c997e5..6669471 100644 --- a/templates/500.html +++ b/templates/500.html @@ -8,4 +8,4 @@

ClassFind hit a small bump.

The page couldn't be completed right now. Your existing reports are safe; try again in a moment.

Back to ClassFind -{% endblock %} \ No newline at end of file +{% endblock %} diff --git a/templates/admin.html b/templates/admin.html index b17c0df..f7cd226 100644 --- a/templates/admin.html +++ b/templates/admin.html @@ -163,4 +163,4 @@

Find a report to review.

{% endfor %} -{% endblock %} \ No newline at end of file +{% endblock %} diff --git a/templates/base.html b/templates/base.html index 720a298..baa5ca4 100644 --- a/templates/base.html +++ b/templates/base.html @@ -78,4 +78,4 @@ {% block scripts %}{% endblock %} - \ No newline at end of file + diff --git a/templates/item.html b/templates/item.html index e1c5fd1..1248f6f 100644 --- a/templates/item.html +++ b/templates/item.html @@ -76,4 +76,4 @@

Think this belongs to you?

{% endif %} -{% endblock %} \ No newline at end of file +{% endblock %} diff --git a/templates/matches.html b/templates/matches.html index 5abe10e..1ce17f2 100644 --- a/templates/matches.html +++ b/templates/matches.html @@ -41,4 +41,4 @@

{{ found.title }}

{% else %}
⌁

NO STRONG MATCHES YET

The board is still learning.

As students add reports, ClassFind will compare active lost and found items for overlapping details.

Add a report
{% endif %} -{% endblock %} \ No newline at end of file +{% endblock %} diff --git a/templates/report.html b/templates/report.html index 6186d23..af9b121 100644 --- a/templates/report.html +++ b/templates/report.html @@ -62,4 +62,4 @@

Three details help most.

-{% endblock %} \ No newline at end of file +{% endblock %} diff --git a/tests/test_app.py b/tests/test_app.py index 46e82e8..ce70a03 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -23,7 +23,6 @@ clean_parsed_report, escalate_unclaimed_valuables, parse_report_rules, - CustodyEvent, add_desk_columns, add_place_columns, StaffInvite, @@ -189,7 +188,8 @@ def test_a_class_on_one_address_can_sign_up_and_sign_in(self): _rate_hits.clear() # Many students signing in at once, each once, is fine... for n in range(30): - self.assertNotEqual(self.post("/login", data={"email": f"s{n}@example.com", "password": "secret123"}).status_code, 429) + signed_in = self.post("/login", data={"email": f"s{n}@example.com", "password": "secret123"}) + self.assertNotEqual(signed_in.status_code, 429) self.post("/logout") # ...but guessing one account's password is still stopped after 10 tries. for _ in range(10): @@ -914,7 +914,8 @@ def voice(self, mode, heard=None, transcript="", audio=b"RIFF....WAVEfmt "): def test_voice_report_takes_gemini_fields_in_english(self): self.register() - heard = {"transcript": "Mujhe computer lab mein ek key mili hai", "english": "I found a key in the computer lab", + heard = {"transcript": "Mujhe computer lab mein ek key mili hai", + "english": "I found a key in the computer lab", "status": "Found", "title": "Key", "description": "A single key, found in the computer lab.", "category": "Keys", "location": "computer lab", "places": ["computer lab"], "when": "today"} response, heard_mock = self.voice("report", heard) @@ -1008,7 +1009,9 @@ def test_a_busy_model_is_tried_again(self): self.addCleanup(os.environ.pop, "GEMINI_API_KEY", None) busy = urllib.error.HTTPError("https://x", 503, "Busy", {}, BytesIO(b"high demand")) answer = {"title": "Key", "description": "A key.", "category": "Keys", "location": "", "status": "Found"} - with mock.patch("app.BUSY_RETRY_WAITS", (0, 0)), mock.patch("urllib.request.urlopen", side_effect=[busy, busy, self.model_reply(answer)]) as calls: + replies = [busy, busy, self.model_reply(answer)] + with mock.patch("app.BUSY_RETRY_WAITS", (0, 0)), \ + mock.patch("urllib.request.urlopen", side_effect=replies) as calls: self.assertEqual(parse_report_with_model("found a key")["title"], "Key") self.assertEqual(calls.call_count, 3) @@ -1040,7 +1043,8 @@ def test_a_retired_model_is_replaced_from_the_providers_list(self): def fake(request_, timeout): if request_.full_url.endswith("/models"): - listing = {"data": [{"id": "whisper-large-v3"}, {"id": "openai/gpt-oss-120b"}, {"id": "llama-3.1-8b-instant"}]} + listing = {"data": [{"id": "whisper-large-v3"}, {"id": "openai/gpt-oss-120b"}, + {"id": "llama-3.1-8b-instant"}]} reply = mock.MagicMock() reply.__enter__.return_value.read.return_value = json.dumps(listing).encode() return reply @@ -1119,7 +1123,8 @@ def test_whisper_sends_the_clip_as_a_form(self): sent = {} def fake(request_, timeout): - sent["url"], sent["body"], sent["type"] = request_.full_url, request_.data, request_.get_header("Content-type") + sent["url"], sent["body"] = request_.full_url, request_.data + sent["type"] = request_.get_header("Content-type") reply = mock.MagicMock() reply.__enter__.return_value.read.return_value = json.dumps({"text": "mujhe ek key mili"}).encode() return reply @@ -1142,7 +1147,8 @@ def test_ai_order_decides_who_answers_text_first(self): self.assertIn("generativelanguage", app_module.llm_providers()[0][0]) def test_the_item_decides_an_obvious_category(self): - fields = clean_parsed_report({"title": "Black purse", "description": "A black purse.", "category": "Accessories", + fields = clean_parsed_report({"title": "Black purse", "description": "A black purse.", + "category": "Accessories", "location": "canteen", "status": "Found"}, "black purse") self.assertEqual(fields["category"], "Wallet & ID") fields = clean_parsed_report({"title": "Steel thing", "category": "Accessories", "status": "Found"}, "x") @@ -1167,7 +1173,8 @@ def fake(request_, timeout): def test_a_misheard_kannada_canteen_still_counts(self): import campus - self.assertEqual(campus.resolve_place("ನನಗೆ ಕೆಂಟಿನ್ ಒಂದು ಪರ್ಸ್ ಸಿಕಿಡೆ")["candidates"], ["canteen", "puff-shop", "nandini"]) + heard = campus.resolve_place("ನನಗೆ ಕೆಂಟಿನ್ ಒಂದು ಪರ್ಸ್ ಸಿಕಿಡೆ") + self.assertEqual(heard["candidates"], ["canteen", "puff-shop", "nandini"]) def test_romanised_kannada_from_whisper(self): fields = parse_report_rules("NANNGAI CANTEEN HATRA UNDU KAPPU PERS SIKKIDA") @@ -1226,7 +1233,8 @@ def test_desk_columns_are_added_to_an_older_database(self): "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 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)", + "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')", ): @@ -1489,7 +1497,7 @@ def test_photo_labels_are_saved_shown_and_used_in_matching(self): with app.app_context(): lost = Item.query.filter_by(title="Steel thing").one() self.assertEqual(lost.image_labels, "Bottle,Shaker") - reasons = [r for l, f, s, r in build_matches() if l.title == "Steel thing"][0] + reasons = [r for lost, _, _, r in build_matches() if lost.title == "Steel thing"][0] self.assertIn("photos show: bottle, shaker", reasons) page = self.client.get(f"/item/{lost.id}").data self.assertIn(b"In the photo", page) diff --git a/tools/build_campus.py b/tools/build_campus.py index e8479a5..a7b4b97 100644 --- a/tools/build_campus.py +++ b/tools/build_campus.py @@ -66,7 +66,8 @@ ["bit main gate", "bit gate", "main gate", "front gate", "gate 15"]), ("law-physio", 16, "Visveswarapura College of Law and Kempegowda Institute of Physiotherapy", "Law / Physio", "block", (585, 1125, 715, 1210), - ["law college", "visveswarapura college of law", "physiotherapy", "physio", "kempegowda institute of physiotherapy"]), + ["law college", "visveswarapura college of law", "physiotherapy", "physio", + "kempegowda institute of physiotherapy"]), ("canteen", 17, "BIT Canteen", "Canteen", "bit", (735, 1125, 862, 1170), ["bit canteen", "main canteen", "college canteen"]), ("xerox-canteen", 18, "Xerox corner near the canteen", "Xerox", "small", (918, 1122, 945, 1158), @@ -204,7 +205,7 @@ def on_segment(point, a, b, tolerance=0.5): def segments(): for road_id, _, points, _ in ROADS: - for a, b in zip(points, points[1:]): + for a, b in zip(points, points[1:], strict=False): yield road_id, a, b @@ -224,14 +225,14 @@ def crossing(a, b, c, d): def inside(point, poly): x, y = point hit = False - for (x0, y0), (x1, y1) in zip(poly, poly[1:] + poly[:1]): + for (x0, y0), (x1, y1) in zip(poly, poly[1:] + poly[:1], strict=True): if (y0 > y) != (y1 > y) and x < x0 + (y - y0) * (x1 - x0) / (y1 - y0): hit = not hit return hit def boundary_distance(point, poly): - return min(project(point, a, b)[1] for a, b in zip(poly, poly[1:] + poly[:1])) + return min(project(point, a, b)[1] for a, b in zip(poly, poly[1:] + poly[:1], strict=True)) def doors(): @@ -284,9 +285,9 @@ def node(pt): nodes.append(pt) return index[pt] - for (road_id, a, b), points in cuts.items(): + for (road_id, a, _), points in cuts.items(): ordered = sorted(points, key=lambda pt: math.dist(a, pt)) - for p, q in zip(ordered, ordered[1:]): + for p, q in zip(ordered, ordered[1:], strict=False): if p != q: edges.append((node(p), node(q), round(math.dist(p, q), 1), road_id)) # Some roads only meet through a building or a car park, e.g. the road from diff --git a/tools/mutate.py b/tools/mutate.py index adde20f..13efcd9 100644 --- a/tools/mutate.py +++ b/tools/mutate.py @@ -56,7 +56,8 @@ def mutation_sites(tree, names): 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): + 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 diff --git a/tools/smoke.py b/tools/smoke.py index 3b2b210..6f4827e 100644 --- a/tools/smoke.py +++ b/tools/smoke.py @@ -51,7 +51,8 @@ def check(name, ok, detail=""): 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 "")) + policy = headers.get("Content-Security-Policy") or "" + check("security policy blocks inline scripts", "script-src 'self'" in policy) 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"))) @@ -76,7 +77,8 @@ def place(text): 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"]) + canteens = place("near the canteen").get("candidates") + check("\"canteen\" asks which of three", canteens == ["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() @@ -88,7 +90,8 @@ def place(text): 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}") + to_login = status in (301, 302, 303) and "login" in (headers.get("Location") or "") + check("reporting needs a sign-in", to_login, f"{status}") status, _, _, _ = fetch(base + "/admin", follow=False) check("admin is not public", status in (301, 302, 303, 403), f"{status}")