baconnier commited on
Commit
0fc768b
·
verified ·
1 Parent(s): efdf3f2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +161 -74
app.py CHANGED
@@ -1,87 +1,174 @@
1
  import gradio as gr
2
- from art_explorer import ArtExplorer
3
- from visualization import create_map_visualization, create_timeline_visualization
4
  from dotenv import load_dotenv
 
 
5
 
6
  # Load environment variables
7
  load_dotenv()
8
 
9
- class ArtExplorerInterface:
10
- def __init__(self):
11
- self.explorer = ArtExplorer()
12
 
13
- def explore(self, query: str, zoom_level: int) -> tuple:
14
- # Get exploration results
15
- response = self.explorer.explore_art_period(query, zoom_level)
16
-
17
- if not response:
18
- return "Error in exploration", None, None
19
-
20
- # Create visualizations
21
- map_fig = create_map_visualization(self.explorer.get_location_data())
22
- timeline_fig = create_timeline_visualization(self.explorer.get_timeline_data())
23
-
24
- # Format text response
25
- text_response = f"""
26
- Period: {response.time_period.name}
27
- Years: {response.time_period.start_year} - {response.time_period.end_year}
28
-
29
- Cultural Context:
30
- {response.cultural_context}
31
-
32
- Key Artists:
33
- {', '.join(artist.name for artist in response.key_artists)}
34
-
35
- Notable Works:
36
- {', '.join(work.title for work in response.notable_works)}
37
-
38
- Influence:
39
- {response.influence_on_later_periods}
40
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- return text_response, map_fig, timeline_fig
 
 
 
 
 
 
 
 
43
 
44
- def create_interface(self):
45
- with gr.Blocks(title="Art History Explorer") as interface:
46
- gr.Markdown("# Art History Explorer")
47
-
48
- with gr.Row():
49
- query_input = gr.Textbox(
50
- label="Enter your art history query",
51
- placeholder="e.g., Italian Renaissance in Florence"
52
- )
53
- zoom_level = gr.Slider(
54
- minimum=1,
55
- maximum=5,
56
- value=1,
57
- step=1,
58
- label="Zoom Level"
59
- )
60
-
61
- explore_btn = gr.Button("Explore")
62
-
63
- with gr.Row():
64
- text_output = gr.Textbox(
65
- label="Exploration Results",
66
- interactive=False
67
- )
68
-
69
- with gr.Row():
70
- map_output = gr.Plot(label="Geographic Context")
71
- timeline_output = gr.Plot(label="Historical Timeline")
72
-
73
- explore_btn.click(
74
- fn=self.explore,
75
- inputs=[query_input, zoom_level],
76
- outputs=[text_output, map_output, timeline_output]
77
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
 
79
- return interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
- def main():
82
- app = ArtExplorerInterface()
83
- interface = app.create_interface()
84
- interface.launch(share=True)
 
 
 
 
 
85
 
86
  if __name__ == "__main__":
87
- main()
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import json
3
+ import os
4
  from dotenv import load_dotenv
5
+ from art_explorer import ExplorationPathGenerator
6
+ from typing import Dict, Any
7
 
8
  # Load environment variables
9
  load_dotenv()
10
 
11
+ # Initialize the generator
12
+ generator = ExplorationPathGenerator(api_key=os.getenv("GROQ_API_KEY"))
 
13
 
14
+ def format_output(result: Dict[str, Any]) -> str:
15
+ """Format the exploration result for display"""
16
+ return json.dumps(result, indent=2)
17
+
18
+ def parse_json_input(json_str: str, default_value: Any) -> Any:
19
+ """Safely parse JSON input with fallback to default value"""
20
+ try:
21
+ return json.loads(json_str) if json_str else default_value
22
+ except json.JSONDecodeError:
23
+ return default_value
24
+
25
+ def explore(
26
+ query: str,
27
+ path_history: str = "[]",
28
+ parameters: str = "{}",
29
+ depth: int = 5,
30
+ domain: str = ""
31
+ ) -> str:
32
+ """
33
+ Generate exploration path based on user input
34
+
35
+ Args:
36
+ query (str): User's exploration query
37
+ path_history (str): JSON string of previous exploration path
38
+ parameters (str): JSON string of exploration parameters
39
+ depth (int): Exploration depth parameter
40
+ domain (str): Specific domain context
41
+
42
+ Returns:
43
+ str: Formatted JSON string of exploration results
44
+ """
45
+ # Parse path history
46
+ selected_path = parse_json_input(path_history, [])
47
+
48
+ # Parse and merge parameters
49
+ base_parameters = {
50
+ "depth": depth,
51
+ "domain": domain if domain else None,
52
+ "previous_explorations": []
53
+ }
54
+
55
+ custom_parameters = parse_json_input(parameters, {})
56
+ exploration_parameters = {**base_parameters, **custom_parameters}
57
+
58
+ try:
59
+ # Generate exploration path
60
+ result = generator.generate_exploration_path(
61
+ user_query=query,
62
+ selected_path=selected_path,
63
+ exploration_parameters=exploration_parameters
64
+ )
65
 
66
+ # Format and return result
67
+ return format_output(result)
68
+ except Exception as e:
69
+ error_response = {
70
+ "error": str(e),
71
+ "status": "failed",
72
+ "message": "Failed to generate exploration path"
73
+ }
74
+ return format_output(error_response)
75
 
76
+ def create_interface() -> gr.Interface:
77
+ """Create and configure the Gradio interface"""
78
+
79
+ # Define interface inputs
80
+ inputs = [
81
+ gr.Textbox(
82
+ label="Exploration Query",
83
+ placeholder="Enter your art history exploration query...",
84
+ lines=2
85
+ ),
86
+ gr.Textbox(
87
+ label="Path History (JSON)",
88
+ placeholder="[]",
89
+ lines=3,
90
+ value="[]"
91
+ ),
92
+ gr.Textbox(
93
+ label="Additional Parameters (JSON)",
94
+ placeholder="{}",
95
+ lines=3,
96
+ value="{}"
97
+ ),
98
+ gr.Slider(
99
+ label="Exploration Depth",
100
+ minimum=1,
101
+ maximum=10,
102
+ value=5,
103
+ step=1
104
+ ),
105
+ gr.Textbox(
106
+ label="Domain Context",
107
+ placeholder="Optional: Specify art history period or movement",
108
+ lines=1
109
+ )
110
+ ]
111
+
112
+ # Define interface output
113
+ output = gr.Textbox(
114
+ label="Exploration Result",
115
+ lines=20
116
+ )
117
+
118
+ # Create and return interface
119
+ return gr.Interface(
120
+ fn=explore,
121
+ inputs=inputs,
122
+ outputs=output,
123
+ title="Art History Exploration Path Generator",
124
+ description="""
125
+ Generate structured exploration paths for art history queries.
126
 
