GOGO198 commited on
Commit
803396c
·
verified ·
1 Parent(s): b841e5b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -10
app.py CHANGED
@@ -164,18 +164,36 @@ def predict(vector):
164
  for i in range(k):
165
  try:
166
  idx = I[0][i]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  result = {
168
  "source": metadata.iloc[idx]["source"],
169
  "content": metadata.iloc[idx].get("content", ""),
170
- "confidence": float(1/(1+D[0][i])),
171
- "distance": float(D[0][i])
172
  }
173
  results.append(result)
174
  except Exception as e:
175
  print(f"结果处理错误: {str(e)}")
176
  results.append({
177
  "error": f"结果 {i+1}: 数据获取失败",
178
- "confidence": 0.0
 
179
  })
180
 
181
  return {
@@ -183,13 +201,11 @@ def predict(vector):
183
  "results": results
184
  }
185
  except Exception as e:
186
- return JSONResponse(
187
- status_code=500,
188
- content={
189
- "status": "error",
190
- "message": f"服务器内部错误: {str(e)}"
191
- }
192
- )
193
 
194
  # 创建FastAPI应用
195
  app = FastAPI()
 
164
  for i in range(k):
165
  try:
166
  idx = I[0][i]
167
+
168
+ # 安全处理距离值
169
+ distance = D[0][i]
170
+ if not np.isfinite(distance) or distance < 0:
171
+ print(f"警告: 无效距离值 {distance},使用默认值0")
172
+ distance = 0.0
173
+
174
+ # 安全处理置信度值
175
+ try:
176
+ confidence = 1 / (1 + distance)
177
+ except ZeroDivisionError:
178
+ confidence = 1.0
179
+
180
+ if not np.isfinite(confidence) or confidence < 0:
181
+ print(f"警告: 无效置信度 {confidence},使用默认值0.5")
182
+ confidence = 0.5
183
+
184
  result = {
185
  "source": metadata.iloc[idx]["source"],
186
  "content": metadata.iloc[idx].get("content", ""),
187
+ "confidence": float(confidence),
188
+ "distance": float(distance)
189
  }
190
  results.append(result)
191
  except Exception as e:
192
  print(f"结果处理错误: {str(e)}")
193
  results.append({
194
  "error": f"结果 {i+1}: 数据获取失败",
195
+ "confidence": 0.5,
196
+ "distance": 0.0
197
  })
198
 
199
  return {
 
201
  "results": results
202
  }
203
  except Exception as e:
204
+ # 返回错误响应
205
+ return {
206
+ "status": "error",
207
+ "message": f"服务器内部错误: {str(e)}"
208
+ }
 
 
209
 
210
  # 创建FastAPI应用
211
  app = FastAPI()