Skip to content

Latest commit

 

History

History
358 lines (300 loc) · 13.5 KB

File metadata and controls

358 lines (300 loc) · 13.5 KB

Barcode Generation & Recognition Web Application - Architecture

Project Overview

A Python web application for generating and recognizing barcodes, with focus on food & beverage products in Europe.

Recommended APIs

1. Open Food Facts API (Primary - RECOMMENDED)

  • URL: https://world.openfoodfacts.org/api/v2/
  • Pros:
    • Completely FREE and open source
    • Excellent European coverage (especially Italy, France, Germany)
    • No API key required
    • Rich product data (nutritional info, ingredients, images)
    • Community-driven, regularly updated
  • Endpoint: GET /api/v2/product/{barcode}
  • Use for: Food & beverage product lookup

2. EAN-Search API (Secondary - Optional)

  • URL: https://www.ean-search.org/
  • Pros:
    • Good European product database
    • Free tier available
    • Simple to use
  • Use for: Non-food products or fallback

Barcode Types to Support

Primary: EAN-13 (European Article Number)

  • 13 digits
  • Standard for retail products in Europe
  • Example: 8000500310427 (Nutella)

Secondary Support:

  1. EAN-8: 8 digits (smaller products)
  2. UPC-A: 12 digits (US products, common in imports)
  3. Code128: Variable length (shipping, logistics)

Recommendation: Focus on EAN-13 and EAN-8 for food/beverage in Italy/Europe.

Technology Stack

Backend

  • Framework: Flask or FastAPI
    • Flask: Simple, well-documented, perfect for this scope
    • FastAPI: Modern, async, auto-documentation
  • Python Version: 3.9+

Barcode Libraries

  1. python-barcode: Barcode generation

    • pip install python-barcode
    • Supports EAN-13, EAN-8, UPC-A, Code128
  2. pyzbar: Barcode recognition/decoding

    • pip install pyzbar
    • Reads barcodes from images
    • Requires system library: libzbar0
  3. Pillow (PIL): Image processing

    • pip install Pillow

Frontend

  • HTML5 + CSS3 + JavaScript
  • Bootstrap 5: Responsive UI
  • Optional: Simple file upload with drag-&-drop

Deployment

  • Development: Flask built-in server
  • Production: Gunicorn + Nginx (or Railway/Render/PythonAnywhere)

Application Architecture

┌─────────────────────────────────────────────────────┐
│                   Web Browser                       │
│  ┌──────────────┐  ┌──────────────┐  ┌───────────┐  │
│  │ Upload Image │  │ Enter Barcode│  │ View Info │  │
│  └──────────────┘  └──────────────┘  └───────────┘  │
└────────────┬────────────────┬──────────────┬────────┘
             │                │              │
             ▼                ▼              ▼
┌─────────────────────────────────────────────────────┐
│              Flask Web Application                  │
│  ┌──────────────────────────────────────────────┐   │
│  │            Routes/Controllers                 │  │
│  │  • /                  (Home)                  │  │
│  │  • /upload            (Image upload)          │  │
│  │  • /decode            (Decode barcode)        │  │
│  │  • /generate          (Generate barcode)      │  │
│  │  • /product-info      (Product lookup)        │  │
│  └──────────────────────────────────────────────┘   │
│                                                     │
│  ┌──────────────────────────────────────────────┐   │
│  │            Business Logic Layer              │   │
│  │  ┌──────────────┐  ┌────────────────────┐   │   │
│  │  │ Barcode      │  │ Product Info       │   │   │
│  │  │ Decoder      │  │ Service            │   │   │
│  │  │ (pyzbar)     │  │ (API client)       │   │   │
│  │  └──────────────┘  └────────────────────┘   │   │
│  │  ┌──────────────┐  ┌────────────────────┐   │   │
│  │  │ Barcode      │  │ Image Processing   │   │   │
│  │  │ Generator    │  │ (Pillow)           │   │   │
│  │  │ (python-     │  │                    │   │   │
│  │  │  barcode)    │  │                    │   │   │
│  │  └──────────────┘  └────────────────────┘   │   │
│  └─────────────────────────────────────────────┘   │
│                                                    │
│  ┌──────────────────────────────────────────────┐  │
│  │            Static Files Handler               │ │
│  │  • /static/css/                               │ │
│  │  • /static/js/                                │ │
│  │  • /static/images/                            │ │
│  │  • /uploads/ (temporary uploaded images)      │ │
│  └──────────────────────────────────────────────┘  │
└────────────┬──────────────────────────────┬────────┘
             │                              │
             ▼                              ▼
┌──────────────────────┐      ┌──────────────────────┐
│ Open Food Facts API  │      │ File System          │
│ world.openfoodfacts  │      │ (temp uploads,       │
│      .org            │      │  generated barcodes) │
└──────────────────────┘      └──────────────────────┘

Project Structure

