m-ric HF staff commited on
Commit
455fa84
1 Parent(s): e2caac8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -17
app.py CHANGED
@@ -4,10 +4,15 @@ import numpy as np
4
  from ast import literal_eval
5
  import pandas as pd
6
 
 
7
  from gradio_folium import Folium
8
  import folium
9
  from huggingface_hub import InferenceClient
10
  from geopy.geocoders import Nominatim
 
 
 
 
11
 
12
  from examples import (
13
  description_sf,
@@ -17,15 +22,6 @@ from examples import (
17
  df_examples
18
  )
19
 
20
- geolocator = Nominatim(user_agent="HF-trip-planner")
21
-
22
- def get_coordinates(address):
23
- location = geolocator.geocode(address)
24
- if location:
25
- return (location.latitude, location.longitude)
26
- else:
27
- return None
28
-
29
  repo_id = "mistralai/Mixtral-8x7B-Instruct-v0.1"
30
  llm_client = InferenceClient(model=repo_id, timeout=180)
31
 
@@ -60,15 +56,61 @@ def parse_llm_output(output):
60
  return dataframe, rationale
61
 
62
 
63
- def get_coordinates_row(row):
64
- coords = get_coordinates(row["name"])
65
- if coords is not None:
66
- row["lat"], row["lon"] = coords
67
- return row
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
 
70
  def create_map_from_markers(dataframe):
71
- dataframe = dataframe.apply(get_coordinates_row, axis=1)
 
 
 
72
  f_map = Map(
73
  location=[dataframe["lat"].mean(), dataframe["lon"].mean()],
74
  zoom_start=5,
@@ -106,7 +148,8 @@ def run_display(text):
106
  def select_example(df, data: gr.SelectData):
107
  row = df.iloc[data.index[0], :]
108
  dataframe, rationale = parse_llm_output(row["output"])
109
- return row["description"], create_map_from_markers(dataframe), rationale
 
110
 
111
 
112
  with gr.Blocks(
@@ -127,7 +170,7 @@ with gr.Blocks(
127
  example_dataframe, example_rationale = parse_llm_output(output_example_sf)
128
  display_rationale = gr.Markdown(example_rationale)
129
  starting_map = create_map_from_markers(example_dataframe)
130
- map = Folium(value=starting_map, height=700, label="Chosen locations")
131
  button.click(run_display, inputs=[text], outputs=[map, display_rationale])
132
 
133
  gr.Markdown("### Other examples")
 
4
  from ast import literal_eval
5
  import pandas as pd
6
 
7
+ import asyncio
8
  from gradio_folium import Folium
9
  import folium
10
  from huggingface_hub import InferenceClient
11
  from geopy.geocoders import Nominatim
12
+ from collections import OrderedDict
13
+ from geopy.adapters import AioHTTPAdapter
14
+ import nest_asyncio
15
+ nest_asyncio.apply()
16
 
17
  from examples import (
18
  description_sf,
 
22
  df_examples
23
  )
24
 
 
 
 
 
 
 
 
 
 
25
  repo_id = "mistralai/Mixtral-8x7B-Instruct-v0.1"
26
  llm_client = InferenceClient(model=repo_id, timeout=180)
27
 
 
56
  return dataframe, rationale
57
 
58
 
59
+ class AsyncLRUCache:
60
+ def __init__(self, maxsize=100):
61
+ self.cache = OrderedDict()
62
+ self.maxsize = maxsize
63
+
64
+ async def get(self, key):
65
+ if key not in self.cache:
66
+ return None
67
+ self.cache.move_to_end(key)
68
+ return self.cache[key]
69
+
70
+ async def set(self, key, value):
71
+ if key in self.cache:
72
+ self.cache.move_to_end(key)
73
+ self.cache[key] = value
74
+ if len(self.cache) > self.maxsize:
75
+ self.cache.popitem(last=False)
76
+
77
+
78
+ # Instantiate the cache
79
+ cache = AsyncLRUCache(maxsize=500)
80
+
81
+ async def geocode_address(address):
82
+ # Check if the result is in cache
83
+ cached_location = await cache.get(address)
84
+ if cached_location:
85
+ return cached_location
86
+
87
+ # If not in cache, perform the geolocation request
88
+ async with Nominatim(
89
+ user_agent="HF-trip-planner",
90
+ adapter_factory=AioHTTPAdapter,
91
+ ) as geolocator:
92
+ location = await geolocator.geocode(address, timeout=10)
93
+ if location:
94
+ # Save the result in cache for future use
95
+ await cache.set(address, location)
96
+ return location
97
+
98
+ async def ageocode_addresses(addresses):
99
+ tasks = [geocode_address(address) for address in addresses]
100
+ locations = await asyncio.gather(*tasks)
101
+ return locations
102
+
103
+ def geocode_addresses(addresses):
104
+ loop = asyncio.get_event_loop()
105
+ result = loop.run_until_complete(ageocode_addresses(addresses))
106
+ return result
107
 
108
 
109
  def create_map_from_markers(dataframe):
110
+ locations = geocode_addresses(dataframe["name"])
111
+ dataframe["lat"] = [location.latitude if location else None for location in locations]
112
+ dataframe["lon"] = [location.longitude if location else None for location in locations]
113
+
114
  f_map = Map(
115
  location=[dataframe["lat"].mean(), dataframe["lon"].mean()],
116
  zoom_start=5,
 
148
  def select_example(df, data: gr.SelectData):
149
  row = df.iloc[data.index[0], :]
150
  dataframe, rationale = parse_llm_output(row["output"])
151
+ map = create_map_from_markers(dataframe)
152
+ return row["description"], map, rationale
153
 
154
 
155
  with gr.Blocks(
 
170
  example_dataframe, example_rationale = parse_llm_output(output_example_sf)
171
  display_rationale = gr.Markdown(example_rationale)
172
  starting_map = create_map_from_markers(example_dataframe)
173
+ map = Folium(value=starting_map, height=600, label="Chosen locations")
174
  button.click(run_display, inputs=[text], outputs=[map, display_rationale])
175
 
176
  gr.Markdown("### Other examples")