Spaces:
Running
Running
File size: 8,338 Bytes
0878cf7 7e7dbe4 0878cf7 7e7dbe4 0878cf7 7e7dbe4 0878cf7 7e7dbe4 0878cf7 7e7dbe4 0878cf7 7e7dbe4 0878cf7 7e7dbe4 0878cf7 |
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 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 |
import streamlit as st
import googlemaps
import pandas as pd
import requests
from datetime import datetime
# π Google API Keys
API_KEY = "AIzaSyCHmsNAEP7I-ASxt8uS2kxc8O5P2x_-KQY"
SEARCH_API_KEY = "AIzaSyCHmsNAEP7I-ASxt8uS2kxc8O5P2x_-KQY"
CX = "561935e384c5e4a19" # Your Custom Search Engine ID
# Initialize Google Maps client
gmaps = googlemaps.Client(key=API_KEY)
def get_business_suggestions(query, location):
try:
response = gmaps.places_autocomplete(query, location=location)
return [{"name": item["description"], "place_id": item["place_id"]} for item in response]
except Exception as e:
st.error(f"Autocomplete error: {str(e)}")
return []
def get_google_maps_rank(keyword, location, business_name, business_place_id, search_radius_km, max_results=5):
results = {"keyword": keyword, "source": "Google Maps", "rank": None, "name": None, "address": None}
search_radius_m = search_radius_km * 1000
try:
geocode = gmaps.geocode(location)
if not geocode:
return {"error": "Location not found"}
latlng = geocode[0]['geometry']['location']
places_result = gmaps.places(
query=keyword,
location=(latlng['lat'], latlng['lng']),
radius=search_radius_m
)
if 'results' not in places_result:
return {"error": "No results found for this search"}
places = places_result['results'][:max_results]
for rank, place in enumerate(places, 1):
if place["place_id"] == business_place_id:
results["rank"] = rank
results["name"] = place.get("name", "N/A")
results["address"] = place.get("formatted_address", "N/A")
return results
results["rank"] = f"Not in top {max_results}"
return results
except Exception as e:
return {"error": str(e)}
def get_serp_rankings(keyword, location, website_url=None):
try:
geocode = gmaps.geocode(location)
if not geocode:
return {"error": "Location not found"}
params = {
'key': SEARCH_API_KEY,
'cx': CX,
'q': f"{keyword} near {location}",
'gl': location.split(",")[-1].strip().lower(), # Country code
'num': 10,
'lr': 'lang_en'
}
response = requests.get("https://www.googleapis.com/customsearch/v1", params=params)
results = response.json()
if "items" in results:
for i, item in enumerate(results["items"], 1):
link = item.get("link", "")
if website_url and website_url.lower() in link.lower():
return {
"keyword": keyword,
"source": "Google Search",
"rank": i,
"title": item.get("title", "N/A"),
"link": link
}
return {
"keyword": keyword,
"source": "Google Search",
"rank": f"Not in top {len(results['items'])}",
"title": "N/A",
"link": "N/A"
}
return {"error": "No results found"}
except Exception as e:
return {"error": str(e)}
def save_to_excel(data, filename="my_website_rankings.xlsx"):
try:
df = pd.DataFrame(data)
df.to_excel(filename, index=False, engine='openpyxl')
st.success(f"β
Your website rankings saved to **{filename}**")
st.download_button(
label="π₯ Download Excel File",
data=open(filename, "rb").read(),
file_name=filename,
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)
except Exception as e:
st.error(f"Error saving Excel file: {str(e)}")
# Streamlit UI
st.set_page_config(page_title="Business Rank Checker", layout="wide")
st.title("π Business Rank Checker")
st.markdown("Check your business ranking on Google Maps and search results")
# User Inputs
with st.form("search_form"):
col1, col2 = st.columns(2)
with col1:
location = st.text_input("π Target Location", "Nottingham, MD, USA")
with col2:
search_radius_km = st.slider("π Search Radius (km)", 1, 20, 2)
# Combined business name input with autocomplete dropdown
business_query = st.text_input("π’ Your Business Name", "", key="business_query")
business_place_id = None
business_selection = None
if business_query:
suggestions = get_business_suggestions(business_query, location)
if suggestions:
# Create a selectbox that appears below the input field
selected_index = 0
options = [s["name"] for s in suggestions]
business_selection = st.selectbox(
"π Select from suggestions",
options=options,
index=selected_index,
key="business_selection",
label_visibility="collapsed" # Hide the label
)
business_place_id = next(s["place_id"] for s in suggestions if s["name"] == business_selection)
else:
st.warning("No matching businesses found")
website_url = st.text_input("π Your Website URL", "", help="Enter your website to check if it appears in search results")
keywords_input = st.text_input("π Search Keywords (comma separated)", "Phone repair, mobile repair")
submitted = st.form_submit_button("π Check Rankings")
if submitted and business_query and business_place_id:
keywords = [kw.strip() for kw in keywords_input.split(",") if kw.strip()]
if not keywords:
st.warning("Please enter at least one search keyword")
st.stop()
my_website_rankings = [] # Store only your website's rankings
with st.spinner("Analyzing rankings..."):
for keyword in keywords:
st.subheader(f"π Results for keyword: '{keyword}'")
# Google Maps Results
st.markdown("### π Google Maps Rankings")
maps_rankings = get_google_maps_rank(
keyword, location,
business_selection, business_place_id,
search_radius_km
)
if "error" in maps_rankings:
st.error(f"Error: {maps_rankings['error']}")
else:
# Add to Excel data
my_website_rankings.append({
"Keyword": keyword,
"Source": "Google Maps",
"Rank": maps_rankings["rank"],
"Business Name": maps_rankings["name"],
"Address": maps_rankings["address"]
})
# Display in app
st.markdown(f"#### Your Business: **{business_selection}**")
st.write(f"Rank: {maps_rankings['rank']}")
st.write(f"Address: {maps_rankings['address']}")
# SERP Results
st.markdown(f"### π Search Results for '{keyword}' in {location}")
serp_results = get_serp_rankings(keyword, location, website_url)
if "error" in serp_results:
st.error(serp_results["error"])
else:
# Add to Excel data
my_website_rankings.append({
"Keyword": keyword,
"Source": "Google Search",
"Rank": serp_results["rank"],
"Title": serp_results["title"],
"Link": serp_results["link"]
})
# Display in app
st.write(f"Rank: {serp_results['rank']}")
if serp_results['rank'] != f"Not in top {10}":
st.write(f"Title: {serp_results['title']}")
st.write(f"Link: {serp_results['link']}")
st.markdown("---") # Separator between keywords
# Save your website's rankings to Excel
if my_website_rankings:
save_to_excel(my_website_rankings) |