leonsimon23 commited on
Commit
fe9b8a5
·
verified ·
1 Parent(s): c888602

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +13 -31
app.py CHANGED
@@ -3,7 +3,6 @@ import base64
3
  import requests
4
  import json
5
  from flask import Flask, render_template, request, jsonify
6
- from werkzeug.utils import secure_filename
7
  from PIL import Image
8
  import io
9
 
@@ -12,7 +11,7 @@ app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024 # 10MB max file size
12
 
13
  # Gemini API configuration
14
  GEMINI_API_KEY = os.environ.get('GEMINI_API_KEY')
15
- GEMINI_API_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-exp:generateContent"
16
 
17
  ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
18
 
@@ -20,13 +19,13 @@ def allowed_file(filename):
20
  return '.' in filename and \
21
  filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
22
 
23
- # 优化图像函数不需要改动
24
- def optimize_image(image_file, max_size=(1024, 1024), quality=85):
25
  """优化图像大小和质量"""
26
  try:
27
- img = Image.open(image_file)
 
28
 
29
- # Convert RGBA to RGB if necessary
30
  if img.mode in ('RGBA', 'LA'):
31
  background = Image.new('RGB', img.size, (255, 255, 255))
32
  if img.mode == 'RGBA':
@@ -35,10 +34,8 @@ def optimize_image(image_file, max_size=(1024, 1024), quality=85):
35
  background.paste(img, mask=img.split()[-1])
36
  img = background
37
 
38
- # Resize if too large
39
  img.thumbnail(max_size, Image.Resampling.LANCZOS)
40
 
41
- # Save to bytes
42
  img_byte_arr = io.BytesIO()
43
  img.save(img_byte_arr, format='JPEG', quality=quality, optimize=True)
44
  img_byte_arr.seek(0)
@@ -46,18 +43,16 @@ def optimize_image(image_file, max_size=(1024, 1024), quality=85):
46
  return img_byte_arr.getvalue()
47
  except Exception as e:
48
  print(f"Image optimization error: {e}")
49
- # Fallback: return original file data
50
- image_file.seek(0)
51
- return image_file.read()
52
 
53
- # call_gemini_api 函数不需要改动
54
  def call_gemini_api(text_content=None, image_data=None):
55
  """调用Gemini API进行分析"""
56
 
57
  if not GEMINI_API_KEY:
58
  return {"error": "未配置Gemini API密钥,请设置环境变量GEMINI_API_KEY"}
59
 
60
- # 构建专业的皮肤科医生prompt
61
  system_prompt = """你是一位经验丰富的皮肤科专家医生,具有多年的临床诊疗经验。请基于提供的信息进行专业的皮肤病分析。
62
 
63
  分析要求:
@@ -98,18 +93,14 @@ def call_gemini_api(text_content=None, image_data=None):
98
  ---
99
  **免责声明**: 此分析仅供临床参考,最终诊断需结合完整病史、体格检查等综合判断。建议患者及时就医,接受专业医师诊疗。"""
100
 
101
- # 构建请求内容
102
  parts = []
103
 
104
- # 添加系统提示和文本内容
105
  if text_content:
106
  parts.append({"text": f"{system_prompt}\n\n患者症状描述:{text_content}"})
107
  else:
108
  parts.append({"text": system_prompt + "\n\n请基于图像进行分析。"})
109
 
110
- # 添加图像数据
111
  if image_data:
112
- # 转换为base64
113
  image_base64 = base64.b64encode(image_data).decode('utf-8')
114
  parts.append({
115
  "inline_data": {
@@ -118,7 +109,6 @@ def call_gemini_api(text_content=None, image_data=None):
118
  }
119
  })
120
 
121
- # 构建请求体
122
  request_body = {
123
  "contents": [
124
  {
@@ -126,7 +116,7 @@ def call_gemini_api(text_content=None, image_data=None):
126
  }
127
  ],
128
  "generationConfig": {
129
- "temperature": 0.1, # 降低随机性,提高专业性
130
  "topK": 40,
131
  "topP": 0.95,
132
  "maxOutputTokens": 2048,
@@ -151,7 +141,6 @@ def call_gemini_api(text_content=None, image_data=None):
151
  ]
152
  }
153
 
