test / app.py
Johnniewhite's picture
Update app.py
97fb7f7 verified
raw
history blame
No virus
4.45 kB
import os
import re
from datetime import datetime, timedelta
import openai
import gradio as gr
from ics import Calendar, Event
# Set your OpenAI API key
openai.api_key = ("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")
# Define a custom calendar class
class CustomCalendar:
def __init__(self, file_path):
self.file_path = file_path
self.calendar = Calendar()
def create_event(self, title, start_time, end_time):
event = Event()
event.name = title
event.begin = start_time
event.end = end_time
self.calendar.events.add(event)
self.save_to_file()
def update_event(self, old_title, new_start_time, new_end_time):
for event in self.calendar.events:
if event.name == old_title:
event.begin = new_start_time
event.end = new_end_time
self.save_to_file()
break
def get_events(self):
return list(self.calendar.events)
def save_to_file(self):
with open(self.file_path, "w") as file:
file.writelines(self.calendar)
# Helper function to extract event details from the chatbot's response
def extract_event_details(response):
time_pattern = r"(\d{1,2})\s*([ap]m)"
title_pattern = r"(for|about)\s+(.+)"
time_match = re.search(time_pattern, response, re.IGNORECASE)
title_match = re.search(title_pattern, response, re.IGNORECASE)
if time_match:
hour = int(time_match.group(1))
meridiem = time_match.group(2).lower()
if meridiem == "pm" and hour < 12:
hour += 12
elif meridiem == "am" and hour == 12:
hour = 0
if title_match:
title = title_match.group(2)
if time_match and title_match:
start_time = datetime.now().replace(hour=hour, minute=0, second=0, microsecond=0)
end_time = start_time + timedelta(hours=1)
return title, start_time, end_time
return None, None, None
# Function to handle user messages
def handle_message(texts):
global calendar
responses = []
for text in texts:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": text}],
temperature=0.7,
)
response_text = response.choices[0].message.content
# Check for event creation or adjustment
title, start_time, end_time = extract_event_details(response_text)
if title and start_time and end_time:
if "create" in text or "set" in text or "make" in text:
calendar.create_event(title, start_time, end_time)
responses.append(f"Appointment created: {title} at {start_time.strftime('%I:%M %p')}")
elif "change" in text or "adjust" in text or "modify" in text:
old_title = None
for event in calendar.get_events():
if event.name.lower() in response_text.lower():
old_title = event.name
break
if old_title:
calendar.update_event(old_title, start_time, end_time)
responses.append(f"Appointment updated: {old_title} to {start_time.strftime('%I:%M %p')}")
else:
responses.append("Sorry, I couldn't find the appointment you wanted to adjust.")
elif "show" in response_text or "list" in response_text or "view" in response_text:
events = calendar.get_events()
if events:
event_list = "\n".join([f"{event.name}: {event.begin.strftime('%I:%M %p')} - {event.end.strftime('%I:%M %p')}" for event in events])
responses.append(f"Your appointments:\n{event_list}")
else:
responses.append("You don't have any appointments scheduled.")
else:
responses.append(response_text)
return responses
# Define calendar file path
calendar_file_path = "calendar.ics"
# Create a custom calendar instance
calendar = CustomCalendar(calendar_file_path)
# Define Gradio interface
iface = gr.Interface(
fn=handle_message,
inputs=gr.Textbox(lines=3, label="Enter your messages (one per line)"),
outputs="text",
title="Calendar Chatbot",
description="Interact with the chatbot to manage your calendar events.",
)
# Run the Gradio interface
iface.launch(debug=True, share=True)