Flavio de Oliveira commited on
Commit
4e53efb
•
1 Parent(s): 6220393

First commit

Browse files
Files changed (4) hide show
  1. .gitignore +5 -0
  2. app.py +146 -0
  3. examples/.gitkeep +0 -0
  4. requirements.txt +48 -0
.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ flagged/
2
+ __pycache__
3
+ .DS_Store
4
+ *.pt
5
+ *.ipynb
app.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import cv2
4
+ import supervision as sv # For annotations
5
+ from ultralytics import YOLO
6
+ import glob
7
+ import json
8
+ import ast
9
+
10
+ # TODO: finetune/test bigger models
11
+ model_1 = YOLO('best.pt') # Finetuned YoloV8s
12
+ # model_2 =
13
+ # model_3 =
14
+
15
+ box_annotator = sv.BoxAnnotator(
16
+ thickness=2,
17
+ text_thickness=2,
18
+ text_scale=1
19
+ )
20
+
21
+ def show_preds_image(option, image_path):
22
+
23
+ predict = []
24
+
25
+ if(option == "yolov8s-ft-yalta-ai-segmonto-manuscript"):
26
+ model = model_1
27
+ # if(option == "yolov8m-ft-yalta-ai-segmonto-manuscript"):
28
+ # model = model_2
29
+ # if(option == "yolov8l-ft-yalta-ai-segmonto-manuscript"):
30
+ # model = model_3
31
+
32
+ image = cv2.imread(image_path)
33
+
34
+ outputs = model.predict(source=image_path, device="cpu")
35
+
36
+ ##############
37
+ # result = outputs[0]
38
+ # bboxes = np.array(result.boxes.xyxy, dtype="int") # result.boxes.xyxy.cpu()
39
+ # classes = np.array(result.boxes.cls, dtype="int")
40
+
41
+ # for cls, bbox in zip(classes, bboxes):
42
+ # (x, y, x2, y2) = bbox
43
+ # cv2.rectangle(frame, (x, y), (x2, y2), (0, 0, 225), 3)
44
+ # # cv2.putText(frame, str(cls), (x, y - 5), cv2.FONT_HERSHEY_PLAIN, 2, (0, 0, 225), 2)
45
+ # cv2.putText(frame, str(model.names[int(cls)]), (x, y - 5), cv2.FONT_HERSHEY_PLAIN, 2, (0, 0, 225), 2)
46
+
47
+ # return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
48
+ ################
49
+
50
+ result = outputs[0]
51
+ # detections = sv.Detections.from_yolov8(result) # Deprecated
52
+ detections = sv.Detections.from_ultralytics(result)
53
+
54
+ labels = [
55
+ f"{model.model.names[class_id]} {confidence:0.2f}"
56
+ for _, _, confidence, class_id, _
57
+ in detections
58
+ ]
59
+ frame = box_annotator.annotate(
60
+ scene=image,
61
+ detections=detections,
62
+ labels=labels
63
+ )
64
+
65
+ # Build the dictionary
66
+ predict.append(
67
+ {
68
+ "label": [ast.literal_eval(model.model.names[id]) for id in detections.class_id.tolist()],
69
+ # The list of coordinates of the points of the polygon.
70
+ "bbox": detections.xyxy.tolist(),
71
+ # Confidence that the model predicts the polygon in the right place
72
+ "confidence": detections.confidence.tolist(),
73
+ }
74
+ )
75
+
76
+ # captions = {
77
+ # f"{model.model.names[class_id]}": float("{:.2f}".format(confidence))
78
+ # for _, _, confidence, class_id, _
79
+ # in detections
80
+ # }
81
+
82
+ return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB), json.dumps(predict, indent=2)#, captions
83
+
84
+ title = "<h1 style='text-align: center'>YoloV8 Medieval Manuscript Region Detection 📜🪶 - SegmOnto Ontology</h1>"
85
+ description="""Treating page layout recognition on historical documents as an object detection task (compared to the usual pixel segmentation approach). Model finetuned on **YALTAi Segmonto Manuscript and Early Printed Book Dataset** (HF `dataset card`: [biglam/yalta_ai_segmonto_manuscript_dataset](https://huggingface.co/datasets/biglam/yalta_ai_segmonto_manuscript_dataset)).
86
+ * Note that this demo is running on a small resource environment, `basic CPU plan` (`2 vCPU, 16GB RAM`).
87
+ """
88
+ article = "<p style='text-align: center'>ArXiv: <a href='https://arxiv.org/abs/2207.11230v1' target='_blank'>You Actually Look Twice At it (YALTAi): using an object detection approach instead of region segmentation within the Kraken engine</a></p>"
89
+
90
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
91
+
92
+ gr.HTML(title)
93
+ gr.Markdown(description)
94
+ # gr.HTML(description)
95
+
96
+ with gr.Row():
97
+ with gr.Column(scale=1, variant="panel"):
98
+ with gr.Row():
99
+ input_image = gr.components.Image(type="filepath", label="Input Image", height=350)
100
+
101
+ with gr.Row():
102
+ input_model = gr.components.Dropdown(["yolov8s-ft-yalta-ai-segmonto-manuscript"], label="Model")
103
+
104
+ with gr.Row():
105
+ btn_clear = gr.Button(value="Clear")
106
+ btn = gr.Button(value="Submit")
107
+ # btn.click(show_preds_image, inputs=[input_model, input_image], outputs=output)
108
+
109
+ with gr.Row(): # gr.Column()
110
+ with gr.Accordion(label="Choose an example:", open=False):
111
+ gr.Examples(
112
+ examples = [["yolov8s-ft-yalta-ai-segmonto-manuscript", str(file)] for file in glob.glob("./examples/*.jpg")],
113
+ inputs = [input_model, input_image],
114
+ # label="Samples",
115
+ )
116
+
117
+ with gr.Column(scale=1, variant="panel"):
118
+ with gr.Tab("Output"):
119
+ with gr.Row():
120
+ output = gr.components.Image(type="numpy", label="Output", height=500)
121
+
122
+ # with gr.Row():
123
+ # btn_flag = gr.Button(value="Flag") # TODO
124
+
125
+ # with gr.Row():
126
+ # captions = gr.Dataframe(headers=["Label", "Confidence"])
127
+
128
+ with gr.Tab("JSON Output"):
129
+ with gr.Row():
130
+ # Create a column so that the JSON output doesn't take the full size of the page
131
+ with gr.Column():
132
+ # Create a collapsible region
133
+ with gr.Accordion(label="JSON Output", open="False"):
134
+ # Generates a json with the model predictions
135
+ json_output = gr.JSON(label="JSON")
136
+
137
+ btn.click(show_preds_image, inputs=[input_model, input_image], outputs=[output, json_output])
138
+ btn_clear.click(lambda: [None, None, None, None], outputs=[input_image, input_model, output, json_output])
139
+ # btn_flag.click()
140
+
141
+ with gr.Row():
142
+ gr.HTML(article)
143
+
144
+ if __name__ =="__main__":
145
+
146
+ demo.queue().launch() # share=True, auth=("username", "password")
examples/.gitkeep ADDED
File without changes
requirements.txt ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ultralytics requirements
2
+ # Usage: pip install -r requirements.txt
3
+
4
+ # Base ----------------------------------------
5
+ hydra-core>=1.2.0
6
+ matplotlib>=3.2.2
7
+ numpy>=1.18.5
8
+ opencv-python>=4.1.1
9
+ Pillow>=7.1.2
10
+ PyYAML>=5.3.1
11
+ requests>=2.23.0
12
+ scipy>=1.4.1
13
+ torch>=1.7.0
14
+ torchvision>=0.8.1
15
+ tqdm>=4.64.0
16
+ ultralytics
17
+ gradio_client==0.2.7
18
+
19
+ # Logging -------------------------------------
20
+ tensorboard>=2.4.1
21
+ # clearml
22
+ # comet
23
+
24
+ # Plotting ------------------------------------
25
+ pandas>=1.1.4
26
+ seaborn>=0.11.0
27
+
28
+ # Export --------------------------------------
29
+ # coremltools>=6.0 # CoreML export
30
+ # onnx>=1.12.0 # ONNX export
31
+ # onnx-simplifier>=0.4.1 # ONNX simplifier
32
+ # nvidia-pyindex # TensorRT export
33
+ # nvidia-tensorrt # TensorRT export
34
+ # scikit-learn==0.19.2 # CoreML quantization
35
+ # tensorflow>=2.4.1 # TF exports (-cpu, -aarch64, -macos)
36
+ # tensorflowjs>=3.9.0 # TF.js export
37
+ # openvino-dev # OpenVINO export
38
+
39
+ # Extras --------------------------------------
40
+ ipython # interactive notebook
41
+ psutil # system utilization
42
+ thop>=0.1.1 # FLOPs computation
43
+ # albumentations>=1.0.3
44
+ # pycocotools>=2.0.6 # COCO mAP
45
+ # roboflow
46
+
47
+ # HUB -----------------------------------------
48
+ GitPython>=3.1.24