154
- # 发送请求
155
  headers = {
156
  'Content-Type': 'application/json',
157
  'x-goog-api-key': GEMINI_API_KEY
@@ -168,7 +157,6 @@ def call_gemini_api(text_content=None, image_data=None):
168
  response.raise_for_status()
169
  result = response.json()
170
 
171
- # 解析响应
172
  if 'candidates' in result and len(result['candidates']) > 0:
173
  content = result['candidates'][0]['content']['parts'][0]['text']
174
  return {"result": content}
@@ -197,30 +185,24 @@ def analyze():
197
  text_content = request.form.get('text', '').strip()
198
  image_data = None
199
 
200
- # 修复图像处理逻辑
201
  if 'image' in request.files:
202
  file = request.files['image']
203
  if file.filename != '':
204
  if allowed_file(file.filename):
205
  try:
206
- # 从 FileStorage 对象中直接读取数据
207
- image_data = file.read()
208
 
209
- # 确保文件指针回到开头,以便 optimize_image 函数能正确读取
210
- file.seek(0)
211
-
212
- # 优化图像
213
- image_data = optimize_image(file)
214
  except Exception as e:
215
  return jsonify({"error": f"图像处理失败: {str(e)}"}), 400
216
  else:
217
  return jsonify({"error": "不支持的文件格式,请上传PNG、JPG、JPEG或GIF格式的图像"}), 400
218
 
219
- # 验证输入
220
  if not text_content and not image_data:
221
  return jsonify({"error": "请至少提供症状描述或上传皮肤图像"}), 400
222
 
223
- # 调用Gemini API
224
  result = call_gemini_api(text_content, image_data)
225
 
226
  return jsonify(result)
 
3
  import requests
4
  import json
5
  from flask import Flask, render_template, request, jsonify
 
6
  from PIL import Image
7
  import io
8
 
 
11
 
12
  # Gemini API configuration
13
  GEMINI_API_KEY = os.environ.get('GEMINI_API_KEY')
14
+ GEMINI_API_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent"
15
 
16
  ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
17
 
 
19
  return '.' in filename and \
20
  filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
21
 
22
+ # 优化图像函数,现在接受字节数据作为输入
23
+ def optimize_image(image_bytes, max_size=(1024, 1024), quality=85):
24
  """优化图像大小和质量"""
25
  try:
26
+ # 使用 io.BytesIO 将字节数据转换为文件对象,供 Pillow 使用
27
+ img = Image.open(io.BytesIO(image_bytes))
28
 
 
29
  if img.mode in ('RGBA', 'LA'):
30
  background = Image.new('RGB', img.size, (255, 255, 255))
31
  if img.mode == 'RGBA':
 
34
  background.paste(img, mask=img.split()[-1])
35
  img = background
36
 
 
37
  img.thumbnail(max_size, Image.Resampling.LANCZOS)
38
 
 
39
  img_byte_arr = io.BytesIO()
40
  img.save(img_byte_arr, format='JPEG', quality=quality, optimize=True)
41
  img_byte_arr.seek(0)
 
43
  return img_byte_arr.getvalue()
44
  except Exception as e:
45
  print(f"Image optimization error: {e}")
46
+ # 优化失败,返回原始字节数据
47
+ return image_bytes
 
48
 
49
+ # call_gemini_api 函数
50
  def call_gemini_api(text_content=None, image_data=None):
51
  """调用Gemini API进行分析"""
52
 
53
  if not GEMINI_API_KEY:
54
  return {"error": "未配置Gemini API密钥,请设置环境变量GEMINI_API_KEY"}
55
 
 
56
  system_prompt = """你是一位经验丰富的皮肤科专家医生,具有多年的临床诊疗经验。请基于提供的信息进行专业的皮肤病分析。
57
 
58
  分析要求:
 
93
  ---
94
  **免责声明**: 此分析仅供临床参考,最终诊断需结合完整病史、体格检查等综合判断。建议患者及时就医,接受专业医师诊疗。"""
95
 
 
96
  parts = []
97
 
 
98
  if text_content:
99
  parts.append({"text": f"{system_prompt}\n\n患者症状描述:{text_content}"})
100
  else:
101
  parts.append({"text": system_prompt + "\n\n请基于图像进行分析。"})
102
 
 
103
  if image_data:
 
104
  image_base64 = base64.b64encode(image_data).decode('utf-8')
105
  parts.append({
106
  "inline_data": {
 
109
  }
110
  })
111
 
 
112
  request_body = {
113
  "contents": [
114
  {
 
116
  }
117
  ],
118
  "generationConfig": {
119
+ "temperature": 0.1,
120
  "topK": 40,
121
  "topP": 0.95,
122
  "maxOutputTokens": 2048,
 
141
  ]
142
  }
143
 
 
144
  headers = {
145
  'Content-Type': 'application/json',
146
  'x-goog-api-key': GEMINI_API_KEY
 
157
  response.raise_for_status()
158
  result = response.json()
159
 
 
160
  if 'candidates' in result and len(result['candidates']) > 0:
161
  content = result['candidates'][0]['content']['parts'][0]['text']
162
  return {"result": content}
 
185
  text_content = request.form.get('text', '').strip()
186
  image_data = None
187
 
 
188
  if 'image' in request.files:
189
  file = request.files['image']
190
  if file.filename != '':
191
  if allowed_file(file.filename):
192
  try:
193
+ # 核心修复:一次性将文件流读入内存
194
+ original_image_bytes = file.read()
195
 
196
+ # 调用优化函数,它现在接受字节数据
197
+ image_data = optimize_image(original_image_bytes)
 
 
 
198
  except Exception as e:
199
  return jsonify({"error": f"图像处理失败: {str(e)}"}), 400
200
  else:
201
  return jsonify({"error": "不支持的文件格式,请上传PNG、JPG、JPEG或GIF格式的图像"}), 400
202
 
 
203
  if not text_content and not image_data:
204
  return jsonify({"error": "请至少提供症状描述或上传皮肤图像"}), 400
205
 
 
206
  result = call_gemini_api(text_content, image_data)
207
 
208
  return jsonify(result)