{"id":29932970,"url":"https://github.com/utkarshg1/ml_project_backend","last_synced_at":"2026-05-01T21:33:57.024Z","repository":{"id":306914920,"uuid":"1027660507","full_name":"utkarshg1/ml_project_backend","owner":"utkarshg1","description":"ML project API backend with FastAPI","archived":false,"fork":false,"pushed_at":"2025-07-28T12:23:28.000Z","size":30,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-07-28T12:34:18.866Z","etag":null,"topics":["backend-api","fastapi","logistic-regression","machine-learning","pipeline","scikit-learn"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/utkarshg1.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-07-28T10:44:08.000Z","updated_at":"2025-07-28T12:23:32.000Z","dependencies_parsed_at":"2025-07-28T12:34:23.865Z","dependency_job_id":"9c237ad7-e716-4efb-881f-4113597257b9","html_url":"https://github.com/utkarshg1/ml_project_backend","commit_stats":null,"previous_names":["utkarshg1/ml_project_backend"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/utkarshg1/ml_project_backend","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/utkarshg1%2Fml_project_backend","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/utkarshg1%2Fml_project_backend/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/utkarshg1%2Fml_project_backend/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/utkarshg1%2Fml_project_backend/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/utkarshg1","download_url":"https://codeload.github.com/utkarshg1/ml_project_backend/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/utkarshg1%2Fml_project_backend/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":278741642,"owners_count":26037645,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-07T02:00:06.786Z","response_time":59,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["backend-api","fastapi","logistic-regression","machine-learning","pipeline","scikit-learn"],"created_at":"2025-08-02T18:34:51.631Z","updated_at":"2025-10-07T08:23:12.555Z","avatar_url":"https://github.com/utkarshg1.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Iris Classification API\n\nA FastAPI-based REST API for classifying Iris flower species using machine learning. This service provides endpoints for single predictions, batch processing, and file uploads.\n\n## 📋 Table of Contents\n\n- [Overview](#-overview)\n- [Features](#-features)\n- [API Endpoints](#-api-endpoints)\n- [Installation](#-installation)\n- [Usage](#-usage)\n- [API Reference](#-api-reference)\n- [Request/Response Models](#-requestresponse-models)\n- [Error Handling](#-error-handling)\n- [CORS Configuration](#-cors-configuration)\n- [Testing](#-testing)\n- [Deployment](#-deployment)\n- [Performance](#-performance)\n- [Author](#-author)\n\n## 🌸 Overview\n\nThis FastAPI service provides a production-ready REST API for the Iris flower classification model. It offers multiple prediction endpoints to handle different use cases, from single sample predictions to batch processing and file uploads.\n\nThe API is built on top of the trained Logistic Regression model and provides:\n\n- Real-time predictions with probability scores\n- Batch processing capabilities\n- File upload support for CSV datasets\n- Comprehensive error handling\n- CORS support for web applications\n- Interactive API documentation\n\n## ✨ Features\n\n- **RESTful API**: Clean, intuitive REST endpoints\n- **Multiple Input Methods**: Single samples, batch requests, and file uploads\n- **Probability Scores**: Returns prediction probabilities for all classes\n- **CORS Enabled**: Ready for web application integration\n- **Interactive Documentation**: Auto-generated Swagger UI and ReDoc\n- **Error Handling**: Comprehensive error responses\n- **Type Safety**: Pydantic models for request/response validation\n- **Health Check**: Service health monitoring endpoint\n\n## 🚀 API Endpoints\n\n| Method | Endpoint         | Description                                |\n| ------ | ---------------- | ------------------------------------------ |\n| `GET`  | `/`              | Welcome message and endpoint overview      |\n| `GET`  | `/health`        | Health check endpoint                      |\n| `POST` | `/predict`       | Single sample prediction                   |\n| `POST` | `/predict_batch` | Batch prediction for multiple samples      |\n| `POST` | `/predict_file`  | File upload prediction (CSV)               |\n| `GET`  | `/docs`          | Interactive API documentation (Swagger UI) |\n| `GET`  | `/redoc`         | Alternative API documentation (ReDoc)      |\n\n## 🔧 Installation\n\n### Prerequisites\n\n- Python 3.8+\n- Trained Iris model (run `main.py` first to generate the model)\n- [uv](https://docs.astral.sh/uv/) package manager (recommended)\n\n### Setup\n\n1. **Ensure the model is trained**\n\n   ```bash\n   # Train the model first if not already done\n   uv run main.py\n   ```\n\n2. **Install FastAPI dependencies**\n\n   ```bash\n   # Add FastAPI dependencies to your project\n   uv add fastapi uvicorn python-multipart\n   ```\n\n3. **Alternative: Install with pip**\n   ```bash\n   pip install fastapi uvicorn python-multipart\n   ```\n\n## 📖 Usage\n\n### Starting the Server\n\n**Development Server:**\n\n```bash\n# Using uv\nuv run uvicorn service:app --reload --host 0.0.0.0 --port 8000\n\n# Traditional method\nuvicorn service:app --reload --host 0.0.0.0 --port 8000\n```\n\n**Production Server:**\n\n```bash\n# Using uv with Gunicorn\nuv run gunicorn service:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000\n\n# Traditional method\ngunicorn service:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000\n```\n\nThe API will be available at:\n\n- **API Base URL**: `http://localhost:8000`\n- **Interactive Docs**: `http://localhost:8000/docs`\n- **Alternative Docs**: `http://localhost:8000/redoc`\n\n### API Usage Examples\n\n#### 1. Health Check\n\n```bash\ncurl -X GET \"http://localhost:8000/health\"\n```\n\n**Response:**\n\n```json\n{\n  \"status\": \"ok\"\n}\n```\n\n#### 2. Single Prediction\n\n```bash\ncurl -X POST \"http://localhost:8000/predict\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"sepal_length\": 5.1,\n    \"sepal_width\": 3.5,\n    \"petal_length\": 1.4,\n    \"petal_width\": 0.2\n  }'\n```\n\n**Response:**\n\n```json\n{\n  \"prediction\": \"setosa\",\n  \"probabilities\": {\n    \"setosa\": 0.9876,\n    \"versicolor\": 0.0123,\n    \"virginica\": 0.0001\n  }\n}\n```\n\n#### 3. Batch Prediction\n\n```bash\ncurl -X POST \"http://localhost:8000/predict_batch\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"samples\": [\n      {\n        \"sepal_length\": 5.1,\n        \"sepal_width\": 3.5,\n        \"petal_length\": 1.4,\n        \"petal_width\": 0.2\n      },\n      {\n        \"sepal_length\": 6.7,\n        \"sepal_width\": 3.1,\n        \"petal_length\": 4.7,\n        \"petal_width\": 1.5\n      }\n    ]\n  }'\n```\n\n**Response:**\n\n```json\n[\n  {\n    \"prediction\": \"setosa\",\n    \"probabilities\": {\n      \"setosa\": 0.9876,\n      \"versicolor\": 0.0123,\n      \"virginica\": 0.0001\n    }\n  },\n  {\n    \"prediction\": \"versicolor\",\n    \"probabilities\": {\n      \"setosa\": 0.0023,\n      \"versicolor\": 0.8456,\n      \"virginica\": 0.1521\n    }\n  }\n]\n```\n\n#### 4. File Upload Prediction\n\n```bash\ncurl -X POST \"http://localhost:8000/predict_file\" \\\n  -H \"Content-Type: multipart/form-data\" \\\n  -F \"file=@iris_sample.csv\"\n```\n\n**Sample CSV format:**\n\n```csv\nsepal_length,sepal_width,petal_length,petal_width\n5.1,3.5,1.4,0.2\n6.7,3.1,4.7,1.5\n5.8,2.7,5.1,1.9\n```\n\n## 📚 API Reference\n\n### Request Models\n\n#### Features\n\n```python\nclass Features(BaseModel):\n    sepal_length: float  # Sepal length in cm\n    sepal_width: float   # Sepal width in cm\n    petal_length: float  # Petal length in cm\n    petal_width: float   # Petal width in cm\n```\n\n#### BatchRequest\n\n```python\nclass BatchRequest(BaseModel):\n    samples: List[Features]  # List of feature samples\n```\n\n### Response Models\n\n#### PredictionResult\n\n```python\nclass PredictionResult(BaseModel):\n    prediction: str                    # Predicted species name\n    probabilities: Dict[str, float]    # Prediction probabilities by class\n```\n\n### Endpoints Detail\n\n#### `GET /`\n\n**Description**: Welcome endpoint with API overview\n**Response**: JSON object with welcome message and available endpoints\n\n#### `GET /health`\n\n**Description**: Health check endpoint for monitoring\n**Response**: `{\"status\": \"ok\"}`\n\n#### `POST /predict`\n\n**Description**: Predict species for a single sample\n**Request Body**: `Features` model\n**Response**: `PredictionResult` model\n\n#### `POST /predict_batch`\n\n**Description**: Predict species for multiple samples\n**Request Body**: `BatchRequest` model\n**Response**: `List[PredictionResult]`\n\n#### `POST /predict_file`\n\n**Description**: Predict species from uploaded CSV file\n**Request**: Multipart form data with CSV file\n**Response**: List of prediction results\n**File Requirements**:\n\n- Content type: `text/csv`\n- Required columns: `sepal_length`, `sepal_width`, `petal_length`, `petal_width`\n\n## ⚠️ Error Handling\n\nThe API provides comprehensive error handling:\n\n### HTTP Status Codes\n\n- `200`: Success\n- `400`: Bad Request (invalid input data)\n- `422`: Validation Error (invalid request format)\n- `500`: Internal Server Error\n\n### Example Error Response\n\n```json\n{\n  \"detail\": \"Only CSV files are accepted.\"\n}\n```\n\n### Common Errors\n\n1. **Invalid file type**: Only CSV files are accepted for file upload\n2. **Missing features**: All four features must be provided\n3. **Invalid data types**: Features must be numeric values\n4. **Model not found**: Ensure the model is trained and saved\n\n## 🌐 CORS Configuration\n\nThe API is configured with CORS middleware to allow cross-origin requests:\n\n```python\napp.add_middleware(\n    CORSMiddleware,\n    allow_origins=[\"*\"],        # Allow all origins\n    allow_methods=[\"POST\", \"GET\"], # Allowed HTTP methods\n    allow_headers=[\"Content-Type\"], # Allowed headers\n)\n```\n\n**Production Note**: Replace `allow_origins=[\"*\"]` with specific domains for security.\n\n## 🧪 Testing\n\nTest the API using the interactive documentation at `http://localhost:8000/docs` or use curl commands as shown in the usage examples above.\n\n## 🚀 Deployment\n\n### Docker Deployment\n\nCreate a `Dockerfile`:\n\n```dockerfile\nFROM python:3.9-slim\n\nWORKDIR /app\n\nCOPY requirements.txt .\nRUN pip install -r requirements.txt\n\nCOPY . .\n\nEXPOSE 8000\n\nCMD [\"uvicorn\", \"service:app\", \"--host\", \"0.0.0.0\", \"--port\", \"8000\"]\n```\n\nBuild and run:\n\n```bash\ndocker build -t iris-api .\ndocker run -p 8000:8000 iris-api\n```\n\n### Cloud Deployment Options\n\n1. **Heroku**: Use `Procfile` with `web: uvicorn service:app --host=0.0.0.0 --port=${PORT:-5000}`\n2. **AWS Lambda**: Use Mangum adapter for serverless deployment\n3. **Google Cloud Run**: Deploy with cloud-native scaling\n4. **Azure Container Instances**: Easy container deployment\n\n### Environment Variables\n\nSet these environment variables for production:\n\n- `MODEL_PATH`: Path to the trained model file\n- `HOST`: Server host (default: 0.0.0.0)\n- `PORT`: Server port (default: 8000)\n\n## ⚡ Performance\n\n- **Single Prediction**: ~10-50ms response time\n- **Batch Processing**: Scales linearly with sample count\n- **Memory Usage**: ~50-100MB per worker process\n- Model is cached using `@lru_cache` for efficient memory usage\n\n## 👨‍💻 Author\n\n**Utkarsh Gaikwad**\n\n## 📄 License\n\nThis project is open source and available under the [MIT License](LICENSE).\n\n---\n\n**Quick Start**:\n\n1. Train the model: `uv run main.py`\n2. Start the API: `uv run uvicorn service:app --reload`\n3. Visit `http://localhost:8000/docs` for interactive documentation\n4. Test with: `curl -X GET \"http://localhost:8000/health\"`\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Futkarshg1%2Fml_project_backend","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Futkarshg1%2Fml_project_backend","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Futkarshg1%2Fml_project_backend/lists"}