Spaces:
Runtime error
Runtime error
import gradio as gr | |
import spacy | |
import textdistance | |
nlp = spacy.load("zh_core_web_sm") | |
def game_starts(): | |
return "星期天,你是一名侦探,小兔子被杀了,她的室友有三人。" | |
def extract_command(doc): | |
for ent in doc.ents: | |
if ent.label_ == "COMMAND": | |
return ent.text.lower() | |
def get_best_match(input_text, options): | |
distances = {option: textdistance.jaro_winkler.similarity(input_text, option) for option in options} | |
return max(distances, key=distances.get) | |
def game(player_input): | |
# 解析玩家输入 | |
doc = nlp(player_input) | |
command = extract_command(doc) | |
if command: | |
# 匹配已知的操作指令 | |
if command in ["看", "案情"]: | |
return "小兔子被刺伤在胸口,现场找到一把锋利的刀。" | |
elif command in ["查", "室友"]: | |
return "1.王某:晚上一直在家陪女友看电影。\ | |
2.李某:说自己去了夜店,和朋友喝了一晚,但没有人能为他作证。\ | |
3.张某:嫌疑人目击证言显示她在案发当晚凌晨在小兔子的房间里。" | |
elif command in ["抓", "凶手"]: | |
return "恭喜你,成功找到了凶手并将 TA 抓获!" | |
else: | |
return "你的操作有误,请重新输入。" | |
else: | |
# 没有明确的操作指令,我们会尝试从包含关键词的短语中获得更多的线索 | |
search_phrases = {ent.text.lower() for ent in doc.ents if ent.label_ == "SEARCH_PHRASE"} | |
if search_phrases: | |
# 获取受支持的搜索短语列表 | |
keyword_lists = { | |
"看": ["案情", "现场", "凶器", "证人"], | |
"查": ["室友", "目击证言"], | |
"抓": ["凶手", "嫌疑人", "线索"] | |
} | |
options = [] | |
for command, keywords in keyword_lists.items(): | |
for keyword in keywords: | |
phrase = f"{command}{keyword}" | |
options.append(phrase) | |
# 获取与搜索短语最匹配的操作指令 | |
best_match = get_best_match(" ".join(search_phrases), options) | |
return f"您的操作指令可能是:{best_match}。" | |
else: | |
return "您的操作有误,请重新输入。" | |
iface = gr.Interface(game, | |
inputs=gr.inputs.Textbox("输入操作指令:"), | |
outputs="text", | |
title="文字冒险游戏", | |
description="一个简单的文字冒险游戏,你是一名侦探,小兔子被杀了,找出真凶并逮捕 'TA',别让 'TA' 逃脱!" | |
) | |
iface.launch() |