baconnier commited on
Commit
10cff5d
·
verified ·
1 Parent(s): 2efbb70

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +199 -58
app.py CHANGED
@@ -4,78 +4,219 @@ import os
4
  from dotenv import load_dotenv
5
  from art_explorer import ExplorationPathGenerator
6
  from typing import Dict, Any, Optional, Union
 
7
 
8
  # Load environment variables
9
  load_dotenv()
10
 
11
  # Initialize the generator with error handling
12
  try:
13
- api_key = os.getenv("GROQ_API_KEY")
14
- if not api_key:
15
- raise ValueError("GROQ_API_KEY not found in environment variables")
16
- generator = ExplorationPathGenerator(api_key=api_key)
17
  except Exception as e:
18
- print(f"Error initializing ExplorationPathGenerator: {e}")
19
- raise
20
 
21
  def format_output(result: Dict[str, Any]) -> str:
22
- """Format the exploration result for display with error handling"""
23
- try:
24
- return json.dumps(result, indent=2, ensure_ascii=False)
25
- except Exception as e:
26
- return json.dumps({
27
- "error": str(e),
28
- "status": "failed",
29
- "message": "Failed to format output"
30
- }, indent=2)
31
 
32
  def parse_json_input(json_str: str, default_value: Any) -> Any:
33
- """
34
- Safely parse JSON input with detailed error handling
35
-
36
- Args:
37
- json_str: JSON string to parse
38
- default_value: Fallback value if parsing fails
39
- """
40
- if not json_str or json_str.strip() in ('', '{}', '[]'):
41
- return default_value
42
- try:
43
- return json.loads(json_str)
44
- except json.JSONDecodeError as e:
45
- print(f"JSON parse error: {e}")
46
- return default_value
47
 
48
  def validate_parameters(
49
- depth: int,
50
- domain: str,
51
- parameters: Dict[str, Any]
52
  ) -> Dict[str, Any]:
53
- """Validate and merge exploration parameters"""
54
- validated_params = {
55
- "depth": max(1, min(10, depth)), # Clamp depth between 1-10
56
- "domain": domain if domain.strip() else None,
57
- "previous_explorations": []
58
- }
59
- if isinstance(parameters, dict):
60
- validated_params.update(parameters)
61
- return validated_params
62
 
63
  def explore(
64
- query: str,
65
- path_history: str = "[]",
66
- parameters: str = "{}",
67
- depth: int = 5,
68
- domain: str = ""
69
  ) -> str:
70
- """
71
- Generate exploration path based on user input with comprehensive error handling
72
-
73
- Args:
74
- query (str): User's exploration query
75
- path_history (str): JSON string of previous exploration path
76
- parameters (str): JSON string of exploration parameters
77
- depth (int): Exploration depth parameter (1-10)
78
- domain (str): Specific domain context
79
-
80
- Returns:
81
- str: Formatted JSON string of exploration results or error message
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  from dotenv import load_dotenv
5
  from art_explorer import ExplorationPathGenerator
6
  from typing import Dict, Any, Optional, Union
7
+ from datetime import datetime
8
 
9
  # Load environment variables
10
  load_dotenv()
11
 
12
  # Initialize the generator with error handling
13
  try:
14
+ api_key = os.getenv("GROQ_API_KEY")
15
+ if not api_key:
16
+ raise ValueError("GROQ_API_KEY not found in environment variables")
17
+ generator = ExplorationPathGenerator(api_key=api_key)
18
  except Exception as e:
19
+ print(f"Error initializing ExplorationPathGenerator: {e}")
20
+ raise
21
 
22
  def format_output(result: Dict[str, Any]) -> str:
23
+ """Format the exploration result for display with error handling"""
24
+ try:
25
+ return json.dumps(result, indent=2, ensure_ascii=False)
26
+ except Exception as e:
27
+ return json.dumps({
28
+ "error": str(e),
29
+ "status": "failed",
30
+ "message": "Failed to format output"
31
+ }, indent=2)
32
 
33
  def parse_json_input(json_str: str, default_value: Any) -> Any:
34
+ """
35
+ Safely parse JSON input with detailed error handling
36
+
37
+ Args:
38
+ json_str: JSON string to parse
39
+ default_value: Fallback value if parsing fails
40
+ """
41
+ if not json_str or json_str.strip() in ('', '{}', '[]'):
42
+ return default_value
43
+ try:
44
+ return json.loads(json_str)
45
+ except json.JSONDecodeError as e:
46
+ print(f"JSON parse error: {e}")
47
+ return default_value
48
 
49
  def validate_parameters(
50
+ depth: int,
51
+ domain: str,
52
+ parameters: Dict[str, Any]
53
  ) -> Dict[str, Any]:
54
+ """Validate and merge exploration parameters"""
55
+ validated_params = {
56
+ "depth": max(1, min(10, depth)), # Clamp depth between 1-10
57
+ "domain": domain if domain.strip() else None,
58
+ "previous_explorations": []
59
+ }
60
+ if isinstance(parameters, dict):
61
+ validated_params.update(parameters)
62
+ return validated_params
63
 
64
  def explore(
65
+ query: str,
66
+ path_history: str = "[]",
67
+ parameters: str = "{}",
68
+ depth: int = 5,
69
+ domain: str = ""
70
  ) -> str:
71
+ """
72
+ Generate exploration path based on user input with comprehensive error handling
73
+
74
+ Args:
75
+ query (str): User's exploration query
76
+ path_history (str): JSON string of previous exploration path
77
+ parameters (str): JSON string of exploration parameters
78
+ depth (int): Exploration depth parameter (1-10)
79
+ domain (str): Specific domain context
80
+
81
+ Returns:
82
+ str: Formatted JSON string of exploration results or error message
83
+ """
84
+ try:
85
+ # Input validation
86
+ if not query.strip():
87
+ raise ValueError("Query cannot be empty")
88
+
89
+ # Parse and validate inputs
90
+ selected_path = parse_json_input(path_history, [])
91
+ custom_parameters = parse_json_input(parameters, {})
92
+
93
+ # Validate and merge parameters
94
+ exploration_parameters = validate_parameters(depth, domain, custom_parameters)
95
+
96
+ # Debug logging
97
+ print(f"Processing query: {query}")
98
+ print(f"Parameters: {json.dumps(exploration_parameters, indent=2)}")
99
+
100
+ # Generate exploration path
101
+ result = generator.generate_exploration_path(
102
+ user_query=query,
103
+ selected_path=selected_path,
104
+ exploration_parameters=exploration_parameters
105
+ )
106
+
107
+ # Validate result
108
+ if not isinstance(result, dict):
109
+ raise ValueError("Invalid response format from generator")
110
+
111
+ return format_output(result)
112
+
113
+ except Exception as e:
114
+ error_response = {
115
+ "error": str(e),
116
+ "status": "failed",
117
+ "message": "Failed to generate exploration path",
118
+ "details": {
119
+ "query": query,
120
+ "depth": depth,
121
+ "domain": domain
122
+ }
123
+ }
124
+ print(f"Error in explore function: {e}")
125
+ return format_output(error_response)
126
+
127
+ def create_interface() -> gr.Interface:
128
+ """Create and configure the Gradio interface with enhanced examples and documentation"""
129
+
130
+ inputs = [
131
+ gr.Textbox(
132
+ label="Exploration Query",
133
+ placeholder="Enter your art history exploration query...",
134
+ lines=2
135
+ ),
136
+ gr.Textbox(
137
+ label="Path History (JSON)",
138
+ placeholder="[]",
139
+ lines=3,
140
+ value="[]"
141
+ ),
142
+ gr.Textbox(
143
+ label="Additional Parameters (JSON)",
144
+ placeholder="{}",
145
+ lines=3,
146
+ value="{}"
147
+ ),
148
+ gr.Slider(
149
+ label="Exploration Depth",
150
+ minimum=1,
151
+ maximum=10,
152
+ value=5,
153
+ step=1
154
+ ),
155
+ gr.Textbox(
156
+ label="Domain Context",
157
+ placeholder="Optional: Specify art history period or movement",
158
+ lines=1
159
+ )
160
+ ]
161
+
162
+ output = gr.Textbox(
163
+ label="Exploration Result",
164
+ lines=20
165
+ )
166
+
167
+ examples = [
168
+ [
169
+ "Explore the evolution of Renaissance painting techniques",
170
+ "[]",
171
+ "{}",
172
+ 5,
173
+ "Renaissance"
174
+ ],
175
+ [
176
+ "Investigate the influence of Japanese art on Impressionism",
177
+ "[]",
178
+ "{}",
179
+ 7,
180
+ "Impressionism"
181
+ ],
182
+ [
183
+ "Analyze the development of Cubism through Picasso's work",
184
+ "[]",
185
+ "{}",
186
+ 6,
187
+ "Cubism"
188
+ ]
189
+ ]
190
+
191
+ return gr.Interface(
192
+ fn=explore,
193
+ inputs=inputs,
194
+ outputs=output,
195
+ title="Art History Exploration Path Generator",
196
+ description="""Generate structured exploration paths for art history queries.
197
+
198
+ ## Features:
199
+ - Dynamic exploration path generation
200
+ - Contextual understanding of art history
201
+ - Multi-dimensional analysis
202
+ - Customizable exploration depth
203
+
204
+ ## Usage:
205
+ 1. Enter your art history query
206
+ 2. Adjust exploration depth (1-10)
207
+ 3. Optionally specify domain context
208
+ 4. View generated exploration path""",
209
+ examples=examples,
210
+ theme="default",
211
+ analytics_enabled=False
212
+ )
213
+
214
+ if __name__ == "__main__":
215
+ try:
216
+ print(f"===== Application Startup at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} =====")
217
+ # Create interface
218
+ iface = create_interface()
219
+ # Launch with custom configurations
220
+ iface.launch()
221
+ except Exception as e:
222
+ print(f"Failed to launch interface: {e}")