File size: 7,171 Bytes
90de23d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aafaa22
 
90de23d
 
 
 
 
aafaa22
 
90de23d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import logging
import os
from typing import Any

import pandas as pd
import streamlit as st
from countryinfo import CountryInfo
from dotenv import load_dotenv

from common import HintType, configs, get_distance
from hint import AudioHint, ImageHint, TextHint


def setup_models(_cache: Any, configs: dict) -> None:
    """Setups all hint models.

    Args:
        _cache (st.session_state): Streamlit cache object
        configs (dict): Configurations used by the models
    """
    for model_type in _cache["hint_types"]:
        if _cache["model"][model_type] is None:
            if model_type == HintType.TEXT.value:
                _cache["model"][model_type] = setup_text_hint(configs)
            elif model_type == HintType.IMAGE.value:
                _cache["model"][model_type] = setup_image_hint(configs)
            elif model_type == HintType.AUDIO.value:
                _cache["model"][model_type] = setup_audio_hint(configs)


@st.cache_resource()
def setup_text_hint(configs: dict) -> TextHint:
    """Setups the text hint model.

    Args:
        configs (dict): Configurations used by the model

    Returns:
        TextHint: Hint model
    """
    with st.spinner("Loading text model..."):
        model_configs = configs["local"][HintType.TEXT.value.lower()]
        model_configs["hf_access_token"] = os.environ["HF_ACCESS_TOKEN"]
        textHint = TextHint(configs=model_configs)
        textHint.initialize()
    return textHint


@st.cache_resource()
def setup_image_hint(configs: dict) -> ImageHint:
    """Setups the image hint model.

    Args:
        configs (dict): Configurations used by the model

    Returns:
        ImageHint: Hint model
    """
    with st.spinner("Loading image model..."):
        model_configs = configs["local"][HintType.IMAGE.value.lower()]
        imageHint = ImageHint(configs=model_configs)
        imageHint.initialize()
    return imageHint


@st.cache_resource()
def setup_audio_hint(configs: dict) -> AudioHint:
    """Setups the audio hint model.

    Args:
        configs (dict): Configurations used by the model

    Returns:
        AudioHint: Hint model
    """
    with st.spinner("Loading audio model..."):
        model_configs = configs["local"][HintType.AUDIO.value.lower()]
        audioHint = AudioHint(configs=model_configs)
        audioHint.initialize()
    return audioHint


@st.cache_resource()
def get_country_list() -> pd.DataFrame:
    """Builds a database of countries and metadata.

    Returns:
        pd.DataFrame: Country database
    """
    country_list = list(CountryInfo().all().keys())

    country_df = {}
    for country in country_list:
        try:
            area = CountryInfo(country).area()
            country_df[country] = area
        except:
            pass

    country_df = pd.DataFrame(country_df.items(), columns=["country", "area"])
    return country_df


def pick_country(country_df: pd.DataFrame) -> str:
    """Selects a country, the probability of each country is related to its area size.

    Args:
        country_df (pd.DataFrame): Database of country and their metadata

    Returns:
        str: The selected country
    """
    country = country_df.sample(n=1, weights="area")["country"].iloc[0]
    return country


def reset_cache() -> None:
    """Reset the Streamlit APP cache."""
    country_df = get_country_list()
    st.session_state["country_list"] = country_df["country"].values.tolist()
    st.session_state["country"] = pick_country(country_df)
    st.session_state["hint_types"] = []
    st.session_state["n_hints"] = 1
    st.session_state["game_started"] = False
    st.session_state["model"] = {
        HintType.TEXT.value: None,
        HintType.IMAGE.value: None,
        HintType.AUDIO.value: None,
    }


logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

st.set_page_config(
    page_title="Gen AI GeoGuesser",
    page_icon="🌎",
)

if not st.session_state:
    load_dotenv()
    reset_cache()

st.title("Generative AI GeoGuesser 🌎")

st.markdown("### Guess the country based on hints generated by AI")

st.markdown("(Only working with image hints for performance reasons)")

col1, col2 = st.columns([2, 1])

with col1:
    st.session_state["hint_types"] = st.multiselect(
        "Chose which hint types you want",
        # [x.value for x in HintType],
        [HintType.IMAGE.value],
        default=st.session_state["hint_types"],
    )

with col2:
    st.session_state["n_hints"] = st.slider(
        "Number of hints",
        min_value=1,
        max_value=5,
        value=st.session_state["n_hints"],
    )

start_btn = st.button("Start game")

if start_btn:
    if not st.session_state["hint_types"]:
        st.error("Pick at least one hint type")
        reset_cache()
    else:
        print(f'Chosen country "{st.session_state["country"]}"')

        setup_models(st.session_state, configs)

        for hint_type in st.session_state["hint_types"]:
            with st.spinner(f"Generating {hint_type} hint..."):
                st.session_state["model"][hint_type].generate_hint(
                    st.session_state["country"],
                    st.session_state["n_hints"],
                )

        st.session_state["game_started"] = True

if st.session_state["game_started"]:
    game_col1, game_col2, game_col3 = st.columns([2, 1, 1])

    with game_col1:
        guess = st.selectbox("Country guess", ([""] + st.session_state["country_list"]))
    with game_col2:
        guess_btn = st.button("Make a guess")
    with game_col3:
        reset_btn = st.button("Reset game")

    if guess_btn:
        if st.session_state["country"] == guess:
            st.success("Correct guess you won!")
            st.balloons()
        else:
            if guess:
                country_latlong = CountryInfo(st.session_state["country"]).latlng()
                guess_latlong = CountryInfo(guess).latlng()
                distance = int(get_distance(country_latlong, guess_latlong))
                st.error(
                    f"""
                    Wrong guess, you missed the correct country by {distance} KM.
                    The correct answer was {st.session_state["country"]}.
                    """
                )
            else:
                st.error("Pick a country.")

    if reset_btn:
        reset_cache()

if st.session_state["game_started"]:
    tabs = st.tabs([f"{x} hint" for x in st.session_state["hint_types"]])

    for tab_idx, tab in enumerate(tabs):
        hint_type = st.session_state["hint_types"][tab_idx]
        with tab:
            if st.session_state["model"][hint_type]:
                for hint_idx, hint in enumerate(
                    st.session_state["model"][hint_type].hints
                ):
                    st.markdown(f"#### Hint #{hint_idx+1}")
                    if hint_type == HintType.TEXT.value:
                        st.write(hint["text"])
                    elif hint_type == HintType.IMAGE.value:
                        st.image(hint["image"])
                    elif hint_type == HintType.AUDIO.value:
                        st.audio(hint["audio"], sample_rate=hint["sample_rate"])