Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

orchestra-rehearsal-plan

Keeps an orchestra's Google Calendar in sync with rehearsal dates posted to a Telegram channel. Documents (PDF/DOCX) and plain-text messages are pulled from the channel, their date/description/location tables are extracted with Azure AI, and the resulting rehearsals are added/updated/deleted in Google Calendar.

Architecture (hexagonal / ports & adapters)

                         ┌─────────────────────────────┐
   adapter.in            │        application          │            adapter.out
 ┌───────────────┐       │  ┌───────────────────────┐  │       ┌────────────────────┐
 │    Runner     │──────▶│  │ SyncRehearsalsUseCase │  │       │  Telegram adapter   │──▶ Telegram Bot API
 │(ApplicationRunner)│   │  │ RehearsalSyncService  │  │──────▶│  (MessageSourcePort)│
 └───────────────┘       │  └───────────────────────┘  │       ├────────────────────┤
                         │   outbound ports:            │──────▶│  Azure AI adapter   │──▶ Document Intelligence
                         │   • MessageSourcePort        │       │  (ExtractionPort)   │──▶ Azure OpenAI
                         │   • RehearsalExtractionPort  │──────▶├────────────────────┤
                         │   • CalendarPort             │       │  Google Calendar    │──▶ Google Calendar API
                         │   domain: Rehearsal, ...     │       │  (CalendarPort)     │
                         └─────────────────────────────┘       └────────────────────┘
  • domain – framework-free records: Rehearsal, IncomingMessage, Attachment, MailMessage, RehearsalPlan, CalendarChange.
  • application.port.in – driving port SyncRehearsalsUseCase.
  • application.port.out – driven ports: MessageSourcePort, MailSourcePort, RehearsalExtractionPort, CalendarPort, NotificationPort.
  • application – RehearsalSyncService orchestrates fetch → (classify) → extract → reconcile → notify.
  • adapter.in.runner – runs a single sync on startup, then the app terminates (see Lifecycle).
  • adapter.out.{telegram,mail,azure,google} – the outgoing adapters. Telegram provides both the message source and the change-notification sender; mail is a Gmail source.

Lifecycle

The app is a one-shot batch job: on startup it runs a single sync (adapter.in.runner) and then the JVM exits (a non-zero exit code signals a failed run). There is no in-process schedule — the platform (e.g. GCP) starts the process on a schedule (nightly). Both sources therefore use an overlapping look-back window rather than persisted state: 25 h, so with a 24 h run cadence a one-hour overlap guarantees nothing is missed between runs. Disable the auto-run with rehearsal.runner.enabled=false (used by tests).

Sources

  • Telegram — documents are trusted rehearsal plans; text is a targeted update. Each run pulls the updates the Bot API currently retains and keeps only those within the look-back window (rehearsal.telegram.lookback-hours, default 25). No cursor is persisted; note the Bot API only retains un-acknowledged updates for ~24 h, which caps the effective reach.

  • Mailbox (Gmail) — a rolling, overlapping look-back window (rehearsal.mail.lookback-hours, default 25) reads mails from a configured sender via the Gmail API (keyless Workspace domain-wide delegation). Attachments are classified (via Document Intelligence + the LLM): those that are rehearsal plans are processed exactly like a Telegram document (full project sync); everything else (e.g. sheet music) is ignored. Only PDF/DOCX attachments are sent to the classifier.

  • Attachment size guard. PDF/DOCX attachments larger than rehearsal.max-document-size-mb (default 20 MB in application.yml; set it to 4 on the Azure Document Intelligence F0 tier, whose limit is 4 MB) are skipped before any AI call — no classification, no cost — and reported to the Telegram channel so you can check them manually. Applies to both mail and Telegram documents.

  • Stateless. No database is used. Instead of persisting a Telegram cursor or a set of processed mails, both sources rely on the overlapping look-back window plus idempotent calendar reconciliation: a message or mail seen twice across overlapping runs produces no duplicate event. The trade-off is that mails re-appearing in the one-hour overlap are re-classified (a small, bounded repeat of the Azure call).

