Babe7777's picture
Add free original LayoutLM document QA service
c500593 verified
Raw History Blame Contribute Delete
2.62 kB
import base64
import io
import spaces
import gradio as gr
import torch
from PIL import Image
from transformers import pipeline
MODEL = 'impira/layoutlm-document-qa'
REVISION = 'beed3c4d02d86017ebca5bd0fdf210046b907aa6'
LANGUAGES = {'en':'eng','es':'spa','fr':'fra','de':'deu','it':'ita','pt':'por'}
Image.MAX_IMAGE_PIXELS = 16000000
qa = pipeline('document-question-answering', model=MODEL, revision=REVISION, device=-1, model_kwargs={'use_safetensors':True})
@spaces.GPU(duration=30)
def answer(payload):
if not isinstance(payload, dict) or payload.get('model') != MODEL:
raise gr.Error('Only the pinned impira/layoutlm-document-qa model is supported')
inputs = payload.get('inputs', {})
encoded = inputs.get('image', '')
if not isinstance(encoded,str) or len(encoded)>5592408:
raise gr.Error('Document image must be base64 and at most 4 MiB')
image = Image.open(io.BytesIO(base64.b64decode(encoded, validate=True)))
if image.width*image.height>16000000:
raise gr.Error('Document image exceeds 16 megapixels')
image=image.convert('RGB')
question=inputs.get('question')
if not isinstance(question,str) or not question.strip() or len(question)>2000:
raise gr.Error('A question of 1 to 2000 characters is required')
parameters=payload.get('parameters',{})
if set(parameters)-{'top_k','max_answer_len','handle_impossible_answer','lang'}:
raise gr.Error('Unsupported document QA parameter')
options=dict(parameters)
lang=options.pop('lang','en')
if lang not in LANGUAGES: raise gr.Error('Unsupported OCR language')
for k,maximum in [('top_k',20),('max_answer_len',512)]:
v=options.get(k)
if v is not None and (type(v) is not int or not 1<=v<=maximum):
raise gr.Error('Invalid '+k)
if 'handle_impossible_answer' in options and type(options['handle_impossible_answer']) is not bool:
raise gr.Error('handle_impossible_answer must be boolean')
qa.model.to('cuda')
qa.device=torch.device('cuda')
return qa(image=image, question=question, lang=LANGUAGES[lang], **options)
app=gr.Interface(fn=answer,inputs=gr.JSON(label='Document QA request'),outputs=gr.JSON(label='Extracted answers'),api_name='document_qa',title='PixoFlow Document QA',description='Layout-aware extractive document QA using the pinned MIT-licensed Impira model. Free ZeroGPU quota; never enables paid hardware. Do not submit private documents to this public demo.',allow_flagging='never',analytics_enabled=False)
app.queue(max_size=8,default_concurrency_limit=1).launch(show_error=True,max_file_size='4mb')