File size: 8,216 Bytes
cb8b77e
881a2c6
 
 
 
cb8b77e
 
881a2c6
cb8b77e
 
881a2c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
---
title: Docling Multi-Template Extraction API
emoji: πŸ“„
colorFrom: blue
colorTo: green
sdk: docker
pinned: false
license: apache-2.0
---

# Docling Multi-Template Document Extraction API

πŸš€ Deploy Docling on Hugging Face Spaces with dynamic template matching for invoice and payment advice extraction.

## Features

- πŸ”„ **Dynamic Template Discovery**: Automatically detects and loads templates from the `templates/` directory
- 🎯 **Smart Name Matching**: Works with any naming convention (snake_case, kebab-case, PascalCase)
- πŸ€– **Auto-Detection**: Automatically identifies document types from content
- πŸ“Š **Structured JSON Output**: Extract invoices, payment advices, and custom documents to JSON
- 🌐 **REST API**: Easy integration with n8n, Make, Zapier, or custom workflows
- 🎨 **Web UI**: Built-in Gradio interface for testing

## Quick Start

### Deploy to Hugging Face Spaces

1. **Create a new Space:**
   - Go to [huggingface.co/spaces](https://huggingface.co/spaces)
   - Click "Create new Space"
   - Name: `docling-api` (or your preferred name)
   - SDK: **Docker**
   - Hardware: **CPU basic (free tier)** - 2 vCPU, 16 GB RAM

2. **Clone and push code:**
```bash
git clone https://huggingface.co/spaces/YOUR-USERNAME/docling-api
cd docling-api

# Copy all files from this project
# (app.py, templates/, requirements.txt, Dockerfile, README.md)

git add .
git commit -m "Initial deployment"
git push
```

3. **Wait for build** (5-10 minutes for first deployment)

4. **Your API is live at:** `https://YOUR-USERNAME-docling-api.hf.space`

## API Endpoints

### Extract Document Data
```http
POST /api/extract
Content-Type: multipart/form-data

Query Parameters:
- template_type: auto | payment_advice | invoice | custom_template
```

**Example with curl:**
```bash
curl -X POST "https://YOUR-SPACE.hf.space/api/extract?template_type=auto" \
  -F "file=@invoice.pdf"
```

**Response:**
```json
{
  "success": true,
  "template_used": "invoice",
  "data": {
    "bill_no": "JRPL14725-26",
    "bill_date": "03-12-2025",
    "total_amount": 16618.0,
    "seller": {
      "name": "Jobuss Resources Pvt Ltd",
      "gst_no": "27AAECJ2353C1ZX"
    },
    "buyer": {
      "name": "Reliance Industries Limited",
      "vendor_code": "3347687"
    }
  },
  "filename": "invoice.pdf"
}
```

### List Available Templates
```http
GET /api/templates
```

### Template Variations
```http
GET /api/templates/variations
```

## Flexible Naming

All these work identically:
```bash
?template_type=payment_advice    # snake_case
?template_type=payment-advice    # kebab-case
?template_type=PaymentAdvice     # PascalCase
?template_type=PAYMENT_ADVICE    # UPPER_CASE
```

## Using with n8n

### Setup HTTP Request Node

1. **Method:** POST
2. **URL:** `https://YOUR-SPACE.hf.space/api/extract`
3. **Query Parameters:**
   - Name: `template_type`
   - Value: `auto` (or specific template name)
4. **Body Content Type:** Multipart-Form-Data
5. **Body Parameters:**
   - Name: `file`
   - Type: `n8n Binary File`
   - Input Data Field Name: `data` (or your binary field)

### Example n8n Workflow

```
[Trigger/File Input] 
    ↓
[HTTP Request - Docling API]
    ↓
[Code Node - Parse Response]
    ↓
[Database/Spreadsheet Output]
```

### Parse Response in Code Node (n8n)

```javascript
// Access the extracted data
const response = $input.item.json;

if (response.success) {
  const data = response.data;
  
  return {
    invoice_number: data.bill_no,
    date: data.bill_date,
    amount: data.total_amount,
    vendor: data.seller?.name,
    all_data: data
  };
}
```

## Adding Custom Templates

Create a new file in `templates/` directory:

### Example: `templates/purchase_order_template.py`

```python
from pydantic import BaseModel, Field
from typing import Optional, List

class POLineItem(BaseModel):
    item_code: Optional[str] = Field(default=None)
    description: Optional[str] = Field(default=None)
    quantity: Optional[float] = Field(default=None)
    unit_price: Optional[float] = Field(default=None)
    total: Optional[float] = Field(default=None)

class Vendor(BaseModel):
    vendor_id: Optional[str] = Field(default=None)
    name: Optional[str] = Field(default=None)
    address: Optional[str] = Field(default=None)

class PurchaseOrder(BaseModel):
    document_type: str = Field(default="purchase_order")
    po_number: Optional[str] = Field(default=None)
    po_date: Optional[str] = Field(default=None)
    delivery_date: Optional[str] = Field(default=None)
    vendor: Optional[Vendor] = Field(default=None)
    subtotal: Optional[float] = Field(default=None)
    tax_amount: Optional[float] = Field(default=None)
    total_amount: Optional[float] = Field(default=None)
    line_items: Optional[List[POLineItem]] = Field(default=[])
```

**That's it!** The template is automatically discovered and available at:
```
?template_type=purchase_order
```

## Template Naming Convention

File must follow this pattern:
- **Filename:** `{template_name}_template.py`
- **Class name:** PascalCase version of template_name (e.g., `PurchaseOrder`)
- **Must inherit from:** `pydantic.BaseModel`

Examples:
- `payment_advice_template.py` β†’ class `PaymentAdvice`
- `invoice_template.py` β†’ class `Invoice`
- `purchase_order_template.py` β†’ class `PurchaseOrder`

## Auto-Detection Keywords

Edit `template_router.py` to add detection rules:

```python
detection_rules = {
    "payment_advice": ["payment advice", "payment document"],
    "invoice": ["tax invoice", "bill no", "invoice date"],
    "purchase_order": ["purchase order", "po number"],
    "your_custom_type": ["your", "keywords", "here"],
}
```

## Web Interface

Access the Gradio UI at: `https://YOUR-SPACE.hf.space/gradio`

- Upload documents
- Select template or use auto-detect
- View extracted JSON instantly

## Supported Document Formats

- PDF documents
- Images (PNG, JPG, JPEG)
- DOCX (requires additional configuration)

## Hardware Requirements

### Free Tier (CPU basic)
- βœ… Standard invoices (1-5 pages)
- βœ… Payment advices
- βœ… Simple documents
- ⚠️ Large PDFs may timeout (30s limit)

### Upgraded Tier (Recommended for production)
- CPU basic upgrade: 4 vCPU, 16 GB RAM
- Faster processing
- Handle larger documents

## Troubleshooting

### Template Not Found Error
```json
{"detail": "Template 'xyz' not found. Available templates: payment_advice, invoice"}
```
**Solution:** Check filename matches `{name}_template.py` pattern

### Timeout Errors
**Solution:** Upgrade to larger hardware tier or reduce document size

### Import Errors
**Solution:** Ensure all dependencies in `requirements.txt` and rebuild Space

## API Rate Limits

Hugging Face Spaces free tier:
- No official rate limit
- Fair usage policy applies
- For production: Consider Hugging Face Pro ($9/month)

## Local Development

```bash
# Clone repository
git clone https://huggingface.co/spaces/YOUR-USERNAME/docling-api
cd docling-api

# Install dependencies
pip install -r requirements.txt

# Run locally
uvicorn app:app --host 0.0.0.0 --port 7860 --reload
```

Access at: `http://localhost:7860`

## Environment Variables

Optional configurations (add in Space settings):

```bash
# Logging level
LOG_LEVEL=INFO

# Max file size (MB)
MAX_FILE_SIZE=50
```

## Security Notes

- ⚠️ Free tier Spaces are public by default
- πŸ”’ For sensitive documents, use private Spaces (Hugging Face Pro)
- πŸ” Consider adding API key authentication for production

## Contributing

Add new templates or improve detection logic:

1. Fork the Space
2. Add your template in `templates/`
3. Update detection rules in `template_router.py`
4. Test with sample documents
5. Submit pull request

## License

Apache 2.0

## Support

- Documentation: [Docling GitHub](https://github.com/docling-project/docling)
- Issues: Create issue in your Space repository
- Community: Hugging Face Discord

## Credits

Built with:
- [Docling](https://github.com/docling-project/docling) - Document processing
- [FastAPI](https://fastapi.tiangolo.com/) - Web framework
- [Gradio](https://gradio.app/) - Web interface
- [Pydantic](https://docs.pydantic.dev/) - Data validation

---

**Made with ❀️ for the document automation community**