recommend.py
4.17 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
"""Course recommend: query MySQL, keyword-match, emit SSO relay URL on stdout.
Usage:
python recommend.py "<user_query>" ["<phone>"]
Reads env (auto-loads .env.skill from skill root):
COURSE_DATABASE_URL mysql://user:pass@host:3306/db
COURSE_BASE_URL http://localhost:5173
Output: single JSON line on stdout
{"courseId":"...","url":".../?courseId=...","title":"..."}
When phone is provided, the url includes &phone={phone}.
Errors: stderr + exit 1
"""
import json
import os
import re
import sys
from pathlib import Path
from urllib.parse import urlparse
SKILL_ROOT = Path(__file__).resolve().parent.parent
TITLE_WEIGHT = 3
CATALOG_WEIGHT = 1
CN_BLOCK = re.compile(r"[一-鿿]+")
EN_BLOCK = re.compile(r"[A-Za-z0-9]+")
def load_env():
# 优先从 backend/.env 加载,再加载 .env.skill(setdefault 确保 backend/.env 优先)
backend_env = SKILL_ROOT.parent.parent / ".env"
skill_env = SKILL_ROOT / ".env.skill"
for candidate in [backend_env, skill_env]:
if candidate.is_file():
for line in candidate.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
k, v = line.split("=", 1)
os.environ.setdefault(k.strip(), v.strip().strip('"').strip("'"))
def require_env(name: str) -> str:
v = os.environ.get(name)
if not v:
print(f"ERROR: env {name} not set", file=sys.stderr)
sys.exit(1)
return v
def tokenize(text: str) -> list[str]:
tokens: list[str] = []
for cn in CN_BLOCK.findall(text):
if len(cn) == 1:
tokens.append(cn)
else:
tokens.extend(cn[i:i + 2] for i in range(len(cn) - 1))
tokens.extend(EN_BLOCK.findall(text))
return tokens
def score(query_tokens: list[str], title: str, catalog: str) -> int:
s = 0
for tok in query_tokens:
if tok and tok in title:
s += TITLE_WEIGHT
if tok and tok in catalog:
s += CATALOG_WEIGHT
return s
def fetch_courses(db_url: str) -> list[tuple[str, str, str]]:
import pymysql
parsed = urlparse(db_url.replace("mysql+pymysql://", "mysql://"))
try:
conn = pymysql.connect(
host=parsed.hostname,
port=parsed.port or 3306,
user=parsed.username,
password=parsed.password or "",
database=parsed.path.lstrip("/"),
connect_timeout=5,
cursorclass=pymysql.cursors.Cursor,
)
except Exception as e:
print(f"ERROR: db connect failed: {e}", file=sys.stderr)
sys.exit(1)
try:
with conn.cursor() as cur:
cur.execute(
"SELECT id, title, catalog FROM dj_beisen_course WHERE course_status = %s",
(40,),
)
rows = cur.fetchall()
finally:
conn.close()
return [(r[0], r[1] or "", r[2] or "") for r in rows]
def main():
load_env()
if len(sys.argv) < 2 or not sys.argv[1].strip():
print("usage: recommend.py <query> [phone]", file=sys.stderr)
sys.exit(1)
query = sys.argv[1]
phone = sys.argv[2] if len(sys.argv) > 2 and sys.argv[2].strip() else None
db_url = require_env("COURSE_DATABASE_URL")
base_url = require_env("COURSE_BASE_URL").rstrip("/")
rows = fetch_courses(db_url)
if not rows:
print("ERROR: no active courses (course_status=40 in dj_beisen_course)", file=sys.stderr)
sys.exit(1)
tokens = tokenize(query)
scored = [(score(tokens, t, c), cid, t) for cid, t, c in rows]
best_score = max((s for s, _, _ in scored), default=0)
if best_score == 0:
print(f"ERROR: no course matched query: {query}", file=sys.stderr)
sys.exit(1)
phone_suffix = f"&phone={phone}" if phone else ""
matches = [
{
"courseId": cid,
"url": f"{base_url}/?courseId={cid}{phone_suffix}",
"title": title,
}
for s, cid, title in scored
if s == best_score
]
print(json.dumps(
{"count": len(matches), "matches": matches},
ensure_ascii=False,
))
if __name__ == "__main__":
main()