Spaces:
Sleeping
Sleeping
Download app.py from sofiamak/Sunzi-nihao: direct link, hf CLI and curl.
- Browser
- Download file 9.33 kB
-
https://huggingface.co/spaces/sofiamak/Sunzi-nihao/resolve/main/app.py
- Command line
-
hf download hf://spaces/sofiamak/Sunzi-nihao/app.py
-
curl -L -o app.py https://huggingface.co/spaces/sofiamak/Sunzi-nihao/resolve/main/app.py
9.33 kB
| import json, os, html, random | |
| import gradio as gr | |
| APP_TITLE = "孙子你好" | |
| DATA_FILE = "playbook.json" | |
| # 读取固定答案库 | |
| def load_kb(): | |
| if not os.path.exists(DATA_FILE): | |
| raise RuntimeError("未找到 playbook.json,请先上传。") | |
| with open(DATA_FILE, "r", encoding="utf-8") as f: | |
| data = json.load(f) | |
| # 章节小副标(可根据需要增补) | |
| chap_hint = { | |
| "计篇":"先算后战","作战篇":"速战速决","谋攻篇":"上兵伐谋","军形篇":"先固己势", | |
| "兵势篇":"势能制胜","虚实篇":"避实击虚","军争篇":"抢占先机","九变篇":"因变制胜", | |
| "行军篇":"察情定位","地形篇":"因地用兵","九地篇":"九地九策","火攻篇":"借势放大", | |
| "用间篇":"情报为先","始计篇":"先计而后战" | |
| } | |
| for item in data: | |
| item["chapter_hint"] = chap_hint.get(item.get("chapter",""), "") | |
| item["triggers"] = item.get("triggers", []) | |
| return data | |
| KB = load_kb() | |
| def match_candidates(user_text: str): | |
| """ | |
| 简单触发词计分 → 取最高分 intent → 返回该 intent 的条目池(打乱顺序)。 | |
| 若无匹配,返回若干随机候选并附提示。 | |
| """ | |
| text = (user_text or "").lower() | |
| scored = [] | |
| for it in KB: | |
| score = sum(1 for t in it.get("triggers", []) if t.lower() in text) | |
| if score > 0: | |
| scored.append((score, it)) | |
| if not scored: | |
| pool = random.sample(KB, k=min(len(KB), 6)) | |
| return pool, "(未匹配到明确场景,先给你几个思路)" | |
| scored.sort(key=lambda x: -x[0]) | |
| top_intent = scored[0][1]["intent"] | |
| pool = [it for _, it in scored if it["intent"] == top_intent] | |
| random.shuffle(pool) | |
| return pool, "" | |
| def render_plan(item, show_speech=False, tip_msg=""): | |
| """渲染完整方案;show_speech=True 时附带话术卡片""" | |
| chap = html.escape(item.get("chapter","")) | |
| hint = html.escape(item.get("chapter_hint","")) | |
| quote= html.escape(item.get("quote","")) | |
| idea = html.escape(item.get("idea","")) | |
| methods = item.get("methods", []) | |
| methods_html = "".join([f"<div> {i+1}. {html.escape(m)}</div>" for i,m in enumerate(methods)]) | |
| speech = html.escape(item.get("speech","")).replace("\n","<br>") | |
| speech_html = f""" | |
| <div style="margin-top:10px;padding:12px 14px;border:1px dashed #e2d7f2;border-radius:10px;background:#fbf8ff;"> | |
| <div style="font-weight:600;">💬 话术示例:</div> | |
| <div>{speech}</div> | |
| </div> | |
| """ if (show_speech and speech) else "" | |
| tip = f"<div style='color:#9a8fb3;font-size:14px;margin-bottom:6px;'>{html.escape(tip_msg)}</div>" if tip_msg else "" | |
| return f""" | |
| <div style="font-size:22px;line-height:1.7em;"> | |
| {tip} | |
| 🧠 《{chap}》:{hint}<br><br> | |
| 「{quote}」<br><br> | |
| ⸻<br><br> | |
| <span style="font-weight:600;">思路:</span>{idea}<br><br> | |
| <span style="font-weight:600;">做法:</span> | |
| {methods_html} | |
| {speech_html} | |
| </div> | |
| """ | |
| def render_speech_only(item): | |
| """只显示话术示例卡片""" | |
| speech = html.escape(item.get("speech","")).replace("\n", "<br>") | |
| return f""" | |
| <div style="font-size:22px;line-height:1.8em;padding:20px;background:#fbf8ff;border-radius:12px;border:1px solid #e2d7f2;"> | |
| <div style="font-weight:600;margin-bottom:10px;">💬 话术示例:</div> | |
| <div>{speech}</div> | |
| </div> | |
| """ | |
| # 为了控制按钮显隐,统一一个输出打包方法 | |
| def pack_outputs(html_out, pool, idx, show_flag, show_switch, show_speech_btn, show_back, show_again, user_text_keep=True): | |
| return ( | |
| html_out, | |
| pool, | |
| idx, | |
| show_flag, | |
| gr.update(visible=show_switch), # btn_switch | |
| gr.update(visible=show_speech_btn), # btn_speech | |
| gr.update(visible=show_back), # btn_back | |
| gr.update(visible=show_again), # btn_again | |
| (gr.update() if user_text_keep else gr.update(value="")) # Textbox | |
| ) | |
| # ---- 回调:生成 / 换兵法 / 只看话术 / 返回兵法 / 重新提问 ---- | |
| def on_generate(user_text, state_pool, state_idx, state_show): | |
| pool, tip = match_candidates(user_text) | |
| if not pool: | |
| return pack_outputs("<div style='font-size:20px;'>抱歉,暂未找到合适方案。</div>", | |
| [], 0, False, False, False, False, False, True) | |
| # 生成后:显示“换兵法”“显示话术示例”“问孙子其他问题”,不显示“返回兵法” | |
| html_out = render_plan(pool[0], False, tip) | |
| return pack_outputs(html_out, pool, 0, False, True, True, False, True, True) | |
| def on_switch(state_pool, state_idx, state_show): | |
| pool = state_pool or [] | |
| if not pool: | |
| return pack_outputs("<div style='font-size:20px;'>请先输入你的问题并点击生成兵法。</div>", | |
| pool, state_idx, state_show, False, False, False, False, True) | |
| idx = (state_idx + 1) % len(pool) | |
| # 切换后:仍显示“换兵法”“显示话术示例”“问孙子其他问题”,隐藏“返回兵法” | |
| html_out = render_plan(pool[idx], False, "") | |
| return pack_outputs(html_out, pool, idx, False, True, True, False, True, True) | |
| def on_show_speech(state_pool, state_idx, state_show): | |
| """只显示话术示例;此时需要出现“返回兵法”""" | |
| pool = state_pool or [] | |
| if not pool: | |
| return pack_outputs("<div style='font-size:20px;'>请先输入你的问题并点击生成兵法。</div>", | |
| pool, state_idx, state_show, False, False, False, False, True) | |
| idx = max(0, min(state_idx, len(pool)-1)) | |
| html_out = render_speech_only(pool[idx]) | |
| # 此时:显示“返回兵法”“换兵法”“显示话术示例”“问孙子其他问题”都可以保留 | |
| return pack_outputs(html_out, pool, idx, True, True, True, True, True, True) | |
| def on_back(state_pool, state_idx, state_show): | |
| """从“只看话术”返回到完整兵法视图;隐藏‘返回兵法’""" | |
| pool = state_pool or [] | |
| if not pool: | |
| return pack_outputs("<div style='font-size:20px;'>请先输入你的问题并点击生成兵法。</div>", | |
| pool, state_idx, state_show, False, False, False, False, True) | |
| idx = max(0, min(state_idx, len(pool)-1)) | |
| html_out = render_plan(pool[idx], False, "") | |
| return pack_outputs(html_out, pool, idx, False, True, True, False, True, True) | |
| def on_again(state_pool, state_idx, state_show): | |
| """回到初始状态:清空输出与输入,只显示生成兵法""" | |
| html_out = "" | |
| empty_pool = [] | |
| # 初始:只有“生成兵法”可见(其它按钮隐藏) | |
| return pack_outputs(html_out, empty_pool, 0, False, False, False, False, False, user_text_keep=False) | |
| # ---- UI ---- | |
| theme = gr.themes.Soft(primary_hue="pink", neutral_hue="slate") | |
| CSS = """ | |
| body,.gradio-container{background:#f7f6fb!important;} | |
| .header{font-weight:900;font-size:28px;color:#111;text-align:center;padding:24px 0;} | |
| .card{background:#fff;border:1px solid #eddcf3;border-radius:14px; box-shadow:0 4px 18px rgba(0,0,0,.05);padding:16px;} | |
| """ | |
| with gr.Blocks(title=APP_TITLE, theme=theme, css=CSS, analytics_enabled=False) as demo: | |
| gr.HTML("<div class='header'>孙子你好</div>") | |
| with gr.Group(elem_classes=["card"]): | |
| user_text = gr.Textbox(label="你的问题", placeholder="例如:朋友借钱不还;老板让我加班;邻居太吵;甲方拖款…", lines=3) | |
| btn_gen = gr.Button("🎯 生成兵法", variant="primary") | |
| with gr.Row(): | |
| btn_switch = gr.Button("♻️ 换兵法", visible=False) | |
| btn_speech = gr.Button("💬 显示示例话术", visible=False) | |
| btn_back = gr.Button("↩️ 返回兵法", visible=False) | |
| btn_again = gr.Button("🧭 问孙子其他问题", visible=False) | |
| out = gr.HTML() | |
| # 状态:候选池、当前下标、是否处于“只看话术” | |
| state_pool = gr.State([]) | |
| state_idx = gr.State(0) | |
| state_show = gr.State(False) | |
| # 事件绑定(注意输出多了按钮可见性与文本框) | |
| btn_gen.click(on_generate, inputs=[user_text, state_pool, state_idx, state_show], | |
| outputs=[out, state_pool, state_idx, state_show, btn_switch, btn_speech, btn_back, btn_again, user_text]) | |
| btn_switch.click(on_switch, inputs=[state_pool, state_idx, state_show], | |
| outputs=[out, state_pool, state_idx, state_show, btn_switch, btn_speech, btn_back, btn_again, user_text]) | |
| btn_speech.click(on_show_speech, inputs=[state_pool, state_idx, state_show], | |
| outputs=[out, state_pool, state_idx, state_show, btn_switch, btn_speech, btn_back, btn_again, user_text]) | |
| btn_back.click(on_back, inputs=[state_pool, state_idx, state_show], | |
| outputs=[out, state_pool, state_idx, state_show, btn_switch, btn_speech, btn_back, btn_again, user_text]) | |
| btn_again.click(on_again, inputs=[state_pool, state_idx, state_show], | |
| outputs=[out, state_pool, state_idx, state_show, btn_switch, btn_speech, btn_back, btn_again, user_text]) | |
| if __name__ == "__main__": | |
| demo.launch() |