Johnniewhite commited on
Commit
9150b81
1 Parent(s): e5187c6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +119 -121
app.py CHANGED
@@ -1,126 +1,124 @@
1
  import os
 
 
 
2
  import gradio as gr
3
- import time
4
-
5
- from langchain.chat_models import ChatOpenAI
6
 
7
  # Set your OpenAI API key
8
- os.environ["OPENAI_API_KEY"] = "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"
9
-
10
- # Initialize the ChatOpenAI model
11
- chat_model = ChatOpenAI(model="gpt-3.5-turbo-1106", temperature=0.2)
12
-
13
- # Define the apartment details dictionary
14
- apartment_details = {
15
- "1": {
16
- "name": "Luxury Apartment in Downtown",
17
- "address": "123 Main St, Anytown, USA",
18
- "bedrooms": 2,
19
- "bathrooms": 2,
20
- "sqft": 1200,
21
- "price": "$2000/month",
22
- "description": "Beautiful luxury apartment in the heart of downtown. Spacious living area, modern kitchen, and stunning views."
23
- },
24
- "2": {
25
- "name": "Cozy Studio near Park",
26
- "address": "456 Elm St, Anytown, USA",
27
- "bedrooms": 0,
28
- "bathrooms": 1,
29
- "sqft": 500,
30
- "price": "$1000/month",
31
- "description": "Charming studio apartment located near the park. Perfect for a single person or couple. Close to amenities."
32
- },
33
- "3": {
34
- "name": "Family-Friendly Townhouse",
35
- "address": "789 Oak St, Anytown, USA",
36
- "bedrooms": 3,
37
- "bathrooms": 2.5,
38
- "sqft": 1800,
39
- "price": "$2500/month",
40
- "description": "Spacious townhouse with plenty of room for a family. Close to schools, parks, and shopping centers."
41
- }
42
- }
43
-
44
- def provide_information(apartment_id=None):
45
- if apartment_id:
46
- apartment_info = apartment_details.get(apartment_id)
47
- if apartment_info:
48
- return (
49
- f"Name: {apartment_info['name']}\n"
50
- f"Address: {apartment_info['address']}\n"
51
- f"Bedrooms: {apartment_info['bedrooms']}\n"
52
- f"Bathrooms: {apartment_info['bathrooms']}\n"
53
- f"Square Footage: {apartment_info['sqft']} sqft\n"
54
- f"Price: {apartment_info['price']}\n"
55
- f"Description: {apartment_info['description']}"
56
- )
57
- else:
58
- return "Apartment not found"
59
- else:
60
- all_apartments_info = ""
61
- for apartment_id, apartment_info in apartment_details.items():
62
- all_apartments_info += (
63
- f"Apartment ID: {apartment_id}\n"
64
- f"Name: {apartment_info['name']}\n"
65
- f"Address: {apartment_info['address']}\n"
66
- f"Bedrooms: {apartment_info['bedrooms']}\n"
67
- f"Bathrooms: {apartment_info['bathrooms']}\n"
68
- f"Square Footage: {apartment_info['sqft']} sqft\n"
69
- f"Price: {apartment_info['price']}\n"
70
- f"Description: {apartment_info['description']}\n\n"
71
- )
72
- return all_apartments_info
73
-
74
- def make_purchase_reservation(apartment_id: str, documents: dict):
75
- # Print the provided data and a success message
76
- print(f"Apartment ID: {apartment_id}, Documents: {documents}")
77
- return "SUCCESS"
78
-
79
- def execute_purchase(apartment_id, documents):
80
- # For simplicity, let's just print the data provided and a success message
81
- print(f"Apartment ID: {apartment_id}, Documents: {documents}")
82
- return make_purchase_reservation(apartment_id, documents)
83
-
84
- def update_owner_information(owner_id, new_number):
85
- # For simplicity, let's just print the data provided and a success message
86
- print(f"Owner ID: {owner_id}, New Number: {new_number}")
87
- return "Owner information updated successfully."
88
-
89
- def handle_message(message, history=None):
90
- # Split message into parts
91
- parts = message.split()
92
-
93
- # Check for different categories of problems
94
- if "provide information" in message:
95
- if "on Apartment" in message:
96
- apartment_id = parts[-1]
97
- return provide_information(apartment_id)
 
 
 
 
98
  else:
99
- return provide_information()
100
- elif "execute purchase" in message:
101
- apartment_id, *documents = parts[-2:]
102
- return execute_purchase(apartment_id, " ".join(documents))
103
- elif "update owner information" in message:
104
- owner_id, new_number = parts[-2:]
105
- return update_owner_information(owner_id, new_number)
106
- elif "list all houses" in message:
107
- return provide_information()
108
- else:
109
- # Use the LangChain model for general chat
110
- response = chat_model.predict(message)
111
- return response
112
-
113
- # Create a Gradio chat interface
114
- gr.ChatInterface(
115
- handle_message,
116
- chatbot=gr.Chatbot(height=300),
117
- textbox=gr.Textbox(placeholder="How can I help you today?", container=True, scale=8),
118
- title="Joe's Real Estate Chatbot",
119
- description="Ask D'Law any law related question",
120
- theme="compact",
121
- examples=["list all houses", "provide information on Apartment 2", "execute purchase on apartment 2", "update owner information on apartment"],
122
- retry_btn=None,
123
- submit_btn='Send',
124
- undo_btn=False,
125
- clear_btn="Clear",
126
- ).launch(share=True)
 
