{"id":29996729,"url":"https://github.com/nhanphamthanh-it/handwritten-digits-classification","last_synced_at":"2025-08-05T02:54:34.695Z","repository":{"id":306919102,"uuid":"1027504843","full_name":"NhanPhamThanh-IT/Handwritten-Digits-Classification","owner":"NhanPhamThanh-IT","description":"✏️ An AI-driven web app for handwritten digit recognition using the MNIST dataset. It leverages TensorFlow for deep learning model training and Gradio to create an intuitive, interactive UI. Users can draw digits and receive instant predictions, showcasing practical AI deployment and real-time inference capabilities.","archived":false,"fork":false,"pushed_at":"2025-07-28T11:16:18.000Z","size":1019,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-07-28T13:14:25.830Z","etag":null,"topics":["artificial-intelligence","classification","dataset","deep-learning","gradio","gradio-interface","handwritten-digit-recognition","jupyter-notebook","learning-materials","machine-learning","mnist","model-training","network-layer","neural-network","open-source","python","realtime-rendering","tensorflow","web-application"],"latest_commit_sha":null,"homepage":"","language":"Jupyter Notebook","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/NhanPhamThanh-IT.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-28T05:45:53.000Z","updated_at":"2025-07-28T11:16:22.000Z","dependencies_parsed_at":"2025-07-28T13:15:19.499Z","dependency_job_id":"483501e3-4f4c-4587-bf62-17be2a2cddba","html_url":"https://github.com/NhanPhamThanh-IT/Handwritten-Digits-Classification","commit_stats":null,"previous_names":["nhanphamthanh-it/handwritten-digits-classification"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/NhanPhamThanh-IT/Handwritten-Digits-Classification","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NhanPhamThanh-IT%2FHandwritten-Digits-Classification","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NhanPhamThanh-IT%2FHandwritten-Digits-Classification/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NhanPhamThanh-IT%2FHandwritten-Digits-Classification/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NhanPhamThanh-IT%2FHandwritten-Digits-Classification/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/NhanPhamThanh-IT","download_url":"https://codeload.github.com/NhanPhamThanh-IT/Handwritten-Digits-Classification/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NhanPhamThanh-IT%2FHandwritten-Digits-Classification/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":268825602,"owners_count":24313268,"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-08-05T02:00:12.334Z","response_time":2576,"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":["artificial-intelligence","classification","dataset","deep-learning","gradio","gradio-interface","handwritten-digit-recognition","jupyter-notebook","learning-materials","machine-learning","mnist","model-training","network-layer","neural-network","open-source","python","realtime-rendering","tensorflow","web-application"],"created_at":"2025-08-05T02:54:31.134Z","updated_at":"2025-08-05T02:54:34.660Z","avatar_url":"https://github.com/NhanPhamThanh-IT.png","language":"Jupyter Notebook","funding_links":[],"categories":[],"sub_categories":[],"readme":"# \u003cdiv align=\"center\"\u003e✏️ Handwritten-Digits-Classification ✏️\u003c/div\u003e\n\n\u003cdiv align=\"center\"\u003e\n\n![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg) ![Python](https://img.shields.io/badge/python-3.8%2B-blue) ![TensorFlow](https://img.shields.io/badge/TensorFlow-2.x-orange) ![Gradio](https://img.shields.io/badge/Gradio-UI-green) ![Build](https://img.shields.io/badge/build-passing-brightgreen) ![Contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg)\n\n_An AI-driven web app for handwritten digit recognition using the MNIST dataset. It leverages TensorFlow for deep learning model training and Gradio to create an intuitive, interactive UI. Users can draw digits and receive instant predictions, showcasing practical AI deployment and real-time inference capabilities._\n\n\u003c/div\u003e\n\n---\n\n\u003cdiv align=\"justify\"\u003e\n\n## Table of Contents\n\n- [Overview](#overview)\n- [Features](#features)\n- [Demo](#demo)\n- [Architecture](#architecture)\n- [Project Structure](#project-structure)\n- [Installation](#installation)\n- [Environment Variables](#environment-variables)\n- [Usage](#usage)\n- [Model Details](#model-details)\n- [Gradio Interface](#gradio-interface)\n- [Configuration](#configuration)\n- [Testing](#testing)\n- [Deployment](#deployment)\n- [Customization](#customization)\n- [Performance Tips](#performance-tips)\n- [Code Walkthrough](#code-walkthrough)\n- [Troubleshooting](#troubleshooting)\n- [FAQ](#faq)\n- [Contributing](#contributing)\n- [License](#license)\n- [References](#references)\n- [Acknowledgements](#acknowledgements)\n- [Contact](#contact)\n\n---\n\n## Project Content\n\n### 1. Application Code (`app/`)\n- **`main.py`**  \n  The main entry point for the application. It loads the trained Keras model and launches a Gradio web interface, allowing users to draw digits and receive instant predictions.\n\n- **`configs/system-variables.py`**  \n  Contains system configuration variables such as the model path, input size, and other settings that control the app’s behavior.\n\n- **`configs/__init__.py`**  \n  Marks the `configs` directory as a Python package.\n\n---\n\n### 2. Models (`models/`)\n- **`model.keras`**  \n  The pre-trained Keras model file used for digit classification.\n\n- **`training.ipynb`**  \n  A Jupyter notebook for training and evaluating the model on the MNIST dataset. Users can retrain the model, experiment with different architectures, and save new models.\n\n---\n\n### 3. Documentation (`docs/`)\n- **`gradio.md`**  \n  Documentation on using Gradio for the user interface, including setup and customization tips.\n\n- **`mnist-dataset.md`**  \n  Information about the MNIST dataset, its structure, and how it is used in this project.\n\n- **`tensorflow.md`**  \n  Guidance and notes on using TensorFlow within the project, including installation and troubleshooting.\n\n---\n\n### 4. Project Management \u0026 Metadata\n- **`README.md`**  \n  The main documentation file, providing an overview, setup instructions, usage, customization, deployment, troubleshooting, and more.\n\n- **`requirements.txt`**  \n  Lists all Python dependencies required to run the project, such as TensorFlow and Gradio.\n\n- **`LICENSE`**  \n  The MIT License file, specifying the terms for open-source use and distribution.\n\n---\n\n### 5. Key Features\n- **Interactive Gradio UI:**  \n  Users can draw digits in their browser and receive real-time predictions from the trained model.\n\n- **Deep Learning Model:**  \n  Utilizes a Convolutional Neural Network (CNN) trained on the MNIST dataset for high-accuracy digit recognition.\n\n- **Easy Retraining:**  \n  The included Jupyter notebook allows users to retrain the model or experiment with new architectures.\n\n- **Configurable:**  \n  System variables and settings can be easily adjusted in the configuration files.\n\n- **Well-Documented:**  \n  Comprehensive guides and code comments are provided for easy understanding and customization.\n\n---\n\n### 6. Example Directory Structure\n\n```\nHandwritten-Digits-Classification/\n│\n├── app/\n│   ├── configs/\n│   │   ├── __init__.py\n│   │   └── system-variables.py\n│   └── main.py\n│\n├── docs/\n│   ├── gradio.md\n│   ├── mnist-dataset.md\n│   └── tensorflow.md\n│\n├── models/\n│   ├── model.keras\n│   └── training.ipynb\n│\n├── README.md\n├── requirements.txt\n└── LICENSE\n```\n\n---\n\n## Overview\n\nThis project demonstrates a complete pipeline for handwritten digit recognition using deep learning. It includes:\n\n- Training a neural network on the MNIST dataset.\n- Saving and loading the trained model.\n- Deploying the model as a web app using Gradio, allowing users to draw digits and get instant predictions.\n\nThe project is ideal for learning about computer vision, neural networks, and deploying AI models in real-world applications.\n\n---\n\n## Features\n\n- 🧠 **Deep Learning Model**: Built with TensorFlow/Keras, trained on MNIST.\n- 🖼️ **Interactive UI**: Draw digits directly in your browser using Gradio.\n- ⚡ **Real-Time Inference**: Instant predictions as you draw.\n- 🔄 **Easy Retraining**: Jupyter notebook provided for model retraining.\n- 🛠️ **Configurable**: System variables and settings are easily adjustable.\n- 📦 **Portable**: Simple requirements, easy to run locally.\n- 📝 **Well-Documented**: Includes guides and code comments for easy understanding.\n- 🧪 **Tested**: Model and app tested for accuracy and usability.\n- 🌐 **Deployable**: Ready for deployment on cloud or local servers.\n- 🔒 **Secure**: No user data is stored or transmitted externally.\n\n---\n\n## Demo\n\n\u003e **Live Demo:** _Coming soon!_\n\n![Gradio Demo Screenshot](assets/screenshot.jpg) \u003c!-- Replace with actual screenshot if available --\u003e\n\n---\n\n## Architecture\n\n```mermaid\nflowchart TD\n    A[User draws digit in browser] --\u003e B[Gradio UI]\n    B --\u003e C[Image Preprocessing]\n    C --\u003e D[Trained TensorFlow Model]\n    D --\u003e E[Prediction Output]\n    E --\u003e F[Display result in UI]\n```\n\n- **Frontend**: Gradio web interface for drawing and displaying results.\n- **Backend**: Python server running TensorFlow model for inference.\n- **Model**: CNN trained on MNIST dataset.\n\n---\n\n## Project Structure\n\n```\nHandwritten-Digits-Classification/\n│\n├── app/\n│   ├── configs/\n│   │   ├── __init__.py\n│   │   └── system-variables.py\n│   └── main.py\n│\n├── docs/\n│   ├── gradio.md\n│   ├── mnist-dataset.md\n│   └── tensorflow.md\n│\n├── models/\n│   ├── model.keras\n│   └── training.ipynb\n│\n├── README.md\n├── requirements.txt\n└── LICENSE\n```\n\n- **app/**: Main application code and configuration.\n- **docs/**: Documentation and guides.\n- **models/**: Trained model and training notebook.\n- **requirements.txt**: Python dependencies.\n\n---\n\n## Installation\n\n### 1. Clone the Repository\n\n```bash\ngit clone https://github.com/NhanPhamThanh-IT/Handwritten-Digits-Classification.git\ncd Handwritten-Digits-Classification\n```\n\n### 2. Create a Virtual Environment (Recommended)\n\n```bash\npython -m venv venv\nsource venv/bin/activate  # On Windows: venv\\Scripts\\activate\n```\n\n### 3. Install Dependencies\n\n```bash\npip install -r requirements.txt\n```\n\n---\n\n## Environment Variables\n\nYou can configure the following environment variables (optional):\n\n| Variable    | Description                    | Default Value      |\n| ----------- | ------------------------------ | ------------------ |\n| MODEL_PATH  | Path to the trained model file | models/model.keras |\n| GRADIO_PORT | Port for Gradio web server     | 7860               |\n| DEBUG       | Enable debug mode (True/False) | False              |\n\nSet them in your shell or in a `.env` file (if using `python-dotenv`).\n\n---\n\n## Usage\n\n### 1. Train the Model (Optional)\n\nIf you want to retrain the model, open the Jupyter notebook:\n\n```bash\njupyter notebook models/training.ipynb\n```\n\nFollow the notebook instructions to train and save a new model.\n\n### 2. Run the Web App\n\n```bash\npython app/main.py\n```\n\nThis will launch the Gradio interface in your browser. Draw a digit and see the prediction in real time!\n\n#### Custom Port\n\n```bash\nGRADIO_PORT=8080 python app/main.py\n```\n\n---\n\n## Model Details\n\n- **Dataset**: [MNIST](http://yann.lecun.com/exdb/mnist/)\n- **Architecture**: Convolutional Neural Network (CNN)\n- **Framework**: TensorFlow / Keras\n- **Input**: 28x28 grayscale images\n- **Output**: Digit class (0-9)\n- **Training Notebook**: `models/training.ipynb`\n- **Saved Model**: `models/model.keras`\n\n### Example Model Architecture\n\n```python\nimport tensorflow as tf\nfrom tensorflow.keras import layers, models\n\nmodel = models.Sequential([\n    layers.Input(shape=(28, 28, 1)),\n    layers.Conv2D(32, (3, 3), activation='relu'),\n    layers.MaxPooling2D((2, 2)),\n    layers.Conv2D(64, (3, 3), activation='relu'),\n    layers.MaxPooling2D((2, 2)),\n    layers.Flatten(),\n    layers.Dense(64, activation='relu'),\n    layers.Dense(10, activation='softmax')\n])\n```\n\n---\n\n## Gradio Interface\n\nThe app uses Gradio to provide a user-friendly web interface:\n\n- **Draw Area**: Use your mouse or touchscreen to draw a digit.\n- **Predict Button**: Instantly see the model's prediction and confidence.\n- **Clear Button**: Reset the canvas to try again.\n\n### Example Gradio Integration\n\n```python\nimport gradio as gr\nimport numpy as np\nfrom tensorflow.keras.models import load_model\n\nmodel = load_model('models/model.keras')\n\ndef predict_digit(image):\n    image = image.reshape(1, 28, 28, 1) / 255.0\n    prediction = model.predict(image)\n    return {str(i): float(prediction[0][i]) for i in range(10)}\n\niface = gr.Interface(\n    fn=predict_digit,\n    inputs=gr.Image(shape=(28, 28), image_mode='L', invert_colors=True, source='canvas'),\n    outputs=gr.Label(num_top_classes=3),\n    live=True,\n    title=\"Handwritten Digit Recognition\",\n    description=\"Draw a digit (0-9) and the model will predict it!\"\n)\n\niface.launch()\n```\n\nFor more details, see [docs/gradio.md](docs/gradio.md).\n\n---\n\n## Configuration\n\nSystem variables and settings can be adjusted in:\n\n- `app/configs/system-variables.py`\n\nYou can modify parameters such as model path, input size, etc.\n\n---\n\n## Testing\n\nTo test the model or app:\n\n1. **Unit Tests**: (Add your own tests in a `tests/` directory)\n2. **Manual Testing**: Run the app and try drawing various digits.\n3. **Model Evaluation**: Use the notebook to evaluate accuracy on the MNIST test set.\n\n---\n\n## Deployment\n\n### Deploy on Hugging Face Spaces\n\n- [Gradio + Hugging Face Spaces Guide](https://gradio.app/docs/hosting_on_huggingface/)\n\n### Deploy on Heroku\n\n1. Add a `Procfile`:\n   ```\n   web: python app/main.py\n   ```\n2. Push to Heroku and set buildpacks for Python.\n\n### Docker Deployment\n\n1. Create a `Dockerfile`:\n   ```dockerfile\n   FROM python:3.10\n   WORKDIR /app\n   COPY . .\n   RUN pip install -r requirements.txt\n   EXPOSE 7860\n   CMD [\"python\", \"app/main.py\"]\n   ```\n2. Build and run:\n   ```bash\n   docker build -t digit-classifier .\n   docker run -p 7860:7860 digit-classifier\n   ```\n\n---\n\n## Customization\n\n- **Change Model**: Edit and retrain in `models/training.ipynb`.\n- **Change UI**: Modify Gradio interface in `app/main.py`.\n- **Add Features**: E.g., upload image, batch prediction, etc.\n\n---\n\n## Performance Tips\n\n- Use GPU for faster training (see TensorFlow docs).\n- Optimize model size for faster inference.\n- Use quantization or pruning for deployment on edge devices.\n\n---\n\n## Code Walkthrough\n\n- **app/main.py**: Entry point for the Gradio app. Loads the model and defines the prediction function.\n- **models/training.ipynb**: Jupyter notebook for training and evaluating the model.\n- **app/configs/system-variables.py**: Stores configuration variables (e.g., model path).\n- **docs/**: Contains additional documentation on Gradio, MNIST, and TensorFlow.\n\n---\n\n## Troubleshooting\n\n- **Gradio not launching?**\n\n  - Ensure all dependencies are installed.\n  - Try running `python -m pip install --upgrade pip` and reinstall requirements.\n\n- **Model not found?**\n\n  - Make sure `models/model.keras` exists, or retrain using the notebook.\n\n- **Jupyter not found?**\n\n  - Install with `pip install notebook`.\n\n- **Other issues?**\n  - Check the [docs/](docs/) folder for more help.\n\n---\n\n## FAQ\n\n**Q: Can I use my own dataset?**  \nA: Yes! Modify the training notebook to load your dataset and retrain the model.\n\n**Q: How do I improve accuracy?**  \nA: Try deeper networks, data augmentation, or hyperparameter tuning in the notebook.\n\n**Q: Can I deploy this app online?**  \nA: Yes! Gradio supports easy deployment to Hugging Face Spaces, or you can use services like Heroku, AWS, or Azure.\n\n**Q: How do I change the model architecture?**  \nA: Edit the model definition in `models/training.ipynb` and retrain.\n\n**Q: Why is my prediction always wrong?**  \nA: Make sure you draw clearly within the box, and the model is properly loaded.\n\n**Q: How do I run on a different port?**  \nA: Set the `GRADIO_PORT` environment variable.\n\n---\n\n## Contributing\n\nContributions are welcome! Please open issues or pull requests for suggestions, bug fixes, or improvements.\n\n### How to Contribute\n\n1. Fork the repository.\n2. Create a new branch (`git checkout -b feature/your-feature`).\n3. Make your changes.\n4. Commit and push (`git commit -am 'Add new feature' \u0026\u0026 git push origin feature/your-feature`).\n5. Open a pull request.\n\n---\n\n## License\n\nThis project is licensed under the MIT License. See [LICENSE](LICENSE) for details.\n\n---\n\n## References\n\n- [MNIST Dataset](http://yann.lecun.com/exdb/mnist/)\n- [TensorFlow Documentation](https://www.tensorflow.org/)\n- [Gradio Documentation](https://gradio.app/)\n- [Keras Documentation](https://keras.io/)\n- [Jupyter Notebook](https://jupyter.org/)\n\n---\n\n## Acknowledgements\n\n- Inspired by classic MNIST digit recognition projects.\n- Thanks to the open-source community for tools and datasets.\n\n---\n\n## Contact\n\nFor questions or support, please open an issue or contact ptnhanit230104@gmail.com.\n\n---\n\n## API Endpoints\n\nThe app can be extended to provide a REST API for predictions.\n\n| Endpoint   | Method | Description                | Input         | Output      |\n|------------|--------|----------------------------|---------------|-------------|\n| `/predict` | POST   | Predict digit from image   | 28x28 image   | JSON result |\n\n**Example Request:**\n```bash\ncurl -X POST -F \"image=@digit.png\" http://localhost:7860/predict\n```\n\n---\n\n## Advanced Customization\n\n- **Add New Preprocessing Steps:**  \n  Edit the image preprocessing logic in `app/main.py` to include noise reduction, thresholding, or resizing.\n\n- **Support for Color Images:**  \n  Change the input shape and preprocessing to handle RGB images.\n\n- **Batch Prediction:**  \n  Modify the Gradio interface to accept and predict multiple images at once.\n\n- **Logging and Monitoring:**  \n  Integrate tools like TensorBoard or Weights \u0026 Biases for experiment tracking.\n\n---\n\n## Security Considerations\n\n- Ensure the app is run behind a secure proxy (e.g., Nginx) in production.\n- Use HTTPS for all external deployments.\n- Validate and sanitize all user inputs.\n- Do not expose sensitive environment variables or model internals.\n\n---\n\n## Changelog\n\n- **v1.0.0**: Initial release with Gradio UI and MNIST model.\n- **v1.1.0**: Added configuration file and environment variable support.\n- **v1.2.0**: Improved documentation and added Docker support.\n\n---\n\n## Related Projects\n\n- [keras-io/examples/vision/mnist_convnet.py](https://github.com/keras-team/keras-io/blob/master/examples/vision/mnist_convnet.py)\n- [Gradio MNIST Example](https://gradio.app/get_started)\n\n---\n\n## Community \u0026 Support\n\n- [GitHub Discussions](https://github.com/NhanPhamThanh-IT/Handwritten-Digits-Classification/discussions)\n- [Stack Overflow](https://stackoverflow.com/questions/tagged/mnist)\n- Email: ptnhanit230104@gmail.com\n\n\u003c/div\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnhanphamthanh-it%2Fhandwritten-digits-classification","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnhanphamthanh-it%2Fhandwritten-digits-classification","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnhanphamthanh-it%2Fhandwritten-digits-classification/lists"}