yunusserhat commited on
Commit
d93bc09
1 Parent(s): b0b2255

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -25
app.py CHANGED
@@ -25,7 +25,6 @@ def load_spacy_model(model_name="en_core_web_md"):
25
  return spacy.load(model_name)
26
 
27
 
28
-
29
  nlp = load_spacy_model()
30
 
31
  IMAGE_SIZE = (224, 224)
@@ -63,9 +62,9 @@ def most_frequent_locations(text: str):
63
  # Format the output to show location names along with their counts
64
  common_locations_str = ', '.join([f"{loc[0]} ({loc[1]} occurrences)" for loc in most_common_locations])
65
 
66
- return f"Most Mentioned Locations: {common_locations_str}"
67
  else:
68
- return "No locations found"
69
 
70
 
71
  # Transform image for model prediction
@@ -78,6 +77,17 @@ def transform_image(image: Image) -> torch.Tensor:
78
  return transform(image).unsqueeze(0)
79
 
80
 
 
 
 
 
 
 
 
 
 
 
 
81
  # Fetch city GeoJSON data
82
  def get_city_geojson(location_name: str) -> dict:
83
  geolocator = Nominatim(user_agent="predictGeolocforImage")
@@ -119,6 +129,7 @@ def predict_location(image: Image, model: Geolocalizer) -> tuple:
119
  st.error(f"Failed to predict the location: {e}")
120
  return None
121
 
 
122
  # Display map in Streamlit
123
  def display_map(city_geojson: dict, gps_degrees: list) -> None:
124
  map_view = pdk.Deck(
@@ -175,10 +186,8 @@ def scrape_webpage(url: str) -> tuple:
175
 
176
 
177
  def main():
178
-
179
  st.title('Welcome to Geolocation Guesstimation Demo 👋')
180
 
181
-
182
  # Define page navigation using the sidebar
183
  page = st.sidebar.selectbox(
184
  "Choose your action:",
@@ -188,16 +197,16 @@ def main():
188
 
189
  st.sidebar.success("Select a demo above.")
190
  st.sidebar.info(
191
- """
192
- - Web App URL: <https://yunusserhat-guesstimatelocation.hf.space/>
193
- """)
194
 
195
  st.sidebar.title("Contact")
196
  st.sidebar.info(
197
- """
198
- Yunus Serhat Bıçakçı at [yunusserhat.com](https://yunusserhat.com) | [GitHub](https://github.com/yunusserhat) | [Twitter](https://twitter.com/yunusserhat) | [LinkedIn](https://www.linkedin.com/in/yunusserhat)
199
- """)
200
-
201
  if page == "Home":
202
  st.write("Welcome to the Geolocation Predictor. Please select an action from the sidebar dropdown.")
203
 
@@ -256,13 +265,15 @@ def social_media_page():
256
  if result:
257
  gps_degrees, location_query, city_geojson, processing_time = result
258
  location_name = f"{location_query['name']}, {location_query['admin1']}, {location_query['cc']}"
259
- st.write(f"City: {location_query['name']}, Region: {location_query['admin1']}, Country: {location_query['cc']}")
 
260
  if city_geojson:
261
  display_map(city_geojson, gps_degrees)
262
  st.write(f"Processing Time (seconds): {processing_time}")
263
  # Check for match and notify
264
- if location_query['name'] in most_common_locations:
265
- st.success(f"The predicted location {location_query['name']} matches the most frequently mentioned location!")
 
266
  else:
267
  st.error(f"Failed to fetch image at URL {media_url}: HTTP {response.status_code}")
268
 
@@ -271,20 +282,35 @@ def web_page_url_page():
271
  st.header("Web Page Analyser")
272
  web_page_url = st.text_input("Enter a web page URL to scrape:", key='web_page_url_input')
273
  if web_page_url:
274
- text, images = scrape_webpage(web_page_url) # Assume this function is defined elsewhere
275
  if text:
276
- st.subheader("Extracted Text First 500 Chracter:")
277
  st.write(text[:500])
278
- most_used_location = most_frequent_locations(text)
279
  st.subheader("Most Frequent Location")
280
  st.write(most_used_location)
281
- show_images = st.checkbox('Show Images', key='show_images')
282
- if show_images:
283
- st.subheader("Images Found")
284
- for image_url in images:
285
- display_image(image_url) # Assumes a function to display images with error handling
286
- else:
287
- st.write("No data found or unable to parse the webpage.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
288
 
289
 
290
  if __name__ == '__main__':
 
25
  return spacy.load(model_name)
26
 
27
 
 
28
  nlp = load_spacy_model()
29
 
30
  IMAGE_SIZE = (224, 224)
 
62
  # Format the output to show location names along with their counts
63
  common_locations_str = ', '.join([f"{loc[0]} ({loc[1]} occurrences)" for loc in most_common_locations])
64
 
65
+ return f"Most Mentioned Locations: {common_locations_str}", [loc[0] for loc in most_common_locations]
66
  else:
67
+ return "No locations found", []
68
 
69
 
70
  # Transform image for model prediction
 
77
  return transform(image).unsqueeze(0)
78
 
79
 
80
+ def check_location_match(location_query, most_common_locations):
81
+ name = location_query['name']
82
+ admin1 = location_query['admin1']
83
+ cc = location_query['cc']
84
+
85
+ for loc in most_common_locations:
86
+ if name in loc and admin1 in loc and cc in loc:
87
+ return True
88
+ return False
89
+
90
+
91
  # Fetch city GeoJSON data
92
  def get_city_geojson(location_name: str) -> dict:
93
  geolocator = Nominatim(user_agent="predictGeolocforImage")
 
129
  st.error(f"Failed to predict the location: {e}")
130
  return None
131
 
132
+
133
  # Display map in Streamlit
134
  def display_map(city_geojson: dict, gps_degrees: list) -> None:
135
  map_view = pdk.Deck(
 
186
 
187
 
188
  def main():
 
189
  st.title('Welcome to Geolocation Guesstimation Demo 👋')
190
 
 
191
  # Define page navigation using the sidebar
192
  page = st.sidebar.selectbox(
193
  "Choose your action:",
 
197
 
198
  st.sidebar.success("Select a demo above.")
199
  st.sidebar.info(
200
+ """
201
+ - Web App URL: <https://yunusserhat-guesstimatelocation.hf.space/>
202
+ """)
203
 
204
  st.sidebar.title("Contact")
205
  st.sidebar.info(
206
+ """
207
+ Yunus Serhat Bıçakçı at [yunusserhat.com](https://yunusserhat.com) | [GitHub](https://github.com/yunusserhat) | [Twitter](https://twitter.com/yunusserhat) | [LinkedIn](https://www.linkedin.com/in/yunusserhat)
208
+ """)
209
+
210
  if page == "Home":
211
  st.write("Welcome to the Geolocation Predictor. Please select an action from the sidebar dropdown.")
212
 
 
265
  if result:
266
  gps_degrees, location_query, city_geojson, processing_time = result
267
  location_name = f"{location_query['name']}, {location_query['admin1']}, {location_query['cc']}"
268
+ st.write(
269
+ f"City: {location_query['name']}, Region: {location_query['admin1']}, Country: {location_query['cc']}")
270
  if city_geojson:
271
  display_map(city_geojson, gps_degrees)
272
  st.write(f"Processing Time (seconds): {processing_time}")
273
  # Check for match and notify
274
+ if check_location_match(location_query, most_common_locations):
275
+ st.success(
276
+ f"The predicted location {location_name} matches one of the most frequently mentioned locations!")
277
  else:
278
  st.error(f"Failed to fetch image at URL {media_url}: HTTP {response.status_code}")
279
 
 
282
  st.header("Web Page Analyser")
283
  web_page_url = st.text_input("Enter a web page URL to scrape:", key='web_page_url_input')
284
  if web_page_url:
285
+ text, images = scrape_webpage(web_page_url)
286
  if text:
287
+ st.subheader("Extracted Text First 500 Characters:")
288
  st.write(text[:500])
289
+ most_used_location, most_common_locations = most_frequent_locations(text)
290
  st.subheader("Most Frequent Location")
291
  st.write(most_used_location)
292
+ if images:
293
+ selected_image_url = st.selectbox("Select an image to predict location:", images)
294
+ if selected_image_url:
295
+ response = requests.get(selected_image_url)
296
+ if response.status_code == 200:
297
+ image = Image.open(BytesIO(response.content)).convert('RGB')
298
+ st.image(image, caption=f'Selected Image from URL: {selected_image_url}', use_column_width=True)
299
+ model = load_geoloc_model()
300
+ if model:
301
+ result = predict_location(image, model)
302
+ if result:
303
+ gps_degrees, location_query, city_geojson, processing_time = result
304
+ location_name = f"{location_query['name']}, {location_query['admin1']}, {location_query['cc']}"
305
+ st.write(
306
+ f"City: {location_query['name']}, Region: {location_query['admin1']}, Country: {location_query['cc']}")
307
+ if city_geojson:
308
+ display_map(city_geojson, gps_degrees)
309
+ st.write(f"Processing Time (seconds): {processing_time}")
310
+ # Check for match and notify
311
+ if check_location_match(location_query, most_common_locations):
312
+ st.success(
313
+ f"The predicted location {location_name} matches one of the most frequently mentioned locations!")
314
 
315
 
316
  if __name__ == '__main__':