baconnier commited on
Commit
a48e4da
Β·
verified Β·
1 Parent(s): f975e53

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +170 -173
app.py CHANGED
@@ -3,45 +3,46 @@ import openai
3
  import gradio as gr
4
  import json
5
  import plotly.graph_objects as go
6
-
7
- from variables import *
8
-
9
 
10
  class ArtExplorer:
11
- def __init__(self):
12
- self.client = openai.OpenAI(
13
- base_url="https://api.groq.com/openai/v1",
14
- api_key=os.environ.get("GROQ_API_KEY")
15
- )
16
- self.current_state = {
17
- "zoom_level": 0,
18
- "selections": {}
19
- }
20
-
21
- def create_map(self, locations):
22
- """Create a Plotly map figure from location data"""
23
- if not locations:
24
- locations = [{"name": "Paris", "lat": 48.8566, "lon": 2.3522}]
25
-
26
- fig = go.Figure(go.Scattermapbox(
27
- lat=[loc.get('lat') for loc in locations],
28
- lon=[loc.get('lon') for loc in locations],
29
- mode='markers',
30
- marker=go.scattermapbox.Marker(size=10),
31
- text=[loc.get('name') for loc in locations]
32
- ))
33
-
34
- fig.update_layout(
35
- mapbox_style="open-street-map",
36
- mapbox=dict(
37
- center=dict(lat=48.8566, lon=2.3522),
38
- zoom=4
39
- ),
40
- margin=dict(r=0, t=0, l=0, b=0)
41
- )
42
- return fig
43
-
44
- def get_llm_response(self, query: str, zoom_context: dict = None) -> dict:
 
 
 
45
  try:
46
  current_zoom_states = {
47
  "temporal": {"level": self.current_state["zoom_level"], "selection": ""},
@@ -49,12 +50,12 @@ class ArtExplorer:
49
  "style": {"level": self.current_state["zoom_level"], "selection": ""},
50
  "subject": {"level": self.current_state["zoom_level"], "selection": ""}
51
  }
52
-
53
  if zoom_context:
54
  for key, value in zoom_context.items():
55
  if key in current_zoom_states:
56
  current_zoom_states[key]["selection"] = value
57
-
58
  messages = [
59
  {"role": "system", "content": "You are an expert art historian specializing in interactive exploration."},
60
  {"role": "user", "content": CONTEXTUAL_ZOOM_PROMPT.format(
@@ -62,155 +63,151 @@ class ArtExplorer:
62
  current_zoom_states=json.dumps(current_zoom_states, indent=2)
63
  )}
64
  ]
65
-
66
- # Print the messages being sent to the LLM for debugging
67
  print("Messages sent to LLM:")
68
- for message in messages:
69
- print(f"{message['role']}: {message['content']}")
70
-
71
  response = self.client.chat.completions.create(
72
  model="mixtral-8x7b-32768",
73
  messages=messages,
74
  temperature=0.1,
75
  max_tokens=2048
76
  )
77
-
78
- # Print the raw response from the LLM for debugging
79
  print("Raw response from LLM:")
80
  print(response)
81
-
82
  result = json.loads(response.choices[0].message.content)
83
-
84
- # Print the parsed result for debugging
85
- print("Parsed result from LLM:")
86
  print(result)
87
-
88
  return result
89
- except json.JSONDecodeError as json_err:
90
- print(f"JSON decode error: {str(json_err)}")
91
- print(f"Response content: {response.choices[0].message.content}")
92
- return self.get_default_response()
93
  except Exception as e:
94
  print(f"Error in LLM response: {str(e)}")
95
  return self.get_default_response()
96
 
