Spaces:
				
			
			
	
			
			
		Sleeping
		
	
	
	
			
			
	
	
	
	
		
		
		Sleeping
		
	| import gradio as gr | |
| import json | |
| import os | |
| from dotenv import load_dotenv | |
| from art_explorer import ExplorationPathGenerator | |
| from typing import Dict, Any, Optional, Union | |
| # Load environment variables | |
| load_dotenv() | |
| # Initialize the generator with error handling | |
| try: | |
| api_key = os.getenv("GROQ_API_KEY") | |
| if not api_key: | |
| raise ValueError("GROQ_API_KEY not found in environment variables") | |
| generator = ExplorationPathGenerator(api_key=api_key) | |
| except Exception as e: | |
| print(f"Error initializing ExplorationPathGenerator: {e}") | |
| raise | |
| def format_output(result: Dict[str, Any]) -> str: | |
| """Format the exploration result for display with error handling""" | |
| try: | |
| return json.dumps(result, indent=2, ensure_ascii=False) | |
| except Exception as e: | |
| return json.dumps({ | |
| "error": str(e), | |
| "status": "failed", | |
| "message": "Failed to format output" | |
| }, indent=2) | |
| def parse_json_input(json_str: str, default_value: Any) -> Any: | |
| """ | |
| Safely parse JSON input with detailed error handling | |
| Args: | |
| json_str: JSON string to parse | |
| default_value: Fallback value if parsing fails | |
| """ | |
| if not json_str or json_str.strip() in ('', '{}', '[]'): | |
| return default_value | |
| try: | |
| return json.loads(json_str) | |
| except json.JSONDecodeError as e: | |
| print(f"JSON parse error: {e}") | |
| return default_value | |
| def validate_parameters( | |
| depth: int, | |
| domain: str, | |
| parameters: Dict[str, Any] | |
| ) -> Dict[str, Any]: | |
| """Validate and merge exploration parameters""" | |
| validated_params = { | |
| "depth": max(1, min(10, depth)), # Clamp depth between 1-10 | |
| "domain": domain if domain.strip() else None, | |
| "previous_explorations": [] | |
| } | |
| if isinstance(parameters, dict): | |
| validated_params.update(parameters) | |
| return validated_params | |
| def explore( | |
| query: str, | |
| path_history: str = "[]", | |
| parameters: str = "{}", | |
| depth: int = 5, | |
| domain: str = "" | |
| ) -> str: | |
| """ | |
| Generate exploration path based on user input with comprehensive error handling | |
| Args: | |
| query (str): User's exploration query | |
| path_history (str): JSON string of previous exploration path | |
| parameters (str): JSON string of exploration parameters | |
| depth (int): Exploration depth parameter (1-10) | |
| domain (str): Specific domain context | |
| Returns: | |
| str: Formatted JSON string of exploration results or error message | |
| """ | |
| try: | |
| # Input validation | |
| if not query.strip(): | |
| raise ValueError("Query cannot be empty") | |
| # Parse and validate inputs | |
| selected_path = parse_json_input(path_history, []) | |
| custom_parameters = parse_json_input(parameters, {}) | |
| # Validate and merge parameters | |
| exploration_parameters = validate_parameters(depth, domain, custom_parameters) | |
| # Debug logging | |
| print(f"Processing query: {query}") | |
| print(f"Parameters: {json.dumps(exploration_parameters, indent=2)}") | |
| # Generate exploration path | |
| result = generator.generate_exploration_path( | |
| user_query=query, | |
| selected_path=selected_path, | |
| exploration_parameters=exploration_parameters | |
| ) | |
| # Validate result | |
| if not isinstance(result, dict): | |
| raise ValueError("Invalid response format from generator") | |
| return format_output(result) | |
| except Exception as e: | |
| error_response = { | |
| "error": str(e), | |
| "status": "failed", | |
| "message": "Failed to generate exploration path", | |
| "details": { | |
| "query": query, | |
| "depth": depth, | |
| "domain": domain | |
| } | |
| } | |
| print(f"Error in explore function: {e}") | |
| return format_output(error_response) | |
| def create_interface() -> gr.Interface: | |
| """Create and configure the Gradio interface with enhanced examples and documentation""" | |
| inputs = [ | |
| gr.Textbox( | |
| label="Exploration Query", | |
| placeholder="Enter your art history exploration query...", | |
| lines=2 | |
| ), | |
| gr.Textbox( | |
| label="Path History (JSON)", | |
| placeholder="[]", | |
| lines=3, | |
| value="[]" | |
| ), | |
| gr.Textbox( | |
| label="Additional Parameters (JSON)", | |
| placeholder="{}", | |
| lines=3, | |
| value="{}" | |
| ), | |
| gr.Slider( | |
| label="Exploration Depth", | |
| minimum=1, | |
| maximum=10, | |
| value=5, | |
| step=1 | |
| ), | |
| gr.Textbox( | |
| label="Domain Context", | |
| placeholder="Optional: Specify art history period or movement", | |
| lines=1 | |
| ) | |
| ] | |
| output = gr.Textbox( | |
| label="Exploration Result", | |
| lines=20 | |
| ) | |
| examples = [ | |
| [ | |
| "Explore the evolution of Renaissance painting techniques", | |
| "[]", | |
| "{}", | |
| 5, | |
| "Renaissance" | |
| ], | |
| [ | |
| "Investigate the influence of Japanese art on Impressionism", | |
| "[]", | |
| "{}", | |
| 7, | |
| "Impressionism" | |
| ], | |
| [ | |
| "Analyze the development of Cubism through Picasso's work", | |
| "[]", | |
| "{}", | |
| 6, | |
| "Cubism" | |
| ] | |
| ] | |
| return gr.Interface( | |
| fn=explore, | |
| inputs=inputs, | |
| outputs=output, | |
| title="Art History Exploration Path Generator", | |
| description=""" | |
| Generate structured exploration paths for art history queries. | |
| ## Features: | |
| - Dynamic exploration path generation | |
| - Contextual understanding of art history | |
| - Multi-dimensional analysis | |
| - Customizable exploration depth | |
| ## Usage: | |
| 1. Enter your art history query | |
| 2. Adjust exploration depth (1-10) | |
| 3. Optionally specify domain context | |
| 4. View generated exploration path | |
| """, | |
| examples=examples, | |
| theme="default", | |
| analytics_enabled=False | |
| ) | |
| if __name__ == "__main__": | |
| try: | |
| # Create interface | |
| iface = create_interface() | |
| # Launch with custom configurations | |
| iface.launch() | |
| except Exception as e: | |
| print(f"Failed to launch interface: {e}") |