voiceCal / core /calendar_service.py
Peter Michael Gits
feat: Deploy complete VoiceCal application with all files v0.5.6
5e8a657
"""
Calendar Service - Simplified Google Calendar integration for Hugging Face.
This is a streamlined version that focuses on the core booking functionality
while being compatible with the HF environment.
"""
import logging
from typing import Dict, List, Any, Optional
from datetime import datetime, timedelta
import json
from .config import config
logger = logging.getLogger(__name__)
class CalendarService:
"""Simplified Google Calendar service for HF deployment."""
def __init__(self):
self.calendar_id = config.google_calendar_id
# For development/demo mode, we'll simulate calendar operations
self.demo_mode = not (config.google_client_id and config.google_client_secret)
if self.demo_mode:
logger.warning("πŸ“… Running in demo mode - no actual calendar integration")
else:
logger.info("πŸ“… Google Calendar integration enabled")
async def book_appointment(self, booking_info: Dict[str, Any], user_info: Dict[str, Any]) -> Dict[str, Any]:
"""Book an appointment on Google Calendar."""
try:
if self.demo_mode:
return self._simulate_booking(booking_info, user_info)
# TODO: Implement actual Google Calendar booking
# For now, return simulation
return self._simulate_booking(booking_info, user_info)
except Exception as e:
logger.error(f"Booking error: {e}")
return {
"success": False,
"error": str(e)
}
def _simulate_booking(self, booking_info: Dict[str, Any], user_info: Dict[str, Any]) -> Dict[str, Any]:
"""Simulate a booking for demo purposes."""
# Generate a mock event
event_id = f"demo_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
# Parse the booking info
date_time = booking_info.get("date_time", "2024-01-01 14:00")
duration = booking_info.get("duration", 30)
meeting_type = booking_info.get("meeting_type", "google_meet")
topic = booking_info.get("topic", "Meeting")
# Create event details
event = {
"id": event_id,
"start_time": date_time,
"duration": duration,
"topic": topic,
"attendee_name": user_info.get("name", "Guest"),
"attendee_email": user_info.get("email", ""),
"attendee_phone": user_info.get("phone", ""),
"meeting_type": meeting_type
}
# Add Google Meet link for video meetings
if meeting_type == "google_meet":
event["meet_link"] = f"πŸŽ₯ **Google Meet:** https://meet.google.com/demo-link-{event_id[:8]}"
return {
"success": True,
"event": event,
"message": "Demo booking created successfully!"
}
async def get_availability(self, days: int = 7) -> str:
"""Get availability information."""
if self.demo_mode:
return self._simulate_availability(days)
# TODO: Implement actual availability checking
return self._simulate_availability(days)
def _simulate_availability(self, days: int = 7) -> str:
"""Simulate availability for demo purposes."""
today = datetime.now()
availability = []
for i in range(days):
date = today + timedelta(days=i)
day_name = date.strftime("%A")
date_str = date.strftime("%B %d")
if date.weekday() < 5: # Weekday
times = ["9:00 AM", "11:00 AM", "2:00 PM", "4:00 PM"]
else: # Weekend
times = ["10:00 AM", "1:00 PM", "3:00 PM"]
# Randomly remove some slots to simulate bookings
import random
available_times = random.sample(times, max(1, len(times) - random.randint(0, 2)))
availability.append(f"**{day_name}, {date_str}:** {', '.join(available_times)}")
return "\n".join(availability)
async def cancel_appointment(self, event_id: str) -> Dict[str, Any]:
"""Cancel an appointment."""
if self.demo_mode:
return {
"success": True,
"message": f"Demo appointment {event_id} cancelled successfully!"
}
# TODO: Implement actual cancellation
return {
"success": False,
"error": "Cancellation not yet implemented"
}
async def list_upcoming_events(self, days: int = 7) -> List[Dict[str, Any]]:
"""List upcoming events."""
if self.demo_mode:
return self._simulate_upcoming_events(days)
# TODO: Implement actual event listing
return self._simulate_upcoming_events(days)
def _simulate_upcoming_events(self, days: int = 7) -> List[Dict[str, Any]]:
"""Simulate upcoming events for demo."""
events = []
today = datetime.now()
# Create a few sample events
import random
for i in range(3):
date = today + timedelta(days=i+1, hours=random.randint(9, 17))
events.append({
"id": f"demo_event_{i}",
"summary": f"Sample Meeting {i+1}",
"start_time": date.strftime("%Y-%m-%d %H:%M"),
"duration": 30,
"attendees": ["sample@email.com"]
})
return events
def format_event_for_display(self, event: Dict[str, Any]) -> str:
"""Format an event for display."""
start_time = event.get("start_time", "")
duration = event.get("duration", 30)
topic = event.get("topic", "Meeting")
formatted = f"πŸ“… {topic}\n"
formatted += f"πŸ• {start_time} ({duration} minutes)\n"
if event.get("meet_link"):
formatted += f"{event['meet_link']}\n"
return formatted