sofiamak commited on
Commit
c6e4036
·
verified ·
1 Parent(s): dafa9c9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -262
app.py CHANGED
@@ -1,294 +1,141 @@
1
- import os, json, html, re, random
2
  import gradio as gr
3
 
4
- # ====== 依赖:DeepSeek(OpenAI 兼容) ======
5
- _HAS_OPENAI = False
6
- client = None
7
- DEEPSEEK_KEY = os.getenv("DEEPSEEK_API_KEY")
8
- try:
9
- from openai import OpenAI
10
- if DEEPSEEK_KEY:
11
- client = OpenAI(api_key=DEEPSEEK_KEY, base_url="https://api.deepseek.com")
12
- _HAS_OPENAI = True
13
- except Exception:
14
- _HAS_OPENAI = False
15
-
16
- # ====== 依赖:中文分词 + TFIDF 相似度 ======
17
- import jieba
18
- from sklearn.feature_extraction.text import TfidfVectorizer
19
- from sklearn.metrics.pairwise import cosine_similarity
20
-
21
  APP_TITLE = "孙子你好"
22
- CORPUS_FILE = "sunzi_full.json" # 全书语料(见下方文件格式示例)
23
- TOP_K = 5 # 交给大模型挑选的候选条目数
24
 
25
- # ---------------- 读全书 + 建索引 ----------------
26
- def load_corpus():
27
- if not os.path.exists(CORPUS_FILE):
28
- raise RuntimeError("未找到 sunzi_full.json,请先上传全书语料。")
29
- with open(CORPUS_FILE, "r", encoding="utf-8") as f:
30
- data = json.load(f)
31
- # 规范字段
32
- rows = []
33
- for i, it in enumerate(data):
34
- rows.append({
35
- "id": it.get("id", f"q_{i:04d}"),
36
- "chapter": it.get("chapter", "").strip(),
37
- "quote": it.get("quote", "").strip()
38
- })
39
- return rows
40
 
41
- CORPUS = load_corpus()
 
 
 
 
42
 
43
- def jieba_tokenizer(s):
44
- return [w for w in jieba.lcut(s) if w.strip()]
45
 
46
- DOCS = [f'{r["chapter"]} {r["quote"]}' for r in CORPUS]
47
- VEC = TfidfVectorizer(tokenizer=jieba_tokenizer, ngram_range=(1,2), min_df=1)
48
- MATRIX = VEC.fit_transform(DOCS)
 
 
 
 
 
 
 
49
 
50
- def topk_candidates(user_text, k=TOP_K):
51
- qv = VEC.transform([user_text])
52
- sims = cosine_similarity(qv, MATRIX).ravel()
53
- idxs = sims.argsort()[::-1][:k]
54
- return [CORPUS[i] for i in idxs]
55
 
56
- # ------------- UI 渲染(沿用你的短模板) -------------
57
- CHAP_HINT = {
58
- "始计篇":"先计而后战","作战篇":"速战速决","谋攻篇":"上兵伐谋","军形篇":"先固己势",
59
- "兵势篇":"势能制胜","虚实篇":"避实击虚","军争篇":"抢占先机","九变篇":"因变制胜",
60
- "行军篇":"察情定位","地形篇":"因地用兵","九地篇":"九地九策","火攻篇":"借势放大",
61
- "用间篇":"情报为先"
62
- }
63
 
64
- def render_plan(item, show_speech=False, tip_msg=""):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  chap = html.escape(item.get("chapter",""))
66
- hint = html.escape(CHAP_HINT.get(chap,""))
67
  quote= html.escape(item.get("quote",""))
