File size: 6,568 Bytes
ad5d213 | 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 | """
Docling Hugging Face Spaces API
Deploy this on Hugging Face Spaces to provide Docling extraction API
"""
import os
import tempfile
from pathlib import Path
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from docling.document_converter import DocumentConverter
from docling.datamodel.base_models import InputFormat
import uvicorn
app = FastAPI(
title="Docling Document Converter API",
description="Convert documents using Docling AI",
version="1.0.0"
)
# Allow CORS for DataSync integration
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Global converter instance
converter = None
def get_converter():
"""Get or create DocumentConverter instance"""
global converter
if converter is None:
converter = DocumentConverter()
return converter
@app.get("/")
def root():
"""Health check"""
return {
"status": "ok",
"service": "Docling API",
"version": "1.0.0"
}
@app.get("/health")
def health():
"""Health check"""
return {"status": "ok", "gpu": "available"}
@app.post("/convert")
async def convert_document(file: UploadFile = File(...)):
"""
Convert document to structured data
Returns: JSON with markdown, tables, and metadata
"""
if not file.filename:
raise HTTPException(status_code=400, detail="No file provided")
supported_extensions = ['.pdf', '.docx', '.xlsx', '.pptx', '.html', '.txt', '.md']
ext = Path(file.filename).suffix.lower()
if ext not in supported_extensions:
raise HTTPException(
status_code=400,
detail=f"Unsupported format: {ext}. Supported: {supported_extensions}"
)
try:
# Save uploaded file temporarily
with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as tmp:
content = await file.read()
tmp.write(content)
tmp_path = tmp.name
# Convert document
converter = get_converter()
result = converter.convert(tmp_path)
# Extract data
doc = result.document
# Get markdown
markdown_text = doc.export_to_markdown()
# Extract tables
tables_data = []
for table_idx, table in enumerate(doc.tables):
try:
df = table.export_to_dataframe()
table_dict = {
"table_index": table_idx,
"rows": df.to_dict('records'),
"row_count": len(df)
}
tables_data.append(table_dict)
except Exception as e:
tables_data.append({
"table_index": table_idx,
"error": str(e)
})
# Build response
response = {
"success": True,
"file_name": file.filename,
"document": {
"markdown": markdown_text,
"text": doc.export_to_text() if hasattr(doc, 'export_to_text') else markdown_text,
"num_pages": len(doc.pages) if hasattr(doc, 'pages') else 0,
"tables": tables_data,
"tables_count": len(tables_data)
},
"metadata": {
"format": ext,
"engine": "docling",
"model": "docling-default"
}
}
# Cleanup
os.unlink(tmp_path)
return JSONResponse(content=response)
except Exception as e:
# Cleanup on error
if 'tmp_path' in locals():
try:
os.unlink(tmp_path)
except:
pass
raise HTTPException(status_code=500, detail=f"Conversion failed: {str(e)}")
@app.post("/convert/markdown")
async def convert_to_markdown(file: UploadFile = File(...)):
"""Convert document to markdown only (lightweight)"""
try:
with tempfile.NamedTemporaryFile(delete=False, suffix=Path(file.filename).suffix.lower()) as tmp:
content = await file.read()
tmp.write(content)
tmp_path = tmp.name
converter = get_converter()
result = converter.convert(tmp_path)
markdown = result.document.export_to_markdown()
os.unlink(tmp_path)
return {
"success": True,
"markdown": markdown,
"file_name": file.filename
}
except Exception as e:
if 'tmp_path' in locals():
try:
os.unlink(tmp_path)
except:
pass
raise HTTPException(status_code=500, detail=str(e))
@app.post("/convert/tables")
async def convert_tables(file: UploadFile = File(...)):
"""Extract tables only from document"""
try:
with tempfile.NamedTemporaryFile(delete=False, suffix=Path(file.filename).suffix.lower()) as tmp:
content = await file.read()
tmp.write(content)
tmp_path = tmp.name
converter = get_converter()
result = converter.convert(tmp_path)
tables_data = []
for table_idx, table in enumerate(result.document.tables):
try:
df = table.export_to_dataframe()
tables_data.append({
"table_index": table_idx,
"headers": list(df.columns),
"rows": df.to_dict('records'),
"row_count": len(df)
})
except:
pass
os.unlink(tmp_path)
return {
"success": True,
"tables": tables_data,
"tables_count": len(tables_data),
"file_name": file.filename
}
except Exception as e:
if 'tmp_path' in locals():
try:
os.unlink(tmp_path)
except:
pass
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
print("="*60)
print("Docling Document Converter API")
print("="*60)
print("URL: http://localhost:8080")
print("Docs: http://localhost:8080/docs")
print("="*60)
uvicorn.run(
"app:app",
host="0.0.0.0",
port=8080,
reload=True
)
|