97
- def get_default_response(self):
98
- return CONTEXTUAL_ZOOM_default_response
99
-
100
- def create_interface(self):
101
- with gr.Blocks() as demo:
102
- gr.Markdown("# Art History Explorer")
103
-
104
- with gr.Row():
105
- query = gr.Textbox(
106
- label="Enter your art history query",
107
- placeholder="e.g., Napoleon wars, Renaissance Italy"
108
- )
109
- search_btn = gr.Button("Explore")
110
-
111
- with gr.Row():
112
- # Temporal axis
113
- with gr.Column():
114
- time_slider = gr.Slider(
115
- minimum=1000,
116
- maximum=2024,
117
- label="Time Period",
118
- interactive=True
119
- )
120
- time_explanation = gr.Markdown()
121
- time_zoom = gr.Button("πŸ” Zoom Time Period")
122
-
123
- # Geographical axis
124
- with gr.Column():
125
- map_plot = gr.Plot(label="Geographic Location")
126
- geo_explanation = gr.Markdown()
127
- geo_zoom = gr.Button("πŸ” Zoom Geography")
128
-
129
- with gr.Row():
130
- style_select = gr.Dropdown(
131
- multiselect=True,
132
- label="Artistic Styles"
133
- )
134
- style_explanation = gr.Markdown()
135
- style_zoom = gr.Button("πŸ” Zoom Styles")
136
-
137
- def initial_search(query):
138
- config = self.get_llm_response(query)
139
- temporal_config = config["axis_configurations"]["temporal"]["current_zoom"]
140
- geographical_config = config["axis_configurations"]["geographical"]["current_zoom"]
141
- style_config = config["axis_configurations"]["style"]["current_zoom"]
142
-
143
- map_fig = self.create_map(geographical_config["locations"])
144
-
145
- return {
146
- time_slider: temporal_config["range"],
147
- map_plot: map_fig,
148
- style_select: gr.Dropdown(choices=style_config["options"]),
149
- time_explanation: temporal_config["explanation"],
150
- geo_explanation: geographical_config.get("explanation", ""),
151
- style_explanation: style_config["explanation"]
152
- }
153
-
154
- def zoom_axis(query, axis_name, current_value):
155
- self.current_state["zoom_level"] += 1
156
- config = self.get_llm_response(
157
- query,
158
- zoom_context={axis_name: current_value}
159
- )
160
- axis_config = config["axis_configurations"][axis_name]["current_zoom"]
161
-
162
- if axis_name == "temporal":
163
- return {
164
- time_slider: axis_config["range"],
165
- time_explanation: axis_config["explanation"]
166
- }
167
- elif axis_name == "geographical":
168
- map_fig = self.create_map(axis_config["locations"])
169
- return {
170
- map_plot: map_fig,
171
- geo_explanation: axis_config.get("explanation", "")
172
- }
173
- else: # style
174
- return {
175
- style_select: gr.Dropdown(choices=axis_config["options"]),
176
- style_explanation: axis_config["explanation"]
177
- }
178
-
179
- # Connect event handlers
180
- search_btn.click(
181
- fn=initial_search,
182
- inputs=[query],
183
- outputs=[
184
- time_slider,
185
- map_plot,
186
- style_select,
187
- time_explanation,
188
- geo_explanation,
189
- style_explanation
190
- ]
191
- )
192
-
193
- time_zoom.click(
194
- fn=lambda q, v: zoom_axis(q, "temporal", v),
195
- inputs=[query, time_slider],
196
- outputs=[time_slider, time_explanation]
197
- )
198
-
199
- geo_zoom.click(
200
- fn=lambda q, v: zoom_axis(q, "geographical", v),
201
- inputs=[query, map_plot],
202
- outputs=[map_plot, geo_explanation]
203
- )
204
-
205
- style_zoom.click(
206
- fn=lambda q, v: zoom_axis(q, "style", v),
207
- inputs=[query, style_select],
208
- outputs=[style_select, style_explanation]
209
- )
210
-
211
- return demo
212
 
213
  if __name__ == "__main__":
214
- explorer = ArtExplorer()
215
- demo = explorer.create_interface()
216
- demo.launch()
 
 
 
 
 