68
- insight = html.escape(item.get("insight",""))
69
- action = html.escape(item.get("action",""))
70
- speech = html.escape(item.get("speech","")).replace("\n","<br>")
71
-
72
- speech_html = f"""
73
- <div style="margin-top:12px;padding:12px 14px;border:1px dashed #e2d7f2;border-radius:10px;background:#fbf8ff;">
74
- <div style="font-weight:600;">💬 话术示例:</div>
75
- <div>{speech}</div>
76
- </div>
77
- """ if (show_speech and speech) else ""
78
-
79
- tip = f"<div style='color:#9a8fb3;font-size:13px;margin-bottom:6px'>{html.escape(tip_msg)}</div>" if tip_msg else ""
80
 
 
81
  return f"""
82
- <div style="font-size:22px;line-height:1.7em;">
83
- {tip}
84
  🧠 《{chap}》:{hint}<br><br>
85
  「{quote}」<br><br>
86
- ⸻<br><br>
87
- <span style="font-weight:600;">启示:</span>{insight}<br><br>
88
- <span style="font-weight:600;">做法:</span>{action}
89
- {speech_html}
90
  </div>
91
  """
92
 
93
- def render_speech_only(item):
94
- speech = html.escape(item.get("speech","")).replace("\n", "<br>")
95
- return f"""
96
- <div style="font-size:22px;line-height:1.8em;padding:20px;background:#fbf8ff;border-radius:12px;border:1px solid #e2d7f2;">
97
- <div style="font-weight:600;margin-bottom:10px;">💬 话术示例:</div>
98
- <div>{speech}</div>
99
- </div>
100
- """
101
-
102
- def pack_outputs(html_out, pool, idx, show_flag, show_switch, show_speech_btn, show_back, show_again, user_text_keep=True):
103
- return (
104
- html_out,
105
- pool,
106
- idx,
107
- show_flag,
108
- gr.update(visible=show_switch),
109
- gr.update(visible=show_speech_btn),
110
- gr.update(visible=show_back),
111
- gr.update(visible=show_again),
112
- (gr.update() if user_text_keep else gr.update(value=""))
113
- )
114
-
115
- # ------------- DeepSeek 受限生成:仅在 Top-K 中选 -------------
116
- SYS_LOCKED = (
117
- "你是中文军师,用《孙子兵法》解决现实问题。"
118
- "系统会给你一个候选列表(含编号/篇名/原文)。你必须:"
119
- "1) 只在候选中选出【一条】最贴切原文(不可更换或自造原句);"
120
- "2) 输出一个 JSON 对象,字段仅限:"
121
- "id(所选编号)、chapter(篇名)、quote(原文原句)、"
122
- "insight(≤18字,人话、直白精炼)、"
123
- "action(仅1条,≤40字、具体到动作/步骤)、"
124
- "speech(≤80字、可对对方直说;礼貌、委婉、幽默有边界)。"
125
- "严格禁止输出除 JSON 外的任何内容。"
126
- )
127
-
128
- FEWSHOT = [
129
- {
130
- "role":"user",
131
- "content":(
132
- "【候选】\n"
133
- "1) 作战篇|夫兵久而国利者,未之有也。\n"
134
- "2) 虚实篇|避实而击虚。\n"
135
- "【用户问题】老板让我临时加班但我状态很差,如何拒绝更体面?\n"
136
- "只输出JSON。"
137
- )
138
- },
139
- {
140
- "role":"assistant",
141
- "content":json.dumps({
142
- "id":"1",
143
- "chapter":"作战篇",
144
- "quote":"夫兵久而国利者,未之有也。",
145
- "insight":"别耗死自己,用质量说服。",
146
- "action":"给“今晚初稿/明早终版”两选项,让对方决定。",
147
- "speech":"老板,我担心今晚赶出来质量不稳。不如我明早7:30交完整版本,保证更稳,您看行吗?"
148
- }, ensure_ascii=False)
149
- }
150
- ]
151
-
152
- def _extract_json(text: str) -> dict:
153
- m = re.search(r"\{.*\}", text, flags=re.S)
154
- js = m.group(0) if m else text
155
- return json.loads(js)
156
-
157
- def _fallback_from_top1(cands, tip="使用本地兜底(可能未连接API)"):
158
- if not cands:
159
- return {
160
- "item": {"chapter":"始计篇","quote":"先计而后战。","insight":"先摸清再出手。","action":"列两种稳妥方案并承诺时间点。","speech":"我们按更稳的节奏推进,彼此都放心。"},
161
- "tip": tip
162
- }
163
- c = cands[0]
164
- return {
165
- "item": {"chapter": c["chapter"], "quote": c["quote"], "insight":"先捋清状况再出手。","action":"定目标与底线,给一个具体步骤。","speech":"我这边按更稳的节奏推进,给你一个清晰方案。"},
166
- "tip": tip
167
- }
168
 
