Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import pipeline
|
| 3 |
+
|
| 4 |
+
MODEL_ID = "kanansharmaa/layoutlm_document_qa"
|
| 5 |
+
|
| 6 |
+
qa = pipeline(
|
| 7 |
+
"document-question-answering",
|
| 8 |
+
model=MODEL_ID,
|
| 9 |
+
device=-1
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
def answer_document(image, question):
|
| 13 |
+
if image is None:
|
| 14 |
+
return "Please upload a document image."
|
| 15 |
+
if not question or not question.strip():
|
| 16 |
+
return "Please enter a question."
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
results = qa(image, question.strip())
|
| 20 |
+
if not results:
|
| 21 |
+
return "No answer was returned. Try a clearer image or a more specific question."
|
| 22 |
+
|
| 23 |
+
result = results[0]
|
| 24 |
+
answer = result.get("answer", "")
|
| 25 |
+
confidence = result.get("score", 0)
|
| 26 |
+
|
| 27 |
+
return (
|
| 28 |
+
f"Answer: {answer}\n\n"
|
| 29 |
+
f"Model confidence: {confidence:.1%}\n\n"
|
| 30 |
+
"Verification note: Check the answer against the original document. "
|
| 31 |
+
"The confidence score is not a guarantee of correctness."
|
| 32 |
+
)
|
| 33 |
+
except Exception as exc:
|
| 34 |
+
return (
|
| 35 |
+
"The document could not be processed. "
|
| 36 |
+
"Check the Space logs for technical details.\n"
|
| 37 |
+
f"Error: {str(exc)[:400]}"
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
demo = gr.Interface(
|
| 41 |
+
fn=answer_document,
|
| 42 |
+
inputs=[
|
| 43 |
+
gr.Image(type="pil", label="Upload document image"),
|
| 44 |
+
gr.Textbox(
|
| 45 |
+
label="Your question",
|
| 46 |
+
placeholder="What is the date on this document?"
|
| 47 |
+
)
|
| 48 |
+
],
|
| 49 |
+
outputs=gr.Textbox(label="Document answer", lines=6),
|
| 50 |
+
title="S.E. Global | Document Intelligence",
|
| 51 |
+
description=(
|
| 52 |
+
"Upload a document image and ask a question about its contents. "
|
| 53 |
+
"Verify important answers against the original document."
|
| 54 |
+
),
|
| 55 |
+
examples=None
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
if __name__ == "__main__":
|
| 59 |
+
demo.launch()
|
| 60 |
+
|