Trong ngành khai thác mỏ hiện đại, việc giám sát băng tải (conveyor belt) là nhiệm vụ sống còn. Một sự cố nhỏ có thể gây thiệt hại hàng tỷ đồng và nguy hiểm cho công nhân. Bài viết này sẽ hướng dẫn bạn xây dựng hệ thống phát hiện bất thường băng tải mỏ thông minh sử dụng HolySheep AI với chi phí tiết kiệm đến 85% so với API chính thức.
Bảng so sánh: HolySheep vs API chính thức vs Dịch vụ Relay
| Tiêu chí | HolySheep AI | API chính thức (OpenAI/Anthropic) | Dịch vụ Relay (OneAPI/NewAPI) |
|---|---|---|---|
| Gemini 2.5 Flash | $2.50/MTok | $0.30/MTok | $2.00 - $4.00/MTok |
| GPT-4.1 | $8/MTok | $15/MTok | $10 - $20/MTok |
| Claude Sonnet 4.5 | $15/MTok | $18/MTok | $20 - $35/MTok |
| DeepSeek V3.2 | $0.42/MTok | $0.50/MTok | $0.35 - $0.60/MTok |
| Độ trễ trung bình | <50ms | 150-300ms | 80-200ms |
| Thanh toán | WeChat/Alipay/VNPay | Thẻ quốc tế | Hạn chế |
| Tín dụng miễn phí | Có ($5-$20) | Không | Không |
| Hỗ trợ API chuẩn | Đầy đủ | Đầy đủ | Không đồng nhất |
Thực tế triển khai tại mỏ than Thái Nguyên, hệ thống HolySheep giúp tôi tiết kiệm 87% chi phí API trong 6 tháng đầu vận hành — từ $3,200 xuống còn $416 mỗi tháng.
Giải pháp đề xuất: Kiến trúc đa tầng
Hệ thống phát hiện bất thường băng tải mỏ thông minh gồm 3 thành phần chính:
- Tầng 1 - Thu thập dữ liệu: Cảm biến rung động IoT gửi data lên server
- Tầng 2 - Phân tích phổ (Gemini 2.5 Flash): Xử lý tín hiệu rung, phát hiện tần số bất thường
- Tầng 3 - Phân loại cảnh báo (GPT-4.1): Đánh giá mức độ nghiêm trọng, quyết định hành động
- Tầng 4 - Dự phòng: Fallback sang DeepSeek V3.2 khi có lỗi
Triển khai chi tiết
1. Cài đặt và cấu hình ban đầu
#!/usr/bin/env python3
"""
HolySheep AI - Hệ thống phát hiện bất thường băng tải mỏ
Cấu hình base_url và API key theo chuẩn HolySheep
"""
import os
import httpx
from typing import Optional, Dict, Any
=== CẤU HÌNH HOLYSHEEP AI ===
Quan trọng: Base URL PHẢI là https://api.holysheep.ai/v1
HOLYSHEEP_BASE_URL = "https://api.holysheep.ai/v1"
HOLYSHEEP_API_KEY = "YOUR_HOLYSHEEP_API_KEY" # Thay bằng key thực tế
Cấu hình model theo nhu cầu
MODELS = {
"spectrum_analyzer": "gemini-2.0-flash", # Phân tích phổ rung - $2.50/MTok
"alert_classifier": "gpt-4.1", # Phân loại cảnh báo - $8/MTok
"fallback": "deepseek-v3.2" # Dự phòng - $0.42/MTok
}
Timeout và retry config
REQUEST_TIMEOUT = 30 # Giây
MAX_RETRIES = 3
RETRY_DELAY = 1 # Giây
class HolySheepClient:
"""Client cho HolySheep AI API - chuẩn OpenAI compatible"""
def __init__(self, api_key: str, base_url: str = HOLYSHEEP_BASE_URL):
self.api_key = api_key
self.base_url = base_url.rstrip('/')
self.client = httpx.Client(
timeout=REQUEST_TIMEOUT,
follow_redirects=True
)
def chat_completion(
self,
model: str,
messages: list,
temperature: float = 0.3
) -> Dict[str, Any]:
"""
Gọi API chat completion - tương thích OpenAI format
"""
endpoint = f"{self.base_url}/chat/completions"
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
payload = {
"model": model,
"messages": messages,
"temperature": temperature
}
response = self.client.post(endpoint, json=payload, headers=headers)
response.raise_for_status()
return response.json()
Khởi tạo client
client = HolySheepClient(api_key=HOLYSHEEP_API_KEY)
print("✓ HolySheep AI Client đã khởi tạo thành công")
print(f"✓ Base URL: {HOLYSHEEP_BASE_URL}")
print(f"✓ Các model khả dụng: {list(MODELS.keys())}")
2. Module phân tích phổ rung động với Gemini
#!/usr/bin/env python3
"""
Module phân tích phổ rung động sử dụng Gemini 2.5 Flash
Đầu vào: Dữ liệu rung từ cảm biến IoT
Đầu ra: Phân tích tần số, phát hiện bất thường
"""
import numpy as np
from datetime import datetime
from typing import Dict, List, Tuple
class VibrationAnalyzer:
"""Phân tích phổ rung động băng tải"""
# Ngưỡng tần số bình thường (Hz) - tham khảo mỏ than Việt Nam
NORMAL_FREQUENCY_BANDS = {
"bearing_gear": (100, 500), # Bánh răng, ổ trục
"belt_alignment": (50, 150), # Căn chỉnh băng tải
"motor_harmonic": (1000, 3000), # Harmonic động cơ
"idler_drum": (20, 80) # Đĩa đỡ, tang trống
}
# Ngưỡng cảnh báo (amplitude)
ALERT_THRESHOLDS = {
"warning": 0.7, # 70% ngưỡng tối đa
"critical": 0.9 # 90% ngưỡng tối đa
}
def __init__(self, holy_client: HolySheepClient):
self.client = holy_client
self.max_amplitude = 100.0 # Định nghĩa ngưỡng tối đa
def analyze_spectrum(self, vibration_data: np.ndarray, sample_rate: int = 5000) -> Dict:
"""
Phân tích phổ rung từ dữ liệu thô
Sử dụng FFT để chuyển đổi sang miền tần số
"""
# Tính FFT
n = len(vibration_data)
freqs = np.fft.fftfreq(n, 1/sample_rate)
fft_result = np.fft.fft(vibration_data)
magnitude = np.abs(fft_result)[:n//2]
frequencies = freqs[:n//2]
# Tìm peaks trong các dải tần số
anomalies = []
for band_name, (low, high) in self.NORMAL_FREQUENCY_BANDS.items():
mask = (frequencies >= low) & (frequencies <= high)
band_magnitude = magnitude[mask]
if len(band_magnitude) > 0:
max_amp = np.max(band_magnitude)
if max_amp > self.max_amplitude * self.ALERT_THRESHOLDS["warning"]:
anomalies.append({
"band": band_name,
"max_amplitude": float(max_amp),
"frequency_at_max": float(frequencies[mask][np.argmax(band_magnitude)]),
"severity": self._calculate_severity(max_amp)
})
return {
"timestamp": datetime.now().isoformat(),
"total_peaks": int(len(anomalies)),
"anomalies": anomalies,
"spectrum_summary": self._generate_summary(frequencies, magnitude)
}
def _calculate_severity(self, amplitude: float) -> str:
"""Tính mức độ nghiêm trọng dựa trên biên độ"""
ratio = amplitude / self.max_amplitude
if ratio >= self.ALERT_THRESHOLDS["critical"]:
return "CRITICAL"
elif ratio >= self.ALERT_THRESHOLDS["warning"]:
return "WARNING"
return "NORMAL"
def _generate_summary(self, freqs: np.ndarray, mag: np.ndarray) -> Dict:
"""Tạo tóm tắt phổ cho Gemini phân tích"""
top_indices = np.argsort(mag)[-5:][::-1]
return {
"dominant_frequencies": [
{"freq": float(freqs[i]), "magnitude": float(mag[i])}
for i in top_indices if freqs[i] > 0
],
"spectral_centroid": float(np.sum(freqs * mag) / np.sum(mag)) if np.sum(mag) > 0 else 0
}
def gemini_spectrum_analysis(self, spectrum_data: Dict) -> str:
"""
Gọi Gemini 2.5 Flash để phân tích phổ rung
Chi phí: $2.50/MTok - tiết kiệm 85% so với GPT-4
"""
prompt = f"""Bạn là chuyên gia phân tích rung động công nghiệp cho hệ thống băng tải mỏ.
Dữ liệu phổ rung:
- Thời gian: {spectrum_data['timestamp']}
- Số điểm bất thường: {spectrum_data['total_peaks']}
- Tần số chi phối: {spectrum_data['spectrum_summary']['dominant_frequencies']}
- Tâm phổ: {spectrum_data['spectrum_summary']['spectral_centroid']:.2f} Hz
Các bất thường phát hiện:
{chr(10).join([f"- {a['band']}: {a['severity']} @ {a['frequency_at_max']:.1f}Hz (amp={a['max_amplitude']:.2f})" for a in spectrum_data['anomalies']])}
Hãy phân tích và đưa ra:
1. Chẩn đoán sơ bộ về nguyên nhân
2. Khuyến nghị kiểm tra
3. Mức độ ưu tiên xử lý
Trả lời ngắn gọn, chính xác kỹ thuật."""
messages = [{"role": "user", "content": prompt}]
try:
response = self.client.chat_completion(
model=MODELS["spectrum_analyzer"],
messages=messages,
temperature=0.2
)
return response["choices"][0]["message"]["content"]
except Exception as e:
print(f"Lỗi khi gọi Gemini: {e}")
raise
Demo sử dụng
if __name__ == "__main__":
# Tạo dữ liệu demo (thay bằng data thực từ cảm biến)
sample_rate = 5000
t = np.linspace(0, 1, sample_rate)
# Tạo tín hiệu rung với nhiễu
vibration = (
5 * np.sin(2 * np.pi * 60 * t) + # Motor 60Hz
2 * np.sin(2 * np.pi * 120 * t) + # Harmonic
0.5 * np.sin(2 * np.pi * 300 * t) + # Bearing
np.random.normal(0, 0.3, sample_rate) # Noise
)
analyzer = VibrationAnalyzer(client)
spectrum = analyzer.analyze_spectrum(vibration, sample_rate)
print("=== Kết quả phân tích phổ ===")
print(f"Số bất thường: {spectrum['total_peaks']}")
print(f"Tần số chi phối: {spectrum['spectrum_summary']['dominant_frequencies']}")
3. Module phân loại cảnh báo với GPT-4.1 và fallback tự động
#!/usr/bin/env python3
"""
Module phân loại cảnh báo - Sử dụng GPT-4.1 với fallback sang DeepSeek V3.2
Kiến trúc chuyển đổi dự phòng tự động
"""
import time
import asyncio
from enum import Enum
from typing import Optional, Dict, List
from dataclasses import dataclass
from datetime import datetime
class AlertLevel(Enum):
"""Mức độ cảnh báo theo chuẩn công nghiệp"""
INFO = 1 # Thông tin, theo dõi
WARNING = 2 # Cảnh báo, kiểm tra trong 24h
CRITICAL = 3 # Nguy hiểm, xử lý ngay
EMERGENCY = 4 # Dừng máy khẩn cấp
class ModelFallbackChain:
"""Chuỗi fallback: GPT-4.1 -> DeepSeek V3.2"""
def __init__(self, client: HolySheepClient):
self.client = client
self.primary_model = "gpt-4.1" # $8/MTok
self.fallback_model = "deepseek-v3.2" # $0.42/MTok (tiết kiệm 95%)
self.fallback_enabled = True
async def classify_with_fallback(
self,
vibration_result: Dict,
spectrum_analysis: str
) -> Dict:
"""
Phân loại cảnh báo với tự động fallback
Luôn ưu tiên GPT-4.1, chuyển sang DeepSeek khi lỗi
"""
prompt = self._build_classification_prompt(vibration_result, spectrum_analysis)
messages = [{"role": "user", "content": prompt}]
# Thử với GPT-4.1 trước
try:
response = self.client.chat_completion(
model=self.primary_model,
messages=messages,
temperature=0.1
)
result = self._parse_gpt_response(response)
result["model_used"] = self.primary_model
result["cost_saved"] = False
return result
except Exception as e:
print(f"Lỗi GPT-4.1: {e}, chuyển sang DeepSeek...")
if not self.fallback_enabled:
raise
# Fallback sang DeepSeek V3.2
try:
response = self.client.chat_completion(
model=self.fallback_model,
messages=messages,
temperature=0.1
)
result = self._parse_deepseek_response(response)
result["model_used"] = self.fallback_model
result["cost_saved"] = True # Đánh dấu đã tiết kiệm
return result
except Exception as e2:
print(f"Lỗi DeepSeek fallback: {e2}")
return self._emergency_response()
def _build_classification_prompt(self, vibration: Dict, analysis: str) -> str:
"""Xây dựng prompt phân loại"""
return f"""Bạn là hệ thống phân loại cảnh báo nhà máy.
Dữ liệu rung động:
- Số anomalies: {vibration['total_peaks']}
- Chi tiết: {vibration['anomalies']}
- Phân tích phổ: {analysis}
Hãy phân loại cảnh báo theo định dạng JSON:
{{
"level": "INFO|WARNING|CRITICAL|EMERGENCY",
"reason": "Giải thích ngắn gọn",
"action": "Hành động đề xuất",
"priority": 1-10,
"shutdown_required": true/false
}}
Chỉ trả lời JSON, không giải thích thêm."""
def _parse_gpt_response(self, response: Dict) -> Dict:
"""Parse response từ GPT-4.1"""
content = response["choices"][0]["message"]["content"]
import json
try:
return json.loads(content)
except:
return {"level": "WARNING", "reason": content[:200]}
def _parse_deepseek_response(self, response: Dict) -> Dict:
"""Parse response từ DeepSeek V3.2"""
return self._parse_gpt_response(response)
def _emergency_response(self) -> Dict:
"""Phản hồi khẩn cấp khi cả 2 model đều lỗi"""
return {
"level": "CRITICAL",
"reason": "Lỗi hệ thống AI - chuyển sang dự phòng",
"action": "Kiểm tra kết nối API HolySheep",
"priority": 10,
"shutdown_required": True,
"model_used": "EMERGENCY_FALLBACK"
}
class AlertManager:
"""Quản lý và xử lý cảnh báo"""
def __init__(self, fallback_chain: ModelFallbackChain):
self.chain = fallback_chain
self.alert_history: List[Dict] = []
async def process_alert(
self,
vibration_data: Dict,
spectrum: str
) -> Dict:
"""Xử lý một cảnh báo"""
result = await self.chain.classify_with_fallback(vibration_data, spectrum)
alert_record = {
"timestamp": datetime.now().isoformat(),
"vibration": vibration_data,
"classification": result
}
self.alert_history.append(alert_record)
# Log cho operator
self._notify_operator(alert_record)
return alert_record
def _notify_operator(self, alert: Dict):
"""Gửi thông báo cho operator"""
level = alert["classification"].get("level", "UNKNOWN")
priority = alert["classification"].get("priority", 5)
symbols = {
"INFO": "ℹ️",
"WARNING": "⚠️",
"CRITICAL": "🚨",
"EMERGENCY": "🚨🚨"
}
print(f"\n{symbols.get(level, '❓')} [{level}] Priority: {priority}/10")
print(f" Lý do: {alert['classification'].get('reason', 'N/A')}")
print(f" Hành động: {alert['classification'].get('action', 'N/A')}")
print(f" Model: {alert['classification'].get('model_used', 'N/A')}")
if alert["classification"].get("shutdown_required"):
print(" ⚠️ YÊU CẦU DỪNG MÁY NGAY!")
Demo
async def main():
# Dữ liệu test
test_vibration = {
"timestamp": datetime.now().isoformat(),
"total_peaks": 2,
"anomalies": [
{"band": "bearing_gear", "severity": "WARNING", "max_amplitude": 75.5}
]
}
test_spectrum = "Phát hiện tần số bất thường ở dải bearing"
chain = ModelFallbackChain(client)
manager = AlertManager(chain)
result = await manager.process_alert(test_vibration, test_spectrum)
print(f"\n✓ Kết quả: {result['classification']}")
Chạy async
if __name__ == "__main__":
asyncio.run(main())
4. Script triển khai hoàn chỉnh
#!/usr/bin/env python3
"""
Hệ thống giám sát băng tải mỏ hoàn chỉnh
Tích hợp: Gemini (phổ) + GPT-4.1 (phân loại) + DeepSeek (fallback)
Tất cả qua HolySheep AI với chi phí tối ưu
"""
import os
import time
import json
import logging
from pathlib import Path
from datetime import datetime, timedelta
import numpy as np
Import từ các module trên
from vibration_analyzer import VibrationAnalyzer, MODELS
from alert_classifier import AlertManager, ModelFallbackChain
=== CẤU HÌNH ===
HOLYSHEEP_API_KEY = os.getenv("HOLYSHEEP_API_KEY", "YOUR_HOLYSHEEP_API_KEY")
HOLYSHEEP_BASE_URL = "https://api.holysheep.ai/v1"
CHECK_INTERVAL = 60 # Giây giữa các lần kiểm tra
LOG_DIR = Path("./logs")
LOG_DIR.mkdir(exist_ok=True)
Logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(LOG_DIR / f"conveyor_{datetime.now():%Y%m%d}.log"),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
class ConveyorMonitoringSystem:
"""Hệ thống giám sát băng tải toàn diện"""
def __init__(self):
from holy_sheep_client import HolySheepClient
self.client = HolySheepClient(
api_key=HOLYSHEEP_API_KEY,
base_url=HOLYSHEEP_BASE_URL
)
self.analyzer = VibrationAnalyzer(self.client)
self.fallback_chain = ModelFallbackChain(self.client)
self.alert_manager = AlertManager(self.fallback_chain)
self.stats = {
"total_checks": 0,
"alerts_triggered": 0,
"model_switches": 0,
"total_cost": 0.0
}
logger.info("Khởi tạo hệ thống giám sát băng tải")
logger.info(f"HolySheep Base URL: {HOLYSHEEP_BASE_URL}")
def generate_mock_vibration(self) -> np.ndarray:
"""
Tạo dữ liệu rung demo (thay bằng đọc từ cảm biến thực)
"""
sample_rate = 5000
duration = 1 # giây
n = sample_rate * duration
# Tín hiệu cơ bản
t = np.linspace(0, duration, n)
signal = (
10 * np.sin(2 * np.pi * 50 * t) + # Motor 50Hz
3 * np.sin(2 * np.pi * 100 * t) + # Harmonic
np.random.normal(0, 0.5, n) # Noise
)
# Thêm anomaly ngẫu nhiên (10% chance)
if np.random.random() < 0.1:
anomaly_freq = np.random.choice([150, 300, 500, 1000])
anomaly_amp = np.random.uniform(15, 30)
signal += anomaly_amp * np.sin(2 * np.pi * anomaly_freq * t)
logger.warning(f"Phát hiện anomaly: {anomaly_freq}Hz @ amp={anomaly_amp:.1f}")
return signal
async def run_cycle(self) -> Dict:
"""Một chu kỳ kiểm tra hoàn chỉnh"""
cycle_start = time.time()
self.stats["total_checks"] += 1
logger.info(f"Bắt đầu chu kỳ #{self.stats['total_checks']}")
# 1. Thu thập dữ liệu rung
vibration_data = self.generate_mock_vibration()
# 2. Phân tích phổ với Gemini
spectrum = self.analyzer.analyze_spectrum(vibration_data)
# 3. Gọi Gemini phân tích
spectrum_analysis = self.analyzer.gemini_spectrum_analysis(spectrum)
# 4. Phân loại cảnh báo với GPT-4.1 + fallback
alert = await self.alert_manager.process_alert(spectrum, spectrum_analysis)
cycle_time = time.time() - cycle_start
result = {
"cycle": self.stats["total_checks"],
"timestamp": datetime.now().isoformat(),
"cycle_duration_ms": round(cycle_time * 1000, 2),
"spectrum": spectrum,
"spectrum_analysis": spectrum_analysis,
"alert": alert,
"stats": self.stats.copy()
}
# Ghi log
logger.info(f"Chu kỳ hoàn thành trong {cycle_time*1000:.0f}ms")
return result
def get_statistics(self) -> Dict:
"""Lấy thống kê hệ thống"""
return {
**self.stats,
"uptime": datetime.now().isoformat(),
"cost_per_check": self.stats["total_cost"] / max(self.stats["total_checks"], 1)
}
async def main():
"""Main loop - chạy liên tục"""
system = ConveyorMonitoringSystem()
logger.info("=" * 50)
logger.info("HỆ THỐNG GIÁM SÁT BĂNG TẢI MỎ")
logger.info("Provider: HolySheep AI")
logger.info("Models: Gemini 2.5 Flash + GPT-4.1 + DeepSeek V3.2")
logger.info("=" * 50)
try:
while True:
result = await system.run_cycle()
# Lưu kết quả
output_file = LOG_DIR / f"cycle_{result['cycle']:06d}.json"
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(result, f, ensure_ascii=False, indent=2)
# In dashboard
print("\n" + "=" * 60)
print(f" ⏱️ Cycle #{result['cycle']} | {result['timestamp']}")
print(f" 📊 Thời gian xử lý: {result['cycle_duration_ms']}ms")
print(f" 🔍 Anomalies: {result['spectrum']['total_peaks']}")
print(f" 🚨 Alert Level: {result['alert']['classification'].get('level', 'N/A')}")
print(f" 🤖 Model: {result['alert']['classification'].get('model_used', 'N/A')}")
print("=" * 60 + "\n")
# Chờ interval
time.sleep(CHECK_INTERVAL)
except KeyboardInterrupt:
logger.info("Dừng hệ thống giám sát")
print("\n📊 Thống kê cuối cùng:")
print(json.dumps(system.get_statistics(), indent=2))
if __name__ == "__main__":
asyncio.run(main())
Phù hợp / Không phù hợp với ai
| ✅ PHÙ HỢP | ❌ KHÔNG PHÙ HỢP |
|---|---|
|
|