guohanghui commited on
Commit
c5459bd
·
verified ·
1 Parent(s): 8616b68

Update pest/source/src/pest.py

Browse files
Files changed (1) hide show
  1. pest/source/src/pest.py +43 -101
pest/source/src/pest.py CHANGED
@@ -8,119 +8,61 @@ def detect_pest(model, image_data):
8
  try:
9
  import torch
10
  import torch.nn.functional as F
11
- import random
12
 
13
  # 检查输入类型
14
- if isinstance(model, dict) and 'model' in model and isinstance(image_data, dict) and 'image_path' in image_data:
15
- model_obj = model['model']
16
- image_path = image_data['image_path']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
- # 检查是否是真实模型
19
- if model.get('is_mock', True) == False and model_obj == 'real_model_loaded':
20
- # 真实模型检测
21
- print("Using real model for detection")
22
- # 从全局变量获取模型和transform
23
- from .utils import _loaded_model, _model_transform
24
-
25
- if _loaded_model is not None and _model_transform is not None:
26
- # 从全局变量获取图像
27
- from .utils import _loaded_image
28
- print(f"Loaded model: {_loaded_model is not None}")
29
- print(f"Loaded transform: {_model_transform is not None}")
30
- print(f"Loaded image: {_loaded_image is not None}")
31
- if _loaded_image is not None:
32
- # 预处理图像
33
- input_tensor = _model_transform(_loaded_image).unsqueeze(0)
34
-
35
- # 模型推理
36
- with torch.no_grad():
37
- outputs = _loaded_model(input_tensor)
38
- probabilities = F.softmax(outputs, dim=1)
39
- confidence, predicted = torch.max(probabilities, 1)
40
-
41
- # 获取前5个预测结果
42
- top5_prob, top5_indices = torch.topk(probabilities, 5)
43
-
44
- predictions = []
45
- for i in range(5):
46
- class_id = top5_indices[0][i].item()
47
- confidence_score = top5_prob[0][i].item()
48
-
49
- predictions.append({
50
- 'class_id': class_id,
51
- 'confidence': confidence_score
52
- })
53
-
54
- return {
55
- 'predictions': predictions,
56
- 'top_prediction': {
57
- 'class_id': predicted.item(),
58
- 'confidence': confidence.item()
59
- },
60
- 'is_mock': False
61
- }
62
-
63
- # 如果真实模型不可用,回退到模拟
64
- print("Real model not available, falling back to mock")
65
- mock_predictions = []
66
- for i in range(5):
67
- class_id = random.randint(1, 102)
68
- confidence = random.uniform(0.1, 0.9)
69
- mock_predictions.append({
70
- 'class_id': class_id,
71
- 'confidence': confidence
72
- })
73
-
74
- return {
75
- 'predictions': mock_predictions,
76
- 'top_prediction': {
77
- 'class_id': mock_predictions[0]['class_id'],
78
- 'confidence': mock_predictions[0]['confidence']
79
- },
80
- 'is_mock': True
81
- }
82
- else:
83
- # 模拟检测结果
84
- print("Using mock model for detection")
85
- mock_predictions = []
86
- for i in range(5):
87
- class_id = random.randint(1, 102) # IP102数据集有102个类别
88
- confidence = random.uniform(0.1, 0.9)
89
- mock_predictions.append({
90
- 'class_id': class_id,
91
- 'confidence': confidence
92
- })
93
-
94
- return {
95
- 'predictions': mock_predictions,
96
- 'top_prediction': {
97
- 'class_id': mock_predictions[0]['class_id'],
98
- 'confidence': mock_predictions[0]['confidence']
99
- },
100
- 'is_mock': True
101
- }
102
- else:
103
- # 简化实现,返回模拟结果
104
- print("Using simplified mock detection")
105
- mock_predictions = []
106
  for i in range(5):
107
- class_id = random.randint(1, 102)
108
- confidence = random.uniform(0.1, 0.9)
109
- mock_predictions.append({
 
110
  'class_id': class_id,
111
- 'confidence': confidence
112
  })
113
 
114
  return {
115
- 'predictions': mock_predictions,
116
  'top_prediction': {
117
- 'class_id': mock_predictions[0]['class_id'],
118
- 'confidence': mock_predictions[0]['confidence']
119
  },
120
- 'is_mock': True
121
  }
122
  except Exception as e:
123
- return f"Detection error: {str(e)}"
124
 
125
  def initialize_detector():
126
  """Initialize the pest detector (only when needed)."""
 
8
  try:
9
  import torch
10
  import torch.nn.functional as F
 
11
 
12
  # 检查输入类型
13
+ if not (isinstance(model, dict) and 'model' in model and isinstance(image_data, dict) and 'image_path' in image_data):
14
+ raise ValueError("Invalid input format for model or image_data")
15
+
16
+ model_obj = model['model']
17
+ image_path = image_data['image_path']
18
+
19
+ # 检查是否是真实模型
20
+ if model.get('is_mock', True) != False or model_obj != 'real_model_loaded':
21
+ raise ValueError("Model is not properly loaded or is in mock mode")
22
+
23
+ # 真实模型检测
24
+ print("Using real model for detection")
25
+ # 从全局变量获取模型和transform
26
+ from .utils import _loaded_model, _model_transform, _loaded_image
27
+
28
+ if _loaded_model is None or _model_transform is None:
29
+ raise RuntimeError("Model or transform not loaded")
30
+
31
+ if _loaded_image is None:
32
+ raise RuntimeError("Image not loaded")
33
+
34
+ # 预处理图像
35
+ input_tensor = _model_transform(_loaded_image).unsqueeze(0)
36
+
37
+ # 模型推理
38
+ with torch.no_grad():
39
+ outputs = _loaded_model(input_tensor)
40
+ probabilities = F.softmax(outputs, dim=1)
41
+ confidence, predicted = torch.max(probabilities, 1)
42
 
43
+ # 获取前5个预测结果
44
+ top5_prob, top5_indices = torch.topk(probabilities, 5)
45
+
46
+ predictions = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  for i in range(5):
48
+ class_id = top5_indices[0][i].item()
49
+ confidence_score = top5_prob[0][i].item()
50
+
51
+ predictions.append({
52
  'class_id': class_id,
53
+ 'confidence': confidence_score
54
  })
55
 
56
  return {
57
+ 'predictions': predictions,
58
  'top_prediction': {
59
+ 'class_id': predicted.item(),
60
+ 'confidence': confidence.item()
61
  },
62
+ 'is_mock': False
63
  }
64
  except Exception as e:
65
+ raise RuntimeError(f"Detection error: {str(e)}")
66
 
67
  def initialize_detector():
68
  """Initialize the pest detector (only when needed)."""