Reconciliation, ordering & notifications

  • Ordering. Messages are processed strictly in updateId order (as sent), one fully before the next, rehearsals within a message in extraction order. Calendar writes are blocking and the run is single-threaded, so a later message always sees earlier effects — important when messages correct/depend on earlier ones.

  • Document = authoritative full sync. An uploaded PDF/DOCX is the complete plan for a project. Its events are tagged with a stable project id (e.g. winter-2026, derived from season+year, ignoring the "Stand" date). On (re-)upload the app creates new rehearsals, updates changed ones, and deletes managed events of that project no longer present. (If extraction yields zero rehearsals, the sync is skipped — never a mass deletion.)

  • Text = partial patch. A free-text message is a partial update: only the fields it mentions are changed, the rest are kept from the existing event (so "… nur bis 17:00" changes just the end time and leaves the start, title, programme intact). The target event is found by stated start time, then by named type/title (e.g. "Anspielprobe" picks the Anspielprobe event when a day has several), else the day's only event. It never deletes; a start-time-bearing message with no match creates a new event. Updates use Google patch, preserving the project tag.

  • Match key. Rehearsals are matched by date (stable), so changing programme/remarks updates the existing event instead of duplicating it; an event is rewritten only when its content differs.

  • Notification. All notices go to rehearsal.telegram.notify-chat-id:

    • Every processed plan gets a ✅ Probeplan verarbeitet confirmation — even with no changes (Keine Änderungen.) — so you always know a plan was seen.
    • Targeted text updates are summarised in a 🗓 Kalender aktualisiert message.
    • Attachments skipped as too large are reported in a ⚠️ Übersprungene Anhänge message.
    • Any exception during a run produces a short (2-3 line) ❗ Fehler message (context + exception type + message). Reported per failing item (message/mail/attachment) and once at the top level for anything else; a failed error-notification is only logged, never retried.

    Each block shows title / date+time / location / description. For an updated event the fields that actually changed are rendered in bold (HTML) — e.g. only the end time, or only the description — and a new event has all its fields bold; deletes are plain. So a review is at a glance. Long messages are split to respect Telegram's limit; a failed notification never fails the sync.

Extraction strategy (both Azure services, one port)

RehearsalExtractionPort has two entry points:

  • extractFromDocument(...) → Azure Document Intelligence (prebuilt-layout) parses tables/text, and the parsed content is then structured into Rehearsal objects by Azure OpenAI.
  • extractFromText(...) → Azure OpenAI directly.

Field mapping (rehearsal-plan tables: Wann / Wo / Was / Bemerkungen)

Calendar field Source
title (summary) <type> <ensemble> — the event type (Probe / Anspielprobe / Generalprobe / Konzert, classified from the labels) plus the optional suffix rehearsal.azure.ensemble (blank by default). E.g. Probe, Konzert; with the suffix ABC: Probe ABC, Konzert ABC.
start/end time Wann time range. When only a start is known, the end is start + 2.5h — but capped at the next event's start on the same day if it begins within that window (so e.g. an Anspielprobe ends when the Konzert begins, no overlap). No time anywhere → all-day.
location Wo
description Was, followed by a blank line and Bemerkungen (if present)

One row can become several events. A Was time inside the Wann range is just the programme (kept in the description). A Was time outside the Wann range — or any Was time when Wann has none — becomes its own event. Examples: 12.12 → main 12:30–13:00 plus an 11:00 Aufbau; 19.12 (no Wann time) → 15:30 Anspielprobe and 17:00 Konzert. Because a date can hold several events, reconciliation keys on (date, start time).

Set the optional title suffix via rehearsal.azure.ensemble (env REHEARSAL_ENSEMBLE). Concert rows are recognized from the labels (e.g. Anspielprobe/Konzert in Was, or a performance venue with an Anspielprobe beforehand) rather than the pink cell colour, which the layout extraction doesn't surface reliably.

Tech

  • Java 25, Spring Boot 4.1.0 (Spring Framework 7, Jackson 3 / tools.jackson)
  • Azure Document Intelligence 1.0.7, Azure OpenAI 1.0.0-beta.16
  • Google Calendar API v3-rev20260708-2.0.0
  • Maven, JUnit 5 + AssertJ

Build

mvn verify

