返回 last30days-skill
jobs_story.py
根目录 / skills / last30days / scripts / lib / jobs_story.py
1 """Story terms: the few phrases the jobs lane searches each board for.
2
3 They come from the run's own stories. The host plan sends them as
4 ``jobs_queries``; when it sends none, ``derive_terms`` takes them from the
5 plan's subqueries, leaving out the company, the people, the other side of a
6 comparison and generic words. Terms are fixed once, before the first jobs
7 stream starts, because that stream settles the lane's budget.
8 """
9
10 from __future__ import annotations
11
12 import re
13 from typing import Iterable
14
15 MAX_TERMS = 4
16 MAX_TERM_CHARS = 40
17 # A derived phrase longer than this reads as a sentence, which no job
18 # title or description repeats.
19 MAX_DERIVED_WORDS = 3
20 # A term shorter than this is matched as a whole word ("AI" is not in
21 # "Maintenance"); a longer one anywhere in the text.
22 WHOLE_WORD_UNDER = 5
23
24 GENERIC_WORDS = frozenset("""
25 a about after an and announcement announcements are as at by careers ceo
26 company compared discussion discussions for from has have hiring how in is
27 it its job jobs latest new news of on opinion opinions or over people
28 reaction reactions recent reddit review reviews say says the think this to
29 today twitter update updates versus vs what who why will with x youtube
30 tiktok week month year
31 """.split())
32
33 _EDGE_PUNCT = "\"'()[]{}<>.,;:!?"
34
35
36 def clean_terms(raw: object) -> list[str]:
37 """The plan's story terms: strings, trimmed, deduplicated, the first four."""
38 if not isinstance(raw, list):
39 return []
40 return _first_distinct(
41 " ".join(term.split()) for term in raw if isinstance(term, str)
42 )
43
44
45 def _first_distinct(terms: Iterable[str]) -> list[str]:
46 kept: list[str] = []
47 seen: set[str] = set()
48 for term in terms:
49 key = term.casefold()
50 if not term or len(term) > MAX_TERM_CHARS or key in seen:
51 continue
52 seen.add(key)
53 kept.append(term)
54 if len(kept) == MAX_TERMS:
55 break
56 return kept
57
58
59 def _name_words(names: Iterable[str]) -> set[str]:
60 """Each word of each name, case-folded, a domain's suffix dropped."""
61 words: set[str] = set()
62 for name in names:
63 for word in str(name or "").split():
64 word = word.strip(_EDGE_PUNCT).casefold()
65 if word:
66 words.add(word)
67 words.add(re.sub(r"\.(com|net|org|io|ai|co)$", "", word))
68 return words
69
70
71 def _is_title_word(word: str) -> bool:
72 return len(word) > 1 and word[0].isupper() and word[1:].islower() and word.isalpha()
73
74
75 def derive_terms(search_queries: Iterable[str], excluded_names: Iterable[str]) -> list[str]:
76 """Story terms from the plan's subqueries, when the host sent none.
77
78 Each subquery is cut at every word that is part of an excluded name (the
79 topic, the company, the person, a comparison entity), a generic word, a
80 number, or a run of two or more capitalized words (a person's name such
81 as "Andy Jassy"; the engine cannot tell it from a product's, so both are
82 left out). What remains between the cuts, at most three words, is a term.
83 """
84 excluded = _name_words(excluded_names)
85 found: list[str] = []
86 for query in search_queries:
87 tokens = str(query or "").split()
88 cleaned = [token.strip(_EDGE_PUNCT) for token in tokens]
89 dropped = [
90 not word
91 or word.casefold() in excluded
92 or word.casefold() in GENERIC_WORDS
93 or word.isdigit()
94 for word in cleaned
95 ]
96 # Two or more capitalized words in a row, among the words kept.
97 index = 0
98 while index < len(cleaned):
99 end = index
100 while end < len(cleaned) and not dropped[end] and _is_title_word(cleaned[end]):
101 end += 1
102 if end - index >= 2:
103 for position in range(index, end):
104 dropped[position] = True
105 index = max(end, index + 1)
106 segment: list[str] = []
107 for token, word, drop in zip(tokens, cleaned, dropped):
108 if not drop:
109 segment.append(word)
110 if drop or token != word:
111 # A dropped word or a mark of punctuation ends the phrase.
112 found.extend(_phrase(segment))
113 segment = []
114 found.extend(_phrase(segment))
115 return _first_distinct(found)
116
117
118 def _phrase(words: list[str]) -> list[str]:
119 return [" ".join(words)] if 0 < len(words) <= MAX_DERIVED_WORDS else []
120
121
122 def matches(term: str, text: str) -> bool:
123 """Whether a job's text mentions the story term.
124
125 A term under five characters must stand as a whole word ("AI" matches
126 "AI Native", not "Maintenance"); a longer one may appear anywhere. Case
127 is ignored either way.
128 """
129 term = " ".join(str(term or "").split())
130 if not term:
131 return False
132 if len(term) < WHOLE_WORD_UNDER:
133 return re.search(rf"(?<!\w){re.escape(term)}(?!\w)", text or "", re.IGNORECASE) is not None
134 return term.casefold() in (text or "").casefold()
135
135 lines PYTHON