Nusri7's picture
Update app.py
7e7dbe4 verified
raw
history blame
8.34 kB
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)