BarCode/
├── app.py                      # Main Flask application
├── requirements.txt            # Python dependencies
├── config.py                   # Configuration settings
├── .env                        # Environment variables (API keys, etc.)
├── README.md                   # Project documentation
├── ARCHITECTURE.md             # This file
│
├── services/                   # Business logic layer
│   ├── __init__.py
│   ├── barcode_decoder.py      # Decode barcodes from images
│   ├── barcode_generator.py    # Generate barcode images
│   └── product_api.py          # Open Food Facts API client
│
├── routes/                     # Route handlers
│   ├── __init__.py
│   ├── main.py                 # Main routes (home, about)
│   ├── barcode_routes.py       # Barcode operations
│   └── api_routes.py           # JSON API endpoints
│
├── static/                     # Static assets
│   ├── css/
│   │   └── style.css
│   ├── js/
│   │   └── app.js
│   └── images/
│       └── logo.png
│
├── templates/                  # HTML templates (Jinja2)
│   ├── base.html               # Base template
│   ├── index.html              # Home page
│   ├── upload.html             # Upload barcode image
│   ├── generate.html           # Generate barcode
│   ├── result.html             # Display decoded results
│   └── product_info.html       # Product information display
│
├── uploads/                    # Temporary uploaded images
│   └── .gitkeep
│
└── tests/                      # Unit tests
    ├── __init__.py
    ├── test_decoder.py
    └── test_generator.py

Core Features

1. Barcode Recognition

User Flow:

  1. Upload image (JPG/PNG) containing barcode
  2. System decodes barcode using pyzbar
  3. Display barcode number and type
  4. Optional: Fetch product info from Open Food Facts

Technical:

from pyzbar.pyzbar import decode
from PIL import Image

def decode_barcode(image_path):
    img = Image.open(image_path)
    decoded_objects = decode(img)
    return decoded_objects

2. Barcode Generation

User Flow:

  1. Enter barcode number (13 digits for EAN-13)
  2. Select barcode type
  3. Generate and download barcode image (PNG/SVG)

Technical:

import barcode
from barcode.writer import ImageWriter

def generate_barcode(number, barcode_type='ean13'):
    EAN = barcode.get_barcode_class(barcode_type)
    ean = EAN(number, writer=ImageWriter())
    filename = ean.save('barcode_output')
    return filename

3. Product Information Lookup

User Flow:

  1. After decoding barcode, click "Get Product Info"
  2. System queries Open Food Facts API
  3. Display product details (name, brand, ingredients, nutrition)

Technical:

import requests

def get_product_info(barcode):
    url = f"https://world.openfoodfacts.org/api/v2/product/{barcode}"
    response = requests.get(url)
    if response.status_code == 200:
        return response.json()
    return None

Data Flow

Upload & Decode Flow

User uploads image → Save to /uploads/ → pyzbar decode → 
Extract barcode number → Query Open Food Facts API → 
Display results (barcode + product info) → Delete temp image

Generate Flow

User enters barcode number → Validate format → 
python-barcode generate image → Save to /static/generated/ → 
Display image with download option

Security Considerations

  1. File Upload Validation

    • Whitelist: Only JPG, PNG, WEBP
    • Max size: 5MB
    • Sanitize filenames
  2. Temporary File Cleanup

    • Delete uploaded images after processing
    • Periodic cleanup job for generated barcodes
  3. Input Validation

    • Validate barcode format (numeric, correct length)
    • Prevent path traversal
  4. Rate Limiting

    • Limit API calls to Open Food Facts
    • Implement request throttling

Deployment Considerations

Development

python app.py
# Runs on http://localhost:5000

Production

  • Use Gunicorn as WSGI server
  • Nginx as reverse proxy
  • SSL/TLS certificate (Let's Encrypt)
  • Environment variables for configuration

Platform Options

  1. PythonAnywhere: Free tier, easy Python hosting
  2. Railway: Modern, CI/CD integration
  3. Render: Free tier, auto-deploy from Git
  4. DigitalOcean App Platform: Scalable

Testing Strategy

  1. Unit Tests: Test barcode generation/decoding functions
  2. Integration Tests: Test API endpoints
  3. Manual Testing: Test with real barcode images
  4. Test Data: Use known EAN-13 codes:
    • 8000500310427 (Nutella)
    • 3017620422003 (Nutella French)
    • 8076809513692 (Barilla Pasta)

Future Enhancements

  1. Batch Processing: Upload multiple images
  2. History: Save decoded barcodes (requires database)
  3. QR Codes: Add QR code support
  4. Mobile: PWA for camera access
  5. OCR: Extract text from product labels
  6. Multi-language: i18n support (Italian, English)
  7. Analytics: Track most scanned products

Performance Optimization

  1. Caching: Cache API responses (Redis/in-memory)
  2. Image Optimization: Resize large uploads before processing
  3. Async Processing: Use Celery for heavy operations
  4. CDN: Serve static assets via CDN

Example Barcodes for Testing (Italian Products)

  • 8000500310427: Ferrero Nutella
  • 8076809513692: Barilla Spaghetti
  • 8001480003699: San Pellegrino
  • 8000070126107: Lavazza Caffè
  • 8000825303019: Mulino Bianco Biscotti

Getting Started

  1. Install system dependencies:

    sudo apt-get install libzbar0  # For pyzbar
  2. Create virtual environment:

    python -m venv venv
    source venv/bin/activate
  3. Install Python packages:

    pip install flask python-barcode pyzbar pillow requests
  4. Run application:

    python app.py

Conclusion

This architecture provides a solid foundation for a barcode web application with:

  • Simple: Easy to understand and maintain
  • Scalable: Can grow with additional features
  • European-focused: Uses Open Food Facts (excellent for Italy)
  • Free: No API costs for basic usage
  • Educational: Great learning project for Python web development

Fedora

sudo dnf install zbar Descrizione : ZBar Bar Code Reader is an open source software suite for reading bar : codes from various sources, such as video streams, image files and raw : intensity sensors. It supports EAN-13/UPC-A, UPC-E, EAN-8, Code 128, : Code 93, Code 39, Codabar, Interleaved 2 of 5, QR Code and SQ Code. Produttore : Fedora Project