Spaces:
Sleeping
Sleeping
File size: 6,464 Bytes
233222c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 | import re
from datetime import datetime, timedelta, timezone
import pytz
from dateutil import parser
from typing import Optional, Tuple, Dict
from langchain_core.prompts import ChatPromptTemplate
from .core import get_llm
class DateHandler:
def __init__(self, default_timezone: str = "UTC"):
self.default_timezone = pytz.timezone(default_timezone)
self.llm = get_llm()
def parse_date_string(self, date_string: str) -> Optional[datetime]:
"""Parse date string using LLM and fallback to traditional parsing."""
try:
date_prompt = ChatPromptTemplate.from_messages([
("system", f"""
Convert the following natural language date input into a specific date in DD-MM-YYYY format.
Input: {date_string}
Rules:
- If the year is not specified, use the current year
- If month is not specified, use the next occurrence of that date
- For relative dates (tomorrow, next week, etc.), calculate from current date
- Handle phrases like "5th may", "7 march", "next monday", "tomorrow", "next week"
- If input is ambiguous, make a reasonable assumption and pick the next occurrence
- Return ONLY the date in DD-MM-YYYY format or "INVALID" if cannot be interpreted
Current date: {datetime.now().strftime('%d-%m-%Y')}
"""),
("human", "Please convert the date.")
])
response = (date_prompt | self.llm).invoke({})
llm_date = response.content.strip()
if llm_date != "INVALID":
try:
return datetime.strptime(llm_date, "%d-%m-%Y")
except ValueError:
pass
parsed_date = parser.parse(date_string, dayfirst=True, fuzzy=True)
if parsed_date.year == 1900:
current_year = datetime.now().year
parsed_date = parsed_date.replace(year=current_year)
current_date = datetime.now()
if parsed_date.date() < current_date.date():
if parsed_date.month < current_date.month:
parsed_date = parsed_date.replace(year=current_year + 1)
elif parsed_date.month == current_date.month and parsed_date.day < current_date.day:
parsed_date = parsed_date.replace(year=current_year + 1)
return parsed_date
except (ValueError, TypeError):
formats = [
"%d-%m-%Y", "%d/%m/%Y", "%m-%d-%Y", "%m/%d/%Y",
"%Y-%m-%d", "%Y/%m/%d", "%d.%m.%Y", "%m.%d.%Y",
"%d %b %Y", "%d %B %Y", "%b %d %Y", "%B %d %Y"
]
for fmt in formats:
try:
return datetime.strptime(date_string, fmt)
except ValueError:
continue
final_prompt = ChatPromptTemplate.from_messages([
("system", f"""
The user has provided this date input: '{date_string}'
Please interpret this as a future date, considering:
- Current date is {datetime.now().strftime('%d-%m-%Y')}
- If it's a relative date (tomorrow, next week), calculate accordingly
- If it's ambiguous, choose the next occurrence
- Return the date in DD-MM-YYYY format or "INVALID"
"""),
("human", "Please provide the interpreted date.")
])
final_response = (final_prompt | self.llm).invoke({})
final_date = final_response.content.strip()
if final_date != "INVALID":
try:
return datetime.strptime(final_date, "%d-%m-%Y")
except ValueError:
pass
return None
def validate_date(self, date_string: str, timezone_str: str = None) -> Tuple[bool, str, Optional[str]]:
"""Validate the parsed date."""
date_string = re.sub(r'\s+', ' ', date_string.strip())
parsed_date = self.parse_date_string(date_string)
if not parsed_date:
return False, "", "I couldn't understand that date format. Please provide a date like '7 March' or 'next Monday'."
current_date = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
if parsed_date.replace(tzinfo=timezone.utc) < current_date:
return False, "", "The date cannot be in the past. Please provide a future date."
max_future_date = current_date + timedelta(days=730)
if parsed_date.replace(tzinfo=timezone.utc) > max_future_date:
return False, "", "The date cannot be more than 2 years in the future."
formatted_date = parsed_date.strftime("%d-%m-%Y")
return True, formatted_date, None
def get_phase_dates(self, phase_start_date: str, timezone_str: str) -> Dict[str, str]:
tz = pytz.timezone(timezone_str)
phase_start = datetime.strptime(phase_start_date, "%d-%m-%Y")
phase_start = tz.localize(phase_start.replace(hour=0, minute=0, second=0, microsecond=0))
phase_end = phase_start + timedelta(days=15)
drill_registration_start = datetime.now(tz).replace(microsecond=0)
drill_registration_end = phase_start - timedelta(days=1)
return {
"phaseStartDt": phase_start.strftime("%d-%m-%Y"),
"phaseEndDt": phase_end.strftime("%d-%m-%Y"),
"drillRegistrationStartDt": drill_registration_start.strftime("%d-%m-%Y"),
"drillRegistrationEndDt": drill_registration_end.strftime("%d-%m-%Y")
}
def get_timezone_offset(self, timezone_str: str) -> str:
tz = pytz.timezone(timezone_str)
offset = tz.utcoffset(datetime.now())
hours = int(offset.total_seconds() // 3600)
minutes = int((offset.total_seconds() % 3600) // 60)
return f"{'+' if hours >= 0 else '-'}{abs(hours):02d}:{minutes:02d}" |