169
- def deepseek_choose_and_write(user_text: str, cands: list, alt: bool=False):
170
- """
171
- 把 TF-IDF Top-K 候选喂给 DeepSeek,只允许从中选一条并生成短模板。
172
- alt=True 时提示换表达,但仍限定在同一候选集。
173
- """
174
- listing = "\n".join([f'{i+1}) {c["chapter"]}|{c["quote"]}' for i,c in enumerate(cands)])
175
- ask = f"【候选】\n{listing}\n【用户问题】{user_text}\n只输出JSON。"
176
- if alt:
177
- ask += "\n请换一种表述思路(仍只能在候选内选),避免与上次措辞重复。"
178
-
179
- if not _HAS_OPENAI:
180
- fb = _fallback_from_top1(cands, "未检测到 DEEPSEEK_API_KEY,已使用本地兜底。")
181
- return fb["item"], fb["tip"]
182
-
183
- try:
184
- msgs = [{"role":"system","content":SYS_LOCKED}] + FEWSHOT + [{"role":"user","content":ask}]
185
- resp = client.chat.completions.create(
186
- model="deepseek-chat",
187
- messages=msgs,
188
- temperature=0.25 if not alt else 0.55,
189
- max_tokens=420,
190
- timeout=30
191
- )
192
- data = _extract_json(resp.choices[0].message.content.strip())
193
- sel_id = str(data.get("id","1")).strip()
194
- # 把编号对应回候选,确保不越界
195
- try:
196
- idx = max(1, min(len(cands), int(re.sub(r"[^0-9]", "", sel_id) or "1"))) - 1
197
- except Exception:
198
- idx = 0
199
- c = cands[idx]
200
- item = {
201
- "chapter": c["chapter"],
202
- "quote": c["quote"],
203
- "insight": str(data.get("insight","先捋清状况再出手。")).strip(),
204
- "action": str(data.get("action","给出一个具体且可执行的步骤。")).strip(),
205
- "speech": str(data.get("speech","我们按更稳的节奏推进,彼此都放心。")).strip()
206
- }
207
- return item, ""
208
- except Exception as e:
209
- fb = _fallback_from_top1(cands, f"已使用兜底({type(e).__name__})")
210
- return fb["item"], fb["tip"]
211
-
212
- # ----------------- 回调(维持你的按钮可见逻辑) -----------------
213
- def on_generate(user_text, state_pool, state_idx, state_show):
214
- user_text = (user_text or "").strip()
215
- if not user_text:
216
- return pack_outputs("<div style='font-size:20px;'>请先输入你的问题。</div>", [], 0, False, False, False, False, False, True)
217
- cands = topk_candidates(user_text, TOP_K)
218
- item, tip = deepseek_choose_and_write(user_text, cands, alt=False)
219
- pool = [item]
220
- html_out = render_plan(item, False, tip)
221
- return pack_outputs(html_out, pool, 0, False, True, True, False, True, True)
222
-
223
- def on_switch(state_pool, state_idx, state_show, user_text):
224
- user_text = (user_text or "").strip()
225
- if not user_text:
226
- return pack_outputs("<div style='font-size:20px;'>请先输入你的问题并点击生成兵法。</div>", [], 0, False, False, False, False, False, True)
227
- cands = topk_candidates(user_text, TOP_K)
228
- item, tip = deepseek_choose_and_write(user_text, cands, alt=True)
229
- pool = [item]
230
- html_out = render_plan(item, False, tip)
231
- return pack_outputs(html_out, pool, 0, False, True, True, False, True, True)
232
-
233
- def on_show_speech(state_pool, state_idx, state_show):
234
- pool = state_pool or []
235
  if not pool:
236
- return pack_outputs("<div style='font-size:20px;'>请先输入你的问题并点击生成兵法。</div>", pool, state_idx, state_show, False, False, False, False, True)
237
- idx = max(0, min(state_idx, len(pool)-1))
238
- html_out = render_speech_only(pool[idx])
239
- return pack_outputs(html_out, pool, idx, True, True, True, True, True, True)
240
-
241
- def on_back(state_pool, state_idx, state_show):
242
- pool = state_pool or []
243
- if not pool:
244
- return pack_outputs("<div style='font-size:20px;'>请先输入你的问题并点击生成兵法。</div>", pool, state_idx, state_show, False, False, False, False, True)
245
- idx = max(0, min(state_idx, len(pool)-1))
246
- html_out = render_plan(pool[idx], False, "")
247
- return pack_outputs(html_out, pool, idx, False, True, True, False, True, True)
248
 
249
- def on_again(state_pool, state_idx, state_show):
250
- return pack_outputs("", [], 0, False, False, False, False, False, user_text_keep=False)
 
251
 
252
- # ----------------- UI -----------------
253
- theme = gr.themes.Soft(primary_hue="pink", neutral_hue="slate")
254
  CSS = """
255
  body,.gradio-container{background:#f7f6fb!important;}
256
  .header{font-weight:900;font-size:28px;color:#111;text-align:center;padding:24px 0;}
257
- .card{background:#fff;border:1px solid #eddcf3;border-radius:14px; box-shadow:0 4px 18px rgba(0,0,0,.05);padding:16px;}
 
258
  """
259
 
260
- with gr.Blocks(title=APP_TITLE, theme=theme, css=CSS, analytics_enabled=False) as demo:
261
  gr.HTML("<div class='header'>孙子你好</div>")
262
- with gr.Group(elem_classes=["card"]):
263
- user_text = gr.Textbox(label="你的问题", placeholder="例如:朋友借钱不还;老板让我加班;邻居太吵;甲方拖款…", lines=3)
264
- btn_gen = gr.Button("🎯 生成兵法", variant="primary")
265
-
266
- with gr.Row():
267
- btn_switch = gr.Button("♻️ 换兵法", visible=False)
268
- btn_speech = gr.Button("💬 显示示例话术", visible=False)
269
- btn_back = gr.Button("↩️ 返回兵法", visible=False)
270
- btn_again = gr.Button("🧭 问孙子其他问题", visible=False)
271
-
272
- out = gr.HTML()
273
-
274
- state_pool = gr.State([])
275
- state_idx = gr.State(0)
276
- state_show = gr.State(False)
277
-
278
- btn_gen.click(on_generate, inputs=[user_text, state_pool, state_idx, state_show],
279
- outputs=[out, state_pool, state_idx, state_show, btn_switch, btn_speech, btn_back, btn_again, user_text])
280
-
281
- btn_switch.click(on_switch, inputs=[state_pool, state_idx, state_show, user_text],
282
- outputs=[out, state_pool, state_idx, state_show, btn_switch, btn_speech, btn_back, btn_again, user_text])
283
-
284
- btn_speech.click(on_show_speech, inputs=[state_pool, state_idx, state_show],
285
- outputs=[out, state_pool, state_idx, state_show, btn_switch, btn_speech, btn_back, btn_again, user_text])
286
-
287
- btn_back.click(on_back, inputs=[state_pool, state_idx, state_show],
288
- outputs=[out, state_pool, state_idx, state_show, btn_switch, btn_speech, btn_back, btn_again, user_text])
289
-
290
- btn_again.click(on_again, inputs=[state_pool, state_idx, state_show],
291
- outputs=[out, state_pool, state_idx, state_show, btn_switch, btn_speech, btn_back, btn_again, user_text])
292
 
