A comprehensive tool for analyzing Power BI TMDL (Tabular Model Definition Language) files against Microsoft's Analysis Services best practice rules, with optional AI-enhanced recommendations.An AI-powered tool that analyzes Power BI TMDL (Tabular Model Definition Language) files against Microsoft's Analysis Services best practice rules.
- π Comprehensive Analysis: Analyzes tables, measures, columns, and relationships in TMDL files
- π Best Practices Validation: Checks against Microsoft's official Analysis Services best practice rules
- π¨ Detailed Reporting: Generates detailed reports with violations, severity levels, and fix suggestions
- π Web Interface: Easy-to-use web interface for uploading and analyzing models
Then open http://localhost:5000 in your browser.
-
π Export Reports: Download analysis reports in Markdown format
-
β‘ Fast Processing: Efficiently parses and analyzes large TMDL models
python run_analyzer.py "path/to/YourModel.SemanticModel"-
Clone or download this repository
-
Install Python dependencies:
pip install -r requirements.txt pip install -r requirements.txtPBIP/3. Ensure you have the BPARules.json file (automatically downloaded from Microsoft's repository)
βββ run_web_interface.py # Launch web interface
βββ run_analyzer.py # Command-line tool## OpenAI Integration (Optional)
βββ requirements.txt # Python dependencies
βββ .gitignore # Git ignore rulesThe analyzer works perfectly without OpenAI, but you can enhance it with AI-powered features:
βββ config_template.py # OpenAI configuration template
β### Setting Up OpenAI API Key
βββ src/ # Source code
β βββ init.pyOption 1: Environment Variable (Recommended)
β βββ tmdl_analyzer.py # Core analyzer```bash
β βββ ai_enhanced_analyzer.py # AI-enhanced analyzer# Windows PowerShell
β βββ web_interface.py # Flask web app$env:OPENAI_API_KEY = "sk-your-api-key-here"
β βββ config.py # Configuration (create from template)
β# Linux/Mac
βββ data/ # Data filesexport OPENAI_API_KEY="sk-your-api-key-here"
β βββ BPARules.json # Microsoft best practice rules```
β
βββ tests/ # Test filesOption 2: Configuration File
β βββ test_ai_analyzer.py1. Copy config_template.py to config.py
β βββ test_ai_enhancements.py2. Add your API key: OPENAI_API_KEY = "sk-your-api-key-here"
β βββ test_column_references.py
β βββ test_rules.pyGet API Key: Visit OpenAI Platform
β βββ debug_column_refs.py
β### AI-Enhanced Features
βββ examples/ # Example scripts- π€ Smart Explanations: Context-aware violation explanations
β βββ demo.py- π Strategic Recommendations: High-level improvement strategies
β βββ quick_start_ai.py- β‘ DAX Analysis: Intelligent pattern detection
β βββ example_with_openai.py- π‘ Custom Fixes: Specific, actionable suggestions
β
βββ docs/ # DocumentationSee OPENAI_SETUP.md for detailed instructions.
β βββ OPENAI_SETUP.md
β βββ TROUBLESHOOTING.md## Usage
β βββ AI_CONFIGURATION_FIXED.md
β βββ AI_FIXES_COMPLETE.md### Option 1: Command Line Interface
β βββ AI_PERFORMANCE_FIXES.md
β βββ AI_RULE_TYPE_OPTIMIZATION.md```bash
β βββ RULE_LEVEL_AI_ENHANCEMENT.mdpython tmdl_analyzer.py <model_path> [rules_file] [output_file]
β βββ ALL_RULES_VISIBILITY.md```
β
βββ reports/ # Generated reportsExamples:
βββ analysis_report.md```bash
βββ demo_analysis_report.md# Basic analysis
## π¦ Installation# With custom rules file and output
python tmdl_analyzer.py "Sales Dashboard.SemanticModel" BPARules.json report.md
1. **Clone or download** this repository
# Analyze different model
2. **Install dependencies:**python tmdl_analyzer.py "C:\Models\MyModel.SemanticModel" BPARules.json analysis.md**
```bash
pip install -r requirements.txt- **(Optional) Configure OpenAI for AI-enhanced analysis:**1. Start the web server:
python web_interface.py copy config_template.py src\\config.py ```cp config_template.py src/config.py
- Upload your TMDL model directory using the web interface
## π― Features## Best Practice Rules Checked
### Core AnalysisThe analyzer checks for violations in the following categories:
- β
Parses TMDL files from Power BI semantic models
- β
Checks 8+ best practice rules from Microsoft### Performance Rules
- β
Identifies violations with severity levels- β Avoid floating point data types (Double)
- β
Provides fix suggestions where available- β‘ Set IsAvailableInMdx to false on non-attribute columns
- β
Generates detailed markdown reports- π Avoid excessive bi-directional relationships
- β
Shows all rules checked (even those with 0 violations)- π Model should have a date table
- π― Hide foreign keys
### AI-Enhanced Analysis (Optional)- π Reduce usage of calculated columns
- π€ Strategic recommendations for your model
- π€ Rule-level explanations (not per-violation to save costs)### DAX Expression Rules
- π€ Priority ranking and effort estimates- π Column references should be fully qualified
- π€ Implementation strategies- π― Measure references should be unqualified
- π€ 90% cost reduction vs. individual enhancements- β Use DIVIDE function instead of `/` operator
- π« Avoid IFERROR function
### Web Interface- π Filter expressions optimization
- π Drag & drop file upload- π No duplicate measures
- π Real-time analysis
- π Interactive results viewer### Formatting Rules
- π Expandable rule checklist- π·οΈ Provide format strings for measures
- π Download reports- π Hide fact table columns used in measures
- π AI analyzer selector- π€ Object naming conventions
- π
Date and month column formatting
## π Usage- π’ Numeric column summarization settings
### Method 1: Web Interface### Error Prevention Rules
- β
Data columns must have source columns
```bash- π Expression-reliant objects must have expressions
python run_web_interface.py- π Relationship column data type consistency
```- π« Avoid invalid characters in names
1. Open http://localhost:5000### Maintenance Rules
2. Choose analyzer type (Regular or AI-Enhanced)- π§Ή Remove unnecessary columns and measures
3. Upload your `.SemanticModel` folder- π Fix referential integrity violations
4. View results and download report- π Add descriptions to objects
- π Remove unused perspectives and roles
### Method 2: Command Line
## Output
**Basic analysis:**
```bashThe analyzer generates comprehensive reports including:
python run_analyzer.py "Sales Dashboard.SemanticModel"
```- **Summary Statistics**: Count of tables, measures, columns, relationships
- **Violation Counts**: By severity (Error, Warning, Info) and category
**AI-enhanced analysis:**- **Detailed Violations**: Specific issues found with:
```bash - Rule name and description
python run_analyzer.py "Sales Dashboard.SemanticModel" --ai - Affected object and location
``` - Severity level
- Fix suggestions (where available)
**Custom output:**
```bash### Sample Output
python run_analyzer.py "Sales Dashboard.SemanticModel" --output "reports/my_report.md"
Model: Sales Dashboard.SemanticModel
import sys
sys.path.insert(0, 'src')## Summary
- Tables: 9
from tmdl_analyzer import TMDLBestPracticesAgent- Measures: 56
- Columns: 106
# Create analyzer- Relationships: 6
agent = TMDLBestPracticesAgent('data/BPARules.json')- Total Violations: 166
# Analyze model### Violations by Severity
result = agent.analyze_model('Sales Dashboard.SemanticModel')- WARNING: 90
- ERROR: 76
# Generate report
agent.generate_report(result, 'reports/output.md')### Violations by Category
```- Performance: 63
- DAX Expressions: 43
**AI-enhanced:**- Formatting: 60
```python```
from ai_enhanced_analyzer import AIEnhancedTMDLAnalyzer
## File Structure
agent = AIEnhancedTMDLAnalyzer('data/BPARules.json')
result = agent.analyze_model('Sales Dashboard.SemanticModel')```
```PBIP/
βββ tmdl_analyzer.py # Main analyzer engine
## π§ Configurationβββ web_interface.py # Web interface
βββ BPARules.json # Microsoft's best practice rules
### OpenAI API Key (for AI features)βββ requirements.txt # Python dependencies
βββ README.md # This file
Create `src/config.py`:βββ Sales Dashboard.SemanticModel/ # Sample TMDL model
```python βββ definition/
# OpenAI Configuration β βββ model.tmdl
OPENAI_API_KEY = "sk-proj-your-api-key-here" β βββ relationships.tmdl
OPENAI_MODEL = "gpt-4" # or "gpt-3.5-turbo" for faster/cheaper β βββ tables/
MAX_TOKENS = 300 β βββ Fact_Sales.tmdl
TEMPERATURE = 0.3 β βββ Dim_Customers.tmdl
``` β βββ ...
βββ ...
Or set environment variable:```
```bash
# Windows## Technical Details
set OPENAI_API_KEY=sk-proj-your-key-here
### TMDL Parser
# Linux/Mac- Parses table definitions and extracts measures, columns, properties
export OPENAI_API_KEY=sk-proj-your-key-here- Handles multi-line DAX expressions with proper escaping
```- Extracts relationship definitions and cardinalities
- Supports complex TMDL syntax and annotations
## π Analysis Results
### Rule Engine
### What Gets Checked- Implements Microsoft's Analysis Services best practice rules
- Supports rule expressions with pattern matching
The analyzer checks all 8 rules from Microsoft's BPARules.json:- Evaluates DAX code for common anti-patterns
- Provides contextual fix suggestions
1. **[Performance] Do not use floating point data types**
2. **[Performance] Set IsAvailableInMdx to false on non-attribute columns**### Web Interface
3. **[DAX Expressions] Column references should be fully qualified**- Flask-based web application
4. **[DAX Expressions] Measure references should be unqualified**- Drag-and-drop file upload with directory support
5. **[DAX Expressions] Use the DIVIDE function for division**- Real-time progress tracking
6. **[DAX Expressions] Avoid using the IFERROR function**- Interactive results visualization
7. **[Formatting] Provide format string for measures**- Downloadable reports
8. **[Formatting] Hide foreign keys**
## Supported TMDL Elements
### Results Include
- β
**Tables**: Data tables and calculated tables
- **Summary:** Object counts, violation totals by severity/category- β
**Measures**: DAX measures with expressions and formatting
- **Rules Checked:** All 8 rules showing passed β
or violations β- β
**Columns**: Data columns, calculated columns, and properties
- **Violations:** Detailed list with object info, descriptions, fix suggestions- β
**Relationships**: All relationship types and cardinalities
- **AI Recommendations:** (AI mode) Strategic guidance and implementation plan- β
**Partitions**: Data source and query information
- β
**Model Properties**: Model-level settings and annotations
## π Documentation
## Best Practices Covered
- **[docs/OPENAI_SETUP.md](docs/OPENAI_SETUP.md)** - Configure AI features
- **[docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md)** - Common issues and solutionsThe analyzer implements rules from Microsoft's official best practices guide:
- **[docs/RULE_LEVEL_AI_ENHANCEMENT.md](docs/RULE_LEVEL_AI_ENHANCEMENT.md)** - How AI analysis works- [Analysis Services Best Practice Rules](https://github.com/microsoft/Analysis-Services/tree/master/BestPracticeRules)
- **[docs/ALL_RULES_VISIBILITY.md](docs/ALL_RULES_VISIBILITY.md)** - Understanding the rules checklist- Performance optimization recommendations
- DAX coding standards
## π§ͺ Testing- Data modeling best practices
- Security and maintenance guidelines
Run tests:
```bash## Contributing
# Navigate to tests directory
cd testsTo add new rules or improve existing ones:
# Run individual tests1. **Add rules to BPARules.json** following Microsoft's format
python test_rules.py2. **Implement rule logic** in the `BestPracticesChecker` class
python test_ai_analyzer.py3. **Add tests** for new functionality
```4. **Update documentation** with new rule descriptions
## π‘ Examples## Troubleshooting
Check the `examples/` folder for sample scripts:### Common Issues
- `demo.py` - Basic usage example
- `quick_start_ai.py` - AI-enhanced quick start**"Definition folder not found"**
- `example_with_openai.py` - Advanced AI integration- Ensure you're pointing to the `.SemanticModel` directory
- Check that the `definition` folder exists with TMDL files
## π€ Contributing
**"BPARules.json not found"**
1. Fork the repository- Ensure the rules file is in the same directory as the analyzer
2. Create a feature branch- Download from the Microsoft repository if missing
3. Make your changes
4. Test thoroughly**Web interface not starting**
5. Submit a pull request- Check that Flask is installed: `pip install flask`
- Ensure port 5000 is not in use
## π License- Try running with different port: modify `app.run(port=5001)`
This project uses Microsoft's BPARules.json for best practice rules.## License
## π SupportThis tool is provided as-is for educational and analysis purposes. The best practice rules are from Microsoft's official Analysis Services repository.
- Check [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md) for common issues## Version History
- Review example scripts in `examples/`
- Check documentation in `docs/`- **v1.0.0** - Initial release with core analysis functionality
- **v1.1.0** - Added web interface and improved reporting
## π― Roadmap- **v1.2.0** - Enhanced TMDL parsing and additional rule support
- [ ] Add more Microsoft best practice rules
- [ ] Support for custom rules
- [ ] Export to different formats (JSON, CSV)
- [ ] Integration with Power BI pipelines
- [ ] Enhanced AI features
---
**Made with β€οΈ for the Power BI community**