3
  import gradio as gr
4
  import json
5
  import plotly.graph_objects as go
6
+ from variables import CONTEXTUAL_ZOOM_PROMPT, CONTEXTUAL_ZOOM_default_response
 
 
7
 
8
  class ArtExplorer:
9
+ def __init__(self):
10
+ print("Initializing ArtExplorer...")
11
+ self.client = openai.OpenAI(
12
+ base_url="https://api.groq.com/openai/v1",
13
+ api_key=os.environ.get("GROQ_API_KEY")
14
+ )
15
+ print("OpenAI client initialized")
16
+ self.current_state = {
17
+ "zoom_level": 0,
18
+ "selections": {}
19
+ }
20
+ print("Current state initialized")
21
+
22
+ def create_map(self, locations):
23
+ """Create a Plotly map figure from location data"""
24
+ if not locations:
25
+ locations = [{"name": "Paris", "lat": 48.8566, "lon": 2.3522}]
26
+
27
+ fig = go.Figure(go.Scattermapbox(
28
+ lat=[loc.get('lat') for loc in locations],
29
+ lon=[loc.get('lon') for loc in locations],
30
+ mode='markers',
31
+ marker=go.scattermapbox.Marker(size=10),
32
+ text=[loc.get('name') for loc in locations]
33
+ ))
34
+
35
+ fig.update_layout(
36
+ mapbox_style="open-street-map",
37
+ mapbox=dict(
38
+ center=dict(lat=48.8566, lon=2.3522),
39
+ zoom=4
40
+ ),
41
+ margin=dict(r=0, t=0, l=0, b=0)
42
+ )
43
+ return fig
44
+
45
+ def get_llm_response(self, query: str, zoom_context: dict = None) -> dict:
46
  try:
47
  current_zoom_states = {
48
  "temporal": {"level": self.current_state["zoom_level"], "selection": ""},
 
50
  "style": {"level": self.current_state["zoom_level"], "selection": ""},
51
  "subject": {"level": self.current_state["zoom_level"], "selection": ""}
52
  }
53
+
54
  if zoom_context:
55
  for key, value in zoom_context.items():
56
  if key in current_zoom_states:
57
  current_zoom_states[key]["selection"] = value
58
+
59
  messages = [
60
  {"role": "system", "content": "You are an expert art historian specializing in interactive exploration."},
61
  {"role": "user", "content": CONTEXTUAL_ZOOM_PROMPT.format(
 
63
  current_zoom_states=json.dumps(current_zoom_states, indent=2)
64
  )}
65
  ]
66
+
 
67
  print("Messages sent to LLM:")
68
+ print(messages)
69
+
 
70
  response = self.client.chat.completions.create(
71
  model="mixtral-8x7b-32768",
72
  messages=messages,
73
  temperature=0.1,
74
  max_tokens=2048
75
  )
76
+
 
77
  print("Raw response from LLM:")
78
  print(response)
79
+
80
  result = json.loads(response.choices[0].message.content)
81
+
82
+ print("Parsed result:")
 
83
  print(result)
84
+
85
  return result
 
 
 
 
86
  except Exception as e:
87
  print(f"Error in LLM response: {str(e)}")
88
  return self.get_default_response()
89
 
