Nusri7 commited on
Commit
0878cf7
Β·
verified Β·
1 Parent(s): da2e64f

initial file

Browse files
Files changed (1) hide show
  1. app.py +209 -0
app.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import googlemaps
3
+ import pandas as pd
4
+ import requests
5
+ from datetime import datetime
6
+
7
+ # πŸ”‘ Google API Keys
8
+ API_KEY = "AIzaSyCHmsNAEP7I-ASxt8uS2kxc8O5P2x_-KQY"
9
+ SEARCH_API_KEY = "AIzaSyCHmsNAEP7I-ASxt8uS2kxc8O5P2x_-KQY"
10
+ CX = "561935e384c5e4a19" # Your Custom Search Engine ID
11
+
12
+ # Initialize Google Maps client
13
+ gmaps = googlemaps.Client(key=API_KEY)
14
+
15
+ def get_business_suggestions(query, location):
16
+ try:
17
+ response = gmaps.places_autocomplete(query, location=location)
18
+ return [{"name": item["description"], "place_id": item["place_id"]} for item in response]
19
+ except Exception as e:
20
+ st.error(f"Autocomplete error: {str(e)}")
21
+ return []
22
+
23
+ def get_google_maps_rank(keyword, location, business_name, business_place_id, search_radius_km, max_results=5):
24
+ results = {"keyword": keyword, "source": "Google Maps", "rank": None, "name": None, "address": None}
25
+ search_radius_m = search_radius_km * 1000
26
+
27
+ try:
28
+ geocode = gmaps.geocode(location)
29
+ if not geocode:
30
+ return {"error": "Location not found"}
31
+
32
+ latlng = geocode[0]['geometry']['location']
33
+
34
+ places_result = gmaps.places(
35
+ query=keyword,
36
+ location=(latlng['lat'], latlng['lng']),
37
+ radius=search_radius_m
38
+ )
39
+
40
+ if 'results' not in places_result:
41
+ return {"error": "No results found for this search"}
42
+
43
+ places = places_result['results'][:max_results]
44
+
45
+ for rank, place in enumerate(places, 1):
46
+ if place["place_id"] == business_place_id:
47
+ results["rank"] = rank
48
+ results["name"] = place.get("name", "N/A")
49
+ results["address"] = place.get("formatted_address", "N/A")
50
+ return results
51
+
52
+ results["rank"] = f"Not in top {max_results}"
53
+ return results
54
+
55
+ except Exception as e:
56
+ return {"error": str(e)}
57
+
58
+ def get_serp_rankings(keyword, location, website_url=None):
59
+ try:
60
+ geocode = gmaps.geocode(location)
61
+ if not geocode:
62
+ return {"error": "Location not found"}
63
+
64
+ params = {
65
+ 'key': SEARCH_API_KEY,
66
+ 'cx': CX,
67
+ 'q': f"{keyword} near {location}",
68
+ 'gl': location.split(",")[-1].strip().lower(), # Country code
69
+ 'num': 10,
70
+ 'lr': 'lang_en'
71
+ }
72
+
73
+ response = requests.get("https://www.googleapis.com/customsearch/v1", params=params)
74
+ results = response.json()
75
+
76
+ if "items" in results:
77
+ for i, item in enumerate(results["items"], 1):
78
+ link = item.get("link", "")
79
+ if website_url and website_url.lower() in link.lower():
80
+ return {
81
+ "keyword": keyword,
82
+ "source": "Google Search",
83
+ "rank": i,
84
+ "title": item.get("title", "N/A"),
85
+ "link": link
86
+ }
87
+
88
+ return {
89
+ "keyword": keyword,
90
+ "source": "Google Search",
91
+ "rank": f"Not in top {len(results['items'])}",
92
+ "title": "N/A",
93
+ "link": "N/A"
94
+ }
95
+ return {"error": "No results found"}
96
+ except Exception as e:
97
+ return {"error": str(e)}
98
+
99
+ def save_to_excel(data, filename="my_website_rankings.xlsx"):
100
+ try:
101
+ df = pd.DataFrame(data)
102
+ df.to_excel(filename, index=False)
103
+ st.success(f"βœ… Your website rankings saved to **{filename}**")
104
+ st.download_button(
105
+ label="πŸ“₯ Download Excel File",
106
+ data=open(filename, "rb").read(),
107
+ file_name=filename,
108
+ mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
109
+ )
110
+ except Exception as e:
111
+ st.error(f"Error saving Excel file: {str(e)}")
112
+
113
+ # Streamlit UI
114
+ st.set_page_config(page_title="Business Rank Checker", layout="wide")
115
+ st.title("πŸ“Š Business Rank Checker")
116
+ st.markdown("Check your business ranking on Google Maps and search results")
117
+
118
+ # User Inputs
119
+ with st.form("search_form"):
120
+ col1, col2 = st.columns(2)
121
+ with col1:
122
+ location = st.text_input("πŸ“ Target Location", "Rajagiriya, Sri Lanka")
123
+ with col2:
124
+ search_radius_km = st.slider("πŸ” Search Radius (km)", 1, 20, 2)
125
+
126
+ business_query = st.text_input("🏒 Your Business Name", "")
127
+ website_url = st.text_input("🌐 Your Website URL", "", help="Enter your website to check if it appears in search results")
128
+
129
+ if business_query:
130
+ suggestions = get_business_suggestions(business_query, location)
131
+ if suggestions:
132
+ business_selection = st.selectbox(
133
+ "πŸ”Ž Select Your Business",
134
+ options=[s["name"] for s in suggestions],
135
+ index=0
136
+ )
137
+ business_place_id = next(s["place_id"] for s in suggestions if s["name"] == business_selection)
138
+ else:
139
+ st.warning("No matching businesses found")
140
+
141
+ keywords_input = st.text_input("πŸ“Œ Search Keywords (comma separated)", "coffee shop, cafe, breakfast place")
142
+
143
+ submitted = st.form_submit_button("πŸš€ Check Rankings")
144
+
145
+ if submitted and business_query:
146
+ keywords = [kw.strip() for kw in keywords_input.split(",") if kw.strip()]
147
+
148
+ if not keywords:
149
+ st.warning("Please enter at least one search keyword")
150
+ st.stop()
151
+
152
+ my_website_rankings = [] # Store only your website's rankings
153
+
154
+ with st.spinner("Analyzing rankings..."):
155
+ for keyword in keywords:
156
+ st.subheader(f"πŸ” Results for keyword: '{keyword}'")
157
+
158
+ # Google Maps Results
159
+ st.markdown("### πŸ“Œ Google Maps Rankings")
160
+ maps_rankings = get_google_maps_rank(
161
+ keyword, location,
162
+ business_selection, business_place_id,
163
+ search_radius_km
164
+ )
165
+
166
+ if "error" in maps_rankings:
167
+ st.error(f"Error: {maps_rankings['error']}")
168
+ else:
169
+ # Add to Excel data
170
+ my_website_rankings.append({
171
+ "Keyword": keyword,
172
+ "Source": "Google Maps",
173
+ "Rank": maps_rankings["rank"],
174
+ "Business Name": maps_rankings["name"],
175
+ "Address": maps_rankings["address"]
176
+ })
177
+
178
+ # Display in app
179
+ st.markdown(f"#### Your Business: **{business_selection}**")
180
+ st.write(f"Rank: {maps_rankings['rank']}")
181
+ st.write(f"Address: {maps_rankings['address']}")
182
+
183
+ # SERP Results
184
+ st.markdown(f"### 🌐 Search Results for '{keyword}' in {location}")
185
+ serp_results = get_serp_rankings(keyword, location, website_url)
186
+
187
+ if "error" in serp_results:
188
+ st.error(serp_results["error"])
189
+ else:
190
+ # Add to Excel data
191
+ my_website_rankings.append({
192
+ "Keyword": keyword,
193
+ "Source": "Google Search",
194
+ "Rank": serp_results["rank"],
195
+ "Title": serp_results["title"],
196
+ "Link": serp_results["link"]
197
+ })
198
+
199
+ # Display in app
200
+ st.write(f"Rank: {serp_results['rank']}")
201
+ if serp_results['rank'] != f"Not in top {10}":
202
+ st.write(f"Title: {serp_results['title']}")
203
+ st.write(f"Link: {serp_results['link']}")
204
+
205
+ st.markdown("---") # Separator between keywords
206
+
207
+ # Save your website's rankings to Excel
208
+ if my_website_rankings:
209
+ save_to_excel(my_website_rankings)