Spaces:
Runtime error
Runtime error
Zengyf-CVer
commited on
Commit
•
0e4f466
1
Parent(s):
296d0dd
init
Browse files- .gitignore +45 -0
- README.md +3 -1
- __init__.py +2 -0
- app.py +385 -0
- cls_name/cls_name.csv +80 -0
- cls_name/cls_name.yaml +7 -0
- cls_name/cls_name_ar.yaml +9 -0
- cls_name/cls_name_en.yaml +9 -0
- cls_name/cls_name_es.yaml +9 -0
- cls_name/cls_name_ko.yaml +9 -0
- cls_name/cls_name_ru.yaml +9 -0
- cls_name/cls_name_zh.yaml +7 -0
- model_config/model_name_p5_all.csv +5 -0
- model_config/model_name_p5_all.yaml +1 -0
- model_config/model_name_p5_n.csv +1 -0
- model_config/model_name_p5_n.yaml +1 -0
- model_config/model_name_p5_p6_all.yaml +1 -0
- model_config/model_name_p6_all.csv +5 -0
- model_config/model_name_p6_all.yaml +1 -0
- model_download/yolov5_model_p5_all.sh +8 -0
- model_download/yolov5_model_p5_n.sh +4 -0
- model_download/yolov5_model_p6_all.sh +8 -0
- util/fonts_opt.py +67 -0
- util/pdf_opt.py +78 -0
.gitignore
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 图片格式
|
2 |
+
*.jpg
|
3 |
+
*.jpeg
|
4 |
+
*.png
|
5 |
+
*.svg
|
6 |
+
*.gif
|
7 |
+
|
8 |
+
# 视频格式
|
9 |
+
*.mp4
|
10 |
+
*.avi
|
11 |
+
.ipynb_checkpoints
|
12 |
+
*/__pycache__
|
13 |
+
|
14 |
+
# 日志格式
|
15 |
+
*.log
|
16 |
+
*.data
|
17 |
+
*.txt
|
18 |
+
*.csv
|
19 |
+
|
20 |
+
# 参数文件
|
21 |
+
*.yaml
|
22 |
+
*.json
|
23 |
+
|
24 |
+
# 压缩文件格式
|
25 |
+
*.zip
|
26 |
+
*.tar
|
27 |
+
*.tar.gz
|
28 |
+
*.rar
|
29 |
+
|
30 |
+
# 字体格式
|
31 |
+
*.ttc
|
32 |
+
*.ttf
|
33 |
+
*.otf
|
34 |
+
|
35 |
+
*.pt
|
36 |
+
*.db
|
37 |
+
|
38 |
+
/flagged
|
39 |
+
/run
|
40 |
+
!requirements.txt
|
41 |
+
!cls_name/*
|
42 |
+
!model_config/*
|
43 |
+
!img_example/*
|
44 |
+
|
45 |
+
app copy.py
|
README.md
CHANGED
@@ -1,6 +1,6 @@
|
|
1 |
---
|
2 |
title: Gradio_YOLOv5_Det_v3
|
3 |
-
emoji:
|
4 |
colorFrom: purple
|
5 |
colorTo: yellow
|
6 |
sdk: gradio
|
@@ -11,3 +11,5 @@ license: gpl-3.0
|
|
11 |
---
|
12 |
|
13 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference
|
|
|
|
|
|
1 |
---
|
2 |
title: Gradio_YOLOv5_Det_v3
|
3 |
+
emoji: 🚀
|
4 |
colorFrom: purple
|
5 |
colorTo: yellow
|
6 |
sdk: gradio
|
|
|
11 |
---
|
12 |
|
13 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference
|
14 |
+
|
15 |
+
🚀 Project homepage:https://gitee.com/CV_Lab/gradio_yolov5_det
|
__init__.py
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
__author__ = "曾逸夫(Zeng Yifu)"
|
2 |
+
__email__ = "zyfiy1314@163.com"
|
app.py
ADDED
@@ -0,0 +1,385 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Gradio YOLOv5 Det v0.3
|
2 |
+
# author:Zeng Yifu(曾逸夫)
|
3 |
+
# creation time:2022-05-09
|
4 |
+
# email:zyfiy1314@163.com
|
5 |
+
# Project homepage:https://gitee.com/CV_Lab/gradio_yolov5_det
|
6 |
+
|
7 |
+
import os
|
8 |
+
|
9 |
+
os.system("pip install gradio==2.9.4")
|
10 |
+
|
11 |
+
import argparse
|
12 |
+
import csv
|
13 |
+
import json
|
14 |
+
import sys
|
15 |
+
from pathlib import Path
|
16 |
+
import pandas as pd
|
17 |
+
|
18 |
+
import gradio as gr
|
19 |
+
import torch
|
20 |
+
import yaml
|
21 |
+
from PIL import Image, ImageDraw, ImageFont
|
22 |
+
|
23 |
+
from util.fonts_opt import is_fonts
|
24 |
+
from util.pdf_opt import pdf_generate
|
25 |
+
|
26 |
+
ROOT_PATH = sys.path[0] # root directory
|
27 |
+
|
28 |
+
# model path
|
29 |
+
model_path = "ultralytics/yolov5"
|
30 |
+
|
31 |
+
# Gradio YOLOv5 Det version
|
32 |
+
GYD_VERSION = "Gradio YOLOv5 Det v0.3"
|
33 |
+
|
34 |
+
# model name temporary variable
|
35 |
+
model_name_tmp = ""
|
36 |
+
|
37 |
+
# Device temporary variables
|
38 |
+
device_tmp = ""
|
39 |
+
|
40 |
+
# File extension
|
41 |
+
suffix_list = [".csv", ".yaml"]
|
42 |
+
|
43 |
+
# font size
|
44 |
+
FONTSIZE = 25
|
45 |
+
|
46 |
+
|
47 |
+
def parse_args(known=False):
|
48 |
+
parser = argparse.ArgumentParser(description="Gradio YOLOv5 Det v0.3")
|
49 |
+
parser.add_argument("--source", "-src", default="upload", type=str, help="input source")
|
50 |
+
parser.add_argument("--img_tool", "-it", default="editor", type=str, help="input image tool")
|
51 |
+
parser.add_argument("--model_name", "-mn", default="yolov5s", type=str, help="model name")
|
52 |
+
parser.add_argument(
|
53 |
+
"--model_cfg",
|
54 |
+
"-mc",
|
55 |
+
default="./model_config/model_name_p5_p6_all.yaml",
|
56 |
+
type=str,
|
57 |
+
help="model config",
|
58 |
+
)
|
59 |
+
parser.add_argument(
|
60 |
+
"--cls_name",
|
61 |
+
"-cls",
|
62 |
+
default="./cls_name/cls_name_zh.yaml",
|
63 |
+
type=str,
|
64 |
+
help="cls name",
|
65 |
+
)
|
66 |
+
parser.add_argument(
|
67 |
+
"--nms_conf",
|
68 |
+
"-conf",
|
69 |
+
default=0.5,
|
70 |
+
type=float,
|
71 |
+
help="model NMS confidence threshold",
|
72 |
+
)
|
73 |
+
parser.add_argument("--nms_iou", "-iou", default=0.45, type=float, help="model NMS IoU threshold")
|
74 |
+
parser.add_argument(
|
75 |
+
"--device",
|
76 |
+
"-dev",
|
77 |
+
default="cuda:0",
|
78 |
+
type=str,
|
79 |
+
help="cuda or cpu",
|
80 |
+
)
|
81 |
+
parser.add_argument("--inference_size", "-isz", default=640, type=int, help="model inference size")
|
82 |
+
parser.add_argument("--max_detnum", "-mdn", default="50", type=str, help="model max det num")
|
83 |
+
|
84 |
+
args = parser.parse_known_args()[0] if known else parser.parse_args()
|
85 |
+
return args
|
86 |
+
|
87 |
+
|
88 |
+
# yaml file parsing
|
89 |
+
def yaml_parse(file_path):
|
90 |
+
return yaml.safe_load(open(file_path, encoding="utf-8").read())
|
91 |
+
|
92 |
+
|
93 |
+
# yaml csv file parsing
|
94 |
+
def yaml_csv(file_path, file_tag):
|
95 |
+
file_suffix = Path(file_path).suffix
|
96 |
+
if file_suffix == suffix_list[0]:
|
97 |
+
# model name
|
98 |
+
file_names = [i[0] for i in list(csv.reader(open(file_path)))] # csv version
|
99 |
+
elif file_suffix == suffix_list[1]:
|
100 |
+
# model name
|
101 |
+
file_names = yaml_parse(file_path).get(file_tag) # yaml version
|
102 |
+
else:
|
103 |
+
print(f"{file_path} is not in the correct format! Program exits!")
|
104 |
+
sys.exit()
|
105 |
+
|
106 |
+
return file_names
|
107 |
+
|
108 |
+
|
109 |
+
# model loading
|
110 |
+
def model_loading(model_name, device):
|
111 |
+
|
112 |
+
# load model
|
113 |
+
model = torch.hub.load(
|
114 |
+
model_path, model_name, force_reload=True, device=device, _verbose=False
|
115 |
+
)
|
116 |
+
|
117 |
+
return model
|
118 |
+
|
119 |
+
|
120 |
+
# check information
|
121 |
+
def export_json(results, model, img_size):
|
122 |
+
|
123 |
+
return [
|
124 |
+
[
|
125 |
+
{
|
126 |
+
"id": i,
|
127 |
+
"class": int(result[i][5]),
|
128 |
+
# "class_name": model.model.names[int(result[i][5])],
|
129 |
+
"class_name": model_cls_name_cp[int(result[i][5])],
|
130 |
+
"normalized_box": {
|
131 |
+
"x0": round(result[i][:4].tolist()[0], 6),
|
132 |
+
"y0": round(result[i][:4].tolist()[1], 6),
|
133 |
+
"x1": round(result[i][:4].tolist()[2], 6),
|
134 |
+
"y1": round(result[i][:4].tolist()[3], 6),},
|
135 |
+
"confidence": round(float(result[i][4]), 2),
|
136 |
+
"fps": round(1000 / float(results.t[1]), 2),
|
137 |
+
"width": img_size[0],
|
138 |
+
"height": img_size[1],} for i in range(len(result))] for result in results.xyxyn]
|
139 |
+
|
140 |
+
|
141 |
+
# frame conversion
|
142 |
+
def pil_draw(img, countdown_msg, textFont, xyxy, font_size, opt):
|
143 |
+
|
144 |
+
img_pil = ImageDraw.Draw(img)
|
145 |
+
|
146 |
+
img_pil.rectangle(xyxy, fill=None, outline="green") # bounding box
|
147 |
+
|
148 |
+
if "label" in opt:
|
149 |
+
text_w, text_h = textFont.getsize(countdown_msg) # Label size
|
150 |
+
img_pil.rectangle(
|
151 |
+
(xyxy[0], xyxy[1], xyxy[0] + text_w, xyxy[1] + text_h),
|
152 |
+
fill="green",
|
153 |
+
outline="green",
|
154 |
+
) # label background
|
155 |
+
img_pil.multiline_text(
|
156 |
+
(xyxy[0], xyxy[1]),
|
157 |
+
countdown_msg,
|
158 |
+
fill=(205, 250, 255),
|
159 |
+
font=textFont,
|
160 |
+
align="center",
|
161 |
+
)
|
162 |
+
|
163 |
+
return img
|
164 |
+
|
165 |
+
|
166 |
+
# YOLOv5 image detection function
|
167 |
+
def yolo_det(img, device, model_name, inference_size, conf, iou, max_num, model_cls, opt):
|
168 |
+
|
169 |
+
global model, model_name_tmp, device_tmp
|
170 |
+
|
171 |
+
if model_name_tmp != model_name:
|
172 |
+
# Model judgment to avoid repeated loading
|
173 |
+
model_name_tmp = model_name
|
174 |
+
model = model_loading(model_name_tmp, device)
|
175 |
+
elif device_tmp != device:
|
176 |
+
device_tmp = device
|
177 |
+
model = model_loading(model_name_tmp, device)
|
178 |
+
|
179 |
+
# -------------Model tuning -------------
|
180 |
+
model.conf = conf # NMS confidence threshold
|
181 |
+
model.iou = iou # NMS IoU threshold
|
182 |
+
model.max_det = int(max_num) # Maximum number of detection frames
|
183 |
+
model.classes = model_cls # model classes
|
184 |
+
|
185 |
+
results = model(img, size=inference_size) # detection
|
186 |
+
|
187 |
+
dataframe = results.pandas().xyxy[0].round(2)
|
188 |
+
|
189 |
+
img_size = img.size # frame size
|
190 |
+
|
191 |
+
# ----------------Load fonts----------------
|
192 |
+
yaml_index = cls_name.index(".yaml")
|
193 |
+
cls_name_lang = cls_name[yaml_index - 2:yaml_index]
|
194 |
+
|
195 |
+
if cls_name_lang == "en":
|
196 |
+
# Chinese
|
197 |
+
textFont = ImageFont.truetype(str(f"{ROOT_PATH}/fonts/SimSun.ttf"), size=FONTSIZE)
|
198 |
+
elif cls_name_lang in ["en", "ru", "es", "ar"]:
|
199 |
+
# English, Russian, Spanish, Arabic
|
200 |
+
textFont = ImageFont.truetype(str(f"{ROOT_PATH}/fonts/TimesNewRoman.ttf"), size=FONTSIZE)
|
201 |
+
elif cls_name_lang == "ko":
|
202 |
+
# Korean
|
203 |
+
textFont = ImageFont.truetype(str(f"{ROOT_PATH}/fonts/malgun.ttf"), size=FONTSIZE)
|
204 |
+
|
205 |
+
for result in results.xyxyn:
|
206 |
+
for i in range(len(result)):
|
207 |
+
id = int(i) # instance ID
|
208 |
+
obj_cls_index = int(result[i][5]) # category index
|
209 |
+
obj_cls = model_cls_name_cp[obj_cls_index] # category
|
210 |
+
|
211 |
+
# ------------ border coordinates ------------
|
212 |
+
x0 = float(result[i][:4].tolist()[0])
|
213 |
+
y0 = float(result[i][:4].tolist()[1])
|
214 |
+
x1 = float(result[i][:4].tolist()[2])
|
215 |
+
y1 = float(result[i][:4].tolist()[3])
|
216 |
+
|
217 |
+
# ------------ Actual coordinates of the border ------------
|
218 |
+
x0 = int(img_size[0] * x0)
|
219 |
+
y0 = int(img_size[1] * y0)
|
220 |
+
x1 = int(img_size[0] * x1)
|
221 |
+
y1 = int(img_size[1] * y1)
|
222 |
+
|
223 |
+
conf = float(result[i][4]) # confidence
|
224 |
+
# fps = f"{(1000 / float(results.t[1])):.2f}" # FPS
|
225 |
+
|
226 |
+
det_img = pil_draw(
|
227 |
+
img,
|
228 |
+
f"{id}-{obj_cls}:{conf:.2f}",
|
229 |
+
textFont,
|
230 |
+
[x0, y0, x1, y1],
|
231 |
+
FONTSIZE,
|
232 |
+
opt,
|
233 |
+
)
|
234 |
+
|
235 |
+
det_json = export_json(results, model, img.size)[0] # Detection information
|
236 |
+
|
237 |
+
# JSON formatting
|
238 |
+
det_json_format = json.dumps(det_json, sort_keys=False, indent=4, separators=(",", ":"), ensure_ascii=False)
|
239 |
+
|
240 |
+
# -------pdf-------
|
241 |
+
report = "./Det_Report.pdf"
|
242 |
+
if "pdf" in opt:
|
243 |
+
pdf_generate(f"{det_json_format}", report, GYD_VERSION)
|
244 |
+
else:
|
245 |
+
report = None
|
246 |
+
|
247 |
+
if "json" not in opt:
|
248 |
+
det_json = None
|
249 |
+
|
250 |
+
return det_img, det_json, report, dataframe
|
251 |
+
|
252 |
+
|
253 |
+
def main(args):
|
254 |
+
gr.close_all()
|
255 |
+
|
256 |
+
global model, model_cls_name_cp, cls_name
|
257 |
+
|
258 |
+
slider_step = 0.05 # sliding step
|
259 |
+
|
260 |
+
source = args.source
|
261 |
+
img_tool = args.img_tool
|
262 |
+
nms_conf = args.nms_conf
|
263 |
+
nms_iou = args.nms_iou
|
264 |
+
model_name = args.model_name
|
265 |
+
model_cfg = args.model_cfg
|
266 |
+
cls_name = args.cls_name
|
267 |
+
device = args.device
|
268 |
+
inference_size = args.inference_size
|
269 |
+
max_detnum = args.max_detnum
|
270 |
+
|
271 |
+
is_fonts(f"{ROOT_PATH}/fonts") # Check font files
|
272 |
+
|
273 |
+
# model loading
|
274 |
+
model = model_loading(model_name, device)
|
275 |
+
|
276 |
+
model_names = yaml_csv(model_cfg, "model_names") # model names
|
277 |
+
model_cls_name = yaml_csv(cls_name, "model_cls_name") # class name
|
278 |
+
|
279 |
+
model_cls_name_cp = model_cls_name.copy() # class name
|
280 |
+
|
281 |
+
# ------------------- Input Components -------------------
|
282 |
+
inputs_img = gr.inputs.Image(image_mode="RGB", source=source, tool=img_tool, type="pil", label="original image")
|
283 |
+
inputs_device = gr.inputs.Radio(choices=["cuda:0", "cpu"], default=device, label="device")
|
284 |
+
|
285 |
+
inputs_model = gr.inputs.Dropdown(choices=model_names, default=model_name, type="value", label="model")
|
286 |
+
inputs_size = gr.inputs.Radio(choices=[320, 640, 1280], default=inference_size, label="inference size")
|
287 |
+
input_conf = gr.inputs.Slider(0, 1, step=slider_step, default=nms_conf, label="confidence threshold")
|
288 |
+
inputs_iou = gr.inputs.Slider(0, 1, step=slider_step, default=nms_iou, label="IoU threshold")
|
289 |
+
inputs_maxnum = gr.inputs.Textbox(lines=1, placeholder="Maximum number of detections", default=max_detnum, label="Maximum number of detections")
|
290 |
+
inputs_clsName = gr.inputs.CheckboxGroup(choices=model_cls_name, default=model_cls_name, type="index", label="category")
|
291 |
+
inputs_opt = gr.inputs.CheckboxGroup(choices=["label", "pdf", "json"],
|
292 |
+
default=["label", "pdf"],
|
293 |
+
type="value",
|
294 |
+
label="action")
|
295 |
+
|
296 |
+
# Input parameters
|
297 |
+
inputs = [
|
298 |
+
inputs_img, # input image
|
299 |
+
inputs_device, # device
|
300 |
+
inputs_model, # model
|
301 |
+
inputs_size, # inference size
|
302 |
+
input_conf, # confidence threshold
|
303 |
+
inputs_iou, # IoU threshold
|
304 |
+
inputs_maxnum, # maximum number of detections
|
305 |
+
inputs_clsName, # category
|
306 |
+
inputs_opt, # detect operations
|
307 |
+
]
|
308 |
+
|
309 |
+
# Output parameters
|
310 |
+
outputs_img = gr.outputs.Image(type="pil", label="Detection image")
|
311 |
+
outputs_json = gr.outputs.JSON(label="Detection information")
|
312 |
+
outputs_pdf = gr.outputs.File(label="Download test report")
|
313 |
+
outputs_df = gr.outputs.Dataframe(max_rows=5, overflow_row_behaviour="paginate", type="pandas", label="List of detection information")
|
314 |
+
|
315 |
+
outputs = [outputs_img, outputs_json, outputs_pdf, outputs_df]
|
316 |
+
|
317 |
+
# title
|
318 |
+
title = "Gradio-based YOLOv5 general target detection system v0.3"
|
319 |
+
|
320 |
+
# describe
|
321 |
+
description = "<div align='center'>Customizable target detection model, easy to install, easy to use</div>"
|
322 |
+
|
323 |
+
# example image
|
324 |
+
examples = [
|
325 |
+
[
|
326 |
+
"./img_example/bus.jpg",
|
327 |
+
"cpu",
|
328 |
+
"yolov5s",
|
329 |
+
640,
|
330 |
+
0.6,
|
331 |
+
0.5,
|
332 |
+
10,
|
333 |
+
["person", "bus"],
|
334 |
+
["label", "pdf"],],
|
335 |
+
[
|
336 |
+
"./img_example/Millenial-at-work.jpg",
|
337 |
+
"cpu",
|
338 |
+
"yolov5l",
|
339 |
+
320,
|
340 |
+
0.5,
|
341 |
+
0.45,
|
342 |
+
12,
|
343 |
+
["person", "chair", "cup", "laptop"],
|
344 |
+
["label", "pdf"],],
|
345 |
+
[
|
346 |
+
"./img_example/zidane.jpg",
|
347 |
+
"cpu",
|
348 |
+
"yolov5m",
|
349 |
+
640,
|
350 |
+
0.25,
|
351 |
+
0.5,
|
352 |
+
15,
|
353 |
+
["person", "tie"],
|
354 |
+
["pdf", "json"],],
|
355 |
+
[
|
356 |
+
"./img_example/MichaelMiley.jpg",
|
357 |
+
"cpu",
|
358 |
+
"yolov5s6",
|
359 |
+
1280,
|
360 |
+
0.5,
|
361 |
+
0.5,
|
362 |
+
20,
|
363 |
+
["people", "kites"],
|
364 |
+
["label", "pdf"],],]
|
365 |
+
|
366 |
+
# interface
|
367 |
+
gr.Interface(
|
368 |
+
fn=yolo_det,
|
369 |
+
inputs=inputs,
|
370 |
+
outputs=outputs,
|
371 |
+
title=title,
|
372 |
+
description=description,
|
373 |
+
article="",
|
374 |
+
examples=examples,
|
375 |
+
theme="seafoam",
|
376 |
+
flagging_dir="run", # output directory
|
377 |
+
).launch(
|
378 |
+
inbrowser=True, # Automatically open default browser
|
379 |
+
show_tips=True, # Automatically display the latest features of gradio
|
380 |
+
)
|
381 |
+
|
382 |
+
|
383 |
+
if __name__ == "__main__":
|
384 |
+
args = parse_args()
|
385 |
+
main(args)
|
cls_name/cls_name.csv
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
人
|
2 |
+
自行车
|
3 |
+
汽车
|
4 |
+
摩托车
|
5 |
+
飞机
|
6 |
+
公交车
|
7 |
+
火车
|
8 |
+
卡车
|
9 |
+
船
|
10 |
+
红绿灯
|
11 |
+
消防栓
|
12 |
+
停止标志
|
13 |
+
停车收费表
|
14 |
+
长凳
|
15 |
+
鸟
|
16 |
+
猫
|
17 |
+
狗
|
18 |
+
马
|
19 |
+
羊
|
20 |
+
牛
|
21 |
+
象
|
22 |
+
熊
|
23 |
+
斑马
|
24 |
+
长颈鹿
|
25 |
+
背包
|
26 |
+
雨伞
|
27 |
+
手提包
|
28 |
+
领带
|
29 |
+
手提箱
|
30 |
+
飞盘
|
31 |
+
滑雪板
|
32 |
+
单板滑雪
|
33 |
+
运动球
|
34 |
+
风筝
|
35 |
+
棒球棒
|
36 |
+
棒球手套
|
37 |
+
滑板
|
38 |
+
冲浪板
|
39 |
+
网球拍
|
40 |
+
瓶子
|
41 |
+
红酒杯
|
42 |
+
杯子
|
43 |
+
叉子
|
44 |
+
刀
|
45 |
+
勺
|
46 |
+
碗
|
47 |
+
香蕉
|
48 |
+
苹果
|
49 |
+
三明治
|
50 |
+
橙子
|
51 |
+
西兰花
|
52 |
+
胡萝卜
|
53 |
+
热狗
|
54 |
+
比萨
|
55 |
+
甜甜圈
|
56 |
+
蛋糕
|
57 |
+
椅子
|
58 |
+
长椅
|
59 |
+
盆栽
|
60 |
+
床
|
61 |
+
餐桌
|
62 |
+
马桶
|
63 |
+
电视
|
64 |
+
笔记本电脑
|
65 |
+
鼠标
|
66 |
+
遥控器
|
67 |
+
键盘
|
68 |
+
手机
|
69 |
+
微波炉
|
70 |
+
烤箱
|
71 |
+
烤面包机
|
72 |
+
洗碗槽
|
73 |
+
冰箱
|
74 |
+
书
|
75 |
+
时钟
|
76 |
+
花瓶
|
77 |
+
剪刀
|
78 |
+
泰迪熊
|
79 |
+
吹风机
|
80 |
+
牙刷
|
cls_name/cls_name.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
model_cls_name: ['人', '自行车', '汽车', '摩托车', '飞机', '公交车', '火车', '卡车', '船', '红绿灯', '消防栓', '停止标志',
|
2 |
+
'停车收费表', '长凳', '鸟', '猫', '狗', '马', '羊', '牛', '象', '熊', '斑马', '长颈鹿', '背包', '雨伞', '手提包', '领带',
|
3 |
+
'手提箱', '飞盘', '滑雪板', '单板滑雪', '运动球', '风筝', '棒球棒', '棒球手套', '滑板', '冲浪板', '网球拍', '瓶子', '红酒杯',
|
4 |
+
'杯子', '叉子', '刀', '勺', '碗', '香蕉', '苹果', '三明治', '橙子', '西兰花', '胡萝卜', '热狗', '比萨', '甜甜圈', '蛋糕',
|
5 |
+
'椅子', '长椅', '盆栽', '床', '餐桌', '马桶', '电视', '笔记本电脑', '鼠标', '遥控器', '键盘', '手机', '微波炉', '烤箱',
|
6 |
+
'烤面包机', '洗碗槽', '冰箱', '书', '时钟', '花瓶', '剪刀', '泰迪熊', '吹风机', '牙刷'
|
7 |
+
]
|
cls_name/cls_name_ar.yaml
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
model_cls_name: [" الناس " , " الدراجات " , " السيارات " , " الدراجات النارية " , " الطائرات " , " الحافلات " , " القطارات " , " الشاحنات " , " السفن " , " إشارات المرور " ,
|
2 |
+
" صنبور " , " علامة " , " موقف سيارات " , " الجدول " , " مقعد " , " الطيور " , " القط " , " الكلب " , " الحصان " , " الأغنام " , " الثور " , " الفيل " ,
|
3 |
+
" الدب " , " حمار وحشي " , " الزرافة " , " حقيبة " , " مظلة " , " حقيبة يد " , " ربطة عنق " , " حقيبة " , " الفريسبي " , " الزلاجات " , " الزلاجات " ,
|
4 |
+
" الكرة الرياضية " , " طائرة ورقية " , " مضرب بيسبول " , " قفازات البيسبول " , " لوح التزلج " , " ركوب الأمواج " , " مضرب تنس " , " زجاجة " ,
|
5 |
+
" كأس " , " كأس " , " شوكة " , " سكين " , " ملعقة " , " وعاء " , " الموز " , " التفاح " , " ساندويتش " , " البرتقال " , " القرنبيط " ,
|
6 |
+
" الجزر " , " الكلاب الساخنة " , " البيتزا " , " دونات " , " كعكة " , " كرسي " , " أريكة " , " بوعاء " , " السرير " , " طاولة الطعام " , " المرحاض " ,
|
7 |
+
التلفزيون , الكمبيوتر المحمول , الفأرة , وحدة تحكم عن بعد , لوحة المفاتيح , الهاتف المحمول , فرن الميكروويف , محمصة خبز كهربائية , بالوعة , ثلاجة ,
|
8 |
+
" كتاب " , " ساعة " , " زهرية " , " مقص " , " دمية دب " , " مجفف الشعر " , " فرشاة الأسنان "
|
9 |
+
]
|
cls_name/cls_name_en.yaml
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
model_cls_name: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
|
2 |
+
'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant',
|
3 |
+
'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard',
|
4 |
+
'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', 'bottle',
|
5 |
+
'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli',
|
6 |
+
'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'dining table', 'toilet',
|
7 |
+
'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator',
|
8 |
+
'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush'
|
9 |
+
]
|
cls_name/cls_name_es.yaml
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
model_cls_name: ['persona', 'bicicleta', 'coche', 'motocicleta', 'avión', 'autobús', 'tren', 'camión', 'barco', 'semáforo',
|
2 |
+
'boca de incendios', 'señal de alto', 'parquímetro', 'banco', 'pájaro', 'gato', 'perro', 'caballo', 'oveja', 'vaca', 'elefante',
|
3 |
+
'oso', 'cebra', 'jirafa', 'mochila', 'paraguas', 'bolso', 'corbata', 'maleta', 'frisbee', 'esquís', 'snowboard',
|
4 |
+
'pelota deportiva', 'cometa', 'bate de béisbol', 'guante de béisbol', 'monopatín', 'tabla de surf', 'raqueta de tenis', 'botella',
|
5 |
+
'copa de vino', 'taza', 'tenedor', 'cuchillo', 'cuchara', 'tazón', 'plátano', 'manzana', 'sándwich', 'naranja', 'brócoli',
|
6 |
+
'zanahoria', 'perrito caliente', 'pizza', 'rosquilla', 'pastel', 'silla', 'sofá', 'planta en maceta', 'cama', 'mesa de comedor', 'inodoro',
|
7 |
+
'tv', 'laptop', 'ratón', 'control remoto', 'teclado', 'celular', 'microondas', 'horno', 'tostadora', 'fregadero', 'nevera',
|
8 |
+
'libro', 'reloj', 'jarrón', 'tijeras', 'oso de peluche', 'secador de pelo', 'cepillo de dientes'
|
9 |
+
]
|
cls_name/cls_name_ko.yaml
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
model_cls_name: ['사람', '자전거', '자동차', '오토바이', '비행기', '버스', '기차', '트럭', '보트', '신호등',
|
2 |
+
'소화전', '정지 신호', '주차 미터기', '벤치', '새', '고양이', '개', '말', '양', '소', '코끼리',
|
3 |
+
'곰', '얼룩말', '기린', '배낭', '우산', '핸드백', '타이', '여행가방', '프리스비', '스키', '스노우보드',
|
4 |
+
'스포츠 공', '연', '야구 방망이', '야구 글러브', '스케이트보드', '서프보드', '테니스 라켓', '병',
|
5 |
+
'와인잔', '컵', '포크', '나이프', '숟가락', '그릇', '바나나', '사과', '샌드위치', '오렌지', '브로콜리',
|
6 |
+
'당근', '핫도그', '피자', '도넛', '케이크', '의자', '소파', '화분', '침대', '식탁', '화장실',
|
7 |
+
'tv', '노트북', '마우스', '리모컨', '키보드', '휴대전화', '전자레인지', '오븐', '토스터', '싱크대', '냉장고',
|
8 |
+
'책', '시계', '꽃병', '가위', '테디베어', '드라이기', '칫솔'
|
9 |
+
]
|
cls_name/cls_name_ru.yaml
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
model_cls_name: ['человек', 'велосипед', 'автомобиль', 'мотоцикл', 'самолет', 'автобус', 'поезд', 'грузовик', 'лодка', 'светофор',
|
2 |
+
'пожарный гидрант', 'стоп', 'паркомат', 'скамейка', 'птица', 'кошка', 'собака', 'лошадь', 'овца', 'корова', 'слон',
|
3 |
+
'медведь', 'зебра', 'жираф', 'рюкзак', 'зонт', 'сумочка', 'галстук', 'чемодан', 'фрисби', 'лыжи', 'сноуборд',
|
4 |
+
'спортивный мяч', 'воздушный змей', 'бейсбольная бита', 'бейсбольная перчатка', 'скейтборд', 'доска для серфинга', 'теннисная ракетка', 'бутылка',
|
5 |
+
'бокал', 'чашка', 'вилка', 'нож', 'ложка', 'миска', 'банан', 'яблоко', 'бутерброд', 'апельсин', 'брокколи',
|
6 |
+
'морковь', 'хот-дог', 'пицца', 'пончик', 'торт', 'стул', 'диван', 'растение в горшке', 'кровать', 'обеденный стол', 'туалет',
|
7 |
+
'телевизор', 'ноутбук', 'мышь', 'пульт', 'клавиатура', 'мобильный телефон', 'микроволновая печь', 'духовка', 'тостер', 'раковина', 'холодильник',
|
8 |
+
'книга', 'часы', 'ваза', 'ножницы', 'плюшевый мишка', 'фен', 'зубная щетка'
|
9 |
+
]
|
cls_name/cls_name_zh.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
model_cls_name: ['人', '自行车', '汽车', '摩托车', '飞机', '公交车', '火车', '卡车', '船', '红绿灯', '消防栓', '停止标志',
|
2 |
+
'停车收费表', '长凳', '鸟', '猫', '狗', '马', '羊', '牛', '象', '熊', '斑马', '长颈鹿', '背包', '雨伞', '手提包', '领带',
|
3 |
+
'手提箱', '飞盘', '滑雪板', '单板滑雪', '运动球', '风筝', '棒球棒', '棒球手套', '滑板', '冲浪板', '网球拍', '瓶子', '红酒杯',
|
4 |
+
'杯子', '叉子', '刀', '勺', '碗', '香蕉', '苹果', '三明治', '橙子', '西兰花', '胡萝卜', '热狗', '比萨', '甜甜圈', '蛋糕',
|
5 |
+
'椅子', '长椅', '盆栽', '床', '餐桌', '马桶', '电视', '笔记本电脑', '鼠标', '遥控器', '键盘', '手机', '微波炉', '烤箱',
|
6 |
+
'烤面包机', '洗碗槽', '冰箱', '书', '时钟', '花瓶', '剪刀', '泰迪熊', '吹风机', '牙刷'
|
7 |
+
]
|
model_config/model_name_p5_all.csv
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
yolov5n
|
2 |
+
yolov5s
|
3 |
+
yolov5m
|
4 |
+
yolov5l
|
5 |
+
yolov5x
|
model_config/model_name_p5_all.yaml
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
model_names: ["yolov5n", "yolov5s", "yolov5m", "yolov5l", "yolov5x"]
|
model_config/model_name_p5_n.csv
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
yolov5n
|
model_config/model_name_p5_n.yaml
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
model_names: ["yolov5n"]
|
model_config/model_name_p5_p6_all.yaml
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
model_names: ["yolov5n", "yolov5s", "yolov5m", "yolov5l", "yolov5x", "yolov5n6", "yolov5s6", "yolov5m6", "yolov5l6", "yolov5x6"]
|
model_config/model_name_p6_all.csv
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
yolov5n6
|
2 |
+
yolov5s6
|
3 |
+
yolov5m6
|
4 |
+
yolov5l6
|
5 |
+
yolov5x6
|
model_config/model_name_p6_all.yaml
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
model_names: ["yolov5n6", "yolov5s6", "yolov5m6", "yolov5l6", "yolov5x6"]
|
model_download/yolov5_model_p5_all.sh
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
cd ./yolov5
|
2 |
+
|
3 |
+
# 下载YOLOv5模型
|
4 |
+
wget -c -t 0 https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5n.pt
|
5 |
+
wget -c -t 0 https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5s.pt
|
6 |
+
wget -c -t 0 https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5m.pt
|
7 |
+
wget -c -t 0 https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5l.pt
|
8 |
+
wget -c -t 0 https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5x.pt
|
model_download/yolov5_model_p5_n.sh
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
cd ./yolov5
|
2 |
+
|
3 |
+
# 下载YOLOv5模型
|
4 |
+
wget -c -t 0 https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5n.pt
|
model_download/yolov5_model_p6_all.sh
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
cd ./yolov5
|
2 |
+
|
3 |
+
# 下载YOLOv5模型
|
4 |
+
wget -c -t 0 https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5n6.pt
|
5 |
+
wget -c -t 0 https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5s6.pt
|
6 |
+
wget -c -t 0 https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5m6.pt
|
7 |
+
wget -c -t 0 https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5l6.pt
|
8 |
+
wget -c -t 0 https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5x6.pt
|
util/fonts_opt.py
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 字体管理
|
2 |
+
# 创建人:曾逸夫
|
3 |
+
# 创建时间:2022-05-01
|
4 |
+
|
5 |
+
import os
|
6 |
+
import sys
|
7 |
+
from pathlib import Path
|
8 |
+
|
9 |
+
import wget
|
10 |
+
from rich.console import Console
|
11 |
+
|
12 |
+
ROOT_PATH = sys.path[0] # 项目根目录
|
13 |
+
|
14 |
+
# 中文、英文、俄语、西班牙语、阿拉伯语、韩语
|
15 |
+
fonts_list = ["SimSun.ttf", "TimesNewRoman.ttf", "malgun.ttf"] # 字体列表
|
16 |
+
fonts_suffix = ["ttc", "ttf", "otf"] # 字体后缀
|
17 |
+
|
18 |
+
data_url_dict = {
|
19 |
+
"SimSun.ttf": "https://gitee.com/CV_Lab/gradio_yolov5_det/attach_files/1053539/download/SimSun.ttf",
|
20 |
+
"TimesNewRoman.ttf": "https://gitee.com/CV_Lab/gradio_yolov5_det/attach_files/1053537/download/TimesNewRoman.ttf",
|
21 |
+
"malgun.ttf": "https://gitee.com/CV_Lab/gradio_yolov5_det/attach_files/1053538/download/malgun.ttf",}
|
22 |
+
|
23 |
+
console = Console()
|
24 |
+
|
25 |
+
|
26 |
+
# 创建字体库
|
27 |
+
def add_fronts(font_diff):
|
28 |
+
|
29 |
+
global font_name
|
30 |
+
|
31 |
+
for k, v in data_url_dict.items():
|
32 |
+
if k in font_diff:
|
33 |
+
font_name = v.split("/")[-1] # 字体名称
|
34 |
+
Path(f"{ROOT_PATH}/fonts").mkdir(parents=True, exist_ok=True) # 创建目录
|
35 |
+
|
36 |
+
file_path = f"{ROOT_PATH}/fonts/{font_name}" # 字体路径
|
37 |
+
|
38 |
+
try:
|
39 |
+
# 下载字体文件
|
40 |
+
wget.download(v, file_path)
|
41 |
+
except Exception as e:
|
42 |
+
print("路径错误!程序结束!")
|
43 |
+
print(e)
|
44 |
+
sys.exit()
|
45 |
+
else:
|
46 |
+
print()
|
47 |
+
console.print(f"{font_name} [bold green]字体文件下载完成![/bold green] 已保存至:{file_path}")
|
48 |
+
|
49 |
+
|
50 |
+
# 判断字体文件
|
51 |
+
def is_fonts(fonts_dir):
|
52 |
+
if os.path.isdir(fonts_dir):
|
53 |
+
# 如果字体库存在
|
54 |
+
f_list = os.listdir(fonts_dir) # 本地字体库
|
55 |
+
|
56 |
+
font_diff = list(set(fonts_list).difference(set(f_list)))
|
57 |
+
|
58 |
+
if font_diff != []:
|
59 |
+
# 字体不存在
|
60 |
+
console.print("[bold red]字体不存在,正在加载。。。[/bold red]")
|
61 |
+
add_fronts(font_diff) # 创建字体库
|
62 |
+
else:
|
63 |
+
console.print(f"{fonts_list}[bold green]字体已存在![/bold green]")
|
64 |
+
else:
|
65 |
+
# 字体库不存在,创建字体库
|
66 |
+
console.print("[bold red]字体库不存在,正在创建。。。[/bold red]")
|
67 |
+
add_fronts(fonts_list) # 创建字体库
|
util/pdf_opt.py
ADDED
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# PDF管理
|
2 |
+
# 创建人:曾逸夫
|
3 |
+
# 创建时间:2022-05-05
|
4 |
+
|
5 |
+
from fpdf import FPDF
|
6 |
+
|
7 |
+
|
8 |
+
# PDF生成类
|
9 |
+
class PDF(FPDF):
|
10 |
+
# 参考:https://pyfpdf.readthedocs.io/en/latest/Tutorial/index.html
|
11 |
+
def header(self):
|
12 |
+
# 设置中文字体
|
13 |
+
self.add_font("SimSun", "", "./fonts/SimSun.ttf", uni=True)
|
14 |
+
self.set_font("SimSun", "", 16)
|
15 |
+
# Calculate width of title and position
|
16 |
+
w = self.get_string_width(title) + 6
|
17 |
+
self.set_x((210 - w) / 2)
|
18 |
+
# Colors of frame, background and text
|
19 |
+
self.set_draw_color(255, 255, 255)
|
20 |
+
self.set_fill_color(255, 255, 255)
|
21 |
+
self.set_text_color(0, 0, 0)
|
22 |
+
# Thickness of frame (1 mm)
|
23 |
+
# self.set_line_width(1)
|
24 |
+
# Title
|
25 |
+
self.cell(w, 9, title, 1, 1, "C", 1)
|
26 |
+
# Line break
|
27 |
+
self.ln(10)
|
28 |
+
|
29 |
+
def footer(self):
|
30 |
+
# Position at 1.5 cm from bottom
|
31 |
+
self.set_y(-15)
|
32 |
+
# 设置中文字体
|
33 |
+
self.add_font("SimSun", "", "./fonts/SimSun.ttf", uni=True)
|
34 |
+
self.set_font("SimSun", "", 12)
|
35 |
+
# Text color in gray
|
36 |
+
self.set_text_color(128)
|
37 |
+
# Page number
|
38 |
+
self.cell(0, 10, "Page " + str(self.page_no()), 0, 0, "C")
|
39 |
+
|
40 |
+
def chapter_title(self, num, label):
|
41 |
+
# 设置中文字体
|
42 |
+
self.add_font("SimSun", "", "./fonts/SimSun.ttf", uni=True)
|
43 |
+
self.set_font("SimSun", "", 12)
|
44 |
+
# Background color
|
45 |
+
self.set_fill_color(200, 220, 255)
|
46 |
+
# Title
|
47 |
+
# self.cell(0, 6, 'Chapter %d : %s' % (num, label), 0, 1, 'L', 1)
|
48 |
+
self.cell(0, 6, "检测结果:", 0, 1, "L", 1)
|
49 |
+
# Line break
|
50 |
+
self.ln(4)
|
51 |
+
|
52 |
+
def chapter_body(self, name):
|
53 |
+
|
54 |
+
# 设置中文字体
|
55 |
+
self.add_font("SimSun", "", "./fonts/SimSun.ttf", uni=True)
|
56 |
+
self.set_font("SimSun", "", 12)
|
57 |
+
# Output justified text
|
58 |
+
self.multi_cell(0, 5, name)
|
59 |
+
# Line break
|
60 |
+
self.ln()
|
61 |
+
self.cell(0, 5, "--------------------------------------")
|
62 |
+
|
63 |
+
def print_chapter(self, num, title, name):
|
64 |
+
self.add_page()
|
65 |
+
self.chapter_title(num, title)
|
66 |
+
self.chapter_body(name)
|
67 |
+
|
68 |
+
|
69 |
+
# pdf生成函数
|
70 |
+
def pdf_generate(input_file, output_file, title_):
|
71 |
+
global title
|
72 |
+
|
73 |
+
title = title_
|
74 |
+
pdf = PDF()
|
75 |
+
pdf.set_title(title)
|
76 |
+
pdf.set_author("Zeng Yifu")
|
77 |
+
pdf.print_chapter(1, "A RUNAWAY REEF", input_file)
|
78 |
+
pdf.output(output_file)
|