tianxiangxing commited on
Commit
0277e30
·
1 Parent(s): bbbc3e5

edit to flask

Browse files
Files changed (2) hide show
  1. app.py +87 -12
  2. requirements.txt +19 -10
app.py CHANGED
@@ -1,22 +1,48 @@
1
- from flask import Flask, request, jsonify
2
- import joblib
3
- from PIL import Image
4
  import numpy as np
 
 
 
 
 
 
5
 
6
- app = Flask(__name__)
7
-
8
- # 加载模型
9
- model = joblib.load('skin_cancer_model.pkl')
10
 
11
- # 图像预处理
12
  def preprocess_image(image):
13
- size = (224, 224)
14
  image = image.resize(size)
15
  image_array = np.array(image) / 255.0
16
  image_flattened = image_array.flatten()
17
  return [image_flattened]
18
 
19
- # 接收图像并分析
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  @app.route('/analyze', methods=['POST'])
21
  def analyze():
22
  file = request.files['image']
@@ -27,5 +53,54 @@ def analyze():
27
  result = class_names[prediction]
28
  return jsonify({"result": result})
29
 
30
- if __name__ == "__main__":
31
- app.run()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
 
 
2
  import numpy as np
3
+ from PIL import Image
4
+ import joblib
5
+ from flask import Flask, request, jsonify
6
+ from streamlit_webrtc import webrtc_streamer, VideoTransformerBase
7
+ import cv2
8
+ import threading
9
 
10
+ # 加载训练好的模型
11
+ model_file_path = 'skin_cancer_model.pkl'
12
+ model = joblib.load(model_file_path)
 
13
 
14
+ # 图像预处理函数
15
  def preprocess_image(image):
16
+ size = (224, 224) # 模型输入尺寸
17
  image = image.resize(size)
18
  image_array = np.array(image) / 255.0
19
  image_flattened = image_array.flatten()
20
  return [image_flattened]
21
 
22
+ # 定义视频转换器类,处理视频帧
23
+ class VideoTransformer(VideoTransformerBase):
24
+ def transform(self, frame):
25
+ img = frame.to_ndarray(format="bgr24")
26
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
27
+
28
+ # 预处理图像
29
+ img_resized = cv2.resize(img, (224, 224))
30
+ img_resized = img_resized.astype("float32") / 255.0
31
+ img_resized = np.expand_dims(img_resized, axis=0)
32
+
33
+ # 模型预测
34
+ prediction = model.predict(img_resized)
35
+ predicted_class = np.argmax(prediction, axis=1)[0]
36
+
37
+ # 在 Streamlit 中显示预测结果
38
+ st.write(f"Skin Cancer Prediction (Video): {predicted_class}")
39
+
40
+ return img
41
+
42
+ # Flask 应用设置
43
+ app = Flask(__name__)
44
+
45
+ # 接收图像并通过模型分析
46
  @app.route('/analyze', methods=['POST'])
47
  def analyze():
48
  file = request.files['image']
 
53
  result = class_names[prediction]
54
  return jsonify({"result": result})
55
 
56
+ # 运行 Flask 应用
57
+ def run_flask():
58
+ app.run(host='0.0.0.0', port=8000)
59
+
60
+ # 主程序 - Streamlit UI 和交互逻辑
61
+ def main():
62
+ st.title("Skin Diagnosis")
63
+
64
+ st.write(
65
+ "Please note that this app is not 100% accurate. If your result happens to be malignant, please contact a medical professional for further instructions.")
66
+
67
+ # 实时视频诊断
68
+ st.header("Real-Time Video Diagnosis")
69
+ webrtc_streamer(key="example", video_processor_factory=VideoTransformer)
70
+
71
+ # 图像上传与预测
72
+ st.header("Image Upload Diagnosis")
73
+ st.write("**Upload an image to detect if it's benign or malignant:**")
74
+
75
+ uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
76
+
77
+ if uploaded_file is not None:
78
+ image = Image.open(uploaded_file)
79
+ st.image(image, caption='Uploaded Image', use_column_width=True)
80
+
81
+ # 预处理图像
82
+ processed_image = preprocess_image(image)
83
+
84
+ # 模型预测
85
+ prediction = model.predict([processed_image])[0]
86
+ class_names = {0: 'Benign', 1: 'Malignant'}
87
+ result = class_names[prediction]
88
+
89
+ st.write(f"Skin Cancer Prediction (Image): {result}")
90
+
91
+ # 阳光暴露选项
92
+ st.write("**Have you had a large amount of sun exposure recently?**")
93
+ result = st.button("Yes")
94
+ if result:
95
+ st.write(
96
+ "Please note that high levels of sun exposure can increase the risk of skin cancer. Be cautious and consider regular skin check-ups.")
97
+
98
+ # 使用线程并行运行 Flask 和 Streamlit
99
+ if __name__ == '__main__':
100
+ # 启动 Flask 服务器线程
101
+ flask_thread = threading.Thread(target=run_flask)
102
+ flask_thread.daemon = True
103
+ flask_thread.start()
104
+
105
+ # 运行 Streamlit 前端
106
+ main()
requirements.txt CHANGED
@@ -1,29 +1,38 @@
1
  # Streamlit for the frontend interface
2
- streamlit==1.15.2
3
 
4
  # Flask for backend API
5
- Flask==2.1.0 # 版本与 Werkzeug 兼容
6
 
7
  # Werkzeug for Flask compatibility
8
- Werkzeug==2.1.2 # 与 Flask 2.1.0 兼容的版本
9
 
10
  # Joblib for loading and saving models
11
- joblib==1.1.0
12
 
13
  # Numpy for numerical computations
14
- numpy==1.21.6
15
 
16
  # Scipy for scientific computing (required by scikit-learn)
17
- scipy==1.7.3
18
 
19
  # Scikit-learn for machine learning model
20
- scikit-learn==1.0.2
21
 
22
  # PIL (Python Imaging Library) for image processing
23
- Pillow==9.0.1
24
 
25
  # OpenCV for image and video processing
26
- opencv-python-headless==4.5.5.62
27
 
28
  # Streamlit WebRTC for video streaming
29
- streamlit-webrtc==0.30.0
 
 
 
 
 
 
 
 
 
 
1
  # Streamlit for the frontend interface
2
+ streamlit
3
 
4
  # Flask for backend API
5
+ Flask
6
 
7
  # Werkzeug for Flask compatibility
8
+ Werkzeug
9
 
10
  # Joblib for loading and saving models
11
+ joblib
12
 
13
  # Numpy for numerical computations
14
+ numpy
15
 
16
  # Scipy for scientific computing (required by scikit-learn)
17
+ scipy
18
 
19
  # Scikit-learn for machine learning model
20
+ scikit-learn
21
 
22
  # PIL (Python Imaging Library) for image processing
23
+ Pillow
24
 
25
  # OpenCV for image and video processing
26
+ opencv-python-headless
27
 
28
  # Streamlit WebRTC for video streaming
29
+ streamlit-webrtc
30
+
31
+ # (Optional) Flask-CORS for handling CORS requests in Flask
32
+ Flask-Cors
33
+
34
+ # (Optional) Requests for sending HTTP requests
35
+ requests
36
+
37
+ # (Optional) Python-dotenv for managing environment variables
38
+ python-dotenv