Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,20 +1,25 @@
|
|
| 1 |
import os
|
| 2 |
import requests
|
| 3 |
import json
|
|
|
|
| 4 |
from flask import Flask, request, jsonify, send_from_directory
|
| 5 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
# 初始化Flask应用,并指定静态文件目录
|
| 7 |
app = Flask(__name__, static_folder='static', static_url_path='')
|
| 8 |
|
| 9 |
-
# 从环境变量中获取API
|
| 10 |
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
|
| 11 |
-
# 修正:使用稳定且公开的 gemini-pro-vision 模型端点
|
| 12 |
-
GEMINI_API_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent"
|
| 13 |
|
| 14 |
-
#
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
|
|
|
|
|
|
| 18 |
请严格遵循以下JSON结构:
|
| 19 |
{
|
| 20 |
"image_features": ["从图像中识别出的关键皮损形态学特征列表", "例如:色素网络不规则", "例如:蓝白结构"],
|
|
@@ -35,36 +40,37 @@ SYSTEM_PROMPT = """
|
|
| 35 |
"further_examinations": ["建议的下一步检查列表", "例如:皮肤镜检查", "例如:皮肤活检"],
|
| 36 |
"treatment_suggestions": ["初步的、符合临床指南的治疗方向建议列表", "例如:外用糖皮质激素", "例如:建议手术切除"]
|
| 37 |
}
|
| 38 |
-
}
|
| 39 |
-
"""
|
| 40 |
|
| 41 |
-
# ==============================================================================
|
| 42 |
-
# == 新增的健康检查路由 ==
|
| 43 |
-
# 这个路由非常简单,只返回"OK"和200状态码,确保健康检查能100%通过
|
| 44 |
-
# ==============================================================================
|
| 45 |
@app.route('/healthz')
|
| 46 |
def health_check():
|
| 47 |
"""Health check endpoint"""
|
|
|
|
| 48 |
return "OK", 200
|
| 49 |
|
| 50 |
@app.route('/')
|
| 51 |
def index():
|
| 52 |
"""提供前端HTML页面"""
|
|
|
|
| 53 |
return send_from_directory(app.static_folder, 'index.html')
|
| 54 |
|
| 55 |
@app.route('/api/analyze', methods=['POST'])
|
| 56 |
def analyze_skin():
|
| 57 |
"""处理分析请求的核心API端点"""
|
|
|
|
|
|
|
| 58 |
if not GEMINI_API_KEY:
|
|
|
|
| 59 |
return jsonify({"error": "服务端未配置GEMINI_API_KEY"}), 500
|
| 60 |
-
|
| 61 |
data = request.json
|
| 62 |
if not data or 'image' not in data or 'text' not in data:
|
|
|
|
| 63 |
return jsonify({"error": "请求中缺少图像或文本信息"}), 400
|
| 64 |
-
|
| 65 |
image_base64 = data.get('image')
|
| 66 |
text_prompt = data.get('text')
|
| 67 |
-
|
| 68 |
headers = {
|
| 69 |
'Content-Type': 'application/json',
|
| 70 |
}
|
|
@@ -85,29 +91,44 @@ def analyze_skin():
|
|
| 85 |
}
|
| 86 |
]
|
| 87 |
}
|
| 88 |
-
|
| 89 |
try:
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
response.raise_for_status()
|
| 92 |
|
| 93 |
gemini_result = response.json()
|
|
|
|
| 94 |
|
| 95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
-
return jsonify(parsed_json)
|
| 100 |
-
|
| 101 |
except requests.exceptions.RequestException as e:
|
|
|
|
| 102 |
return jsonify({"error": f"调用Gemini API时发生网络错误: {e}"}), 500
|
| 103 |
-
except (KeyError, IndexError):
|
| 104 |
-
# 增加对返回结果的打印,方便调试
|
| 105 |
-
error_details = response.json() if 'response' in locals() else "No response from API"
|
| 106 |
-
return jsonify({"error": "解析Gemini API响应失败,格式不正确", "details": error_details}), 500
|
| 107 |
-
except json.JSONDecodeError:
|
| 108 |
-
return jsonify({"error": "Gemini API未返回有效的JSON格式", "details": analysis_content_string}), 500
|
| 109 |
except Exception as e:
|
|
|
|
| 110 |
return jsonify({"error": f"发生未知错误: {e}"}), 500
|
| 111 |
|
| 112 |
if __name__ == '__main__':
|
| 113 |
-
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import requests
|
| 3 |
import json
|
| 4 |
+
import logging
|
| 5 |
from flask import Flask, request, jsonify, send_from_directory
|
| 6 |
|
| 7 |
+
# 配置日志
|
| 8 |
+
logging.basicConfig(level=logging.INFO)
|
| 9 |
+
logger = logging.getLogger(__name__)
|
| 10 |
+
|
| 11 |
# 初始化Flask应用,并指定静态文件目录
|
| 12 |
app = Flask(__name__, static_folder='static', static_url_path='')
|
| 13 |
|
| 14 |
+
# 从环境变量中获取API密钥
|
| 15 |
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
|
|
|
|
|
|
|
| 16 |
|
| 17 |
+
# Gemini API URL
|
| 18 |
+
GEMINI_API_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent"
|
| 19 |
+
|
| 20 |
+
# 系统提示
|
| 21 |
+
SYSTEM_PROMPT = """你是一个世界顶级的皮肤科医生AI助手。你的任务是基于用户上传的皮肤图像和病历文本,进行专业的临床诊疗辅助分析。你的输出必须是一个单一、有效的JSON对象,不包含任何JSON格式之外的文字或标记(例如不要使用 "```json")。
|
| 22 |
+
|
| 23 |
请严格遵循以下JSON结构:
|
| 24 |
{
|
| 25 |
"image_features": ["从图像中识别出的关键皮损形态学特征列表", "例如:色素网络不规则", "例如:蓝白结构"],
|
|
|
|
| 40 |
"further_examinations": ["建议的下一步检查列表", "例如:皮肤镜检查", "例如:皮肤活检"],
|
| 41 |
"treatment_suggestions": ["初步的、符合临床指南的治疗方向建议列表", "例如:外用糖皮质激素", "例如:建议手术切除"]
|
| 42 |
}
|
| 43 |
+
}"""
|
|
|
|
| 44 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
@app.route('/healthz')
|
| 46 |
def health_check():
|
| 47 |
"""Health check endpoint"""
|
| 48 |
+
logger.info("Health check endpoint accessed")
|
| 49 |
return "OK", 200
|
| 50 |
|
| 51 |
@app.route('/')
|
| 52 |
def index():
|
| 53 |
"""提供前端HTML页面"""
|
| 54 |
+
logger.info("Main page accessed")
|
| 55 |
return send_from_directory(app.static_folder, 'index.html')
|
| 56 |
|
| 57 |
@app.route('/api/analyze', methods=['POST'])
|
| 58 |
def analyze_skin():
|
| 59 |
"""处理分析请求的核心API端点"""
|
| 60 |
+
logger.info("Analysis endpoint accessed")
|
| 61 |
+
|
| 62 |
if not GEMINI_API_KEY:
|
| 63 |
+
logger.error("GEMINI_API_KEY not configured")
|
| 64 |
return jsonify({"error": "服务端未配置GEMINI_API_KEY"}), 500
|
| 65 |
+
|
| 66 |
data = request.json
|
| 67 |
if not data or 'image' not in data or 'text' not in data:
|
| 68 |
+
logger.error("Invalid request data")
|
| 69 |
return jsonify({"error": "请求中缺少图像或文本信息"}), 400
|
| 70 |
+
|
| 71 |
image_base64 = data.get('image')
|
| 72 |
text_prompt = data.get('text')
|
| 73 |
+
|
| 74 |
headers = {
|
| 75 |
'Content-Type': 'application/json',
|
| 76 |
}
|
|
|
|
| 91 |
}
|
| 92 |
]
|
| 93 |
}
|
| 94 |
+
|
| 95 |
try:
|
| 96 |
+
logger.info("Calling Gemini API")
|
| 97 |
+
response = requests.post(
|
| 98 |
+
f"{GEMINI_API_URL}?key={GEMINI_API_KEY}",
|
| 99 |
+
headers=headers,
|
| 100 |
+
json=payload,
|
| 101 |
+
timeout=60
|
| 102 |
+
)
|
| 103 |
response.raise_for_status()
|
| 104 |
|
| 105 |
gemini_result = response.json()
|
| 106 |
+
logger.info("Received response from Gemini API")
|
| 107 |
|
| 108 |
+
# 修复解析错误
|
| 109 |
+
try:
|
| 110 |
+
analysis_content_string = gemini_result['candidates'][0]['content']['parts'][0]['text']
|
| 111 |
+
except (KeyError, IndexError) as e:
|
| 112 |
+
logger.error(f"Error parsing Gemini response structure: {e}")
|
| 113 |
+
logger.error(f"Gemini response: {gemini_result}")
|
| 114 |
+
return jsonify({"error": "解析Gemini API响应失败,格式不正确", "details": str(gemini_result)}), 500
|
| 115 |
|
| 116 |
+
try:
|
| 117 |
+
parsed_json = json.loads(analysis_content_string)
|
| 118 |
+
logger.info("Successfully parsed JSON response")
|
| 119 |
+
return jsonify(parsed_json)
|
| 120 |
+
except json.JSONDecodeError as e:
|
| 121 |
+
logger.error(f"JSON decode error: {e}")
|
| 122 |
+
logger.error(f"Content: {analysis_content_string}")
|
| 123 |
+
return jsonify({"error": "Gemini API未返回有效的JSON格式", "details": analysis_content_string}), 500
|
| 124 |
|
|
|
|
|
|
|
| 125 |
except requests.exceptions.RequestException as e:
|
| 126 |
+
logger.error(f"Network error calling Gemini API: {e}")
|
| 127 |
return jsonify({"error": f"调用Gemini API时发生网络错误: {e}"}), 500
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
except Exception as e:
|
| 129 |
+
logger.error(f"Unexpected error: {e}")
|
| 130 |
return jsonify({"error": f"发生未知错误: {e}"}), 500
|
| 131 |
|
| 132 |
if __name__ == '__main__':
|
| 133 |
+
logger.info("Starting Flask application...")
|
| 134 |
+
app.run(host='0.0.0.0', port=8080, debug=False)
|