Spaces:
Sleeping
Sleeping
Update app.py
Browse files6 unmodified lines7891011121314151617181921 unmodified lines414243444546474810 unmodified lines596061626364656667686970717273747576777879808182838485868788899091926 unmodified lines# 初始化Flask应用app = Flask(__name__)# 配置日志logging.basicConfig(level=logging.INFO)app.logger = logging.getLogger("CodeSearchAPI")# 预定义代码片段CODE_SNIPPETS = ["""def sort_list(x): return sorted(x)""","""def count_above_threshold(elements, threshold=0):return sum(1 for e in elements if e > threshold)""","""def find_min_max(elements):21 unmodified lines# 预计算编码(强制使用CPU)code_emb = model.encode(CODE_SNIPPETS,convert_to_tensor=True,device="cpu")service_ready = Trueapp.logger.info("服务初始化完成")10 unmodified lineselse:return jsonify({"status": "initializing"}), 503# 搜索API端点@app.route('/search', methods=['POST'])def handle_search():if not service_ready:return jsonify({"error": "服务正在初始化"}), 503try:data = request.get_json()query = data.get('query', '').strip()if not query:return jsonify({"error": "查询不能为空"}), 400query_emb = model.encode(query,convert_to_tensor=True,device="cpu")hits = util.semantic_search(query_emb, code_emb, top_k=1)[0]best = hits[0]return jsonify({"code": CODE_SNIPPETS[best['corpus_id']],"score": round(float(best['score']), 4)})except Exception as e:app.logger.error(f"请求处理失败: {str(e)}")return jsonify({"error": "服务器内部错误"}), 500if __name__ == "__main__":# Hugging Face Spaces会通过gunicorn启动,此处仅为本地测试保留app.run(host='0.0.0.0', port=7860)6 unmodified lines7891011121314151617181921 unmodified lines414243444546474810 unmodified lines59606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041056 unmodified lines# 初始化Flask应用app = Flask(__name__)# 配置日志,日志级别设为INFOlogging.basicConfig(level=logging.INFO)app.logger = logging.getLogger("CodeSearchAPI")# 预定义代码片段CODE_SNIPPETS = ["def sort_list(x): return sorted(x)","""def count_above_threshold(elements, threshold=0):return sum(1 for e in elements if e > threshold)""","""def find_min_max(elements):21 unmodified lines# 预计算编码(强制使用CPU)code_emb = model.encode(CODE_SNIPPETS,convert_to_tensor=True,device="cpu")service_ready = Trueapp.logger.info("服务初始化完成")10 unmodified lineselse:return jsonify({"status": "initializing"}), 503# 支持GET和POST请求的搜索API端点@app.route('/search', methods=['GET', 'POST'])def handle_search():if not service_ready:return jsonify({"error": "服务正在初始化"}), 503try:# 区分GET和POST请求,GET从URL参数中获取query,POST从JSON体中获取if request.method == 'GET':query = request.args.get('query', '').strip()else:data = request.get_json() or {}query = data.get('query', '').strip()if not query:app.logger.info("收到空的查询请求")return jsonify({"error": "查询不能为空"}), 400# 记录接收到的查询app.logger.info("收到查询请求: %s", query)# 对查询进行编码,并搜索最匹配的代码片段query_emb = model.encode(query,convert_to_tensor=True,device="cpu")hits = util.semantic_search(query_emb, code_emb, top_k=1)[0]best = hits[0]result = {"code": CODE_SNIPPETS[best['corpus_id']],"score": round(float(best['score']), 4)}# 记录返回结果app.logger.info("返回结果: %s", result)return jsonify(result)except Exception as e:app.logger.error("请求处理失败: %s", str(e))return jsonify({"error": "服务器内部错误"}), 500if __name__ == "__main__":# Hugging Face Spaces会通过gunicorn启动,此处仅为本地测试保留app.run(host='0.0.0.0', port=7860)
app.py+31-18