Spaces:
Running
Running
File size: 12,081 Bytes
9bf60ea |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 |
"""
Template Validator for HuggingFace Space Generator
This module provides comprehensive validation of the space template
to ensure it contains all required components and valid Python syntax.
Used during development and before deployment package generation.
"""
import ast
from typing import Dict, List, Any
def validate_template(template_string: str = None) -> bool:
"""
Comprehensive validation of the space template
Args:
template_string: The template to validate. If None, imports from space_template.
Returns:
bool: True if validation passes, raises ValueError if it fails
"""
# Import template if not provided
if template_string is None:
from space_template import SPACE_TEMPLATE
template_string = SPACE_TEMPLATE
# Required placeholders that must exist in the template
required_placeholders = [
'name', 'description', 'system_prompt', 'temperature', 'max_tokens',
'model', 'api_key_var', 'theme', 'grounding_urls', 'enable_dynamic_urls',
'enable_file_upload', 'examples', 'language'
]
validation_results = {
'placeholder_check': {'passed': True, 'missing': [], 'errors': []},
'syntax_check': {'passed': True, 'errors': []},
'structure_check': {'passed': True, 'errors': []},
'import_check': {'passed': True, 'errors': []},
'class_check': {'passed': True, 'errors': []},
'function_check': {'passed': True, 'errors': []}
}
# 1. Check for required placeholders
print("π Checking placeholders...")
missing = []
for placeholder in required_placeholders:
if f'{{{placeholder}}}' not in template_string:
missing.append(placeholder)
if missing:
validation_results['placeholder_check']['passed'] = False
validation_results['placeholder_check']['missing'] = missing
validation_results['placeholder_check']['errors'].append(
f"Missing required placeholders: {', '.join(missing)}"
)
else:
print("β
All required placeholders found")
# 2. Validate Python syntax with sample values
print("π Checking Python syntax...")
sample_values = {
'name': repr("Test Space"),
'description': repr("Test Description"),
'system_prompt': repr("You are a helpful assistant."),
'temperature': '0.7',
'max_tokens': '2000',
'model': repr("openai/gpt-4o-mini"),
'api_key_var': repr("API_KEY"),
'theme': repr("Default"),
'grounding_urls': '[]',
'enable_dynamic_urls': 'False',
'enable_file_upload': 'False',
'examples': '[]',
'language': repr("English")
}
# Create test template with sample values
test_template = template_string
for key, value in sample_values.items():
test_template = test_template.replace(f'{{{key}}}', value)
try:
# Parse the template as Python code
ast.parse(test_template)
print("β
Python syntax is valid")
except SyntaxError as e:
validation_results['syntax_check']['passed'] = False
validation_results['syntax_check']['errors'].append(
f"Syntax error at line {e.lineno}: {e.msg}"
)
print(f"β Syntax error: {e}")
# 3. Check for required imports
print("π Checking required imports...")
required_imports = [
'import gradio as gr',
'import requests',
'import json',
'from datetime import datetime'
]
for imp in required_imports:
if imp not in template_string:
validation_results['import_check']['passed'] = False
validation_results['import_check']['errors'].append(f"Missing import: {imp}")
if validation_results['import_check']['passed']:
print("β
All required imports present")
# 4. Check for required classes
print("π Checking required classes...")
required_classes = ['ConfigurationManager'] # Only ConfigurationManager is a class in the template
for cls in required_classes:
if f'class {cls}' not in template_string:
validation_results['class_check']['passed'] = False
validation_results['class_check']['errors'].append(f"Missing class: {cls}")
if validation_results['class_check']['passed']:
print("β
All required classes found")
# 5. Check for required functions
print("π Checking required functions...")
required_functions = [
'def respond', # Main chat response function
'def process_file_upload',
'def fetch_url_content',
'def export_conversation',
'def create_interface'
]
for func in required_functions:
if func not in template_string:
validation_results['function_check']['passed'] = False
validation_results['function_check']['errors'].append(
f"Missing function: {func.replace('def ', '')}"
)
if validation_results['function_check']['passed']:
print("β
All required functions found")
# 6. Structure validation
print("π Checking template structure...")
# Check for proper configuration section
if 'DEFAULT_CONFIG = {' not in template_string:
validation_results['structure_check']['passed'] = False
validation_results['structure_check']['errors'].append("Missing DEFAULT_CONFIG dictionary")
# Check for Gradio app launch
if 'demo.launch()' not in template_string and 'app.launch()' not in template_string:
validation_results['structure_check']['passed'] = False
validation_results['structure_check']['errors'].append("Missing Gradio app launch")
# Check for main execution block (with double quotes in template)
if 'if __name__ == "__main__":' not in template_string:
validation_results['structure_check']['passed'] = False
validation_results['structure_check']['errors'].append("Missing main execution block")
if validation_results['structure_check']['passed']:
print("β
Template structure is valid")
# Generate summary
all_passed = all(check['passed'] for check in validation_results.values())
if all_passed:
print("\nβ
Template validation PASSED - All checks successful!")
return True
else:
print("\nβ Template validation FAILED:")
for check_name, result in validation_results.items():
if not result['passed']:
print(f"\n {check_name.replace('_', ' ').title()}:")
for error in result['errors']:
print(f" - {error}")
if result.get('missing'):
print(f" Missing items: {', '.join(result['missing'])}")
raise ValueError("Template validation failed. See details above.")
return all_passed
def validate_silently(template_string: str = None) -> tuple[bool, Dict[str, Any]]:
"""
Silent validation that returns results without printing
Args:
template_string: The template to validate. If None, imports from space_template.
Returns:
tuple: (success: bool, results: dict with validation details)
"""
# Import template if not provided
if template_string is None:
from space_template import SPACE_TEMPLATE
template_string = SPACE_TEMPLATE
# Required placeholders that must exist in the template
required_placeholders = [
'name', 'description', 'system_prompt', 'temperature', 'max_tokens',
'model', 'api_key_var', 'theme', 'grounding_urls', 'enable_dynamic_urls',
'enable_file_upload', 'examples', 'language'
]
validation_results = {
'placeholder_check': {'passed': True, 'missing': [], 'errors': []},
'syntax_check': {'passed': True, 'errors': []},
'structure_check': {'passed': True, 'errors': []},
'import_check': {'passed': True, 'errors': []},
'class_check': {'passed': True, 'errors': []},
'function_check': {'passed': True, 'errors': []}
}
# 1. Check for required placeholders
missing = []
for placeholder in required_placeholders:
if f'{{{placeholder}}}' not in template_string:
missing.append(placeholder)
if missing:
validation_results['placeholder_check']['passed'] = False
validation_results['placeholder_check']['missing'] = missing
validation_results['placeholder_check']['errors'].append(
f"Missing required placeholders: {', '.join(missing)}"
)
# 2. Validate Python syntax with sample values
sample_values = {
'name': repr("Test Space"),
'description': repr("Test Description"),
'system_prompt': repr("You are a helpful assistant."),
'temperature': '0.7',
'max_tokens': '2000',
'model': repr("openai/gpt-4o-mini"),
'api_key_var': repr("API_KEY"),
'theme': repr("Default"),
'grounding_urls': '[]',
'enable_dynamic_urls': 'False',
'enable_file_upload': 'False',
'examples': '[]',
'language': repr("English")
}
# Create test template with sample values
test_template = template_string
for key, value in sample_values.items():
test_template = test_template.replace(f'{{{key}}}', value)
try:
# Parse the template as Python code
ast.parse(test_template)
except SyntaxError as e:
validation_results['syntax_check']['passed'] = False
validation_results['syntax_check']['errors'].append(
f"Syntax error at line {e.lineno}: {e.msg}"
)
# 3. Check for required imports
required_imports = [
'import gradio as gr',
'import requests',
'import json',
'from datetime import datetime'
]
for imp in required_imports:
if imp not in template_string:
validation_results['import_check']['passed'] = False
validation_results['import_check']['errors'].append(f"Missing import: {imp}")
# 4. Check for required classes
required_classes = ['ConfigurationManager']
for cls in required_classes:
if f'class {cls}' not in template_string:
validation_results['class_check']['passed'] = False
validation_results['class_check']['errors'].append(f"Missing class: {cls}")
# 5. Check for required functions
required_functions = [
'def respond',
'def process_file_upload',
'def fetch_url_content',
'def export_conversation',
'def create_interface'
]
for func in required_functions:
if func not in template_string:
validation_results['function_check']['passed'] = False
validation_results['function_check']['errors'].append(
f"Missing function: {func.replace('def ', '')}"
)
# 6. Structure validation
if 'DEFAULT_CONFIG = {' not in template_string:
validation_results['structure_check']['passed'] = False
validation_results['structure_check']['errors'].append("Missing DEFAULT_CONFIG dictionary")
if 'demo.launch()' not in template_string and 'app.launch()' not in template_string:
validation_results['structure_check']['passed'] = False
validation_results['structure_check']['errors'].append("Missing Gradio app launch")
if 'if __name__ == "__main__":' not in template_string:
validation_results['structure_check']['passed'] = False
validation_results['structure_check']['errors'].append("Missing main execution block")
# Generate summary
all_passed = all(check['passed'] for check in validation_results.values())
return all_passed, validation_results
if __name__ == "__main__":
# Run validation when module is executed directly
validate_template() |