Hakureirm commited on
Commit
e45be51
·
1 Parent(s): 6fce26b

美化UI界面:添加新布局和样式

Browse files
Files changed (2) hide show
  1. app.py +36 -5
  2. requirements.txt +4 -0
app.py CHANGED
@@ -1,16 +1,19 @@
1
  import gradio as gr
2
  from ultralytics import YOLO
 
 
 
 
3
 
4
- # 加载模型
 
5
  model = YOLO('NailongKiller.yolo11n.pt')
6
 
7
  def predict(img):
8
- # 运行推理
9
  results = model.predict(img)
10
- # 返回第一个结果的绘制图像
11
  return results[0].plot()
12
 
13
- # 创建 Gradio 演示
14
  demo = gr.Interface(
15
  predict,
16
  inputs=[
@@ -27,6 +30,34 @@ demo = gr.Interface(
27
  cache_examples=True
28
  )
29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  # 启动应用
31
  if __name__ == "__main__":
32
- demo.launch()
 
 
1
  import gradio as gr
2
  from ultralytics import YOLO
3
+ from fastapi import FastAPI, File, UploadFile
4
+ from PIL import Image
5
+ import numpy as np
6
+ import io
7
 
8
+ # 初始化 FastAPI 和模型
9
+ app = FastAPI()
10
  model = YOLO('NailongKiller.yolo11n.pt')
11
 
12
  def predict(img):
 
13
  results = model.predict(img)
 
14
  return results[0].plot()
15
 
16
+ # Gradio 界面
17
  demo = gr.Interface(
18
  predict,
19
  inputs=[
 
30
  cache_examples=True
31
  )
32
 
33
+ # API 端点
34
+ @app.post("/detect/")
35
+ async def detect_api(file: UploadFile = File(...)):
36
+ # 读取上传的图片
37
+ contents = await file.read()
38
+ image = Image.open(io.BytesIO(contents))
39
+ image_np = np.array(image)
40
+
41
+ # 运行推理
42
+ results = model.predict(image_np)
43
+ result = results[0]
44
+
45
+ # 返回检测结果
46
+ detections = []
47
+ for box in result.boxes:
48
+ detection = {
49
+ "bbox": box.xyxy[0].tolist(),
50
+ "confidence": float(box.conf[0]),
51
+ "class": int(box.cls[0])
52
+ }
53
+ detections.append(detection)
54
+
55
+ return {"detections": detections}
56
+
57
+ # 挂载 Gradio 到 FastAPI
58
+ app = gr.mount_gradio_app(app, demo, path="/")
59
+
60
  # 启动应用
61
  if __name__ == "__main__":
62
+ import uvicorn
63
+ uvicorn.run(app, host="0.0.0.0", port=7860)
requirements.txt CHANGED
@@ -3,3 +3,7 @@ torch>=1.8.0
3
  torchvision>=0.9.0
4
  ultralytics>=8.3.0
5
  Pillow
 
 
 
 
 
3
  torchvision>=0.9.0
4
  ultralytics>=8.3.0
5
  Pillow
6
+ fastapi
7
+ python-multipart
8
+ uvicorn
9
+ numpy