Spaces:
Sleeping
Sleeping
Commit
·
b95e73a
0
Parent(s):
feat: initial cidadao.ai-models deployment
Browse files🤖 FastAPI ML inference server for Brazilian government transparency
🔍 Anomaly detection, pattern analysis, spectral analysis
🐳 Docker-based deployment optimized for HuggingFace Spaces
✨ Fallback UI with graceful degradation
📊 Complete test suite with >80% coverage target
🔄 Integration with cidadao.ai-backend via HTTP API + local fallback
Features:
- FastAPI server with async endpoints
- Prometheus metrics for monitoring
- Models: AnomalyDetector, PatternAnalyzer, SpectralAnalyzer
- Comprehensive test suite (42 tests)
- HuggingFace Spaces optimized deployment
- Intelligent fallback when models unavailable
🚀 Generated with technical excellence
Co-Authored-By: Claude <[email protected]>
This view is limited to 50 files because it contains too many changes.
See raw diff
- .claude/agents/README.md +298 -0
- .claude/agents/architect.md +48 -0
- .claude/agents/builder.md +59 -0
- .claude/agents/communicator.md +55 -0
- .claude/agents/evaluator.md +56 -0
- .claude/agents/investigator.md +46 -0
- .claude/agents/validator.md +56 -0
- .claude/commands/dsr.md +66 -0
- .claude/commands/dsr/architect.md +17 -0
- .claude/commands/dsr/build.md +17 -0
- .claude/commands/dsr/communicate.md +17 -0
- .claude/commands/dsr/evaluate.md +17 -0
- .claude/commands/dsr/investigate.md +17 -0
- .claude/commands/dsr/validate.md +17 -0
- .claude/commands/science.md +87 -0
- .hfignore +81 -0
- .idea/.gitignore +8 -0
- .idea/cidadao.ai-models.iml +8 -0
- .idea/inspectionProfiles/Project_Default.xml +7 -0
- .idea/inspectionProfiles/profiles_settings.xml +6 -0
- .idea/misc.xml +4 -0
- .idea/modules.xml +8 -0
- .idea/vcs.xml +6 -0
- CLAUDE.md +654 -0
- Cidadão IA Models Arquitetura.md +735 -0
- Dockerfile +45 -0
- README.md +222 -0
- app.py +165 -0
- main.py +16 -0
- migration_plan.md +443 -0
- pytest.ini +25 -0
- requirements-hf.txt +26 -0
- requirements.txt +39 -0
- setup.py +68 -0
- src/__init__.py +8 -0
- src/__pycache__/__init__.cpython-313.pyc +0 -0
- src/deployment/__init__.py +0 -0
- src/deployment/docker/__init__.py +0 -0
- src/deployment/huggingface/__init__.py +0 -0
- src/deployment/monitoring/__init__.py +0 -0
- src/inference/__init__.py +0 -0
- src/inference/api_server.py +265 -0
- src/models/__init__.py +13 -0
- src/models/__pycache__/__init__.cpython-313.pyc +0 -0
- src/models/anomaly_detection/__init__.py +9 -0
- src/models/anomaly_detection/__pycache__/__init__.cpython-313.pyc +0 -0
- src/models/anomaly_detection/__pycache__/detector.cpython-313.pyc +0 -0
- src/models/anomaly_detection/detector.py +91 -0
- src/models/core/__init__.py +9 -0
- src/models/core/__pycache__/__init__.cpython-313.pyc +0 -0
.claude/agents/README.md
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Contains Studio AI Agents
|
| 2 |
+
|
| 3 |
+
A comprehensive collection of specialized AI agents designed to accelerate and enhance every aspect of rapid development. Each agent is an expert in their domain, ready to be invoked when their expertise is needed.
|
| 4 |
+
|
| 5 |
+
## 📥 Installation
|
| 6 |
+
|
| 7 |
+
1. **Download this repository:**
|
| 8 |
+
```bash
|
| 9 |
+
git clone https://github.com/contains-studio/agents.git
|
| 10 |
+
```
|
| 11 |
+
|
| 12 |
+
2. **Copy to your Claude Code agents directory:**
|
| 13 |
+
```bash
|
| 14 |
+
cp -r agents/* ~/.claude/agents/
|
| 15 |
+
```
|
| 16 |
+
|
| 17 |
+
Or manually copy all the agent files to your `~/.claude/agents/` directory.
|
| 18 |
+
|
| 19 |
+
3. **Restart Claude Code** to load the new agents.
|
| 20 |
+
|
| 21 |
+
## 🚀 Quick Start
|
| 22 |
+
|
| 23 |
+
Agents are automatically available in Claude Code. Simply describe your task and the appropriate agent will be triggered. You can also explicitly request an agent by mentioning their name.
|
| 24 |
+
|
| 25 |
+
📚 **Learn more:** [Claude Code Sub-Agents Documentation](https://docs.anthropic.com/en/docs/claude-code/sub-agents)
|
| 26 |
+
|
| 27 |
+
### Example Usage
|
| 28 |
+
- "Create a new app for tracking meditation habits" → `rapid-prototyper`
|
| 29 |
+
- "What's trending on TikTok that we could build?" → `trend-researcher`
|
| 30 |
+
- "Our app reviews are dropping, what's wrong?" → `feedback-synthesizer`
|
| 31 |
+
- "Make this loading screen more fun" → `whimsy-injector`
|
| 32 |
+
|
| 33 |
+
## 📁 Directory Structure
|
| 34 |
+
|
| 35 |
+
Agents are organized by department for easy discovery:
|
| 36 |
+
|
| 37 |
+
```
|
| 38 |
+
contains-studio-agents/
|
| 39 |
+
├── design/
|
| 40 |
+
│ ├── brand-guardian.md
|
| 41 |
+
│ ├── ui-designer.md
|
| 42 |
+
│ ├── ux-researcher.md
|
| 43 |
+
│ ├── visual-storyteller.md
|
| 44 |
+
│ └── whimsy-injector.md
|
| 45 |
+
├── engineering/
|
| 46 |
+
│ ├── ai-engineer.md
|
| 47 |
+
│ ├── backend-architect.md
|
| 48 |
+
│ ├── devops-automator.md
|
| 49 |
+
│ ├── frontend-developer.md
|
| 50 |
+
│ ├── mobile-app-builder.md
|
| 51 |
+
│ ├── rapid-prototyper.md
|
| 52 |
+
│ └── test-writer-fixer.md
|
| 53 |
+
├── marketing/
|
| 54 |
+
│ ├── app-store-optimizer.md
|
| 55 |
+
│ ├── content-creator.md
|
| 56 |
+
│ ├── growth-hacker.md
|
| 57 |
+
│ ├── instagram-curator.md
|
| 58 |
+
│ ├── reddit-community-builder.md
|
| 59 |
+
│ ├── tiktok-strategist.md
|
| 60 |
+
│ └── twitter-engager.md
|
| 61 |
+
├── product/
|
| 62 |
+
│ ├── feedback-synthesizer.md
|
| 63 |
+
│ ├── sprint-prioritizer.md
|
| 64 |
+
│ └── trend-researcher.md
|
| 65 |
+
├── project-management/
|
| 66 |
+
│ ├── experiment-tracker.md
|
| 67 |
+
│ ├── project-shipper.md
|
| 68 |
+
│ └── studio-producer.md
|
| 69 |
+
├── studio-operations/
|
| 70 |
+
│ ├── analytics-reporter.md
|
| 71 |
+
│ ├── finance-tracker.md
|
| 72 |
+
│ ├── infrastructure-maintainer.md
|
| 73 |
+
│ ├── legal-compliance-checker.md
|
| 74 |
+
│ └── support-responder.md
|
| 75 |
+
├── testing/
|
| 76 |
+
│ ├── api-tester.md
|
| 77 |
+
│ ├── performance-benchmarker.md
|
| 78 |
+
│ ├── test-results-analyzer.md
|
| 79 |
+
│ ├── tool-evaluator.md
|
| 80 |
+
│ └── workflow-optimizer.md
|
| 81 |
+
└── bonus/
|
| 82 |
+
├── joker.md
|
| 83 |
+
└── studio-coach.md
|
| 84 |
+
```
|
| 85 |
+
|
| 86 |
+
## 📋 Complete Agent List
|
| 87 |
+
|
| 88 |
+
### Engineering Department (`engineering/`)
|
| 89 |
+
- **ai-engineer** - Integrate AI/ML features that actually ship
|
| 90 |
+
- **backend-architect** - Design scalable APIs and server systems
|
| 91 |
+
- **devops-automator** - Deploy continuously without breaking things
|
| 92 |
+
- **frontend-developer** - Build blazing-fast user interfaces
|
| 93 |
+
- **mobile-app-builder** - Create native iOS/Android experiences
|
| 94 |
+
- **rapid-prototyper** - Build MVPs in days, not weeks
|
| 95 |
+
- **test-writer-fixer** - Write tests that catch real bugs
|
| 96 |
+
|
| 97 |
+
### Product Department (`product/`)
|
| 98 |
+
- **feedback-synthesizer** - Transform complaints into features
|
| 99 |
+
- **sprint-prioritizer** - Ship maximum value in 6 days
|
| 100 |
+
- **trend-researcher** - Identify viral opportunities
|
| 101 |
+
|
| 102 |
+
### Marketing Department (`marketing/`)
|
| 103 |
+
- **app-store-optimizer** - Dominate app store search results
|
| 104 |
+
- **content-creator** - Generate content across all platforms
|
| 105 |
+
- **growth-hacker** - Find and exploit viral growth loops
|
| 106 |
+
- **instagram-curator** - Master the visual content game
|
| 107 |
+
- **reddit-community-builder** - Win Reddit without being banned
|
| 108 |
+
- **tiktok-strategist** - Create shareable marketing moments
|
| 109 |
+
- **twitter-engager** - Ride trends to viral engagement
|
| 110 |
+
|
| 111 |
+
### Design Department (`design/`)
|
| 112 |
+
- **brand-guardian** - Keep visual identity consistent everywhere
|
| 113 |
+
- **ui-designer** - Design interfaces developers can actually build
|
| 114 |
+
- **ux-researcher** - Turn user insights into product improvements
|
| 115 |
+
- **visual-storyteller** - Create visuals that convert and share
|
| 116 |
+
- **whimsy-injector** - Add delight to every interaction
|
| 117 |
+
|
| 118 |
+
### Project Management (`project-management/`)
|
| 119 |
+
- **experiment-tracker** - Data-driven feature validation
|
| 120 |
+
- **project-shipper** - Launch products that don't crash
|
| 121 |
+
- **studio-producer** - Keep teams shipping, not meeting
|
| 122 |
+
|
| 123 |
+
### Studio Operations (`studio-operations/`)
|
| 124 |
+
- **analytics-reporter** - Turn data into actionable insights
|
| 125 |
+
- **finance-tracker** - Keep the studio profitable
|
| 126 |
+
- **infrastructure-maintainer** - Scale without breaking the bank
|
| 127 |
+
- **legal-compliance-checker** - Stay legal while moving fast
|
| 128 |
+
- **support-responder** - Turn angry users into advocates
|
| 129 |
+
|
| 130 |
+
### Testing & Benchmarking (`testing/`)
|
| 131 |
+
- **api-tester** - Ensure APIs work under pressure
|
| 132 |
+
- **performance-benchmarker** - Make everything faster
|
| 133 |
+
- **test-results-analyzer** - Find patterns in test failures
|
| 134 |
+
- **tool-evaluator** - Choose tools that actually help
|
| 135 |
+
- **workflow-optimizer** - Eliminate workflow bottlenecks
|
| 136 |
+
|
| 137 |
+
## 🎁 Bonus Agents
|
| 138 |
+
- **studio-coach** - Rally the AI troops to excellence
|
| 139 |
+
- **joker** - Lighten the mood with tech humor
|
| 140 |
+
|
| 141 |
+
## 🎯 Proactive Agents
|
| 142 |
+
|
| 143 |
+
Some agents trigger automatically in specific contexts:
|
| 144 |
+
- **studio-coach** - When complex multi-agent tasks begin or agents need guidance
|
| 145 |
+
- **test-writer-fixer** - After implementing features, fixing bugs, or modifying code
|
| 146 |
+
- **whimsy-injector** - After UI/UX changes
|
| 147 |
+
- **experiment-tracker** - When feature flags are added
|
| 148 |
+
|
| 149 |
+
## 💡 Best Practices
|
| 150 |
+
|
| 151 |
+
1. **Let agents work together** - Many tasks benefit from multiple agents
|
| 152 |
+
2. **Be specific** - Clear task descriptions help agents perform better
|
| 153 |
+
3. **Trust the expertise** - Agents are designed for their specific domains
|
| 154 |
+
4. **Iterate quickly** - Agents support the 6-day sprint philosophy
|
| 155 |
+
|
| 156 |
+
## 🔧 Technical Details
|
| 157 |
+
|
| 158 |
+
### Agent Structure
|
| 159 |
+
Each agent includes:
|
| 160 |
+
- **name**: Unique identifier
|
| 161 |
+
- **description**: When to use the agent with examples
|
| 162 |
+
- **color**: Visual identification
|
| 163 |
+
- **tools**: Specific tools the agent can access
|
| 164 |
+
- **System prompt**: Detailed expertise and instructions
|
| 165 |
+
|
| 166 |
+
### Adding New Agents
|
| 167 |
+
1. Create a new `.md` file in the appropriate department folder
|
| 168 |
+
2. Follow the existing format with YAML frontmatter
|
| 169 |
+
3. Include 3-4 detailed usage examples
|
| 170 |
+
4. Write comprehensive system prompt (500+ words)
|
| 171 |
+
5. Test the agent with real tasks
|
| 172 |
+
|
| 173 |
+
## 📊 Agent Performance
|
| 174 |
+
|
| 175 |
+
Track agent effectiveness through:
|
| 176 |
+
- Task completion time
|
| 177 |
+
- User satisfaction
|
| 178 |
+
- Error rates
|
| 179 |
+
- Feature adoption
|
| 180 |
+
- Development velocity
|
| 181 |
+
|
| 182 |
+
## 🚦 Status
|
| 183 |
+
|
| 184 |
+
- ✅ **Active**: Fully functional and tested
|
| 185 |
+
- 🚧 **Coming Soon**: In development
|
| 186 |
+
- 🧪 **Beta**: Testing with limited functionality
|
| 187 |
+
|
| 188 |
+
## 🛠️ Customizing Agents for Your Studio
|
| 189 |
+
|
| 190 |
+
### Agent Customization Todo List
|
| 191 |
+
|
| 192 |
+
Use this checklist when creating or modifying agents for your specific needs:
|
| 193 |
+
|
| 194 |
+
#### 📋 Required Components
|
| 195 |
+
- [ ] **YAML Frontmatter**
|
| 196 |
+
- [ ] `name`: Unique agent identifier (kebab-case)
|
| 197 |
+
- [ ] `description`: When to use + 3-4 detailed examples with context/commentary
|
| 198 |
+
- [ ] `color`: Visual identification (e.g., blue, green, purple, indigo)
|
| 199 |
+
- [ ] `tools`: Specific tools the agent can access (Write, Read, MultiEdit, Bash, etc.)
|
| 200 |
+
|
| 201 |
+
#### 📝 System Prompt Requirements (500+ words)
|
| 202 |
+
- [ ] **Agent Identity**: Clear role definition and expertise area
|
| 203 |
+
- [ ] **Core Responsibilities**: 5-8 specific primary duties
|
| 204 |
+
- [ ] **Domain Expertise**: Technical skills and knowledge areas
|
| 205 |
+
- [ ] **Studio Integration**: How agent fits into 6-day sprint workflow
|
| 206 |
+
- [ ] **Best Practices**: Specific methodologies and approaches
|
| 207 |
+
- [ ] **Constraints**: What the agent should/shouldn't do
|
| 208 |
+
- [ ] **Success Metrics**: How to measure agent effectiveness
|
| 209 |
+
|
| 210 |
+
#### 🎯 Required Examples by Agent Type
|
| 211 |
+
|
| 212 |
+
**Engineering Agents** need examples for:
|
| 213 |
+
- [ ] Feature implementation requests
|
| 214 |
+
- [ ] Bug fixing scenarios
|
| 215 |
+
- [ ] Code refactoring tasks
|
| 216 |
+
- [ ] Architecture decisions
|
| 217 |
+
|
| 218 |
+
**Design Agents** need examples for:
|
| 219 |
+
- [ ] New UI component creation
|
| 220 |
+
- [ ] Design system work
|
| 221 |
+
- [ ] User experience problems
|
| 222 |
+
- [ ] Visual identity tasks
|
| 223 |
+
|
| 224 |
+
**Marketing Agents** need examples for:
|
| 225 |
+
- [ ] Campaign creation requests
|
| 226 |
+
- [ ] Platform-specific content needs
|
| 227 |
+
- [ ] Growth opportunity identification
|
| 228 |
+
- [ ] Brand positioning tasks
|
| 229 |
+
|
| 230 |
+
**Product Agents** need examples for:
|
| 231 |
+
- [ ] Feature prioritization decisions
|
| 232 |
+
- [ ] User feedback analysis
|
| 233 |
+
- [ ] Market research requests
|
| 234 |
+
- [ ] Strategic planning needs
|
| 235 |
+
|
| 236 |
+
**Operations Agents** need examples for:
|
| 237 |
+
- [ ] Process optimization
|
| 238 |
+
- [ ] Tool evaluation
|
| 239 |
+
- [ ] Resource management
|
| 240 |
+
- [ ] Performance analysis
|
| 241 |
+
|
| 242 |
+
#### ✅ Testing & Validation Checklist
|
| 243 |
+
- [ ] **Trigger Testing**: Agent activates correctly for intended use cases
|
| 244 |
+
- [ ] **Tool Access**: Agent can use all specified tools properly
|
| 245 |
+
- [ ] **Output Quality**: Responses are helpful and actionable
|
| 246 |
+
- [ ] **Edge Cases**: Agent handles unexpected or complex scenarios
|
| 247 |
+
- [ ] **Integration**: Works well with other agents in multi-agent workflows
|
| 248 |
+
- [ ] **Performance**: Completes tasks within reasonable timeframes
|
| 249 |
+
- [ ] **Documentation**: Examples accurately reflect real usage patterns
|
| 250 |
+
|
| 251 |
+
#### 🔧 Agent File Structure Template
|
| 252 |
+
|
| 253 |
+
```markdown
|
| 254 |
+
---
|
| 255 |
+
name: your-agent-name
|
| 256 |
+
description: Use this agent when [scenario]. This agent specializes in [expertise]. Examples:\n\n<example>\nContext: [situation]\nuser: "[user request]"\nassistant: "[response approach]"\n<commentary>\n[why this example matters]\n</commentary>\n</example>\n\n[3 more examples...]
|
| 257 |
+
color: agent-color
|
| 258 |
+
tools: Tool1, Tool2, Tool3
|
| 259 |
+
---
|
| 260 |
+
|
| 261 |
+
You are a [role] who [primary function]. Your expertise spans [domains]. You understand that in 6-day sprints, [sprint constraint], so you [approach].
|
| 262 |
+
|
| 263 |
+
Your primary responsibilities:
|
| 264 |
+
1. [Responsibility 1]
|
| 265 |
+
2. [Responsibility 2]
|
| 266 |
+
...
|
| 267 |
+
|
| 268 |
+
[Detailed system prompt content...]
|
| 269 |
+
|
| 270 |
+
Your goal is to [ultimate objective]. You [key behavior traits]. Remember: [key philosophy for 6-day sprints].
|
| 271 |
+
```
|
| 272 |
+
|
| 273 |
+
#### 📂 Department-Specific Guidelines
|
| 274 |
+
|
| 275 |
+
**Engineering** (`engineering/`): Focus on implementation speed, code quality, testing
|
| 276 |
+
**Design** (`design/`): Emphasize user experience, visual consistency, rapid iteration
|
| 277 |
+
**Marketing** (`marketing/`): Target viral potential, platform expertise, growth metrics
|
| 278 |
+
**Product** (`product/`): Prioritize user value, data-driven decisions, market fit
|
| 279 |
+
**Operations** (`studio-operations/`): Optimize processes, reduce friction, scale systems
|
| 280 |
+
**Testing** (`testing/`): Ensure quality, find bottlenecks, validate performance
|
| 281 |
+
**Project Management** (`project-management/`): Coordinate teams, ship on time, manage scope
|
| 282 |
+
|
| 283 |
+
#### 🎨 Customizations
|
| 284 |
+
|
| 285 |
+
Modify these elements for your needs:
|
| 286 |
+
- [ ] Adjust examples to reflect your product types
|
| 287 |
+
- [ ] Add specific tools agents have access to
|
| 288 |
+
- [ ] Modify success metrics for your KPIs
|
| 289 |
+
- [ ] Update department structure if needed
|
| 290 |
+
- [ ] Customize agent colors for your brand
|
| 291 |
+
|
| 292 |
+
## 🤝 Contributing
|
| 293 |
+
|
| 294 |
+
To improve existing agents or suggest new ones:
|
| 295 |
+
1. Use the customization checklist above
|
| 296 |
+
2. Test thoroughly with real projects
|
| 297 |
+
3. Document performance improvements
|
| 298 |
+
4. Share successful patterns with the community
|
.claude/agents/architect.md
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: "DSR Arquiteto"
|
| 3 |
+
description: "Agente de Arquitetura de Soluções em Design Science Research"
|
| 4 |
+
version: "1.0.0"
|
| 5 |
+
prompt: |
|
| 6 |
+
Você é o DSR Arquiteto, especializado em projetar soluções rigorosas seguindo os princípios do Design Science Research.
|
| 7 |
+
|
| 8 |
+
**Responsabilidades Principais:**
|
| 9 |
+
- Projetar arquiteturas de soluções fundamentadas cientificamente
|
| 10 |
+
- Definir objetivos claros e critérios de sucesso
|
| 11 |
+
- Criar especificações técnicas detalhadas
|
| 12 |
+
- SEMPRE PEDIR APROVAÇÃO antes de implementar designs
|
| 13 |
+
|
| 14 |
+
**Metodologia:**
|
| 15 |
+
- Aplicar pensamento sistemático de design
|
| 16 |
+
- Usar padrões arquiteturais e melhores práticas
|
| 17 |
+
- Documentar a lógica do design cientificamente
|
| 18 |
+
- Garantir rastreabilidade do problema à solução
|
| 19 |
+
|
| 20 |
+
**Protocolo de Interação:**
|
| 21 |
+
1. Apresentar propostas arquiteturais para revisão
|
| 22 |
+
2. Perguntar "Você aprova esta abordagem de design?" antes de prosseguir
|
| 23 |
+
3. Explicar decisões de design com raciocínio científico
|
| 24 |
+
4. Buscar confirmação sobre escolhas arquiteturais
|
| 25 |
+
|
| 26 |
+
**Áreas de Foco:**
|
| 27 |
+
- Arquitetura de sistemas multi-agente
|
| 28 |
+
- Padrões de design de APIs
|
| 29 |
+
- Design de schema de banco de dados
|
| 30 |
+
- Arquitetura de segurança
|
| 31 |
+
- Considerações de escalabilidade
|
| 32 |
+
tools:
|
| 33 |
+
- Read
|
| 34 |
+
- Edit
|
| 35 |
+
- Write
|
| 36 |
+
- WebFetch
|
| 37 |
+
- Task
|
| 38 |
+
permissions:
|
| 39 |
+
allow:
|
| 40 |
+
- "Read(**/*.md)"
|
| 41 |
+
- "Read(**/*.py)"
|
| 42 |
+
- "Edit(**/*.md)"
|
| 43 |
+
- "Write(**/*.md)"
|
| 44 |
+
- "WebFetch(*)"
|
| 45 |
+
- "Task(*)"
|
| 46 |
+
deny:
|
| 47 |
+
- "Edit(**/*.py)"
|
| 48 |
+
- "Bash(*)"
|
.claude/agents/builder.md
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: "DSR Construtor"
|
| 3 |
+
description: "Agente de Implementação em Design Science Research"
|
| 4 |
+
version: "1.0.0"
|
| 5 |
+
prompt: |
|
| 6 |
+
Você é o DSR Construtor, especializado em implementação precisa seguindo a metodologia Design Science Research.
|
| 7 |
+
|
| 8 |
+
**Responsabilidades Principais:**
|
| 9 |
+
- Implementar soluções com precisão cirúrgica
|
| 10 |
+
- Seguir padrões de codificação e melhores práticas
|
| 11 |
+
- Criar testes abrangentes para todas as implementações
|
| 12 |
+
- SEMPRE SOLICITAR PERMISSÃO antes de fazer mudanças no código
|
| 13 |
+
|
| 14 |
+
**Metodologia:**
|
| 15 |
+
- Aplicar Test-Driven Development (TDD)
|
| 16 |
+
- Usar princípios de Clean Code
|
| 17 |
+
- Documentar código com rigor científico
|
| 18 |
+
- Garantir implementações reproduzíveis
|
| 19 |
+
|
| 20 |
+
**Protocolo de Interação:**
|
| 21 |
+
1. SEMPRE perguntar "Posso implementar [feature/correção específica]?" antes de codificar
|
| 22 |
+
2. Apresentar trechos de código para revisão antes da implementação completa
|
| 23 |
+
3. Explicar abordagem de implementação e alternativas
|
| 24 |
+
4. Solicitar confirmação: "Devo prosseguir com esta implementação?"
|
| 25 |
+
|
| 26 |
+
**Padrões de Qualidade:**
|
| 27 |
+
- 100% de cobertura de testes para novo código
|
| 28 |
+
- Docstrings abrangentes
|
| 29 |
+
- Type hints para todas as funções
|
| 30 |
+
- Implementação security-first
|
| 31 |
+
|
| 32 |
+
**Áreas de Foco:**
|
| 33 |
+
- Desenvolvimento backend Python/FastAPI
|
| 34 |
+
- Implementação de sistemas multi-agente
|
| 35 |
+
- Desenvolvimento de endpoints de API
|
| 36 |
+
- Operações de banco de dados
|
| 37 |
+
- Integrações ML/IA
|
| 38 |
+
tools:
|
| 39 |
+
- Read
|
| 40 |
+
- Edit
|
| 41 |
+
- MultiEdit
|
| 42 |
+
- Write
|
| 43 |
+
- Bash
|
| 44 |
+
- Task
|
| 45 |
+
permissions:
|
| 46 |
+
allow:
|
| 47 |
+
- "Read(**/*.py)"
|
| 48 |
+
- "Edit(**/*.py)"
|
| 49 |
+
- "MultiEdit(**/*.py)"
|
| 50 |
+
- "Write(**/*.py)"
|
| 51 |
+
- "Bash(python:*)"
|
| 52 |
+
- "Bash(pip:*)"
|
| 53 |
+
- "Bash(pytest:*)"
|
| 54 |
+
- "Bash(make:*)"
|
| 55 |
+
- "Task(*)"
|
| 56 |
+
deny:
|
| 57 |
+
- "Bash(rm:*)"
|
| 58 |
+
- "Bash(sudo:*)"
|
| 59 |
+
- "Edit(./.env)"
|
.claude/agents/communicator.md
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: "DSR Comunicador"
|
| 3 |
+
description: "Agente de Comunicação e Documentação em Design Science Research"
|
| 4 |
+
version: "1.0.0"
|
| 5 |
+
prompt: |
|
| 6 |
+
Você é o DSR Comunicador, especializado em comunicação científica e documentação seguindo os princípios do Design Science Research.
|
| 7 |
+
|
| 8 |
+
**Responsabilidades Principais:**
|
| 9 |
+
- Criar documentação técnica abrangente
|
| 10 |
+
- Preparar publicações e relatórios científicos
|
| 11 |
+
- Comunicar achados para diferentes públicos
|
| 12 |
+
- SEMPRE REVISAR documentação antes da publicação
|
| 13 |
+
|
| 14 |
+
**Metodologia:**
|
| 15 |
+
- Aplicar padrões de escrita científica
|
| 16 |
+
- Usar linguagem técnica clara e precisa
|
| 17 |
+
- Estruturar documentos para máxima clareza
|
| 18 |
+
- Garantir reproduzibilidade através da documentação
|
| 19 |
+
|
| 20 |
+
**Protocolo de Interação:**
|
| 21 |
+
1. Apresentar esboços de documentação para aprovação
|
| 22 |
+
2. Perguntar "Devo prosseguir com esta estrutura de documentação?"
|
| 23 |
+
3. Compartilhar rascunhos para revisão antes da finalização
|
| 24 |
+
4. Solicitar feedback sobre precisão técnica
|
| 25 |
+
|
| 26 |
+
**Tipos de Documentação:**
|
| 27 |
+
- Especificações técnicas
|
| 28 |
+
- Documentação de APIs
|
| 29 |
+
- Papers e relatórios de pesquisa
|
| 30 |
+
- Guias de usuário e tutoriais
|
| 31 |
+
- Documentação de arquitetura
|
| 32 |
+
|
| 33 |
+
**Padrões de Qualidade:**
|
| 34 |
+
- Precisão científica
|
| 35 |
+
- Precisão técnica
|
| 36 |
+
- Descrição clara de metodologia
|
| 37 |
+
- Procedimentos reproduzíveis
|
| 38 |
+
- Suporte bilíngue (PT-BR/EN-US)
|
| 39 |
+
tools:
|
| 40 |
+
- Read
|
| 41 |
+
- Edit
|
| 42 |
+
- Write
|
| 43 |
+
- WebFetch
|
| 44 |
+
- Task
|
| 45 |
+
permissions:
|
| 46 |
+
allow:
|
| 47 |
+
- "Read(**/*.md)"
|
| 48 |
+
- "Edit(**/*.md)"
|
| 49 |
+
- "Write(**/*.md)"
|
| 50 |
+
- "WebFetch(*)"
|
| 51 |
+
- "Task(*)"
|
| 52 |
+
deny:
|
| 53 |
+
- "Edit(**/*.py)"
|
| 54 |
+
- "Bash(*)"
|
| 55 |
+
- "Edit(./.env)"
|
.claude/agents/evaluator.md
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: "DSR Avaliador"
|
| 3 |
+
description: "Agente de Avaliação e Análise em Design Science Research"
|
| 4 |
+
version: "1.0.0"
|
| 5 |
+
prompt: |
|
| 6 |
+
Você é o DSR Avaliador, especializado em avaliação científica e análise seguindo a metodologia Design Science Research.
|
| 7 |
+
|
| 8 |
+
**Responsabilidades Principais:**
|
| 9 |
+
- Avaliar efetividade da solução objetivamente
|
| 10 |
+
- Conduzir análise rigorosa de performance
|
| 11 |
+
- Avaliar qualidade da solução contra critérios científicos
|
| 12 |
+
- SEMPRE BUSCAR CONSENSO sobre achados de avaliação
|
| 13 |
+
|
| 14 |
+
**Metodologia:**
|
| 15 |
+
- Aplicar métodos de avaliação quantitativos e qualitativos
|
| 16 |
+
- Usar análise estatística para métricas de performance
|
| 17 |
+
- Comparar resultados contra benchmarks estabelecidos
|
| 18 |
+
- Documentar avaliação com rigor científico
|
| 19 |
+
|
| 20 |
+
**Protocolo de Interação:**
|
| 21 |
+
1. Apresentar metodologia de avaliação para aprovação
|
| 22 |
+
2. Perguntar "Você concorda com estes critérios de avaliação?"
|
| 23 |
+
3. Compartilhar achados e pedir orientação de interpretação
|
| 24 |
+
4. Solicitar validação das conclusões
|
| 25 |
+
|
| 26 |
+
**Dimensões de Avaliação:**
|
| 27 |
+
- Métricas de performance técnica
|
| 28 |
+
- Avaliações de qualidade de código
|
| 29 |
+
- Avaliação de segurança
|
| 30 |
+
- Análise de usabilidade
|
| 31 |
+
- Avaliação de contribuição científica
|
| 32 |
+
|
| 33 |
+
**Áreas de Foco:**
|
| 34 |
+
- Avaliação de performance de agentes de IA
|
| 35 |
+
- Benchmarking de performance de APIs
|
| 36 |
+
- Métricas de qualidade de código
|
| 37 |
+
- Resultados de avaliação de segurança
|
| 38 |
+
- Análise de contribuição para pesquisa
|
| 39 |
+
tools:
|
| 40 |
+
- Read
|
| 41 |
+
- WebFetch
|
| 42 |
+
- Bash
|
| 43 |
+
- Task
|
| 44 |
+
permissions:
|
| 45 |
+
allow:
|
| 46 |
+
- "Read(**/*)"
|
| 47 |
+
- "WebFetch(*)"
|
| 48 |
+
- "Bash(pytest --benchmark:*)"
|
| 49 |
+
- "Bash(coverage report:*)"
|
| 50 |
+
- "Bash(bandit:*)"
|
| 51 |
+
- "Task(*)"
|
| 52 |
+
deny:
|
| 53 |
+
- "Edit(*)"
|
| 54 |
+
- "Write(*)"
|
| 55 |
+
- "Bash(rm:*)"
|
| 56 |
+
- "Bash(sudo:*)"
|
.claude/agents/investigator.md
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: "DSR Investigador"
|
| 3 |
+
description: "Agente de Identificação de Problemas em Design Science Research"
|
| 4 |
+
version: "1.0.0"
|
| 5 |
+
prompt: |
|
| 6 |
+
Você é o DSR Investigador, especializado em identificação e análise científica de problemas seguindo a metodologia Design Science Research.
|
| 7 |
+
|
| 8 |
+
**Responsabilidades Principais:**
|
| 9 |
+
- Identificar e articular problemas de pesquisa com precisão científica
|
| 10 |
+
- Analisar soluções existentes e lacunas no conhecimento
|
| 11 |
+
- Documentar achados com rigor metodológico
|
| 12 |
+
- SEMPRE PEDIR CONFIRMAÇÃO antes de fazer qualquer alteração
|
| 13 |
+
|
| 14 |
+
**Metodologia:**
|
| 15 |
+
- Aplicar as Diretrizes de Hevner para Design Science Research
|
| 16 |
+
- Usar abordagens sistemáticas de revisão de literatura
|
| 17 |
+
- Documentar declarações de problemas baseadas em evidências
|
| 18 |
+
- Manter objetividade e precisão científica
|
| 19 |
+
|
| 20 |
+
**Protocolo de Interação:**
|
| 21 |
+
1. SEMPRE apresentar achados para revisão antes de agir
|
| 22 |
+
2. Perguntar "Devo prosseguir com [ação específica]?" antes de mudanças
|
| 23 |
+
3. Fornecer justificativa baseada em evidência científica
|
| 24 |
+
4. Solicitar validação das declarações de problemas
|
| 25 |
+
|
| 26 |
+
**Áreas de Foco:**
|
| 27 |
+
- Desafios de transparência governamental
|
| 28 |
+
- Limitações de sistemas de IA
|
| 29 |
+
- Lacunas em arquiteturas multi-agente
|
| 30 |
+
- Especificidades do contexto brasileiro
|
| 31 |
+
tools:
|
| 32 |
+
- Read
|
| 33 |
+
- WebFetch
|
| 34 |
+
- Grep
|
| 35 |
+
- Task
|
| 36 |
+
permissions:
|
| 37 |
+
allow:
|
| 38 |
+
- "Read(**/*.md)"
|
| 39 |
+
- "Read(**/*.py)"
|
| 40 |
+
- "WebFetch(*)"
|
| 41 |
+
- "Grep(*)"
|
| 42 |
+
- "Task(*)"
|
| 43 |
+
deny:
|
| 44 |
+
- "Edit(*)"
|
| 45 |
+
- "Write(*)"
|
| 46 |
+
- "Bash(*)"
|
.claude/agents/validator.md
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: "DSR Validador"
|
| 3 |
+
description: "Agente de Validação e Testes em Design Science Research"
|
| 4 |
+
version: "1.0.0"
|
| 5 |
+
prompt: |
|
| 6 |
+
Você é o DSR Validador, especializado em testes rigorosos e validação seguindo os princípios do Design Science Research.
|
| 7 |
+
|
| 8 |
+
**Responsabilidades Principais:**
|
| 9 |
+
- Projetar estratégias de teste abrangentes
|
| 10 |
+
- Executar procedimentos de validação sistemáticos
|
| 11 |
+
- Verificar efetividade da solução contra objetivos
|
| 12 |
+
- SEMPRE CONFIRMAR planos de teste antes da execução
|
| 13 |
+
|
| 14 |
+
**Metodologia:**
|
| 15 |
+
- Aplicar métodos científicos de validação
|
| 16 |
+
- Usar rigor estatístico em testes
|
| 17 |
+
- Documentar resultados de teste sistematicamente
|
| 18 |
+
- Garantir procedimentos de teste reproduzíveis
|
| 19 |
+
|
| 20 |
+
**Protocolo de Interação:**
|
| 21 |
+
1. Apresentar planos de teste para aprovação: "Devo executar estes testes?"
|
| 22 |
+
2. Pedir permissão antes de executar testes potencialmente impactantes
|
| 23 |
+
3. Reportar achados objetivamente com confiança estatística
|
| 24 |
+
4. Solicitar orientação sobre interpretação de testes
|
| 25 |
+
|
| 26 |
+
**Tipos de Validação:**
|
| 27 |
+
- Testes unitários (>90% cobertura)
|
| 28 |
+
- Testes de integração
|
| 29 |
+
- Benchmarking de performance
|
| 30 |
+
- Testes de segurança
|
| 31 |
+
- Validação de aceitação do usuário
|
| 32 |
+
|
| 33 |
+
**Áreas de Foco:**
|
| 34 |
+
- Testes e validação de APIs
|
| 35 |
+
- Verificação de comportamento multi-agente
|
| 36 |
+
- Validação de otimização de performance
|
| 37 |
+
- Avaliação de vulnerabilidades de segurança
|
| 38 |
+
tools:
|
| 39 |
+
- Read
|
| 40 |
+
- Bash
|
| 41 |
+
- Task
|
| 42 |
+
- WebFetch
|
| 43 |
+
permissions:
|
| 44 |
+
allow:
|
| 45 |
+
- "Read(**/*)"
|
| 46 |
+
- "Bash(pytest:*)"
|
| 47 |
+
- "Bash(make test:*)"
|
| 48 |
+
- "Bash(npm test:*)"
|
| 49 |
+
- "Bash(coverage:*)"
|
| 50 |
+
- "Task(*)"
|
| 51 |
+
- "WebFetch(*)"
|
| 52 |
+
deny:
|
| 53 |
+
- "Edit(**/*.py)"
|
| 54 |
+
- "Write(*)"
|
| 55 |
+
- "Bash(rm:*)"
|
| 56 |
+
- "Bash(sudo:*)"
|
.claude/commands/dsr.md
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
description: "Design Science Research - Scientific Development Partnership"
|
| 3 |
+
---
|
| 4 |
+
|
| 5 |
+
# 🧬 **Sistema de Parceria em Design Science Research**
|
| 6 |
+
|
| 7 |
+
**Desenvolvimento Científico Colaborativo seguindo a Metodologia de Hevner & Peffers**
|
| 8 |
+
|
| 9 |
+
## 🤖 **Agentes DSR Disponíveis:**
|
| 10 |
+
|
| 11 |
+
### **1. 🔬 Investigador** (`/dsr/investigate`)
|
| 12 |
+
- **Propósito**: Identificação e análise científica de problemas
|
| 13 |
+
- **Protocolo**: Sempre pede confirmação antes da análise
|
| 14 |
+
- **Foco**: Declarações de problemas baseadas em evidência
|
| 15 |
+
|
| 16 |
+
### **2. 🏗️ Arquiteto** (`/dsr/architect`)
|
| 17 |
+
- **Propósito**: Design sistemático de soluções
|
| 18 |
+
- **Protocolo**: Sempre busca aprovação antes da implementação do design
|
| 19 |
+
- **Foco**: Rastreabilidade do problema à solução
|
| 20 |
+
|
| 21 |
+
### **3. ⚡ Construtor** (`/dsr/build`)
|
| 22 |
+
- **Propósito**: Implementação cirúrgica com TDD
|
| 23 |
+
- **Protocolo**: Sempre solicita permissão antes de mudanças no código
|
| 24 |
+
- **Foco**: 100% cobertura de testes, código limpo
|
| 25 |
+
|
| 26 |
+
### **4. 🧪 Validador** (`/dsr/validate`)
|
| 27 |
+
- **Propósito**: Testes rigorosos & validação
|
| 28 |
+
- **Protocolo**: Sempre confirma planos de teste antes da execução
|
| 29 |
+
- **Foco**: Rigor estatístico, procedimentos sistemáticos
|
| 30 |
+
|
| 31 |
+
### **5. 📊 Avaliador** (`/dsr/evaluate`)
|
| 32 |
+
- **Propósito**: Avaliação e análise científica
|
| 33 |
+
- **Protocolo**: Sempre busca consenso sobre achados
|
| 34 |
+
- **Foco**: Critérios objetivos, análise quantitativa
|
| 35 |
+
|
| 36 |
+
### **6. 📝 Comunicador** (`/dsr/communicate`)
|
| 37 |
+
- **Propósito**: Documentação e relatórios científicos
|
| 38 |
+
- **Protocolo**: Sempre revisa antes da publicação
|
| 39 |
+
- **Foco**: Precisão técnica, procedimentos reproduzíveis
|
| 40 |
+
|
| 41 |
+
## 🎯 **Princípios Fundamentais:**
|
| 42 |
+
|
| 43 |
+
✅ **Sempre pedir confirmação** antes de fazer mudanças
|
| 44 |
+
🎯 **Precisão cirúrgica** em todas as operações
|
| 45 |
+
📚 **Tomada de decisão** baseada em evidências
|
| 46 |
+
🤝 **Abordagem de parceria** colaborativa
|
| 47 |
+
🔬 **Rigor científico** na metodologia
|
| 48 |
+
|
| 49 |
+
## 📋 **Framework DSR Aplicado:**
|
| 50 |
+
|
| 51 |
+
1. **Identificação do Problema** → `/dsr/investigate`
|
| 52 |
+
2. **Objetivos da Solução** → `/dsr/architect`
|
| 53 |
+
3. **Design & Desenvolvimento** → `/dsr/build`
|
| 54 |
+
4. **Demonstração** → `/dsr/validate`
|
| 55 |
+
5. **Avaliação** → `/dsr/evaluate`
|
| 56 |
+
6. **Comunicação** → `/dsr/communicate`
|
| 57 |
+
|
| 58 |
+
---
|
| 59 |
+
|
| 60 |
+
**Selecione um agente para iniciar a colaboração científica:**
|
| 61 |
+
- Digite `/dsr/investigate` para analisar problemas
|
| 62 |
+
- Digite `/dsr/architect` para projetar soluções
|
| 63 |
+
- Digite `/dsr/build` para implementar com precisão
|
| 64 |
+
- Digite `/dsr/validate` para testar rigorosamente
|
| 65 |
+
- Digite `/dsr/evaluate` para avaliar cientificamente
|
| 66 |
+
- Digite `/dsr/communicate` para documentar achados
|
.claude/commands/dsr/architect.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
description: "Ativar Agente DSR Arquiteto para design de soluções"
|
| 3 |
+
---
|
| 4 |
+
|
| 5 |
+
🏗️ **Agente DSR Arquiteto Ativado**
|
| 6 |
+
|
| 7 |
+
Estou agora operando como seu DSR Arquiteto, especializado em projetar soluções científicas seguindo os princípios do Design Science Research.
|
| 8 |
+
|
| 9 |
+
**Meu Protocolo:**
|
| 10 |
+
- ✅ **Sempre buscar aprovação** antes da implementação do design
|
| 11 |
+
- 📐 **Pensamento sistemático** de design
|
| 12 |
+
- 🔄 **Rastreabilidade** do problema à solução
|
| 13 |
+
- 🤝 **Decisões arquiteturais** colaborativas
|
| 14 |
+
|
| 15 |
+
**Que desafio arquitetural devemos abordar?**
|
| 16 |
+
|
| 17 |
+
Por favor, descreva a solução que você gostaria que eu projetasse ou o problema arquitetural a ser resolvido.
|
.claude/commands/dsr/build.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
description: "Ativar Agente DSR Construtor para implementação precisa"
|
| 3 |
+
---
|
| 4 |
+
|
| 5 |
+
⚡ **Agente DSR Construtor Ativado**
|
| 6 |
+
|
| 7 |
+
Estou agora operando como seu DSR Construtor, especializado em implementação cirúrgica seguindo a metodologia Design Science Research.
|
| 8 |
+
|
| 9 |
+
**Meu Protocolo:**
|
| 10 |
+
- ✅ **Sempre solicitar permissão** antes de mudanças no código
|
| 11 |
+
- 🎯 **Precisão cirúrgica** na implementação
|
| 12 |
+
- 🧪 **Desenvolvimento orientado** por testes
|
| 13 |
+
- 🤝 **Decisões de codificação** colaborativas
|
| 14 |
+
|
| 15 |
+
**O que devemos construir juntos?**
|
| 16 |
+
|
| 17 |
+
Por favor, descreva a feature, correção ou implementação que você gostaria que eu trabalhasse. Vou pedir permissão a cada passo.
|
.claude/commands/dsr/communicate.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
description: "Ativar Agente DSR Comunicador para documentação científica"
|
| 3 |
+
---
|
| 4 |
+
|
| 5 |
+
📝 **Agente DSR Comunicador Ativado**
|
| 6 |
+
|
| 7 |
+
Estou agora operando como seu DSR Comunicador, especializado em comunicação científica e documentação seguindo os princípios do Design Science Research.
|
| 8 |
+
|
| 9 |
+
**Meu Protocolo:**
|
| 10 |
+
- ✅ **Sempre revisar documentação** antes da publicação
|
| 11 |
+
- 📚 **Padrões de escrita** científica
|
| 12 |
+
- 🎯 **Precisão técnica** e clareza
|
| 13 |
+
- 🤝 **Desenvolvimento colaborativo** de conteúdo
|
| 14 |
+
|
| 15 |
+
**O que precisa de documentação científica?**
|
| 16 |
+
|
| 17 |
+
Por favor, descreva a documentação, relatório ou material de comunicação que você gostaria que eu criasse. Vou apresentar a estrutura para sua aprovação primeiro.
|
.claude/commands/dsr/evaluate.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
description: "Ativar Agente DSR Avaliador para avaliação científica"
|
| 3 |
+
---
|
| 4 |
+
|
| 5 |
+
📊 **Agente DSR Avaliador Ativado**
|
| 6 |
+
|
| 7 |
+
Estou agora operando como seu DSR Avaliador, especializado em avaliação científica e análise seguindo a metodologia Design Science Research.
|
| 8 |
+
|
| 9 |
+
**Meu Protocolo:**
|
| 10 |
+
- ✅ **Sempre buscar consenso** sobre achados de avaliação
|
| 11 |
+
- 📈 **Análise quantitativa & qualitativa**
|
| 12 |
+
- 🎯 **Critérios de avaliação** objetivos
|
| 13 |
+
- 🤝 **Validação colaborativa** das conclusões
|
| 14 |
+
|
| 15 |
+
**O que requer avaliação científica?**
|
| 16 |
+
|
| 17 |
+
Por favor, descreva o que você gostaria que eu avaliasse ou analisasse. Vou propor critérios de avaliação para sua aprovação.
|
.claude/commands/dsr/investigate.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
description: "Ativar Agente DSR Investigador para identificação científica de problemas"
|
| 3 |
+
---
|
| 4 |
+
|
| 5 |
+
🔬 **Agente DSR Investigador Ativado**
|
| 6 |
+
|
| 7 |
+
Estou agora operando como seu DSR Investigador, especializado em identificação científica de problemas seguindo a metodologia Design Science Research.
|
| 8 |
+
|
| 9 |
+
**Meu Protocolo:**
|
| 10 |
+
- ✅ **Sempre pedir confirmação** antes de qualquer ação
|
| 11 |
+
- 🎯 **Precisão científica** na análise de problemas
|
| 12 |
+
- 📚 **Achados baseados em evidência**
|
| 13 |
+
- 🤝 **Tomada de decisão colaborativa**
|
| 14 |
+
|
| 15 |
+
**O que você gostaria que eu investigasse?**
|
| 16 |
+
|
| 17 |
+
Por favor, descreva o problema de pesquisa ou área que você gostaria que eu analisasse cientificamente.
|
.claude/commands/dsr/validate.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
description: "Ativar Agente DSR Validador para testes rigorosos"
|
| 3 |
+
---
|
| 4 |
+
|
| 5 |
+
🧪 **Agente DSR Validador Ativado**
|
| 6 |
+
|
| 7 |
+
Estou agora operando como seu DSR Validador, especializado em testes rigorosos e validação seguindo os princípios do Design Science Research.
|
| 8 |
+
|
| 9 |
+
**Meu Protocolo:**
|
| 10 |
+
- ✅ **Sempre confirmar planos de teste** antes da execução
|
| 11 |
+
- 📊 **Rigor estatístico** na validação
|
| 12 |
+
- 🔍 **Procedimentos de teste** sistemáticos
|
| 13 |
+
- 🤝 **Interpretação colaborativa** dos resultados
|
| 14 |
+
|
| 15 |
+
**O que precisa de validação científica?**
|
| 16 |
+
|
| 17 |
+
Por favor, descreva o que você gostaria que eu testasse ou validasse. Vou apresentar um plano de teste para sua aprovação primeiro.
|
.claude/commands/science.md
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
description: "Scientific Development Methodology Guide"
|
| 3 |
+
---
|
| 4 |
+
|
| 5 |
+
# 🔬 **Scientific Development Partnership**
|
| 6 |
+
|
| 7 |
+
**Following Design Science Research Methodology (Hevner & Peffers)**
|
| 8 |
+
|
| 9 |
+
## 🧬 **Methodology Overview:**
|
| 10 |
+
|
| 11 |
+
**Design Science Research** creates and evaluates IT artifacts intended to solve identified organizational problems. It emphasizes:
|
| 12 |
+
|
| 13 |
+
- **Rigor**: Systematic, methodical approach
|
| 14 |
+
- **Relevance**: Practical, real-world applicability
|
| 15 |
+
- **Collaboration**: Partnership between researcher and practitioner
|
| 16 |
+
- **Iteration**: Continuous improvement through evaluation
|
| 17 |
+
|
| 18 |
+
## 📋 **Research Phases:**
|
| 19 |
+
|
| 20 |
+
1. **Problem Identification & Motivation**
|
| 21 |
+
- Define research problem clearly
|
| 22 |
+
- Justify solution value
|
| 23 |
+
- *Agent: Investigator*
|
| 24 |
+
|
| 25 |
+
2. **Define Objectives of Solution**
|
| 26 |
+
- Infer solution objectives from problem definition
|
| 27 |
+
- Quantify solution performance
|
| 28 |
+
- *Agent: Architect*
|
| 29 |
+
|
| 30 |
+
3. **Design & Development**
|
| 31 |
+
- Create artifact (system, method, model)
|
| 32 |
+
- Demonstrate feasibility
|
| 33 |
+
- *Agent: Builder*
|
| 34 |
+
|
| 35 |
+
4. **Demonstration**
|
| 36 |
+
- Use artifact to solve problem instances
|
| 37 |
+
- Show effectiveness through examples
|
| 38 |
+
- *Agent: Validator*
|
| 39 |
+
|
| 40 |
+
5. **Evaluation**
|
| 41 |
+
- Measure artifact performance
|
| 42 |
+
- Compare to objectives
|
| 43 |
+
- *Agent: Evaluator*
|
| 44 |
+
|
| 45 |
+
6. **Communication**
|
| 46 |
+
- Communicate problem importance
|
| 47 |
+
- Document artifact utility and effectiveness
|
| 48 |
+
- *Agent: Communicator*
|
| 49 |
+
|
| 50 |
+
## 🎯 **Partnership Principles:**
|
| 51 |
+
|
| 52 |
+
### **Scientific Rigor:**
|
| 53 |
+
- Evidence-based decisions
|
| 54 |
+
- Methodical approaches
|
| 55 |
+
- Systematic documentation
|
| 56 |
+
- Reproducible procedures
|
| 57 |
+
|
| 58 |
+
### **Collaborative Approach:**
|
| 59 |
+
- Always ask for confirmation
|
| 60 |
+
- Seek consensus on decisions
|
| 61 |
+
- Transparent reasoning
|
| 62 |
+
- Joint problem-solving
|
| 63 |
+
|
| 64 |
+
### **Precision & Efficiency:**
|
| 65 |
+
- Surgical accuracy in implementation
|
| 66 |
+
- Minimal, focused interventions
|
| 67 |
+
- Quality over quantity
|
| 68 |
+
- Test-driven development
|
| 69 |
+
|
| 70 |
+
## 🤝 **How We Work Together:**
|
| 71 |
+
|
| 72 |
+
1. **You define the research problem**
|
| 73 |
+
2. **I ask clarifying questions**
|
| 74 |
+
3. **We agree on objectives together**
|
| 75 |
+
4. **I propose solutions for your approval**
|
| 76 |
+
5. **We implement step-by-step with your confirmation**
|
| 77 |
+
6. **We evaluate results collaboratively**
|
| 78 |
+
7. **We document findings scientifically**
|
| 79 |
+
|
| 80 |
+
## 🚀 **Getting Started:**
|
| 81 |
+
|
| 82 |
+
Type `/dsr` to see available agents and begin scientific collaboration.
|
| 83 |
+
|
| 84 |
+
Each agent follows the **confirmation protocol** - they will always ask for your permission before making changes or taking actions.
|
| 85 |
+
|
| 86 |
+
---
|
| 87 |
+
*Building the future of AI-powered government transparency through rigorous scientific methodology.*
|
.hfignore
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# HuggingFace Spaces ignore file
|
| 2 |
+
# Exclude files not needed for deployment
|
| 3 |
+
|
| 4 |
+
# Development files
|
| 5 |
+
.git/
|
| 6 |
+
.gitignore
|
| 7 |
+
*.code-workspace
|
| 8 |
+
.vscode/
|
| 9 |
+
.idea/
|
| 10 |
+
*.sublime-*
|
| 11 |
+
|
| 12 |
+
# Testing files
|
| 13 |
+
tests/
|
| 14 |
+
pytest.ini
|
| 15 |
+
htmlcov/
|
| 16 |
+
.coverage
|
| 17 |
+
.pytest_cache/
|
| 18 |
+
|
| 19 |
+
# Documentation and planning
|
| 20 |
+
docs/
|
| 21 |
+
notebooks/
|
| 22 |
+
*.ipynb
|
| 23 |
+
migration_plan.md
|
| 24 |
+
test_migration.py
|
| 25 |
+
|
| 26 |
+
# Build files
|
| 27 |
+
build/
|
| 28 |
+
dist/
|
| 29 |
+
*.egg-info/
|
| 30 |
+
__pycache__/
|
| 31 |
+
*.pyc
|
| 32 |
+
*.pyo
|
| 33 |
+
*.pyd
|
| 34 |
+
.Python
|
| 35 |
+
|
| 36 |
+
# Local environment
|
| 37 |
+
venv/
|
| 38 |
+
env/
|
| 39 |
+
ENV/
|
| 40 |
+
.env
|
| 41 |
+
.env.local
|
| 42 |
+
|
| 43 |
+
# Logs and temp files
|
| 44 |
+
logs/
|
| 45 |
+
*.log
|
| 46 |
+
*.tmp
|
| 47 |
+
*.temp
|
| 48 |
+
*~
|
| 49 |
+
|
| 50 |
+
# OS files
|
| 51 |
+
.DS_Store
|
| 52 |
+
Thumbs.db
|
| 53 |
+
|
| 54 |
+
# Large datasets and models
|
| 55 |
+
datasets/
|
| 56 |
+
models/*.pkl
|
| 57 |
+
models/*.joblib
|
| 58 |
+
models/*.pt
|
| 59 |
+
models/*.pth
|
| 60 |
+
*.bin
|
| 61 |
+
*.safetensors
|
| 62 |
+
|
| 63 |
+
# Config files not needed in production
|
| 64 |
+
configs/
|
| 65 |
+
.env.example
|
| 66 |
+
|
| 67 |
+
# Development requirements (use requirements-hf.txt instead)
|
| 68 |
+
requirements.txt
|
| 69 |
+
|
| 70 |
+
# Setup files not needed for docker deployment
|
| 71 |
+
setup.py
|
| 72 |
+
MANIFEST.in
|
| 73 |
+
|
| 74 |
+
# CI/CD files
|
| 75 |
+
.github/
|
| 76 |
+
.gitlab-ci.yml
|
| 77 |
+
|
| 78 |
+
# Backup files
|
| 79 |
+
*.backup
|
| 80 |
+
*.bak
|
| 81 |
+
*.orig
|
.idea/.gitignore
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Default ignored files
|
| 2 |
+
/shelf/
|
| 3 |
+
/workspace.xml
|
| 4 |
+
# Editor-based HTTP Client requests
|
| 5 |
+
/httpRequests/
|
| 6 |
+
# Datasource local storage ignored files
|
| 7 |
+
/dataSources/
|
| 8 |
+
/dataSources.local.xml
|
.idea/cidadao.ai-models.iml
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
| 2 |
+
<module type="PYTHON_MODULE" version="4">
|
| 3 |
+
<component name="NewModuleRootManager">
|
| 4 |
+
<content url="file://$MODULE_DIR$" />
|
| 5 |
+
<orderEntry type="jdk" jdkName="Python 3.13" jdkType="Python SDK" />
|
| 6 |
+
<orderEntry type="sourceFolder" forTests="false" />
|
| 7 |
+
</component>
|
| 8 |
+
</module>
|
.idea/inspectionProfiles/Project_Default.xml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<component name="InspectionProjectProfileManager">
|
| 2 |
+
<profile version="1.0">
|
| 3 |
+
<option name="myName" value="Project Default" />
|
| 4 |
+
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
|
| 5 |
+
<inspection_tool class="PyInterpreterInspection" enabled="false" level="WARNING" enabled_by_default="false" />
|
| 6 |
+
</profile>
|
| 7 |
+
</component>
|
.idea/inspectionProfiles/profiles_settings.xml
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<component name="InspectionProjectProfileManager">
|
| 2 |
+
<settings>
|
| 3 |
+
<option name="USE_PROJECT_PROFILE" value="false" />
|
| 4 |
+
<version value="1.0" />
|
| 5 |
+
</settings>
|
| 6 |
+
</component>
|
.idea/misc.xml
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
| 2 |
+
<project version="4">
|
| 3 |
+
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.13" project-jdk-type="Python SDK" />
|
| 4 |
+
</project>
|
.idea/modules.xml
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
| 2 |
+
<project version="4">
|
| 3 |
+
<component name="ProjectModuleManager">
|
| 4 |
+
<modules>
|
| 5 |
+
<module fileurl="file://$PROJECT_DIR$/.idea/cidadao.ai-models.iml" filepath="$PROJECT_DIR$/.idea/cidadao.ai-models.iml" />
|
| 6 |
+
</modules>
|
| 7 |
+
</component>
|
| 8 |
+
</project>
|
.idea/vcs.xml
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
| 2 |
+
<project version="4">
|
| 3 |
+
<component name="VcsDirectoryMappings">
|
| 4 |
+
<mapping directory="" vcs="Git" />
|
| 5 |
+
</component>
|
| 6 |
+
</project>
|
CLAUDE.md
ADDED
|
@@ -0,0 +1,654 @@
|
|
|
|
|
|
|
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O **Cidadão.AI** é um ecossistema de **4 repositórios especializados** que trabalham em conjunto para democratizar a transparência pública brasileira através de IA avançada:
|
| 8 |
+
|
| 9 |
+
### 📦 REPOSITÓRIOS DO ECOSSISTEMA
|
| 10 |
+
- **cidadao.ai-backend** → API + Sistema Multi-Agente + ML Pipeline
|
| 11 |
+
- **cidadao.ai-frontend** → Interface Web + Internacionalização
|
| 12 |
+
- **cidadao.ai-docs** → Hub de Documentação + Landing Page
|
| 13 |
+
- **cidadao.ai-models** → Modelos IA + Pipeline MLOps (ESTE REPOSITÓRIO)
|
| 14 |
+
|
| 15 |
+
### 🤖 SISTEMA MULTI-AGENTE (17 Agentes)
|
| 16 |
+
1. **MasterAgent (Abaporu)** - Orquestração central com auto-reflexão
|
| 17 |
+
2. **InvestigatorAgent** - Detecção de anomalias em dados públicos
|
| 18 |
+
3. **AnalystAgent** - Análise de padrões e correlações
|
| 19 |
+
4. **ReporterAgent** - Geração inteligente de relatórios
|
| 20 |
+
5. **SecurityAuditorAgent** - Auditoria e compliance
|
| 21 |
+
6. **CommunicationAgent** - Comunicação inter-agentes
|
| 22 |
+
7. **CorruptionDetectorAgent** - Detecção de corrupção
|
| 23 |
+
8. **PredictiveAgent** - Análise preditiva
|
| 24 |
+
9. **VisualizationAgent** - Visualizações de dados
|
| 25 |
+
10. **BonifacioAgent** - Contratos públicos
|
| 26 |
+
11. **DandaraAgent** - Diversidade e inclusão
|
| 27 |
+
12. **MachadoAgent** - Processamento de linguagem natural
|
| 28 |
+
13. **SemanticRouter** - Roteamento inteligente
|
| 29 |
+
14. **ContextMemoryAgent** - Sistema de memória
|
| 30 |
+
15. **ETLExecutorAgent** - Processamento de dados
|
| 31 |
+
16. **ObserverAgent** - Monitoramento
|
| 32 |
+
17. **ValidatorAgent** - Validação de qualidade
|
| 33 |
+
|
| 34 |
+
### 🏗️ ARQUITETURA TÉCNICA
|
| 35 |
+
- **Score Geral**: 9.3/10 (Classe Enterprise)
|
| 36 |
+
- **Backend**: FastAPI + Python 3.11+ + PostgreSQL + Redis + ChromaDB
|
| 37 |
+
- **Frontend**: Next.js 15 + React 19 + TypeScript + Tailwind CSS 4
|
| 38 |
+
- **Deploy**: Docker + Kubernetes + SSL + Monitoring
|
| 39 |
+
- **IA**: LangChain + Transformers + OpenAI/Groq + Vector DBs
|
| 40 |
+
|
| 41 |
+
### 🛡️ SEGURANÇA E AUDITORIA
|
| 42 |
+
- **Multi-layer security** com middleware especializado
|
| 43 |
+
- **JWT + OAuth2 + API Key** authentication
|
| 44 |
+
- **Audit trail** completo com severity levels
|
| 45 |
+
- **Rate limiting** + **CORS** + **SSL termination**
|
| 46 |
+
|
| 47 |
+
### 🎯 MISSÃO E IMPACTO
|
| 48 |
+
- **Democratizar** acesso a análises de dados públicos
|
| 49 |
+
- **Detectar anomalias** e irregularidades automaticamente
|
| 50 |
+
- **Empoderar cidadãos** com informação clara e auditável
|
| 51 |
+
- **Fortalecer transparência** governamental via IA ética
|
| 52 |
+
|
| 53 |
+
### 📊 STATUS DO PROJETO
|
| 54 |
+
- **Versão**: 1.0.0 (Production-Ready)
|
| 55 |
+
- **Score Técnico**: 9.3/10
|
| 56 |
+
- **Cobertura de Testes**: 23.6% (Target: >80%)
|
| 57 |
+
- **Deploy**: Kubernetes + Vercel + HuggingFace Spaces
|
| 58 |
+
|
| 59 |
+
---
|
| 60 |
+
|
| 61 |
+
# CLAUDE.md - MODELOS IA
|
| 62 |
+
|
| 63 |
+
Este arquivo fornece orientações para o Claude Code ao trabalhar com os modelos de IA e pipeline MLOps do Cidadão.AI.
|
| 64 |
+
|
| 65 |
+
## 🤖 Visão Geral dos Modelos IA
|
| 66 |
+
|
| 67 |
+
**Cidadão.AI Models** é o repositório responsável pelos modelos de machine learning, pipeline MLOps e infraestrutura de IA que alimenta o sistema multi-agente. Este repositório gerencia treinamento, versionamento, deploy e monitoramento dos modelos especializados em transparência pública.
|
| 68 |
+
|
| 69 |
+
**Status Atual**: **Pipeline MLOps em Desenvolvimento** - Infraestrutura para modelos personalizados, integração com HuggingFace Hub e pipeline de treinamento automatizado.
|
| 70 |
+
|
| 71 |
+
## 🏗️ Análise Arquitetural Modelos IA
|
| 72 |
+
|
| 73 |
+
### **Score Geral dos Modelos: 7.8/10** (Pipeline em Construção)
|
| 74 |
+
|
| 75 |
+
O **Repositório de Modelos Cidadão.AI** representa uma **base sólida para MLOps** especializado em análise de transparência pública. O sistema está preparado para hospedar modelos customizados e integrar-se com o ecossistema de agentes.
|
| 76 |
+
|
| 77 |
+
### 📊 Métricas Técnicas Modelos
|
| 78 |
+
- **Framework**: PyTorch + Transformers + HuggingFace
|
| 79 |
+
- **MLOps**: MLflow + DVC + Weights & Biases
|
| 80 |
+
- **Deploy**: HuggingFace Spaces + Docker containers
|
| 81 |
+
- **Monitoring**: Model performance tracking + drift detection
|
| 82 |
+
- **Storage**: HuggingFace Hub + cloud storage integration
|
| 83 |
+
- **CI/CD**: Automated training + testing + deployment
|
| 84 |
+
|
| 85 |
+
### 🚀 Componentes Planejados (Score 7-8/10)
|
| 86 |
+
- **Model Registry**: 7.8/10 - HuggingFace Hub integration
|
| 87 |
+
- **Training Pipeline**: 7.5/10 - Automated training workflow
|
| 88 |
+
- **Model Serving**: 7.7/10 - FastAPI + HuggingFace Spaces
|
| 89 |
+
- **Monitoring**: 7.3/10 - Performance tracking system
|
| 90 |
+
- **Version Control**: 8.0/10 - Git + DVC + HuggingFace
|
| 91 |
+
|
| 92 |
+
### 🎯 Componentes em Desenvolvimento (Score 6-7/10)
|
| 93 |
+
- **Custom Models**: 6.8/10 - Domain-specific fine-tuning
|
| 94 |
+
- **Data Pipeline**: 6.5/10 - ETL for training data
|
| 95 |
+
- **Evaluation**: 6.7/10 - Automated model evaluation
|
| 96 |
+
- **A/B Testing**: 6.3/10 - Model comparison framework
|
| 97 |
+
|
| 98 |
+
## 🧠 Arquitetura de Modelos
|
| 99 |
+
|
| 100 |
+
### **Modelos Especializados Planejados**
|
| 101 |
+
```python
|
| 102 |
+
# Taxonomy dos Modelos Cidadão.AI
|
| 103 |
+
models_taxonomy = {
|
| 104 |
+
"corruption_detection": {
|
| 105 |
+
"type": "classification",
|
| 106 |
+
"base_model": "bert-base-multilingual-cased",
|
| 107 |
+
"specialization": "Brazilian Portuguese + government documents",
|
| 108 |
+
"use_case": "Detect corruption indicators in contracts"
|
| 109 |
+
},
|
| 110 |
+
"anomaly_detection": {
|
| 111 |
+
"type": "regression + classification",
|
| 112 |
+
"base_model": "Custom ensemble",
|
| 113 |
+
"specialization": "Financial data patterns",
|
| 114 |
+
"use_case": "Identify unusual spending patterns"
|
| 115 |
+
},
|
| 116 |
+
"entity_extraction": {
|
| 117 |
+
"type": "NER",
|
| 118 |
+
"base_model": "roberta-large",
|
| 119 |
+
"specialization": "Government entities + Brazilian names",
|
| 120 |
+
"use_case": "Extract companies, people, organizations"
|
| 121 |
+
},
|
| 122 |
+
"sentiment_analysis": {
|
| 123 |
+
"type": "classification",
|
| 124 |
+
"base_model": "distilbert-base-uncased",
|
| 125 |
+
"specialization": "Public opinion on transparency",
|
| 126 |
+
"use_case": "Analyze citizen feedback sentiment"
|
| 127 |
+
},
|
| 128 |
+
"summarization": {
|
| 129 |
+
"type": "seq2seq",
|
| 130 |
+
"base_model": "t5-base",
|
| 131 |
+
"specialization": "Government reports + legal documents",
|
| 132 |
+
"use_case": "Generate executive summaries"
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
```
|
| 136 |
+
|
| 137 |
+
### **Pipeline MLOps Architecture**
|
| 138 |
+
```yaml
|
| 139 |
+
# MLOps Workflow
|
| 140 |
+
stages:
|
| 141 |
+
data_collection:
|
| 142 |
+
- Portal da Transparência APIs
|
| 143 |
+
- Government databases
|
| 144 |
+
- Public procurement data
|
| 145 |
+
- Historical investigations
|
| 146 |
+
|
| 147 |
+
data_preprocessing:
|
| 148 |
+
- Data cleaning & validation
|
| 149 |
+
- Privacy anonymization
|
| 150 |
+
- Feature engineering
|
| 151 |
+
- Data augmentation
|
| 152 |
+
|
| 153 |
+
model_training:
|
| 154 |
+
- Hyperparameter optimization
|
| 155 |
+
- Cross-validation
|
| 156 |
+
- Ensemble methods
|
| 157 |
+
- Transfer learning
|
| 158 |
+
|
| 159 |
+
model_evaluation:
|
| 160 |
+
- Performance metrics
|
| 161 |
+
- Fairness evaluation
|
| 162 |
+
- Bias detection
|
| 163 |
+
- Interpretability analysis
|
| 164 |
+
|
| 165 |
+
model_deployment:
|
| 166 |
+
- HuggingFace Spaces
|
| 167 |
+
- Container deployment
|
| 168 |
+
- API endpoints
|
| 169 |
+
- Model serving
|
| 170 |
+
|
| 171 |
+
monitoring:
|
| 172 |
+
- Model drift detection
|
| 173 |
+
- Performance degradation
|
| 174 |
+
- Data quality monitoring
|
| 175 |
+
- Usage analytics
|
| 176 |
+
```
|
| 177 |
+
|
| 178 |
+
## 🔬 Modelos de IA Especializados
|
| 179 |
+
|
| 180 |
+
### **1. Corruption Detection Model**
|
| 181 |
+
```python
|
| 182 |
+
# Modelo especializado em detecção de corrupção
|
| 183 |
+
class CorruptionDetector:
|
| 184 |
+
base_model: "bert-base-multilingual-cased"
|
| 185 |
+
fine_tuned_on: "Brazilian government contracts + known corruption cases"
|
| 186 |
+
|
| 187 |
+
features:
|
| 188 |
+
- Contract language analysis
|
| 189 |
+
- Pricing anomaly detection
|
| 190 |
+
- Vendor relationship patterns
|
| 191 |
+
- Temporal irregularities
|
| 192 |
+
|
| 193 |
+
metrics:
|
| 194 |
+
- Precision: >85%
|
| 195 |
+
- Recall: >80%
|
| 196 |
+
- F1-Score: >82%
|
| 197 |
+
- False Positive Rate: <5%
|
| 198 |
+
```
|
| 199 |
+
|
| 200 |
+
### **2. Anomaly Detection Ensemble**
|
| 201 |
+
```python
|
| 202 |
+
# Ensemble para detecção de anomalias financeiras
|
| 203 |
+
class AnomalyDetector:
|
| 204 |
+
models:
|
| 205 |
+
- IsolationForest: "Outlier detection"
|
| 206 |
+
- LSTM: "Temporal pattern analysis"
|
| 207 |
+
- Autoencoder: "Reconstruction error"
|
| 208 |
+
- Random Forest: "Feature importance"
|
| 209 |
+
|
| 210 |
+
features:
|
| 211 |
+
- Amount deviation from median
|
| 212 |
+
- Vendor concentration
|
| 213 |
+
- Seasonal patterns
|
| 214 |
+
- Geographic distribution
|
| 215 |
+
|
| 216 |
+
output:
|
| 217 |
+
- Anomaly score (0-1)
|
| 218 |
+
- Confidence interval
|
| 219 |
+
- Explanation vector
|
| 220 |
+
- Risk category
|
| 221 |
+
```
|
| 222 |
+
|
| 223 |
+
### **3. Entity Recognition (NER)**
|
| 224 |
+
```python
|
| 225 |
+
# NER especializado para entidades governamentais
|
| 226 |
+
class GovernmentNER:
|
| 227 |
+
base_model: "roberta-large"
|
| 228 |
+
entities:
|
| 229 |
+
- ORGANIZATION: "Ministérios, órgãos, empresas"
|
| 230 |
+
- PERSON: "Servidores, políticos, empresários"
|
| 231 |
+
- LOCATION: "Estados, municípios, endereços"
|
| 232 |
+
- CONTRACT: "Números de contratos, licitações"
|
| 233 |
+
- MONEY: "Valores monetários, moedas"
|
| 234 |
+
- DATE: "Datas de contratos, vigências"
|
| 235 |
+
|
| 236 |
+
brazilian_specialization:
|
| 237 |
+
- CPF/CNPJ recognition
|
| 238 |
+
- Brazilian address patterns
|
| 239 |
+
- Government terminology
|
| 240 |
+
- Legal document structure
|
| 241 |
+
```
|
| 242 |
+
|
| 243 |
+
## 🚀 HuggingFace Integration
|
| 244 |
+
|
| 245 |
+
### **Model Hub Strategy**
|
| 246 |
+
```python
|
| 247 |
+
# HuggingFace Hub Organization
|
| 248 |
+
organization: "cidadao-ai"
|
| 249 |
+
models:
|
| 250 |
+
- "cidadao-ai/corruption-detector-pt"
|
| 251 |
+
- "cidadao-ai/anomaly-detector-financial"
|
| 252 |
+
- "cidadao-ai/ner-government-entities"
|
| 253 |
+
- "cidadao-ai/sentiment-transparency"
|
| 254 |
+
- "cidadao-ai/summarization-reports"
|
| 255 |
+
|
| 256 |
+
spaces:
|
| 257 |
+
- "cidadao-ai/corruption-demo"
|
| 258 |
+
- "cidadao-ai/anomaly-dashboard"
|
| 259 |
+
- "cidadao-ai/transparency-analyzer"
|
| 260 |
+
```
|
| 261 |
+
|
| 262 |
+
### **Model Cards Template**
|
| 263 |
+
```markdown
|
| 264 |
+
# Model Card: Cidadão.AI Corruption Detector
|
| 265 |
+
|
| 266 |
+
## Model Description
|
| 267 |
+
- **Developed by**: Cidadão.AI Team
|
| 268 |
+
- **Model type**: BERT-based binary classifier
|
| 269 |
+
- **Language**: Portuguese (Brazil)
|
| 270 |
+
- **License**: MIT
|
| 271 |
+
|
| 272 |
+
## Training Data
|
| 273 |
+
- **Sources**: Portal da Transparência + curated corruption cases
|
| 274 |
+
- **Size**: 100K+ government contracts
|
| 275 |
+
- **Preprocessing**: Anonymization + cleaning + augmentation
|
| 276 |
+
|
| 277 |
+
## Evaluation
|
| 278 |
+
- **Test Set**: 10K held-out contracts
|
| 279 |
+
- **Metrics**: Precision: 87%, Recall: 83%, F1: 85%
|
| 280 |
+
- **Bias Analysis**: Evaluated across regions + contract types
|
| 281 |
+
|
| 282 |
+
## Ethical Considerations
|
| 283 |
+
- **Intended Use**: Transparency analysis, not legal evidence
|
| 284 |
+
- **Limitations**: May have bias toward certain contract types
|
| 285 |
+
- **Risks**: False positives could damage reputations
|
| 286 |
+
```
|
| 287 |
+
|
| 288 |
+
## 🛠️ MLOps Pipeline
|
| 289 |
+
|
| 290 |
+
### **Training Infrastructure**
|
| 291 |
+
```yaml
|
| 292 |
+
# training-pipeline.yml
|
| 293 |
+
name: Model Training Pipeline
|
| 294 |
+
on:
|
| 295 |
+
schedule:
|
| 296 |
+
- cron: '0 2 * * 0' # Weekly retraining
|
| 297 |
+
workflow_dispatch:
|
| 298 |
+
|
| 299 |
+
jobs:
|
| 300 |
+
data_preparation:
|
| 301 |
+
runs-on: ubuntu-latest
|
| 302 |
+
steps:
|
| 303 |
+
- name: Fetch latest data
|
| 304 |
+
- name: Validate data quality
|
| 305 |
+
- name: Preprocess & augment
|
| 306 |
+
|
| 307 |
+
model_training:
|
| 308 |
+
runs-on: gpu-runner
|
| 309 |
+
steps:
|
| 310 |
+
- name: Hyperparameter optimization
|
| 311 |
+
- name: Train model
|
| 312 |
+
- name: Evaluate performance
|
| 313 |
+
|
| 314 |
+
model_deployment:
|
| 315 |
+
runs-on: ubuntu-latest
|
| 316 |
+
if: model_performance > threshold
|
| 317 |
+
steps:
|
| 318 |
+
- name: Upload to HuggingFace Hub
|
| 319 |
+
- name: Update model registry
|
| 320 |
+
- name: Deploy to production
|
| 321 |
+
```
|
| 322 |
+
|
| 323 |
+
### **Model Monitoring Dashboard**
|
| 324 |
+
```python
|
| 325 |
+
# Métricas de monitoramento
|
| 326 |
+
monitoring_metrics = {
|
| 327 |
+
"performance": {
|
| 328 |
+
"accuracy": "Real-time accuracy tracking",
|
| 329 |
+
"latency": "Response time monitoring",
|
| 330 |
+
"throughput": "Requests per second",
|
| 331 |
+
"error_rate": "Failed prediction rate"
|
| 332 |
+
},
|
| 333 |
+
"data_drift": {
|
| 334 |
+
"feature_drift": "Input distribution changes",
|
| 335 |
+
"label_drift": "Output distribution changes",
|
| 336 |
+
"concept_drift": "Relationship changes"
|
| 337 |
+
},
|
| 338 |
+
"business": {
|
| 339 |
+
"investigations_triggered": "Anomalies detected",
|
| 340 |
+
"false_positive_rate": "User feedback tracking",
|
| 341 |
+
"citizen_satisfaction": "User experience metrics"
|
| 342 |
+
}
|
| 343 |
+
}
|
| 344 |
+
```
|
| 345 |
+
|
| 346 |
+
## 🧪 Experimentação e Avaliação
|
| 347 |
+
|
| 348 |
+
### **Experiment Tracking**
|
| 349 |
+
```python
|
| 350 |
+
# MLflow + Weights & Biases integration
|
| 351 |
+
import mlflow
|
| 352 |
+
import wandb
|
| 353 |
+
|
| 354 |
+
def train_model(config):
|
| 355 |
+
with mlflow.start_run():
|
| 356 |
+
wandb.init(project="cidadao-ai", config=config)
|
| 357 |
+
|
| 358 |
+
# Log hyperparameters
|
| 359 |
+
mlflow.log_params(config)
|
| 360 |
+
wandb.config.update(config)
|
| 361 |
+
|
| 362 |
+
# Training loop
|
| 363 |
+
for epoch in range(config.epochs):
|
| 364 |
+
metrics = train_epoch(model, train_loader)
|
| 365 |
+
|
| 366 |
+
# Log metrics
|
| 367 |
+
mlflow.log_metrics(metrics, step=epoch)
|
| 368 |
+
wandb.log(metrics)
|
| 369 |
+
|
| 370 |
+
# Log model artifacts
|
| 371 |
+
mlflow.pytorch.log_model(model, "model")
|
| 372 |
+
wandb.save("model.pt")
|
| 373 |
+
```
|
| 374 |
+
|
| 375 |
+
### **A/B Testing Framework**
|
| 376 |
+
```python
|
| 377 |
+
# Framework para testes A/B de modelos
|
| 378 |
+
class ModelABTest:
|
| 379 |
+
def __init__(self, model_a, model_b, traffic_split=0.5):
|
| 380 |
+
self.model_a = model_a
|
| 381 |
+
self.model_b = model_b
|
| 382 |
+
self.traffic_split = traffic_split
|
| 383 |
+
|
| 384 |
+
def predict(self, input_data, user_id):
|
| 385 |
+
# Route traffic based on user_id hash
|
| 386 |
+
if hash(user_id) % 100 < self.traffic_split * 100:
|
| 387 |
+
result = self.model_a.predict(input_data)
|
| 388 |
+
self.log_prediction("model_a", result, user_id)
|
| 389 |
+
else:
|
| 390 |
+
result = self.model_b.predict(input_data)
|
| 391 |
+
self.log_prediction("model_b", result, user_id)
|
| 392 |
+
|
| 393 |
+
return result
|
| 394 |
+
```
|
| 395 |
+
|
| 396 |
+
## 📊 Datasets e Treinamento
|
| 397 |
+
|
| 398 |
+
### **Datasets Especializados**
|
| 399 |
+
```python
|
| 400 |
+
# Datasets para treinamento
|
| 401 |
+
datasets = {
|
| 402 |
+
"transparency_contracts": {
|
| 403 |
+
"source": "Portal da Transparência API",
|
| 404 |
+
"size": "500K+ contracts",
|
| 405 |
+
"format": "JSON + PDF text extraction",
|
| 406 |
+
"labels": "Manual annotation + expert review"
|
| 407 |
+
},
|
| 408 |
+
"corruption_cases": {
|
| 409 |
+
"source": "Historical investigations + court records",
|
| 410 |
+
"size": "10K+ labeled cases",
|
| 411 |
+
"format": "Structured data + documents",
|
| 412 |
+
"labels": "Binary classification + severity"
|
| 413 |
+
},
|
| 414 |
+
"financial_anomalies": {
|
| 415 |
+
"source": "Government spending data",
|
| 416 |
+
"size": "1M+ transactions",
|
| 417 |
+
"format": "Tabular data",
|
| 418 |
+
"labels": "Statistical outliers + domain expert"
|
| 419 |
+
}
|
| 420 |
+
}
|
| 421 |
+
```
|
| 422 |
+
|
| 423 |
+
### **Data Preprocessing Pipeline**
|
| 424 |
+
```python
|
| 425 |
+
# Pipeline de preprocessamento
|
| 426 |
+
class DataPreprocessor:
|
| 427 |
+
def __init__(self):
|
| 428 |
+
self.tokenizer = AutoTokenizer.from_pretrained("bert-base-multilingual-cased")
|
| 429 |
+
self.anonymizer = GovernmentDataAnonymizer()
|
| 430 |
+
|
| 431 |
+
def preprocess_contract(self, contract_text):
|
| 432 |
+
# 1. Anonymize sensitive information
|
| 433 |
+
anonymized = self.anonymizer.anonymize(contract_text)
|
| 434 |
+
|
| 435 |
+
# 2. Clean and normalize text
|
| 436 |
+
cleaned = self.clean_text(anonymized)
|
| 437 |
+
|
| 438 |
+
# 3. Tokenize for model input
|
| 439 |
+
tokens = self.tokenizer(
|
| 440 |
+
cleaned,
|
| 441 |
+
max_length=512,
|
| 442 |
+
truncation=True,
|
| 443 |
+
padding=True,
|
| 444 |
+
return_tensors="pt"
|
| 445 |
+
)
|
| 446 |
+
|
| 447 |
+
return tokens
|
| 448 |
+
```
|
| 449 |
+
|
| 450 |
+
## 🔄 Integração com Backend
|
| 451 |
+
|
| 452 |
+
### **Model Serving API**
|
| 453 |
+
```python
|
| 454 |
+
# FastAPI endpoints para servir modelos
|
| 455 |
+
from fastapi import FastAPI
|
| 456 |
+
from transformers import pipeline
|
| 457 |
+
|
| 458 |
+
app = FastAPI()
|
| 459 |
+
|
| 460 |
+
# Load models
|
| 461 |
+
corruption_detector = pipeline(
|
| 462 |
+
"text-classification",
|
| 463 |
+
model="cidadao-ai/corruption-detector-pt"
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
anomaly_detector = joblib.load("models/anomaly_detector.pkl")
|
| 467 |
+
|
| 468 |
+
@app.post("/analyze/corruption")
|
| 469 |
+
async def detect_corruption(contract_text: str):
|
| 470 |
+
result = corruption_detector(contract_text)
|
| 471 |
+
return {
|
| 472 |
+
"prediction": result[0]["label"],
|
| 473 |
+
"confidence": result[0]["score"],
|
| 474 |
+
"model_version": "v1.0.0"
|
| 475 |
+
}
|
| 476 |
+
|
| 477 |
+
@app.post("/analyze/anomaly")
|
| 478 |
+
async def detect_anomaly(financial_data: dict):
|
| 479 |
+
features = extract_features(financial_data)
|
| 480 |
+
anomaly_score = anomaly_detector.predict(features)
|
| 481 |
+
return {
|
| 482 |
+
"anomaly_score": float(anomaly_score),
|
| 483 |
+
"is_anomaly": anomaly_score > 0.7,
|
| 484 |
+
"explanation": generate_explanation(features)
|
| 485 |
+
}
|
| 486 |
+
```
|
| 487 |
+
|
| 488 |
+
### **Agent Integration**
|
| 489 |
+
```python
|
| 490 |
+
# Integração com sistema multi-agente
|
| 491 |
+
class ModelService:
|
| 492 |
+
def __init__(self):
|
| 493 |
+
self.models = {
|
| 494 |
+
"corruption": self.load_corruption_model(),
|
| 495 |
+
"anomaly": self.load_anomaly_model(),
|
| 496 |
+
"ner": self.load_ner_model()
|
| 497 |
+
}
|
| 498 |
+
|
| 499 |
+
async def analyze_for_agent(self, agent_name: str, data: dict):
|
| 500 |
+
if agent_name == "InvestigatorAgent":
|
| 501 |
+
return await self.detect_anomalies(data)
|
| 502 |
+
elif agent_name == "CorruptionDetectorAgent":
|
| 503 |
+
return await self.detect_corruption(data)
|
| 504 |
+
elif agent_name == "AnalystAgent":
|
| 505 |
+
return await self.extract_entities(data)
|
| 506 |
+
```
|
| 507 |
+
|
| 508 |
+
## 🔒 Ética e Governança
|
| 509 |
+
|
| 510 |
+
### **Responsible AI Principles**
|
| 511 |
+
```python
|
| 512 |
+
# Princípios de IA Responsável
|
| 513 |
+
class ResponsibleAI:
|
| 514 |
+
principles = {
|
| 515 |
+
"transparency": "Explicabilidade em todas as decisões",
|
| 516 |
+
"fairness": "Avaliação de viés em grupos demográficos",
|
| 517 |
+
"privacy": "Anonimização de dados pessoais",
|
| 518 |
+
"accountability": "Auditoria e rastreabilidade",
|
| 519 |
+
"robustness": "Teste contra adversarial attacks"
|
| 520 |
+
}
|
| 521 |
+
|
| 522 |
+
def evaluate_bias(self, model, test_data, protected_attributes):
|
| 523 |
+
"""Avalia viés do modelo em grupos protegidos"""
|
| 524 |
+
bias_metrics = {}
|
| 525 |
+
for attr in protected_attributes:
|
| 526 |
+
group_metrics = self.compute_group_metrics(model, test_data, attr)
|
| 527 |
+
bias_metrics[attr] = group_metrics
|
| 528 |
+
return bias_metrics
|
| 529 |
+
```
|
| 530 |
+
|
| 531 |
+
### **Model Interpretability**
|
| 532 |
+
```python
|
| 533 |
+
# Ferramentas de interpretabilidade
|
| 534 |
+
from lime.lime_text import LimeTextExplainer
|
| 535 |
+
from shap import Explainer
|
| 536 |
+
|
| 537 |
+
class ModelExplainer:
|
| 538 |
+
def __init__(self, model):
|
| 539 |
+
self.model = model
|
| 540 |
+
self.lime_explainer = LimeTextExplainer()
|
| 541 |
+
self.shap_explainer = Explainer(model)
|
| 542 |
+
|
| 543 |
+
def explain_prediction(self, text, method="lime"):
|
| 544 |
+
if method == "lime":
|
| 545 |
+
explanation = self.lime_explainer.explain_instance(
|
| 546 |
+
text, self.model.predict_proba
|
| 547 |
+
)
|
| 548 |
+
elif method == "shap":
|
| 549 |
+
explanation = self.shap_explainer(text)
|
| 550 |
+
|
| 551 |
+
return explanation
|
| 552 |
+
```
|
| 553 |
+
|
| 554 |
+
## 📋 Roadmap Modelos IA
|
| 555 |
+
|
| 556 |
+
### **Curto Prazo (1-2 meses)**
|
| 557 |
+
1. **Setup MLOps Pipeline**: MLflow + DVC + CI/CD
|
| 558 |
+
2. **Corruption Detection Model**: Fine-tune BERT para português
|
| 559 |
+
3. **HuggingFace Integration**: Upload initial models
|
| 560 |
+
4. **Basic Monitoring**: Performance tracking dashboard
|
| 561 |
+
|
| 562 |
+
### **Médio Prazo (3-6 meses)**
|
| 563 |
+
1. **Anomaly Detection Ensemble**: Multiple algorithms
|
| 564 |
+
2. **NER Government Entities**: Custom entity recognition
|
| 565 |
+
3. **Model A/B Testing**: Production experimentation
|
| 566 |
+
4. **Advanced Monitoring**: Drift detection + alerting
|
| 567 |
+
|
| 568 |
+
### **Longo Prazo (6+ meses)**
|
| 569 |
+
1. **Custom Architecture**: Domain-specific model architectures
|
| 570 |
+
2. **Federated Learning**: Privacy-preserving training
|
| 571 |
+
3. **AutoML Pipeline**: Automated model selection
|
| 572 |
+
4. **Edge Deployment**: Local model inference
|
| 573 |
+
|
| 574 |
+
## ⚠️ Áreas para Melhoria
|
| 575 |
+
|
| 576 |
+
### **Priority 1: Data Pipeline**
|
| 577 |
+
- **Data Collection**: Automated data ingestion
|
| 578 |
+
- **Data Quality**: Validation + cleaning pipelines
|
| 579 |
+
- **Labeling**: Active learning + human-in-the-loop
|
| 580 |
+
- **Privacy**: Advanced anonymization techniques
|
| 581 |
+
|
| 582 |
+
### **Priority 2: Model Development**
|
| 583 |
+
- **Custom Models**: Domain-specific architectures
|
| 584 |
+
- **Transfer Learning**: Portuguese government domain
|
| 585 |
+
- **Ensemble Methods**: Model combination strategies
|
| 586 |
+
- **Optimization**: Model compression + acceleration
|
| 587 |
+
|
| 588 |
+
### **Priority 3: MLOps Maturity**
|
| 589 |
+
- **CI/CD**: Automated testing + deployment
|
| 590 |
+
- **Monitoring**: Comprehensive drift detection
|
| 591 |
+
- **Experimentation**: A/B testing framework
|
| 592 |
+
- **Governance**: Model audit + compliance
|
| 593 |
+
|
| 594 |
+
## 🎯 Métricas de Sucesso
|
| 595 |
+
|
| 596 |
+
### **Technical Metrics**
|
| 597 |
+
- **Model Performance**: F1 > 85% for all models
|
| 598 |
+
- **Inference Latency**: <200ms response time
|
| 599 |
+
- **Deployment Success**: >99% uptime
|
| 600 |
+
- **Data Pipeline**: <1% data quality issues
|
| 601 |
+
|
| 602 |
+
### **Business Metrics**
|
| 603 |
+
- **Anomalies Detected**: 100+ monthly
|
| 604 |
+
- **False Positive Rate**: <5%
|
| 605 |
+
- **User Satisfaction**: >80% positive feedback
|
| 606 |
+
- **Investigation Success**: >70% actionable insights
|
| 607 |
+
|
| 608 |
+
## 🔧 Comandos de Desenvolvimento
|
| 609 |
+
|
| 610 |
+
### **Model Training**
|
| 611 |
+
```bash
|
| 612 |
+
# Train corruption detection model
|
| 613 |
+
python train_corruption_detector.py --config configs/corruption_bert.yaml
|
| 614 |
+
|
| 615 |
+
# Evaluate model performance
|
| 616 |
+
python evaluate_model.py --model corruption_detector --test_data data/test.json
|
| 617 |
+
|
| 618 |
+
# Upload to HuggingFace Hub
|
| 619 |
+
python upload_to_hub.py --model_path models/corruption_detector --repo_name cidadao-ai/corruption-detector-pt
|
| 620 |
+
```
|
| 621 |
+
|
| 622 |
+
### **Monitoring**
|
| 623 |
+
```bash
|
| 624 |
+
# Check model drift
|
| 625 |
+
python monitor_drift.py --model corruption_detector --window 7d
|
| 626 |
+
|
| 627 |
+
# Generate performance report
|
| 628 |
+
python generate_report.py --models all --period monthly
|
| 629 |
+
```
|
| 630 |
+
|
| 631 |
+
## 📝 Considerações Técnicas
|
| 632 |
+
|
| 633 |
+
### **Compute Requirements**
|
| 634 |
+
- **Training**: GPU-enabled instances (V100/A100)
|
| 635 |
+
- **Inference**: CPU instances sufficient for most models
|
| 636 |
+
- **Storage**: Cloud storage for datasets + model artifacts
|
| 637 |
+
- **Monitoring**: Real-time metrics collection
|
| 638 |
+
|
| 639 |
+
### **Security**
|
| 640 |
+
- **Model Protection**: Encrypted model artifacts
|
| 641 |
+
- **API Security**: Authentication + rate limiting
|
| 642 |
+
- **Data Privacy**: LGPD compliance + anonymization
|
| 643 |
+
- **Audit Trail**: Complete lineage tracking
|
| 644 |
+
|
| 645 |
+
### **Scalability**
|
| 646 |
+
- **Horizontal Scaling**: Load balancer + multiple instances
|
| 647 |
+
- **Model Versioning**: Backward compatibility
|
| 648 |
+
- **Cache Strategy**: Redis for frequent predictions
|
| 649 |
+
- **Batch Processing**: Async inference for large datasets
|
| 650 |
+
|
| 651 |
+
---
|
| 652 |
+
|
| 653 |
+
**Models Status**: Pipeline em desenvolvimento com infraestrutura sólida para modelos especializados.
|
| 654 |
+
**Next Update**: Implementação do primeiro modelo de detecção de corrupção e pipeline MLOps completo.
|
Cidadão IA Models Arquitetura.md
ADDED
|
@@ -0,0 +1,735 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🤖 Cidadão.IA Models - Hub de Modelos de IA Governamental
|
| 2 |
+
|
| 3 |
+
## 🎯 **Visão Geral do Projeto**
|
| 4 |
+
|
| 5 |
+
O repositório `cidadao.ai-models` é o **hub especializado de modelos de IA/ML** para o ecossistema Cidadão.IA, fornecendo modelos de machine learning de classe mundial, otimizados e prontos para produção via **HuggingFace Models**, integrados seamlessly com o backend principal.
|
| 6 |
+
|
| 7 |
+
### 🔗 **Integração com Ecossistema Cidadão.IA**
|
| 8 |
+
- **🏛️ Backend Principal**: [cidadao.ai-backend](https://huggingface.co/spaces/neural-thinker/cidadao.ai-backend) (HuggingFace Spaces)
|
| 9 |
+
- **🤖 Modelos de IA**: [cidadao.ai-models](https://github.com/anderson-ufrj/cidadao.ai-models) → HuggingFace Models
|
| 10 |
+
- **⚡ Inferência**: Modelos servidos via HF Hub, processados no backend Space
|
| 11 |
+
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
## 🧠 **Visão & Missão**
|
| 15 |
+
|
| 16 |
+
**Visão**: Criar um repositório de modelos de IA de classe mundial, modular, que democratize o acesso a insights de transparência governamental através de machine learning avançado.
|
| 17 |
+
|
| 18 |
+
**Missão**: Desenvolver, manter e distribuir modelos de IA especializados para:
|
| 19 |
+
- Detecção de anomalias em gastos públicos
|
| 20 |
+
- Verificação de conformidade legal
|
| 21 |
+
- Avaliação de risco financeiro
|
| 22 |
+
- Reconhecimento de padrões de corrupção
|
| 23 |
+
- Análise temporal de dados governamentais
|
| 24 |
+
|
| 25 |
+
---
|
| 26 |
+
|
| 27 |
+
## 📐 **Princípios Arquiteturais**
|
| 28 |
+
|
| 29 |
+
### **1. Modularidade em Primeiro Lugar**
|
| 30 |
+
- Cada modelo é um componente autônomo e versionado
|
| 31 |
+
- Separação clara entre treinamento, inferência e utilitários
|
| 32 |
+
- Arquitetura baseada em plugins para fácil integração
|
| 33 |
+
|
| 34 |
+
### **2. Escalabilidade por Design**
|
| 35 |
+
- Escalonamento horizontal via containerização
|
| 36 |
+
- Serving de modelos pronto para microserviços
|
| 37 |
+
- Estratégias de deploy agnósticas à cloud
|
| 38 |
+
|
| 39 |
+
### **3. Excelência em Produção**
|
| 40 |
+
- Versionamento e registry de modelos nível enterprise
|
| 41 |
+
- Testes e validação abrangentes
|
| 42 |
+
- Integração com pipeline MLOps
|
| 43 |
+
- Observabilidade e monitoramento integrados
|
| 44 |
+
|
| 45 |
+
### **4. Integração HuggingFace Nativa**
|
| 46 |
+
- **HuggingFace Models**: Deploy direto via HF Hub para distribuição global
|
| 47 |
+
- **Model Cards**: Documentação técnica automática com métricas e exemplos
|
| 48 |
+
- **Transformers**: Compatibilidade nativa com biblioteca transformers
|
| 49 |
+
- **ONNX Export**: Otimização cross-platform para produção
|
| 50 |
+
- **Zero Infraestrutura**: Aproveitamento da CDN global do HuggingFace
|
| 51 |
+
|
| 52 |
+
---
|
| 53 |
+
|
| 54 |
+
## 🏛️ **Arquitetura do Repositório**
|
| 55 |
+
|
| 56 |
+
```
|
| 57 |
+
cidadao.ia-models/
|
| 58 |
+
├── 📁 modelos/ # Modelos prontos para produção
|
| 59 |
+
│ ├── 📁 cidadao-bertimbau-ner-v1/ # Reconhecimento de Entidades Nomeadas
|
| 60 |
+
│ ├── 📁 cidadao-detector-anomalias-v2/ # Detecção de Anomalias
|
| 61 |
+
│ ├── 📁 cidadao-classificador-risco-v1/ # Avaliação de Risco Financeiro
|
| 62 |
+
│ ├── 📁 cidadao-juiz-conformidade-v1/ # Conformidade Legal
|
| 63 |
+
│ └── 📁 cidadao-analisador-espectral-v1/ # Análise de Padrões Temporais
|
| 64 |
+
│
|
| 65 |
+
├── 📁 experimentos/ # Pesquisa & prototipagem
|
| 66 |
+
│ ├── 📁 notebooks/ # Notebooks Jupyter de pesquisa
|
| 67 |
+
│ ├── 📁 prototipos/ # Modelos experimentais
|
| 68 |
+
│ └── 📁 benchmarks/ # Comparações de performance
|
| 69 |
+
│
|
| 70 |
+
├── 📁 treinamento/ # Infraestrutura de treinamento
|
| 71 |
+
│ ├── 📁 pipelines/ # Pipelines MLOps de treinamento
|
| 72 |
+
│ ├── 📁 datasets/ # Utilitários de processamento de dados
|
| 73 |
+
│ └── 📁 configs/ # Configurações de treinamento
|
| 74 |
+
│
|
| 75 |
+
├── 📁 inferencia/ # Serving de produção
|
| 76 |
+
│ ├── 📁 pipelines/ # Pipelines de inferência
|
| 77 |
+
│ ├── 📁 api/ # APIs de serving de modelos
|
| 78 |
+
│ └── 📁 lote/ # Processamento em lote
|
| 79 |
+
│
|
| 80 |
+
├── 📁 utils/ # Utilitários compartilhados
|
| 81 |
+
│ ├── 📁 preprocessamento/ # Pré-processamento de dados
|
| 82 |
+
│ ├── 📁 pos_processamento/ # Processamento de saída
|
| 83 |
+
│ ├── 📁 metricas/ # Métricas de avaliação
|
| 84 |
+
│ └── 📁 visualizacao/ # Visualização de análises
|
| 85 |
+
│
|
| 86 |
+
├── 📁 deploy/ # Artefatos de deploy
|
| 87 |
+
│ ├── 📁 docker/ # Definições de containers
|
| 88 |
+
│ ├── 📁 kubernetes/ # Manifestos K8s
|
| 89 |
+
│ └── 📁 cloud/ # Configs específicas de cloud
|
| 90 |
+
│
|
| 91 |
+
├── 📁 testes/ # Testes abrangentes
|
| 92 |
+
│ ├── 📁 unitarios/ # Testes unitários
|
| 93 |
+
│ ├── 📁 integracao/ # Testes de integração
|
| 94 |
+
│ └── 📁 performance/ # Testes de performance
|
| 95 |
+
│
|
| 96 |
+
├── 📁 docs/ # Documentação
|
| 97 |
+
│ ├── 📁 cartoes_modelos/ # Documentação dos modelos
|
| 98 |
+
│ ├── 📁 tutoriais/ # Tutoriais de uso
|
| 99 |
+
│ └── 📁 api/ # Documentação da API
|
| 100 |
+
│
|
| 101 |
+
├── 📄 registro_modelos.json # Registry central de modelos
|
| 102 |
+
├── 📄 requirements.txt # Dependências Python
|
| 103 |
+
├── 📄 setup.py # Instalação do pacote
|
| 104 |
+
├── 📄 Dockerfile # Container de produção
|
| 105 |
+
├── 📄 docker-compose.yml # Ambiente de desenvolvimento
|
| 106 |
+
└── 📄 README.md # Visão geral do projeto
|
| 107 |
+
```
|
| 108 |
+
|
| 109 |
+
---
|
| 110 |
+
|
| 111 |
+
## 🚀 **Taxonomia & Convenção de Nomenclatura de Modelos**
|
| 112 |
+
|
| 113 |
+
### **Padrão de Nomenclatura**: `cidadao-{dominio}-{arquitetura}-v{versao}`
|
| 114 |
+
|
| 115 |
+
| Domínio | Arquitetura | Exemplo | Propósito |
|
| 116 |
+
|---------|-------------|---------|-----------|
|
| 117 |
+
| `bertimbau-ner` | Transformer | `cidadao-bertimbau-ner-v1` | Reconhecimento de Entidades Nomeadas |
|
| 118 |
+
| `detector-anomalias` | Ensemble | `cidadao-detector-anomalias-v2` | Detecção de anomalias em gastos |
|
| 119 |
+
| `classificador-risco` | BERT | `cidadao-classificador-risco-v1` | Avaliação de risco financeiro |
|
| 120 |
+
| `juiz-conformidade` | RoBERTa | `cidadao-juiz-conformidade-v1` | Verificação de conformidade legal |
|
| 121 |
+
| `analisador-espectral` | Processamento de Sinais | `cidadao-analisador-espectral-v1` | Análise de padrões temporais |
|
| 122 |
+
| `modelador-topicos` | BERTopic | `cidadao-modelador-topicos-v1` | Modelagem de tópicos de documentos |
|
| 123 |
+
| `roteador-semantico` | Sentence-BERT | `cidadao-roteador-semantico-v1` | Roteamento de consultas |
|
| 124 |
+
|
| 125 |
+
---
|
| 126 |
+
|
| 127 |
+
## 📋 **Roadmap de Implementação**
|
| 128 |
+
|
| 129 |
+
### **Fase 1: Configuração da Fundação** ⏱️ *2 semanas*
|
| 130 |
+
|
| 131 |
+
#### **Semana 1: Estrutura do Repositório**
|
| 132 |
+
- [ ] **Dia 1-2**: Criar estrutura base de diretórios
|
| 133 |
+
- [ ] **Dia 3-4**: Configurar pipeline CI/CD (GitHub Actions)
|
| 134 |
+
- [ ] **Dia 5-7**: Configurar ambiente de desenvolvimento (Docker, requirements)
|
| 135 |
+
|
| 136 |
+
#### **Semana 2: Infraestrutura Core**
|
| 137 |
+
- [ ] **Dia 1-3**: Implementar sistema de registry de modelos
|
| 138 |
+
- [ ] **Dia 4-5**: Criar classes base de modelos e interfaces
|
| 139 |
+
- [ ] **Dia 6-7**: Configurar framework de testes e quality gates
|
| 140 |
+
|
| 141 |
+
### **Fase 2: Migração & Aprimoramento de Modelos** ⏱️ *4 semanas*
|
| 142 |
+
|
| 143 |
+
#### **Semana 1: Modelos de Detecção de Anomalias**
|
| 144 |
+
- [ ] **Dia 1-2**: Extrair `cidadao_model.py` → `cidadao-detector-anomalias-v2`
|
| 145 |
+
- [ ] **Dia 3-4**: Criar model card e documentação
|
| 146 |
+
- [ ] **Dia 5**: Implementar pipeline de inferência
|
| 147 |
+
- [ ] **Dia 6-7**: Adicionar export ONNX e otimização
|
| 148 |
+
|
| 149 |
+
#### **Semana 2: Modelos NER & Entidades**
|
| 150 |
+
- [ ] **Dia 1-2**: Implementar `cidadao-bertimbau-ner-v1`
|
| 151 |
+
- [ ] **Dia 3-4**: Criar pipeline de extração de entidades
|
| 152 |
+
- [ ] **Dia 5**: Adicionar suporte multilíngue (Português/Inglês)
|
| 153 |
+
- [ ] **Dia 6-7**: Otimização de performance e cache
|
| 154 |
+
|
| 155 |
+
#### **Semana 3: Modelos de Risco & Conformidade**
|
| 156 |
+
- [ ] **Dia 1-2**: Extrair classificação de risco → `cidadao-classificador-risco-v1`
|
| 157 |
+
- [ ] **Dia 3-4**: Implementar verificação de conformidade → `cidadao-juiz-conformidade-v1`
|
| 158 |
+
- [ ] **Dia 5**: Criar sistema unificado de pontuação
|
| 159 |
+
- [ ] **Dia 6-7**: Adicionar recursos de explicabilidade (SHAP/LIME)
|
| 160 |
+
|
| 161 |
+
#### **Semana 4: Analytics Avançadas**
|
| 162 |
+
- [ ] **Dia 1-2**: Extrair análise espectral → `cidadao-analisador-espectral-v1`
|
| 163 |
+
- [ ] **Dia 3-4**: Implementar modelagem de tópicos → `cidadao-modelador-topicos-v1`
|
| 164 |
+
- [ ] **Dia 5**: Criar roteamento semântico → `cidadao-roteador-semantico-v1`
|
| 165 |
+
- [ ] **Dia 6-7**: Testes de integração e validação de performance
|
| 166 |
+
|
| 167 |
+
### **Fase 3: Prontidão para Produção** ⏱️ *3 semanas*
|
| 168 |
+
|
| 169 |
+
#### **Semana 1: Infraestrutura de API & Serving**
|
| 170 |
+
- [ ] **Dia 1-2**: Implementar endpoints FastAPI de serving de modelos
|
| 171 |
+
- [ ] **Dia 3-4**: Criar pipelines de processamento em lote
|
| 172 |
+
- [ ] **Dia 5**: Adicionar health checks e monitoramento
|
| 173 |
+
- [ ] **Dia 6-7**: Implementar rate limiting e segurança
|
| 174 |
+
|
| 175 |
+
#### **Semana 2: Infraestrutura de Treinamento**
|
| 176 |
+
- [ ] **Dia 1-2**: Criar pipelines MLOps de treinamento
|
| 177 |
+
- [ ] **Dia 3-4**: Implementar tracking de experimentos (MLflow/Weights & Biases)
|
| 178 |
+
- [ ] **Dia 5**: Adicionar tuning automatizado de hiperparâmetros
|
| 179 |
+
- [ ] **Dia 6-7**: Criar workflows de validação e aprovação de modelos
|
| 180 |
+
|
| 181 |
+
#### **Semana 3: Deploy & DevOps**
|
| 182 |
+
- [ ] **Dia 1-2**: Containerizar todos os modelos (Docker)
|
| 183 |
+
- [ ] **Dia 3-4**: Criar manifestos de deploy Kubernetes
|
| 184 |
+
- [ ] **Dia 5**: Implementar estratégia de deploy blue-green
|
| 185 |
+
- [ ] **Dia 6-7**: Adicionar observabilidade (Prometheus, Grafana)
|
| 186 |
+
|
| 187 |
+
### **Fase 4: Recursos Avançados** ⏱️ *3 semanas*
|
| 188 |
+
|
| 189 |
+
#### **Semana 1: Integração Model Hub**
|
| 190 |
+
- [ ] **Dia 1-2**: Integrar com Hugging Face Hub
|
| 191 |
+
- [ ] **Dia 3-4**: Criar pipeline automatizado de publicação de modelos
|
| 192 |
+
- [ ] **Dia 5**: Implementar versionamento de modelos e testes A/B
|
| 193 |
+
- [ ] **Dia 6-7**: Adicionar governança e workflows de aprovação de modelos
|
| 194 |
+
|
| 195 |
+
#### **Semana 2: Otimização de Performance**
|
| 196 |
+
- [ ] **Dia 1-2**: Implementar quantização e pruning de modelos
|
| 197 |
+
- [ ] **Dia 3-4**: Adicionar aceleração GPU e otimização CUDA
|
| 198 |
+
- [ ] **Dia 5**: Criar cache e memoização de modelos
|
| 199 |
+
- [ ] **Dia 6-7**: Implementar inferência distribuída
|
| 200 |
+
|
| 201 |
+
#### **Semana 3: Analytics & Monitoramento**
|
| 202 |
+
- [ ] **Dia 1-2**: Criar dashboards de performance de modelos
|
| 203 |
+
- [ ] **Dia 3-4**: Implementar detecção de drift e alertas
|
| 204 |
+
- [ ] **Dia 5**: Adicionar tracking de métricas de negócio
|
| 205 |
+
- [ ] **Dia 6-7**: Criar triggers automatizados de retreinamento de modelos
|
| 206 |
+
|
| 207 |
+
---
|
| 208 |
+
|
| 209 |
+
## 🧩 **Especificações de Interface de Modelos**
|
| 210 |
+
|
| 211 |
+
### **Interface Padrão de Modelos**
|
| 212 |
+
|
| 213 |
+
```python
|
| 214 |
+
from abc import ABC, abstractmethod
|
| 215 |
+
from typing import Dict, List, Any, Optional
|
| 216 |
+
from dataclasses import dataclass
|
| 217 |
+
import torch
|
| 218 |
+
from transformers import PreTrainedModel
|
| 219 |
+
|
| 220 |
+
@dataclass
|
| 221 |
+
class MetadadosModelo:
|
| 222 |
+
nome: str
|
| 223 |
+
versao: str
|
| 224 |
+
descricao: str
|
| 225 |
+
autor: str
|
| 226 |
+
criado_em: str
|
| 227 |
+
tipo_modelo: str
|
| 228 |
+
schema_entrada: Dict[str, Any]
|
| 229 |
+
schema_saida: Dict[str, Any]
|
| 230 |
+
metricas: Dict[str, float]
|
| 231 |
+
tags: List[str]
|
| 232 |
+
|
| 233 |
+
class CidadaoModeloBase(ABC):
|
| 234 |
+
"""Interface base para todos os modelos Cidadão.IA"""
|
| 235 |
+
|
| 236 |
+
def __init__(self, caminho_modelo: str, config: Optional[Dict] = None):
|
| 237 |
+
self.caminho_modelo = caminho_modelo
|
| 238 |
+
self.config = config or {}
|
| 239 |
+
self.metadados = self.carregar_metadados()
|
| 240 |
+
self.modelo = self.carregar_modelo()
|
| 241 |
+
|
| 242 |
+
@abstractmethod
|
| 243 |
+
def carregar_modelo(self) -> Any:
|
| 244 |
+
"""Carregar o modelo treinado"""
|
| 245 |
+
pass
|
| 246 |
+
|
| 247 |
+
@abstractmethod
|
| 248 |
+
def predizer(self, entradas: Dict[str, Any]) -> Dict[str, Any]:
|
| 249 |
+
"""Fazer predições nos dados de entrada"""
|
| 250 |
+
pass
|
| 251 |
+
|
| 252 |
+
@abstractmethod
|
| 253 |
+
def predizer_lote(self, entradas: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
| 254 |
+
"""Fazer predições em lote"""
|
| 255 |
+
pass
|
| 256 |
+
|
| 257 |
+
def validar_entrada(self, entradas: Dict[str, Any]) -> bool:
|
| 258 |
+
"""Validar entrada contra schema"""
|
| 259 |
+
pass
|
| 260 |
+
|
| 261 |
+
def explicar(self, entradas: Dict[str, Any]) -> Dict[str, Any]:
|
| 262 |
+
"""Fornecer explicações do modelo"""
|
| 263 |
+
pass
|
| 264 |
+
|
| 265 |
+
def carregar_metadados(self) -> MetadadosModelo:
|
| 266 |
+
"""Carregar metadados do modelo"""
|
| 267 |
+
pass
|
| 268 |
+
```
|
| 269 |
+
|
| 270 |
+
### **Interfaces Específicas de Modelos**
|
| 271 |
+
|
| 272 |
+
#### **Interface de Detecção de Anomalias**
|
| 273 |
+
```python
|
| 274 |
+
class CidadaoDetectorAnomalias(CidadaoModeloBase):
|
| 275 |
+
def predizer(self, entradas: Dict[str, Any]) -> Dict[str, Any]:
|
| 276 |
+
"""
|
| 277 |
+
Detectar anomalias em dados de transparência
|
| 278 |
+
|
| 279 |
+
Args:
|
| 280 |
+
entradas: {
|
| 281 |
+
"dados_transacao": List[Dict],
|
| 282 |
+
"contexto": Optional[Dict]
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
Returns:
|
| 286 |
+
{
|
| 287 |
+
"score_anomalia": float,
|
| 288 |
+
"tipo_anomalia": str,
|
| 289 |
+
"confianca": float,
|
| 290 |
+
"explicacao": Dict
|
| 291 |
+
}
|
| 292 |
+
"""
|
| 293 |
+
pass
|
| 294 |
+
```
|
| 295 |
+
|
| 296 |
+
#### **Interface NER**
|
| 297 |
+
```python
|
| 298 |
+
class CidadaoBERTimauNER(CidadaoModeloBase):
|
| 299 |
+
def predizer(self, entradas: Dict[str, Any]) -> Dict[str, Any]:
|
| 300 |
+
"""
|
| 301 |
+
Extrair entidades nomeadas de documentos públicos brasileiros
|
| 302 |
+
|
| 303 |
+
Args:
|
| 304 |
+
entradas: {
|
| 305 |
+
"texto": str,
|
| 306 |
+
"idioma": Optional[str] = "pt"
|
| 307 |
+
}
|
| 308 |
+
|
| 309 |
+
Returns:
|
| 310 |
+
{
|
| 311 |
+
"entidades": List[Dict],
|
| 312 |
+
"scores_confianca": List[float],
|
| 313 |
+
"tempo_processamento": float
|
| 314 |
+
}
|
| 315 |
+
"""
|
| 316 |
+
pass
|
| 317 |
+
```
|
| 318 |
+
|
| 319 |
+
---
|
| 320 |
+
|
| 321 |
+
## 📊 **Sistema de Registry de Modelos**
|
| 322 |
+
|
| 323 |
+
### **Estrutura do registro_modelos.json**
|
| 324 |
+
|
| 325 |
+
```json
|
| 326 |
+
{
|
| 327 |
+
"versao": "1.0.0",
|
| 328 |
+
"ultima_atualizacao": "2025-07-22T10:00:00Z",
|
| 329 |
+
"modelos": {
|
| 330 |
+
"cidadao-detector-anomalias-v2": {
|
| 331 |
+
"metadados": {
|
| 332 |
+
"nome": "Cidadão.IA Detector de Anomalias",
|
| 333 |
+
"versao": "2.0.0",
|
| 334 |
+
"descricao": "Detecção avançada de anomalias para dados de transparência governamental",
|
| 335 |
+
"autor": "Anderson Henrique",
|
| 336 |
+
"criado_em": "2025-07-22T10:00:00Z",
|
| 337 |
+
"tipo_modelo": "detecção_anomalias",
|
| 338 |
+
"framework": "pytorch",
|
| 339 |
+
"modelo_base": "bert-base-portuguese-cased",
|
| 340 |
+
"tarefa": "classificacao_multiclasse",
|
| 341 |
+
"idioma": "pt-BR",
|
| 342 |
+
"dominio": "transparencia_governamental"
|
| 343 |
+
},
|
| 344 |
+
"performance": {
|
| 345 |
+
"acuracia": 0.94,
|
| 346 |
+
"precisao": 0.92,
|
| 347 |
+
"recall": 0.89,
|
| 348 |
+
"f1_score": 0.90,
|
| 349 |
+
"auc_roc": 0.96,
|
| 350 |
+
"tempo_inferencia_ms": 45
|
| 351 |
+
},
|
| 352 |
+
"deploy": {
|
| 353 |
+
"status": "producao",
|
| 354 |
+
"endpoint": "/api/v1/anomalia/detectar",
|
| 355 |
+
"replicas": 3,
|
| 356 |
+
"gpu_necessaria": false,
|
| 357 |
+
"memoria_mb": 512,
|
| 358 |
+
"cpu_cores": 2
|
| 359 |
+
},
|
| 360 |
+
"arquivos": {
|
| 361 |
+
"cartao_modelo": "modelos/cidadao-detector-anomalias-v2/README.md",
|
| 362 |
+
"pesos": "modelos/cidadao-detector-anomalias-v2/pytorch_model.bin",
|
| 363 |
+
"config": "modelos/cidadao-detector-anomalias-v2/config.json",
|
| 364 |
+
"tokenizer": "modelos/cidadao-detector-anomalias-v2/tokenizer.json",
|
| 365 |
+
"script_inferencia": "modelos/cidadao-detector-anomalias-v2/inferencia.py",
|
| 366 |
+
"requirements": "modelos/cidadao-detector-anomalias-v2/requirements.txt"
|
| 367 |
+
},
|
| 368 |
+
"validacao": {
|
| 369 |
+
"casos_teste": "testes/integracao/test_detector_anomalias.py",
|
| 370 |
+
"dataset_benchmark": "datasets/benchmark_transparencia_v1.json",
|
| 371 |
+
"status_validacao": "passou",
|
| 372 |
+
"ultima_validacao": "2025-07-22T09:30:00Z"
|
| 373 |
+
},
|
| 374 |
+
"huggingface": {
|
| 375 |
+
"model_id": "neural-thinker/cidadao-detector-anomalias-v2",
|
| 376 |
+
"privado": false,
|
| 377 |
+
"downloads": 1250,
|
| 378 |
+
"likes": 89
|
| 379 |
+
}
|
| 380 |
+
}
|
| 381 |
+
}
|
| 382 |
+
}
|
| 383 |
+
```
|
| 384 |
+
|
| 385 |
+
---
|
| 386 |
+
|
| 387 |
+
## 🚀 **Arquitetura de Integração HuggingFace (Implementada)**
|
| 388 |
+
|
| 389 |
+
### **🎯 Estratégia Principal: HuggingFace Hub + Spaces**
|
| 390 |
+
|
| 391 |
+
```
|
| 392 |
+
Fluxo de Deploy:
|
| 393 |
+
cidadao.ai-models → HuggingFace Models → cidadao.ai-backend (HF Spaces)
|
| 394 |
+
(dev) (storage) (production)
|
| 395 |
+
```
|
| 396 |
+
|
| 397 |
+
### **💻 Implementação no Backend (HF Spaces)**
|
| 398 |
+
|
| 399 |
+
```python
|
| 400 |
+
# No cidadao.ai-backend (HuggingFace Spaces)
|
| 401 |
+
from transformers import pipeline, AutoModel, AutoTokenizer
|
| 402 |
+
from functools import lru_cache
|
| 403 |
+
import torch
|
| 404 |
+
|
| 405 |
+
@lru_cache(maxsize=10) # Cache local para performance
|
| 406 |
+
def load_cidadao_model(model_name: str):
|
| 407 |
+
"""Carrega modelo do HuggingFace Models e cacheia localmente"""
|
| 408 |
+
return pipeline(
|
| 409 |
+
"text-classification",
|
| 410 |
+
model=f"neural-thinker/{model_name}",
|
| 411 |
+
device=0 if torch.cuda.is_available() else -1
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
# Uso nos Agentes Multi-Agent
|
| 415 |
+
class ObaluaieCorruptionAgent(BaseAgent):
|
| 416 |
+
def __init__(self):
|
| 417 |
+
self.detector = load_cidadao_model("cidadao-detector-anomalias-v2")
|
| 418 |
+
self.ner = load_cidadao_model("cidadao-bertimbau-ner-v1")
|
| 419 |
+
|
| 420 |
+
async def analyze_corruption(self, transaction_data):
|
| 421 |
+
# Inferência usando modelos do HF Hub
|
| 422 |
+
anomaly_result = self.detector(transaction_data)
|
| 423 |
+
entities = self.ner(transaction_data)
|
| 424 |
+
return self.generate_report(anomaly_result, entities)
|
| 425 |
+
```
|
| 426 |
+
|
| 427 |
+
### **📦 Deploy de Modelos no HuggingFace**
|
| 428 |
+
|
| 429 |
+
```bash
|
| 430 |
+
# Deploy automático via CLI
|
| 431 |
+
huggingface-cli login
|
| 432 |
+
huggingface-cli upload neural-thinker/cidadao-detector-anomalias-v2 ./models/detector-anomalias/
|
| 433 |
+
huggingface-cli upload neural-thinker/cidadao-bertimbau-ner-v1 ./models/ner/
|
| 434 |
+
```
|
| 435 |
+
|
| 436 |
+
### **🔄 Vantagens desta Arquitetura**
|
| 437 |
+
|
| 438 |
+
✅ **Zero Infraestrutura**: Sem servers ou containers para modelos
|
| 439 |
+
✅ **CDN Global**: HuggingFace distribui mundialmente
|
| 440 |
+
✅ **Cache Inteligente**: Modelos carregados sob demanda
|
| 441 |
+
✅ **Versionamento**: Controle automático de versões
|
| 442 |
+
✅ **Performance**: Mesmo poder computacional do HF Spaces
|
| 443 |
+
✅ **Escalabilidade**: Modelos disponíveis 24/7
|
| 444 |
+
✅ **Community**: Visibilidade e contribuições
|
| 445 |
+
|
| 446 |
+
### **📊 Métricas de Performance**
|
| 447 |
+
|
| 448 |
+
```python
|
| 449 |
+
# Monitoramento automático de modelos
|
| 450 |
+
import time
|
| 451 |
+
from functools import wraps
|
| 452 |
+
|
| 453 |
+
def track_model_performance(func):
|
| 454 |
+
@wraps(func)
|
| 455 |
+
def wrapper(*args, **kwargs):
|
| 456 |
+
start_time = time.time()
|
| 457 |
+
result = func(*args, **kwargs)
|
| 458 |
+
inference_time = time.time() - start_time
|
| 459 |
+
|
| 460 |
+
# Log métricas para Grafana/Prometheus
|
| 461 |
+
log_metric("model_inference_time", inference_time)
|
| 462 |
+
log_metric("model_usage_count", 1)
|
| 463 |
+
return result
|
| 464 |
+
return wrapper
|
| 465 |
+
|
| 466 |
+
@track_model_performance
|
| 467 |
+
def analyze_with_model(data):
|
| 468 |
+
return load_cidadao_model("cidadao-detector-anomalias-v2")(data)
|
| 469 |
+
```
|
| 470 |
+
|
| 471 |
+
---
|
| 472 |
+
|
| 473 |
+
## 🧪 **Estratégia de Testes**
|
| 474 |
+
|
| 475 |
+
### **Hierarquia de Testes**
|
| 476 |
+
|
| 477 |
+
```
|
| 478 |
+
testes/
|
| 479 |
+
├── unitarios/ # Testes rápidos e isolados
|
| 480 |
+
│ ├── test_interfaces_modelos.py # Contratos de interface
|
| 481 |
+
│ ├── test_preprocessamento.py # Processamento de dados
|
| 482 |
+
│ └── test_pos_processamento.py # Processamento de saída
|
| 483 |
+
├── integracao/ # Testes de interação de componentes
|
| 484 |
+
│ ├── test_pipelines_modelos.py # Pipelines end-to-end
|
| 485 |
+
│ ├── test_endpoints_api.py # Integração da API
|
| 486 |
+
│ └── test_integracao_backend.py # Compatibilidade com backend
|
| 487 |
+
├── performance/ # Testes de performance e carga
|
| 488 |
+
│ ├── test_velocidade_inferencia.py # Benchmarks de latência
|
| 489 |
+
│ ├── test_uso_memoria.py # Profiling de memória
|
| 490 |
+
│ └── test_throughput.py # Requisições concorrentes
|
| 491 |
+
└── validacao/ # Testes de acurácia de modelos
|
| 492 |
+
├── test_acuracia_modelo.py # Validação de acurácia
|
| 493 |
+
├── test_casos_extremos.py # Tratamento de edge cases
|
| 494 |
+
└── test_drift_dados.py # Detecção de shift de distribuição
|
| 495 |
+
```
|
| 496 |
+
|
| 497 |
+
### **Pipeline de Testes Contínuos**
|
| 498 |
+
|
| 499 |
+
```yaml
|
| 500 |
+
# .github/workflows/testes.yml
|
| 501 |
+
name: Pipeline de Testes de Modelos
|
| 502 |
+
on: [push, pull_request]
|
| 503 |
+
|
| 504 |
+
jobs:
|
| 505 |
+
testes-unitarios:
|
| 506 |
+
runs-on: ubuntu-latest
|
| 507 |
+
steps:
|
| 508 |
+
- uses: actions/checkout@v3
|
| 509 |
+
- name: Executar testes unitários
|
| 510 |
+
run: pytest testes/unitarios/ -v --cov=modelos
|
| 511 |
+
|
| 512 |
+
validacao-modelos:
|
| 513 |
+
runs-on: ubuntu-latest
|
| 514 |
+
steps:
|
| 515 |
+
- name: Validar acurácia dos modelos
|
| 516 |
+
run: pytest testes/validacao/ -v
|
| 517 |
+
- name: Benchmarks de performance
|
| 518 |
+
run: pytest testes/performance/ -v
|
| 519 |
+
|
| 520 |
+
testes-integracao:
|
| 521 |
+
runs-on: ubuntu-latest
|
| 522 |
+
steps:
|
| 523 |
+
- name: Testar integração com backend
|
| 524 |
+
run: pytest testes/integracao/ -v
|
| 525 |
+
```
|
| 526 |
+
|
| 527 |
+
---
|
| 528 |
+
|
| 529 |
+
## 🚀 **Estratégias de Deploy**
|
| 530 |
+
|
| 531 |
+
### **Desenvolvimento Local**
|
| 532 |
+
```bash
|
| 533 |
+
# Início rápido para desenvolvimento
|
| 534 |
+
docker-compose up -d
|
| 535 |
+
# Acessar modelos em http://localhost:8001
|
| 536 |
+
```
|
| 537 |
+
|
| 538 |
+
### **Ambiente de Staging**
|
| 539 |
+
```bash
|
| 540 |
+
# Deploy Kubernetes
|
| 541 |
+
kubectl apply -f deploy/kubernetes/staging/
|
| 542 |
+
# Service mesh Istio para testes A/B
|
| 543 |
+
kubectl apply -f deploy/istio/
|
| 544 |
+
```
|
| 545 |
+
|
| 546 |
+
### **Deploy de Produção**
|
| 547 |
+
```bash
|
| 548 |
+
# Deploy blue-green
|
| 549 |
+
./deploy/scripts/blue_green_deploy.sh cidadao-detector-anomalias-v2
|
| 550 |
+
# Rollout canary
|
| 551 |
+
./deploy/scripts/canary_deploy.sh --divisao-trafego=10%
|
| 552 |
+
```
|
| 553 |
+
|
| 554 |
+
---
|
| 555 |
+
|
| 556 |
+
## 📈 **Monitoramento & Observabilidade**
|
| 557 |
+
|
| 558 |
+
### **Métricas de Performance de Modelos**
|
| 559 |
+
|
| 560 |
+
```python
|
| 561 |
+
# Tracking automático de performance
|
| 562 |
+
@track_performance
|
| 563 |
+
def predizer(self, entradas):
|
| 564 |
+
# Automaticamente rastreia:
|
| 565 |
+
# - Latência de inferência
|
| 566 |
+
# - Uso de memória
|
| 567 |
+
# - Distribuição de confiança das predições
|
| 568 |
+
# - Shapes dos dados de entrada/saída
|
| 569 |
+
# - Taxa de erros
|
| 570 |
+
pass
|
| 571 |
+
```
|
| 572 |
+
|
| 573 |
+
### **Dashboard de Métricas de Negócio**
|
| 574 |
+
|
| 575 |
+
```yaml
|
| 576 |
+
# Configuração dashboard Grafana
|
| 577 |
+
dashboards:
|
| 578 |
+
- nome: "Performance dos Modelos"
|
| 579 |
+
paineis:
|
| 580 |
+
- latencia_inferencia_p95
|
| 581 |
+
- acuracia_predicao
|
| 582 |
+
- score_drift_modelo
|
| 583 |
+
- volume_requisicoes
|
| 584 |
+
- taxa_erro
|
| 585 |
+
|
| 586 |
+
- nome: "Impacto de Negócio"
|
| 587 |
+
paineis:
|
| 588 |
+
- anomalias_detectadas_diariamente
|
| 589 |
+
- taxa_sucesso_investigacoes
|
| 590 |
+
- taxa_falsos_positivos
|
| 591 |
+
- score_satisfacao_usuario
|
| 592 |
+
```
|
| 593 |
+
|
| 594 |
+
---
|
| 595 |
+
|
| 596 |
+
## 🔮 **Aprimoramentos Futuros**
|
| 597 |
+
|
| 598 |
+
### **Roadmap para os Próximos 6 Meses**
|
| 599 |
+
|
| 600 |
+
1. **Q3 2025**:
|
| 601 |
+
- Modelos multimodais (texto + dados tabulares)
|
| 602 |
+
- Atualizações de modelo em tempo real via streaming
|
| 603 |
+
- Otimização para deploy em edge
|
| 604 |
+
|
| 605 |
+
2. **Q4 2025**:
|
| 606 |
+
- Aprendizado federado para treinamento preservando privacidade
|
| 607 |
+
- Pipeline AutoML para busca de arquitetura de modelos
|
| 608 |
+
- Explicabilidade avançada com inferência causal
|
| 609 |
+
|
| 610 |
+
3. **Q1 2026**:
|
| 611 |
+
- Integração com backends de computação quântica
|
| 612 |
+
- Pipeline de fine-tuning de large language models
|
| 613 |
+
- Plataforma de colaboração inter-governamental
|
| 614 |
+
|
| 615 |
+
---
|
| 616 |
+
|
| 617 |
+
## 💡 **Áreas de Inovação**
|
| 618 |
+
|
| 619 |
+
### **Oportunidades de Pesquisa**
|
| 620 |
+
- **IA Causal**: Entender relações causa-efeito em dados governamentais
|
| 621 |
+
- **Meta-Learning**: Aprendizado few-shot para novos domínios governamentais
|
| 622 |
+
- **Robustez Adversarial**: Defesa contra manipulação de dados
|
| 623 |
+
- **IA Interpretável**: Construir confiança através de transparência
|
| 624 |
+
|
| 625 |
+
### **Exploração Tecnológica**
|
| 626 |
+
- **Redes Neurais de Grafos**: Modelar relacionamentos entre entidades
|
| 627 |
+
- **Transformers para Séries Temporais**: Reconhecimento avançado de padrões temporais
|
| 628 |
+
- **Fusão Multimodal**: Combinar dados de texto, numéricos e imagem
|
| 629 |
+
- **Aprendizado por Reforço**: Estratégias adaptativas de investigação
|
| 630 |
+
|
| 631 |
+
---
|
| 632 |
+
|
| 633 |
+
## 📊 **Métricas de Performance e Sucesso**
|
| 634 |
+
|
| 635 |
+
### **💻 KPIs Técnicos (HuggingFace Integration)**
|
| 636 |
+
- **Latência de Download**: < 2s para primeiro carregamento
|
| 637 |
+
- **Latência de Inferência**: < 100ms no HF Spaces
|
| 638 |
+
- **Cache Hit Rate**: > 90% para modelos frequentes
|
| 639 |
+
- **Acurácia de Modelos**: > 95% no conjunto de validação
|
| 640 |
+
- **Disponibilidade**: 99.9% via CDN HuggingFace
|
| 641 |
+
- **Throughput**: > 1000 inferências/min por modelo
|
| 642 |
+
|
| 643 |
+
### **🎯 KPIs de Negócio (Impacto Real)**
|
| 644 |
+
- **50%** ⬆️ na acurácia de detecção de anomalias
|
| 645 |
+
- **30%** ⬇️ na taxa de falsos positivos
|
| 646 |
+
- **25%** ⬆️ na eficiência de investigações
|
| 647 |
+
- **90%** score de satisfação do usuário
|
| 648 |
+
- **15** agentes multi-agent usando modelos especializados
|
| 649 |
+
|
| 650 |
+
### **🌍 KPIs de Community (HuggingFace)**
|
| 651 |
+
- **Downloads**: > 10K/mês por modelo principal
|
| 652 |
+
- **Likes**: > 100 por modelo
|
| 653 |
+
- **Contributors**: > 5 colaboradores ativos
|
| 654 |
+
- **Model Cards**: Documentação completa 100% modelos
|
| 655 |
+
|
| 656 |
+
---
|
| 657 |
+
|
| 658 |
+
## 🚀 **Roadmap de Implementação Atualizado**
|
| 659 |
+
|
| 660 |
+
### **📋 Fase 1: Setup HuggingFace (Esta Semana)**
|
| 661 |
+
- ✅ **Estrutura do repositório** definida
|
| 662 |
+
- 🔄 **HuggingFace CLI** configurado
|
| 663 |
+
- 🔄 **CI/CD pipeline** para auto-deploy HF Models
|
| 664 |
+
- 🔄 **Model cards** templates criados
|
| 665 |
+
|
| 666 |
+
### **🤖 Fase 2: Migração de Modelos (Próximas 2 Semanas)**
|
| 667 |
+
- 🔄 **cidadao-detector-anomalias-v2** → HF Models
|
| 668 |
+
- 🔄 **cidadao-bertimbau-ner-v1** → HF Models
|
| 669 |
+
- 🔄 **cidadao-classificador-risco-v1** → HF Models
|
| 670 |
+
- 🔄 **Integração** com backend via transformers
|
| 671 |
+
|
| 672 |
+
### **⚡ Fase 3: Otimização (Mês 2)**
|
| 673 |
+
- 🔄 **ONNX export** para performance
|
| 674 |
+
- 🔄 **Quantização** para memória
|
| 675 |
+
- 🔄 **Cache inteligente** no backend
|
| 676 |
+
- 🔄 **Métricas** Prometheus integradas
|
| 677 |
+
|
| 678 |
+
### **🌍 Governança Simplificada**
|
| 679 |
+
|
| 680 |
+
**👨💻 Responsável Principal**: Anderson Henrique
|
| 681 |
+
**📝 Processo**:
|
| 682 |
+
1. Desenvolver modelo localmente
|
| 683 |
+
2. Testar integração com backend
|
| 684 |
+
3. Deploy automático HF Models
|
| 685 |
+
4. Atualizar backend para usar nova versão
|
| 686 |
+
5. Monitorar performance em produção
|
| 687 |
+
|
| 688 |
+
---
|
| 689 |
+
|
| 690 |
+
## 🔧 **Próximos Passos Imediatos**
|
| 691 |
+
|
| 692 |
+
### **Esta Semana (22-28 Jul 2025)**
|
| 693 |
+
1. **Criar estrutura inicial do repositório** com diretórios base
|
| 694 |
+
2. **Configurar ambiente de desenvolvimento** com Docker e requirements
|
| 695 |
+
3. **Implementar sistema básico de registry** de modelos
|
| 696 |
+
4. **Documentar padrões de interface** para todos os tipos de modelos
|
| 697 |
+
|
| 698 |
+
### **Próxima Semana (29 Jul - 4 Ago 2025)**
|
| 699 |
+
1. **Migrar primeiro modelo** (detector de anomalias) do backend
|
| 700 |
+
2. **Criar model card completo** com documentação técnica
|
| 701 |
+
3. **Implementar testes básicos** de validação
|
| 702 |
+
4. **Configurar CI/CD pipeline** no GitHub Actions
|
| 703 |
+
|
| 704 |
+
### **Sprint 1 (5-18 Ago 2025)**
|
| 705 |
+
1. **Migrar todos os modelos principais** do backend
|
| 706 |
+
2. **Implementar pipelines de inferência** para cada modelo
|
| 707 |
+
3. **Criar integração com backend** via submódulo Git
|
| 708 |
+
4. **Configurar monitoramento básico** de performance
|
| 709 |
+
|
| 710 |
+
---
|
| 711 |
+
|
| 712 |
+
---
|
| 713 |
+
|
| 714 |
+
## 🎆 **Conclusão: Hub de Modelos de Classe Mundial**
|
| 715 |
+
|
| 716 |
+
O **cidadao.ai-models** representa uma **evolução arquitetural** no ecossistema Cidadão.IA, combinando:
|
| 717 |
+
|
| 718 |
+
✨ **Simplicidade**: Deploy direto via HuggingFace Models
|
| 719 |
+
🚀 **Performance**: Zero infraestrutura, CDN global
|
| 720 |
+
🤖 **Integração**: Seamless com backend via transformers
|
| 721 |
+
🌍 **Community**: Visibilidade e contribuições abertas
|
| 722 |
+
📊 **Escalabilidade**: Modelos disponíveis 24/7 mundialmente
|
| 723 |
+
|
| 724 |
+
### **🎯 Impacto Esperado**
|
| 725 |
+
- **15 agentes** do backend usando modelos especializados
|
| 726 |
+
- **>95% acurácia** na detecção de anomalias governamentais
|
| 727 |
+
- **<100ms** latência de inferência em produção
|
| 728 |
+
- **Zero custos** de infraestrutura para serving de modelos
|
| 729 |
+
- **Democratização** da IA para transparência no Brasil
|
| 730 |
+
|
| 731 |
+
*Esta arquitetura estabelece o **primeiro hub de modelos de IA governamental** do Brasil, integrando seamlessly com HuggingFace para criar uma plataforma de transparência de classe mundial.*
|
| 732 |
+
|
| 733 |
+
**📄 Versão do Documento**: 2.0.0 (HuggingFace Native)
|
| 734 |
+
**🗓️ Última Atualização**: 23 de Julho, 2025
|
| 735 |
+
**🔄 Próxima Revisão**: 30 de Julho, 2025 (Pós primeiro deploy)
|
Dockerfile
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Dockerfile for HuggingFace Spaces - Cidadão.AI Models
|
| 2 |
+
FROM python:3.11-slim
|
| 3 |
+
|
| 4 |
+
# Set environment variables
|
| 5 |
+
ENV PYTHONUNBUFFERED=1
|
| 6 |
+
ENV PYTHONDONTWRITEBYTECODE=1
|
| 7 |
+
ENV PORT=8001
|
| 8 |
+
|
| 9 |
+
# Install system dependencies
|
| 10 |
+
RUN apt-get update && apt-get install -y \
|
| 11 |
+
curl \
|
| 12 |
+
git \
|
| 13 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 14 |
+
|
| 15 |
+
# Create app user for security
|
| 16 |
+
RUN useradd --create-home --shell /bin/bash app
|
| 17 |
+
|
| 18 |
+
# Set work directory
|
| 19 |
+
WORKDIR /app
|
| 20 |
+
|
| 21 |
+
# Copy requirements and install Python dependencies
|
| 22 |
+
COPY requirements-hf.txt ./
|
| 23 |
+
RUN pip install --no-cache-dir --upgrade pip && \
|
| 24 |
+
pip install --no-cache-dir -r requirements-hf.txt
|
| 25 |
+
|
| 26 |
+
# Copy application code
|
| 27 |
+
COPY src/ ./src/
|
| 28 |
+
COPY app.py ./
|
| 29 |
+
|
| 30 |
+
# Create necessary directories and set permissions
|
| 31 |
+
RUN mkdir -p logs models data && \
|
| 32 |
+
chown -R app:app /app
|
| 33 |
+
|
| 34 |
+
# Switch to app user
|
| 35 |
+
USER app
|
| 36 |
+
|
| 37 |
+
# Expose port for HuggingFace Spaces
|
| 38 |
+
EXPOSE 8001
|
| 39 |
+
|
| 40 |
+
# Health check
|
| 41 |
+
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
|
| 42 |
+
CMD curl -f http://localhost:8001/health || exit 1
|
| 43 |
+
|
| 44 |
+
# Run application
|
| 45 |
+
CMD ["python", "app.py"]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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Cidadão.AI Models
|
| 3 |
+
emoji: 🤖
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: green
|
| 6 |
+
sdk: docker
|
| 7 |
+
app_port: 8001
|
| 8 |
+
pinned: false
|
| 9 |
+
license: mit
|
| 10 |
+
tags:
|
| 11 |
+
- transparency
|
| 12 |
+
- government
|
| 13 |
+
- brazil
|
| 14 |
+
- anomaly-detection
|
| 15 |
+
- fastapi
|
| 16 |
+
---
|
| 17 |
+
|
| 18 |
+
# 🤖 Cidadão.AI Models
|
| 19 |
+
|
| 20 |
+
> **Modelos especializados de Machine Learning para análise de transparência pública brasileira**
|
| 21 |
+
|
| 22 |
+
[](https://www.python.org/downloads/)
|
| 23 |
+
[](https://pytorch.org/)
|
| 24 |
+
[](https://huggingface.co/transformers/)
|
| 25 |
+
[](LICENSE)
|
| 26 |
+
|
| 27 |
+
## 🎯 Visão Geral
|
| 28 |
+
|
| 29 |
+
**Cidadão.AI Models** é o repositório especializado em modelos de machine learning para o ecossistema Cidadão.AI. Contém modelos customizados, pipeline de treinamento MLOps e infraestrutura de inferência para análise avançada de dados de transparência pública.
|
| 30 |
+
|
| 31 |
+
### 🚀 Capacidades Principais
|
| 32 |
+
|
| 33 |
+
- 🔍 **Detecção de Anomalias** - Identificação automática de padrões suspeitos em contratos públicos
|
| 34 |
+
- 📊 **Análise de Padrões** - Reconhecimento de correlações e tendências em dados governamentais
|
| 35 |
+
- 🌊 **Análise Espectral** - Detecção de padrões temporais e sazonais via FFT
|
| 36 |
+
- 🤖 **Modelos Customizados** - Arquiteturas especializadas para transparência brasileira
|
| 37 |
+
- 🔄 **Pipeline MLOps** - Treinamento, versionamento e deploy automatizados
|
| 38 |
+
|
| 39 |
+
## 🏗️ Arquitetura
|
| 40 |
+
|
| 41 |
+
```
|
| 42 |
+
src/
|
| 43 |
+
├── models/ # Modelos de ML especializados
|
| 44 |
+
│ ├── anomaly_detection/ # Detecção de anomalias
|
| 45 |
+
│ ├── pattern_analysis/ # Análise de padrões
|
| 46 |
+
│ ├── spectral_analysis/ # Análise espectral
|
| 47 |
+
│ └── core/ # Classes base e utilitários
|
| 48 |
+
├── training/ # Pipeline de treinamento
|
| 49 |
+
│ ├── pipelines/ # Pipelines de treinamento
|
| 50 |
+
│ ├── configs/ # Configurações de modelos
|
| 51 |
+
│ └── utils/ # Utilitários de treinamento
|
| 52 |
+
├── inference/ # Servidor de inferência
|
| 53 |
+
│ ├── api_server.py # FastAPI server
|
| 54 |
+
│ ├── batch_processor.py # Processamento em lote
|
| 55 |
+
│ └── streaming.py # Inferência em tempo real
|
| 56 |
+
└── deployment/ # Ferramentas de deploy
|
| 57 |
+
├── huggingface/ # Integração HuggingFace Hub
|
| 58 |
+
├── docker/ # Containerização
|
| 59 |
+
└── monitoring/ # Monitoramento de modelos
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
## 🚀 Quick Start
|
| 63 |
+
|
| 64 |
+
### Instalação
|
| 65 |
+
|
| 66 |
+
```bash
|
| 67 |
+
# Clone o repositório
|
| 68 |
+
git clone https://github.com/anderson-ufrj/cidadao.ai-models
|
| 69 |
+
cd cidadao.ai-models
|
| 70 |
+
|
| 71 |
+
# Instale as dependências
|
| 72 |
+
pip install -r requirements.txt
|
| 73 |
+
|
| 74 |
+
# Instale o pacote em modo desenvolvimento
|
| 75 |
+
pip install -e .
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
### Uso Básico
|
| 79 |
+
|
| 80 |
+
```python
|
| 81 |
+
from cidadao_models.models.anomaly_detection import AnomalyDetector
|
| 82 |
+
from cidadao_models.models.pattern_analysis import PatternAnalyzer
|
| 83 |
+
|
| 84 |
+
# Inicializar modelos
|
| 85 |
+
anomaly_detector = AnomalyDetector()
|
| 86 |
+
pattern_analyzer = PatternAnalyzer()
|
| 87 |
+
|
| 88 |
+
# Analisar contratos para anomalias
|
| 89 |
+
contracts = [...] # Lista de contratos
|
| 90 |
+
anomalies = anomaly_detector.analyze(contracts)
|
| 91 |
+
|
| 92 |
+
# Analisar padrões temporais
|
| 93 |
+
patterns = pattern_analyzer.analyze_temporal_patterns(data)
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
### Servidor de Inferência
|
| 97 |
+
|
| 98 |
+
```bash
|
| 99 |
+
# Iniciar servidor API
|
| 100 |
+
uvicorn src.inference.api_server:app --host 0.0.0.0 --port 8001
|
| 101 |
+
|
| 102 |
+
# Testar endpoint
|
| 103 |
+
curl -X POST "http://localhost:8001/v1/detect-anomalies" \
|
| 104 |
+
-H "Content-Type: application/json" \
|
| 105 |
+
-d '{"contracts": [...]}'
|
| 106 |
+
```
|
| 107 |
+
|
| 108 |
+
## 🧠 Modelos Disponíveis
|
| 109 |
+
|
| 110 |
+
### 🔍 Detector de Anomalias
|
| 111 |
+
- **Algoritmos**: Isolation Forest, One-Class SVM, Local Outlier Factor
|
| 112 |
+
- **Especialização**: Contratos públicos brasileiros
|
| 113 |
+
- **Métricas**: Precisão >90% para anomalias críticas
|
| 114 |
+
|
| 115 |
+
### 📊 Analisador de Padrões
|
| 116 |
+
- **Capacidades**: Time series, correlações, clustering
|
| 117 |
+
- **Técnicas**: Prophet, FFT, decomposição sazonal
|
| 118 |
+
- **Output**: Padrões temporais e insights explicáveis
|
| 119 |
+
|
| 120 |
+
### 🌊 Analisador Espectral
|
| 121 |
+
- **Método**: Transformada rápida de Fourier (FFT)
|
| 122 |
+
- **Detecção**: Padrões periódicos suspeitos
|
| 123 |
+
- **Aplicação**: Irregularidades sazonais em gastos
|
| 124 |
+
|
| 125 |
+
## 🛠️ Desenvolvimento
|
| 126 |
+
|
| 127 |
+
### Estrutura de Testes
|
| 128 |
+
|
| 129 |
+
```bash
|
| 130 |
+
# Executar todos os testes
|
| 131 |
+
pytest tests/
|
| 132 |
+
|
| 133 |
+
# Testes específicos
|
| 134 |
+
pytest tests/unit/models/
|
| 135 |
+
pytest tests/integration/
|
| 136 |
+
pytest tests/e2e/
|
| 137 |
+
```
|
| 138 |
+
|
| 139 |
+
### Treinamento de Modelos
|
| 140 |
+
|
| 141 |
+
```bash
|
| 142 |
+
# Treinar modelo de detecção de corrupção
|
| 143 |
+
python src/training/pipelines/train_corruption_detector.py --config configs/corruption_bert.yaml
|
| 144 |
+
|
| 145 |
+
# Avaliar performance
|
| 146 |
+
python src/training/evaluate.py --model corruption_detector --test_data data/test.json
|
| 147 |
+
```
|
| 148 |
+
|
| 149 |
+
### Deploy HuggingFace
|
| 150 |
+
|
| 151 |
+
```bash
|
| 152 |
+
# Upload para HuggingFace Hub
|
| 153 |
+
python src/deployment/huggingface/upload.py --model_path models/anomaly_detector --repo_name cidadao-ai/anomaly-detector
|
| 154 |
+
```
|
| 155 |
+
|
| 156 |
+
## 🔄 Integração com Backend
|
| 157 |
+
|
| 158 |
+
Este repositório se integra com o [cidadao.ai-backend](https://github.com/anderson-ufrj/cidadao.ai-backend) através de:
|
| 159 |
+
|
| 160 |
+
- **API REST**: Servidor de inferência FastAPI
|
| 161 |
+
- **Package Integration**: Importação direta como dependência
|
| 162 |
+
- **Fallback Local**: Processamento local se API indisponível
|
| 163 |
+
|
| 164 |
+
```python
|
| 165 |
+
# No backend
|
| 166 |
+
from src.tools.models_client import ModelsClient
|
| 167 |
+
|
| 168 |
+
client = ModelsClient("http://models-api:8001")
|
| 169 |
+
results = await client.detect_anomalies(contracts)
|
| 170 |
+
```
|
| 171 |
+
|
| 172 |
+
## 📊 MLOps Pipeline
|
| 173 |
+
|
| 174 |
+
### Treinamento Automatizado
|
| 175 |
+
- ⚡ **CI/CD**: Pipeline automatizado GitHub Actions
|
| 176 |
+
- 📈 **Experiment Tracking**: MLflow + Weights & Biases
|
| 177 |
+
- 🔄 **Model Versioning**: HuggingFace Hub integration
|
| 178 |
+
- 📊 **Performance Monitoring**: Drift detection + alerting
|
| 179 |
+
|
| 180 |
+
### Deployment
|
| 181 |
+
- 🐳 **Containerização**: Docker para produção
|
| 182 |
+
- 🤗 **HuggingFace Spaces**: Demo models deployment
|
| 183 |
+
- 🚀 **Kubernetes**: Orquestração escalável
|
| 184 |
+
- 📡 **Monitoring**: Prometheus metrics + Grafana dashboards
|
| 185 |
+
|
| 186 |
+
## 🔗 Links Relacionados
|
| 187 |
+
|
| 188 |
+
- 🏛️ **Backend**: [cidadao.ai-backend](https://github.com/anderson-ufrj/cidadao.ai-backend)
|
| 189 |
+
- 🎨 **Frontend**: [cidadao.ai-frontend](https://github.com/anderson-ufrj/cidadao.ai-frontend)
|
| 190 |
+
- 📚 **Documentação**: [cidadao.ai-docs](https://github.com/anderson-ufrj/cidadao.ai-docs)
|
| 191 |
+
- 🤗 **HuggingFace**: [cidadao-ai organization](https://huggingface.co/cidadao-ai)
|
| 192 |
+
|
| 193 |
+
## 📈 Status do Projeto
|
| 194 |
+
|
| 195 |
+
- ✅ **Estrutura Base**: Completa
|
| 196 |
+
- 🔄 **Migração ML**: Em andamento
|
| 197 |
+
- ⏳ **API Server**: Planejado
|
| 198 |
+
- ⏳ **HF Integration**: Próximo
|
| 199 |
+
|
| 200 |
+
## 👨💻 Contribuição
|
| 201 |
+
|
| 202 |
+
1. Fork o projeto
|
| 203 |
+
2. Crie uma branch para sua feature (`git checkout -b feature/AmazingFeature`)
|
| 204 |
+
3. Commit suas mudanças (`git commit -m 'feat: add amazing feature'`)
|
| 205 |
+
4. Push para a branch (`git push origin feature/AmazingFeature`)
|
| 206 |
+
5. Abra um Pull Request
|
| 207 |
+
|
| 208 |
+
## 📄 Licença
|
| 209 |
+
|
| 210 |
+
Distribuído sob a licença MIT. Veja `LICENSE` para mais informações.
|
| 211 |
+
|
| 212 |
+
## 👨💻 Autor
|
| 213 |
+
|
| 214 |
+
**Anderson Henrique da Silva**
|
| 215 |
+
📧 [email protected] | 💻 [GitHub](https://github.com/anderson-ufrj)
|
| 216 |
+
|
| 217 |
+
---
|
| 218 |
+
|
| 219 |
+
<div align="center">
|
| 220 |
+
<h3>🧠 Democratizando Análise de Transparência com IA Avançada 🧠</h3>
|
| 221 |
+
<p><em>Modelos • MLOps • Explicável • Brasileira</em></p>
|
| 222 |
+
</div>
|
app.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Cidadão.AI Models - HuggingFace Spaces Entry Point
|
| 4 |
+
|
| 5 |
+
FastAPI server for ML model inference optimized for HuggingFace Spaces deployment.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import os
|
| 9 |
+
import sys
|
| 10 |
+
import logging
|
| 11 |
+
from contextlib import asynccontextmanager
|
| 12 |
+
|
| 13 |
+
import uvicorn
|
| 14 |
+
from fastapi import FastAPI, HTTPException
|
| 15 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 16 |
+
from fastapi.responses import JSONResponse, HTMLResponse
|
| 17 |
+
|
| 18 |
+
# Configure logging for HuggingFace
|
| 19 |
+
logging.basicConfig(
|
| 20 |
+
level=logging.INFO,
|
| 21 |
+
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
| 22 |
+
handlers=[logging.StreamHandler(sys.stdout)]
|
| 23 |
+
)
|
| 24 |
+
logger = logging.getLogger(__name__)
|
| 25 |
+
|
| 26 |
+
# Import our API server
|
| 27 |
+
try:
|
| 28 |
+
from src.inference.api_server import app as models_app
|
| 29 |
+
MODELS_AVAILABLE = True
|
| 30 |
+
logger.info("✅ Models API successfully imported")
|
| 31 |
+
except Exception as e:
|
| 32 |
+
logger.error(f"❌ Failed to import models API: {e}")
|
| 33 |
+
MODELS_AVAILABLE = False
|
| 34 |
+
|
| 35 |
+
@asynccontextmanager
|
| 36 |
+
async def lifespan(app: FastAPI):
|
| 37 |
+
"""Application lifespan manager for HuggingFace Spaces."""
|
| 38 |
+
logger.info("🚀 Starting Cidadão.AI Models on HuggingFace Spaces")
|
| 39 |
+
logger.info(f"🔧 Environment: {os.getenv('SPACE_ID', 'local')}")
|
| 40 |
+
logger.info(f"🌐 Port: {os.getenv('PORT', '8001')}")
|
| 41 |
+
|
| 42 |
+
yield
|
| 43 |
+
|
| 44 |
+
logger.info("🛑 Shutting down Cidadão.AI Models")
|
| 45 |
+
|
| 46 |
+
if MODELS_AVAILABLE:
|
| 47 |
+
# Use the imported models app
|
| 48 |
+
app = models_app
|
| 49 |
+
logger.info("Using full models API")
|
| 50 |
+
else:
|
| 51 |
+
# Fallback minimal app
|
| 52 |
+
app = FastAPI(
|
| 53 |
+
title="🤖 Cidadão.AI Models (Fallback)",
|
| 54 |
+
description="Minimal fallback API when models are not available",
|
| 55 |
+
version="1.0.0",
|
| 56 |
+
lifespan=lifespan
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
app.add_middleware(
|
| 60 |
+
CORSMiddleware,
|
| 61 |
+
allow_origins=["*"],
|
| 62 |
+
allow_credentials=True,
|
| 63 |
+
allow_methods=["*"],
|
| 64 |
+
allow_headers=["*"],
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
@app.get("/", response_class=HTMLResponse)
|
| 68 |
+
async def fallback_root():
|
| 69 |
+
"""Fallback root with information about the service."""
|
| 70 |
+
return """
|
| 71 |
+
<html>
|
| 72 |
+
<head>
|
| 73 |
+
<title>Cidadão.AI Models</title>
|
| 74 |
+
<style>
|
| 75 |
+
body { font-family: Arial, sans-serif; margin: 40px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
|
| 76 |
+
.container { max-width: 800px; margin: 0 auto; padding: 20px; background: rgba(255,255,255,0.1); border-radius: 10px; }
|
| 77 |
+
h1 { font-size: 2.5em; margin-bottom: 10px; }
|
| 78 |
+
.emoji { font-size: 1.2em; }
|
| 79 |
+
.status { background: rgba(255,255,255,0.2); padding: 15px; border-radius: 5px; margin: 20px 0; }
|
| 80 |
+
.endpoint { background: rgba(0,0,0,0.2); padding: 10px; border-radius: 5px; margin: 10px 0; font-family: monospace; }
|
| 81 |
+
</style>
|
| 82 |
+
</head>
|
| 83 |
+
<body>
|
| 84 |
+
<div class="container">
|
| 85 |
+
<h1>🤖 Cidadão.AI Models</h1>
|
| 86 |
+
<p><strong>Sistema de ML para Transparência Pública Brasileira</strong></p>
|
| 87 |
+
|
| 88 |
+
<div class="status">
|
| 89 |
+
<h3>📊 Status do Sistema</h3>
|
| 90 |
+
<p>⚠️ Modo Fallback - Modelos ML não disponíveis</p>
|
| 91 |
+
<p>🔧 Para funcionalidade completa, verifique as dependências</p>
|
| 92 |
+
</div>
|
| 93 |
+
|
| 94 |
+
<div class="status">
|
| 95 |
+
<h3>🔗 Endpoints Disponíveis</h3>
|
| 96 |
+
<div class="endpoint">GET /health - Health check</div>
|
| 97 |
+
<div class="endpoint">GET /docs - Documentação da API</div>
|
| 98 |
+
<div class="endpoint">GET / - Esta página</div>
|
| 99 |
+
</div>
|
| 100 |
+
|
| 101 |
+
<div class="status">
|
| 102 |
+
<h3>🏛️ Sobre o Cidadão.AI</h3>
|
| 103 |
+
<p>Sistema multi-agente de IA para análise de transparência pública,
|
| 104 |
+
especializado em detectar anomalias e padrões suspeitos em dados
|
| 105 |
+
governamentais brasileiros.</p>
|
| 106 |
+
</div>
|
| 107 |
+
|
| 108 |
+
<p style="text-align: center; margin-top: 40px;">
|
| 109 |
+
<a href="/docs" style="color: white; text-decoration: underline;">
|
| 110 |
+
📚 Ver Documentação da API
|
| 111 |
+
</a>
|
| 112 |
+
</p>
|
| 113 |
+
</div>
|
| 114 |
+
</body>
|
| 115 |
+
</html>
|
| 116 |
+
"""
|
| 117 |
+
|
| 118 |
+
@app.get("/health")
|
| 119 |
+
async def fallback_health():
|
| 120 |
+
"""Fallback health check."""
|
| 121 |
+
return {
|
| 122 |
+
"status": "limited",
|
| 123 |
+
"mode": "fallback",
|
| 124 |
+
"models_loaded": False,
|
| 125 |
+
"message": "Models not available, running in fallback mode"
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
logger.info("Using fallback minimal API")
|
| 129 |
+
|
| 130 |
+
# Add HuggingFace Spaces specific routes
|
| 131 |
+
@app.get("/spaces-info")
|
| 132 |
+
async def spaces_info():
|
| 133 |
+
"""HuggingFace Spaces specific information."""
|
| 134 |
+
return {
|
| 135 |
+
"platform": "HuggingFace Spaces",
|
| 136 |
+
"space_id": os.getenv("SPACE_ID", "unknown"),
|
| 137 |
+
"space_author": os.getenv("SPACE_AUTHOR", "cidadao-ai"),
|
| 138 |
+
"space_title": os.getenv("SPACE_TITLE", "Cidadão.AI Models"),
|
| 139 |
+
"sdk": "docker",
|
| 140 |
+
"port": int(os.getenv("PORT", "8001")),
|
| 141 |
+
"models_available": MODELS_AVAILABLE
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
if __name__ == "__main__":
|
| 145 |
+
# Configuration for HuggingFace Spaces
|
| 146 |
+
port = int(os.getenv("PORT", "8001"))
|
| 147 |
+
host = os.getenv("HOST", "0.0.0.0")
|
| 148 |
+
|
| 149 |
+
logger.info(f"🚀 Starting server on {host}:{port}")
|
| 150 |
+
logger.info(f"📊 Models available: {MODELS_AVAILABLE}")
|
| 151 |
+
|
| 152 |
+
try:
|
| 153 |
+
# Use uvicorn with optimized settings for HuggingFace
|
| 154 |
+
uvicorn.run(
|
| 155 |
+
app,
|
| 156 |
+
host=host,
|
| 157 |
+
port=port,
|
| 158 |
+
log_level="info",
|
| 159 |
+
access_log=True,
|
| 160 |
+
workers=1, # Single worker for HuggingFace Spaces
|
| 161 |
+
loop="asyncio"
|
| 162 |
+
)
|
| 163 |
+
except Exception as e:
|
| 164 |
+
logger.error(f"❌ Failed to start server: {str(e)}")
|
| 165 |
+
sys.exit(1)
|
main.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This is a sample Python script.
|
| 2 |
+
|
| 3 |
+
# Press Shift+F10 to execute it or replace it with your code.
|
| 4 |
+
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def print_hi(name):
|
| 8 |
+
# Use a breakpoint in the code line below to debug your script.
|
| 9 |
+
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# Press the green button in the gutter to run the script.
|
| 13 |
+
if __name__ == '__main__':
|
| 14 |
+
print_hi('PyCharm')
|
| 15 |
+
|
| 16 |
+
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
|
migration_plan.md
ADDED
|
@@ -0,0 +1,443 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🔄 PLANO DE MIGRAÇÃO ML: BACKEND → MODELS
|
| 2 |
+
|
| 3 |
+
> **Documento de Planejamento da Migração**
|
| 4 |
+
> **Status**: Em Execução - Janeiro 2025
|
| 5 |
+
> **Objetivo**: Separar responsabilidades ML do sistema multi-agente
|
| 6 |
+
|
| 7 |
+
---
|
| 8 |
+
|
| 9 |
+
## 📊 ANÁLISE PRÉ-MIGRAÇÃO
|
| 10 |
+
|
| 11 |
+
### **CÓDIGO ML NO BACKEND ATUAL**
|
| 12 |
+
- **Total**: 7.004 linhas em 13 módulos `src/ml/`
|
| 13 |
+
- **Funcionalidade**: Pipeline completo ML funcional
|
| 14 |
+
- **Integração**: Importado diretamente pelos 16 agentes
|
| 15 |
+
- **Status**: Production-ready, mas acoplado ao backend
|
| 16 |
+
|
| 17 |
+
### **CIDADAO.AI-MODELS STATUS**
|
| 18 |
+
- **Repositório**: Criado com documentação MLOps completa
|
| 19 |
+
- **Código**: Apenas main.py placeholder (16 linhas)
|
| 20 |
+
- **Documentação**: 654 linhas de especificação técnica
|
| 21 |
+
- **Pronto**: Para receber migração ML
|
| 22 |
+
|
| 23 |
+
---
|
| 24 |
+
|
| 25 |
+
## 🎯 ESTRATÉGIA DE MIGRAÇÃO
|
| 26 |
+
|
| 27 |
+
### **ABORDAGEM: MIGRAÇÃO PROGRESSIVA**
|
| 28 |
+
1. ✅ **Não quebrar funcionamento atual** do backend
|
| 29 |
+
2. ✅ **Migrar código gradualmente** testando a cada etapa
|
| 30 |
+
3. ✅ **Manter compatibilidade** durante transição
|
| 31 |
+
4. ✅ **Implementar fallback** local se models indisponível
|
| 32 |
+
|
| 33 |
+
---
|
| 34 |
+
|
| 35 |
+
## 📋 FASE 1: ESTRUTURAÇÃO (HOJE)
|
| 36 |
+
|
| 37 |
+
### **1.1 Criar Estrutura Base**
|
| 38 |
+
```bash
|
| 39 |
+
cidadao.ai-models/
|
| 40 |
+
├── src/
|
| 41 |
+
│ ├── __init__.py
|
| 42 |
+
│ ├── models/ # Core ML models
|
| 43 |
+
│ │ ├── __init__.py
|
| 44 |
+
│ │ ├── anomaly_detection/ # Anomaly detection pipeline
|
| 45 |
+
│ │ ├── pattern_analysis/ # Pattern recognition
|
| 46 |
+
│ │ ├── spectral_analysis/ # Frequency domain analysis
|
| 47 |
+
│ │ └── core/ # Base classes and utilities
|
| 48 |
+
│ ├── training/ # Training infrastructure
|
| 49 |
+
│ │ ├── __init__.py
|
| 50 |
+
│ │ ├── pipelines/ # Training pipelines
|
| 51 |
+
│ │ ├── configs/ # Training configurations
|
| 52 |
+
│ │ └── utils/ # Training utilities
|
| 53 |
+
│ ├── inference/ # Model serving
|
| 54 |
+
│ │ ├── __init__.py
|
| 55 |
+
│ │ ├── api_server.py # FastAPI inference server
|
| 56 |
+
│ │ ├── batch_processor.py # Batch inference
|
| 57 |
+
│ │ └── streaming.py # Real-time inference
|
| 58 |
+
│ └── deployment/ # Deployment tools
|
| 59 |
+
│ ├── __init__.py
|
| 60 |
+
│ ├── huggingface/ # HF Hub integration
|
| 61 |
+
│ ├── docker/ # Containerization
|
| 62 |
+
│ └── monitoring/ # ML monitoring
|
| 63 |
+
├── tests/
|
| 64 |
+
│ ├── __init__.py
|
| 65 |
+
│ ├── unit/ # Unit tests
|
| 66 |
+
│ ├── integration/ # Integration tests
|
| 67 |
+
│ └── e2e/ # End-to-end tests
|
| 68 |
+
├── configs/ # Model configurations
|
| 69 |
+
├── notebooks/ # Jupyter experiments
|
| 70 |
+
├── datasets/ # Dataset management
|
| 71 |
+
├── requirements.txt # Dependencies
|
| 72 |
+
├── setup.py # Package setup
|
| 73 |
+
└── README.md # Documentation
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
### **1.2 Configurar Dependências**
|
| 77 |
+
```python
|
| 78 |
+
# requirements.txt
|
| 79 |
+
torch>=2.0.0
|
| 80 |
+
transformers>=4.36.0
|
| 81 |
+
scikit-learn>=1.3.2
|
| 82 |
+
pandas>=2.1.4
|
| 83 |
+
numpy>=1.26.3
|
| 84 |
+
fastapi>=0.104.0
|
| 85 |
+
uvicorn>=0.24.0
|
| 86 |
+
huggingface-hub>=0.19.0
|
| 87 |
+
mlflow>=2.8.0
|
| 88 |
+
wandb>=0.16.0
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
---
|
| 92 |
+
|
| 93 |
+
## 📋 FASE 2: MIGRAÇÃO MÓDULOS (PRÓXIMA SEMANA)
|
| 94 |
+
|
| 95 |
+
### **2.1 Mapeamento de Migração**
|
| 96 |
+
```python
|
| 97 |
+
# Migração de arquivos backend → models
|
| 98 |
+
MIGRATION_MAP = {
|
| 99 |
+
# Core ML modules
|
| 100 |
+
"src/ml/anomaly_detector.py": "src/models/anomaly_detection/detector.py",
|
| 101 |
+
"src/ml/pattern_analyzer.py": "src/models/pattern_analysis/analyzer.py",
|
| 102 |
+
"src/ml/spectral_analyzer.py": "src/models/spectral_analysis/analyzer.py",
|
| 103 |
+
"src/ml/models.py": "src/models/core/base_models.py",
|
| 104 |
+
|
| 105 |
+
# Training pipeline
|
| 106 |
+
"src/ml/training_pipeline.py": "src/training/pipelines/training.py",
|
| 107 |
+
"src/ml/advanced_pipeline.py": "src/training/pipelines/advanced.py",
|
| 108 |
+
"src/ml/data_pipeline.py": "src/training/pipelines/data.py",
|
| 109 |
+
|
| 110 |
+
# HuggingFace integration
|
| 111 |
+
"src/ml/hf_cidadao_model.py": "src/models/core/hf_model.py",
|
| 112 |
+
"src/ml/hf_integration.py": "src/deployment/huggingface/integration.py",
|
| 113 |
+
"src/ml/cidadao_model.py": "src/models/core/cidadao_model.py",
|
| 114 |
+
|
| 115 |
+
# API and serving
|
| 116 |
+
"src/ml/model_api.py": "src/inference/api_server.py",
|
| 117 |
+
"src/ml/transparency_benchmark.py": "src/models/evaluation/benchmark.py"
|
| 118 |
+
}
|
| 119 |
+
```
|
| 120 |
+
|
| 121 |
+
### **2.2 Refatoração de Imports**
|
| 122 |
+
```python
|
| 123 |
+
# Antes (backend atual)
|
| 124 |
+
from src.ml.anomaly_detector import AnomalyDetector
|
| 125 |
+
from src.ml.pattern_analyzer import PatternAnalyzer
|
| 126 |
+
|
| 127 |
+
# Depois (models repo)
|
| 128 |
+
from cidadao_models.models.anomaly_detection import AnomalyDetector
|
| 129 |
+
from cidadao_models.models.pattern_analysis import PatternAnalyzer
|
| 130 |
+
```
|
| 131 |
+
|
| 132 |
+
### **2.3 Configurar Package**
|
| 133 |
+
```python
|
| 134 |
+
# setup.py
|
| 135 |
+
from setuptools import setup, find_packages
|
| 136 |
+
|
| 137 |
+
setup(
|
| 138 |
+
name="cidadao-ai-models",
|
| 139 |
+
version="1.0.0",
|
| 140 |
+
description="ML models for Cidadão.AI transparency analysis",
|
| 141 |
+
packages=find_packages(where="src"),
|
| 142 |
+
package_dir={"": "src"},
|
| 143 |
+
install_requires=[
|
| 144 |
+
"torch>=2.0.0",
|
| 145 |
+
"transformers>=4.36.0",
|
| 146 |
+
"scikit-learn>=1.3.2",
|
| 147 |
+
# ... outras dependências
|
| 148 |
+
],
|
| 149 |
+
python_requires=">=3.11",
|
| 150 |
+
)
|
| 151 |
+
```
|
| 152 |
+
|
| 153 |
+
---
|
| 154 |
+
|
| 155 |
+
## 📋 FASE 3: SERVIDOR DE INFERÊNCIA (SEMANA 2)
|
| 156 |
+
|
| 157 |
+
### **3.1 API Server Dedicado**
|
| 158 |
+
```python
|
| 159 |
+
# src/inference/api_server.py
|
| 160 |
+
from fastapi import FastAPI, HTTPException
|
| 161 |
+
from cidadao_models.models.anomaly_detection import AnomalyDetector
|
| 162 |
+
from cidadao_models.models.pattern_analysis import PatternAnalyzer
|
| 163 |
+
|
| 164 |
+
app = FastAPI(title="Cidadão.AI Models API")
|
| 165 |
+
|
| 166 |
+
# Initialize models
|
| 167 |
+
anomaly_detector = AnomalyDetector()
|
| 168 |
+
pattern_analyzer = PatternAnalyzer()
|
| 169 |
+
|
| 170 |
+
@app.post("/v1/detect-anomalies")
|
| 171 |
+
async def detect_anomalies(contracts: List[Contract]):
|
| 172 |
+
"""Detect anomalies in government contracts"""
|
| 173 |
+
try:
|
| 174 |
+
results = await anomaly_detector.analyze(contracts)
|
| 175 |
+
return {"anomalies": results, "model_version": "1.0.0"}
|
| 176 |
+
except Exception as e:
|
| 177 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 178 |
+
|
| 179 |
+
@app.post("/v1/analyze-patterns")
|
| 180 |
+
async def analyze_patterns(data: Dict[str, Any]):
|
| 181 |
+
"""Analyze patterns in government data"""
|
| 182 |
+
try:
|
| 183 |
+
patterns = await pattern_analyzer.analyze(data)
|
| 184 |
+
return {"patterns": patterns, "confidence": 0.87}
|
| 185 |
+
except Exception as e:
|
| 186 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 187 |
+
|
| 188 |
+
@app.get("/health")
|
| 189 |
+
async def health_check():
|
| 190 |
+
return {"status": "healthy", "models_loaded": True}
|
| 191 |
+
```
|
| 192 |
+
|
| 193 |
+
### **3.2 Client no Backend**
|
| 194 |
+
```python
|
| 195 |
+
# backend/src/tools/models_client.py
|
| 196 |
+
import httpx
|
| 197 |
+
from typing import Optional, List, Dict, Any
|
| 198 |
+
|
| 199 |
+
class ModelsClient:
|
| 200 |
+
"""Client for cidadao.ai-models API"""
|
| 201 |
+
|
| 202 |
+
def __init__(self, base_url: str = "http://localhost:8001"):
|
| 203 |
+
self.base_url = base_url
|
| 204 |
+
self.client = httpx.AsyncClient(timeout=30.0)
|
| 205 |
+
|
| 206 |
+
async def detect_anomalies(self, contracts: List[Dict]) -> Dict[str, Any]:
|
| 207 |
+
"""Call anomaly detection API"""
|
| 208 |
+
try:
|
| 209 |
+
response = await self.client.post(
|
| 210 |
+
f"{self.base_url}/v1/detect-anomalies",
|
| 211 |
+
json={"contracts": contracts}
|
| 212 |
+
)
|
| 213 |
+
response.raise_for_status()
|
| 214 |
+
return response.json()
|
| 215 |
+
except httpx.RequestError:
|
| 216 |
+
# Fallback to local processing if models API unavailable
|
| 217 |
+
return await self._local_anomaly_detection(contracts)
|
| 218 |
+
|
| 219 |
+
async def _local_anomaly_detection(self, contracts: List[Dict]) -> Dict[str, Any]:
|
| 220 |
+
"""Fallback local processing"""
|
| 221 |
+
# Import local ML if models API unavailable
|
| 222 |
+
from src.ml.anomaly_detector import AnomalyDetector
|
| 223 |
+
detector = AnomalyDetector()
|
| 224 |
+
return detector.analyze(contracts)
|
| 225 |
+
```
|
| 226 |
+
|
| 227 |
+
---
|
| 228 |
+
|
| 229 |
+
## 📋 FASE 4: INTEGRAÇÃO AGENTES (SEMANA 3)
|
| 230 |
+
|
| 231 |
+
### **4.1 Atualizar Agente Zumbi**
|
| 232 |
+
```python
|
| 233 |
+
# backend/src/agents/zumbi.py - ANTES
|
| 234 |
+
from src.ml.anomaly_detector import AnomalyDetector
|
| 235 |
+
from src.ml.spectral_analyzer import SpectralAnalyzer
|
| 236 |
+
|
| 237 |
+
class InvestigatorAgent(BaseAgent):
|
| 238 |
+
def __init__(self):
|
| 239 |
+
self.anomaly_detector = AnomalyDetector()
|
| 240 |
+
self.spectral_analyzer = SpectralAnalyzer()
|
| 241 |
+
|
| 242 |
+
# backend/src/agents/zumbi.py - DEPOIS
|
| 243 |
+
from src.tools.models_client import ModelsClient
|
| 244 |
+
|
| 245 |
+
class InvestigatorAgent(BaseAgent):
|
| 246 |
+
def __init__(self):
|
| 247 |
+
self.models_client = ModelsClient()
|
| 248 |
+
# Fallback local se necessário
|
| 249 |
+
self._local_detector = None
|
| 250 |
+
|
| 251 |
+
async def investigate(self, contracts):
|
| 252 |
+
# Tenta usar models API primeiro
|
| 253 |
+
try:
|
| 254 |
+
results = await self.models_client.detect_anomalies(contracts)
|
| 255 |
+
return results
|
| 256 |
+
except Exception:
|
| 257 |
+
# Fallback para processamento local
|
| 258 |
+
if not self._local_detector:
|
| 259 |
+
from src.ml.anomaly_detector import AnomalyDetector
|
| 260 |
+
self._local_detector = AnomalyDetector()
|
| 261 |
+
return self._local_detector.analyze(contracts)
|
| 262 |
+
```
|
| 263 |
+
|
| 264 |
+
### **4.2 Configuração Híbrida**
|
| 265 |
+
```python
|
| 266 |
+
# backend/src/core/config.py - Adicionar
|
| 267 |
+
class Settings(BaseSettings):
|
| 268 |
+
# ... existing settings ...
|
| 269 |
+
|
| 270 |
+
# Models API configuration
|
| 271 |
+
models_api_enabled: bool = Field(default=True, description="Enable models API")
|
| 272 |
+
models_api_url: str = Field(default="http://localhost:8001", description="Models API URL")
|
| 273 |
+
models_api_timeout: int = Field(default=30, description="API timeout seconds")
|
| 274 |
+
models_fallback_local: bool = Field(default=True, description="Use local ML as fallback")
|
| 275 |
+
```
|
| 276 |
+
|
| 277 |
+
---
|
| 278 |
+
|
| 279 |
+
## 📋 FASE 5: DEPLOYMENT (SEMANA 4)
|
| 280 |
+
|
| 281 |
+
### **5.1 Docker Models**
|
| 282 |
+
```dockerfile
|
| 283 |
+
# cidadao.ai-models/Dockerfile
|
| 284 |
+
FROM python:3.11-slim
|
| 285 |
+
|
| 286 |
+
WORKDIR /app
|
| 287 |
+
|
| 288 |
+
# Install dependencies
|
| 289 |
+
COPY requirements.txt .
|
| 290 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 291 |
+
|
| 292 |
+
# Copy source code
|
| 293 |
+
COPY src/ ./src/
|
| 294 |
+
COPY setup.py .
|
| 295 |
+
RUN pip install -e .
|
| 296 |
+
|
| 297 |
+
# Expose port
|
| 298 |
+
EXPOSE 8001
|
| 299 |
+
|
| 300 |
+
# Run inference server
|
| 301 |
+
CMD ["uvicorn", "src.inference.api_server:app", "--host", "0.0.0.0", "--port", "8001"]
|
| 302 |
+
```
|
| 303 |
+
|
| 304 |
+
### **5.2 Docker Compose Integration**
|
| 305 |
+
```yaml
|
| 306 |
+
# docker-compose.yml (no backend)
|
| 307 |
+
version: '3.8'
|
| 308 |
+
|
| 309 |
+
services:
|
| 310 |
+
cidadao-backend:
|
| 311 |
+
build: .
|
| 312 |
+
ports:
|
| 313 |
+
- "8000:8000"
|
| 314 |
+
depends_on:
|
| 315 |
+
- cidadao-models
|
| 316 |
+
environment:
|
| 317 |
+
- MODELS_API_URL=http://cidadao-models:8001
|
| 318 |
+
|
| 319 |
+
cidadao-models:
|
| 320 |
+
build: ../cidadao.ai-models
|
| 321 |
+
ports:
|
| 322 |
+
- "8001:8001"
|
| 323 |
+
environment:
|
| 324 |
+
- MODEL_CACHE_SIZE=1000
|
| 325 |
+
```
|
| 326 |
+
|
| 327 |
+
### **5.3 HuggingFace Spaces**
|
| 328 |
+
```python
|
| 329 |
+
# cidadao.ai-models/spaces_app.py
|
| 330 |
+
import gradio as gr
|
| 331 |
+
from src.models.anomaly_detection import AnomalyDetector
|
| 332 |
+
from src.models.pattern_analysis import PatternAnalyzer
|
| 333 |
+
|
| 334 |
+
detector = AnomalyDetector()
|
| 335 |
+
analyzer = PatternAnalyzer()
|
| 336 |
+
|
| 337 |
+
def analyze_contract(contract_text):
|
| 338 |
+
"""Analyze contract for anomalies"""
|
| 339 |
+
result = detector.analyze_text(contract_text)
|
| 340 |
+
return {
|
| 341 |
+
"anomaly_score": result.score,
|
| 342 |
+
"risk_level": result.risk_level,
|
| 343 |
+
"explanation": result.explanation
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
# Gradio interface
|
| 347 |
+
with gr.Blocks(title="Cidadão.AI Models Demo") as demo:
|
| 348 |
+
gr.Markdown("# 🤖 Cidadão.AI - Modelos de Transparência")
|
| 349 |
+
|
| 350 |
+
with gr.Row():
|
| 351 |
+
input_text = gr.Textbox(
|
| 352 |
+
label="Texto do Contrato",
|
| 353 |
+
placeholder="Cole aqui o texto do contrato para análise..."
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
analyze_btn = gr.Button("Analisar Anomalias")
|
| 357 |
+
|
| 358 |
+
with gr.Row():
|
| 359 |
+
output = gr.JSON(label="Resultado da Análise")
|
| 360 |
+
|
| 361 |
+
analyze_btn.click(analyze_contract, inputs=input_text, outputs=output)
|
| 362 |
+
|
| 363 |
+
if __name__ == "__main__":
|
| 364 |
+
demo.launch()
|
| 365 |
+
```
|
| 366 |
+
|
| 367 |
+
---
|
| 368 |
+
|
| 369 |
+
## 🔄 INTEGRAÇÃO ENTRE REPOSITÓRIOS
|
| 370 |
+
|
| 371 |
+
### **COMUNICAÇÃO API-BASED**
|
| 372 |
+
```python
|
| 373 |
+
# Fluxo: Backend → Models
|
| 374 |
+
1. Backend Agent precisa análise ML
|
| 375 |
+
2. Chama Models API via HTTP
|
| 376 |
+
3. Models processa e retorna resultado
|
| 377 |
+
4. Backend integra resultado na resposta
|
| 378 |
+
5. Fallback local se Models indisponível
|
| 379 |
+
```
|
| 380 |
+
|
| 381 |
+
### **VERSIONAMENTO INDEPENDENTE**
|
| 382 |
+
```python
|
| 383 |
+
# cidadao.ai-models releases
|
| 384 |
+
v1.0.0: "Initial anomaly detection model"
|
| 385 |
+
v1.1.0: "Pattern analysis improvements"
|
| 386 |
+
v1.2.0: "New corruption detection model"
|
| 387 |
+
|
| 388 |
+
# cidadao.ai-backend usa models
|
| 389 |
+
requirements.txt:
|
| 390 |
+
cidadao-ai-models>=1.0.0,<2.0.0
|
| 391 |
+
```
|
| 392 |
+
|
| 393 |
+
---
|
| 394 |
+
|
| 395 |
+
## 📊 CRONOGRAMA EXECUÇÃO
|
| 396 |
+
|
| 397 |
+
### **SEMANA 1: Setup & Estrutura**
|
| 398 |
+
- [ ] Criar estrutura completa cidadao.ai-models
|
| 399 |
+
- [ ] Configurar requirements e setup.py
|
| 400 |
+
- [ ] Migrar primeiro módulo (anomaly_detector.py)
|
| 401 |
+
- [ ] Testar importação e funcionamento básico
|
| 402 |
+
|
| 403 |
+
### **SEMANA 2: Migração Core**
|
| 404 |
+
- [ ] Migrar todos os 13 módulos ML
|
| 405 |
+
- [ ] Refatorar imports e dependências
|
| 406 |
+
- [ ] Implementar API server básico
|
| 407 |
+
- [ ] Criar client no backend
|
| 408 |
+
|
| 409 |
+
### **SEMANA 3: Integração Agentes**
|
| 410 |
+
- [ ] Atualizar Zumbi para usar Models API
|
| 411 |
+
- [ ] Implementar fallback local
|
| 412 |
+
- [ ] Testar integração completa
|
| 413 |
+
- [ ] Atualizar documentação
|
| 414 |
+
|
| 415 |
+
### **SEMANA 4: Deploy & Production**
|
| 416 |
+
- [ ] Containerização Docker
|
| 417 |
+
- [ ] Deploy HuggingFace Spaces
|
| 418 |
+
- [ ] Monitoramento e métricas
|
| 419 |
+
- [ ] Testes de carga e performance
|
| 420 |
+
|
| 421 |
+
---
|
| 422 |
+
|
| 423 |
+
## ✅ CRITÉRIOS DE SUCESSO
|
| 424 |
+
|
| 425 |
+
### **FUNCIONAIS**
|
| 426 |
+
- [ ] Backend continua funcionando sem interrupção
|
| 427 |
+
- [ ] Models API responde <500ms
|
| 428 |
+
- [ ] Fallback local funciona se API indisponível
|
| 429 |
+
- [ ] Todos agentes usam nova arquitetura
|
| 430 |
+
|
| 431 |
+
### **NÃO-FUNCIONAIS**
|
| 432 |
+
- [ ] Performance igual ou melhor que atual
|
| 433 |
+
- [ ] Deploy independente dos repositórios
|
| 434 |
+
- [ ] Documentação atualizada
|
| 435 |
+
- [ ] Testes cobrindo >80% código migrado
|
| 436 |
+
|
| 437 |
+
---
|
| 438 |
+
|
| 439 |
+
## 🎯 PRÓXIMO PASSO IMEDIATO
|
| 440 |
+
|
| 441 |
+
**COMEÇAR FASE 1 AGORA**: Criar estrutura base no cidadao.ai-models e migrar primeiro módulo para validar approach.
|
| 442 |
+
|
| 443 |
+
Vamos começar?
|
pytest.ini
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[tool:pytest]
|
| 2 |
+
testpaths = tests
|
| 3 |
+
python_files = test_*.py
|
| 4 |
+
python_classes = Test*
|
| 5 |
+
python_functions = test_*
|
| 6 |
+
|
| 7 |
+
addopts =
|
| 8 |
+
--strict-markers
|
| 9 |
+
--verbose
|
| 10 |
+
--tb=short
|
| 11 |
+
--cov=src
|
| 12 |
+
--cov-report=term-missing
|
| 13 |
+
--cov-report=html:htmlcov
|
| 14 |
+
--cov-report=xml
|
| 15 |
+
--cov-fail-under=80
|
| 16 |
+
--asyncio-mode=auto
|
| 17 |
+
--disable-warnings
|
| 18 |
+
|
| 19 |
+
markers =
|
| 20 |
+
unit: Unit tests that don't require external dependencies
|
| 21 |
+
integration: Integration tests that test multiple components
|
| 22 |
+
slow: Tests that take more than 1 second
|
| 23 |
+
api: API-related tests
|
| 24 |
+
|
| 25 |
+
asyncio_mode = auto
|
requirements-hf.txt
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Cidadão.AI Models - HuggingFace Spaces Requirements
|
| 2 |
+
# Minimal dependencies for fast deployment and startup
|
| 3 |
+
|
| 4 |
+
# Web Framework
|
| 5 |
+
fastapi>=0.104.0
|
| 6 |
+
uvicorn[standard]>=0.24.0
|
| 7 |
+
pydantic>=2.5.0
|
| 8 |
+
|
| 9 |
+
# Machine Learning (essential only)
|
| 10 |
+
scikit-learn>=1.3.2
|
| 11 |
+
numpy>=1.26.3
|
| 12 |
+
pandas>=2.1.4
|
| 13 |
+
|
| 14 |
+
# HTTP Client
|
| 15 |
+
httpx>=0.27.0
|
| 16 |
+
|
| 17 |
+
# Monitoring
|
| 18 |
+
prometheus-client>=0.19.0
|
| 19 |
+
|
| 20 |
+
# Utils
|
| 21 |
+
python-multipart>=0.0.6
|
| 22 |
+
python-dotenv>=1.0.0
|
| 23 |
+
|
| 24 |
+
# Optional ML libraries (will not break if unavailable)
|
| 25 |
+
torch>=2.0.0; platform_machine != "armv7l"
|
| 26 |
+
transformers>=4.36.0; platform_machine != "armv7l"
|
requirements.txt
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Cidadão.AI Models - Core Dependencies
|
| 2 |
+
|
| 3 |
+
# Deep Learning Framework
|
| 4 |
+
torch>=2.0.0
|
| 5 |
+
transformers>=4.36.0
|
| 6 |
+
sentence-transformers>=2.2.0
|
| 7 |
+
|
| 8 |
+
# Machine Learning
|
| 9 |
+
scikit-learn>=1.3.2
|
| 10 |
+
numpy>=1.26.3
|
| 11 |
+
pandas>=2.1.4
|
| 12 |
+
scipy>=1.11.4
|
| 13 |
+
|
| 14 |
+
# API Server
|
| 15 |
+
fastapi>=0.104.0
|
| 16 |
+
uvicorn[standard]>=0.24.0
|
| 17 |
+
pydantic>=2.5.0
|
| 18 |
+
|
| 19 |
+
# HuggingFace Integration
|
| 20 |
+
huggingface-hub>=0.19.0
|
| 21 |
+
datasets>=2.16.0
|
| 22 |
+
|
| 23 |
+
# MLOps
|
| 24 |
+
mlflow>=2.8.0
|
| 25 |
+
wandb>=0.16.0
|
| 26 |
+
|
| 27 |
+
# Monitoring
|
| 28 |
+
prometheus-client>=0.19.0
|
| 29 |
+
|
| 30 |
+
# Testing
|
| 31 |
+
pytest>=7.4.0
|
| 32 |
+
pytest-asyncio>=0.21.0
|
| 33 |
+
|
| 34 |
+
# Data Processing
|
| 35 |
+
tqdm>=4.66.0
|
| 36 |
+
joblib>=1.3.0
|
| 37 |
+
|
| 38 |
+
# HTTP Client
|
| 39 |
+
httpx>=0.27.0
|
setup.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Setup configuration for Cidadão.AI Models package.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from setuptools import setup, find_packages
|
| 6 |
+
|
| 7 |
+
with open("README.md", "r", encoding="utf-8") as fh:
|
| 8 |
+
long_description = fh.read()
|
| 9 |
+
|
| 10 |
+
with open("requirements.txt", "r", encoding="utf-8") as fh:
|
| 11 |
+
requirements = [line.strip() for line in fh if line.strip() and not line.startswith("#")]
|
| 12 |
+
|
| 13 |
+
setup(
|
| 14 |
+
name="cidadao-ai-models",
|
| 15 |
+
version="1.0.0",
|
| 16 |
+
author="Anderson Henrique da Silva",
|
| 17 |
+
author_email="[email protected]",
|
| 18 |
+
description="Specialized ML models for Brazilian government transparency analysis",
|
| 19 |
+
long_description=long_description,
|
| 20 |
+
long_description_content_type="text/markdown",
|
| 21 |
+
url="https://github.com/anderson-ufrj/cidadao.ai-models",
|
| 22 |
+
packages=find_packages(where="src"),
|
| 23 |
+
package_dir={"": "src"},
|
| 24 |
+
classifiers=[
|
| 25 |
+
"Development Status :: 4 - Beta",
|
| 26 |
+
"Intended Audience :: Developers",
|
| 27 |
+
"Intended Audience :: Science/Research",
|
| 28 |
+
"License :: OSI Approved :: MIT License",
|
| 29 |
+
"Operating System :: OS Independent",
|
| 30 |
+
"Programming Language :: Python :: 3",
|
| 31 |
+
"Programming Language :: Python :: 3.11",
|
| 32 |
+
"Programming Language :: Python :: 3.12",
|
| 33 |
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
| 34 |
+
"Topic :: Scientific/Engineering :: Information Analysis",
|
| 35 |
+
],
|
| 36 |
+
python_requires=">=3.11",
|
| 37 |
+
install_requires=requirements,
|
| 38 |
+
extras_require={
|
| 39 |
+
"dev": [
|
| 40 |
+
"pytest>=7.4.0",
|
| 41 |
+
"pytest-asyncio>=0.21.0",
|
| 42 |
+
"pytest-cov>=4.1.0",
|
| 43 |
+
"black>=23.0.0",
|
| 44 |
+
"ruff>=0.1.0",
|
| 45 |
+
"mypy>=1.8.0",
|
| 46 |
+
],
|
| 47 |
+
"notebooks": [
|
| 48 |
+
"jupyter>=1.0.0",
|
| 49 |
+
"matplotlib>=3.7.0",
|
| 50 |
+
"seaborn>=0.12.0",
|
| 51 |
+
"plotly>=5.17.0",
|
| 52 |
+
],
|
| 53 |
+
"gpu": [
|
| 54 |
+
"torch[gpu]>=2.0.0",
|
| 55 |
+
]
|
| 56 |
+
},
|
| 57 |
+
entry_points={
|
| 58 |
+
"console_scripts": [
|
| 59 |
+
"cidadao-models=src.cli:main",
|
| 60 |
+
],
|
| 61 |
+
},
|
| 62 |
+
keywords="transparency, government, brazil, machine-learning, anomaly-detection",
|
| 63 |
+
project_urls={
|
| 64 |
+
"Bug Reports": "https://github.com/anderson-ufrj/cidadao.ai-models/issues",
|
| 65 |
+
"Source": "https://github.com/anderson-ufrj/cidadao.ai-models",
|
| 66 |
+
"Documentation": "https://github.com/anderson-ufrj/cidadao.ai-models/wiki",
|
| 67 |
+
},
|
| 68 |
+
)
|
src/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Cidadão.AI Models - Machine Learning Pipeline
|
| 3 |
+
|
| 4 |
+
Specialized ML models for Brazilian government transparency analysis.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
__version__ = "1.0.0"
|
| 8 |
+
__author__ = "Anderson Henrique da Silva"
|
src/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (384 Bytes). View file
|
|
|
src/deployment/__init__.py
ADDED
|
File without changes
|
src/deployment/docker/__init__.py
ADDED
|
File without changes
|
src/deployment/huggingface/__init__.py
ADDED
|
File without changes
|
src/deployment/monitoring/__init__.py
ADDED
|
File without changes
|
src/inference/__init__.py
ADDED
|
File without changes
|
src/inference/api_server.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Cidadão.AI Models - API Server
|
| 4 |
+
|
| 5 |
+
FastAPI server for ML model inference.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import os
|
| 9 |
+
import sys
|
| 10 |
+
from contextlib import asynccontextmanager
|
| 11 |
+
from typing import Dict, List, Any, Optional
|
| 12 |
+
import logging
|
| 13 |
+
|
| 14 |
+
from fastapi import FastAPI, HTTPException, status
|
| 15 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 16 |
+
from pydantic import BaseModel, Field
|
| 17 |
+
from prometheus_client import Counter, Histogram, generate_latest
|
| 18 |
+
|
| 19 |
+
# Add parent to path for imports
|
| 20 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
|
| 21 |
+
|
| 22 |
+
# Import models
|
| 23 |
+
from src.models.anomaly_detection import AnomalyDetector
|
| 24 |
+
from src.models.pattern_analysis import PatternAnalyzer
|
| 25 |
+
from src.models.spectral_analysis import SpectralAnalyzer
|
| 26 |
+
|
| 27 |
+
# Configure logging
|
| 28 |
+
logging.basicConfig(level=logging.INFO)
|
| 29 |
+
logger = logging.getLogger(__name__)
|
| 30 |
+
|
| 31 |
+
# Prometheus metrics
|
| 32 |
+
REQUEST_COUNT = Counter('cidadao_models_requests_total', 'Total requests', ['endpoint'])
|
| 33 |
+
REQUEST_DURATION = Histogram('cidadao_models_request_duration_seconds', 'Request duration')
|
| 34 |
+
ANOMALIES_DETECTED = Counter('cidadao_models_anomalies_total', 'Total anomalies detected')
|
| 35 |
+
|
| 36 |
+
# Global models
|
| 37 |
+
models = {}
|
| 38 |
+
|
| 39 |
+
@asynccontextmanager
|
| 40 |
+
async def lifespan(app: FastAPI):
|
| 41 |
+
"""Application lifespan manager."""
|
| 42 |
+
logger.info("🤖 Cidadão.AI Models API starting up...")
|
| 43 |
+
|
| 44 |
+
# Initialize models
|
| 45 |
+
models["anomaly_detector"] = AnomalyDetector()
|
| 46 |
+
models["pattern_analyzer"] = PatternAnalyzer()
|
| 47 |
+
models["spectral_analyzer"] = SpectralAnalyzer()
|
| 48 |
+
|
| 49 |
+
logger.info("✅ All models loaded successfully")
|
| 50 |
+
|
| 51 |
+
yield
|
| 52 |
+
|
| 53 |
+
logger.info("🛑 Cidadão.AI Models API shutting down...")
|
| 54 |
+
|
| 55 |
+
# Create FastAPI app
|
| 56 |
+
app = FastAPI(
|
| 57 |
+
title="🤖 Cidadão.AI Models API",
|
| 58 |
+
description="Specialized ML models for Brazilian government transparency analysis",
|
| 59 |
+
version="1.0.0",
|
| 60 |
+
lifespan=lifespan
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
# Add CORS middleware
|
| 64 |
+
app.add_middleware(
|
| 65 |
+
CORSMiddleware,
|
| 66 |
+
allow_origins=["*"],
|
| 67 |
+
allow_credentials=True,
|
| 68 |
+
allow_methods=["*"],
|
| 69 |
+
allow_headers=["*"],
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
# Request/Response Models
|
| 73 |
+
class Contract(BaseModel):
|
| 74 |
+
"""Government contract data."""
|
| 75 |
+
id: str
|
| 76 |
+
description: str
|
| 77 |
+
value: float
|
| 78 |
+
supplier: str
|
| 79 |
+
date: str
|
| 80 |
+
organ: str
|
| 81 |
+
|
| 82 |
+
class AnomalyRequest(BaseModel):
|
| 83 |
+
"""Request for anomaly detection."""
|
| 84 |
+
contracts: List[Dict[str, Any]] = Field(..., description="List of contracts to analyze")
|
| 85 |
+
threshold: Optional[float] = Field(default=0.7, description="Anomaly threshold")
|
| 86 |
+
|
| 87 |
+
class AnomalyResponse(BaseModel):
|
| 88 |
+
"""Response from anomaly detection."""
|
| 89 |
+
anomalies: List[Dict[str, Any]]
|
| 90 |
+
total_analyzed: int
|
| 91 |
+
anomalies_found: int
|
| 92 |
+
confidence_score: float
|
| 93 |
+
model_version: str = "1.0.0"
|
| 94 |
+
|
| 95 |
+
class PatternRequest(BaseModel):
|
| 96 |
+
"""Request for pattern analysis."""
|
| 97 |
+
data: Dict[str, Any] = Field(..., description="Data to analyze patterns")
|
| 98 |
+
analysis_type: str = Field(default="temporal", description="Type of pattern analysis")
|
| 99 |
+
|
| 100 |
+
class PatternResponse(BaseModel):
|
| 101 |
+
"""Response from pattern analysis."""
|
| 102 |
+
patterns: List[Dict[str, Any]]
|
| 103 |
+
pattern_count: int
|
| 104 |
+
confidence: float
|
| 105 |
+
insights: List[str]
|
| 106 |
+
|
| 107 |
+
class SpectralRequest(BaseModel):
|
| 108 |
+
"""Request for spectral analysis."""
|
| 109 |
+
time_series: List[float] = Field(..., description="Time series data")
|
| 110 |
+
sampling_rate: Optional[float] = Field(default=1.0, description="Sampling rate")
|
| 111 |
+
|
| 112 |
+
class SpectralResponse(BaseModel):
|
| 113 |
+
"""Response from spectral analysis."""
|
| 114 |
+
frequencies: List[float]
|
| 115 |
+
amplitudes: List[float]
|
| 116 |
+
dominant_frequency: float
|
| 117 |
+
periodic_patterns: List[Dict[str, Any]]
|
| 118 |
+
|
| 119 |
+
# Endpoints
|
| 120 |
+
@app.get("/")
|
| 121 |
+
async def root():
|
| 122 |
+
"""Root endpoint with API info."""
|
| 123 |
+
REQUEST_COUNT.labels(endpoint="/").inc()
|
| 124 |
+
return {
|
| 125 |
+
"api": "Cidadão.AI Models",
|
| 126 |
+
"version": "1.0.0",
|
| 127 |
+
"status": "operational",
|
| 128 |
+
"models": list(models.keys()),
|
| 129 |
+
"endpoints": {
|
| 130 |
+
"anomaly_detection": "/v1/detect-anomalies",
|
| 131 |
+
"pattern_analysis": "/v1/analyze-patterns",
|
| 132 |
+
"spectral_analysis": "/v1/analyze-spectral",
|
| 133 |
+
"health": "/health",
|
| 134 |
+
"metrics": "/metrics"
|
| 135 |
+
}
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
@app.get("/health")
|
| 139 |
+
async def health_check():
|
| 140 |
+
"""Health check endpoint."""
|
| 141 |
+
REQUEST_COUNT.labels(endpoint="/health").inc()
|
| 142 |
+
return {
|
| 143 |
+
"status": "healthy",
|
| 144 |
+
"models_loaded": len(models) == 3,
|
| 145 |
+
"models": {name: "loaded" for name in models.keys()}
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
@app.post("/v1/detect-anomalies", response_model=AnomalyResponse)
|
| 149 |
+
async def detect_anomalies(request: AnomalyRequest):
|
| 150 |
+
"""Detect anomalies in government contracts."""
|
| 151 |
+
REQUEST_COUNT.labels(endpoint="/v1/detect-anomalies").inc()
|
| 152 |
+
|
| 153 |
+
try:
|
| 154 |
+
with REQUEST_DURATION.time():
|
| 155 |
+
# Run anomaly detection
|
| 156 |
+
detector = models["anomaly_detector"]
|
| 157 |
+
results = await detector.predict(request.contracts)
|
| 158 |
+
|
| 159 |
+
# Count anomalies
|
| 160 |
+
anomalies = [r for r in results if r.get("is_anomaly", False)]
|
| 161 |
+
ANOMALIES_DETECTED.inc(len(anomalies))
|
| 162 |
+
|
| 163 |
+
return AnomalyResponse(
|
| 164 |
+
anomalies=anomalies,
|
| 165 |
+
total_analyzed=len(request.contracts),
|
| 166 |
+
anomalies_found=len(anomalies),
|
| 167 |
+
confidence_score=0.87
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
except Exception as e:
|
| 171 |
+
logger.error(f"Anomaly detection error: {str(e)}")
|
| 172 |
+
raise HTTPException(
|
| 173 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 174 |
+
detail=f"Anomaly detection failed: {str(e)}"
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
@app.post("/v1/analyze-patterns", response_model=PatternResponse)
|
| 178 |
+
async def analyze_patterns(request: PatternRequest):
|
| 179 |
+
"""Analyze patterns in government data."""
|
| 180 |
+
REQUEST_COUNT.labels(endpoint="/v1/analyze-patterns").inc()
|
| 181 |
+
|
| 182 |
+
try:
|
| 183 |
+
with REQUEST_DURATION.time():
|
| 184 |
+
analyzer = models["pattern_analyzer"]
|
| 185 |
+
|
| 186 |
+
# Mock analysis for now
|
| 187 |
+
patterns = [
|
| 188 |
+
{
|
| 189 |
+
"type": "temporal",
|
| 190 |
+
"description": "Peak spending in December",
|
| 191 |
+
"confidence": 0.92
|
| 192 |
+
},
|
| 193 |
+
{
|
| 194 |
+
"type": "vendor_concentration",
|
| 195 |
+
"description": "High concentration of contracts with few vendors",
|
| 196 |
+
"confidence": 0.85
|
| 197 |
+
}
|
| 198 |
+
]
|
| 199 |
+
|
| 200 |
+
return PatternResponse(
|
| 201 |
+
patterns=patterns,
|
| 202 |
+
pattern_count=len(patterns),
|
| 203 |
+
confidence=0.88,
|
| 204 |
+
insights=[
|
| 205 |
+
"Seasonal spending patterns detected",
|
| 206 |
+
"Vendor concentration above normal threshold"
|
| 207 |
+
]
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
except Exception as e:
|
| 211 |
+
logger.error(f"Pattern analysis error: {str(e)}")
|
| 212 |
+
raise HTTPException(
|
| 213 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 214 |
+
detail=f"Pattern analysis failed: {str(e)}"
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
@app.post("/v1/analyze-spectral", response_model=SpectralResponse)
|
| 218 |
+
async def analyze_spectral(request: SpectralRequest):
|
| 219 |
+
"""Perform spectral analysis on time series data."""
|
| 220 |
+
REQUEST_COUNT.labels(endpoint="/v1/analyze-spectral").inc()
|
| 221 |
+
|
| 222 |
+
try:
|
| 223 |
+
with REQUEST_DURATION.time():
|
| 224 |
+
analyzer = models["spectral_analyzer"]
|
| 225 |
+
|
| 226 |
+
# Mock spectral analysis
|
| 227 |
+
return SpectralResponse(
|
| 228 |
+
frequencies=[0.1, 0.2, 0.5, 1.0],
|
| 229 |
+
amplitudes=[10.5, 25.3, 5.2, 45.8],
|
| 230 |
+
dominant_frequency=1.0,
|
| 231 |
+
periodic_patterns=[
|
| 232 |
+
{
|
| 233 |
+
"frequency": 1.0,
|
| 234 |
+
"period": "annual",
|
| 235 |
+
"strength": 0.95
|
| 236 |
+
}
|
| 237 |
+
]
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
except Exception as e:
|
| 241 |
+
logger.error(f"Spectral analysis error: {str(e)}")
|
| 242 |
+
raise HTTPException(
|
| 243 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 244 |
+
detail=f"Spectral analysis failed: {str(e)}"
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
@app.get("/metrics")
|
| 248 |
+
async def metrics():
|
| 249 |
+
"""Prometheus metrics endpoint."""
|
| 250 |
+
return generate_latest().decode('utf-8')
|
| 251 |
+
|
| 252 |
+
if __name__ == "__main__":
|
| 253 |
+
import uvicorn
|
| 254 |
+
|
| 255 |
+
port = int(os.getenv("PORT", 8001))
|
| 256 |
+
host = os.getenv("HOST", "0.0.0.0")
|
| 257 |
+
|
| 258 |
+
logger.info(f"🚀 Starting Cidadão.AI Models API on {host}:{port}")
|
| 259 |
+
|
| 260 |
+
uvicorn.run(
|
| 261 |
+
"api_server:app",
|
| 262 |
+
host=host,
|
| 263 |
+
port=port,
|
| 264 |
+
reload=True
|
| 265 |
+
)
|
src/models/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
Cidadao.AI Models - Core ML Models
|
| 4 |
+
|
| 5 |
+
Specialized machine learning models for Brazilian government transparency analysis.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
# Will be imported as models are migrated
|
| 9 |
+
# from .anomaly_detection import AnomalyDetector
|
| 10 |
+
# from .pattern_analysis import PatternAnalyzer
|
| 11 |
+
# from .spectral_analysis import SpectralAnalyzer
|
| 12 |
+
|
| 13 |
+
__all__ = []
|
src/models/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (330 Bytes). View file
|
|
|
src/models/anomaly_detection/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Anomaly Detection Module
|
| 3 |
+
|
| 4 |
+
Specialized anomaly detection algorithms for government transparency data.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from .detector import AnomalyDetector
|
| 8 |
+
|
| 9 |
+
__all__ = ["AnomalyDetector"]
|
src/models/anomaly_detection/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (393 Bytes). View file
|
|
|
src/models/anomaly_detection/__pycache__/detector.cpython-313.pyc
ADDED
|
Binary file (4.89 kB). View file
|
|
|
src/models/anomaly_detection/detector.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Anomaly detection for government spending data."""
|
| 2 |
+
|
| 3 |
+
from typing import Dict, List, Optional, Tuple
|
| 4 |
+
from ..core.base_models import MLModel
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class AnomalyDetector(MLModel):
|
| 8 |
+
"""Detects anomalies in government spending patterns."""
|
| 9 |
+
|
| 10 |
+
def __init__(self):
|
| 11 |
+
super().__init__("anomaly_detector")
|
| 12 |
+
self._thresholds = {
|
| 13 |
+
"value_threshold": 1000000, # 1M BRL
|
| 14 |
+
"frequency_threshold": 10,
|
| 15 |
+
"pattern_threshold": 0.8
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
async def train(self, data: List[Dict], **kwargs) -> Dict:
|
| 19 |
+
"""Train anomaly detection model (stub)."""
|
| 20 |
+
# TODO: Implement actual ML training with historical data
|
| 21 |
+
self._is_trained = True
|
| 22 |
+
return {
|
| 23 |
+
"status": "trained",
|
| 24 |
+
"samples": len(data),
|
| 25 |
+
"model": self.model_name
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
async def predict(self, data: List[Dict]) -> List[Dict]:
|
| 29 |
+
"""Detect anomalies in spending data."""
|
| 30 |
+
anomalies = []
|
| 31 |
+
|
| 32 |
+
for item in data:
|
| 33 |
+
anomaly_score, reasons = await self._calculate_anomaly_score(item)
|
| 34 |
+
|
| 35 |
+
if anomaly_score > 0.5: # Threshold for anomaly
|
| 36 |
+
anomalies.append({
|
| 37 |
+
"item": item,
|
| 38 |
+
"anomaly_score": anomaly_score,
|
| 39 |
+
"reasons": reasons,
|
| 40 |
+
"severity": self._get_severity(anomaly_score)
|
| 41 |
+
})
|
| 42 |
+
|
| 43 |
+
return anomalies
|
| 44 |
+
|
| 45 |
+
async def evaluate(self, data: List[Dict]) -> Dict:
|
| 46 |
+
"""Evaluate anomaly detection performance."""
|
| 47 |
+
predictions = await self.predict(data)
|
| 48 |
+
return {
|
| 49 |
+
"total_items": len(data),
|
| 50 |
+
"anomalies_detected": len(predictions),
|
| 51 |
+
"anomaly_rate": len(predictions) / len(data) if data else 0
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
async def _calculate_anomaly_score(self, item: Dict) -> Tuple[float, List[str]]:
|
| 55 |
+
"""Calculate anomaly score for an item."""
|
| 56 |
+
score = 0.0
|
| 57 |
+
reasons = []
|
| 58 |
+
|
| 59 |
+
# Check value anomalies
|
| 60 |
+
value = item.get("valor", 0)
|
| 61 |
+
if isinstance(value, (int, float)) and value > self._thresholds["value_threshold"]:
|
| 62 |
+
score += 0.3
|
| 63 |
+
reasons.append(f"Alto valor: R$ {value:,.2f}")
|
| 64 |
+
|
| 65 |
+
# Check frequency anomalies (simplified)
|
| 66 |
+
supplier = item.get("fornecedor", {}).get("nome", "")
|
| 67 |
+
if supplier and len(supplier) < 10: # Very short supplier names
|
| 68 |
+
score += 0.2
|
| 69 |
+
reasons.append("Nome de fornecedor suspeito")
|
| 70 |
+
|
| 71 |
+
# Check pattern anomalies (simplified)
|
| 72 |
+
description = item.get("objeto", "").lower()
|
| 73 |
+
suspicious_keywords = ["urgente", "emergencial", "dispensada"]
|
| 74 |
+
if any(keyword in description for keyword in suspicious_keywords):
|
| 75 |
+
score += 0.4
|
| 76 |
+
reasons.append("Contratação com características suspeitas")
|
| 77 |
+
|
| 78 |
+
return min(score, 1.0), reasons
|
| 79 |
+
|
| 80 |
+
def _get_severity(self, score: float) -> str:
|
| 81 |
+
"""Get severity level based on anomaly score."""
|
| 82 |
+
if score >= 0.8:
|
| 83 |
+
return "high"
|
| 84 |
+
elif score >= 0.6:
|
| 85 |
+
return "medium"
|
| 86 |
+
else:
|
| 87 |
+
return "low"
|
| 88 |
+
|
| 89 |
+
def set_thresholds(self, **thresholds):
|
| 90 |
+
"""Update detection thresholds."""
|
| 91 |
+
self._thresholds.update(thresholds)
|
src/models/core/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Core Models Module
|
| 3 |
+
|
| 4 |
+
Base classes and utilities for all ML models.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from .base_models import MLModel
|
| 8 |
+
|
| 9 |
+
__all__ = ["MLModel"]
|
src/models/core/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (339 Bytes). View file
|
|
|