The context smoke test runs; the four credential-gated integration tests are skipped unless the relevant environment variables are set (see below).

Configuration

All settings live under rehearsal.* in src/main/resources/application.yml and read from environment variables. Provide the following at runtime / for tests:

Component Environment variable Notes
Telegram TELEGRAM_BOT_TOKEN Bot token from @BotFather. The bot must be an admin of the channel to receive channel_post updates.
TELEGRAM_NOTIFY_CHAT_ID Chat/channel the change summary is posted to (e.g. @myChannel or numeric id). Blank = no notifications.
Azure OpenAI AZURE_OPENAI_ENDPOINT e.g. https://<resource>.openai.azure.com
AZURE_OPENAI_KEY API key
AZURE_OPENAI_DEPLOYMENT chat deployment name (default gpt-4o)
Azure Document Intelligence AZURE_DOCINTEL_ENDPOINT Document Intelligence endpoint
AZURE_DOCINTEL_KEY API key
Event titles REHEARSAL_ENSEMBLE (optional) suffix appended to event titles, e.g. ABC → Probe ABC. Blank = plain Probe.
Google Calendar GOOGLE_CREDENTIALS_PATH (optional) service-account JSON key for local dev; on GCP omit it and use the attached service account (ADC, keyless)
GOOGLE_CALENDAR_ID id of a calendar shared with the service account (edit rights)
Mailbox (Gmail) REHEARSAL_MAIL_SA_EMAIL delegated service account (domain-wide delegation, gmail.readonly)
REHEARSAL_MAIL_IMPERSONATED_USER Workspace mailbox to read
REHEARSAL_MAIL_SENDER only mails from this address are processed

Optional: rehearsal.runner.enabled (default true; set false to load the context without running a sync), rehearsal.telegram.lookback-hours / rehearsal.mail.lookback-hours (default 25), and rehearsal.*.time-zone (default Europe/Zurich).

Integration tests

Each adapter has a @SpringBootTest *IT test (run by mvn verify via Failsafe). They read their configuration from application.yml (i.e. the same rehearsal.* properties as the app; values can come from the file or the ${ENV_VAR:...} fallbacks). Each test skips itself (JUnit assumption) when the service it needs isn't configured, so the build stays green. They run under the test profile, so local-only settings (e.g. rehearsal.google.credentials-path, rehearsal.azure.test-document-path) can go into src/test/resources/application-test.yml, which is git-ignored:

  • TelegramMessageSourceAdapterIT — runs when rehearsal.telegram.bot-token is set. Round-trips getUpdates and downloads any attachments.
  • AzureRehearsalExtractionAdapterIT — the text tests run when rehearsal.azure.openai.* is set; the document tests additionally need rehearsal.azure.document-intelligence.* and rehearsal.azure.test-document-path (a local PDF/DOCX with a rehearsal table; none is shipped with the repository).
  • GoogleCalendarAdapterIT — runs when Application Default Credentials are available (or rehearsal.google.credentials-path is set). Full add → find → update → delete lifecycle on a far-future date; cleans up after itself.
  • GmailMailSourceAdapterIT — runs when rehearsal.mail.{service-account-email,impersonated-user,sender} are set (and ADC + delegation are in place). Connects and fetches the recent-mail window without error.
mvn verify

Endpoints may be given with or without the https:// scheme — the Azure adapter normalizes scheme-less endpoints automatically.

Notes / follow-ups

  • No state is persisted between runs; the overlapping look-back windows plus idempotent reconciliation are what prevent gaps and duplicates. If the channel volume ever exceeds rehearsal.telegram.fetch-limit (100) within the window, or the platform run cadence drifts beyond the Bot API's ~24 h update retention, messages could be missed — revisit a persisted cursor then.
  • Reconciling a plan document creates missing events, updates changed ones and deletes events of that project that are no longer listed (never when extraction yields zero rehearsals). Events are matched by date, or by (date, start time) when a day holds several. Free-text messages only create or update, never delete.
  • Events created here are tagged with a private extended property (rehearsalPlanManaged=true, plus rehearsalPlanProject=<id> for plan documents) so the app never touches unrelated calendar entries.

License

Licensed under the Apache License, Version 2.0.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages