Mahmudm commited on
Commit
db84eaa
·
verified ·
1 Parent(s): 1ebddfa

Update ash_animator/basemaps.py

Browse files
Files changed (1) hide show
  1. ash_animator/basemaps.py +28 -15
ash_animator/basemaps.py CHANGED
@@ -10,30 +10,36 @@ import cartopy.feature as cfeature
10
 
11
  def get_cache_dir(app_name):
12
  """
13
- Try to create a cache directory under ./code first.
14
- If it fails (e.g., due to permissions), fallback to system temp directory.
15
  """
16
  try:
17
  preferred = os.path.join("/code", f"{app_name}_cache")
18
  os.makedirs(preferred, exist_ok=True)
19
  return preferred
20
- except PermissionError:
21
- fallback = os.path.join(tempfile.gettempdir(), f"{app_name}_cache")
22
- os.makedirs(fallback, exist_ok=True)
23
- return fallback
 
 
 
 
24
 
25
- # Define and create cache directories
26
  CTX_TILE_CACHE_DIR = get_cache_dir("contextily")
27
  BASEMAP_TILE_CACHE_DIR = get_cache_dir("basemap")
28
  CARTOPY_CACHE_DIR = get_cache_dir("cartopy")
29
 
30
- # Set environment variables for Cartopy
31
- os.environ["CARTOPY_USER_BACKGROUNDS"] = CARTOPY_CACHE_DIR
32
- os.environ["CARTOPY_CACHE_DIR"] = CARTOPY_CACHE_DIR
 
33
 
34
  def draw_etopo_basemap(ax, mode="basemap", zoom=11):
35
  """
36
  Draws a background basemap image on a Cartopy GeoAxes.
 
37
  """
38
  try:
39
  if mode == "stock":
@@ -49,9 +55,10 @@ def draw_etopo_basemap(ax, mode="basemap", zoom=11):
49
  extent = ax.get_extent(crs=ccrs.PlateCarree())
50
  extent_str = "_".join(f"{v:.4f}" for v in extent)
51
  cache_key = hashlib.md5(extent_str.encode()).hexdigest()
52
- cache_file = os.path.join(BASEMAP_TILE_CACHE_DIR, f"{cache_key}_highres.png")
 
53
 
54
- if os.path.exists(cache_file):
55
  img = Image.open(cache_file)
56
  ax.imshow(img, extent=extent, transform=ccrs.PlateCarree())
57
  else:
@@ -65,11 +72,17 @@ def draw_etopo_basemap(ax, mode="basemap", zoom=11):
65
  resolution='f', ax=temp_ax)
66
 
67
  m.shadedrelief()
68
- fig.savefig(cache_file, dpi=300, bbox_inches='tight', pad_inches=0)
 
 
 
 
 
69
  plt.close(fig)
70
 
71
- img = Image.open(cache_file)
72
- ax.imshow(img, extent=extent, transform=ccrs.PlateCarree())
 
73
 
74
  else:
75
  raise ValueError(f"Unsupported basemap mode: {mode}")
 
10
 
11
  def get_cache_dir(app_name):
12
  """
13
+ Attempt to create a writable cache directory.
14
+ Return None if both preferred and fallback locations fail.
15
  """
16
  try:
17
  preferred = os.path.join("/code", f"{app_name}_cache")
18
  os.makedirs(preferred, exist_ok=True)
19
  return preferred
20
+ except Exception:
21
+ try:
22
+ fallback = os.path.join(tempfile.gettempdir(), f"{app_name}_cache")
23
+ os.makedirs(fallback, exist_ok=True)
24
+ return fallback
25
+ except Exception:
26
+ print(f"[Cache Disabled] Could not create cache for {app_name}.")
27
+ return None
28
 
29
+ # Define cache dirs (may be None)
30
  CTX_TILE_CACHE_DIR = get_cache_dir("contextily")
31
  BASEMAP_TILE_CACHE_DIR = get_cache_dir("basemap")
32
  CARTOPY_CACHE_DIR = get_cache_dir("cartopy")
33
 
34
+ # Set env vars if cartopy cache dir is usable
35
+ if CARTOPY_CACHE_DIR:
36
+ os.environ["CARTOPY_USER_BACKGROUNDS"] = CARTOPY_CACHE_DIR
37
+ os.environ["CARTOPY_CACHE_DIR"] = CARTOPY_CACHE_DIR
38
 
39
  def draw_etopo_basemap(ax, mode="basemap", zoom=11):
40
  """
41
  Draws a background basemap image on a Cartopy GeoAxes.
42
+ Falls back to simple features if caching or basemap rendering fails.
43
  """
44
  try:
45
  if mode == "stock":
 
55
  extent = ax.get_extent(crs=ccrs.PlateCarree())
56
  extent_str = "_".join(f"{v:.4f}" for v in extent)
57
  cache_key = hashlib.md5(extent_str.encode()).hexdigest()
58
+ cache_file = (os.path.join(BASEMAP_TILE_CACHE_DIR, f"{cache_key}_highres.png")
59
+ if BASEMAP_TILE_CACHE_DIR else None)
60
 
61
+ if cache_file and os.path.exists(cache_file):
62
  img = Image.open(cache_file)
63
  ax.imshow(img, extent=extent, transform=ccrs.PlateCarree())
64
  else:
 
72
  resolution='f', ax=temp_ax)
73
 
74
  m.shadedrelief()
75
+
76
+ if cache_file:
77
+ try:
78
+ fig.savefig(cache_file, dpi=300, bbox_inches='tight', pad_inches=0)
79
+ except Exception:
80
+ print("[Basemap Cache Write Failed] Skipping cache.")
81
  plt.close(fig)
82
 
83
+ # img = Image.open(cache_file) if cache_file and os.path.exists(cache_file) else None
84
+ # if img:
85
+ # ax.imshow(img, extent=extent, transform=ccrs.PlateCarree())
86
 
87
  else:
88
  raise ValueError(f"Unsupported basemap mode: {mode}")