Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files- app.py +126 -0
- requirements.txt +6 -0
app.py
ADDED
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from gradio import Interface, File, Dropdown, Textbox, Slider
|
2 |
+
import json
|
3 |
+
from gliner import GLiNER
|
4 |
+
from doctr.io import DocumentFile
|
5 |
+
from doctr.models import ocr_predictor
|
6 |
+
|
7 |
+
class DoctrHandler:
|
8 |
+
def __init__(self):
|
9 |
+
self.model = ocr_predictor(det_arch="fast_base", reco_arch="crnn_vgg16_bn", pretrained=True)
|
10 |
+
|
11 |
+
def extract_text(self, file_path):
|
12 |
+
try:
|
13 |
+
# Handle both PDF and image files
|
14 |
+
doc = DocumentFile.from_pdf(file_path) if file_path.endswith('.pdf') else DocumentFile.from_images(file_path)
|
15 |
+
# Perform OCR
|
16 |
+
result = self.model(doc)
|
17 |
+
# Extract text from result
|
18 |
+
text = ""
|
19 |
+
for page in result.pages:
|
20 |
+
for block in page.blocks:
|
21 |
+
for line in block.lines:
|
22 |
+
for word in line.words:
|
23 |
+
text += word.value + " "
|
24 |
+
return text.strip()
|
25 |
+
except Exception as e:
|
26 |
+
raise Exception(f"Error during OCR processing: {str(e)}")
|
27 |
+
|
28 |
+
class GlinerHandler:
|
29 |
+
def __init__(self):
|
30 |
+
self.max_length = 384
|
31 |
+
self.model = GLiNER.from_pretrained("urchade/gliner_multi-v2.1", max_length=self.max_length)
|
32 |
+
|
33 |
+
def predict_entities(self, text, labels, threshold):
|
34 |
+
|
35 |
+
entities = self.model.predict_entities(text, labels, threshold=threshold)
|
36 |
+
|
37 |
+
return entities
|
38 |
+
|
39 |
+
# Initialize handlers
|
40 |
+
ocr_handler = DoctrHandler()
|
41 |
+
ner_handler = GlinerHandler()
|
42 |
+
|
43 |
+
# Default entities
|
44 |
+
DEFAULT_ENTITIES = ["name", "person", "bank account number", "email", "address", "phone number", "date", "currency", "amount", "document number", "iban", "country"]
|
45 |
+
|
46 |
+
def process_file(uploaded_file, selected_entities, custom_entities, threshold=0.5):
|
47 |
+
|
48 |
+
# Input validation
|
49 |
+
if not selected_entities and not custom_entities:
|
50 |
+
return json.dumps({
|
51 |
+
"message": "Please select or provide at least one entity to search for",
|
52 |
+
"hits": 0,
|
53 |
+
"searched_for": [],
|
54 |
+
"entities": []
|
55 |
+
}, indent=4)
|
56 |
+
|
57 |
+
# Handle no file uploaded
|
58 |
+
if not uploaded_file:
|
59 |
+
return json.dumps({
|
60 |
+
"message": "No file uploaded",
|
61 |
+
"hits": 0,
|
62 |
+
"searched_for": [],
|
63 |
+
"entities": []
|
64 |
+
}, indent=4)
|
65 |
+
|
66 |
+
# Convert custom entities string to list and clean whitespace
|
67 |
+
custom_entity_list = [e.strip() for e in custom_entities.split(",") if e.strip()] if custom_entities else []
|
68 |
+
|
69 |
+
# Combine default and custom entities
|
70 |
+
all_entities = selected_entities + custom_entity_list
|
71 |
+
|
72 |
+
# Perform OCR on the uploaded file
|
73 |
+
extracted_text = ocr_handler.extract_text(uploaded_file.name)
|
74 |
+
|
75 |
+
# Perform NER on the extracted text with threshold
|
76 |
+
entities = ner_handler.predict_entities(extracted_text, all_entities, threshold)
|
77 |
+
|
78 |
+
if not entities:
|
79 |
+
return json.dumps({
|
80 |
+
"message": "No entities were found in the document",
|
81 |
+
"hits": 0,
|
82 |
+
"searched_for": all_entities,
|
83 |
+
"entities": []
|
84 |
+
}, indent=4)
|
85 |
+
|
86 |
+
# Clean and sort entities
|
87 |
+
cleaned_entities = []
|
88 |
+
for entity in entities:
|
89 |
+
cleaned_entity = {
|
90 |
+
"text": entity["text"],
|
91 |
+
"label": entity["label"],
|
92 |
+
"confidence": entity["score"]
|
93 |
+
}
|
94 |
+
cleaned_entities.append(cleaned_entity)
|
95 |
+
|
96 |
+
# Sort by confidence score in descending order
|
97 |
+
cleaned_entities.sort(key=lambda x: x["confidence"], reverse=True)
|
98 |
+
|
99 |
+
# Return structured response
|
100 |
+
response = {
|
101 |
+
"message": "Document destroyed successfully!",
|
102 |
+
"hits": len(cleaned_entities),
|
103 |
+
"searched_for": all_entities,
|
104 |
+
"entities": cleaned_entities
|
105 |
+
}
|
106 |
+
|
107 |
+
return json.dumps(response, indent=4)
|
108 |
+
|
109 |
+
|
110 |
+
# Create Gradio interface
|
111 |
+
iface = Interface(
|
112 |
+
fn=process_file,
|
113 |
+
inputs=[
|
114 |
+
File(label="Upload Document (PDF or Image)"),
|
115 |
+
Dropdown(choices=DEFAULT_ENTITIES, label="Select Entities", multiselect=True),
|
116 |
+
Textbox(label="Custom Entities (comma-separated)", placeholder="entity1, entity2, ..."),
|
117 |
+
Slider(minimum=0.1, maximum=1.0, value=0.5, step=0.1, label="Confidence Threshold")
|
118 |
+
],
|
119 |
+
outputs=Textbox(label="Extracted Entities (JSON)"),
|
120 |
+
title="DocDestroyer11000",
|
121 |
+
allow_flagging=False,
|
122 |
+
description="Extract valuable information from your documents in a snap! Upload your PDFs or images, select the entities you care about et started now and watch your documents be **destroyed** (or in other words - turned into JSON)! 🚀<br>Tech: Copilot/Claude Sonnet + https://mindee.github.io/doctr/ + https://huggingface.co/urchade/gliner_multi-v2.1"
|
123 |
+
)
|
124 |
+
|
125 |
+
if __name__ == "__main__":
|
126 |
+
iface.launch()
|
requirements.txt
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
--index-url https://download.pytorch.org/whl/cpu
|
2 |
+
torch
|
3 |
+
torchvision
|
4 |
+
gliner
|
5 |
+
python-doctr
|
6 |
+
gradio
|