| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113 |
- from flask import Flask, request, jsonify
- from flask_cors import CORS # 跨域支持
- from typing import Dict, Any, List
- import logging
- import traceback
- from chat import gen_title, generate_text
- app = Flask(__name__)
- CORS(app) # 允许所有域访问(生产环境应限制)
- logging.basicConfig(level=logging.INFO)
- logger = logging.getLogger("TextGenerationAPI")
- @app.route('/api/description', methods=['POST'])
- def request_description():
- """文本生成核心接口
-
- 请求体要求(JSON格式):
- {
- "plm_info": "商品详细信息文本",
- "img": "https://example.com/image.jpg",
- "graphic_label": ["标签1", "标签2"]
- }
- """
- try:
- data = request.get_json()
- if not data:
- return jsonify({"error": "请求体必须为JSON格式"}), 400
-
- logger.info(f"收到请求数据:{data}")
- required_fields = ["spu","reference_url",'plm_info', 'img', 'graphic_label']
- missing = [field for field in required_fields if field not in data]
- if missing:
- return jsonify({"error": f"缺少必要字段: {missing}"}), 400
- if not isinstance(data['graphic_label'], list) or \
- not all(isinstance(item, str) for item in data['graphic_label']):
- return jsonify({"error": "graphic_label必须是字符串列表"}), 400
- en,kw = generate_text(
- plm_info=data['plm_info'],
- img=data['img'],
- graphic_label=data['graphic_label']
- )
- return jsonify({
- "spu": data['spu'], # 示例请求ID(实际应生成唯一标识)
- "result":{"descr":en,
- "keywords":kw}
- }), 200
-
- except Exception as e:
- logger.error(f"处理失败: {str(e)}\n{traceback.format_exc()}")
- return jsonify({
- "error": "服务器内部错误",
- "detail": str(e)
- }), 500
-
- @app.route('/api/title', methods=['POST'])
- def request_title():
- """文本生成核心接口
-
- 请求体要求(JSON格式):
- {
- "plm_info": "商品详细信息文本",
- "img": "https://example.com/image.jpg",
- "graphic_label": ["标签1", "标签2"]
- }
- """
- try:
- data = request.get_json()
- if not data:
- return jsonify({"error": "请求体必须为JSON格式"}), 400
-
- logger.info(f"收到请求数据:{data}")
- required_fields = ["spu","reference_title",'desc', 'tags']
- missing = [field for field in required_fields if field not in data]
- if missing:
- return jsonify({"error": f"缺少必要字段: {missing}"}), 400
- logger.info(f"11111111111数据完整:{data}")
-
- if not isinstance(data['tags'], list) or \
- not all(isinstance(item, str) for item in data['tags']) :
- return jsonify({"error": "tags必须是字符串列表"}), 400
-
- logger.info(f"数据完整:{data}")
- result = gen_title(
- info=data['desc'],
- tags=data['tags'],
- referencr_title=data["reference_title"]
- )
-
- # 5. 构造标准化响应
- return jsonify({
- "spu": data['spu'], # 示例请求ID(实际应生成唯一标识)
- "result":result
- }), 200
-
- except Exception as e:
- # 异常处理与日志记录
- logger.error(f"处理失败: {str(e)}\n{traceback.format_exc()}")
- return jsonify({
- "error": "服务器内部错误",
- "detail": str(e)
- }), 500
- if __name__ == '__main__':
- # 启动服务(生产环境应使用WSGI服务器)
- app.run(host='0.0.0.0', port=6868, debug=False)
|