Spaces:
Runtime error
Runtime error
| import os | |
| import requests | |
| import json | |
| from flask import Flask, request, jsonify, send_from_directory | |
| app = Flask(__name__, static_folder='static', static_url_path='') | |
| GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY") | |
| GEMINI_API_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent" | |
| SYSTEM_PROMPT = """ | |
| 你是一个世界顶级的皮肤科医生AI助手。你的任务是基于用户上传的皮肤图像和病历文本,进行专业的临床诊疗辅助分析。 | |
| 你的输出必须是一个单一、有效的JSON对象,不包含任何JSON格式之外的文字或标记(例如不要使用 "```json")。 | |
| 请严格遵循以下JSON结构: | |
| { | |
| "image_features": ["从图像中识别出的关键皮损形态学特征列表", "例如:色素网络不规则", "例如:蓝白结构"], | |
| "differential_diagnosis": [ | |
| { "diagnosis": "可能性最高的诊断名称", "likelihood": "高", "evidence": "支持该诊断的关键图像和文本依据" }, | |
| { "diagnosis": "可能性次之的诊断名称", "likelihood": "中", "evidence": "支持该诊断的关键依据" } | |
| ], | |
| "comprehensive_analysis": "一段对整个病情的全面、综合性分析和总结。", | |
| "recommendations": { | |
| "further_examinations": ["建议的下一步检查列表", "例如:皮肤镜检查", "例如:皮肤活检"], | |
| "treatment_suggestions": ["初步的、符合临床指南的治疗方向建议列表", "例如:外用糖皮质激素", "例如:建议手术切除"] | |
| } | |
| } | |
| """ | |
| def health_check(): | |
| """专门用于平台健康检查的路由,确保100%稳定""" | |
| return "OK", 200 | |
| def index(): | |
| """提供前端HTML页面""" | |
| return send_from_directory(app.static_folder, 'index.html') | |
| def analyze_skin(): | |
| """处理分析请求的核心API端点""" | |
| if not GEMINI_API_KEY: | |
| return jsonify({"error": "服务端未配置GEMINI_API_KEY"}), 500 | |
| data = request.json | |
| if not data or 'image' not in data or 'text' not in data: | |
| return jsonify({"error": "请求中缺少图像或文本信息"}), 400 | |
| image_base64 = data.get('image') | |
| text_prompt = data.get('text') | |
| headers = {'Content-Type': 'application/json'} | |
| payload = { | |
| "contents": [{"parts": [ | |
| {"text": SYSTEM_PROMPT}, | |
| {"text": f"临床病历信息如下:\n{text_prompt}"}, | |
| {"inline_data": {"mime_type": "image/jpeg", "data": image_base64}} | |
| ]}] | |
| } | |
| try: | |
| response = requests.post(f"{GEMINI_API_URL}?key={GEMINI_API_KEY}", headers=headers, json=payload, timeout=60) | |
| response.raise_for_status() | |
| gemini_result = response.json() | |
| # 稳健地提取内容 | |
| analysis_content_string = gemini_result['candidates']['content']['parts']['text'] | |
| parsed_json = json.loads(analysis_content_string) | |
| return jsonify(parsed_json) | |
| except requests.exceptions.RequestException as e: | |
| return jsonify({"error": f"调用Gemini API时发生网络错误: {e}"}), 500 | |
| except (KeyError, IndexError, TypeError): | |
| error_details = response.json() if 'response' in locals() else "No response from API" | |
| return jsonify({"error": "解析Gemini API响应失败,格式不正确", "details": error_details}), 500 | |
| except json.JSONDecodeError: | |
| return jsonify({"error": "Gemini API未返回有效的JSON格式", "details": analysis_content_string}), 500 | |
| except Exception as e: | |
| return jsonify({"error": f"发生未知错误: {e}"}), 500 | |
| if __name__ == '__main__': | |
| app.run(host='0.0.0.0', port=8080) |