127
+ - Enter your query about any art history topic
128
+ - Optionally provide previous exploration path as JSON
129
+ - Adjust exploration parameters as needed
130
+ - View the generated exploration path with multiple dimensions
131
+ """,
132
+ examples=[
133
+ [
134
+ "Explore the evolution of Renaissance painting techniques",
135
+ "[]",
136
+ "{}",
137
+ 5,
138
+ "Renaissance"
139
+ ],
140
+ [
141
+ "Investigate the influence of Japanese art on Impressionism",
142
+ "[]",
143
+ "{}",
144
+ 7,
145
+ "Impressionism"
146
+ ]
147
+ ],
148
+ theme="default"
149
+ )
150
+
151
+ # Create and launch the interface
152
+ iface = create_interface()
153
 
154
+ # Add custom CSS for better appearance
155
+ css = """
156
+ .gradio-container {
157
+ font-family: 'Arial', sans-serif;
158
+ }
159
+ .output-text {
160
+ font-family: 'Courier New', monospace;
161
+ }
162
+ """
163
 
164
  if __name__ == "__main__":
165
+ # Launch with custom configurations
166
+ iface.launch(
167
+ share=False, # Set to True to create a public link
168
+ server_name="0.0.0.0", # Listen on all network interfaces
169
+ server_port=7860, # Default Gradio port
170
+ debug=True,
171
+ enable_queue=True,
172
+ max_threads=40,
173
+ custom_css=css
174
+ )