File size: 4,451 Bytes
994d7ce
9150b81
 
 
994d7ce
9150b81
994d7ce
 
9150b81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
994d7ce
9150b81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97fb7f7
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
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)