1
  import os
2
+ import re
3
+ from datetime import datetime, timedelta
4
+ import openai
5
  import gradio as gr
6
+ from ics import Calendar, Event
 
 
7
 
8
  # Set your OpenAI API key
9
+ openai.api_key = ("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")
10
+
11
+ # Define a custom calendar class
12
+ class CustomCalendar:
13
+ def __init__(self, file_path):
14
+ self.file_path = file_path
15
+ self.calendar = Calendar()
16
+
17
+ def create_event(self, title, start_time, end_time):
18
+ event = Event()
19
+ event.name = title
20
+ event.begin = start_time
21
+ event.end = end_time
22
+ self.calendar.events.add(event)
23
+ self.save_to_file()
24
+
25
+ def update_event(self, old_title, new_start_time, new_end_time):
26
+ for event in self.calendar.events:
27
+ if event.name == old_title:
28
+ event.begin = new_start_time
29
+ event.end = new_end_time
30
+ self.save_to_file()
31
+ break
32
+
33
+ def get_events(self):
34
+ return list(self.calendar.events)
35
+
36
+ def save_to_file(self):
37
+ with open(self.file_path, "w") as file:
38
+ file.writelines(self.calendar)
39
+
40
+ # Helper function to extract event details from the chatbot's response
41
+ def extract_event_details(response):
42
+ time_pattern = r"(\d{1,2})\s*([ap]m)"
43
+ title_pattern = r"(for|about)\s+(.+)"
44
+
45
+ time_match = re.search(time_pattern, response, re.IGNORECASE)
46
+ title_match = re.search(title_pattern, response, re.IGNORECASE)
47
+
48
+ if time_match:
49
+ hour = int(time_match.group(1))
50
+ meridiem = time_match.group(2).lower()
51
+ if meridiem == "pm" and hour < 12:
52
+ hour += 12
53
+ elif meridiem == "am" and hour == 12:
54
+ hour = 0
55
+
56
+ if title_match:
57
+ title = title_match.group(2)
58
+
59
+ if time_match and title_match:
60
+ start_time = datetime.now().replace(hour=hour, minute=0, second=0, microsecond=0)
61
+ end_time = start_time + timedelta(hours=1)
62
+ return title, start_time, end_time
63
+
64
+ return None, None, None
65
+
66
+ # Function to handle user messages
67
+ def handle_message(texts):
68
+ global calendar
69
+ responses = []
70
+
71
+ for text in texts:
72
+ response = openai.ChatCompletion.create(
73
+ model="gpt-3.5-turbo",
74
+ messages=[{"role": "user", "content": text}],
75
+ temperature=0.7,
76
+ )
77
+ response_text = response.choices[0].message.content
78
+
79
+ # Check for event creation or adjustment
80
+ title, start_time, end_time = extract_event_details(response_text)
81
+ if title and start_time and end_time:
82
+ if "create" in text or "set" in text or "make" in text:
83
+ calendar.create_event(title, start_time, end_time)
84
+ responses.append(f"Appointment created: {title} at {start_time.strftime('%I:%M %p')}")
85
+ elif "change" in text or "adjust" in text or "modify" in text:
86
+ old_title = None
87
+ for event in calendar.get_events():
88
+ if event.name.lower() in response_text.lower():
89
+ old_title = event.name
90
+ break
91
+ if old_title:
92
+ calendar.update_event(old_title, start_time, end_time)
93
+ responses.append(f"Appointment updated: {old_title} to {start_time.strftime('%I:%M %p')}")
94
+ else:
95
+ responses.append("Sorry, I couldn't find the appointment you wanted to adjust.")
96
+ elif "show" in response_text or "list" in response_text or "view" in response_text:
97
+ events = calendar.get_events()
98
+ if events:
99
+ event_list = "\n".join([f"{event.name}: {event.begin.strftime('%I:%M %p')} - {event.end.strftime('%I:%M %p')}" for event in events])
100
+ responses.append(f"Your appointments:\n{event_list}")
101
+ else:
102
+ responses.append("You don't have any appointments scheduled.")
103
  else:
104
+ responses.append(response_text)
105
+
106
+ return responses
107
+
108
+ # Define calendar file path
109
+ calendar_file_path = "calendar.ics"
110
+
111
+ # Create a custom calendar instance
112
+ calendar = CustomCalendar(calendar_file_path)
113
+
114
+ # Define Gradio interface
115
+ iface = gr.Interface(
116
+ fn=handle_message,
117
+ inputs=gr.Textbox(lines=3, label="Enter your messages (one per line)"),
118
+ outputs="text",
119
+ title="Calendar Chatbot",
120
+ description="Interact with the chatbot to manage your calendar events.",
121
+ )
122
+
123
+ # Run the Gradio interface
124
+ iface.launch(debug=True)