Nusri7 commited on
Commit
a2a14da
Β·
verified Β·
1 Parent(s): d8e43d0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -39
app.py CHANGED
@@ -14,7 +14,7 @@ gmaps = googlemaps.Client(key=API_KEY)
14
 
15
  def get_business_suggestions(query, location):
16
  try:
17
- if not query or len(query) < 3: # Don't search for very short queries
18
  return []
19
  response = gmaps.places_autocomplete(query, location=location)
20
  return [{"name": item["description"], "place_id": item["place_id"]} for item in response]
@@ -25,12 +25,12 @@ def get_business_suggestions(query, location):
25
  def get_google_maps_rank(keyword, location, business_name, business_place_id, search_radius_km, max_results=5):
26
  results = {"keyword": keyword, "source": "Google Maps", "rank": None, "name": None, "address": None}
27
  search_radius_m = search_radius_km * 1000
28
-
29
  try:
30
  geocode = gmaps.geocode(location)
31
  if not geocode:
32
  return {"error": "Location not found"}
33
-
34
  latlng = geocode[0]['geometry']['location']
35
 
36
  places_result = gmaps.places(
@@ -38,10 +38,10 @@ def get_google_maps_rank(keyword, location, business_name, business_place_id, se
38
  location=(latlng['lat'], latlng['lng']),
39
  radius=search_radius_m
40
  )
41
-
42
  if 'results' not in places_result:
43
  return {"error": "No results found for this search"}
44
-
45
  places = places_result['results'][:max_results]
46
 
47
  for rank, place in enumerate(places, 1):
@@ -62,19 +62,19 @@ def get_serp_rankings(keyword, location, website_url=None):
62
  geocode = gmaps.geocode(location)
63
  if not geocode:
64
  return {"error": "Location not found"}
65
-
66
  params = {
67
  'key': SEARCH_API_KEY,
68
  'cx': CX,
69
  'q': f"{keyword} near {location}",
70
- 'gl': location.split(",")[-1].strip().lower(), # Country code
71
  'num': 10,
72
  'lr': 'lang_en'
73
  }
74
-
75
  response = requests.get("https://www.googleapis.com/customsearch/v1", params=params)
76
  results = response.json()
77
-
78
  if "items" in results:
79
  for i, item in enumerate(results["items"], 1):
80
  link = item.get("link", "")
@@ -86,7 +86,7 @@ def get_serp_rankings(keyword, location, website_url=None):
86
  "title": item.get("title", "N/A"),
87
  "link": link
88
  }
