nniehaus commited on
Commit
7409805
·
verified ·
1 Parent(s): faf6738

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -96
app.py CHANGED
@@ -1,34 +1,20 @@
1
  import streamlit as st
2
  import openai
3
- import os
4
- import urllib.parse
5
 
6
  # Ensure your OpenAI API key is set in your environment variables
7
  openai.api_key = os.environ["OPENAI_API_KEY"]
8
 
9
- # Mapping of state names to abbreviations
10
- STATE_ABBREVIATIONS = {
11
- 'alabama': 'al', 'alaska': 'ak', 'arizona': 'az', 'arkansas': 'ar', 'california': 'ca',
12
- 'colorado': 'co', 'connecticut': 'ct', 'delaware': 'de', 'florida': 'fl', 'georgia': 'ga',
13
- 'hawaii': 'hi', 'idaho': 'id', 'illinois': 'il', 'indiana': 'in', 'iowa': 'ia',
14
- 'kansas': 'ks', 'kentucky': 'ky', 'louisiana': 'la', 'maine': 'me', 'maryland': 'md',
15
- 'massachusetts': 'ma', 'michigan': 'mi', 'minnesota': 'mn', 'mississippi': 'ms', 'missouri': 'mo',
16
- 'montana': 'mt', 'nebraska': 'ne', 'nevada': 'nv', 'new hampshire': 'nh', 'new jersey': 'nj',
17
- 'new mexico': 'nm', 'new york': 'ny', 'north carolina': 'nc', 'north dakota': 'nd',
18
- 'ohio': 'oh', 'oklahoma': 'ok', 'oregon': 'or', 'pennsylvania': 'pa', 'rhode island': 'ri',
19
- 'south carolina': 'sc', 'south dakota': 'sd', 'tennessee': 'tn', 'texas': 'tx',
20
- 'utah': 'ut', 'vermont': 'vt', 'virginia': 'va', 'washington': 'wa', 'west virginia': 'wv',
21
- 'wisconsin': 'wi', 'wyoming': 'wy'
22
- }
23
-
24
  initial_messages = [{
25
  "role": "system",
26
  "content": """
27
- You are a neighborhood matchmaker. Given a person's preferences in terms of amenities,
28
- lifestyle, and priorities, suggest exactly three neighborhoods that best match their needs
29
- in a specified city. For each neighborhood, start with a numbered line (1., 2., or 3.)
30
- followed by the full location in the format: 'Neighborhood, City, State:' then provide
31
- a brief description on the next line.
 
32
  """
33
  }]
34
 
@@ -36,64 +22,16 @@ def call_openai_api(messages):
36
  return openai.ChatCompletion.create(
37
  model="gpt-3.5-turbo",
38
  messages=messages,
39
- max_tokens=300
40
  )
41
 
42
- def parse_neighborhoods(response_text):
43
- """
44
- Parse the response text to extract neighborhood information.
45
- Returns a list of dictionaries containing neighborhood info.
46
- """
47
- neighborhoods = []
48
- lines = response_text.strip().split('\n')
49
- for line in lines:
50
- line = line.strip()
51
- if line and (line.startswith('1.') or line.startswith('2.') or line.startswith('3.')):
52
- if ':' in line:
53
- location_parts = line.split(':', 1)[0].split(',')
54
- if len(location_parts) >= 3:
55
- neighborhood = location_parts[0].split('.', 1)[1].strip()
56
- city = location_parts[1].strip()
57
- state = location_parts[2].strip()
58
- neighborhoods.append({
59
- 'neighborhood': neighborhood,
60
- 'city': city,
61
- 'state': state,
62
- 'full': f"{neighborhood}, {city}, {state}"
63
- })
64
- return neighborhoods
65
-
66
- def format_zillow_search(neighborhood_info):
67
- """
68
- Format the location string for Zillow search using 'neighborhood, city, state' format with commas and _rb at the end.
69
- Fallback to a city-level search if the neighborhood is not recognized.
70
- """
71
- # Prepare each component with correct capitalization and format for Zillow
72
- neighborhood = urllib.parse.quote(neighborhood_info['neighborhood'])
73
- city = urllib.parse.quote(neighborhood_info['city'])
74
-
75
- # Convert full state name to abbreviation if needed
76
- state = neighborhood_info['state'].lower()
77
- state_abbr = STATE_ABBREVIATIONS.get(state, state[:2]).upper() # Ensure state is uppercase
78
-
79
- # Primary search path with neighborhood
80
- search_path = f"{neighborhood},-{city},-{state_abbr}_rb"
81
- url = f"https://www.zillow.com/homes/{search_path}/"
82
-
83
- # Check URL - fallback to city-level URL if Zillow cannot interpret it
84
- if not neighborhood: # If neighborhood is empty or unrecognized, return a city-level search URL
85
- search_path = f"{city},-{state_abbr}_rb"
86
- url = f"https://www.zillow.com/homes/{search_path}/"
87
-
88
- return url
89
-
90
- def CustomChatGPT(city, preferences, messages):
91
  query = f"""
92
- User is looking for neighborhoods in {city} with these preferences: {preferences}.
93
- Please suggest exactly 3 suitable neighborhoods. For each one:
94
- 1. Start with a number (1., 2., or 3.)
95
- 2. Provide the full location as 'Neighborhood, City, State:'
96
- 3. Add a brief description on the next line
97
  """
98
 
99
  messages.append({"role": "user", "content": query})
@@ -110,34 +48,22 @@ if "reply" not in st.session_state:
110
  st.session_state["reply"] = None
111
 
112
  # Centered title
113
- st.markdown("<h1 style='text-align: center; color: black;'>Ideal Neighborhood Finder</h1>", unsafe_allow_html=True)
114
 
115
  # User inputs
116
  col1, col2 = st.columns(2)
117
  with col1:
118
- st.markdown("<h2 style='text-align: center; color: black;'>Your Preferences</h2>", unsafe_allow_html=True)
119
- city = st.text_input("City", placeholder="Enter the city you want to search in")
120
- preferences = st.text_area("Describe your ideal neighborhood", placeholder="E.g., family-friendly, near parks, vibrant nightlife")
121
- generate_button = st.button('Find Neighborhoods')
122
 
123
  # Process results on button click
124
- if generate_button and city and preferences:
125
  messages = initial_messages.copy()
126
- st.session_state["reply"], _ = CustomChatGPT(city, preferences, messages)
127
 
128
  # Display results if there is a reply in session state
129
  if st.session_state["reply"]:
130
  with col2:
131
- st.markdown("<h2 style='text-align: center; color: black;'>Recommended Neighborhoods ⬇️</h2>", unsafe_allow_html=True)
132
  st.write(st.session_state["reply"])
133
-
134
- # Extract and display Zillow links
135
- neighborhoods = parse_neighborhoods(st.session_state["reply"])
136
-
137
- if neighborhoods:
138
- st.markdown("### 🏠 Zillow Search Links")
139
- for hood in neighborhoods:
140
- zillow_url = format_zillow_search(hood)
141
- st.markdown(f"- [Search homes in {hood['neighborhood']}, {hood['city']}, {hood['state']}]({zillow_url})")
142
- else:
143
- st.warning("Unable to generate Zillow links. Please try again.")
 
1
  import streamlit as st
2
  import openai
3
+ import os
 
4
 
5
  # Ensure your OpenAI API key is set in your environment variables
6
  openai.api_key = os.environ["OPENAI_API_KEY"]
7
 
8
+ # Initial system message setup for the video topic generator
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  initial_messages = [{
10
  "role": "system",
11
  "content": """
12
+ You are an assistant helping a real estate agent brainstorm video topics and outlines.
13
+ Based on a specified goal or area of focus, suggest five video topics with outlines.
14
+ Each topic should be numbered (1-5) and should include:
15
+ - A catchy title for the video
16
+ - A brief summary of the video's content
17
+ - Key points or segments the video should cover (bullet points)
18
  """
19
  }]
20
 
 
22
  return openai.ChatCompletion.create(
23
  model="gpt-3.5-turbo",
24
  messages=messages,
25
+ max_tokens=500
26
  )
27
 
28
+ def CustomChatGPT(goal, messages):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  query = f"""
30
+ The real estate agent's goal is: {goal}.
31
+ Please provide five video topic ideas with the following structure:
32
+ 1. Title: A catchy title
33
+ 2. Summary: Brief description of the content
34
+ 3. Key Points: Bullet points of segments to cover
35
  """
36
 
37
  messages.append({"role": "user", "content": query})
 
48
  st.session_state["reply"] = None
49
 
50
  # Centered title
51
+ st.markdown("<h1 style='text-align: center; color: black;'>Real Estate Video Topic Generator</h1>", unsafe_allow_html=True)
52
 
53
  # User inputs
54
  col1, col2 = st.columns(2)
55
  with col1:
56
+ st.markdown("<h2 style='text-align: center; color: black;'>Your Video Goal</h2>", unsafe_allow_html=True)
57
+ goal = st.text_area("Describe the focus or goal for your videos", placeholder="E.g., attracting first-time homebuyers, showcasing luxury properties, or explaining market trends.")
58
+ generate_button = st.button('Generate Video Topics')
 
59
 
60
  # Process results on button click
61
+ if generate_button and goal:
62
  messages = initial_messages.copy()
63
+ st.session_state["reply"], _ = CustomChatGPT(goal, messages)
64
 
65
  # Display results if there is a reply in session state
66
  if st.session_state["reply"]:
67
  with col2:
68
+ st.markdown("<h2 style='text-align: center; color: black;'>Video Topics & Outlines ⬇️</h2>", unsafe_allow_html=True)
69
  st.write(st.session_state["reply"])