Spaces:
Sleeping
Sleeping
Attempt 2
#1
by Emfin2429 - opened
12345678910111213141516171819202122232425262728293031323334353668 unmodified lines105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284"""Per Diem / Leave Start Date Calculator (Form e49)Reserve members accrue leave at 2.5 days per month of service (per theofficial "Leave Accrual to Date of Separation" chart), and take thatleave during the final days of the deployment, so the last day of leaveequals the end date on their orders.Given the FIRST and LAST day of the deployment, this app:1. Looks up how much leave was earned over that span, using the sameday-of-month / month accrual logic as the official chart (in 0.5-dayincrements).2. Truncates that to a whole number of usable days (leave can onlyactually be taken in whole days — e.g. 1.5 earned days means only1 day can be taken).3. Adds one bonus day if the deployment end date falls on a weekend orfederal holiday (existing rule, unchanged from the original app).4. Reports the leave start date, so the last day of leave still equalsthe deployment end date.--- IMPORTANT ASSUMPTION ABOUT THE ACCRUAL CHART ---The official chart is expressed relative to the start of the fiscal/leaveyear (Oct 1) and its values reset to ~0 every October. Real leave accrualdoes NOT actually reset mid-deployment — it just keeps accumulating at aconstant 2.5 days/month. Since 6-month deployments routinely cross anOct 1 boundary, this app reproduces the chart's exact day-of-month /month-of-year logic (verified to match the chart's printed valuesexactly within any single fiscal year), but does NOT hard-reset thecounter at each Oct 1 — leave earned is simply(accrual value at end date) - (accrual value at start date).If your unit's actual policy is that leave literally zeroes out everyOct 1 even mid-deployment, this calculation will need to change —flag it and it can be adjusted to hard-reset instead.Usage tracking: every time someone clicks "Calculate", a timestampedrow is appended to a log file in a separate Hugging Face dataset repo68 unmodified linesprint(f"Usage logging failed: {e}")def is_holiday(d: date) -> bool:"""Return True if d is a US federal holiday."""return d in US_HOLIDAYSdef is_weekend(d: date) -> bool:"""Return True if d is a Saturday or Sunday."""return d.weekday() >= 5# --- Leave accrual chart logic ---## The official "Leave Accrual to Date of Separation" table earns 2.5 days# per calendar month, subdivided into five 0.5-day steps per month based# on which 6-day bucket the day-of-month falls into:# days 1-6 -> +0.5 (bucket 1)# days 7-12 -> +1.0 (bucket 2)# days 13-18 -> +1.5 (bucket 3)# days 19-24 -> +2.0 (bucket 4)# days 25-31 -> +2.5 (bucket 5, i.e. the full month)## So within any month, accrued-since-start-of-month = bucket * 0.5, and# each full elapsed calendar month is worth a flat 2.5 days on top of that.def _day_bucket(day_of_month: int) -> int:"""Map a day-of-month (1-31) to its 6-day accrual bucket (1-5)."""if day_of_month <= 6:return 1elif day_of_month <= 12:return 2elif day_of_month <= 18:return 3elif day_of_month <= 24:return 4else:return 5 # 25-31 (or 25-28/29/30 for shorter months)def _accrual_value(d: date) -> float:"""A running accrual "odometer" value for date d: increases by 2.5 forevery full calendar month, plus the partial-month bucket amount.This is anchored to an arbitrary fixed point (not Oct 1 of anyparticular year), which is fine because only *differences* betweentwo of these values are ever used — the anchor cancels out."""absolute_month_index = d.year * 12 + (d.month - 1)return absolute_month_index * 2.5 + _day_bucket(d.day) * 0.5def earned_leave_days(deployment_start: date, deployment_end: date) -> float:"""Days of leave earned over the deployment, per the accrual chart,rounded to the nearest 0.5 to avoid floating point drift."""raw = _accrual_value(deployment_end) - _accrual_value(deployment_start)return round(raw * 2) / 2def calc_leave_plan(deployment_start: date, deployment_end: date) -> dict:"""Given the deployment's first and last day, compute:- earned: raw leave earned (chart lookup, in 0.5-day increments)- usable: whole days actually usable (earned, truncated down)- exception: whether the end date is a weekend/holiday bonus day- total_days: usable days actually taken (usable + bonus day if any)- leave_start: first day of leave (last day is always deployment_end)"""earned = earned_leave_days(deployment_start, deployment_end)usable = int(earned) # whole days only; e.g. 1.5 -> 1 (earned is always >= 0)exception = is_weekend(deployment_end) or is_holiday(deployment_end)total_days = usable + (1 if exception else 0)leave_start = deployment_end - timedelta(days=max(total_days - 1, 0))return {"earned": earned,"usable": usable,"exception": exception,"total_days": total_days,"leave_start": leave_start,"leave_end": deployment_end,}def _parse_date_input(value):"""gr.DateTime can hand back either a datetime object, a string, or anumeric timestamp depending on how the value was set, so handle allthree defensively."""if value is None:return Noneif isinstance(value, str):return datetime.strptime(value.split(" ")[0], "%Y-%m-%d").date()if isinstance(value, (int, float)):return datetime.fromtimestamp(value).date()return value.date()def submit_leave_dates(deployment_start_input, deployment_end_input):deployment_start = _parse_date_input(deployment_start_input)deployment_end = _parse_date_input(deployment_end_input)if deployment_start is None or deployment_end is None:return "Please select both a deployment start date and end date."if deployment_end < deployment_start:return "The deployment end date can't be before the start date."plan = calc_leave_plan(deployment_start, deployment_end)if plan["total_days"] <= 0:return (f"Based on a deployment from {deployment_start:%B %d, %Y} to "f"{deployment_end:%B %d, %Y}, you earned {plan['earned']:g} days ""of leave — not enough to take a full day off.")reason = []if is_weekend(deployment_end):reason.append("your end date falls on a weekend")if is_holiday(deployment_end):reason.append("your end date is a federal holiday")extra_note = (f" You get one extra day of leave because {' and '.join(reason)}, "f"for {plan['total_days']} total days off."if plan["exception"]else "")# Log this use (best-effort, won't block or break the result).log_usage()return (f"Based on a deployment from {deployment_start:%B %d, %Y} to "f"{deployment_end:%B %d, %Y}, you earned {plan['earned']:g} days of "f"leave. Since leave can only be taken in whole days, you can use "f"{plan['usable']} day(s).{extra_note}\n\n"f"Your leave starts on {plan['leave_start']:%B %d, %Y} "f"and ends on {plan['leave_end']:%B %d, %Y}.")with gr.Blocks(title="Leave Start Date Calculator") as app:gr.Markdown("# Leave Start Date Calculator\n""Enter the **first and last day of your deployment** to see how ""much leave you earned and when it starts. Your last day of leave ""will always be your deployment's end date.")with gr.Row():start_input = gr.DateTime(label="First day of deployment",include_time=False,type="datetime",)end_input = gr.DateTime(label="Last day of deployment (Form e49 end date)",include_time=False,type="datetime",)submit_btn = gr.Button("Calculate", variant="primary")output = gr.Textbox(label="Result", interactive=False, lines=4)submit_btn.click(fn=submit_leave_dates, inputs=[start_input, end_input], outputs=output)end_input.submit(fn=submit_leave_dates, inputs=[start_input, end_input], outputs=output)if __name__ == "__main__":app.launch()123456789101112131468 unmodified lines8384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166"""Per Diem / Leave Start Date Calculator (Form e49)Reserve members accrue leave (typically 15 days for a 6-month deployment)and take it during the last 15 days of the deployment, so the last day ofleave equals the end date on their orders. Given that end date, this apptells them when their leave starts.Rule: leave is 15 days inclusive of start and end date.If the end date falls on a weekend or federal holiday, the member getsone extra day of leave (so the start date shifts one day earlier).Usage tracking: every time someone clicks "Calculate", a timestampedrow is appended to a log file in a separate Hugging Face dataset repo68 unmodified linesprint(f"Usage logging failed: {e}")def is_holiday(end_date: date) -> bool:"""Return True if end_date is a US federal holiday."""return end_date in US_HOLIDAYSdef is_weekend(end_date: date) -> bool:"""Return True if end_date is a Saturday or Sunday."""return end_date.weekday() >= 5def fifteen_days_prior(end_date: date, exception: bool) -> date:"""Return the date 15 days (inclusive) before end_date.If `exception` is True (end date is a weekend/holiday), the membergets one extra day of leave, so we go back 15 days instead of 14."""if exception:return end_date - timedelta(days=15)return end_date - timedelta(days=14)def calc_leave_dates(end_date: date) -> tuple[date, date]:"""Determine the leave start date given the leave end date."""exception = is_weekend(end_date) or is_holiday(end_date)start_date = fifteen_days_prior(end_date, exception)return start_date, end_datedef submit_leave_date(end_of_leave):if end_of_leave is None:return "Please select a date."# gr.DateTime can hand back either a datetime object or a string# depending on how the value was set, so handle both defensively.if isinstance(end_of_leave, str):end_of_leave = datetime.strptime(end_of_leave.split(" ")[0], "%Y-%m-%d").date()elif isinstance(end_of_leave, (int, float)):end_of_leave = datetime.fromtimestamp(end_of_leave).date()else:end_of_leave = end_of_leave.date()start_date, end_date = calc_leave_dates(end_of_leave)reason = []if is_weekend(end_date):reason.append("your end date falls on a weekend")if is_holiday(end_date):reason.append("your end date is a federal holiday")extra_note = f" (You get an extra day of leave because {' and '.join(reason)}.)" if reason else ""# Log this use (best-effort, won't block or break the result).log_usage()return (f"Your leave starts on {start_date:%B %d, %Y} "f"and ends on {end_date:%B %d, %Y}.{extra_note}")with gr.Blocks(title="Leave Start Date Calculator") as app:gr.Markdown("# Leave Start Date Calculator\n""Enter the **end date of your deployment (Form e49 end date)** ""to find out when your 15 days of leave will start.")date_input = gr.DateTime(label="When is the end of your leave?",include_time=False,type="datetime",)submit_btn = gr.Button("Calculate", variant="primary")output = gr.Textbox(label="Result", interactive=False)submit_btn.click(fn=submit_leave_date, inputs=date_input, outputs=output)date_input.submit(fn=submit_leave_date, inputs=date_input, outputs=output)if __name__ == "__main__":app.launch()
app.py+61-179