CoolFace
Apppublic

Text-to-Document-Generation/PDF-Redaction-API

sourceHugging Facemitupdated 5mo agoView on Hugging Face
0likes
COMPLETE_GUIDE.md489 linesDownload Raw Back to root
1# ๐Ÿš€ Complete FastAPI Deployment Package2 3## ๐Ÿ“ฆ What You've Got4 5A production-ready FastAPI application for PDF redaction with Named Entity Recognition, ready to deploy on HuggingFace Spaces or any cloud platform.6 7---8 9## ๐Ÿ“ Directory Structure10 11```12pdf-redaction-api/13โ”‚14โ”œโ”€โ”€ ๐Ÿ“„ main.py                     # FastAPI application15โ”œโ”€โ”€ ๐Ÿณ Dockerfile                  # Production container16โ”œโ”€โ”€ ๐Ÿณ docker-compose.yml          # Local development17โ”œโ”€โ”€ ๐Ÿ“‹ requirements.txt            # Python dependencies18โ”‚19โ”œโ”€โ”€ ๐Ÿ“ฑ app/20โ”‚   โ”œโ”€โ”€ __init__.py21โ”‚   โ””โ”€โ”€ redaction.py              # Core redaction engine22โ”‚23โ”œโ”€โ”€ ๐Ÿ“‚ uploads/                    # Temporary uploads24โ”‚   โ””โ”€โ”€ .gitkeep25โ”‚26โ”œโ”€โ”€ ๐Ÿ“‚ outputs/                    # Redacted PDFs27โ”‚   โ””โ”€โ”€ .gitkeep28โ”‚29โ”œโ”€โ”€ ๐Ÿงช tests/30โ”‚   โ””โ”€โ”€ test_api.py               # API tests31โ”‚32โ”œโ”€โ”€ ๐Ÿ“š Documentation/33โ”‚   โ”œโ”€โ”€ README.md                 # Main docs (for HF Spaces)34โ”‚   โ”œโ”€โ”€ DEPLOYMENT.md             # Deployment guide35โ”‚   โ”œโ”€โ”€ QUICKSTART.md             # Quick start guide36โ”‚   โ””โ”€โ”€ STRUCTURE.md              # Project structure37โ”‚38โ”œโ”€โ”€ ๐Ÿ”ง Configuration/39โ”‚   โ”œโ”€โ”€ .env.example              # Environment variables40โ”‚   โ”œโ”€โ”€ .gitignore                # Git ignore41โ”‚   โ””โ”€โ”€ .dockerignore             # Docker ignore42โ”‚43โ”œโ”€โ”€ ๐Ÿค– .github/44โ”‚   โ””โ”€โ”€ workflows/45โ”‚       โ””โ”€โ”€ ci-cd.yml             # GitHub Actions CI/CD46โ”‚47โ”œโ”€โ”€ ๐Ÿ“ client_example.py           # Example API client48โ””โ”€โ”€ ๐Ÿ“œ LICENSE                     # MIT License49```50 51---52 53## โœจ Features54 55### Core Functionality56โœ… PDF upload and processing57โœ… OCR with pytesseract (configurable DPI)58โœ… Named Entity Recognition (NER)59โœ… Accurate coordinate-based redaction60โœ… Multiple entity type support61โœ… Downloadable redacted PDFs62 63### API Features64โœ… RESTful API with FastAPI65โœ… Automatic OpenAPI documentation66โœ… File upload handling67โœ… Background task cleanup68โœ… Health checks69โœ… Statistics endpoint70โœ… CORS support71 72### DevOps73โœ… Docker containerization74โœ… Docker Compose for local dev75โœ… GitHub Actions CI/CD76โœ… HuggingFace Spaces ready77โœ… Comprehensive testing78โœ… Logging and monitoring79 80---81 82## ๐ŸŽฏ Quick Deployment Paths83 84### Option 1: HuggingFace Spaces (Recommended for Demo)85 86**Time: 10 minutes**87 88```bash89# 1. Create Space on HuggingFace (select Docker SDK)90# 2. Clone your space91git clone https://huggingface.co/spaces/YOUR_USERNAME/pdf-redaction-api92cd pdf-redaction-api93 94# 3. Copy all files95cp -r /path/to/pdf-redaction-api/* .96 97# 4. Deploy98git add .99git commit -m "Initial deployment"100git push101```102 103**Your API will be at:** `https://YOUR_USERNAME-pdf-redaction-api.hf.space`104 105**Cost:** FREE (with CPU Basic tier)106 107---108 109### Option 2: Docker Locally110 111**Time: 5 minutes**112 113```bash114# Build115docker build -t pdf-redaction-api .116 117# Run118docker run -p 7860:7860 pdf-redaction-api119 120# Test121curl http://localhost:7860/health122```123 124---125 126### Option 3: Direct Python127 128**Time: 3 minutes**129 130```bash131# Install dependencies132sudo apt-get install tesseract-ocr poppler-utils133pip install -r requirements.txt134 135# Run136python main.py137 138# Access at http://localhost:7860139```140 141---142 143## ๐Ÿ”Œ API Endpoints144 145### Core Endpoints146 147| Method | Endpoint | Description |148|--------|----------|-------------|149| POST | `/redact` | Upload and redact PDF |150| GET | `/download/{job_id}` | Download redacted PDF |151| GET | `/health` | Health check |152| GET | `/stats` | API statistics |153| DELETE | `/cleanup/{job_id}` | Manual cleanup |154| GET | `/docs` | Interactive API docs |155 156### Example Usage157 158**cURL:**159```bash160curl -X POST "http://localhost:7860/redact" \161  -F "file=@document.pdf" \162  -F "dpi=300"163```164 165**Python:**166```python167import requests168 169response = requests.post(170    "http://localhost:7860/redact",171    files={"file": open("document.pdf", "rb")},172    params={"dpi": 300}173)174 175job_id = response.json()["job_id"]176redacted = requests.get(f"http://localhost:7860/download/{job_id}")177```178 179---180 181## ๐ŸŽจ Architecture182 183```184โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”185โ”‚                    CLIENT REQUEST                       โ”‚186โ”‚              (Upload PDF via POST /redact)              โ”‚187โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜188                          โ†“189โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”190โ”‚                   FASTAPI (main.py)                     โ”‚191โ”‚  โ€ข Validate file                                        โ”‚192โ”‚  โ€ข Generate job_id                                      โ”‚193โ”‚  โ€ข Save to uploads/                                     โ”‚194โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜195                          โ†“196โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”197โ”‚              PDFRedactor (app/redaction.py)             โ”‚198โ”‚                                                         โ”‚199โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”           โ”‚200โ”‚  โ”‚ 1. OCR (pytesseract)                    โ”‚           โ”‚201โ”‚  โ”‚    โ€ข Convert PDF โ†’ Images (pdf2image)   โ”‚           โ”‚202โ”‚  โ”‚    โ€ข Extract text + bounding boxes      โ”‚           โ”‚203โ”‚  โ”‚    โ€ข Store image dimensions             โ”‚           โ”‚204โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜           โ”‚205โ”‚                     โ†“                                   โ”‚206โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”           โ”‚207โ”‚  โ”‚ 2. NER (HuggingFace Transformers)       โ”‚           โ”‚208โ”‚  โ”‚    โ€ข Load model                         โ”‚           โ”‚209โ”‚  โ”‚    โ€ข Identify entities in text          โ”‚           โ”‚210โ”‚  โ”‚    โ€ข Return entity types + positions    โ”‚           โ”‚211โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜           โ”‚212โ”‚                     โ†“                                   โ”‚213โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”           โ”‚214โ”‚  โ”‚ 3. Mapping                              โ”‚           โ”‚215โ”‚  โ”‚    โ€ข Create character span index        โ”‚           โ”‚216โ”‚  โ”‚    โ€ข Match NER entities to OCR boxes    โ”‚           โ”‚217โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜           โ”‚218โ”‚                     โ†“                                   โ”‚219โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”           โ”‚220โ”‚  โ”‚ 4. Redaction (pypdf)                    โ”‚           โ”‚221โ”‚  โ”‚    โ€ข Scale image coords โ†’ PDF coords    โ”‚           โ”‚222โ”‚  โ”‚    โ€ข Create black rectangle annotations โ”‚           โ”‚223โ”‚  โ”‚    โ€ข Write redacted PDF                 โ”‚           โ”‚224โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜           โ”‚225โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜226                          โ†“227โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”228โ”‚                   RESPONSE                              โ”‚229โ”‚  โ€ข job_id                                               โ”‚230โ”‚  โ€ข List of entities                                     โ”‚231โ”‚  โ€ข Download URL                                         โ”‚232โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜233```234 235---236 237## ๐Ÿ” Security Considerations238 239### Current Implementation240- โœ… File validation (PDF only)241- โœ… Temporary file cleanup242- โœ… CORS middleware243- โœ… Error handling244 245### For Production (TODO)246- โš ๏ธ Add API key authentication247- โš ๏ธ Implement rate limiting248- โš ๏ธ Add file size limits249- โš ๏ธ Use HTTPS only250- โš ๏ธ Implement user quotas251- โš ๏ธ Add input sanitization252 253**Example API Key Auth:**254```python255# Add to main.py256from fastapi import Security, HTTPException257from fastapi.security import APIKeyHeader258 259API_KEY = "your-secret-key"260api_key_header = APIKeyHeader(name="X-API-Key")261 262def verify_api_key(key: str = Security(api_key_header)):263    if key != API_KEY:264        raise HTTPException(401, "Invalid API Key")265```266 267---268 269## ๐Ÿ“Š Performance Tuning270 271### DPI Settings272 273| DPI | Quality | Speed | Use Case |274|-----|---------|-------|----------|275| 150 | Low | Fast | Quick previews |276| 200 | Medium | Medium | General use |277| 300 | High | Slow | **Recommended** |278| 600 | Very High | Very Slow | Critical documents |279 280### Hardware Requirements281 282**Minimum (Free Tier):**283- CPU: 2 cores284- RAM: 2GB285- Storage: 1GB286 287**Recommended (Production):**288- CPU: 4+ cores289- RAM: 8GB290- Storage: 10GB291- GPU: Optional (speeds up NER)292 293---294 295## ๐Ÿงช Testing296 297```bash298# Install test dependencies299pip install pytest pytest-cov httpx300 301# Run tests302pytest tests/ -v303 304# With coverage305pytest tests/ --cov=app --cov-report=html306 307# View coverage report308open htmlcov/index.html309```310 311---312 313## ๐Ÿ“ˆ Monitoring314 315### Built-in Endpoints316 317**Health Check:**318```bash319curl http://localhost:7860/health320```321 322**Statistics:**323```bash324curl http://localhost:7860/stats325```326 327### Logs328 329**Development:**330```bash331python main.py332# Logs appear in console333```334 335**Docker:**336```bash337docker logs -f container_name338```339 340**HuggingFace Spaces:**341- View in Space dashboard โ†’ Logs tab342 343---344 345## ๐Ÿ’ฐ Cost Estimation346 347### HuggingFace Spaces348 349| Tier | CPU | RAM | Price | Use Case |350|------|-----|-----|-------|----------|351| Basic | 2 | 16GB | **FREE** | Demo, testing |352| CPU Upgrade | 4 | 32GB | $0.50/hr | Production |353| GPU T4 | - | - | $0.60/hr | Heavy load |354| GPU A10G | - | - | $1.50/hr | Enterprise |355 356**Monthly Costs (if always on):**357- Free: $0358- CPU Upgrade: ~$360/month359- GPU T4: ~$432/month360 361**Recommendation:** Start free, upgrade based on usage362 363### Alternatives364 365**AWS ECS Fargate:** ~$30-100/month  366**Google Cloud Run:** Pay per request (~$10-50/month)  367**DigitalOcean App:** $12-24/month  368**Self-hosted VPS:** $5-20/month369 370---371 372## ๐Ÿ”„ CI/CD Pipeline373 374### Automated with GitHub Actions375 376```377Push to GitHub378      โ†“379   [Run Tests]380      โ†“381  [Build Docker]382      โ†“383   [Test Container]384      โ†“385[Deploy to HuggingFace]386```387 388**Setup:**3891. Add secrets in GitHub repo settings:390   - `HF_TOKEN`: HuggingFace access token391   - `HF_SPACE`: Your space name (username/space-name)392 3932. Push to main branch โ†’ Auto-deploy! โœจ394 395---396 397## ๐Ÿ“š Documentation Access398 399| Document | Purpose |400|----------|---------|401| `README.md` | Overview, API docs, usage examples |402| `QUICKSTART.md` | 5-minute setup guide |403| `DEPLOYMENT.md` | Production deployment |404| `STRUCTURE.md` | Code organization |405| `/docs` endpoint | Interactive API documentation |406 407---408 409## ๐ŸŽ“ Learning Resources410 411### FastAPI412- Docs: https://fastapi.tiangolo.com413- Tutorial: https://fastapi.tiangolo.com/tutorial414 415### HuggingFace416- Spaces: https://huggingface.co/docs/hub/spaces417- Transformers: https://huggingface.co/docs/transformers418 419### Docker420- Getting Started: https://docs.docker.com/get-started421 422---423 424## ๐Ÿ› Troubleshooting425 426### Common Issues427 428**Problem:** "Tesseract not found"  429**Solution:** `apt-get install tesseract-ocr`430 431**Problem:** "Poppler not found"  432**Solution:** `apt-get install poppler-utils`433 434**Problem:** Slow processing  435**Solution:** Lower DPI to 150-200436 437**Problem:** Out of memory  438**Solution:** Upgrade hardware or reduce DPI439 440**Problem:** Model not loading  441**Solution:** Check internet, wait for download442 443### Debug Mode444 445```python446# In main.py, add debug mode447if __name__ == "__main__":448    uvicorn.run("main:app", host="0.0.0.0", port=7860, reload=True, log_level="debug")449```450 451---452 453## โœ… Checklist for Production454 455- [ ] Test all endpoints thoroughly456- [ ] Add API key authentication457- [ ] Implement rate limiting458- [ ] Set up monitoring (Sentry, DataDog, etc.)459- [ ] Configure auto-scaling460- [ ] Set up backups461- [ ] Add usage analytics462- [ ] Create user documentation463- [ ] Set up SSL/TLS (HF provides by default)464- [ ] Test with large files465- [ ] Load testing466- [ ] Security audit467- [ ] Legal compliance (GDPR, etc.)468 469---470 471## ๐ŸŽ‰ You're Ready!472 473Your FastAPI PDF Redaction application is complete and ready to deploy!474 475### Next Steps:4761. โœจ Deploy to HuggingFace Spaces (easiest)4772. ๐Ÿงช Test with real PDFs4783. ๐Ÿ“Š Monitor usage4794. ๐Ÿ”’ Add security for production4805. ๐Ÿš€ Scale as needed481 482### Support:483- ๐Ÿ“– Read the documentation484- ๐Ÿ› Check troubleshooting guide485- ๐Ÿ’ฌ HuggingFace community forums486- ๐Ÿ“ง Create issues on your repo487 488**Happy Deploying! ๐Ÿš€**489