90
+ def get_default_response(self):
91
+ return CONTEXTUAL_ZOOM_default_response
92
+
93
+ def create_interface(self):
94
+ with gr.Blocks() as demo:
95
+ gr.Markdown("# Art History Explorer")
96
+
97
+ with gr.Row():
98
+ query = gr.Textbox(
99
+ label="Enter your art history query",
100
+ placeholder="e.g., Napoleon wars, Renaissance Italy"
101
+ )
102
+ search_btn = gr.Button("Explore")
103
+
104
+ with gr.Row():
105
+ # Temporal axis
106
+ with gr.Column():
107
+ time_slider = gr.Slider(
108
+ minimum=1000,
109
+ maximum=2024,
110
+ label="Time Period",
111
+ interactive=True
112
+ )
113
+ time_explanation = gr.Markdown()
114
+ time_zoom = gr.Button("πŸ” Zoom Time Period")
115
+
116
+ # Geographical axis
117
+ with gr.Column():
118
+ map_plot = gr.Plot(label="Geographic Location")
119
+ geo_explanation = gr.Markdown()
120
+ geo_zoom = gr.Button("πŸ” Zoom Geography")
121
+
122
+ with gr.Row():
123
+ style_select = gr.Dropdown(
124
+ multiselect=True,
125
+ label="Artistic Styles"
126
+ )
127
+ style_explanation = gr.Markdown()
128
+ style_zoom = gr.Button("πŸ” Zoom Styles")
129
+
130
+ def initial_search(query):
131
+ config = self.get_llm_response(query)
132
+ temporal_config = config["axis_configurations"]["temporal"]["current_zoom"]
133
+ geographical_config = config["axis_configurations"]["geographical"]["current_zoom"]
134
+ style_config = config["axis_configurations"]["style"]["current_zoom"]
135
+
136
+ map_fig = self.create_map(geographical_config["locations"])
137
+
138
+ return {
139
+ time_slider: temporal_config["range"],
140
+ map_plot: map_fig,
141
+ style_select: gr.Dropdown(choices=style_config["options"]),
142
+ time_explanation: temporal_config["explanation"],
143
+ geo_explanation: geographical_config.get("explanation", ""),
144
+ style_explanation: style_config["explanation"]
145
+ }
146
+
147
+ def zoom_axis(query, axis_name, current_value):
148
+ self.current_state["zoom_level"] += 1
149
+ config = self.get_llm_response(
150
+ query,
151
+ zoom_context={axis_name: current_value}
152
+ )
153
+ axis_config = config["axis_configurations"][axis_name]["current_zoom"]
154
+
155
+ if axis_name == "temporal":
156
+ return {
157
+ time_slider: axis_config["range"],
158
+ time_explanation: axis_config["explanation"]
159
+ }
160
+ elif axis_name == "geographical":
161
+ map_fig = self.create_map(axis_config["locations"])
162
+ return {
163
+ map_plot: map_fig,
164
+ geo_explanation: axis_config.get("explanation", "")
165
+ }
166
+ else: # style
167
+ return {
168
+ style_select: gr.Dropdown(choices=axis_config["options"]),
169
+ style_explanation: axis_config["explanation"]
170
+ }
171
+
172
+ # Connect event handlers
173
+ search_btn.click(
174
+ fn=initial_search,
175
+ inputs=[query],
176
+ outputs=[
177
+ time_slider,
178
+ map_plot,
179
+ style_select,
180
+ time_explanation,
181
+ geo_explanation,
182
+ style_explanation
183
+ ]
184
+ )
185
+
186
+ time_zoom.click(
187
+ fn=lambda q, v: zoom_axis(q, "temporal", v),
188
+ inputs=[query, time_slider],
189
+ outputs=[time_slider, time_explanation]
190
+ )
191
+
192
+ geo_zoom.click(
193
+ fn=lambda q, v: zoom_axis(q, "geographical", v),
194
+ inputs=[query, map_plot],
195
+ outputs=[map_plot, geo_explanation]
196
+ )
197
+
198
+ style_zoom.click(
199
+ fn=lambda q, v: zoom_axis(q, "style", v),
200
+ inputs=[query, style_select],
201
+ outputs=[style_select, style_explanation]
202
+ )
203
+
204
+ return demo
205
 
206
  if __name__ == "__main__":
207
+ print("Starting initialization...")
208
+ explorer = ArtExplorer()
209
+ print("Created ArtExplorer instance")
210
+ demo = explorer.create_interface()
211
+ print("Created interface")
212
+ demo.launch()
213
+ print("Launched demo")