Views
No views yet
1e-6. This model would not be possible without the numerous annotators behind the various datasets available on HTR-United (See dataset for details). A special thanks to Thibault Clérice who converted the original CATMuS dataset (for HTR) to a segmentation dataset.1import requests
2from PIL import Image
3from transformers import AutoProcessor, AutoModelForCausalLM
4import os
5from unittest.mock import patch
6
7import requests
8from PIL import Image
9from transformers import AutoModelForCausalLM, AutoProcessor
10from transformers.dynamic_module_utils import get_imports
11import matplotlib.pyplot as plt
12import matplotlib.patches as patches
13
14# Mac solution => https://huggingface.co/microsoft/Florence-2-large-ft/discussions/4
15def fixed_get_imports(filename: str | os.PathLike) -> list[str]:
16 """Work around for https://huggingface.co/microsoft/phi-1_5/discussions/72."""
17 if not str(filename).endswith("/modeling_florence2.py"):
18 return get_imports(filename)
19 imports = get_imports(filename)
20 imports.remove("flash_attn")
21 return imports
22
23
24with patch("transformers.dynamic_module_utils.get_imports", fixed_get_imports):
25
26 model = AutoModelForCausalLM.from_pretrained("medieval-data/florence2-medieval-bbox-zone-detection", trust_remote_code=True)
27 processor = AutoProcessor.from_pretrained("medieval-data/florence2-medieval-bbox-zone-detection", trust_remote_code=True)
28
29def process_image(url):
30 prompt = "<OD>"
31
32 image = Image.open(requests.get(url, stream=True).raw)
33
34 inputs = processor(text=prompt, images=image, return_tensors="pt")
35
36 generated_ids = model.generate(
37 input_ids=inputs["input_ids"],
38 pixel_values=inputs["pixel_values"],
39 max_new_tokens=1024,
40 do_sample=False,
41 num_beams=3
42 )
43 generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
44
45 result = processor.post_process_generation(generated_text, task="<OD>", image_size=(image.width, image.height))
46 return result, image
47
48
49image = "https://huggingface.co/datasets/CATMuS/medieval-segmentation/resolve/main/data/train/cambridge-corpus-christi-college-ms-111/page-002-of-003.jpg"
50
51result, image = process_image(image)
52fig, ax = plt.subplots(1, figsize=(15, 15))
53ax.imshow(image)
54
55# Add bounding boxes and labels to the plot
56for bbox, label in zip(result['<OD>']['bboxes'], result['<OD>']['labels']):
57 x, y, width, height = bbox[0], bbox[1], bbox[2] - bbox[0], bbox[3] - bbox[1]
58 rect = patches.Rectangle((x, y), width, height, linewidth=2, edgecolor='r', facecolor='none')
59 ax.add_patch(rect)
60 plt.text(x, y, label, fontsize=12, bbox=dict(facecolor='yellow', alpha=0.5))
61
62# Display the plot
63plt.show()