|
| 1 | +"""Demo showcasing simple manual caching with gr.Cache().""" |
| 2 | + |
| 3 | +import time |
| 4 | + |
| 5 | +import gradio as gr |
| 6 | + |
| 7 | +WEATHER_BY_CITY = { |
| 8 | + "san francisco": ("Foggy", 61), |
| 9 | + "new york": ("Cloudy", 72), |
| 10 | + "tokyo": ("Sunny", 78), |
| 11 | + "london": ("Rainy", 58), |
| 12 | + "nairobi": ("Clear", 75), |
| 13 | +} |
| 14 | + |
| 15 | + |
| 16 | +def normalize_city(city: str) -> str: |
| 17 | + return " ".join(city.lower().strip().split()) |
| 18 | + |
| 19 | + |
| 20 | +def lookup_weather(city: str, c=gr.Cache()): |
| 21 | + if not city.strip(): |
| 22 | + return "", "Enter a city name.", "" |
| 23 | + |
| 24 | + cache_key = normalize_city(city) |
| 25 | + cached = c.get(cache_key) |
| 26 | + if cached is not None: |
| 27 | + return cached["forecast"], "Cache hit", cache_key |
| 28 | + |
| 29 | + time.sleep(2) |
| 30 | + condition, temperature = WEATHER_BY_CITY.get(cache_key, ("Windy", 68)) |
| 31 | + forecast = ( |
| 32 | + f"{city.strip()}: {condition}, {temperature} degF.\n" |
| 33 | + f"Normalized cache key: {cache_key}" |
| 34 | + ) |
| 35 | + c.set(cache_key, forecast=forecast) |
| 36 | + return forecast, "Computed and stored", cache_key |
| 37 | + |
| 38 | + |
| 39 | +with gr.Blocks(title="gr.Cache() Demo") as demo: |
| 40 | + gr.Markdown( |
| 41 | + "# `gr.Cache()` Demo\n" |
| 42 | + "This demo manually caches a normalized city lookup. " |
| 43 | + "Try the same city twice, or vary capitalization and spacing " |
| 44 | + "to reuse the same cached result." |
| 45 | + ) |
| 46 | + |
| 47 | + city = gr.Textbox(label="City", value=" San Francisco ") |
| 48 | + forecast = gr.Textbox(label="Forecast", lines=3) |
| 49 | + status = gr.Textbox(label="Status") |
| 50 | + cache_key = gr.Textbox(label="Cache key used") |
| 51 | + |
| 52 | + gr.Button("Lookup").click(lookup_weather, city, [forecast, status, cache_key]) |
| 53 | + |
| 54 | + |
| 55 | +if __name__ == "__main__": |
| 56 | + demo.launch() |
0 commit comments