nniehaus commited on
Commit
51ff7fb
·
verified ·
1 Parent(s): 43952b4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -22
app.py CHANGED
@@ -9,7 +9,11 @@ openai.api_key = os.environ["OPENAI_API_KEY"]
9
  initial_messages = [{
10
  "role": "system",
11
  "content": """
12
- You are a neighborhood matchmaker. Given a person's preferences in terms of amenities, lifestyle, and priorities, suggest three neighborhoods that best match their needs in a specified city. For each neighborhood, include the full location in the format: Neighborhood, City, State, and keep descriptions concise (one or two sentences).
 
 
 
 
13
  """
14
  }]
15
 
@@ -20,8 +24,50 @@ def call_openai_api(messages):
20
  max_tokens=300 # Limit tokens to keep responses concise
21
  )
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  def CustomChatGPT(city, preferences, messages):
24
- query = f"User is looking for neighborhoods in {city} with these preferences: {preferences}. Suggest suitable neighborhoods and describe each briefly, including the full location as Neighborhood, City, State."
 
 
 
 
 
 
 
25
  messages.append({"role": "user", "content": query})
26
  response = call_openai_api(messages)
27
  ChatGPT_reply = response["choices"][0]["message"]["content"]
@@ -31,7 +77,7 @@ def CustomChatGPT(city, preferences, messages):
31
  # Streamlit setup
32
  st.set_page_config(layout="wide")
33
 
34
- # Initialize session state for storing the API reply
35
  if "reply" not in st.session_state:
36
  st.session_state["reply"] = None
37
 
@@ -40,7 +86,6 @@ st.markdown("<h1 style='text-align: center; color: black;'>Ideal Neighborhood Fi
40
 
41
  # User inputs
42
  col1, col2 = st.columns(2)
43
-
44
  with col1:
45
  st.markdown("<h2 style='text-align: center; color: black;'>Your Preferences</h2>", unsafe_allow_html=True)
46
  city = st.text_input("City", placeholder="Enter the city you want to search in")
@@ -50,7 +95,7 @@ with col1:
50
  # Process results on button click
51
  if generate_button and city and preferences:
52
  messages = initial_messages.copy()
53
- st.session_state["reply"], _ = CustomChatGPT(city, preferences, messages) # Store response in session state
54
 
55
  # Display results if there is a reply in session state
56
  if st.session_state["reply"]:
@@ -58,21 +103,13 @@ if st.session_state["reply"]:
58
  st.markdown("<h2 style='text-align: center; color: black;'>Recommended Neighborhoods ⬇️</h2>", unsafe_allow_html=True)
59
  st.write(st.session_state["reply"])
60
 
61
- # Extract only lines with the format "Neighborhood, City, State:"
62
- neighborhoods = []
63
- for line in st.session_state["reply"].splitlines():
64
- if line and "," in line and ":" in line: # Ensure it matches "Neighborhood, City, State:"
65
- location = line.split(":")[0].strip() # Capture up to the first colon
66
- # Remove any numbering
67
- if location[0].isdigit():
68
- location = location.split(" ", 1)[1].strip()
69
- neighborhoods.append(location)
70
 
71
- # Display Zillow links
72
- st.markdown("### Zillow Search Links")
73
- for location in neighborhoods:
74
- # Format the search query correctly
75
- full_location_query = urllib.parse.quote(location)
76
- zillow_url = f"https://www.zillow.com/homes/{full_location_query}_rb/"
77
-
78
- st.markdown(f"- [Search for homes in {location} on Zillow]({zillow_url})")
 
9
  initial_messages = [{
10
  "role": "system",
11
  "content": """
12
+ You are a neighborhood matchmaker. Given a person's preferences in terms of amenities,
13
+ lifestyle, and priorities, suggest exactly three neighborhoods that best match their needs
14
+ in a specified city. For each neighborhood, start with a numbered line (1., 2., or 3.)
15
+ followed by the full location in the format: 'Neighborhood, City, State:' then provide
16
+ a brief description on the next line.
17
  """
18
  }]
19
 
 
24
  max_tokens=300 # Limit tokens to keep responses concise
25
  )