89
-
90
  return {
91
  "keyword": keyword,
92
  "source": "Google Search",
@@ -100,8 +100,45 @@ def get_serp_rankings(keyword, location, website_url=None):
100
 
101
  def save_to_excel(data, filename="my_website_rankings.xlsx"):
102
  try:
103
- df = pd.DataFrame(data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  df.to_excel(filename, index=False, engine='openpyxl')
 
105
  st.success(f"βœ… Your website rankings saved to **{filename}**")
106
  st.download_button(
107
  label="πŸ“₯ Download Excel File",
@@ -117,24 +154,20 @@ st.set_page_config(page_title="Business Rank Checker", layout="wide")
117
  st.title("πŸ“Š Business Rank Checker")
118
  st.markdown("Check your business ranking on Google Maps and search results")
119
 
120
- # Initialize session state variables
121
  if 'business_selection' not in st.session_state:
122
  st.session_state.business_selection = None
123
  if 'business_place_id' not in st.session_state:
124
  st.session_state.business_place_id = None
125
 
126
- # User Inputs
127
  with st.form("search_form"):
128
  col1, col2 = st.columns(2)
129
  with col1:
130
  location = st.text_input("πŸ“ Target Location", "Nottingham, MD, USA")
131
  with col2:
132
  search_radius_km = st.slider("πŸ” Search Radius (km)", 1, 20, 2)
133
-
134
- # Business name input with real-time suggestions
135
  business_query = st.text_input("🏒 Your Business Name", "", key="business_query")
136
-
137
- # Show suggestions as you type (appears automatically)
138
  if st.session_state.business_query and len(st.session_state.business_query) >= 3:
139
  suggestions = get_business_suggestions(st.session_state.business_query, location)
140
  if suggestions:
@@ -145,7 +178,6 @@ with st.form("search_form"):
145
  key="business_suggestion_select",
146
  label_visibility="collapsed"
147
  )
148
- # Update the selected business in session state
149
  if selected_option:
150
  st.session_state.business_selection = selected_option
151
  st.session_state.business_place_id = next(
@@ -154,7 +186,7 @@ with st.form("search_form"):
154
  )
155
  elif len(st.session_state.business_query) >= 3:
156
  st.warning("No matching businesses found")
157
-
158
  website_url = st.text_input("🌐 Your Website URL", "", help="Enter your website to check if it appears in search results")
159
  keywords_input = st.text_input("πŸ“Œ Search Keywords (comma separated)", "Phone repair, mobile repair")
160
 
@@ -162,29 +194,27 @@ with st.form("search_form"):
162
 
163
  if submitted and st.session_state.business_selection and st.session_state.business_place_id:
164
  keywords = [kw.strip() for kw in keywords_input.split(",") if kw.strip()]
165
-
166
  if not keywords:
167
  st.warning("Please enter at least one search keyword")
168
  st.stop()
169
-
170
- my_website_rankings = [] # Store only your website's rankings
171
-
172
  with st.spinner("Analyzing rankings..."):
173
  for keyword in keywords:
174
  st.subheader(f"πŸ” Results for keyword: '{keyword}'")
175
 
176
- # Google Maps Results
177
  st.markdown("### πŸ“Œ Google Maps Rankings")
178
  maps_rankings = get_google_maps_rank(
179
  keyword, location,
180
  st.session_state.business_selection, st.session_state.business_place_id,
181
  search_radius_km
182
  )
183
-
184
  if "error" in maps_rankings:
185
  st.error(f"Error: {maps_rankings['error']}")
186
  else:
187
- # Add to Excel data
188
  my_website_rankings.append({
189
  "Keyword": keyword,
190
  "Source": "Google Maps",
@@ -192,20 +222,16 @@ if submitted and st.session_state.business_selection and st.session_state.busine
192
  "Business Name": maps_rankings["name"],
193
  "Address": maps_rankings["address"]
194
  })
195
-
196
- # Display in app
197
  st.markdown(f"#### Your Business: **{st.session_state.business_selection}**")
198
  st.write(f"Rank: {maps_rankings['rank']}")
199
  st.write(f"Address: {maps_rankings['address']}")
200
-
201
- # SERP Results
202
  st.markdown(f"### 🌐 Search Results for '{keyword}' in {location}")
203
  serp_results = get_serp_rankings(keyword, location, website_url)
204
-
205
  if "error" in serp_results:
206
  st.error(serp_results["error"])
207
  else:
208
- # Add to Excel data
209
  my_website_rankings.append({
210
  "Keyword": keyword,
211
  "Source": "Google Search",
@@ -213,15 +239,13 @@ if submitted and st.session_state.business_selection and st.session_state.busine
213
  "Title": serp_results["title"],
214
  "Link": serp_results["link"]
215
  })
216
-
217
- # Display in app
218
  st.write(f"Rank: {serp_results['rank']}")
219
  if serp_results['rank'] != f"Not in top {10}":
220
  st.write(f"Title: {serp_results['title']}")
221
  st.write(f"Link: {serp_results['link']}")
222
-
223
- st.markdown("---") # Separator between keywords
224
-
225
- # Save your website's rankings to Excel
226
  if my_website_rankings:
227
- save_to_excel(my_website_rankings)
 
14
 
15
  def get_business_suggestions(query, location):
16
  try:
17
+ if not query or len(query) < 3:
18
  return []
19
  response = gmaps.places_autocomplete(query, location=location)
20
  return [{"name": item["description"], "place_id": item["place_id"]} for item in response]
 
25
  def get_google_maps_rank(keyword, location, business_name, business_place_id, search_radius_km, max_results=5):
26
  results = {"keyword": keyword, "source": "Google Maps", "rank": None, "name": None, "address": None}
27
  search_radius_m = search_radius_km * 1000
28
+
29
  try:
30
  geocode = gmaps.geocode(location)
31
  if not geocode:
32
  return {"error": "Location not found"}
33
+
34
  latlng = geocode[0]['geometry']['location']
35
 
36
  places_result = gmaps.places(
 
38
  location=(latlng['lat'], latlng['lng']),
39
  radius=search_radius_m
40
  )
41
+
42
  if 'results' not in places_result:
43
  return {"error": "No results found for this search"}
44
+
45
  places = places_result['results'][:max_results]
46
 
47
  for rank, place in enumerate(places, 1):
 
62
  geocode = gmaps.geocode(location)
63
  if not geocode:
64
  return {"error": "Location not found"}
65
+
66
  params = {
67
  'key': SEARCH_API_KEY,
68
  'cx': CX,
69
  'q': f"{keyword} near {location}",
70
+ 'gl': location.split(",")[-1].strip().lower(),
71
  'num': 10,
72
  'lr': 'lang_en'
73
  }
74
+
75
  response = requests.get("https://www.googleapis.com/customsearch/v1", params=params)
76
  results = response.json()
77
+
78
  if "items" in results:
79
  for i, item in enumerate(results["items"], 1):
80
  link = item.get("link", "")
 
86
  "title": item.get("title", "N/A"),
87
  "link": link
88
  }
89
+
90
  return {
91
  "keyword": keyword,
92
  "source": "Google Search",
 
100
 
101
  def save_to_excel(data, filename="my_website_rankings.xlsx"):
102
  try:
103
+ now = datetime.now()
104
+ current_date = now.strftime("%Y-%m-%d")
105
+ current_time = now.strftime("%H:%M:%S")
106
+
107
+ combined_data = {}
108
+
109
+ for entry in data:
110
+ keyword = entry["Keyword"]
111
+ if keyword not in combined_data:
112
+ combined_data[keyword] = {
113
+ "Date": current_date,
114
+ "Time": current_time,
115
+ "Keyword": keyword,
116
+ "Google Maps Rank": "-",
117
+ "Google Maps Business Name": "-",
118
+ "Google Maps Address": "-",
119
+ "SERP Rank": "-",
120
+ "SERP Title": "-",
121
+ "SERP Link": "-"
122
+ }
123
+
124
+ if entry["Source"] == "Google Maps":
125
+ combined_data[keyword]["Google Maps Rank"] = entry["Rank"]
126
+ combined_data[keyword]["Google Maps Business Name"] = entry.get("Business Name", "-")
127
+ combined_data[keyword]["Google Maps Address"] = entry.get("Address", "-")
128
+ elif entry["Source"] == "Google Search":
129
+ combined_data[keyword]["SERP Rank"] = entry["Rank"]
130
+ combined_data[keyword]["SERP Title"] = entry.get("Title", "-")
131
+ combined_data[keyword]["SERP Link"] = entry.get("Link", "-")
132
+
133
+ df = pd.DataFrame(list(combined_data.values()))
134
+ column_order = [
135
+ "Date", "Time", "Keyword",
136
+ "Google Maps Rank", "Google Maps Business Name", "Google Maps Address",
137
+ "SERP Rank", "SERP Title", "SERP Link"
138
+ ]
139
+ df = df[column_order]
140
  df.to_excel(filename, index=False, engine='openpyxl')
141
+
142
  st.success(f"βœ… Your website rankings saved to **{filename}**")
143
  st.download_button(
144
  label="πŸ“₯ Download Excel File",
 
154
  st.title("πŸ“Š Business Rank Checker")
155
  st.markdown("Check your business ranking on Google Maps and search results")
156
 
 
157
  if 'business_selection' not in st.session_state:
158
  st.session_state.business_selection = None
159
  if 'business_place_id' not in st.session_state:
160
  st.session_state.business_place_id = None
161
 
 
162
  with st.form("search_form"):
163
  col1, col2 = st.columns(2)
164
  with col1:
165
  location = st.text_input("πŸ“ Target Location", "Nottingham, MD, USA")
166
  with col2:
167
  search_radius_km = st.slider("πŸ” Search Radius (km)", 1, 20, 2)
168
+
 
169
  business_query = st.text_input("🏒 Your Business Name", "", key="business_query")
170
+
 
171
  if st.session_state.business_query and len(st.session_state.business_query) >= 3:
172
  suggestions = get_business_suggestions(st.session_state.business_query, location)
173
  if suggestions:
 
178
  key="business_suggestion_select",
179
  label_visibility="collapsed"
180
  )
 
181
  if selected_option:
182
  st.session_state.business_selection = selected_option
183
  st.session_state.business_place_id = next(
 
186
  )
187
  elif len(st.session_state.business_query) >= 3:
188
  st.warning("No matching businesses found")
189
+
190
  website_url = st.text_input("🌐 Your Website URL", "", help="Enter your website to check if it appears in search results")
191
  keywords_input = st.text_input("πŸ“Œ Search Keywords (comma separated)", "Phone repair, mobile repair")
192
 
 
194
 
195
  if submitted and st.session_state.business_selection and st.session_state.business_place_id:
196
  keywords = [kw.strip() for kw in keywords_input.split(",") if kw.strip()]
197
+
198
  if not keywords:
199
  st.warning("Please enter at least one search keyword")
200
  st.stop()
201
+
202
+ my_website_rankings = []
203
+
204
  with st.spinner("Analyzing rankings..."):
205
  for keyword in keywords:
206
  st.subheader(f"πŸ” Results for keyword: '{keyword}'")
207
 
 
208
  st.markdown("### πŸ“Œ Google Maps Rankings")
209
  maps_rankings = get_google_maps_rank(
210
  keyword, location,
211
  st.session_state.business_selection, st.session_state.business_place_id,
212
  search_radius_km
213
  )
214
+
215
  if "error" in maps_rankings:
216
  st.error(f"Error: {maps_rankings['error']}")
217
  else:
 
218
  my_website_rankings.append({
219
  "Keyword": keyword,
220
  "Source": "Google Maps",
 
222
  "Business Name": maps_rankings["name"],
223
  "Address": maps_rankings["address"]
224
  })
 
 
225
  st.markdown(f"#### Your Business: **{st.session_state.business_selection}**")
226
  st.write(f"Rank: {maps_rankings['rank']}")
227
  st.write(f"Address: {maps_rankings['address']}")
228
+
 
229
  st.markdown(f"### 🌐 Search Results for '{keyword}' in {location}")
230
  serp_results = get_serp_rankings(keyword, location, website_url)
231
+
232
  if "error" in serp_results:
233
  st.error(serp_results["error"])
234
  else:
 
235
  my_website_rankings.append({
236
  "Keyword": keyword,
237
  "Source": "Google Search",
 
239
  "Title": serp_results["title"],
240
  "Link": serp_results["link"]
241
  })
242
+
 
243
  st.write(f"Rank: {serp_results['rank']}")
244
  if serp_results['rank'] != f"Not in top {10}":
245
  st.write(f"Title: {serp_results['title']}")
246
  st.write(f"Link: {serp_results['link']}")
247
+
248
+ st.markdown("---")
249
+
 
250
  if my_website_rankings:
251
+ save_to_excel(my_website_rankings)