293
  if __name__ == "__main__":
294
  demo.launch()
 
1
+ import os, json, html, random, requests
2
  import gradio as gr
3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  APP_TITLE = "孙子你好"
5
+ DATA_FILE = "playbook.json"
 
6
 
7
+ # ---------------- 读取知识库 ---------------- #
8
+ def load_kb():
9
+ if not os.path.exists(DATA_FILE):
10
+ return None, f"❌ 未找到 {DATA_FILE}。请确保文件名和 app.py 同目录且大小写一致。"
 
 
 
 
 
 
 
 
 
 
 
11
 
12
+ try:
13
+ with open(DATA_FILE, "r", encoding="utf-8") as f:
14
+ data = json.load(f)
15
+ except Exception as e:
16
+ return None, f"❌ 解析 {DATA_FILE} 出错:{e}"
17
 
18
+ if not isinstance(data, list) or not data:
19
+ return None, f"❌ {DATA_FILE} 内容为空或格式不正确。"
20
 
21
+ hint = {
22
+ "计篇":"先算后战","作战篇":"速战速决","谋攻篇":"上兵伐谋","军形篇":"先固己势",
23
+ "兵势篇":"势能制胜","虚实篇":"避实击虚","军争篇":"抢占先机","九变篇":"因变制胜",
24
+ "行军篇":"察情定位","地形篇":"因地用兵","九地篇":"九地九策","火攻篇":"借势放大",
25
+ "用间篇":"情报为先","始计篇":"先计而后战"
26
+ }
27
+ for it in data:
28
+ it["chapter_hint"] = hint.get(it.get("chapter", ""), "")
29
+ it["triggers"] = it.get("triggers", [])
30
+ return data, ""
31
 
32
+ KB, KB_ERR = load_kb()
 
 
 
 
33
 
34
+ # ---------------- DeepSeek 推理接口 ---------------- #
35
+ DEEPSEEK_API = "https://api.deepseek.com/v1/chat/completions"
36
+ DEEPSEEK_KEY = os.getenv("DEEPSEEK_API_KEY") or "YOUR_API_KEY_HERE"
 
 
 
 
37
 
38
+ def ask_deepseek(prompt):
39
+ """调用 DeepSeek,若失败返回空字符串"""
40
+ try:
41
+ resp = requests.post(
42
+ DEEPSEEK_API,
43
+ headers={
44
+ "Content-Type": "application/json",
45
+ "Authorization": f"Bearer {DEEPSEEK_KEY}",
46
+ },
47
+ json={
48
+ "model": "deepseek-chat",
49
+ "messages": [{"role": "user", "content": prompt}],
50
+ "max_tokens": 800,
51
+ "temperature": 0.7
52
+ },
53
+ timeout=25
54
+ )
55
+ data = resp.json()
56
+ return data.get("choices", [{}])[0].get("message", {}).get("content", "").strip()
57
+ except Exception as e:
58
+ return f"⚠️ DeepSeek 出错:{e}"
59
+
60
+ # ---------------- 兵法匹配逻辑 ---------------- #
61
+ def match_candidates(user_text: str):
62
+ if not KB:
63
+ return [], "知识库加载失败。"
64
+ text = (user_text or "").lower()
65
+ scored = []
66
+ for it in KB:
67
+ score = sum(1 for t in it.get("triggers", []) if t.lower() in text)
68
+ if score > 0:
69
+ scored.append((score, it))
70
+ if not scored:
71
+ return random.sample(KB, k=min(3, len(KB))), "(未匹配到明确场景,先给几个参考)"
72
+ scored.sort(key=lambda x: -x[0])
73
+ top_intent = scored[0][1]["intent"]
74
+ pool = [it for _, it in scored if it["intent"] == top_intent]
75
+ random.shuffle(pool)
76
+ return pool, ""
77
+
78
+ def render_plan(item, tip_msg=""):
79
  chap = html.escape(item.get("chapter",""))
