acecalisto3 commited on
Commit
e0f3044
·
verified ·
1 Parent(s): 00f9a60

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -458
app.py CHANGED
@@ -14,6 +14,12 @@ import asyncio
14
  logging.basicConfig(level=logging.INFO)
15
  logger = logging.getLogger(__name__)
16
 
 
 
 
 
 
 
17
  @dataclass
18
  class Config:
19
  """Configuration class for the agent system"""
@@ -166,6 +172,7 @@ class UIComponentLibrary:
166
  border: 1px solid {self.design_system.get_color('secondary')};
167
  '''
168
  }
 
169
  class WebDesignValidator:
170
  def __init__(self):
171
  self.accessibility_rules = {
@@ -318,470 +325,25 @@ class WebDesignValidator:
318
  def _calculate_overall_status(self, results: Dict[str, Any]) -> str:
319
  # Implementation of overall status calculation
320
  failed_count = sum(len(category.get('failed', [])) for category in results.values())
321
- warning_count = sum(len(category.get('warnings', [])) for category in results.values())
322
-
323
- if failed_count == 0 and warning_count == 0:
324
- return 'PASSED'
325
- elif failed_count == 0:
326
- return 'PASSED_WITH_WARNINGS'
327
- else:
328
- return 'FAILED'
329
 
330
  def _generate_recommendations(self, results: Dict[str, Any]) -> List[str]:
331
  recommendations = []
332
  for category, result in results.items():
333
- if 'failed' in result:
334
- for failure in result['failed']:
335
- recommendations.append(f"Fix {category}: {failure}")
336
- if 'warnings' in result:
337
- for warning in result['warnings']:
338
- recommendations.append(f"Consider improving {category}: {warning}")
339
  return recommendations
340
 
341
- class AgentRole(Enum):
342
- ARCHITECT = auto()
343
- FRONTEND = auto()
344
- BACKEND = auto()
345
- DATABASE = auto()
346
- TESTER = auto()
347
- REVIEWER = auto()
348
- DEPLOYER = auto()
349
- DESIGNER = auto()
350
-
351
- @dataclass
352
- class AgentDecision:
353
- agent: 'Agent'
354
- decision: str
355
- confidence: float
356
- reasoning: str
357
- timestamp: datetime = field(default_factory=datetime.now)
358
- dependencies: List['AgentDecision'] = field(default_factory=list)
359
- design_implications: Dict[str, Any] = field(default_factory=dict)
360
-
361
- class Agent:
362
- def __init__(self, role: AgentRole, design_system: DesignSystem, ui_library: UIComponentLibrary):
363
- self.role = role
364
- self.design_system = design_system
365
- self.ui_library = ui_library
366
- self.decisions: List[AgentDecision] = []
367
- self.current_task: Optional[Dict[str, Any]] = None
368
- self.autonomy_level: float = 5.0 # Scale of 0-10
369
- self.validator = WebDesignValidator()
370
-
371
- async def process_task(self, task: Dict[str, Any]) -> Dict[str, Any]:
372
- self.current_task = task
373
-
374
- try:
375
- if self.role == AgentRole.DESIGNER:
376
- return await self._process_design_task(task)
377
- elif self.role == AgentRole.FRONTEND:
378
- return await self._process_frontend_task(task)
379
- elif self.role == AgentRole.BACKEND:
380
- return await self._process_backend_task(task)
381
- else:
382
- return await self._process_generic_task(task)
383
- except Exception as e:
384
- logger.error(f"Error processing task in {self.role}: {str(e)}")
385
- return {'status': 'error', 'message': str(e)}
386
-
387
- async def _process_design_task(self, task: Dict[str, Any]) -> Dict[str, Any]:
388
- design_requirements = task.get('design_requirements', {})
389
-
390
- # Create design specifications
391
- design_specs = {
392
- 'layout': await self._create_layout_specs(design_requirements),
393
- 'components': await self._create_component_specs(design_requirements),
394
- 'styling': await self._create_styling_specs(design_requirements),
395
- 'interactions': await self._create_interaction_specs(design_requirements)
396
- }
397
-
398
- # Validate design specifications
399
- validation_results = await self.validator.validate_design_principles({
400
- 'specs': design_specs,
401
- 'requirements': design_requirements
402
- })
403
-
404
- if validation_results['overall_status'] == 'FAILED':
405
- return {
406
- 'status': 'revision_needed',
407
- 'specs': design_specs,
408
- 'validation': validation_results,
409
- 'recommendations': validation_results['recommendations']
410
- }
411
-
412
- return {
413
- 'status': 'success',
414
- 'specs': design_specs,
415
- 'validation': validation_results
416
- }
417
-
418
- async def _create_layout_specs(self, requirements: Dict[str, Any]) -> Dict[str, Any]:
419
- return {
420
- 'grid_system': {
421
- 'type': 'flexbox',
422
- 'columns': 12,
423
- 'breakpoints': self.design_system.theme['breakpoints']
424
- },
425
- 'layout_type': requirements.get('layout_type', 'responsive'),
426
- 'containers': {
427
- 'max_width': '1200px',
428
- 'padding': self.design_system.get_spacing('md')
429
- }
430
- }
431
-
432
- async def _create_component_specs(self, requirements: Dict[str, Any]) -> Dict[str, Any]:
433
- components = {}
434
- for component_type in requirements.get('components', []):
435
- template = self.ui_library.get_component_template(component_type)
436
- if template:
437
- components[component_type] = {
438
- 'template': template['template'],
439
- 'styles': template['styles'],
440
- 'variants': self._generate_component_variants(component_type)
441
- }
442
- return components
443
-
444
- async def _process_frontend_task(self, task: Dict[str, Any]) -> Dict[str, Any]:
445
- design_specs = task.get('design_specs', {})
446
-
447
- implementation = {
448
- 'components': await self._implement_components(design_specs),
449
- 'styles': await self._implement_styles(design_specs),
450
- 'layouts': await self._implement_layouts(design_specs)
451
- }
452
-
453
- # Validate frontend implementation
454
- validation_results = await self.validator.validate_design_principles(implementation)
455
-
456
- return {
457
- 'status': 'success',
458
- 'implementation': implementation,
459
- 'validation': validation_results
460
- }
461
-
462
- async def _implement_components(self, design_specs: Dict[str, Any]) -> List[Dict[str, Any]]:
463
- implemented_components = []
464
- for component_name, specs in design_specs.get('components', {}).items():
465
- implemented_components.append({
466
- 'name': component_name,
467
- 'implementation': self.ui_library.get_component_template(component_name),
468
- 'styles': specs.get('styles', {}),
469
- 'variants': specs.get('variants', [])
470
- })
471
- return implemented_components
472
-
473
- class AgentSystem:
474
- def __init__(self, config: Config):
475
- self.config = config
476
- self.design_system = DesignSystem()
477
- self.ui_library = UIComponentLibrary(self.design_system)
478
- self.validator = WebDesignValidator()
479
- self.agents = self._initialize_agents()
480
- self.executor = ThreadPoolExecutor(max_workers=config.max_workers)
481
- self.current_project: Optional[Dict[str, Any]] = None
482
-
483
- def _initialize_agents(self) -> Dict[AgentRole, Agent]:
484
- return {
485
- role: Agent(role, self.design_system, self.ui_library)
486
- for role in AgentRole
487
- }
488
-
489
- async def process_request(self, description: str, context: Dict[str, Any]) -> Dict[str, Any]:
490
- try:
491
- self.current_project = {
492
- 'description': description,
493
- 'context': context,
494
- 'status': 'initializing',
495
- 'timestamp': datetime.now()
496
- }
497
-
498
- # Design Phase
499
- design_result = await self._process_design_phase(context)
500
- if design_result['status'] != 'success':
501
- return design_result
502
-
503
- # Implementation Phase
504
- implementation_result = await self._process_implementation_phase(design_result['specs'])
505
- if implementation_result['status'] != 'success':
506
- return implementation_result
507
-
508
- # Validation Phase
509
- validation_result = await self._process_validation_phase(implementation_result['implementation'])
510
-
511
- return {
512
- 'status': 'success',
513
- 'design': design_result,
514
- 'implementation': implementation_result,
515
- 'validation': validation_result
516
- }
517
-
518
- except Exception as e:
519
- logger.error(f"Error processing request: {str(e)}")
520
- return {'status': 'error', 'message': str(e)}
521
-
522
- async def _process_design_phase(self, context: Dict[str, Any]) -> Dict[str, Any]:
523
- design_agent = self.agents[AgentRole.DESIGNER]
524
- return await design_agent.process_task({
525
- 'type': 'design',
526
- 'requirements': context.get('design_requirements', {}),
527
- 'constraints': context.get('constraints', {})
528
- })
529
-
530
- async def _process_implementation_phase(self, design_specs: Dict[str, Any]) -> Dict[str, Any]:
531
- frontend_result = await self.agents[AgentRole.FRONTEND].process_task({
532
- 'type': 'implementation',
533
- 'design_specs': design_specs
534
- })
535
-
536
- backend_result = await self.agents[AgentRole.BACKEND].process_task({
537
- 'type': 'implementation',
538
- 'design_specs': design_specs
539
- })
540
-
541
- return {
542
- 'status': 'success',
543
- 'frontend': frontend_result,
544
- 'backend': backend_result
545
- }
546
-
547
- async def _process_validation_phase(self, implementation: Dict[str, Any]) -> Dict[str, Any]:
548
- return await self.validator.validate_design_principles(implementation)
549
-
550
- async def set_autonomy_level(self, level: float) -> None:
551
- if not 0 <= level <= 10:
552
- raise ValueError("Autonomy level must be between 0 and 10")
553
- for agent in self.agents.values():
554
- agent.autonomy_level = level
555
-
556
- # Main execution and utility functions
557
- async def create_gradio_interface(agent_system: AgentSystem):
558
- """Create the Gradio interface for the web design system"""
559
-
560
- def process_design_request(description: str, requirements: str) -> Dict[str, Any]:
561
- try:
562
- context = json.loads(requirements) if requirements else {}
563
- result = asyncio.run(agent_system.process_request(description, context))
564
- return json.dumps(result, indent=2)
565
- except Exception as e:
566
- return f"Error: {str(e)}"
567
-
568
- interface = gr.Interface(
569
- fn=process_design_request,
570
- inputs=[
571
- gr.Textbox(label="Project Description", lines=3),
572
- gr.Textbox(label="Design Requirements (JSON)", lines=5)
573
- ],
574
- outputs=gr.JSON(label="Results"),
575
- title="Web Design Agent System",
576
- description="Enter your project details and design requirements to generate web design specifications and implementation."
577
- )
578
-
579
- return interface
580
-
581
- class TestSuite:
582
- """Test suite for the web design system"""
583
-
584
- def __init__(self, agent_system: AgentSystem):
585
- self.agent_system = agent_system
586
- self.test_cases = self._initialize_test_cases()
587
-
588
- def _initialize_test_cases(self) -> List[Dict[str, Any]]:
589
- return [
590
- {
591
- 'name': 'basic_website',
592
- 'description': 'Create a basic website with homepage and contact form',
593
- 'context': {
594
- 'design_requirements': {
595
- 'theme': 'light',
596
- 'components': ['header', 'footer', 'contact_form'],
597
- 'responsive': True
598
- }
599
- }
600
- },
601
- {
602
- 'name': 'e_commerce',
603
- 'description': 'Create an e-commerce product page',
604
- 'context': {
605
- 'design_requirements': {
606
- 'theme': 'modern',
607
- 'components': ['product_card', 'shopping_cart', 'checkout_form'],
608
- 'responsive': True
609
- }
610
- }
611
- }
612
- ]
613
-
614
- async def run_tests(self) -> Dict[str, Any]:
615
- results = {
616
- 'passed': [],
617
- 'failed': [],
618
- 'total_tests': len(self.test_cases),
619
- 'timestamp': datetime.now()
620
- }
621
-
622
- for test_case in self.test_cases:
623
- try:
624
- result = await self.agent_system.process_request(
625
- test_case['description'],
626
- test_case['context']
627
- )
628
-
629
- if result['status'] == 'success':
630
- results['passed'].append({
631
- 'test_name': test_case['name'],
632
- 'result': result
633
- })
634
- else:
635
- results['failed'].append({
636
- 'test_name': test_case['name'],
637
- 'error': result
638
- })
639
-
640
- except Exception as e:
641
- results['failed'].append({
642
- 'test_name': test_case['name'],
643
- 'error': str(e)
644
- })
645
-
646
- return results
647
-
648
- class ProjectManager:
649
- """Manages web design projects and their lifecycle"""
650
-
651
- def __init__(self, agent_system: AgentSystem):
652
- self.agent_system = agent_system
653
- self.projects: Dict[str, Dict[str, Any]] = {}
654
- self.active_project_id: Optional[str] = None
655
-
656
- async def create_project(self, name: str, description: str, requirements: Dict[str, Any]) -> str:
657
- project_id = f"proj_{len(self.projects) + 1}"
658
- self.projects[project_id] = {
659
- 'name': name,
660
- 'description': description,
661
- 'requirements': requirements,
662
- 'status': 'created',
663
- 'created_at': datetime.now(),
664
- 'history': []
665
- }
666
- return project_id
667
-
668
- async def process_project(self, project_id: str) -> Dict[str, Any]:
669
- if project_id not in self.projects:
670
- raise ValueError(f"Project {project_id} not found")
671
-
672
- project = self.projects[project_id]
673
- self.active_project_id = project_id
674
-
675
- try:
676
- result = await self.agent_system.process_request(
677
- project['description'],
678
- {'design_requirements': project['requirements']}
679
- )
680
-
681
- project['status'] = result['status']
682
- project['history'].append({
683
- 'timestamp': datetime.now(),
684
- 'action': 'process',
685
- 'result': result
686
- })
687
-
688
- return result
689
-
690
- except Exception as e:
691
- project['status'] = 'error'
692
- project['history'].append({
693
- 'timestamp': datetime.now(),
694
- 'action': 'process',
695
- 'error': str(e)
696
- })
697
- raise
698
-
699
- def main():
700
- """Main entry point for the application"""
701
-
702
- # Initialize configuration
703
- config = Config(
704
- rag_system_path="/path/to/rag",
705
- max_workers=10,
706
- log_level="INFO",
707
- model_settings={
708
- 'temperature': 0.7,
709
- 'max_tokens': 1000
710
- },
711
- api_keys={},
712
- design_system_config={
713
- 'theme': 'light',
714
- 'responsive': True,
715
- 'accessibility_level': 'AAA'
716
- }
717
- )
718
-
719
- # Initialize agent system
720
- agent_system = AgentSystem(config)
721
-
722
- # Initialize project manager
723
- project_manager = ProjectManager(agent_system)
724
-
725
- # Initialize test suite
726
- test_suite = TestSuite(agent_system)
727
-
728
- # Create and launch Gradio interface
729
- interface = asyncio.run(create_gradio_interface(agent_system))
730
- interface.launch(share=True)
731
-
732
  if __name__ == "__main__":
733
- # Run tests before starting the application
734
- config = Config(rag_system_path="/path/to/rag")
735
- agent_system = AgentSystem(config)
736
- test_suite = TestSuite(agent_system)
737
-
738
- # Run tests
739
- test_results = asyncio.run(test_suite.run_tests())
740
- print("Test Results:", json.dumps(test_results, indent=2))
741
-
742
- # Start the application
743
- main()
744
-
745
- # Pytest functions for testing
746
- def test_agent_system():
747
- config = Config(rag_system_path="/path/to/rag")
748
- agent_system = AgentSystem(config)
749
-
750
- # Test design system initialization
751
- assert agent_system.design_system is not None
752
- assert agent_system.ui_library is not None
753
-
754
- # Test agent initialization
755
- assert len(agent_system.agents) == len(AgentRole)
756
-
757
- # Test validator initialization
758
- assert agent_system.validator is not None
759
-
760
- def test_design_validation():
761
- config = Config(rag_system_path="/path/to/rag")
762
- agent_system = AgentSystem(config)
763
-
764
- implementation = {
765
- 'components': [
766
- {
767
- 'name': 'button',
768
- 'foreground_color': '#FFFFFF',
769
- 'background_color': '#007BFF'
770
- }
771
- ]
772
  }
773
-
774
- validation_result = asyncio.run(agent_system.validator.validate_design_principles(implementation))
775
- assert validation_result is not None
776
- assert 'validation_results' in validation_result
777
- assert 'overall_status' in validation_result
778
 
779
- def test_ui_component_library():
780
- design_system = DesignSystem()
781
- ui_library = UIComponentLibrary(design_system)
782
-
783
- # Test component template retrieval
784
- button_template = ui_library.get_component_template('button')
785
- assert button_template is not None
786
- assert 'template' in button_template
787
- assert 'styles' in button_template
 
14
  logging.basicConfig(level=logging.INFO)
15
  logger = logging.getLogger(__name__)
16
 
17
+ class CustomJSONEncoder(json.JSONEncoder):
18
+ def default(self, obj):
19
+ if isinstance(obj, datetime):
20
+ return obj.isoformat()
21
+ return super().default(obj)
22
+
23
  @dataclass
24
  class Config:
25
  """Configuration class for the agent system"""
 
172
  border: 1px solid {self.design_system.get_color('secondary')};
173
  '''
174
  }
175
+
176
  class WebDesignValidator:
177
  def __init__(self):
178
  self.accessibility_rules = {
 
325
  def _calculate_overall_status(self, results: Dict[str, Any]) -> str:
326
  # Implementation of overall status calculation
327
  failed_count = sum(len(category.get('failed', [])) for category in results.values())
328
+ if failed_count > 0:
329
+ return 'fail'
330
+ return 'pass'
 
 
 
 
 
331
 
332
  def _generate_recommendations(self, results: Dict[str, Any]) -> List[str]:
333
  recommendations = []
334
  for category, result in results.items():
335
+ if 'recommendations' in result:
336
+ recommendations.extend(result['recommendations'])
 
 
 
 
337
  return recommendations
338
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
  if __name__ == "__main__":
340
+ # Example data to test JSON serialization
341
+ test_results = {
342
+ "timestamp": datetime.now(),
343
+ "status": "success"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
344
  }
 
 
 
 
 
345
 
346
+ try:
347
+ print("Test Results:", json.dumps(test_results, indent=2, cls=CustomJSONEncoder))
348
+ except Exception as e:
349
+ logger.error(f"Error serializing test results: {e}")