26
 
27
+ def parse_neighborhoods(response_text):
28
+ """
29
+ Parse the response text to extract neighborhood information more reliably.
30
+ Returns a list of tuples containing (neighborhood name, full location string)
31
+ """
32
+ neighborhoods = []
33
+ current_location = ""
34
+
35
+ # Split the response into lines and process each line
36
+ lines = response_text.strip().split('\n')
37
+ for line in lines:
38
+ line = line.strip()
39
+ # Look for lines that start with a number and contain location info
40
+ if line and (line.startswith('1.') or line.startswith('2.') or line.startswith('3.')):
41
+ if ':' in line:
42
+ # Remove the number and leading space
43
+ location = line.split('.', 1)[1].strip()
44
+ # Split at the colon to get just the location part
45
+ location = location.split(':', 1)[0].strip()
46
+ if ',' in location:
47
+ neighborhoods.append(location)
48
+
49
+ return neighborhoods
50
+
51
+ def format_zillow_search(location):
52
+ """
53
+ Format the location string for Zillow search, handling special characters and spaces.
54
+ """
55
+ # Remove any special characters and extra spaces
56
+ clean_location = ' '.join(location.split())
57
+ # Encode the location for URL
58
+ encoded_location = urllib.parse.quote(clean_location)
59
+ # Create the Zillow search URL
60
+ return f"https://www.zillow.com/homes/{encoded_location}_rb/"
61
+
62
  def CustomChatGPT(city, preferences, messages):
63
+ query = f"""
64
+ User is looking for neighborhoods in {city} with these preferences: {preferences}.
65
+ Please suggest exactly 3 suitable neighborhoods. For each one:
66
+ 1. Start with a number (1., 2., or 3.)
67
+ 2. Provide the full location as 'Neighborhood, City, State:'
68
+ 3. Add a brief description on the next line
69
+ """
70
+
71
  messages.append({"role": "user", "content": query})
72
  response = call_openai_api(messages)
73
  ChatGPT_reply = response["choices"][0]["message"]["content"]
 
77
  # Streamlit setup
78
  st.set_page_config(layout="wide")
79
 
80
+ # Initialize session state
81
  if "reply" not in st.session_state:
82
  st.session_state["reply"] = None
83
 
 
86
 
87
  # User inputs
88
  col1, col2 = st.columns(2)
 
89
  with col1:
90
  st.markdown("<h2 style='text-align: center; color: black;'>Your Preferences</h2>", unsafe_allow_html=True)
91
  city = st.text_input("City", placeholder="Enter the city you want to search in")
 
95
  # Process results on button click
96
  if generate_button and city and preferences:
97
  messages = initial_messages.copy()
98
+ st.session_state["reply"], _ = CustomChatGPT(city, preferences, messages)
99
 
100
  # Display results if there is a reply in session state
101
  if st.session_state["reply"]:
 
103
  st.markdown("<h2 style='text-align: center; color: black;'>Recommended Neighborhoods ⬇️</h2>", unsafe_allow_html=True)
104
  st.write(st.session_state["reply"])
105
 
106
+ # Extract and display Zillow links
107
+ neighborhoods = parse_neighborhoods(st.session_state["reply"])
 
 
 
 
 
 
 
108
 
109
+ if neighborhoods: # Only show the section if we successfully parsed neighborhoods
110
+ st.markdown("### 🏠 Zillow Search Links")
111
+ for location in neighborhoods:
112
+ zillow_url = format_zillow_search(location)
113
+ st.markdown(f"- [Search homes in {location}]({zillow_url})")
114
+ else:
115
+ st.warning("Unable to generate Zillow links. Please try again.")