[aidan] feat: scheduled tasks (#105)

* [eric] ci: gitleaks-ignore the known historical secrets so our branch stops failing on leaks it didnt add

* [eric] workflows: restore scheduled-tasks on the workflow line (revert removal, keep windows fixes + 1.1.69)

* [eric] workflows: re-apply uncommitted scheduling wip (schedule pill, calendar view, slice)

* [eric] ops: gitignore dev-team local state files

* [eric] ops: backlog item for download-tracking visibility

* [eric] ci: allowlist the cdp-routes redaction-test token in gitleaks

* [aidan] feat/scheduled-tasks: keep step labels in sync on edit and show chevron on every step

* [aidan] fix: schedule time in chat

* [aidan] ux/workflows: add workflow step removal (#91)

* [aidan] feat/scheduled-tasks: remember workflow tool permissions across runs

* [aidan] feat/task-scheduling: add hourly and minute (15-min minimum) schedule intervals (#93)

* [aidan] feat/scheduled-tasks: calendar, rename, and edit workflows (#94)

* [aidan] bug: fix schedule button

* [aidan] fix/agent-errors: surface provider rate limits

* [aidan] ux/cards: click-to-rename for chat and workflow titles

Single-click a card's title to enter edit mode inline. Commit on Enter/blur,
cancel on Escape. Rename persists via PATCH for workflows and sessions.

* [aidan] feat/workflows: seed build prompt for zero-step workflows

When a new workflow has no steps, seed the agent with a prompt asking
the user to describe what the workflow should do, rather than starting blank.

* [aidan] feat/workflows: add-to-schedule popover for unscheduled workflows

Clicking the "+" on an unscheduled workflow row opens a popover with two options:
- Keep this schedule: enables the workflow's existing cadence and moves it to Scheduled
- Change schedule: opens the scheduling editor to pick a different time

* [aidan] ux/workflows: wire add-to-schedule popover and simplify New button

- Made the "+" icon on unscheduled workflow rows clickable, opening a popover
  to keep or change the schedule
- Removed AddIcon from toolbar "New" button (now reads "New" instead of "+ New")

* [aidan] fix/scheduled-tasks: open schedule calendar when Schedule pill clicked

Fixed the Schedule pill click being swallowed by the toolbar's dismiss handler.
Exempted the toolbar pills via data-toolbar-pills so their click handlers fire.

* [aidan] ux/workflows: open New workflow in agent build chat instead of empty card

When creating a new workflow from the hub, open it in edit_agent view (with the
agent builder chat) instead of a preview card. The workflow is created on the
backend first so the embedded session has a real ID.

* [aidan] feat/workflow-edit: add draft testing save flow

* [aidan] ux/chat: remove continue chat button

* [aidan] ux/workflows: polish workflow card interactions

* [aidan] fix/workflow-scheduling: save unscheduled workflows as drafts

* aidan ui: schedule naming changes

* [aidan] ui: tool calling desc/naming

* [aidan] ui: calendar sidebar naming

* [aidan] ui: fix stop viewing closing chat

* [aidan] feat/workflows: auto-name workflows and polish the build flow (#95)

* [aidan] feat/workflow-auto-naming: auto-generate workflow titles from steps

Generate a title + description from a workflow's steps (one aux call,
reused for step labels) whenever it is still auto_named, so a workflow
built in the Edit Agent names itself on commit instead of staying
"New workflow". A manual rename sets auto_named=False and is never
overwritten. Stream the aux call (non-streaming drops content on some
9router lanes) and fall back to a step-derived title when the model is
unavailable.

* [aidan] feat/workflows: hide unsaved new workflows until first save

A brand-new "+ New" workflow is created with unsaved=true and kept out
of the hub's scheduled/unscheduled lists while the user is still building
it in the Edit Agent. The first commit (Save) clears the flag and the
workflow appears. Every other create path stays visible immediately.

* [aidan] ux/workflows: remove redundant save workflow button

The Edit Agent already has Discard/Save controls in its strip, so the
header "Save Workflow" button was a duplicate save path. Remove it and
its pulse/edit-session-id wiring; the model/time subtitle stays.

* [aidan] ux/workflows: animate title on auto-rename

Wrap the workflow card title in the same Typewriter the chat card uses,
so when the auto-generated name replaces the placeholder after Save it
retypes letter-by-letter. Gated on a real (non-placeholder) title so it
never animates on mount or for already-named workflows.

* [aidan] ux/workflows: animate sidebar title on auto-rename

Wrap the calendar hub's sidebar row title in the same Typewriter the
workflow card uses, so a title that auto-renames retypes letter-by-letter
in the sidebar too. Extract the placeholder/isRealTitle guard into the
shared workflowVisuals so the card and sidebar stay in sync.

* [aidan] fix/workflows: connect watch tether, keep watched chat open, wire draft run/history

* [aidan] ui: grey out chat pill when not selected

* [aidan] ui: fix running agent display

* [aidan] feat/history-popover: add chat history and scheduled tasks run log tabs (#96)

* [aidan] ux/schedule: toast when calendar view already open on expand

* [aidan] ui: fix popover descs

* [aidan] feat/workflow-runs: add pause, resume, and stop controls for live runs

* [aidan] feat/schedule-calendar: add calendar occurrences endpoint and concrete timezones

* [aidan] feat/workflows: require at least one step to save a workflow

* [aidan] ux/edit-agent: hide Discard for an unsaved new workflow

* [aidan] ux/edit-agent: move fix-prefix card below the step list

* [aidan] feat/workflows: toast when an unattended scheduled run starts

* [aidan] fix/dashboard-tethers: anchor workflow-sidecar tethers to measured card rects

* [aidan] feat/workflows: validate steps before scheduling and keep chat tool memory

* [aidan] feat/mcp-suggestions: dismissable integration banner with per-session cooldown

* [aidan] feat/workflows: add scheduled-run "running now" toast with click-to-view (#97)

* [aidan] ux/workflows: surface paused state on card, sidebar, and calendar; tidy run history

* [aidan] feat/mcp-suggestions: suggest both Google and Microsoft when provider is ambiguous

* [aidan] fix/agent-tokens: friendly out-of-tokens card across all agent surfaces

* [aidan] feat/workflow-model: persist edit-agent model on save with switch notice and fresh drafts

* [aidan] fix/workflow-chat: force stop on watched run mirrors workflow card stop

* [aidan] fix/workflow-cards: keep watched run tethered on finish to avoid duplicate chat

* [aidan] feat/schedule-calendar: mark current time with a now line in week view

* [aidan] refactor/private-names: rename error and schedule classifiers from _ to p_

* [aidan] feat/scheduled-tasks: agent workflow scheduling and in-chat convert (#98)

* [aidan] feat/workflow-suggest: nudge user to convert repeatable chat to workflow

Add SuggestConvertToWorkflow MCP tool that agents call at the end of a task
when they've completed something worth repeating (daily report, weekly check,
recurring data pull). Frontend detects the tool call and glows the "Convert to
workflow" button 3 times to draw the eye. When user clicks it, the suggested
cadence (e.g. "every weekday at 9am") is stored in the draft and seeded into
the scheduling agent's first prompt, so the agent can act on the suggestion
rather than asking the user again.

Tool is never auto-called — agents decide when a task is genuinely repeatable
(not debugging, creative work, one-off lookup). Tool description emphasizes
sparse, high-confidence use only (once per session max).

Files changed:
- backend/apps/agents/schedule_mcp_server.py: add SuggestConvertToWorkflow tool
- frontend/src/shared/mcpToolMeta.ts: add label for new tool
- frontend/src/app/pages/Dashboard/cards/AgentCard.tsx: detect suggestion in
  session messages, show+glow "Convert to workflow" button, pass cadence to draft
- frontend/src/shared/state/workflowsSlice.ts: add suggested_cadence field to
  Workflow interface
- frontend/src/app/pages/Workflows/SchedulingView.tsx: seed scheduling agent
  prompt with suggested cadence hint

* [aidan] feat/agent-scheduling: route recurring asks through native workflows, deny claude cron skill

* [aidan] feat/workflow-convert: in-chat convert popup and auto-open scheduled workflow card

* [aidan] ux/calendar-page: schedule calendar restyle + popover fixes (#99)

* [aidan] fix/dashboard-delete: remove workflows calendar panel on delete key

* [aidan] ux/workflows-calendar: restyle hub, fix today highlight, add toolbar toggle

* [aidan] ux/schedule-popover: compact density, fix sticky header bleed, add header spacing

* [aidan] ux/schedule-calendar: hollow ring dot for past fires in month view

* [aidan] ux/schedule-calendar: clickable +N more opens day's full run list

* [aidan] feat/run-log-filters: add success and skipped pills to scheduled task history

* [aidan] fix/convert-button: stop drag capture so convert-to-workflow click fires

* [aidan] ux/calendar-card: match border color and radius to chat and workflow cards

* [aidan] fix/minimap: render missed-runs card on the minimap

* [aidan] ux/run-sparkline: simplify tooltip to plain run tally

* [aidan] ux/run-history: collapse expanded run view to one clickable line

* [aidan] ux/calendar-card: match corner radius to browser cards

* [aidan] feat/workflows: launch-time scheduling UX and workflow-card polish (#101)

* [aidan] feat/schedule-list: lazy-load list view via scroll sentinel

* [aidan] feat/missed-runs: launch toast with per-workflow counts and pan-to-card

* [aidan] fix/dashboard-tethers: keep watching line anchored on canvas zoom

* [aidan] feat/scheduled-tasks: review missed runs at launch instead of auto-firing on_missed

* [aidan] refactor/workflow-cards: use radius and status design tokens, polish card chrome

* [aidan] ux/agent-card: keep convert-to-workflow visible during runs with mid-turn toast

* [aidan] ux/mcp-bubble: drop redundant verb label when a workflow label is shown

* [aidan] chore/backend: remove stale explanatory comments

* [aidan] fix/workflows-hub: load workflows on hub mount so calendar fills at launch

* [aidan] feat/workflows: generate title, description, step labels at convert time

* [aidan] fix/tidy-layout: include workflows hub in tidy and fit-to-view

* [aidan] feat/schedule-list: window long list via measured-height virtualizer

* [aidan] ux/workflows-hub: remove time-saved badge from calendar header

* [aidan] fix/types: add missing semantic-type labels and drop stray fade arg

* [aidan] feat/schedule: pin monthly day-of-month and honor repeat-every intervals

* [aidan] feat/schedule: inherit source-session tool surface for scheduled runs

* [aidan] ux/calendar: restack hour-cell events as bars with overflow affordance

* [aidan] feat/calendar: open the run card when clicking a scheduled occurrence

* [aidan] ux/missed-runs: add per-group select-all toggle and rename skip action

* [aidan] feat: new scheduled task design ported

* [aidan] ui: sidebar reorder, repeat controls on schedule card

* [aidan] ui: sidebar, scheduling time

* [aidan] feat/schedule: pin monthly last-day-of-month

* [aidan] feat/steps: per-step enable toggle

* [aidan] feat/workflows: per-workflow color swatch

* [aidan] feat/trash: soft-delete workflows with restore and purge

* [aidan] feat/run-monitor: live run monitor card on the canvas

* [aidan] feat/run-context: attach a run as removable chat context

* [aidan] feat/compose: new-workflow landing page and auto-commit build flow

* [aidan] ui/workflows: dark mode and design-system cohesion

* [aidan] ui/calendar: overflow popover, condensed week view, scroll fix

* [aidan] feat/home: ongoing runs, missed review, and accurate Coming-up counts

* [aidan] fix/run-status: sync ongoing runs and heal stuck/interrupted runs

* [aidan] ux/schedule: last-day-of-month UI, Run-at time typing, interval input

* [aidan] ux/workflows: default window size and toolbar icon

* [aidan] fix/schedule: measure ran_late from start and anchor recurrences to created_at

* [aidan] feat/calendar: render fire times from backend, drop JS recurrence reimpl

* [aidan] chore/dashboard: drop dead configure/missed-run cards, refetch on reconnect

* [aidan] chore/agent-card: remove unreachable convert-to-workflow action

* [aidan] fix/workflows: don't bump updated_at on a no-op draft commit so viewing a workflow doesn't reorder the sidebar

* [aidan] feat/schedule: warn when scheduling a workflow that has no steps

* [aidan] fix/selection-tool: never select the workflows app, and exit the tool on Escape without dropping selections

* [aidan] ux/compose: diversify new-workflow starter prompts across personas

* [aidan] ux/run-monitor: spawn the run card a bit farther right of the workflows app

* [aidan] fix/schedule: harden run recovery and storage writes against crashes

* [aidan] ux/compose: restyle new-workflow starters as a clean pill cluster with rich prompts

* [aidan] fix/workflows: optimistically apply edits so the schedule banner updates instantly

* [aidan] ui/workflows: three-tone surface depth so the window lifts off the canvas in both themes

* [aidan] ui/workflows: close buttons turn red on hover, matching the chat card

* [aidan] test/schedule: cover executor pipeline, storage durability, and recurrence gaps

* [aidan] fix: remove package-lock json

* [aidan] fix/workflows-compose: keep compose view until edit agent replies

* [aidan] feat/workflows: auto-generate workflow + step titles with typewriter animation

* [eric] deps: restore frontend/package-lock.json (PR #105 deletion broke npm ci)

---------

Co-authored-by: Eric <ciregenz@berkeley.edu>
Co-authored-by: cire <134991075+ciregenz@users.noreply.github.com>
This commit is contained in:
Aidan
2026-06-24 18:58:43 -07:00
committed by ciregenz
co-authored by Eric cire
parent ab6037267c
commit 3008f083ca
6432 changed files with 1320099 additions and 257 deletions
@@ -0,0 +1,566 @@
import json
import os
import shutil
import regex as re
from dateparser_scripts.order_languages import _get_language_locale_dict
from dateparser_scripts.utils import get_dict_difference, get_raw_data
APOSTROPHE_LOOK_ALIKE_CHARS = [
"\N{RIGHT SINGLE QUOTATION MARK}", # '\u2019'
"\N{MODIFIER LETTER APOSTROPHE}", # '\u02bc'
"\N{MODIFIER LETTER TURNED COMMA}", # '\u02bb'
"\N{ARMENIAN APOSTROPHE}", # '\u055a'
"\N{LATIN SMALL LETTER SALTILLO}", # '\ua78c'
"\N{PRIME}", # '\u2032'
"\N{REVERSED PRIME}", # '\u2035'
"\N{MODIFIER LETTER PRIME}", # '\u02b9'
"\N{FULLWIDTH APOSTROPHE}", # '\uff07'
]
DATE_ORDER_PATTERN = re.compile(
"([DMY])+\u200f*[-/. \t]*([DMY])+\u200f*[-/. \t]*([DMY])+"
)
RELATIVE_PATTERN = re.compile(r"(?<![\+\-]\s*)\{0\}")
DEFAULT_MONTH_PATTERN = re.compile(r"^M?\d+$", re.U)
RE_SANITIZE_APOSTROPHE = re.compile("|".join(APOSTROPHE_LOOK_ALIKE_CHARS))
AM_PATTERN = re.compile(r"^\s*[Aa]\s*\.?\s*[Mm]\s*\.?\s*$")
PM_PATTERN = re.compile(r"^\s*[Pp]\s*\.?\s*[Mm]\s*\.?\s*$")
PARENTHESIS_PATTERN = re.compile(r"[\(\)]")
cldr_dates_full_dir = "../raw_data/cldr_dates_full/main/"
def _filter_relative_string(relative_string):
return (
isinstance(relative_string, str)
and RELATIVE_PATTERN.search(relative_string)
and not PARENTHESIS_PATTERN.search(relative_string)
)
def _filter_month_name(month_name):
return not DEFAULT_MONTH_PATTERN.match(month_name)
def _retrieve_locale_data(locale):
ca_gregorian_file = cldr_dates_full_dir + locale + "/ca-gregorian.json"
dateFields_file = cldr_dates_full_dir + locale + "/dateFields.json"
with open(ca_gregorian_file) as f:
cldr_gregorian_data = json.load(f)
with open(dateFields_file) as g:
cldr_datefields_data = json.load(g)
gregorian_dict = cldr_gregorian_data["main"][locale]["dates"]["calendars"][
"gregorian"
]
date_fields_dict = cldr_datefields_data["main"][locale]["dates"]["fields"]
json_dict = {}
field_keys_1 = ["stand-alone", "format"]
field_keys_2 = [
"wide",
"abbreviated",
] # neglecting "narrow" to avoid problems in translation
year_keys = ["year", "year-short", "year-narrow"]
month_keys = ["month", "month-short", "month-narrow"]
week_keys = ["week", "week-short", "week-narrow"]
day_keys = ["day", "day-short", "day-narrow"]
hour_keys = ["hour", "hour-short", "hour-narrow"]
minute_keys = ["minute", "minute-short", "minute-narrow"]
second_keys = ["second", "second-short", "second-narrow"]
relative_keys = ["relativeTimePattern-count-one", "relativeTimePattern-count-other"]
json_dict["name"] = locale
try:
date_format_string = gregorian_dict["dateFormats"]["short"].upper()
except AttributeError:
date_format_string = gregorian_dict["dateFormats"]["short"]["_value"].upper()
json_dict["date_order"] = DATE_ORDER_PATTERN.sub(
r"\1\2\3", DATE_ORDER_PATTERN.search(date_format_string).group()
)
json_dict["january"] = list(
filter(
_filter_month_name,
[
gregorian_dict["months"][key1][key2]["1"]
for key1 in field_keys_1
for key2 in field_keys_2
],
)
)
json_dict["february"] = list(
filter(
_filter_month_name,
[
gregorian_dict["months"][key1][key2]["2"]
for key1 in field_keys_1
for key2 in field_keys_2
],
)
)
json_dict["march"] = list(
filter(
_filter_month_name,
[
gregorian_dict["months"][key1][key2]["3"]
for key1 in field_keys_1
for key2 in field_keys_2
],
)
)
json_dict["april"] = list(
filter(
_filter_month_name,
[
gregorian_dict["months"][key1][key2]["4"]
for key1 in field_keys_1
for key2 in field_keys_2
],
)
)
json_dict["may"] = list(
filter(
_filter_month_name,
[
gregorian_dict["months"][key1][key2]["5"]
for key1 in field_keys_1
for key2 in field_keys_2
],
)
)
json_dict["june"] = list(
filter(
_filter_month_name,
[
gregorian_dict["months"][key1][key2]["6"]
for key1 in field_keys_1
for key2 in field_keys_2
],
)
)
json_dict["july"] = list(
filter(
_filter_month_name,
[
gregorian_dict["months"][key1][key2]["7"]
for key1 in field_keys_1
for key2 in field_keys_2
],
)
)
json_dict["august"] = list(
filter(
_filter_month_name,
[
gregorian_dict["months"][key1][key2]["8"]
for key1 in field_keys_1
for key2 in field_keys_2
],
)
)
json_dict["september"] = list(
filter(
_filter_month_name,
[
gregorian_dict["months"][key1][key2]["9"]
for key1 in field_keys_1
for key2 in field_keys_2
],
)
)
json_dict["october"] = list(
filter(
_filter_month_name,
[
gregorian_dict["months"][key1][key2]["10"]
for key1 in field_keys_1
for key2 in field_keys_2
],
)
)
json_dict["november"] = list(
filter(
_filter_month_name,
[
gregorian_dict["months"][key1][key2]["11"]
for key1 in field_keys_1
for key2 in field_keys_2
],
)
)
json_dict["december"] = list(
filter(
_filter_month_name,
[
gregorian_dict["months"][key1][key2]["12"]
for key1 in field_keys_1
for key2 in field_keys_2
],
)
)
json_dict["monday"] = [
gregorian_dict["days"][key1][key2]["mon"]
for key1 in field_keys_1
for key2 in field_keys_2
]
json_dict["tuesday"] = [
gregorian_dict["days"][key1][key2]["tue"]
for key1 in field_keys_1
for key2 in field_keys_2
]
json_dict["wednesday"] = [
gregorian_dict["days"][key1][key2]["wed"]
for key1 in field_keys_1
for key2 in field_keys_2
]
json_dict["thursday"] = [
gregorian_dict["days"][key1][key2]["thu"]
for key1 in field_keys_1
for key2 in field_keys_2
]
json_dict["friday"] = [
gregorian_dict["days"][key1][key2]["fri"]
for key1 in field_keys_1
for key2 in field_keys_2
]
json_dict["saturday"] = [
gregorian_dict["days"][key1][key2]["sat"]
for key1 in field_keys_1
for key2 in field_keys_2
]
json_dict["sunday"] = [
gregorian_dict["days"][key1][key2]["sun"]
for key1 in field_keys_1
for key2 in field_keys_2
]
json_dict["am"] = [
AM_PATTERN.sub("am", x)
for x in [
gregorian_dict["dayPeriods"][key1][key2]["am"]
for key1 in field_keys_1
for key2 in field_keys_2
]
]
json_dict["pm"] = [
PM_PATTERN.sub("pm", x)
for x in [
gregorian_dict["dayPeriods"][key1][key2]["pm"]
for key1 in field_keys_1
for key2 in field_keys_2
]
]
json_dict["year"] = [date_fields_dict[key]["displayName"] for key in year_keys]
json_dict["month"] = [date_fields_dict[key]["displayName"] for key in month_keys]
json_dict["week"] = [date_fields_dict[key]["displayName"] for key in week_keys]
json_dict["day"] = [date_fields_dict[key]["displayName"] for key in day_keys]
json_dict["hour"] = [date_fields_dict[key]["displayName"] for key in hour_keys]
json_dict["minute"] = [date_fields_dict[key]["displayName"] for key in minute_keys]
json_dict["second"] = [date_fields_dict[key]["displayName"] for key in second_keys]
json_dict["relative-type"] = {}
json_dict["relative-type"]["1 year ago"] = [
date_fields_dict[key]["relative-type--1"] for key in year_keys
]
json_dict["relative-type"]["0 year ago"] = [
date_fields_dict[key]["relative-type-0"] for key in year_keys
]
json_dict["relative-type"]["in 1 year"] = [
date_fields_dict[key]["relative-type-1"] for key in year_keys
]
json_dict["relative-type"]["1 month ago"] = [
date_fields_dict[key]["relative-type--1"] for key in month_keys
]
json_dict["relative-type"]["0 month ago"] = [
date_fields_dict[key]["relative-type-0"] for key in month_keys
]
json_dict["relative-type"]["in 1 month"] = [
date_fields_dict[key]["relative-type-1"] for key in month_keys
]
json_dict["relative-type"]["1 week ago"] = [
date_fields_dict[key]["relative-type--1"] for key in week_keys
]
json_dict["relative-type"]["0 week ago"] = [
date_fields_dict[key]["relative-type-0"] for key in week_keys
]
json_dict["relative-type"]["in 1 week"] = [
date_fields_dict[key]["relative-type-1"] for key in week_keys
]
json_dict["relative-type"]["1 day ago"] = [
date_fields_dict[key]["relative-type--1"] for key in day_keys
]
json_dict["relative-type"]["0 day ago"] = [
date_fields_dict[key]["relative-type-0"] for key in day_keys
]
json_dict["relative-type"]["in 1 day"] = [
date_fields_dict[key]["relative-type-1"] for key in day_keys
]
json_dict["relative-type"]["0 hour ago"] = [
date_fields_dict[key]["relative-type-0"] for key in hour_keys
]
json_dict["relative-type"]["0 minute ago"] = [
date_fields_dict[key]["relative-type-0"] for key in minute_keys
]
json_dict["relative-type"]["0 second ago"] = [
date_fields_dict[key]["relative-type-0"] for key in second_keys
]
json_dict["relative-type-regex"] = {}
json_dict["relative-type-regex"]["in \\1 year"] = list(
filter(
_filter_relative_string,
[
date_fields_dict[key1]["relativeTime-type-future"].get(key2)
for key1 in year_keys
for key2 in relative_keys
],
)
)
json_dict["relative-type-regex"]["\\1 year ago"] = list(
filter(
_filter_relative_string,
[
date_fields_dict[key1]["relativeTime-type-past"].get(key2)
for key1 in year_keys
for key2 in relative_keys
],
)
)
json_dict["relative-type-regex"]["in \\1 month"] = list(
filter(
_filter_relative_string,
[
date_fields_dict[key1]["relativeTime-type-future"].get(key2)
for key1 in month_keys
for key2 in relative_keys
],
)
)
json_dict["relative-type-regex"]["\\1 month ago"] = list(
filter(
_filter_relative_string,
[
date_fields_dict[key1]["relativeTime-type-past"].get(key2)
for key1 in month_keys
for key2 in relative_keys
],
)
)
json_dict["relative-type-regex"]["in \\1 week"] = list(
filter(
_filter_relative_string,
[
date_fields_dict[key1]["relativeTime-type-future"].get(key2)
for key1 in week_keys
for key2 in relative_keys
],
)
)
json_dict["relative-type-regex"]["\\1 week ago"] = list(
filter(
_filter_relative_string,
[
date_fields_dict[key1]["relativeTime-type-past"].get(key2)
for key1 in week_keys
for key2 in relative_keys
],
)
)
json_dict["relative-type-regex"]["in \\1 day"] = list(
filter(
_filter_relative_string,
[
date_fields_dict[key1]["relativeTime-type-future"].get(key2)
for key1 in day_keys
for key2 in relative_keys
],
)
)
json_dict["relative-type-regex"]["\\1 day ago"] = list(
filter(
_filter_relative_string,
[
date_fields_dict[key1]["relativeTime-type-past"].get(key2)
for key1 in day_keys
for key2 in relative_keys
],
)
)
json_dict["relative-type-regex"]["in \\1 hour"] = list(
filter(
_filter_relative_string,
[
date_fields_dict[key1]["relativeTime-type-future"].get(key2)
for key1 in hour_keys
for key2 in relative_keys
],
)
)
json_dict["relative-type-regex"]["\\1 hour ago"] = list(
filter(
_filter_relative_string,
[
date_fields_dict[key1]["relativeTime-type-past"].get(key2)
for key1 in hour_keys
for key2 in relative_keys
],
)
)
json_dict["relative-type-regex"]["in \\1 minute"] = list(
filter(
_filter_relative_string,
[
date_fields_dict[key1]["relativeTime-type-future"].get(key2)
for key1 in minute_keys
for key2 in relative_keys
],
)
)
json_dict["relative-type-regex"]["\\1 minute ago"] = list(
filter(
_filter_relative_string,
[
date_fields_dict[key1]["relativeTime-type-past"].get(key2)
for key1 in minute_keys
for key2 in relative_keys
],
)
)
json_dict["relative-type-regex"]["in \\1 second"] = list(
filter(
_filter_relative_string,
[
date_fields_dict[key1]["relativeTime-type-future"].get(key2)
for key1 in second_keys
for key2 in relative_keys
],
)
)
json_dict["relative-type-regex"]["\\1 second ago"] = list(
filter(
_filter_relative_string,
[
date_fields_dict[key1]["relativeTime-type-past"].get(key2)
for key1 in second_keys
for key2 in relative_keys
],
)
)
return json_dict
def _clean_string(given_string):
given_string = RE_SANITIZE_APOSTROPHE.sub("'", given_string)
given_string = given_string.replace(".", "")
given_string = given_string.lower()
return " ".join(given_string.split())
def _clean_dict(json_dict):
"""Remove duplicates and sort"""
for key, value in json_dict.items():
if isinstance(value, list):
json_dict[key] = sorted(dict.fromkeys(map(_clean_string, value)))
elif isinstance(value, dict):
json_dict[key] = dict(sorted(value.items()))
json_dict[key] = _clean_dict(json_dict[key])
return dict(filter(lambda x: x[1], json_dict.items()))
def main():
get_raw_data()
language_locale_dict = _get_language_locale_dict()
parent_directory = "../dateparser_data/cldr_language_data"
directory = "../dateparser_data/cldr_language_data/date_translation_data/"
if not os.path.isdir(parent_directory):
os.mkdir(parent_directory)
if os.path.isdir(directory):
shutil.rmtree(directory)
os.mkdir(directory)
for language in language_locale_dict:
json_language_dict = _clean_dict(_retrieve_locale_data(language))
locale_specific_dict = {}
locales_list = language_locale_dict[language]
for locale in locales_list:
json_locale_dict = _clean_dict(_retrieve_locale_data(locale))
locale_specific_dict[locale] = _clean_dict(
get_dict_difference(json_language_dict, json_locale_dict)
)
json_language_dict["locale_specific"] = dict(
sorted(locale_specific_dict.items())
)
filename = directory + language + ".json"
print("writing " + filename)
json_string = json.dumps(
json_language_dict, indent=4, separators=(",", ": "), ensure_ascii=False
).encode("utf-8")
with open(filename, "wb") as f:
f.write(json_string)
if __name__ == "__main__":
main()
@@ -0,0 +1,216 @@
import json
import os
import regex as re
import requests
from parsel import Selector
from dateparser_scripts.utils import get_raw_data
os.chdir(os.path.dirname(os.path.abspath(__file__)))
# Languages with insufficient translation data are excluded
avoid_languages = {"cu", "kkj", "nds", "prg", "tk", "vai", "vai-Latn", "vai-Vaii", "vo"}
def _get_language_locale_dict():
cldr_dates_full_dir = "../raw_data/cldr_dates_full/main/"
available_locale_names = os.listdir(cldr_dates_full_dir)
available_language_names = [
shortname
for shortname in available_locale_names
if not re.search(r"-[A-Z0-9]+$", shortname)
]
available_language_names.remove("root")
language_locale_dict = {}
for language_name in available_language_names:
language_locale_dict[language_name] = []
for locale_name in available_locale_names:
if re.match(language_name + "-[A-Z0-9]+$", locale_name):
language_locale_dict[language_name].append(locale_name)
for language in avoid_languages:
if language in language_locale_dict:
del language_locale_dict[language]
return language_locale_dict
def _get_language_order(language_locale_dict):
def get_most_common_locales():
# Order from https://w3techs.com/technologies/overview/content_language
# Last updated on 03.10.2022
old_common_locales = [
"en",
"ru",
"es",
"de",
"tr",
"fr",
"fa",
"ja",
"zh",
"vi",
"it",
"nl",
"pt",
"ar",
"pl",
"id",
"ko",
"uk",
"th",
"he",
"cs",
"sv",
"ro",
"el",
"da",
"hu",
"fi",
"sr",
"sk",
"bg",
"nb",
"hr",
"lt",
"no",
"hi",
"sl",
"ca",
"et",
]
response = requests.get(
"https://w3techs.com/technologies/overview/content_language"
)
sel = Selector(text=response.text)
if response.ok:
try:
bars = sel.xpath("//table[@class='bars']//a/@href").getall()
if not bars:
raise ValueError("No bars found")
new_most_common_locales = [
i.replace("https://w3techs.com/technologies/details/cl", "").strip(
"-"
)
for i in bars
]
if new_most_common_locales[0] != "en":
raise ValueError("English is not the first language")
except Exception as e:
print(e)
print("The website could have changed, please update the code")
return old_common_locales
else:
return old_common_locales
return new_most_common_locales
territory_info_file = "../raw_data/cldr_core/supplemental/territoryInfo.json"
with open(territory_info_file) as f:
territory_content = json.load(f)
territory_info_data = territory_content["supplemental"]["territoryInfo"]
language_population_dict = {}
for territory in territory_info_data:
population = int(territory_info_data[territory]["_population"])
try:
lang_dict = territory_info_data[territory]["languagePopulation"]
for language in lang_dict:
language_population = (
float(lang_dict[language]["_populationPercent"]) * population
)
if language in language_population_dict:
language_population_dict[language] += language_population
else:
language_population_dict[language] = language_population
except Exception:
pass
most_common_locales = get_most_common_locales()
language_order_with_duplicates = most_common_locales + sorted(
language_population_dict.keys(),
key=lambda x: (language_population_dict[x], x),
reverse=True,
)
language_order = sorted(
set(language_order_with_duplicates),
key=lambda x: language_order_with_duplicates.index(x),
)
for index in range(0, len(language_order)):
language_order[index] = re.sub(r"_", r"-", language_order[index])
cldr_languages = language_locale_dict.keys()
supplementary_date_directory = (
"../dateparser_data/supplementary_language_data/date_translation_data"
)
supplementary_languages = [x[:-5] for x in os.listdir(supplementary_date_directory)]
available_languages = set(cldr_languages).union(set(supplementary_languages))
language_order = [
shortname for shortname in language_order if shortname in available_languages
]
absent_languages = set(available_languages) - set(language_order)
remaining_languages = []
for language in absent_languages:
parent_language = re.sub(r"-\w+", "", language)
if parent_language in language_order:
language_order.insert(language_order.index(parent_language) + 1, language)
else:
remaining_languages.append(language)
language_order = language_order + sorted(remaining_languages)
language_order = list(map(str, language_order))
return language_order
def generate_language_map(language_order):
data = {}
for lang in sorted(language_order):
if "-" not in lang:
data[lang] = [lang]
else:
data[lang.split("-")[0]].append(lang)
return data
def main():
get_raw_data()
language_locale_dict = _get_language_locale_dict()
language_order = _get_language_order(language_locale_dict)
parent_directory = "../dateparser/data/"
filename = "../dateparser/data/languages_info.py"
if not os.path.isdir(parent_directory):
os.mkdir(parent_directory)
language_order_string = "language_order = " + json.dumps(
language_order, separators=(",", ": "), indent=4
)
complete_language_locale_dict = {}
for key in language_order:
if key in language_locale_dict.keys():
complete_language_locale_dict[key] = sorted(language_locale_dict[key])
else:
complete_language_locale_dict[key] = []
language_locale_dict_string = "language_locale_dict = " + json.dumps(
complete_language_locale_dict, separators=(",", ": "), indent=4
)
language_map_data = generate_language_map(language_order)
language_map_data_string = "language_map = " + json.dumps(
language_map_data, separators=(",", ": "), indent=4
)
languages_info_string = (
language_order_string
+ "\n\n"
+ language_map_data_string
+ "\n\n"
+ language_locale_dict_string
+ "\n"
)
with open(filename, "w") as f:
f.write(languages_info_string)
if __name__ == "__main__":
main()
@@ -0,0 +1,48 @@
#!/usr/bin/env python3
import os
from tempfile import TemporaryFile
from dateparser.data.languages_info import language_locale_dict
def to_string(data):
result = ""
language_column_width = 18
for language in sorted(data):
result += language
locales = data[language]
if locales:
result += " " * (language_column_width - len(language))
result += ", ".join("'{}'".format(locale) for locale in sorted(locales))
result += "\n"
return result
def main():
readme_path = os.path.join(
os.path.dirname(__file__), "..", "docs", "supported_locales.rst"
)
new_data = to_string(language_locale_dict)
temporary_file = TemporaryFile("w+")
with open(readme_path) as readme_file:
delimiter = "============ ================================================================\n"
delimiters_seen = 0
is_inside_table = False
for line in readme_file:
if line == delimiter:
delimiters_seen += 1
is_inside_table = delimiters_seen == 2
elif is_inside_table:
continue
temporary_file.write(line)
if is_inside_table:
temporary_file.write(new_data)
temporary_file.seek(0)
with open(readme_path, "w") as readme_file:
readme_file.write(temporary_file.read())
temporary_file.close()
if __name__ == "__main__":
main()
@@ -0,0 +1,72 @@
import os
import shutil
from git import Repo
def get_raw_data():
cldr_version = "31.0.1"
raw_data_directory = "../raw_data"
cldr_data = {
"dates_full": {
"url": "https://github.com/unicode-cldr/cldr-dates-full.git",
"dir": "{}/cldr_dates_full/".format(raw_data_directory),
},
"core": {
"url": "https://github.com/unicode-cldr/cldr-core.git",
"dir": "{}/cldr_core/".format(raw_data_directory),
},
"rbnf": {
"url": "https://github.com/unicode-cldr/cldr-rbnf.git",
"dir": "{}/cldr_rbnf/".format(raw_data_directory),
},
}
if os.path.isdir(raw_data_directory):
# remove current raw data
shutil.rmtree(raw_data_directory)
os.mkdir(raw_data_directory)
for name, data in cldr_data.items():
print('Clonning "{}" from: {}'.format(name, data["url"]))
repo = Repo.clone_from(data["url"], data["dir"], branch="master")
repo.git.co(cldr_version)
def get_dict_difference(parent_dict, child_dict):
difference_dict = {}
for key, child_value in child_dict.items():
parent_value = parent_dict.get(key)
child_specific_value = None
if not parent_value:
child_specific_value = child_value
elif isinstance(child_value, list):
child_specific_value = sorted(set(child_value) - set(parent_value))
elif isinstance(child_value, dict):
child_specific_value = get_dict_difference(parent_value, child_value)
elif child_value != parent_value:
child_specific_value = child_value
if child_specific_value:
difference_dict[key] = child_specific_value
return difference_dict
def combine_dicts(primary_dict, supplementary_dict):
combined_dict = {}
for key, value in primary_dict.items():
if key in supplementary_dict:
if isinstance(value, list):
combined_dict[key] = value + supplementary_dict[key]
elif isinstance(value, dict):
combined_dict[key] = combine_dicts(value, supplementary_dict[key])
else:
combined_dict[key] = supplementary_dict[key]
else:
combined_dict[key] = primary_dict[key]
remaining_keys = [
key for key in supplementary_dict.keys() if key not in primary_dict.keys()
]
for key in remaining_keys:
combined_dict[key] = supplementary_dict[key]
return combined_dict
@@ -0,0 +1,166 @@
import json
import os
import shutil
import regex as re
from ruamel.yaml import YAML
from dateparser_scripts.order_languages import avoid_languages
from dateparser_scripts.utils import combine_dicts
cldr_date_directory = "../dateparser_data/cldr_language_data/date_translation_data/"
supplementary_directory = "../dateparser_data/supplementary_language_data/"
supplementary_date_directory = (
"../dateparser_data/supplementary_language_data/date_translation_data/"
)
translation_data_directory = "../dateparser/data/"
date_translation_directory = "../dateparser/data/date_translation_data/"
os.chdir(os.path.dirname(os.path.abspath(__file__)))
cldr_languages = list(
set(map(lambda x: x[:-5], os.listdir(cldr_date_directory))) - avoid_languages
)
supplementary_languages = [x[:-5] for x in os.listdir(supplementary_date_directory)]
all_languages = set(cldr_languages).union(set(supplementary_languages))
RELATIVE_PATTERN = re.compile(r"\{0\}")
POSSESSIVE_DIGIT_PATTERN = re.compile(r"\\d\+\[\.,\]\?\\d\*")
def _make_possessive(s):
return POSSESSIVE_DIGIT_PATTERN.sub(r"\\d++[.,]?\\d*+", s)
def _to_plain_types(obj):
"""Recursively convert ruamel.yaml CommentedMap/CommentedSeq to plain
dict/list so that json.dumps produces stable output across all
Python versions.
Python 3.14 changed the json C encoder to bypass the Python-level
``__iter__``/``items()`` of dict subclasses and access the underlying C
dict directly. ruamel.yaml's CommentedMap relies on its Python-level
iteration for correct key ordering, so the C shortcut produces a
different (non-deterministic) key order on 3.14. Converting to plain
types before serialisation avoids the issue entirely.
"""
if isinstance(obj, dict):
return {k: _to_plain_types(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [_to_plain_types(v) for v in obj]
return obj
def _modify_relative_data(relative_data):
modified_relative_data = {}
for key, value in relative_data.items():
for i, string in enumerate(value):
string = RELATIVE_PATTERN.sub(r"(\\d++[.,]?\\d*+)", string)
string = _make_possessive(string)
value[i] = string
modified_relative_data[key] = value
return modified_relative_data
def _modify_simplifications(simplifications):
for simplification in simplifications:
for pattern in list(simplification.keys()):
new_pattern = _make_possessive(pattern)
if new_pattern != pattern:
simplification[new_pattern] = simplification.pop(pattern)
def _modify_data(language_data):
relative_data = language_data.get("relative-type-regex", {})
relative_data = _modify_relative_data(relative_data)
simplifications = language_data.get("simplifications", [])
_modify_simplifications(simplifications)
locale_specific_data = language_data.get("locale_specific", {})
for _, info in locale_specific_data.items():
locale_relative_data = info.get("relative-type-regex", {})
locale_relative_data = _modify_relative_data(locale_relative_data)
def _get_complete_date_translation_data(language):
cldr_data = {}
supplementary_data = {}
if language in cldr_languages:
with open(cldr_date_directory + language + ".json") as f:
cldr_data = json.load(f)
if language in supplementary_languages:
with open(supplementary_date_directory + language + ".yaml") as g:
yaml = YAML()
supplementary_data = dict(yaml.load(g))
complete_data = combine_dicts(cldr_data, supplementary_data)
if "name" not in complete_data:
complete_data["name"] = language
return complete_data
def _write_file(filename, text, mode, in_memory, in_memory_result):
if in_memory:
in_memory_result[filename] = text
else:
with open(filename, mode) as out:
out.write(text)
def write_complete_data(in_memory=False):
"""
This function is responsible of generating the needed py files from the
CLDR files (JSON format) and supplementary language data (YAML format).
Use it with in_memory=True to avoid writing real files and getting a
dictionary containing the file names and their content (used when testing).
"""
in_memory_result = {}
if not in_memory:
if not os.path.isdir(translation_data_directory):
os.mkdir(translation_data_directory)
if os.path.isdir(date_translation_directory):
shutil.rmtree(date_translation_directory)
os.mkdir(date_translation_directory)
with open(supplementary_directory + "base_data.yaml") as f:
yaml = YAML()
base_data = yaml.load(f)
for language in all_languages:
date_translation_data = _get_complete_date_translation_data(language)
date_translation_data = combine_dicts(date_translation_data, base_data)
date_translation_data = _to_plain_types(date_translation_data)
_modify_data(date_translation_data)
translation_data = json.dumps(
date_translation_data, indent=4, separators=(",", ": "), ensure_ascii=False
)
out_text = ("info = " + translation_data + "\n").encode("utf-8")
_write_file(
date_translation_directory + language + ".py",
out_text,
"wb",
in_memory,
in_memory_result,
)
init_text = (
"from dateparser.data import date_translation_data\n"
"from .languages_info import language_order, language_locale_dict\n"
)
_write_file(
translation_data_directory + "__init__.py",
init_text,
"w",
False,
in_memory_result,
)
_write_file(
date_translation_directory + "__init__.py", "", "w", False, in_memory_result
)
return in_memory_result
if __name__ == "__main__":
write_complete_data()