Commit e8747185 by xuxingxing

initial commit

parents
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AnalysisProjectProfileManager">
<option name="PROJECT_PROFILE" />
<option name="USE_PROJECT_LEVEL_SETTINGS" value="false" />
<list size="0" />
</component>
<component name="SuppressionsComponent">
<option name="suppComments" value="[]" />
</component>
</project>
\ No newline at end of file
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CheckstyleConfigurable">
<option name="suppFilterFilename" value="" />
<option name="suppCommentFilter" value="false" />
<option name="offComment" value="CHECKSTYLE\:OFF" />
<option name="onComment" value="CHECKSTYLE\:ON" />
<option name="checkFormat" value=".*" />
<option name="messageFormat" value="" />
<option name="checkCPP" value="true" />
<option name="checkC" value="true" />
<option name="suppNearbyCommentFilter" value="false" />
<option name="snCommentFormat" value="SUPPRESS CHECKSTYLE (\w+)" />
<option name="snCheckFormat" value="$1" />
<option name="snMessageFormat" value="" />
<option name="snInfluenceFormat" value="0" />
<option name="snCheckCPP" value="true" />
<option name="snCheckC" value="true" />
<option name="pathToUserRulesConfiguration" value="" />
<option name="pathToJarWithRules" value="" />
</component>
<component name="FindBugsConfigurable">
<option name="make" value="true" />
<option name="effort" value="default" />
<option name="priority" value="Medium" />
<option name="excludeFilter" value="" />
</component>
<component name="GOROOT" url="file:///usr/local/go" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" project-jdk-name="Python 3.11" project-jdk-type="Python SDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
<component name="SuppressionsComponent">
<option name="suppComments" value="[]" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/image.iml" filepath="$PROJECT_DIR$/image.iml" />
</modules>
</component>
</project>
\ No newline at end of file
1.安装必要依赖
pip install -r requirements.txt
2.运行服务
python app.py
3.测试接口: 使用工具(如 Postman 或 curl)测试
curl --location --request POST 'http://127.0.0.1:5001/predict' \
--header 'Content-Type: application/json' \
--header 'Signature: "just for test"' \
--header 'TimeStamp: 1733802424' \
--data-raw '{
"url": "https://dianlv-res.oss-cn-shenzhen.aliyuncs.com/exportFiles/1_265261960876529885.jpg",
"tenantID": 1
}'
\ No newline at end of file
from flask import Flask, request, jsonify
from model import load_model, predict
from PIL import Image
import requests
from io import BytesIO
app = Flask(__name__)
# 加载模型
model, preprocess, device = load_model()
@app.route('/predict', methods=['POST'])
def classify_image():
# 获取请求头
_s = request.headers.get('Signature')
_t = request.headers.get('TimeStamp')
if not _s or not _t:
return jsonify({"error": "Missing required headers '_s' or '_t'"}), 400
# 从请求中获取图片 URL
data = request.json
if 'url' not in data:
return jsonify({'error': 'Image URL is required'}), 400
image_url = data['url']
try:
# 下载图片并加载为Pillow Image
response = requests.get(image_url)
response.raise_for_status()
input_image = Image.open(BytesIO(response.content))
except Exception as e:
return jsonify({'error': f'Failed to load image: {str(e)}'}), 400
# 执行推理
try:
result, inference_time = predict(model, preprocess, device, input_image)
return jsonify({
'succses': True,
'code': 0,
'message': "",
'data':
{
'predicted_class': result['predicted_class'],
'probabilities': result['probabilities'],
'inference_time': inference_time
}
})
except Exception as e:
return jsonify({'error': f'Prediction failed: {str(e)}'}), 500
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5001)
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
import torch
import torch.nn as nn
from torchvision import models, transforms
import time
def load_model():
# 定义预处理步骤
preprocess = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
# 加载模型
model = models.resnet18(weights="IMAGENET1K_V1")
model.fc = nn.Linear(model.fc.in_features, 2) # 修改为2分类
model.load_state_dict(torch.load('./pth/trained_model.pth', map_location=torch.device('cpu')))
model.eval()
# 使用CPU或GPU
device = torch.device('cpu')
model = model.to(device)
return model, preprocess, device
def predict(model, preprocess, device, input_image):
# 预处理图像
input_tensor = preprocess(input_image)
input_batch = input_tensor.unsqueeze(0).to(device)
# 测量推理时间
start_time = time.time()
with torch.no_grad():
output = model(input_batch)
probabilities = torch.softmax(output, dim=1)
end_time = time.time()
# 获取预测结果
_, predicted = torch.max(output, 1)
result = {
'predicted_class': predicted.item(),
'probabilities': [prob.item() for prob in probabilities[0]]
}
inference_time = end_time - start_time
return result, inference_time
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment