File size: 13,492 Bytes
b7d7689
 
d6a8ad7
 
4c0ff10
d6a8ad7
70f3228
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c38a10f
d6a8ad7
 
b7d7689
 
 
 
d6a8ad7
 
b7d7689
d6a8ad7
 
4c0ff10
 
c38a10f
 
 
4c0ff10
 
 
 
 
c38a10f
4c0ff10
 
 
 
 
c38a10f
4c0ff10
 
c38a10f
4c0ff10
 
 
b7d7689
70f3228
c38a10f
 
 
 
 
 
 
 
 
 
 
 
70f3228
 
 
c38a10f
 
 
 
 
70f3228
 
 
 
 
 
 
 
 
 
c38a10f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70f3228
c38a10f
 
 
 
70f3228
c38a10f
 
 
70f3228
 
c38a10f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70f3228
 
c38a10f
d6a8ad7
 
 
b7d7689
d6a8ad7
 
b7d7689
 
 
 
d6a8ad7
 
 
b7d7689
d6a8ad7
 
 
 
b7d7689
d6a8ad7
 
b7d7689
 
d6a8ad7
b7d7689
d6a8ad7
4c0ff10
b7d7689
 
d6a8ad7
 
b7d7689
d6a8ad7
b7d7689
d6a8ad7
b7d7689
 
d6a8ad7
 
b7d7689
d6a8ad7
c38a10f
 
 
 
 
 
 
4c0ff10
d6a8ad7
c38a10f
4c0ff10
c38a10f
 
 
 
d6a8ad7
 
b7d7689
 
 
d6a8ad7
b7d7689
d6a8ad7
b7d7689
c38a10f
 
b7d7689
c38a10f
 
 
 
b7d7689
c38a10f
 
4c0ff10
c38a10f
 
 
 
 
 
 
d6a8ad7
 
 
 
 
c38a10f
 
 
 
 
 
 
 
d6a8ad7
 
 
b7d7689
d6a8ad7
 
 
 
 
b7d7689
4c0ff10
 
d6a8ad7
 
 
9fff027
 
 
 
 
 
 
 
 
 
 
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
import os
import openai
import gradio as gr
import json
import plotly.graph_objects as go


CONTEXTUAL_ZOOM_PROMPT = """
You are an expert art historian specializing in interactive exploration. Analyze the query and generate contextually aware zoom configurations with explanations.

###Input###
User Query: {user_query}
Current Zoom States: {
    "temporal": {"level": "", "selection": ""},
    "geographical": {"level": "", "selection": ""},
    "style": {"level": "", "selection": ""},
    "subject": {"level": "", "selection": ""}
}

###Output Format###
{
    "analysis": {
        "query_focus": "main subject",
        "historical_context": "brief explanation"
    },
    "axis_configurations": {
        "temporal": {
            "component": "st.slider",
            "current_zoom": {
                "level": "century/decade/year",
                "range": [start, end],
                "explanation": "Why this time range is relevant"
            },
            "available_zooms": {
                "in": {
                    "range": [narrower_start, narrower_end],
                    "explanation": "What focusing here reveals"
                },
                "out": {
                    "range": [broader_start, broader_end],
                    "explanation": "Broader historical context"
                }
            },
            "impacted_by": {
                "geographical": "how location affects timeframe",
                "style": "how style affects timeframe"
            }
        },
        "geographical": {
            "component": "st.map",
            "current_zoom": {
                "level": "continent/country/city",
                "locations": [
                    {
                        "name": "",
                        "lat": 0,
                        "lon": 0,
                        "relevance": "why this location matters"
                    }
                ]
            },
            "available_zooms": {
                "in": {
                    "locations": ["more specific locations"],
                    "explanation": "What focusing here reveals"
                },
                "out": {
                    "locations": ["broader regions"],
                    "explanation": "Broader geographical context"
                }
            },
            "impacted_by": {
                "temporal": "how time period affects locations",
                "style": "how style affects locations"
            }
        },
        "style": {
            "component": "st.multiselect" if current_zoom == "broad" else "st.selectbox",
            "current_zoom": {
                "level": "movement/sub_movement/specific",
                "options": ["list of styles"],
                "explanation": "Style context for this period/location"
            }
        }
    },
    "streamlit_adaptations": {
        "recommended_components": {
            "component_name": "reason for recommendation based on zoom level",
            "configuration": {}
        }
    }
}

###Example for "paint during napoleon war"###
{
    "temporal": {
        "component": "st.slider",
        "current_zoom": {
            "level": "period",
            "range": [1799, 1815],
            "explanation": "Napoleon's reign as First Consul and Emperor"[1]
        },
        "available_zooms": {
            "in": {
                "range": [1812, 1815],
                "explanation": "Focus on final campaigns and artistic responses"[1]
            }
        }
    },
    "geographical": {
        "component": "st.map",
        "current_zoom": {
            "level": "continent",
            "locations": [
                {
                    "name": "France",
                    "relevance": "Center of Napoleonic art production"[2]
                },
                {
                    "name": "Spain",
                    "relevance": "Goya's war paintings perspective"[1]
                }
            ]
        }
    }
}

###Requirements###
1. Explain zoom level changes and their historical significance
2. Adapt Streamlit components based on zoom level
3. Show relationships between different axes
4. Provide historical context for available selections
5. Consider how selections affect other axes
6. Include relevant historical explanations for each zoom level

Generate only the JSON response, maintaining strict JSON format."""



class ArtExplorer:
    def __init__(self):
        self.client = openai.OpenAI(
            base_url="https://api.groq.com/openai/v1",
            api_key=os.environ.get("GROQ_API_KEY")
        )
        self.current_state = {
            "zoom_level": 0,
            "selections": {}
        }

    def create_map(self, locations):
        """Create a Plotly map figure from location data"""
        if not locations:
            locations = [{"name": "Paris", "lat": 48.8566, "lon": 2.3522}]
            
        fig = go.Figure(go.Scattermapbox(
            lat=[loc.get('lat') for loc in locations],
            lon=[loc.get('lon') for loc in locations],
            mode='markers',
            marker=go.scattermapbox.Marker(size=10),
            text=[loc.get('name') for loc in locations]
        ))

        fig.update_layout(
            mapbox_style="open-street-map",
            mapbox=dict(
                center=dict(lat=48.8566, lon=2.3522),
                zoom=4
            ),
            margin=dict(r=0, t=0, l=0, b=0)
        )
        return fig

    def get_llm_response(self, query: str, zoom_context: dict = None) -> dict:
        try:
            current_zoom_states = {
                "temporal": {"level": self.current_state["zoom_level"], "selection": ""},
                "geographical": {"level": self.current_state["zoom_level"], "selection": ""},
                "style": {"level": self.current_state["zoom_level"], "selection": ""},
                "subject": {"level": self.current_state["zoom_level"], "selection": ""}
            }
            
            if zoom_context:
                for key, value in zoom_context.items():
                    if key in current_zoom_states:
                        current_zoom_states[key]["selection"] = value

            response = self.client.chat.completions.create(
                model="mixtral-8x7b-32768",
                messages=[
                    {"role": "system", "content": "You are an expert art historian specializing in interactive exploration."},
                    {"role": "user", "content": CONTEXTUAL_ZOOM_PROMPT.format(
                        user_query=query,
                        current_zoom_states=json.dumps(current_zoom_states, indent=2)
                    )}
                ],
                temperature=0.1,
                max_tokens=2048
            )
            
            result = json.loads(response.choices[0].message.content)
            return result
            
        except Exception as e:
            print(f"Error in LLM response: {str(e)}")
            return self.get_default_response()

    def get_default_response(self):
        return {
            "analysis": {
                "query_focus": "Default focus",
                "historical_context": "Default historical context"
            },
            "axis_configurations": {
                "temporal": {
                    "component": "st.slider",
                    "current_zoom": {
                        "level": "century",
                        "range": [1700, 2000],
                        "explanation": "Default time range"
                    },
                    "available_zooms": {
                        "in": {
                            "range": [1800, 1900],
                            "explanation": "Zoom in to see more detail"
                        },
                        "out": {
                            "range": [1500, 2024],
                            "explanation": "Broader historical context"
                        }
                    }
                },
                "geographical": {
                    "current_zoom": {
                        "level": "continent",
                        "locations": [
                            {
                                "name": "Paris",
                                "lat": 48.8566,
                                "lon": 2.3522,
                                "relevance": "Default location"
                            }
                        ]
                    }
                },
                "style": {
                    "current_zoom": {
                        "level": "movement",
                        "options": ["Classical", "Modern"],
                        "explanation": "Default art movements"
                    }
                }
            }
        }

    def create_interface(self):
        with gr.Blocks() as demo:
            gr.Markdown("# Art History Explorer")
            
            with gr.Row():
                query = gr.Textbox(
                    label="Enter your art history query",
                    placeholder="e.g., Napoleon wars, Renaissance Italy"
                )
                search_btn = gr.Button("Explore")

            with gr.Row():
                # Temporal axis
                with gr.Column():
                    time_slider = gr.Slider(
                        minimum=1000,
                        maximum=2024,
                        label="Time Period",
                        interactive=True
                    )
                    time_explanation = gr.Markdown()
                    time_zoom = gr.Button("πŸ” Zoom Time Period")

                # Geographical axis
                with gr.Column():
                    map_plot = gr.Plot(label="Geographic Location")
                    geo_explanation = gr.Markdown()
                    geo_zoom = gr.Button("πŸ” Zoom Geography")

            with gr.Row():
                style_select = gr.Dropdown(
                    multiselect=True,
                    label="Artistic Styles"
                )
                style_explanation = gr.Markdown()
                style_zoom = gr.Button("πŸ” Zoom Styles")

            def initial_search(query):
                config = self.get_llm_response(query)
                
                # Access the correct nested structure
                temporal_config = config["axis_configurations"]["temporal"]["current_zoom"]
                geographical_config = config["axis_configurations"]["geographical"]["current_zoom"]
                style_config = config["axis_configurations"]["style"]["current_zoom"]
                
                # Create map figure
                map_fig = self.create_map(geographical_config["locations"])
                
                return {
                    time_slider: temporal_config["range"],
                    map_plot: map_fig,
                    style_select: gr.Dropdown(choices=style_config["options"]),
                    time_explanation: temporal_config["explanation"],
                    geo_explanation: geographical_config.get("explanation", ""),
                    style_explanation: style_config["explanation"]
                }

            def zoom_axis(query, axis_name, current_value):
                self.current_state["zoom_level"] += 1
                config = self.get_llm_response(
                    query,
                    zoom_context={axis_name: current_value}
                )
                
                axis_config = config["axis_configurations"][axis_name]["current_zoom"]
                
                if axis_name == "temporal":
                    return {
                        time_slider: axis_config["range"],
                        time_explanation: axis_config["explanation"]
                    }
                elif axis_name == "geographical":
                    map_fig = self.create_map(axis_config["locations"])
                    return {
                        map_plot: map_fig,
                        geo_explanation: axis_config.get("explanation", "")
                    }
                else:  # style
                    return {
                        style_select: gr.Dropdown(choices=axis_config["options"]),
                        style_explanation: axis_config["explanation"]
                    }

            # Connect event handlers
            search_btn.click(
                fn=initial_search,
                inputs=[query],
                outputs=[
                    time_slider, 
                    map_plot, 
                    style_select,
                    time_explanation, 
                    geo_explanation, 
                    style_explanation
                ]
            )

            time_zoom.click(
                fn=lambda q, v: zoom_axis(q, "temporal", v),
                inputs=[query, time_slider],
                outputs=[time_slider, time_explanation]
            )

            geo_zoom.click(
                fn=lambda q, v: zoom_axis(q, "geographical", v),
                inputs=[query, map_plot],
                outputs=[map_plot, geo_explanation]
            )

            style_zoom.click(
                fn=lambda q, v: zoom_axis(q, "style", v),
                inputs=[query, style_select],
                outputs=[style_select, style_explanation]
            )

        return demo

if __name__ == "__main__":
    explorer = ArtExplorer()
    demo = explorer.create_interface()
    demo.launch()