Spaces:
Sleeping
Sleeping
File size: 2,993 Bytes
30b1610 08681f4 30b1610 08681f4 30b1610 08681f4 30b1610 08681f4 30b1610 08681f4 22cec65 08681f4 22cec65 08681f4 22cec65 08681f4 30b1610 08681f4 30b1610 08681f4 30b1610 08681f4 30b1610 08681f4 30b1610 08681f4 30b1610 08681f4 30b1610 08681f4 30b1610 08681f4 30b1610 08681f4 2d5b673 b1482b2 30b1610 08681f4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
import gradio as gr
import json
import importlib
import os
from pathlib import Path
def evaluate(input_data):
"""评估代码的主函数
Args:
input_data: 可以是字符串(文件路径)或字典(包含代码信息)
Returns:
dict: 包含评估结果的字典
"""
try:
# 如果输入是文件路径
if isinstance(input_data, str):
with open(input_data, 'r') as f:
code = f.read()
# 从文件扩展名确定语言
language = Path(input_data).suffix[1:]
result = evaluate_code(code, language)
return result
# 如果输入是字典
elif isinstance(input_data, dict):
language = input_data.get('language')
completions = input_data.get('completions', [])
if not completions:
return {"status": "Exception", "error": "No code provided"}
# 评估所有完成的代码
results = []
for code in completions:
result = evaluate_code(code, language)
results.append(result)
# 如果任一代码执行成功,则返回成功
if any(r["status"] == "OK" for r in results):
return {"status": "pass"}
else:
return results[0] # 返回第一个失败结果
else:
return {"status": "Exception", "error": "Invalid input format"}
except Exception as e:
return {"status": "Exception", "error": str(e)}
def evaluate_code(code, language):
"""评估特定语言的代码
Args:
code (str): 要评估的代码
language (str): 编程语言
Returns:
dict: 包含评估结果的字典
"""
try:
# 动态导入对应语言的评估模块
module_name = f"src.eval_{language.lower()}"
module = importlib.import_module(module_name)
# 创建临时文件存储代码
temp_dir = Path("temp")
temp_dir.mkdir(exist_ok=True)
temp_file = temp_dir / f"temp.{language}"
with open(temp_file, "w") as f:
f.write(code)
# 调用对应语言的评估函数
result = module.eval_script(temp_file)
# 清理临时文件
if temp_file.exists():
temp_file.unlink()
return result
except ImportError:
return {"status": "Exception", "error": f"Language {language} not supported"}
except Exception as e:
return {"status": "Exception", "error": str(e)}
# 创建Gradio接口
demo = gr.Interface(
fn=evaluate,
inputs=gr.JSON(),
outputs=gr.JSON(),
title="代码评估服务",
description="支持多种编程语言的代码评估服务",
api_name="/evaluate" # 修改为带有前导斜杠的API名称
)
if __name__ == "__main__":
demo.launch()
|