实时手机检测-通用企业级监控:Prometheus+Grafana指标采集实践
实时手机检测-通用企业级监控:Prometheus+Grafana指标采集实践
1. 项目概述与核心价值
实时手机检测-通用模型是一个基于DAMOYOLO框架的高性能目标检测解决方案,专门用于在各种场景中快速准确地识别手机设备。这个模型不仅具备出色的检测精度,还保持了极高的推理速度,使其成为企业级监控系统的理想选择。
在实际应用中,单纯的模型推理往往不足以满足生产环境的需求。企业需要实时监控模型的运行状态、性能指标和业务数据,以便及时发现问题、优化系统并做出数据驱动的决策。这就是Prometheus和Grafana的价值所在——它们为企业提供了完整的监控可视化解决方案。
通过将实时手机检测模型与Prometheus+Grafana集成,您可以获得:
- 实时性能监控:跟踪模型推理速度、准确率等关键指标
- 资源使用情况:监控CPU、内存、GPU等硬件资源消耗
- 业务数据统计:分析检测到的手机数量、分布等业务指标
- 预警通知:设置阈值告警,及时发现系统异常
2. 环境准备与组件部署
2.1 系统要求与依赖安装
在开始部署之前,确保您的系统满足以下基本要求:
- Ubuntu 18.04+ 或 CentOS 7+ 操作系统
- Python 3.7+ 环境
- 至少4GB可用内存
- 网络连接用于下载依赖包
安装必要的Python依赖:
# 安装模型运行所需依赖
pip install modelscope gradio opencv-python pillow torch torchvision
# 安装监控组件所需依赖
pip install prometheus-client grafana-api requests
# 安装系统监控工具
sudo apt-get install htop iotop nvidia-smi # Ubuntu/Debian
# 或
sudo yum install htop iotop nvidia-smi # CentOS/RHEL
2.2 Prometheus部署与配置
Prometheus是一个开源的系统监控和警报工具包,专门用于收集和存储时间序列数据。
首先下载并安装Prometheus:
# 下载最新版本的Prometheus
wget https://github.com/prometheus/prometheus/releases/download/v2.37.0/prometheus-2.37.0.linux-amd64.tar.gz
# 解压文件
tar xvfz prometheus-2.37.0.linux-amd64.tar.gz
# 移动到合适的位置
cd prometheus-2.37.0.linux-amd64
sudo mv prometheus promtool /usr/local/bin/
sudo mv prometheus.yml /etc/prometheus/
创建Prometheus的systemd服务文件:
sudo nano /etc/systemd/system/prometheus.service
添加以下内容:
[Unit]
Description=Prometheus
Documentation=https://prometheus.io/docs/introduction/overview/
Wants=network-online.target
After=network-online.target
[Service]
User=prometheus
Group=prometheus
Type=simple
ExecStart=/usr/local/bin/prometheus \
--config.file=/etc/prometheus/prometheus.yml \
--storage.tsdb.path=/var/lib/prometheus/ \
--web.console.templates=/etc/prometheus/consoles \
--web.console.libraries=/etc/prometheus/console_libraries \
--web.listen-address=0.0.0.0:9090
Restart=always
[Install]
WantedBy=multi-user.target
2.3 Grafana部署与配置
Grafana是一个开源的数据可视化平台,用于展示Prometheus收集的监控数据。
安装Grafana:
# Ubuntu/Debian
sudo apt-get install -y adduser libfontconfig1
wget https://dl.grafana.com/oss/release/grafana_9.0.1_amd64.deb
sudo dpkg -i grafana_9.0.1_amd64.deb
# CentOS/RHEL
wget https://dl.grafana.com/oss/release/grafana-9.0.1-1.x86_64.rpm
sudo yum install grafana-9.0.1-1.x86_64.rpm
启动Grafana服务:
sudo systemctl daemon-reload
sudo systemctl start grafana-server
sudo systemctl enable grafana-server
3. 监控指标采集实践
3.1 模型性能指标采集
为了监控实时手机检测模型的性能,我们需要在模型推理代码中添加指标采集功能。创建一个名为monitoring.py的文件:
from prometheus_client import start_http_server, Summary, Counter, Gauge, Histogram
import time
import psutil
import GPUtil
# 创建监控指标
MODEL_INFERENCE_TIME = Summary('model_inference_seconds', 'Time spent processing inference')
MODEL_INFERENCE_COUNT = Counter('model_inference_total', 'Total number of inferences')
MODEL_DETECTION_COUNT = Counter('model_detection_total', 'Total number of phones detected')
MODEL_CONFIDENCE = Histogram('model_confidence', 'Confidence of detections')
CPU_USAGE = Gauge('cpu_usage_percent', 'Current CPU usage percentage')
MEMORY_USAGE = Gauge('memory_usage_percent', 'Current memory usage percentage')
GPU_USAGE = Gauge('gpu_usage_percent', 'Current GPU usage percentage')
def start_monitoring_server(port=8000):
"""启动监控指标服务器"""
start_http_server(port)
print(f"Monitoring server started on port {port}")
def collect_system_metrics():
"""收集系统资源指标"""
# CPU使用率
CPU_USAGE.set(psutil.cpu_percent())
# 内存使用率
memory = psutil.virtual_memory()
MEMORY_USAGE.set(memory.percent)
# GPU使用率(如果可用)
try:
gpus = GPUtil.getGPUs()
if gpus:
GPU_USAGE.set(gpus[0].load * 100)
except Exception:
pass # 忽略GPU监控错误
def monitor_inference(func):
"""模型推理监控装饰器"""
def wrapper(*args, **kwargs):
start_time = time.time()
# 收集系统指标
collect_system_metrics()
# 执行推理
result = func(*args, **kwargs)
# 记录推理时间
inference_time = time.time() - start_time
MODEL_INFERENCE_TIME.observe(inference_time)
MODEL_INFERENCE_COUNT.inc()
# 记录检测结果
if result and 'detections' in result:
detection_count = len(result['detections'])
MODEL_DETECTION_COUNT.inc(detection_count)
# 记录置信度分布
for detection in result['detections']:
if 'confidence' in detection:
MODEL_CONFIDENCE.observe(detection['confidence'])
return result
return wrapper
3.2 集成到手机检测模型
修改您的手机检测模型代码,集成监控功能:
import gradio as gr
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks
from monitoring import start_monitoring_server, monitor_inference
import cv2
import numpy as np
# 启动监控服务器
start_monitoring_server(port=8000)
# 加载模型
model_path = 'damo/cv_tinynas_object-detection_damoyolo_phone'
phone_detection = pipeline(Tasks.domain_specific_object_detection, model=model_path)
@monitor_inference
def detect_phones(image):
"""执行手机检测并返回结果"""
result = phone_detection(image)
return result
def process_image(input_image):
"""处理上传的图像并返回检测结果"""
# 转换图像格式
if isinstance(input_image, str):
image = cv2.imread(input_image)
else:
image = input_image
# 执行检测
result = detect_phones(image)
# 绘制检测结果
output_image = image.copy()
detections = result['detections'] if 'detections' in result else []
for detection in detections:
bbox = detection['bbox']
confidence = detection.get('confidence', 0)
label = detection.get('label', 'phone')
# 绘制边界框
x1, y1, x2, y2 = map(int, bbox)
cv2.rectangle(output_image, (x1, y1), (x2, y2), (0, 255, 0), 2)
# 绘制标签和置信度
label_text = f"{label}: {confidence:.2f}"
cv2.putText(output_image, label_text, (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
return output_image, len(detections)
# 创建Gradio界面
def create_gradio_interface():
with gr.Blocks(title="实时手机检测监控系统") as demo:
gr.Markdown("# 实时手机检测-通用监控系统")
gr.Markdown("上传包含手机的图片,系统将自动检测并显示监控指标")
with gr.Row():
with gr.Column():
image_input = gr.Image(label="上传图片", type="numpy")
detect_btn = gr.Button("检测手机")
with gr.Column():
image_output = gr.Image(label="检测结果")
detection_count = gr.Number(label="检测到的手机数量", interactive=False)
# 监控指标显示
with gr.Row():
with gr.Column():
gr.Markdown("### 实时监控指标")
gr.Markdown("访问 http://localhost:8000 查看详细Prometheus指标")
gr.Markdown("访问 http://localhost:3000 查看Grafana仪表板")
detect_btn.click(
fn=process_image,
inputs=image_input,
outputs=[image_output, detection_count]
)
return demo
# 启动应用
if __name__ == "__main__":
demo = create_gradio_interface()
demo.launch(server_name="0.0.0.0", server_port=7860, share=True)
3.3 Prometheus配置优化
修改Prometheus配置文件/etc/prometheus/prometheus.yml,添加手机检测模型的监控目标:
global:
scrape_interval: 15s
evaluation_interval: 15s
scrape_configs:
- job_name: 'phone-detection'
static_configs:
- targets: ['localhost:8000']
labels:
application: 'phone-detection-model'
environment: 'production'
- job_name: 'node-exporter'
static_configs:
- targets: ['localhost:9100']
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
- job_name: 'grafana'
static_configs:
- targets: ['localhost:3000']
4. Grafana仪表板配置
4.1 数据源配置
- 访问Grafana界面(通常为http://localhost:3000)
- 默认用户名/密码:admin/admin
- 添加Prometheus数据源:
- 名称:Prometheus
- URL:http://localhost:9090
- 点击"Save & Test"验证连接
4.2 创建监控仪表板
创建一个名为"手机检测监控看板"的仪表板,添加以下面板:
系统资源监控面板:
{
"title": "系统资源使用率",
"type": "stat",
"targets": [
{
"expr": "100 - (avg by(instance)(irate(node_cpu_seconds_total{mode='idle'}[5m])) * 100)",
"legendFormat": "CPU使用率"
},
{
"expr": "node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes",
"legendFormat": "内存使用"
}
],
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 0}
}
模型性能监控面板:
{
"title": "模型推理性能",
"type": "graph",
"targets": [
{
"expr": "rate(model_inference_seconds_sum[5m]) / rate(model_inference_seconds_count[5m])",
"legendFormat": "平均推理时间"
},
{
"expr": "rate(model_inference_total[5m])",
"legendFormat": "推理频率"
}
],
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 0}
}
检测结果统计面板:
{
"title": "手机检测统计",
"type": "bargauge",
"targets": [
{
"expr": "sum(model_detection_total)",
"legendFormat": "总检测数量"
},
{
"expr": "rate(model_detection_total[5m])",
"legendFormat": "检测频率"
}
],
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 8}
}
4.3 告警规则配置
在Prometheus中添加告警规则,创建/etc/prometheus/alerts.yml文件:
groups:
- name: phone_detection_alerts
rules:
- alert: HighInferenceTime
expr: rate(model_inference_seconds_sum[5m]) / rate(model_inference_seconds_count[5m]) > 0.5
for: 5m
labels:
severity: warning
annotations:
summary: "模型推理时间过高"
description: "模型平均推理时间超过0.5秒,当前值为 {{ $value }} 秒"
- alert: LowDetectionRate
expr: rate(model_detection_total[1h]) < 1
for: 1h
labels:
severity: warning
annotations:
summary: "手机检测率过低"
description: "过去一小时内检测到的手机数量少于1个"
- alert: HighSystemLoad
expr: node_load1 > 5
for: 10m
labels:
severity: critical
annotations:
summary: "系统负载过高"
description: "系统1分钟负载超过5,当前值为 {{ $value }}"
在Prometheus配置文件中引用告警规则:
rule_files:
- "alerts.yml"
alerting:
alertmanagers:
- static_configs:
- targets:
- localhost:9093
5. 实际应用与效果展示
5.1 监控系统运行效果
部署完成后,您的监控系统将提供以下关键功能:
- 实时性能监控:实时显示模型推理时间、检测准确率和系统资源使用情况
- 历史数据分析:查看历史性能趋势,识别性能瓶颈和优化机会
- 多维度统计:按时间、设备、场景等多维度统计检测结果
- 智能告警:在系统异常时及时发送告警通知
5.2 典型监控场景
场景一:日常运营监控
- 监控模型每天的检测数量和成功率
- 跟踪系统资源使用情况,确保稳定运行
- 分析不同时间段的检测需求变化
场景二:性能优化分析
- 识别推理时间过长的原因
- 分析检测准确率的变化趋势
- 优化模型参数和系统配置
场景三:容量规划
- 根据历史数据预测未来资源需求
- 规划系统扩容和升级方案
- 优化资源分配,降低成本
5.3 最佳实践建议
- 定期备份监控数据:确保历史数据不会丢失
- 设置合理的告警阈值:避免误报和漏报
- 定期审查监控配置:根据业务变化调整监控策略
- 建立监控文档:记录监控指标的含义和使用方法
- 培训团队成员:确保团队成员都能使用监控系统
6. 总结
通过将实时手机检测模型与Prometheus+Grafana监控系统集成,您获得了一个完整的企业级监控解决方案。这个系统不仅能够提供实时的性能监控和告警功能,还能帮助您深入分析模型的使用情况和优化方向。
关键收获:
- 全面监控:从系统资源到业务指标的全方位监控
- 实时告警:及时发现和处理系统异常
- 数据驱动:基于监控数据做出优化决策
- 易于扩展:可以轻松添加新的监控指标和功能
实际部署时,建议根据您的具体业务需求调整监控指标和告警阈值,确保监控系统能够真正为业务运营提供价值。
获取更多AI镜像
想探索更多AI镜像和应用场景?访问 CSDN星图镜像广场,提供丰富的预置镜像,覆盖大模型推理、图像生成、视频生成、模型微调等多个领域,支持一键部署。
更多推荐




所有评论(0)