Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import tempfile
|
| 3 |
+
import fitz # PyMuPDF
|
| 4 |
+
import gradio as gr
|
| 5 |
+
from ultralytics import YOLO
|
| 6 |
+
from PIL import Image
|
| 7 |
+
|
| 8 |
+
# 预加载两个模型
|
| 9 |
+
model_doc = YOLO("moldet_yolo11l_960_doc.pt") # PDF 专用
|
| 10 |
+
model_img = YOLO("moldet_yolo11l_640_general.pt") # 图片通用
|
| 11 |
+
|
| 12 |
+
def process_file(file):
|
| 13 |
+
# 创建临时目录
|
| 14 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 15 |
+
input_path = os.path.join(tmpdir, "input.png")
|
| 16 |
+
|
| 17 |
+
# 判断文件类型
|
| 18 |
+
if file.name.lower().endswith(".pdf"):
|
| 19 |
+
# PDF -> 转第一页为图片
|
| 20 |
+
pdf = fitz.open(file.name)
|
| 21 |
+
page = pdf[0]
|
| 22 |
+
pix = page.get_pixmap(dpi=300) # 高分辨率渲染
|
| 23 |
+
pix.save(input_path)
|
| 24 |
+
|
| 25 |
+
# 运行 PDF 模型
|
| 26 |
+
results = model_doc.predict(input_path, save=True, imgsz=960, conf=0.5)
|
| 27 |
+
|
| 28 |
+
else:
|
| 29 |
+
# 图片直接保存
|
| 30 |
+
Image.open(file.name).save(input_path)
|
| 31 |
+
|
| 32 |
+
# 运行图片模型
|
| 33 |
+
results = model_img.predict(input_path, save=True, imgsz=640, conf=0.5)
|
| 34 |
+
|
| 35 |
+
# YOLO 会保存预测结果到 runs/predict/xxx 目录
|
| 36 |
+
save_dir = results[0].save_dir
|
| 37 |
+
pred_path = os.path.join(save_dir, os.path.basename(input_path))
|
| 38 |
+
|
| 39 |
+
return pred_path
|
| 40 |
+
|
| 41 |
+
# Gradio UI
|
| 42 |
+
demo = gr.Interface(
|
| 43 |
+
fn=process_file,
|
| 44 |
+
inputs=gr.File(label="上传图片或 PDF(单页)", file_types=[".png", ".jpg", ".jpeg", ".pdf"]),
|
| 45 |
+
outputs=gr.Image(type="filepath", label="检测结果"),
|
| 46 |
+
title="PDF / 图片目标检测",
|
| 47 |
+
description=(
|
| 48 |
+
"上传一张图片或单页 PDF,系统会自动选择对应的 YOLO 模型进行检测并输出结果。\n"
|
| 49 |
+
"PDF 使用 moldet_yolo11l_960_doc.pt,图片使用 moldet_yolo11l_640_general.pt"
|
| 50 |
+
)
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
if __name__ == "__main__":
|
| 54 |
+
demo.launch()
|