Add your description here
Project description
Tools API - Document Processing & AI Services
A comprehensive FastAPI application providing document conversion, translation, email AI classification, paper tracking, and web search capabilities. Built with modern Python tooling and deployed on Google Cloud Platform.
๐ Features
Document Processing
- Document Conversion: Convert PDFs, DOCs, EPUBs to HTML, JSON, and Markdown formats
- Document Translation: Translate documents between multiple languages with AI
- Horizontal Bilingual Format: Side-by-side comparison view (default since v0.1.4)
- Vertical Bilingual Format: Traditional stacked translation format
- Non-ASCII Filename Support: Proper RFC 5987 encoding for international characters
- OCR Support: Extract text from images within documents
- Chunking: Process large documents by splitting into manageable parts
- Async Processing: Handle large files with background job processing
AI Services
- Email Classification: AI-powered email categorization and analysis
- Paper Tracking: Automated academic paper discovery and summarization
- Web Search: Multi-engine web search capabilities
- Prompt Improvement: AI-assisted translation prompt optimization
Web Interface
- Flutter Web UI: Modern web interface for document processing
- Background Pattern: Enhanced visual design
- Terraform Deployment: Infrastructure as Code for UI deployment
Infrastructure
- Cloud Storage Integration: Google Cloud Storage for file management
- Background Jobs: Cloud Run Jobs for long-running tasks
- Database Tracking: MySQL with Alembic migrations for job and paper tracking
- Email Notifications: Gmail API integration for job completion alerts
- Terraform Configuration: Infrastructure as Code for all services
๐ Project Structure
app/
โโโ __init__.py
โโโ main.py # FastAPI application entry point
โโโ api/ # API layer
โ โโโ __init__.py
โ โโโ v1/ # API version 1
โ โโโ __init__.py
โ โโโ doc_convert.py # Document conversion endpoints
โ โโโ doc_translation.py # Document translation endpoints
โ โโโ emai_ai.py # Email AI classification endpoints
โ โโโ health.py # Health check endpoints
โ โโโ paper_tracking.py # Paper tracking endpoints
โ โโโ general_tool/ # General tools (web search)
โ โโโ web_search.py
โโโ core/ # Core application logic
โ โโโ __init__.py
โ โโโ config/ # Configuration
โ โ โโโ __init__.py
โ โ โโโ settings.py # Application settings
โ โโโ database.py # Database connection
โ โโโ logging.py # Logging configuration
โ โโโ security/ # Security utilities
โ โโโ __init__.py
โ โโโ auth.py # API key authentication
โโโ jobs/ # Background job definitions
โ โโโ __init__.py
โ โโโ doc_convert_job.py
โ โโโ doc_translation_job.py
โ โโโ summary_papers_job.py
โโโ models/ # Data models
โ โโโ __init__.py
โ โโโ entities/ # Database entities
โ โ โโโ __init__.py
โ โ โโโ job_execution.py # Job tracking model
โ โ โโโ paper_tracking.py # Paper tracking model
โ โโโ enums/ # Enumeration definitions
โ โ โโโ __init__.py
โ โ โโโ email_ai.py
โ โ โโโ general_tool/
โ โโโ parses/ # Response parsers
โ โ โโโ __init__.py
โ โ โโโ doc_convert.py
โ โ โโโ doc_translation.py
โ โ โโโ email_ai.py
โ โ โโโ paper_tracking.py
โ โโโ schemas/ # Pydantic schemas
โ โโโ __init__.py
โ โโโ doc_convert.py
โ โโโ doc_translation.py
โ โโโ email_ai.py
โ โโโ general_tool/
โ โโโ health.py
โ โโโ paper_tracking.py
โโโ prompts/ # AI prompt templates
โ โโโ __init__.py
โ โโโ doc_convert.py
โ โโโ doc_translation.py
โ โโโ email_ai.py
โ โโโ paper_tracking.py
โโโ repositories/ # Data access layer
โ โโโ __init__.py
โ โโโ paper_tracking_repository.py
โโโ services/ # Business logic layer
โ โโโ __init__.py
โ โโโ doc_convert/ # Document conversion service
โ โ โโโ __init__.py
โ โ โโโ core_convert_mixin.py
โ โ โโโ doc_convert_service.py
โ โ โโโ post_processing_mixin.py
โ โโโ doc_translation/ # Document translation service
โ โ โโโ __init__.py
โ โ โโโ core_translation_mixin.py
โ โ โโโ doc_translation_service.py
โ โ โโโ improve_prompt_mixin.py
โ โโโ email_ai/ # Email AI service
โ โ โโโ __init__.py
โ โ โโโ email_ai_service.py
โ โโโ general_tool/ # General tools
โ โ โโโ __init__.py
โ โ โโโ web_search/
โ โโโ health/ # Health service
โ โ โโโ __init__.py
โ โ โโโ health_service.py
โ โโโ paper_tracking/ # Paper tracking service
โ โ โโโ __init__.py
โ โ โโโ email_template.py
โ โ โโโ paper_tracking_service.py
โ โ โโโ summary_papers_mixin.py
โ โโโ tracking/ # Job tracking service
โโโ tests/ # Test suite
โ โโโ __init__.py
โ โโโ unit/ # Unit tests
โ โ โโโ utils/
โ โ โโโ test_file_helper.py
โ โโโ integration/ # Integration tests
โ โโโ api/ # API tests
โ โโโ fixtures/ # Test fixtures
โ โโโ e2e/ # End-to-end tests
โโโ utils/ # Utility functions
โโโ __init__.py
โโโ concurrency.py
โโโ email.py
โโโ file_helper.py
โโโ gcs_helper.py
โโโ languages.py
โโโ pdf_helper.py
โโโ time_helper.py
ui/ # Flutter Web UI (separate deployment)
โโโ lib/ # Flutter source code
โโโ web/ # Web-specific files
โโโ pubspec.yaml # Flutter dependencies
โโโ terraform/ # UI Terraform configuration
โโโ main.tf
โโโ variables.tf
โโโ outputs.tf
terraform/ # Backend Terraform configuration
โโโ main.tf # Main infrastructure
โโโ variables.tf # Configuration variables
โโโ outputs.tf # Output values
โโโ cloud_run.tf # Cloud Run services and jobs
โโโ iam.tf # IAM roles and permissions
โโโ secrets.tf # Secret Manager configuration
โโโ build.tf # Cloud Build configuration
๐ Technology Stack
- Framework: FastAPI with Hypercorn ASGI server
- Language: Python 3.12+
- Package Manager: uv (Astral)
- Database: MySQL with SQLAlchemy ORM
- Migrations: Alembic
- AI/ML: Google Gemini AI, LangChain, LangGraph
- Document Processing: Docling, PyPDF, Pandoc, Playwright
- Cloud: Google Cloud Platform (Cloud Run, Cloud Storage, Secret Manager)
- Containerization: Docker with multi-stage builds
- Infrastructure: Terraform for Infrastructure as Code
- Deployment: Cloud Build, GKE, Cloud Run Jobs
- Web UI: Flutter Web with Nginx
๐ Quick Start
Prerequisites
- Python 3.12+
- uv package manager
- MySQL database
- Google Cloud Platform account
- Docker (for containerized deployment)
- Terraform (for infrastructure management)
Local Development
- Clone and setup:
git clone <repository-url>
cd tools
uv sync
- Environment Configuration:
Create a
.envfile with required variables:
# API Configuration
API_TITLE="Tools API"
API_DESCRIPTION="API for document conversion and processing tools"
API_VERSION="v51"
HOST="0.0.0.0"
PORT=8080
DEBUG=false
CORS_ORIGINS=["*"]
# Authentication
API_KEYS=["your-api-key-here"]
# Database Configuration
DB_HOST=localhost
DB_PORT=3306
DB_USER=root
DB_PASSWORD=your_password
DB_NAME=tools_db
# Google Cloud Configuration
GOOGLE_API_KEY=your_google_api_key
UPLOAD_BUCKET=your_gcs_bucket
GOOGLE_APPLICATION_CREDENTIALS=path/to/service-account.json
# Gmail API Configuration
GOOGLE_CREDENTIALS=path/to/google-credentials.json
GOOGLE_TOKEN=path/to/token.json
# Search APIs
GOOGLE_CUSTOM_SEARCH_KEY=your_search_key
GOOGLE_CUSTOM_SEARCH_CSE_ID=your_cse_id
BRAVE_API_KEY=your_brave_key
TAVILY_API_KEY=your_tavily_key
- Database Setup:
# Start MySQL service
brew services start mysql # macOS
# or
sudo systemctl start mysql # Linux
# Create database
mysql -u root -p
CREATE DATABASE tools_db;
- Run Database Migrations:
alembic upgrade head
- Start the Server:
python -m app.main
- Access the API:
- API Documentation: http://localhost:8080/docs
- Health Check: http://localhost:8080/health/
- Simple Health: http://localhost:8080/health/simple
๐ API Endpoints
Health Check
GET /health/- Comprehensive health check with system metricsGET /health/simple- Simple health checkGET /- Root endpoint with API information
Document Conversion (/doc-convert)
POST /- Convert uploaded document to HTML, JSON, and MarkdownPOST /download-zip- Convert document and return as ZIP archivePOST /convert-epub- Convert EPUB files to HTML or PDFPOST /post-processing-html- Post-process HTML with formatting optionsPOST /generate-upload-url- Generate GCS signed URL for direct uploadGET /convert-from-storage- Convert document from GCS storageGET /convert-from-storage/download-zip- Convert from GCS and return ZIPPOST /trigger-large-file-conversion- Trigger async conversion for large files
Document Translation (/doc-translation)
POST /- Translate uploaded document with bilingual format optionsbilingual_format: Choose betweenhorizontal(default) orverticallayout
POST /translate-converted-zip- Translate documents from conversion ZIPPOST /translate-pdf- Translate PDF by converting then translatingPOST /translate-epub- Translate EPUB filesPOST /trigger-large-file-translation- Trigger async translation for large filesPOST /improve-prompt- Get improved translation prompt suggestions
Email AI (/email-ai)
POST /classify-email- Classify single email using AIPOST /classify-email/batch- Classify multiple emails in batchGET /classify-email/categories- Get available classification categories
Paper Tracking (/paper-tracking)
POST /fetch-papers- Fetch academic papers by date and typeGET /summary-papers- Summarize papers with AIPOST /trigger-summary-job- Trigger background job for paper summarization
Web Search (/search-web)
GET /- Search the web using multiple search engines
๐ Database Schema
Job Executions Table
Tracks background job executions with token usage and timing information:
- Job types:
DOC_TRANSLATION,DOC_CONVERT,DOC_TRANSLATION_V2,IMPROVED_TRANSLATION_PROMPT,EMAIL_CLASSIFICATION - Status tracking:
PENDING,RUNNING,COMPLETED,FAILED - Token usage monitoring for AI services
- Email notifications and error handling
Paper Tracking Tables
paper_tracking: Stores academic paper metadatapaper_tracking_types: Links papers to tracking types (daily, weekly, monthly)
๐ง Database Migrations
Create Migration
# Auto-generate from model changes
alembic revision --autogenerate -m "Description of changes" --rev-id="N"
# Create empty migration
alembic revision -m "Description of changes" --rev-id="N"
Apply Migrations
# Apply all pending migrations
alembic upgrade head
# Apply specific migration
alembic upgrade N
# Rollback to previous migration
alembic downgrade -1
# Rollback to specific migration
alembic downgrade N
Migration Management
# Check current migration status
alembic current
# Check migration history
alembic history
# Show SQL for migration (without applying)
alembic upgrade head --sql
๐ Deployment
Terraform (Recommended)
The project uses Terraform for Infrastructure as Code to manage all cloud resources.
Backend Services
- Initialize Terraform:
cd terraform
terraform init
- Configure Variables:
Create
terraform.tfvars:
project_id = "your-gcp-project-id"
region = "us-east1"
api_keys = ["your-api-key"]
- Deploy Infrastructure:
# Plan deployment
terraform plan
# Apply changes
terraform apply
# Deploy with auto-approve
terraform apply -auto-approve
- Access Services:
- Backend API: Output from
terraform output tools_api_url - Cloud Run Jobs: Configured for document conversion and translation
Web UI
- Build and Deploy UI:
cd ui/terraform
terraform init
terraform apply
- Access UI:
- Web Interface: Output from
terraform output ui_url
Google Cloud Run (Legacy)
- Build and Deploy:
# Deploy API service
./deploy.sh
# Deploy all services (API + Cloud Run Jobs)
./deploy-all.sh
# Deploy with tests
./deploy-all.sh --test
- Configuration:
- Update
version.envfor version management - Configure
env.shfor environment variables and secrets - Set up Google Cloud Secret Manager for sensitive data
Google Kubernetes Engine (GKE)
- Prerequisites:
gcloud auth login
gcloud config set project your-project-id
gcloud services enable artifactregistry.googleapis.com container.googleapis.com cloudbuild.googleapis.com
- Deploy:
# Build and deploy to GKE
gcloud builds submit --region=us-east1 --config=cloudbuild.yaml --substitutions=_TAG=v1
- Access:
gcloud container clusters get-credentials tools-cluster --region=us-east1
kubectl get svc tools-api -w
Docker
# Build image
docker build -t tools-api .
# Run container
docker run -p 8080:8080 --env-file .env tools-api
๐ Security
- API Key Authentication: All endpoints require valid API keys
- CORS Configuration: Configurable cross-origin resource sharing
- Secret Management: Google Cloud Secret Manager integration
- Input Validation: Pydantic schemas for request/response validation
- Error Handling: Comprehensive error handling and logging
- RFC 5987 Encoding: Proper handling of international characters in filenames
๐ Monitoring & Logging
- Health Checks: Comprehensive system health monitoring
- Structured Logging: Loguru-based logging with JSON output
- Job Tracking: Database-backed job execution monitoring
- Performance Metrics: CPU, memory, and disk usage tracking
- Error Tracking: Detailed error logging with stack traces
๐งช Testing
# Run unit tests
pytest tests/unit
# Run all tests
pytest
# Manual API testing
curl -X GET "http://localhost:8080/health/" \
-H "X-API-Key: your-api-key"
๐ Documentation
- API Documentation: Auto-generated OpenAPI docs at
/docs - Deployment Guides:
- Code Documentation: Comprehensive docstrings and type hints
๐ What's New
Version 0.1.4 (November 2025)
- โจ Horizontal Bilingual Translation: New side-by-side comparison format (now default)
- ๐ Non-ASCII Filename Support: RFC 5987 encoding for international characters
- ๐จ Flutter Web UI: Modern web interface with Terraform deployment
- ๐ Enhanced Changelog: Improved release notes generation
- ๐ Bug Fixes: Fixed backtick preservation in release notes
Version 0.1.3 (October 2025)
- ๐ง RFC 5987 Encoding: Utility for Content-Disposition headers
- ๐งช Test Organization: Restructured test suite (unit/integration/api/e2e)
- ๐ EPUB Support: Convert and translate EPUB files
- โก Performance: Improved translation speed and reliability
๐ค Contributing
- Follow the established layer architecture pattern
- Add new features by extending the appropriate service layer
- Update API documentation and schemas
- Add database migrations for schema changes
- Write tests for new functionality
- Update CHANGELOG.md for significant changes
- Test thoroughly before deployment
๐ License
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.
Apache License 2.0 is a permissive open-source license that allows you to:
- โ Use the software for any purpose
- โ Modify and distribute the software
- โ Include in proprietary software
- โ Patent use and distribution
- โ Commercial use
Requirements:
- ๐ Include the original license and copyright notice
- ๐ State any changes made to the original software
- ๐ Include the NOTICE file if present
Version: v54.1
Last Updated: 2025-11-08
Maintainer: Cao Minh Tien (iamcaominhtien@gmail.com)