Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
12 changes: 9 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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/`:
Expand All @@ -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,
Expand All @@ -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
```

Expand Down
20 changes: 12 additions & 8 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
"मुझे", "मेरा", "मेरी", "मेरे", "मैंने", "एक", "में", "है", "था", "थी", "मिल", "मिला", "मिली", "मिले",
"गया", "गयी", "गई", "खो", "गुम", "को", "का", "की", "के", "से", "पर", "आज", "कल", "यह", "वह", "पास",
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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():
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion AWS_DEPLOYMENT.md → docs/AWS_DEPLOYMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
When testing is finished, review the Elastic Beanstalk environment, RDS instance and S3 bucket so unused resources do not remain active.
6 changes: 6 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[tool.ruff]
line-length = 120
extend-exclude = [".v", ".venv"]

[tool.ruff.lint]
select = ["E", "F", "W", "B"]
2 changes: 1 addition & 1 deletion static/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -245,4 +245,4 @@ document.addEventListener("DOMContentLoaded", () => {
}, 8000);
});
});
});
});
2 changes: 1 addition & 1 deletion templates/400.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ <h3>That request couldn't be processed.</h3>
<p>{{ message }}</p>
<a class="primary-btn compact" href="{{ url_for('index') }}">Back to ClassFind</a>
</section>
{% endblock %}
{% endblock %}
2 changes: 1 addition & 1 deletion templates/500.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ <h3>ClassFind hit a small bump.</h3>
<p>The page couldn't be completed right now. Your existing reports are safe; try again in a moment.</p>
<a class="primary-btn compact" href="{{ url_for('index') }}">Back to ClassFind</a>
</section>
{% endblock %}
{% endblock %}
2 changes: 1 addition & 1 deletion templates/admin.html
Original file line number Diff line number Diff line change
Expand Up @@ -163,4 +163,4 @@ <h2>Find a report to review.</h2>
{% endfor %}
</div>
</section>
{% endblock %}
{% endblock %}
2 changes: 1 addition & 1 deletion templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,4 @@
<script src="{{ url_for('static', filename='app.js') }}"></script>
{% block scripts %}{% endblock %}
</body>
</html>
</html>
2 changes: 1 addition & 1 deletion templates/item.html
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,4 @@ <h3>Think this belongs to you?</h3>
</ol>
</section>
{% endif %}
{% endblock %}
{% endblock %}
2 changes: 1 addition & 1 deletion templates/matches.html
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,4 @@ <h2>{{ found.title }}</h2>
{% else %}
<div class="empty-state"><div class="empty-icon">⌁</div><p class="section-kicker">NO STRONG MATCHES YET</p><h3>The board is still learning.</h3><p>As students add reports, ClassFind will compare active lost and found items for overlapping details.</p><a class="primary-btn compact" href="{{ url_for('report') }}">Add a report</a></div>
{% endif %}
{% endblock %}
{% endblock %}
2 changes: 1 addition & 1 deletion templates/report.html
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,4 @@ <h2>Three details help most.</h2>
</aside>
</div>
</section>
{% endblock %}
{% endblock %}
28 changes: 18 additions & 10 deletions tests/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
clean_parsed_report,
escalate_unclaimed_valuables,
parse_report_rules,
CustodyEvent,
add_desk_columns,
add_place_columns,
StaffInvite,
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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")
Expand All @@ -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")
Expand Down Expand Up @@ -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', '[email protected]', '2026-09-01')",
):
Expand Down Expand Up @@ -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)
Expand Down
13 changes: 7 additions & 6 deletions tools/build_campus.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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


Expand All @@ -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():
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion tools/mutate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Loading
Loading