Spaces:
Running
on
Zero
Running
on
Zero
revert
Browse files
app.py
CHANGED
@@ -25,6 +25,12 @@ DEFAULT_NER_LABELS = "person, organization, location, date, event"
|
|
25 |
|
26 |
# }
|
27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
def array_to_image_path(image_array):
|
29 |
# Convert numpy array to PIL Image
|
30 |
img = Image.fromarray(np.uint8(image_array))
|
@@ -43,26 +49,14 @@ def array_to_image_path(image_array):
|
|
43 |
return full_path
|
44 |
|
45 |
models = {
|
46 |
-
"Qwen/Qwen2.5-VL-7B-Instruct": Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
47 |
-
"Qwen/Qwen2.5-VL-7B-Instruct", trust_remote_code=True, torch_dtype="auto"
|
48 |
-
).cuda().eval(),
|
49 |
|
50 |
-
"medieval-data/qwen2.5-vl-old-church-slavonic": Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
51 |
-
"medieval-data/qwen2.5-vl-old-church-slavonic", trust_remote_code=True, torch_dtype="auto"
|
52 |
-
).cuda().eval()
|
53 |
}
|
54 |
|
55 |
processors = {
|
56 |
-
"Qwen/Qwen2.5-VL-7B-Instruct": AutoProcessor.from_pretrained(
|
57 |
-
"Qwen/Qwen2.5-VL-7B-Instruct", trust_remote_code=True
|
58 |
-
),
|
59 |
-
|
60 |
-
"medieval-data/qwen2.5-vl-old-church-slavonic": AutoProcessor.from_pretrained(
|
61 |
-
"medieval-data/qwen2.5-vl-old-church-slavonic", trust_remote_code=True
|
62 |
-
)
|
63 |
}
|
64 |
|
65 |
-
|
66 |
DESCRIPTION = "This demo uses[Qwen2.5-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct)"
|
67 |
|
68 |
kwargs = {}
|
@@ -74,104 +68,92 @@ prompt_suffix = "<|end|>\n"
|
|
74 |
|
75 |
@spaces.GPU
|
76 |
def run_example(image, model_id="Qwen/Qwen2.5-VL-7B-Instruct", run_ner=False, ner_labels=DEFAULT_NER_LABELS):
|
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 |
-
"original_text": ocr_text,
|
128 |
-
"entities": []
|
129 |
-
}
|
130 |
|
131 |
-
#
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
threshold=0.3
|
137 |
-
)
|
138 |
|
139 |
-
#
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
last_end =
|
145 |
-
|
146 |
-
# Sort entities by start position
|
147 |
-
sorted_entities = sorted(ner_results, key=lambda x: x["start"])
|
148 |
-
|
149 |
-
# Process each entity and add non-entity text segments
|
150 |
-
for entity in sorted_entities:
|
151 |
-
# Add non-entity text before the current entity
|
152 |
-
if last_end < entity["start"]:
|
153 |
-
highlighted_text.append((ocr_text[last_end:entity["start"]], None))
|
154 |
-
|
155 |
-
# Add the entity text with its label
|
156 |
-
highlighted_text.append((
|
157 |
-
ocr_text[entity["start"]:entity["end"]],
|
158 |
-
entity["label"]
|
159 |
-
))
|
160 |
-
last_end = entity["end"]
|
161 |
-
|
162 |
-
# Add any remaining text after the last entity
|
163 |
-
if last_end < len(ocr_text):
|
164 |
-
highlighted_text.append((ocr_text[last_end:], None))
|
165 |
-
|
166 |
-
return highlighted_text, state_dict
|
167 |
|
168 |
-
#
|
169 |
-
|
170 |
-
|
171 |
|
172 |
-
|
173 |
-
|
174 |
-
return
|
|
|
|
|
|
|
|
|
175 |
|
176 |
css = """
|
177 |
/* Overall app styling */
|
@@ -282,7 +264,7 @@ with gr.Blocks(css=css) as demo:
|
|
282 |
# Modify create_zip to use the state data
|
283 |
def create_zip(image, fname, ocr_result):
|
284 |
# Validate inputs
|
285 |
-
if not fname or image is None:
|
286 |
return None
|
287 |
|
288 |
try:
|
@@ -297,9 +279,9 @@ with gr.Blocks(css=css) as demo:
|
|
297 |
img_path = os.path.join(temp_dir, f"{fname}.png")
|
298 |
image.save(img_path)
|
299 |
|
300 |
-
# Use the OCR result from state
|
301 |
-
original_text = ocr_result.
|
302 |
-
entities = ocr_result.
|
303 |
|
304 |
# Save text
|
305 |
txt_path = os.path.join(temp_dir, f"{fname}.txt")
|
|
|
25 |
|
26 |
# }
|
27 |
|
28 |
+
class TextWithMetadata(list):
|
29 |
+
def __init__(self, *args, **kwargs):
|
30 |
+
super().__init__(*args)
|
31 |
+
self.original_text = kwargs.get('original_text', '')
|
32 |
+
self.entities = kwargs.get('entities', [])
|
33 |
+
|
34 |
def array_to_image_path(image_array):
|
35 |
# Convert numpy array to PIL Image
|
36 |
img = Image.fromarray(np.uint8(image_array))
|
|
|
49 |
return full_path
|
50 |
|
51 |
models = {
|
52 |
+
"Qwen/Qwen2.5-VL-7B-Instruct": Qwen2_5_VLForConditionalGeneration.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct", trust_remote_code=True, torch_dtype="auto").cuda().eval()
|
|
|
|
|
53 |
|
|
|
|
|
|
|
54 |
}
|
55 |
|
56 |
processors = {
|
57 |
+
"Qwen/Qwen2.5-VL-7B-Instruct": AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct", trust_remote_code=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
58 |
}
|
59 |
|
|
|
60 |
DESCRIPTION = "This demo uses[Qwen2.5-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct)"
|
61 |
|
62 |
kwargs = {}
|
|
|
68 |
|
69 |
@spaces.GPU
|
70 |
def run_example(image, model_id="Qwen/Qwen2.5-VL-7B-Instruct", run_ner=False, ner_labels=DEFAULT_NER_LABELS):
|
71 |
+
# First get the OCR text
|
72 |
+
text_input = "Convert the image to text."
|
73 |
+
image_path = array_to_image_path(image)
|
74 |
+
|
75 |
+
model = models[model_id]
|
76 |
+
processor = processors[model_id]
|
77 |
+
|
78 |
+
prompt = f"{user_prompt}<|image_1|>\n{text_input}{prompt_suffix}{assistant_prompt}"
|
79 |
+
image = Image.fromarray(image).convert("RGB")
|
80 |
+
messages = [
|
81 |
+
{
|
82 |
+
"role": "user",
|
83 |
+
"content": [
|
84 |
+
{
|
85 |
+
"type": "image",
|
86 |
+
"image": image_path,
|
87 |
+
},
|
88 |
+
{"type": "text", "text": text_input},
|
89 |
+
],
|
90 |
+
}
|
91 |
+
]
|
92 |
+
|
93 |
+
# Preparation for inference
|
94 |
+
text = processor.apply_chat_template(
|
95 |
+
messages, tokenize=False, add_generation_prompt=True
|
96 |
+
)
|
97 |
+
image_inputs, video_inputs = process_vision_info(messages)
|
98 |
+
inputs = processor(
|
99 |
+
text=[text],
|
100 |
+
images=image_inputs,
|
101 |
+
videos=video_inputs,
|
102 |
+
padding=True,
|
103 |
+
return_tensors="pt",
|
104 |
+
)
|
105 |
+
inputs = inputs.to("cuda")
|
106 |
+
|
107 |
+
# Inference: Generation of the output
|
108 |
+
generated_ids = model.generate(**inputs, max_new_tokens=1024)
|
109 |
+
generated_ids_trimmed = [
|
110 |
+
out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
|
111 |
+
]
|
112 |
+
output_text = processor.batch_decode(
|
113 |
+
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
|
114 |
+
)
|
115 |
+
|
116 |
+
ocr_text = output_text[0]
|
117 |
+
|
118 |
+
# If NER is enabled, process the OCR text
|
119 |
+
if run_ner:
|
120 |
+
ner_results = gliner_model.predict_entities(
|
121 |
+
ocr_text,
|
122 |
+
ner_labels.split(","),
|
123 |
+
threshold=0.3
|
124 |
)
|
125 |
|
126 |
+
# Create a list of tuples (text, label) for highlighting
|
127 |
+
highlighted_text = []
|
128 |
+
last_end = 0
|
129 |
|
130 |
+
# Sort entities by start position
|
131 |
+
sorted_entities = sorted(ner_results, key=lambda x: x["start"])
|
|
|
|
|
|
|
132 |
|
133 |
+
# Process each entity and add non-entity text segments
|
134 |
+
for entity in sorted_entities:
|
135 |
+
# Add non-entity text before the current entity
|
136 |
+
if last_end < entity["start"]:
|
137 |
+
highlighted_text.append((ocr_text[last_end:entity["start"]], None))
|
|
|
|
|
138 |
|
139 |
+
# Add the entity text with its label
|
140 |
+
highlighted_text.append((
|
141 |
+
ocr_text[entity["start"]:entity["end"]],
|
142 |
+
entity["label"]
|
143 |
+
))
|
144 |
+
last_end = entity["end"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
145 |
|
146 |
+
# Add any remaining text after the last entity
|
147 |
+
if last_end < len(ocr_text):
|
148 |
+
highlighted_text.append((ocr_text[last_end:], None))
|
149 |
|
150 |
+
# Create TextWithMetadata instance with the highlighted text and metadata
|
151 |
+
result = TextWithMetadata(highlighted_text, original_text=ocr_text, entities=ner_results)
|
152 |
+
return result, result # Return twice: once for display, once for state
|
153 |
+
|
154 |
+
# If NER is disabled, return the text without highlighting
|
155 |
+
result = TextWithMetadata([(ocr_text, None)], original_text=ocr_text, entities=[])
|
156 |
+
return result, result # Return twice: once for display, once for state
|
157 |
|
158 |
css = """
|
159 |
/* Overall app styling */
|
|
|
264 |
# Modify create_zip to use the state data
|
265 |
def create_zip(image, fname, ocr_result):
|
266 |
# Validate inputs
|
267 |
+
if not fname or image is None: # Changed the validation check
|
268 |
return None
|
269 |
|
270 |
try:
|
|
|
279 |
img_path = os.path.join(temp_dir, f"{fname}.png")
|
280 |
image.save(img_path)
|
281 |
|
282 |
+
# Use the OCR result from state
|
283 |
+
original_text = ocr_result.original_text if ocr_result else ""
|
284 |
+
entities = ocr_result.entities if ocr_result else []
|
285 |
|
286 |
# Save text
|
287 |
txt_path = os.path.join(temp_dir, f"{fname}.txt")
|