File size: 17,960 Bytes
a0debed |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 |
---
title: Proportio โ Precision Proportion Calculator
emoji: ๐งฎ
colorFrom: red
colorTo: gray
sdk: gradio
app_file: app.py
pinned: false
license: apache-2.0
tags:
- mcp-server
- proportion-calculator
- gradio
- python
- mathematics
- llm-tools
---
<div align="center">
<img src="logo_1024.png" alt="Proportio Logo" width="200" height="200">
</div>
[](LICENSE)
[](https://python.org)
[](Dockerfile)
[](tests/)
[](https://modelcontextprotocol.io)
**Professional mathematical calculations for proportions, percentages, and scaling operations with assertion-based validation and MCP server integration.**
---
## ๐ฏ Overview
Proportio is a specialized mathematical calculation server designed for LLM agents and applications requiring precise proportion calculations. Built with **assertion-based validation** and **zero-tolerance error handling**, it provides reliable mathematical operations through both a web interface and Model Context Protocol (MCP) integration.
### Key Use Cases
- **Recipe Scaling**: Scale ingredient quantities for different serving sizes
- **Financial Calculations**: Calculate percentages, ratios, and proportional growth
- **Engineering**: Resize dimensions, scale measurements, and maintain proportional relationships
- **Data Analysis**: Compute percentages, ratios, and proportional transformations
- **LLM Integration**: Provide reliable mathematical operations through MCP protocol
---
https://github.com/user-attachments/assets/96d30b20-1bf0-4b2b-a1ea-d0a5776f547c
---
## โจ Features
### ๐ข Mathematical Functions
- **Percentage Calculations** - Convert parts to percentages with precision
- **Proportion Solving** - Solve missing terms in a/b = c/d relationships
- **Ratio Scaling** - Scale values by precise ratios
- **Proportionality Constants** - Find k in y = kx relationships
- **Dimension Resizing** - Uniform scaling of width/height pairs
### ๐ก๏ธ Validation Architecture
- **Assertion-Based Validation** - Explicit mathematical preconditions
- **Zero Exception Handling** - No try-catch blocks, fast failure detection
- **Precise Error Messages** - Clear, actionable error descriptions
- **Type Safety** - Robust input validation and type checking
### ๐ Integration Options
- **Web Interface** - Professional Gradio-based UI with custom branding
- **MCP Server** - Native Model Context Protocol support for LLM agents
- **Docker Ready** - Containerized deployment with security best practices
- **API Access** - Direct function calls with comprehensive documentation
### ๐จ Professional Design
- **Custom Branding** - Red-black-white theme with geometric logo
- **Responsive Layout** - Optimized for desktop and mobile devices
- **Split Results** - Clear separation of input/output sections
- **Error Handling** - User-friendly error messages and validation
---
## ๐ Table of Contents
- [๐ฏ Overview](#-overview)
- [โจ Features](#-features)
- [๐ Quick Start](#-quick-start)
- [๐ง Core Functions](#-core-functions)
- [๐๏ธ Architecture](#๏ธ-architecture)
- [๐ฆ Installation](#-installation)
- [๐ณ Docker Deployment](#-docker-deployment)
- [๐งช Testing](#-testing)
- [๐ MCP Integration](#-mcp-integration)
- [๐ API Reference](#-api-reference)
- [๐ ๏ธ Development](#๏ธ-development)
- [๐ License](#-license)
---
## ๐ Quick Start
### Using Docker (Recommended)
```bash
# Clone the repository
git clone https://github.com/leksval/proportio.git
cd proportio
# Build and run with Docker
docker build -t proportio-server .
docker run -p 7860:7860 proportio-server
# Access the web interface
open http://localhost:7860
```
### Local Development
```bash
# Install dependencies
pip install -r requirements.txt
# Run the server
python proportion_server.py
# Access the web interface
open http://localhost:7860
```
### Quick Function Examples
```python
from proportion_server import percent_of, solve_proportion, resize_dimensions
# Calculate percentage
result = percent_of(25, 100) # Returns: 25.0
# Solve proportion: 3/4 = 6/?
result = solve_proportion(3, 4, 6, None) # Returns: 8.0
# Resize dimensions by 2x
width, height = resize_dimensions(100, 50, 2.0) # Returns: (200.0, 100.0)
```
---
## ๐ง Core Functions
### 1. **`percent_of(part, whole)`**
Calculate what percentage the part is of the whole.
```python
percent_of(25, 100) # โ 25.0%
percent_of(3, 4) # โ 75.0%
percent_of(150, 100) # โ 150.0%
```
**Mathematical Preconditions:**
- `whole != 0` (division by zero protection)
**Real-world Examples:**
- Sales conversion rates
- Test score percentages
- Growth rate calculations
### 2. **`solve_proportion(a, b, c, d)`**
Solve missing term in proportion a/b = c/d (exactly one parameter must be None).
```python
solve_proportion(3, 4, 6, None) # โ 8.0 (3/4 = 6/8)
solve_proportion(None, 4, 6, 8) # โ 3.0 (?/4 = 6/8)
solve_proportion(2, None, 6, 9) # โ 3.0 (2/? = 6/9)
```
**Mathematical Preconditions:**
- Exactly one value must be None (missing)
- Division denominators != 0 (varies by missing value)
**Real-world Examples:**
- Recipe scaling (4 servings : 2 cups = 6 servings : ? cups)
- Currency exchange rates
- Map scale calculations
### 3. **`scale_by_ratio(value, ratio)`**
Scale a value by a given ratio.
```python
scale_by_ratio(100, 1.5) # โ 150.0
scale_by_ratio(200, 0.5) # โ 100.0
scale_by_ratio(50, 2.0) # โ 100.0
```
**Use Cases:**
- Applying discount percentages
- Scaling measurements
- Financial calculations
### 4. **`direct_k(x, y)`**
Find proportionality constant k in direct variation y = kx.
```python
direct_k(5, 15) # โ 3.0 (15 = 3 ร 5)
direct_k(4, 12) # โ 3.0 (12 = 3 ร 4)
direct_k(2, 7) # โ 3.5 (7 = 3.5 ร 2)
```
**Mathematical Preconditions:**
- `x != 0` (division by zero protection)
**Applications:**
- Physics calculations (force = k ร displacement)
- Economics (cost = k ร quantity)
- Engineering (stress = k ร strain)
### 5. **`resize_dimensions(width, height, scale)`**
Resize dimensions with uniform scale factor.
```python
resize_dimensions(100, 50, 2.0) # โ (200.0, 100.0)
resize_dimensions(200, 100, 0.5) # โ (100.0, 50.0)
resize_dimensions(150, 75, 1.5) # โ (225.0, 112.5)
```
**Mathematical Preconditions:**
- `width >= 0` (dimensions must be non-negative)
- `height >= 0` (dimensions must be non-negative)
- `scale > 0` (scale factor must be positive)
**Applications:**
- Image resizing
- Screen resolution scaling
- Architectural drawings
---
## ๐๏ธ Architecture
### Assertion-Based Validation
Proportio uses **assertion-based validation** throughout, providing several key advantages:
```python
def percent_of(part: float, whole: float) -> float:
# Mathematical preconditions
assert whole != 0, "Division by zero: whole cannot be zero"
# Direct calculation
percentage = (part / whole) * 100
return percentage
```
**Benefits:**
- **Fast Failure**: Immediate error detection with precise messages
- **No Exception Overhead**: Zero try-catch complexity
- **Clear Preconditions**: Mathematical requirements explicitly documented
- **Predictable Behavior**: Consistent error handling across all functions
### Project Structure
```
proportio/
โโโ proportion_server.py # Core mathematical functions + Gradio server
โโโ models.py # Pydantic data models (simplified)
โโโ config.py # Configuration and logging setup
โโโ styles.css # Custom branding and responsive design
โโโ tests/
โ โโโ test_tools.py # Comprehensive test suite (58 tests)
โโโ requirements.txt # Minimal dependencies (3 packages)
โโโ Dockerfile # Single-stage containerization
โโโ README.md # This documentation
```
### Dependency Architecture
**Streamlined Dependencies** (only 3 required):
- **`gradio[mcp]>=5.0.0`** - Web framework with MCP server capabilities
- **`pydantic>=2.8.0`** - Data validation and parsing
- **`pytest>=8.0.0`** - Testing framework
### Error Handling Philosophy
**No Try-Catch Blocks** - All validation done through assertions:
```python
# โ Old approach (complex exception handling)
try:
if whole == 0:
raise ValueError("Division by zero")
result = part / whole
except ValueError as e:
# Handle error...
# โ
New approach (assertion-based)
assert whole != 0, "Division by zero: whole cannot be zero"
result = part / whole
```
---
## ๐ฆ Installation
### System Requirements
- **Python 3.11+**
- **pip** package manager
- **Docker** (optional, for containerized deployment)
### Local Installation
```bash
# Clone repository
git clone https://github.com/leksval/proportio.git
cd proportio
# Create virtual environment (recommended)
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt
# Verify installation
python -c "from proportion_server import percent_of; print(percent_of(25, 100))"
```
### Development Installation
```bash
# Install with development dependencies
pip install -r requirements.txt
# Run tests to verify setup
python -m pytest tests/test_tools.py -v
# Start development server
python proportion_server.py
```
---
## ๐ณ Docker Deployment
### Building the Container
```bash
# Build image
docker build -t proportio-server .
# Run container
docker run -p 7860:7860 proportio-server
# Run with custom configuration
docker run -p 8080:7860 -e PORT=7860 proportio-server
```
### Container Features
- **Security**: Non-root user execution
- **Optimization**: Single-stage build for minimal image size
- **Flexibility**: Configurable port and environment settings
- **Health**: Automatic process management
### Production Deployment
```bash
# Run detached with restart policy
docker run -d \
--name proportio \
--restart unless-stopped \
-p 7860:7860 \
proportio-server
# View logs
docker logs proportio
# Stop container
docker stop proportio
```
---
## ๐งช Testing
### Test Suite Coverage
**58 comprehensive tests** covering:
- โ
Basic functionality for all 5 core functions
- โ
Edge cases and boundary conditions
- โ
Error handling and assertion validation
- โ
Integration workflows and chained calculations
- โ
Floating-point precision and mathematical accuracy
- โ
Type validation and input sanitization
### Running Tests
```bash
# Run all tests
python -m pytest tests/test_tools.py -v
# Run specific test class
python -m pytest tests/test_tools.py::TestPercentOf -v
# Run with coverage (if pytest-cov installed)
python -m pytest tests/test_tools.py --cov=proportion_server
# Run tests in Docker
docker run --rm proportio-server python -m pytest tests/test_tools.py -v
```
### Test Categories
#### **Unit Tests**
- Individual function validation
- Mathematical accuracy verification
- Error condition testing
#### **Integration Tests**
- Chained calculation workflows
- Real-world scenario testing
- Cross-function compatibility
#### **Edge Case Tests**
- Floating-point precision limits
- Very large and very small numbers
- Boundary condition validation
### Sample Test Output
```
==================== test session starts ====================
collected 58 items
tests/test_tools.py::TestPercentOf::test_basic_percentage PASSED
tests/test_tools.py::TestPercentOf::test_zero_part PASSED
tests/test_tools.py::TestPercentOf::test_negative_values PASSED
...
tests/test_tools.py::TestIntegration::test_real_world_recipe_scaling PASSED
tests/test_tools.py::TestIntegration::test_financial_calculation_workflow PASSED
==================== 58 passed in 0.45s ====================
```
---
## ๐ MCP Integration
### Model Context Protocol Support
Proportio provides native **MCP server capabilities** for seamless LLM integration:
```python
# Launch with MCP support
demo.launch(
server_name="0.0.0.0",
server_port=7860,
mcp_server=True, # Enable MCP functionality
show_error=True
)
```
### Using with LLM Agents
The MCP server exposes all mathematical functions as tools that LLMs can call directly:
**Available MCP Tools:**
- `percent_of` - Calculate percentage relationships
- `solve_proportion` - Solve missing proportion terms
- `scale_by_ratio` - Apply scaling ratios
- `direct_k` - Find proportionality constants
- `resize_dimensions` - Scale dimensional pairs
### MCP Connection Example
```json
{
"name": "proportio",
"type": "sse",
"url": "http://localhost:7860/mcp"
}
```
### Integration Benefits
- **Reliable Math**: LLMs can delegate complex calculations
- **Error Handling**: Clear error messages for invalid inputs
- **Type Safety**: Automatic input validation and conversion
- **Performance**: Fast, direct mathematical operations
---
## ๐ API Reference
### Function Signatures
```python
def percent_of(part: float, whole: float) -> float:
"""Calculate percentage that part is of whole."""
def solve_proportion(
a: Optional[float] = None,
b: Optional[float] = None,
c: Optional[float] = None,
d: Optional[float] = None
) -> float:
"""Solve missing term in proportion a/b = c/d."""
def scale_by_ratio(value: float, ratio: float) -> float:
"""Scale value by given ratio."""
def direct_k(x: float, y: float) -> float:
"""Find proportionality constant k where y = kx."""
def resize_dimensions(width: float, height: float, scale: float) -> Tuple[float, float]:
"""Resize dimensions with uniform scale factor."""
```
### Error Messages
All functions provide clear, actionable error messages:
```python
# Division by zero errors
"Division by zero: whole cannot be zero"
"Division by zero: x cannot be zero"
"Division by zero: denominator"
# Validation errors
"Exactly one value must be None"
"Width must be non-negative"
"Height must be non-negative"
"Scale factor must be positive"
```
### Return Types
- **Single Values**: `float` for mathematical results
- **Dimension Pairs**: `Tuple[float, float]` for width/height
- **Errors**: `AssertionError` with descriptive messages
---
## ๐ ๏ธ Development
### Project Philosophy
1. **Assertion-Based Validation** - No try-catch complexity
2. **Mathematical Precision** - Accurate calculations with clear preconditions
3. **Minimal Dependencies** - Only essential packages
4. **Comprehensive Testing** - High test coverage with edge cases
5. **Professional Design** - Clean, branded user interface
### Code Style
```python
# Clear function signatures with type hints
def function_name(param: Type) -> ReturnType:
"""
Brief description.
Args:
param: Parameter description
Returns:
Return value description
Mathematical preconditions:
- Explicit constraint documentation
"""
# Assertion-based validation
assert condition, "Clear error message"
# Direct calculation
result = calculation
# Optional logging
logger.debug(f"Operation completed: {result}")
return result
```
### Adding New Functions
1. **Implement Core Logic** - Add function to `proportion_server.py`
2. **Add Mathematical Preconditions** - Document constraints explicitly
3. **Create Demo Function** - Add Gradio interface wrapper
4. **Write Comprehensive Tests** - Cover all edge cases
5. **Update Documentation** - Add examples and use cases
### Contributing Guidelines
1. **Fork the Repository** - Create your feature branch
2. **Follow Code Style** - Use assertion-based validation
3. **Add Tests** - Ensure comprehensive test coverage
4. **Update Documentation** - Keep README current
5. **Submit Pull Request** - Include description of changes
---
## ๐ License
This project is licensed under the **Apache License 2.0** - see the [LICENSE](LICENSE) file for details.
### Key License Points
- โ
**Commercial Use** - Use in commercial applications
- โ
**Modification** - Modify and distribute changes
- โ
**Distribution** - Distribute original or modified versions
- โ
**Patent Use** - Grant of patent rights from contributors
- โ ๏ธ **Attribution** - Must include license and copyright notice
- โ ๏ธ **State Changes** - Must document modifications
---
## ๐ค Support
### Getting Help
- **Issues**: [GitHub Issues](https://github.com/leksval/proportio/issues)
- **Documentation**: This README and inline code documentation
- **Examples**: See `tests/test_tools.py` for usage examples
### Contributing
We welcome contributions! Please see the [Development](#๏ธ-development) section for guidelines.
### Reporting Bugs
When reporting bugs, please include:
1. **Environment Details** (Python version, OS, Docker version)
2. **Reproduction Steps** (minimal code example)
3. **Expected vs Actual Behavior**
4. **Error Messages** (full stack trace if applicable)
---
**Built with โค๏ธ for mathematical precision and LLM integration**
*Proportio - Where Mathematics Meets Reliability*
|