| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140 |
- from flask import Flask, request, jsonify
- # from flask_cors import CORS # 跨域支持
- from typing import Dict, Any, List
- import traceback
- import logging
- # 首先导入日志配置模块,确保日志系统在导入其他模块之前就配置好
- import logger_config
- # 确保日志系统已正确配置(因为可能多次导入,特别是gunicorn多worker情况下)
- logger_config.setup_logging()
- # 获取应用日志器
- logger = logger_config.get_logger("TextGenerationAPI")
- # 现在导入chat模块(它会导入conf等模块,此时日志已经配置好了)
- from chat import gen_title, generate_text, check_image_url
- # 验证chat和llm模块的logger是否正确配置(在导入后验证)
- chat_logger = logging.getLogger("chat")
- llm_logger = logging.getLogger("llm")
- # 确保chat和llm的logger有handler(通过propagate到root logger)
- chat_logger.propagate = True
- llm_logger.propagate = True
- logger.info("Flask应用启动,日志系统已初始化")
- logger.info(f"chat模块logger级别: {chat_logger.getEffectiveLevel()}, llm模块logger级别: {llm_logger.getEffectiveLevel()}")
- logger.info(f"根logger级别: {logging.root.getEffectiveLevel()}, handlers数量: {len(logging.root.handlers)}")
- app = Flask(__name__)
- # CORS(app) # 允许所有域访问(生产环境应限制)
- @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": "The request body must be in JSON format."}), 400
-
- logger.info(f"收到请求数据:{data}")
- required_fields = ["spu",'plm_info', 'img', 'graphic_label']
- if 'plm_info' not in data or len(data["plm_info"])<1:
- return jsonify({"error": f"Contact the designer to maintain product selling points data(plm_info)"}), 400
- missing = [field for field in required_fields if field not in data]
- if missing:
- return jsonify({"error": f"Necessary values are missing: {missing}"}), 400
- is_valid, message=check_image_url(data['img'])
- if not is_valid:
- return jsonify({"error": message}), 400
- if not isinstance(data['graphic_label'], list) or \
- not all(isinstance(item, str) for item in data['graphic_label']):
- return jsonify({"error": "The graphic_label must be a list of strings."}), 400
- en,kw = generate_text(
- plm_info=data['plm_info'],
- img=data['img'],
- graphic_label=data['graphic_label']
- )
- logger.info(f"生成描述:{en}")
- logger.info(f"生成关键词:{kw}")
- 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": "Internal server 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(force=True)
- if not data:
- return jsonify({"error": "The request body must be in JSON format."}), 400
-
- logger.info(f"收到请求数据:{data}")
- required_fields = ["spu",'desc']
- missing = [field for field in required_fields if field not in data]
- if missing:
- return jsonify({"error": f"Necessary values are missing: {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": "The tags must be a list of strings."}), 400
- reference_title = data.get("reference_title", "")
- tags = data.get("tags", "")
- logger.info(f"数据完整:{data}")
- result = gen_title(
- info=data['desc'],
- tags=tags,
- referencr_title=reference_title
- )
- logger.info(f"生成标题:{result}")
- # 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=5555, debug=False)
|