Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -3,25 +3,63 @@ 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
|
14 |
def format_output(result: Dict[str, Any]) -> str:
|
15 |
-
"""Format the exploration result for display"""
|
16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
|
18 |
def parse_json_input(json_str: str, default_value: Any) -> Any:
|
19 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
try:
|
21 |
-
return json.loads(json_str)
|
22 |
-
except json.JSONDecodeError:
|
|
|
23 |
return default_value
|
24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
def explore(
|
26 |
query: str,
|
27 |
path_history: str = "[]",
|
@@ -30,32 +68,34 @@ def explore(
|
|
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,
|
@@ -63,20 +103,29 @@ def explore(
|
|
63 |
exploration_parameters=exploration_parameters
|
64 |
)
|
65 |
|
66 |
-
#
|
|
|
|
|
|
|
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",
|
@@ -109,13 +158,35 @@ def create_interface() -> gr.Interface:
|
|
109 |
)
|
110 |
]
|
111 |
|
112 |
-
# Define interface output
|
113 |
output = gr.Textbox(
|
114 |
label="Exploration Result",
|
115 |
lines=20
|
116 |
)
|
117 |
|
118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
119 |
return gr.Interface(
|
120 |
fn=explore,
|
121 |
inputs=inputs,
|
@@ -124,35 +195,32 @@ def create_interface() -> gr.Interface:
|
|
124 |
description="""
|
125 |
Generate structured exploration paths for art history queries.
|
126 |
|
127 |
-
|
128 |
-
-
|
129 |
-
-
|
130 |
-
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
131 |
""",
|
132 |
-
examples=
|
133 |
-
|
134 |
-
|
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 |
-
|
155 |
-
|
156 |
if __name__ == "__main__":
|
157 |
-
|
158 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
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 = "[]",
|
|
|
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
|
82 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
83 |
try:
|
84 |
+
# Input validation
|
85 |
+
if not query.strip():
|
86 |
+
raise ValueError("Query cannot be empty")
|
87 |
+
|
88 |
+
# Parse and validate inputs
|
89 |
+
selected_path = parse_json_input(path_history, [])
|
90 |
+
custom_parameters = parse_json_input(parameters, {})
|
91 |
+
|
92 |
+
# Validate and merge parameters
|
93 |
+
exploration_parameters = validate_parameters(depth, domain, custom_parameters)
|
94 |
+
|
95 |
+
# Debug logging
|
96 |
+
print(f"Processing query: {query}")
|
97 |
+
print(f"Parameters: {json.dumps(exploration_parameters, indent=2)}")
|
98 |
+
|
99 |
# Generate exploration path
|
100 |
result = generator.generate_exploration_path(
|
101 |
user_query=query,
|
|
|
103 |
exploration_parameters=exploration_parameters
|
104 |
)
|
105 |
|
106 |
+
# Validate result
|
107 |
+
if not isinstance(result, dict):
|
108 |
+
raise ValueError("Invalid response format from generator")
|
109 |
+
|
110 |
return format_output(result)
|
111 |
+
|
112 |
except Exception as e:
|
113 |
error_response = {
|
114 |
"error": str(e),
|
115 |
"status": "failed",
|
116 |
+
"message": "Failed to generate exploration path",
|
117 |
+
"details": {
|
118 |
+
"query": query,
|
119 |
+
"depth": depth,
|
120 |
+
"domain": domain
|
121 |
+
}
|
122 |
}
|
123 |
+
print(f"Error in explore function: {e}")
|
124 |
return format_output(error_response)
|
125 |
|
126 |
def create_interface() -> gr.Interface:
|
127 |
+
"""Create and configure the Gradio interface with enhanced examples and documentation"""
|
128 |
|
|
|
129 |
inputs = [
|
130 |
gr.Textbox(
|
131 |
label="Exploration Query",
|
|
|
158 |
)
|
159 |
]
|
160 |
|
|
|
161 |
output = gr.Textbox(
|
162 |
label="Exploration Result",
|
163 |
lines=20
|
164 |
)
|
165 |
|
166 |
+
examples = [
|
167 |
+
[
|
168 |
+
"Explore the evolution of Renaissance painting techniques",
|
169 |
+
"[]",
|
170 |
+
"{}",
|
171 |
+
5,
|
172 |
+
"Renaissance"
|
173 |
+
],
|
174 |
+
[
|
175 |
+
"Investigate the influence of Japanese art on Impressionism",
|
176 |
+
"[]",
|
177 |
+
"{}",
|
178 |
+
7,
|
179 |
+
"Impressionism"
|
180 |
+
],
|
181 |
+
[
|
182 |
+
"Analyze the development of Cubism through Picasso's work",
|
183 |
+
"[]",
|
184 |
+
"{}",
|
185 |
+
6,
|
186 |
+
"Cubism"
|
187 |
+
]
|
188 |
+
]
|
189 |
+
|
190 |
return gr.Interface(
|
191 |
fn=explore,
|
192 |
inputs=inputs,
|
|
|
195 |
description="""
|
196 |
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 |
""",
|
210 |
+
examples=examples,
|
211 |
+
theme="default",
|
212 |
+
analytics_enabled=False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
213 |
)
|
214 |
|
|
|
|
|
|
|
|
|
|
|
215 |
if __name__ == "__main__":
|
216 |
+
try:
|
217 |
+
# Create interface
|
218 |
+
iface = create_interface()
|
219 |
+
# Launch with custom configurations
|
220 |
+
iface.launch(
|
221 |
+
server_name="0.0.0.0",
|
222 |
+
share=False,
|
223 |
+
debug=True
|
224 |
+
)
|
225 |
+
except Exception as e:
|
226 |
+
print(f"Failed to launch interface: {e}")
|