{"id":32929237,"url":"https://github.com/viraj-gavade/wine-quality-api","last_synced_at":"2026-05-09T05:04:05.402Z","repository":{"id":322093307,"uuid":"1088184459","full_name":"viraj-gavade/Wine-Quality-API","owner":"viraj-gavade","description":"A modular FastAPI backend that serves PyTorch neural network models for wine analysis. Train, evaluate, and deploy models for both classification (wine type: red/white) and regression (quality score prediction) tasks through clean REST API endpoints.","archived":false,"fork":false,"pushed_at":"2025-11-02T13:57:25.000Z","size":95,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-11-02T15:19:34.610Z","etag":null,"topics":["fastapi","mlops","neural-networks","python","pytorch"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/viraj-gavade.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"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,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-11-02T13:38:23.000Z","updated_at":"2025-11-02T13:57:29.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/viraj-gavade/Wine-Quality-API","commit_stats":null,"previous_names":["viraj-gavade/wine-quality-api"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/viraj-gavade/Wine-Quality-API","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/viraj-gavade%2FWine-Quality-API","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/viraj-gavade%2FWine-Quality-API/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/viraj-gavade%2FWine-Quality-API/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/viraj-gavade%2FWine-Quality-API/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/viraj-gavade","download_url":"https://codeload.github.com/viraj-gavade/Wine-Quality-API/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/viraj-gavade%2FWine-Quality-API/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32807861,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-08T08:22:46.396Z","status":"online","status_checked_at":"2026-05-09T02:00:06.633Z","response_time":123,"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":["fastapi","mlops","neural-networks","python","pytorch"],"created_at":"2025-11-11T11:19:24.381Z","updated_at":"2026-05-09T05:04:05.394Z","avatar_url":"https://github.com/viraj-gavade.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Wine Quality API 🍷\n\nA modular FastAPI backend that serves PyTorch neural network models for wine analysis. Train, evaluate, and deploy models for both **classification** (wine type: red/white) and **regression** (quality score prediction) tasks through clean REST API endpoints.\n\n\u003e **Note:** This is a learning project focused on MLOps-style architecture, modular design, and deployment patterns rather than achieving state-of-the-art model accuracy.\n\n---\n\n## 🌐 Live Demo\n\n**🚀 Try it now:** [https://wine-quality-api-gidk.onrender.com](https://wine-quality-api-gidk.onrender.com)\n\n- **Interactive API Docs (Swagger UI)**: [https://wine-quality-api-gidk.onrender.com/docs](https://wine-quality-api-gidk.onrender.com/docs)\n- **API Documentation (ReDoc)**: [https://wine-quality-api-gidk.onrender.com/redoc](https://wine-quality-api-gidk.onrender.com/redoc)\n- **API Base URL**: `https://wine-quality-api-gidk.onrender.com/model`\n\n\u003e ⚠️ **Note:** Free-tier hosting may experience cold starts (~30-60 seconds) on the first request after inactivity.\n\n---\n\n## 📋 Table of Contents\n\n- [Live Demo](#-live-demo)\n- [Features](#-features)\n- [Tech Stack](#-tech-stack)\n- [Project Structure](#-project-structure)\n- [Quick Start](#-quick-start)\n- [API Reference](#-api-reference)\n- [Usage Examples](#-usage-examples)\n- [Configuration](#-configuration)\n- [Development](#-development)\n- [Contributing](#-contributing)\n- [License](#-license)\n\n---\n\n## ✨ Features\n\n- **🎯 Dual Task Support**: Train models for classification (wine type) or regression (quality prediction)\n- **🔧 Configurable Training**: Dynamic hyperparameter configuration via API requests\n- **💾 Model Persistence**: Automatic model saving/loading with organized file management\n- **📊 Evaluation Pipeline**: Comprehensive testing endpoints with metrics reporting\n- **🚀 Real-time Inference**: Fast prediction API for production use\n- **📝 Structured Logging**: Detailed logs for debugging and monitoring\n- **✅ Request Validation**: Pydantic schemas ensure data integrity\n- **📚 Auto Documentation**: Interactive API docs via Swagger UI\n- **🌐 Cloud Deployment**: Live production deployment on Render\n\n---\n\n## 🛠 Tech Stack\n\n| Component | Technology |\n|-----------|-----------|\n| **Framework** | FastAPI |\n| **ML Library** | PyTorch |\n| **Validation** | Pydantic |\n| **Server** | Uvicorn |\n| **Deployment** | Render |\n| **Language** | Python 3.x |\n\n---\n\n## 📁 Project Structure\n\n```\nwine-quality-api/\n├── app.py                      # FastAPI application entrypoint\n├── requirements.txt            # Python dependencies\n│\n├── controllers/                # Business logic layer\n│   └── model_controllers.py    # Train/test/predict implementations\n│\n├── routes/                     # API route definitions\n│   └── model_routes.py         # Model endpoint routes\n│\n├── Schemas/                    # Request/response models\n│   ├── train_schema.py         # Training request schema\n│   ├── test_schema.py          # Testing request schema\n│   └── predict_schema.py       # Prediction request schema\n│\n├── src/                        # Core ML components\n│   ├── models.py               # Neural network architectures\n│   ├── training_pipeline.py    # Training orchestration\n│   ├── testing_pipeline.py     # Evaluation logic\n│   └── processing.py           # Data preprocessing\n│\n├── utils/                      # Utility functions\n│   ├── data_loader.py          # Dataset loading\n│   ├── preprocessing.py        # Feature engineering\n│   ├── save_load.py            # Model serialization\n│   ├── params.py               # Parameter definitions\n│   └── logger.py               # Logging configuration\n│\n├── Models/                     # Model artifacts\n│   └── trained/                # Saved .pth model files\n│\n├── data/                       # Datasets\n│   └── processed_winequality.csv\n│\n├── notebooks/                  # Jupyter experiments\n│   └── exploration.ipynb\n│\n└── logs/                       # Application logs\n    └── training.log\n```\n\n### Component Overview\n\n| Directory | Purpose |\n|-----------|---------|\n| `controllers/` | Glue layer between routes and ML pipelines; handles model selection and response formatting |\n| `routes/` | FastAPI router registration and endpoint definitions |\n| `Schemas/` | Pydantic models for request validation and response serialization |\n| `src/` | Core ML functionality: model architecture, training loops, evaluation |\n| `utils/` | Shared utilities: data loading, preprocessing, I/O operations, configuration |\n| `Models/trained/` | Persistent storage for trained model weights (.pth files) |\n\n---\n\n## 🚀 Quick Start\n\n### Option 1: Use the Live API (Recommended for Testing)\n\nSimply visit the Swagger UI and start making requests:\n- **Swagger UI**: [https://wine-quality-api-gidk.onrender.com/docs](https://wine-quality-api-gidk.onrender.com/docs)\n\nNo installation required! 🎉\n\n### Option 2: Run Locally\n\n#### Prerequisites\n\n- Python 3.8 or higher\n- pip package manager\n- (Optional) CUDA-compatible GPU for faster training\n\n#### Installation\n\n1. **Clone the repository**\n   ```bash\n   git clone https://github.com/yourusername/wine-quality-api.git\n   cd wine-quality-api\n   ```\n\n2. **Create virtual environment**\n   ```bash\n   # Windows (PowerShell)\n   python -m venv .venv\n   .\\.venv\\Scripts\\Activate.ps1\n   \n   # macOS/Linux\n   python3 -m venv .venv\n   source .venv/bin/activate\n   ```\n\n3. **Install dependencies**\n   ```bash\n   pip install -r requirements.txt\n   ```\n\n4. **Configure dataset path**\n   \n   Edit `controllers/model_controllers.py` and update the `file_path` variable:\n   ```python\n   file_path = r\"path/to/your/data/processed_winequality.csv\"\n   ```\n\n5. **Start the server**\n   ```bash\n   uvicorn app:app --reload --host 0.0.0.0 --port 8000\n   ```\n\n6. **Access the local API**\n   - **Swagger UI**: http://127.0.0.1:8000/docs\n   - **ReDoc**: http://127.0.0.1:8000/redoc\n   - **API Base**: http://127.0.0.1:8000/model\n\n---\n\n## 📡 API Reference\n\nAll endpoints are mounted under the `/model` prefix.\n\n### Base URLs\n- **Production**: `https://wine-quality-api-gidk.onrender.com/model`\n- **Local**: `http://127.0.0.1:8000/model`\n\n### 1. Train Model\n\n**Endpoint:** `POST /model/train/`\n\nTrain a new model with custom hyperparameters.\n\n**Request Body:**\n```json\n{\n  \"model_type\": \"classification\",\n  \"epochs\": 50,\n  \"learning_rate\": 0.001,\n  \"optimizer\": \"Adam\",\n  \"loss_function\": \"CrossEntropyLoss\",\n  \"output_feature\": \"type\",\n  \"model_file_name\": \"wine_class_model.pth\"\n}\n```\n\n**Parameters:**\n\n| Field | Type | Options | Description |\n|-------|------|---------|-------------|\n| `model_type` | string | `classification`, `regression` | Task type |\n| `epochs` | integer | 1-1000 | Training iterations |\n| `learning_rate` | float | 0.0001-0.1 | Optimizer learning rate |\n| `optimizer` | string | `Adam`, `SGD`, `RMSprop` | Optimization algorithm |\n| `loss_function` | string | `CrossEntropyLoss`, `MSELoss`, `L1Loss` | Loss function |\n| `output_feature` | string | `type`, `quality` | Target column |\n| `model_file_name` | string | Any valid filename | Save location |\n\n**Response:**\n```json\n{\n  \"status\": \"Training completed successfully\",\n  \"model_type\": \"classification\",\n  \"optimizer\": \"Adam\",\n  \"loss_function\": \"CrossEntropyLoss\",\n  \"epochs\": 50,\n  \"learning_rate\": 0.001,\n  \"model_path\": \"Models/trained/classification_20250102_143022.pth\"\n}\n```\n\n---\n\n### 2. Test Model\n\n**Endpoint:** `POST /model/test/`\n\nEvaluate a saved model on the test dataset.\n\n**Request Body:**\n```json\n{\n  \"model_type\": \"regression\",\n  \"epochs\": 50,\n  \"learning_rate\": 0.001,\n  \"optimizer\": \"Adam\",\n  \"loss_function\": \"MSELoss\",\n  \"output_feature\": \"quality\",\n  \"model_file_name\": \"wine_regression_model.pth\"\n}\n```\n\n**Response:**\n```json\n{\n  \"status\": \"Model evaluation completed successfully\",\n  \"model_type\": \"regression\",\n  \"model_file_name\": \"wine_regression_model.pth\",\n  \"results\": {\n    \"loss\": 0.234,\n    \"r2_score\": 0.82,\n    \"mae\": 0.45\n  }\n}\n```\n\n---\n\n### 3. Predict\n\n**Endpoint:** `POST /model/predict`\n\nRun inference on new data using a trained model.\n\n**Request Body:**\n```json\n{\n  \"model_type\": \"classification\",\n  \"model_file_name\": \"wine_classification_model.pth\",\n  \"input_data\": [\n    [7.4, 0.7, 0.0, 1.9, 0.076, 11.0, 34.0, 0.9978, 3.51, 0.56, 9.4, 0.0]\n  ],\n  \"device\": \"cpu\"\n}\n```\n\n**Input Features (in order):**\n1. Fixed acidity\n2. Volatile acidity\n3. Citric acid\n4. Residual sugar\n5. Chlorides\n6. Free sulfur dioxide\n7. Total sulfur dioxide\n8. Density\n9. pH\n10. Sulphates\n11. Alcohol\n12. (Reserved for encoding)\n\n**Response:**\n```json\n{\n  \"status\": \"Prediction successful\",\n  \"model_type\": \"classification\",\n  \"predictions\": [1]\n}\n```\n\n**Prediction Outputs:**\n- **Classification**: `0` (red wine) or `1` (white wine)\n- **Regression**: Float value between 0-10 (quality score)\n\n---\n\n## 💡 Usage Examples\n\n### Training a Classification Model (Production)\n\n**PowerShell:**\n```powershell\n$body = @{\n    model_type = \"classification\"\n    epochs = 100\n    learning_rate = 0.001\n    optimizer = \"Adam\"\n    loss_function = \"CrossEntropyLoss\"\n    output_feature = \"type\"\n    model_file_name = \"wine_classifier_v1.pth\"\n} | ConvertTo-Json\n\nInvoke-RestMethod -Uri \"https://wine-quality-api-gidk.onrender.com/model/train/\" -Method POST -Body $body -ContentType \"application/json\"\n```\n\n**cURL:**\n```bash\ncurl -X POST \"https://wine-quality-api-gidk.onrender.com/model/train/\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"model_type\": \"classification\",\n    \"epochs\": 100,\n    \"learning_rate\": 0.001,\n    \"optimizer\": \"Adam\",\n    \"loss_function\": \"CrossEntropyLoss\",\n    \"output_feature\": \"type\",\n    \"model_file_name\": \"wine_classifier_v1.pth\"\n  }'\n```\n\n**Python:**\n```python\nimport requests\n\n# Use production API\nBASE_URL = \"https://wine-quality-api-gidk.onrender.com\"\n\npayload = {\n    \"model_type\": \"classification\",\n    \"epochs\": 100,\n    \"learning_rate\": 0.001,\n    \"optimizer\": \"Adam\",\n    \"loss_function\": \"CrossEntropyLoss\",\n    \"output_feature\": \"type\",\n    \"model_file_name\": \"wine_classifier_v1.pth\"\n}\n\nresponse = requests.post(\n    f\"{BASE_URL}/model/train/\",\n    json=payload\n)\nprint(response.json())\n```\n\n---\n\n### Making Predictions (Production)\n\n**Python:**\n```python\nimport requests\n\nBASE_URL = \"https://wine-quality-api-gidk.onrender.com\"\n\n# Sample wine features\nwine_sample = [7.4, 0.7, 0.0, 1.9, 0.076, 11.0, 34.0, 0.9978, 3.51, 0.56, 9.4, 0.0]\n\npayload = {\n    \"model_type\": \"classification\",\n    \"model_file_name\": \"wine_classifier_v1.pth\",\n    \"input_data\": [wine_sample],\n    \"device\": \"cpu\"\n}\n\nresponse = requests.post(\n    f\"{BASE_URL}/model/predict\",\n    json=payload\n)\n\nresult = response.json()\nwine_type = \"White Wine\" if result[\"predictions\"][0] == 1 else \"Red Wine\"\nprint(f\"Prediction: {wine_type}\")\n```\n\n**JavaScript (Fetch):**\n```javascript\nconst BASE_URL = \"https://wine-quality-api-gidk.onrender.com\";\n\nconst wineSample = [7.4, 0.7, 0.0, 1.9, 0.076, 11.0, 34.0, 0.9978, 3.51, 0.56, 9.4, 0.0];\n\nconst payload = {\n  model_type: \"classification\",\n  model_file_name: \"wine_classifier_v1.pth\",\n  input_data: [wineSample],\n  device: \"cpu\"\n};\n\nfetch(`${BASE_URL}/model/predict`, {\n  method: \"POST\",\n  headers: { \"Content-Type\": \"application/json\" },\n  body: JSON.stringify(payload)\n})\n  .then(res =\u003e res.json())\n  .then(data =\u003e {\n    const wineType = data.predictions[0] === 1 ? \"White Wine\" : \"Red Wine\";\n    console.log(`Prediction: ${wineType}`);\n  });\n```\n\n---\n\n## ⚙️ Configuration\n\n### Environment Variables\n\nCreate a `.env` file in the project root:\n\n```env\n# Server Configuration\nHOST=0.0.0.0\nPORT=8000\nRELOAD=true\n\n# Dataset Path\nDATA_PATH=data/processed_winequality.csv\n\n# Model Storage\nMODEL_DIR=Models/trained/\n\n# Logging\nLOG_LEVEL=INFO\nLOG_FILE=logs/training.log\n\n# PyTorch\nCUDA_VISIBLE_DEVICES=0\n```\n\n### Hyperparameter Tuning\n\nRecommended starting points:\n\n**Classification:**\n- Epochs: 50-150\n- Learning Rate: 0.001-0.01\n- Optimizer: Adam\n- Loss: CrossEntropyLoss\n\n**Regression:**\n- Epochs: 100-200\n- Learning Rate: 0.0001-0.001\n- Optimizer: Adam\n- Loss: MSELoss or L1Loss\n\n---\n\n## 🔧 Development\n\n### Running Tests\n\n```bash\npytest tests/ -v\n```\n\n### Code Formatting\n\n```bash\n# Format with black\nblack .\n\n# Sort imports\nisort .\n\n# Lint with flake8\nflake8 .\n```\n\n### Logging\n\nLogs are written to:\n- **File**: `logs/training.log`\n- **Console**: stdout (during development with `--reload`)\n\nLog levels: DEBUG, INFO, WARNING, ERROR, CRITICAL\n\n---\n\n## 🤝 Contributing\n\nContributions are welcome! This is a learning project, so feel free to experiment and suggest improvements.\n\n1. Fork the repository\n2. Create a feature branch (`git checkout -b feature/AmazingFeature`)\n3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)\n4. Push to the branch (`git push origin feature/AmazingFeature`)\n5. Open a Pull Request\n\n---\n\n## 📄 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n---\n\n## 👨‍💻 Author\n\n**Viraj Gavade**\n\nA learning project exploring modern ML deployment patterns with FastAPI and PyTorch. Built to demonstrate modular pipeline architecture, clean API design, and MLOps best practices.\n\n---\n\n## 🙏 Acknowledgments\n\n- FastAPI framework for excellent developer experience\n- PyTorch team for the powerful ML library\n- UCI Machine Learning Repository for the wine quality dataset\n- Render for reliable free-tier hosting\n\n---\n\n## 📞 Support\n\n- 🌐 **Live API**: [https://wine-quality-api-gidk.onrender.com/docs](https://wine-quality-api-gidk.onrender.com/docs)\n- 📧 **Email**: vrajgavade17@gmail.com\n- 🐛 **Issues**: [GitHub Issues](https://github.com/yourusername/wine-quality-api/issues)\n- 💬 **Discussions**: [GitHub Discussions](https://github.com/yourusername/wine-quality-api/discussions)\n\n---\n\n## 🚀 Deployment\n\nThis API is deployed on Render's free tier. For your own deployment:\n\n1. Fork this repository\n2. Connect your GitHub repo to Render\n3. Configure build command: `pip install -r requirements.txt`\n4. Configure start command: `uvicorn app:app --host 0.0.0.0 --port $PORT`\n5. Deploy! 🎉\n\n---\n\n**⭐ If you find this project helpful, please consider giving it a star!**\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fviraj-gavade%2Fwine-quality-api","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fviraj-gavade%2Fwine-quality-api","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fviraj-gavade%2Fwine-quality-api/lists"}