80
+ hint = html.escape(item.get("chapter_hint",""))
81
  quote= html.escape(item.get("quote",""))
82
+ idea = html.escape(item.get("idea",""))
83
+ methods = item.get("methods", [])
84
+ m_html = "".join([f"<div>{i+1}. {html.escape(m)}</div>" for i,m in enumerate(methods)])
 
 
 
 
 
 
 
 
 
85
 
86
+ tip = f"<div style='color:#999;font-size:14px;margin-bottom:4px;'>{html.escape(tip_msg)}</div>" if tip_msg else ""
87
  return f"""
88
+ {tip}
89
+ <div style='font-size:22px;line-height:1.7em;'>
90
  🧠 《{chap}》:{hint}<br><br>
91
  「{quote}」<br><br>
92
+ <b>思路:</b>{idea}<br><br>
93
+ <b>做法:</b><br>{m_html}
 
 
94
  </div>
95
  """
96
 
97
+ # ---------------- 主逻辑 ---------------- #
98
+ def on_generate(user_text):
99
+ if KB_ERR:
100
+ return f"<div style='color:red'>{KB_ERR}</div>"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
+ pool, tip = match_candidates(user_text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  if not pool:
104
+ return "<div>❌ 没找到合适的兵法。</div>"
105
+
106
+ # prompt: 让 DeepSeek 输出孙子风格回答
107
+ chosen = pool[0]
108
+ prompt = f"""
109
+ 你是一位幽默、聪明、有边界的中文军师。
110
+ 结合《孙子兵法》中“{chosen['chapter']} - {chosen['quote']}”的智慧,
111
+ 回答以下问题:“{user_text}”。
112
+ 请给出一段简短建议(100字内),风格机智、委婉、有策略。
113
+ """
114
+ ai_reply = ask_deepseek(prompt)
 
115
 
116
+ html_out = render_plan(chosen, tip)
117
+ html_ai = f"<div style='margin-top:20px;padding:15px;background:#fbf8ff;border-radius:10px;border:1px dashed #ccc;'><b>💬 孙子点评:</b><br>{html.escape(ai_reply)}</div>"
118
+ return html_out + html_ai
119
 
120
+ # ---------------- UI ---------------- #
121
+ theme = gr.themes.Soft(primary_hue="pink", neutral_hue="gray")
122
  CSS = """
123
  body,.gradio-container{background:#f7f6fb!important;}
124
  .header{font-weight:900;font-size:28px;color:#111;text-align:center;padding:24px 0;}
125
+ .card{background:#fff;border:1px solid #eddcf3;border-radius:14px;
126
+ box-shadow:0 4px 18px rgba(0,0,0,.05);padding:16px;}
127
  """
128
 
129
+ with gr.Blocks(title=APP_TITLE, theme=theme, css=CSS) as demo:
130
  gr.HTML("<div class='header'>孙子你好</div>")
131
+ if KB_ERR:
132
+ gr.HTML(f"<div style='color:red'>{KB_ERR}</div>")
133
+ else:
134
+ with gr.Group(elem_classes=["card"]):
135
+ q = gr.Textbox(label="你的问题", placeholder="例如:朋友借钱不还、邻居太吵、老板让我加班…", lines=3)
136
+ btn = gr.Button("🎯 生成兵法", variant="primary")
137
+ out = gr.HTML()
138
+ btn.click(on_generate, inputs=q, outputs=out)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
 
140
  if __name__ == "__main__":
141
  demo.launch()