Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Inquire on the user's calendar days (#412 T8): date filters in the agent, the list tool and both searches are local-day UTC bounds and keep the last day; the agent's today and the dates it shows are local
Murtaza Nasird16b022609ba
diff --git a/src/api/inquire.py b/src/api/inquire.pyindex 7ab3b9ac..c17b731d 100644--- a/src/api/inquire.py+++ b/src/api/inquire.py@@ -9,6 +9,7 @@ import jsonimport reimport timefrom datetime import datetime, timedelta+from src.utils.timezones import to_user_local, user_timezonefrom flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, send_file, Response, current_appfrom flask_login import login_required, current_userfrom werkzeug.utils import secure_filename@@ -530,7 +531,7 @@ Respond with only a JSON array of strings: ["term1", "term2", ...]"""# Build recording header with complete metadataheader = f"=== {recording.title} [Recording ID: {recording_id}] ==="if recording.meeting_date:- header += f" ({recording.meeting_date})"+ header += f" ({to_user_local(recording.meeting_date, current_user).strftime('%Y-%m-%d %H:%M')})"# Add participants informationif recording.participants:@@ -825,6 +826,7 @@ Order your response with notes from the most recent meetings first. Always use p'title': user_title,'company': user_company,'output_language': user_output_language,+ 'timezone': user_timezone(current_user),}agent_gen = run_inquire_agent(app, user_id, user_ctx, user_message, message_history,diff --git a/src/services/embeddings.py b/src/services/embeddings.pyindex 255861f8..9a7b3f07 100644--- a/src/services/embeddings.py+++ b/src/services/embeddings.py@@ -651,10 +651,16 @@ def basic_text_search_chunks(user_id, query, filters=None, top_k=5):TranscriptChunk.recording_id.in_(filters['recording_ids']))- if filters.get('date_from'):- chunks_query = chunks_query.filter(Recording.meeting_date >= filters['date_from'])- if filters.get('date_to'):- chunks_query = chunks_query.filter(Recording.meeting_date <= filters['date_to'])+ if filters.get('date_from') or filters.get('date_to'):+ # Local calendar days of the user, as UTC bounds; date_to is+ # inclusive (it used to drop the last day, #412).+ from src.utils.timezones import local_date_bounds, user_timezone_by_id+ _start, _end = local_date_bounds(filters.get('date_from'), filters.get('date_to'),+ user_timezone_by_id(user_id))+ if _start is not None:+ chunks_query = chunks_query.filter(Recording.meeting_date >= _start)+ if _end is not None:+ chunks_query = chunks_query.filter(Recording.meeting_date < _end)# Text search - filter stop words and rank by match countstop_words = {'a', 'an', 'the', 'is', 'are', 'was', 'were', 'be', 'been',@@ -813,10 +819,16 @@ def semantic_search_chunks(user_id, query, filters=None, top_k=5):TranscriptChunk.recording_id.in_(filters['recording_ids']))- if filters.get('date_from'):- chunks_query = chunks_query.filter(Recording.meeting_date >= filters['date_from'])- if filters.get('date_to'):- chunks_query = chunks_query.filter(Recording.meeting_date <= filters['date_to'])+ if filters.get('date_from') or filters.get('date_to'):+ # Local calendar days of the user, as UTC bounds; date_to is+ # inclusive (it used to drop the last day, #412).+ from src.utils.timezones import local_date_bounds, user_timezone_by_id+ _start, _end = local_date_bounds(filters.get('date_from'), filters.get('date_to'),+ user_timezone_by_id(user_id))+ if _start is not None:+ chunks_query = chunks_query.filter(Recording.meeting_date >= _start)+ if _end is not None:+ chunks_query = chunks_query.filter(Recording.meeting_date < _end)# Get chunks that have embeddingschunks = chunks_query.filter(TranscriptChunk.embedding.isnot(None)).all()diff --git a/src/services/inquire_agent.py b/src/services/inquire_agent.pyindex f37eeb5f..f64a5969 100644--- a/src/services/inquire_agent.py+++ b/src/services/inquire_agent.py@@ -133,10 +133,14 @@ def resolve_allowed_recording_ids(user_id, filters):Recording.participants.ilike(f'%{name}%')for name in filters['speaker_names']]))- if filters.get('date_from'):- q = q.filter(Recording.meeting_date >= datetime.combine(filters['date_from'], dtime.min))- if filters.get('date_to'):- q = q.filter(Recording.meeting_date <= datetime.combine(filters['date_to'], dtime.max))+ # Local calendar days of the user, as UTC bounds (#412).+ from src.utils.timezones import local_date_bounds, user_timezone_by_id+ _start, _end = local_date_bounds(filters.get('date_from'), filters.get('date_to'),+ user_timezone_by_id(user_id))+ if _start is not None:+ q = q.filter(Recording.meeting_date >= _start)+ if _end is not None:+ q = q.filter(Recording.meeting_date < _end)return {row[0] for row in q.all()}@@ -157,7 +161,7 @@ def _truncate_to_tokens(text, cap_tokens, pagination_hint=None):return text[:cap_chars] + marker-def _recording_brief(rec):+def _recording_brief(rec, zone=None):d = {'recording_id': rec.id,'title': rec.title or 'Untitled Recording',@@ -166,7 +170,8 @@ def _recording_brief(rec):'has_notes': bool(rec.notes),}if rec.meeting_date:- d['meeting_date'] = rec.meeting_date.strftime('%Y-%m-%d %H:%M')+ from src.utils.timezones import to_local, user_timezone+ d['meeting_date'] = to_local(rec.meeting_date, zone or user_timezone(rec.owner)).strftime('%Y-%m-%d %H:%M')if rec.participants:d['participants'] = rec.participantsif rec.audio_duration_seconds:@@ -254,6 +259,8 @@ def tool_search_transcripts(ctx, args):except ValueError:return {'error': f"{arg} must be an ISO date (YYYY-MM-DD)"}+ from src.utils.timezones import to_local, user_timezone_by_id+ _zone = user_timezone_by_id(ctx.user_id)if mode == 'keyword':results = basic_text_search_chunks(ctx.user_id, query, filters, top_k)search_type = 'keyword'@@ -278,7 +285,7 @@ def tool_search_transcripts(ctx, args):hits.append({'recording_id': chunk.recording_id,'title': chunk.recording.title or 'Untitled Recording',- 'meeting_date': chunk.recording.meeting_date.strftime('%Y-%m-%d') if chunk.recording.meeting_date else None,+ 'meeting_date': to_local(chunk.recording.meeting_date, _zone).strftime('%Y-%m-%d') if chunk.recording.meeting_date else None,'speaker': chunk.speaker_name,'time': _fmt_time(chunk.start_time),'seek_seconds': int(chunk.start_time) if chunk.start_time is not None else None,@@ -293,16 +300,21 @@ def tool_list_recordings(ctx, args):q = Recording.query.filter(Recording.id.in_(ctx.allowed_ids))if args.get('participant'):q = q.filter(Recording.participants.ilike(f"%{args['participant']}%"))- for arg, op in (('date_from', 'ge'), ('date_to', 'le')):+ from src.utils.timezones import local_date_bounds, user_timezone_by_id+ _zone = user_timezone_by_id(ctx.user_id)+ _bounds = {}+ for arg in ('date_from', 'date_to'):if args.get(arg):try:- parsed = datetime.fromisoformat(str(args[arg]))+ _bounds[arg] = datetime.fromisoformat(str(args[arg])).date()except ValueError:return {'error': f"{arg} must be an ISO date (YYYY-MM-DD)"}- if op == 'ge':- q = q.filter(Recording.meeting_date >= parsed)- else:- q = q.filter(Recording.meeting_date <= datetime.combine(parsed.date(), dtime.max))+ # Local calendar days of the user, as UTC bounds (#412).+ _start, _end = local_date_bounds(_bounds.get('date_from'), _bounds.get('date_to'), _zone)+ if _start is not None:+ q = q.filter(Recording.meeting_date >= _start)+ if _end is not None:+ q = q.filter(Recording.meeting_date < _end)sort = args.get('sort', 'newest')q = q.order_by(Recording.meeting_date.asc() if sort == 'oldest' else Recording.meeting_date.desc())limit = min(max(int(args.get('limit', 25) or 25), 1), 100)@@ -311,7 +323,7 @@ def tool_list_recordings(ctx, args):return {'total_in_scope': total,'returned': len(recs),- 'recordings': [_recording_brief(r) for r in recs],+ 'recordings': [_recording_brief(r, _zone) for r in recs],}@@ -388,7 +400,8 @@ def tool_get_recording_metadata(ctx, args):rec, err = ctx.check_scope(args.get('recording_id'))if err:return {'error': err}- info = _recording_brief(rec)+ from src.utils.timezones import user_timezone_by_id+ info = _recording_brief(rec, user_timezone_by_id(ctx.user_id))try:info['tags'] = [t.name for t in rec.tags]except Exception:@@ -551,6 +564,13 @@ def _summary_line(tool_counts):# Prompts# ---------------------------------------------------------------------------+def _today_for(user_ctx):+ """Today in the user's timezone (#412); UTC when none is known."""+ from src.utils.timezones import now_local, is_valid_timezone+ zone = user_ctx.get('timezone')+ return now_local(zone if is_valid_timezone(zone) else 'UTC').strftime('%Y-%m-%d')++def _system_prompt(user_ctx, filters_text, availability, tool_mode_prompt_block):language_instruction = (f"Respond in {user_ctx['output_language']}. " if user_ctx.get('output_language') else '')@@ -558,7 +578,7 @@ def _system_prompt(user_ctx, filters_text, availability, tool_mode_prompt_block)summaries_line = "stored summaries, " if availability.get('summaries') else ''return f"""You are a research assistant analyzing {user_ctx['name']}'s audio recording library \(meetings, calls, voice notes). {user_ctx['name']} is a(n) {user_ctx['title']} at {user_ctx['company']}. \-{language_instruction}Today's date is {datetime.utcnow().strftime('%Y-%m-%d')}.+{language_instruction}Today's date is {_today_for(user_ctx)}.You have tools to search transcripts, list recordings, and read transcripts, {summaries_line}{notes_line}\and metadata{filters_text}. Work iteratively: search or browse first, read more where needed, and only \diff --git a/src/utils/timezones.py b/src/utils/timezones.pyindex 45b08ca6..6a0b6674 100644--- a/src/utils/timezones.py+++ b/src/utils/timezones.py@@ -70,6 +70,26 @@ def local_day_start_utc(day, zone_name):return start.astimezone(timezone.utc).replace(tzinfo=None)+def local_date_bounds(date_from, date_to, zone_name):+ """UTC bounds for an inclusive range of local calendar days.++ Returns (start, end) as naive UTC: start of date_from, and the start of the+ day after date_to (exclusive). Either may be None. Comparing a stored UTC+ datetime with a bare date dropped the last day and used UTC days (#412).+ """+ from datetime import timedelta+ start = local_day_start_utc(date_from, zone_name) if date_from else None+ end = local_day_start_utc(date_to + timedelta(days=1), zone_name) if date_to else None+ return start, end+++def user_timezone_by_id(user_id):+ """user_timezone for a user id (the admin default when the user is unknown)."""+ from src.database import db+ from src.models import User+ return user_timezone(db.session.get(User, user_id) if user_id else None)++def request_timezone(value, user):"""The zone for an interactive request: the browser's if valid, else the user's."""return value if is_valid_timezone(value) else user_timezone(user)diff --git a/tests/test_inquire_dates.py b/tests/test_inquire_dates.pynew file mode 100644index 00000000..592df86f--- /dev/null+++ b/tests/test_inquire_dates.py@@ -0,0 +1,71 @@+"""Inquire answers date questions on the user's calendar days (#412 T8).++The agent and both search functions compared stored UTC datetimes with bare+dates, so the last day of a range was dropped and days were UTC days; the+agent's "today" and the dates it shows were UTC too.++SHARED-DB: the user and recordings are removed afterwards.+"""++import os+import sys+import uuid+from datetime import datetime+from unittest.mock import patch++import pytest++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from src.app import app, db+from src.models import Recording, User+from src.services import inquire_agent as ia+++def world():+ with app.app_context():+ s = uuid.uuid4().hex[:8]+ u = User(username=f"iqd_{s}", email=f"iqd_{s}@local.test", password="x",+ timezone="Asia/Tokyo", timezone_mode="fixed")+ db.session.add(u)+ db.session.commit()+ # 2026-03-04 23:30 UTC = 2026-03-05 08:30 Tokyo; 2026-03-05 18:00 UTC = 2026-03-06 03:00 Tokyo+ a = Recording(user_id=u.id, title="Morning", original_filename="a.wav", status="COMPLETED",+ meeting_date=datetime(2026, 3, 4, 23, 30))+ b = Recording(user_id=u.id, title="Next day", original_filename="b.wav", status="COMPLETED",+ meeting_date=datetime(2026, 3, 5, 18, 0))+ db.session.add_all([a, b])+ db.session.commit()+ ids = dict(user=u.id, a=a.id, b=b.id)+ yield ids+ with app.app_context():+ for model, key in ((Recording, "a"), (Recording, "b"), (User, "user")):+ obj = db.session.get(model, ids[key])+ if obj is not None:+ db.session.delete(obj)+ db.session.commit()+++def test_list_tool_uses_local_days_and_keeps_the_last_day(world):+ with app.app_context():+ ctx = ia.ToolContext(world["user"], {}, {world["a"], world["b"]}, {"summaries": True, "notes": True})+ out = ia.tool_list_recordings(ctx, {"date_from": "2026-03-05", "date_to": "2026-03-05"})+ titles = {r["title"] for r in out["recordings"]}+ assert titles == {"Morning"}+ brief = next(r for r in out["recordings"] if r["title"] == "Morning")+ assert brief["meeting_date"] == "2026-03-05 08:30"+++def test_scope_filter_uses_local_days(world):+ with app.app_context():+ allowed = ia.resolve_allowed_recording_ids(world["user"], {"date_from": datetime(2026, 3, 6).date(),+ "date_to": datetime(2026, 3, 6).date()})+ assert world["b"] in allowed and world["a"] not in allowed+++def test_today_is_the_users_day():+ with patch("src.utils.timezones.now_local", return_value=datetime(2026, 3, 6, 1, 0)):+ prompt = ia._system_prompt({"name": "A", "title": "x", "company": "y", "timezone": "Asia/Tokyo"},+ "", {"summaries": True, "notes": True}, "")+ assert "Today's date is 2026-03-06." in prompt