NAFNet-Image-Restoration-API

Development Guide

Project Setup

Prerequisites

Initial Setup

# Clone repository
git clone https://github.com/Gtajisan/NAFNet-Image-Restoration-API.git
cd NAFNet-Image-Restoration-API

# Create virtual environment
python -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate

# Install development dependencies
pip install -r requirements.txt
pip install -e ".[dev]"

Code Style

PEP 8 Compliance

This project follows PEP 8 standards.

# Check code style
flake8 app.py

# Auto-format code
black app.py

# Sort imports
isort app.py

Naming Conventions

Docstring Format

def enhance_image(input_file):
    """
    Restore and enhance image using image processing techniques.
    
    Args:
        input_file: Image file object or path
        
    Returns:
        PIL.Image: Enhanced image
        
    Raises:
        ValueError: If image format is not supported
        IOError: If file cannot be read
    """
    pass

Testing

Running Tests

# Run all tests
pytest

# Run with coverage
pytest --cov=nafnet

# Run specific test file
pytest tests/test_api.py

# Run with verbose output
pytest -v

Writing Tests

# tests/test_api.py
import pytest
from app import app

@pytest.fixture
def client():
    app.config['TESTING'] = True
    return app.test_client()

def test_api_info(client):
    response = client.get('/api/info')
    assert response.status_code == 200
    assert 'name' in response.json

def test_image_upload(client):
    with open('test_image.jpg', 'rb') as f:
        response = client.post('/api/fix', data={'file': f})
        assert response.status_code == 200

Local Development

Run Development Server

# With Flask debug mode
FLASK_ENV=development python app.py

# Access at http://localhost:5000

Test with cURL

# Get API info
curl http://localhost:5000/api/info

# Upload image
curl -X POST -F "file=@test_image.jpg" \
  http://localhost:5000/api/fix \
  -o restored.png

Test with Python

import requests
from PIL import Image

# Create test image
img = Image.new('RGB', (100, 100), color='red')
img.save('test.jpg')

# Upload
with open('test.jpg', 'rb') as f:
    r = requests.post('http://localhost:5000/api/fix', files={'file': f})

# Save result
with open('restored.png', 'wb') as out:
    out.write(r.content)

Docker Development

Build Image

docker build -t nafnet-api:dev .

Run Container

docker run -p 5000:5000 -v $(pwd):/app nafnet-api:dev python app.py

Build for Production

docker build -t nafnet-api:latest .
docker tag nafnet-api:latest nafnet-api:v1.0.0

CI/CD Pipeline

GitHub Actions

Workflows are configured in .github/workflows/:

Pre-commit Hooks

# Install pre-commit
pip install pre-commit

# Setup hooks
pre-commit install

# Run hooks
pre-commit run --all-files

Performance Optimization

Profiling

import cProfile
import pstats
from io import StringIO

pr = cProfile.Profile()
pr.enable()

# Code to profile
enhance_image(file)

pr.disable()
s = StringIO()
ps = pstats.Stats(pr, stream=s).sort_stats('cumulative')
ps.print_stats()
print(s.getvalue())

Benchmarking

import timeit

# Benchmark image processing
time = timeit.timeit(
    'enhance_image(file)',
    setup='from app import enhance_image; file = open("test.jpg", "rb")',
    number=10
)
print(f"Average time: {time/10:.2f}s")

Debugging

Enable Debug Mode

# In app.py
if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=5000)

Logging

import logging

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

logger.debug("Processing image...")
logger.info("Image processed successfully")
logger.error("Error processing image: %s", str(e))

Release Process

Version Bumping

# Update version in:
# - pyproject.toml
# - README.md (optional)

# Commit changes
git add .
git commit -m "Bump version to 1.1.0"

# Create tag
git tag -a v1.1.0 -m "Release version 1.1.0"

# Push
git push origin main --tags

Building Distribution

# Install build tools
pip install build

# Build package
python -m build

# Upload to PyPI
twine upload dist/*

Troubleshooting

Common Issues

ImportError: No module named ‘flask’

pip install -r requirements.txt

Port already in use

lsof -i :5000
kill -9 <PID>

Image processing error

Resources

Support

For development questions or issues: