Spaces:
Sleeping
Sleeping
File size: 7,871 Bytes
9ef70e8 | 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 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 | #!/usr/bin/env python3
import argparse
import sys
import string
import math
from nltk.stem import PorterStemmer
from lib.inverted_index import InvertedIndex
from lib.search_utils import load_stopwords
from lib.keyword_search import bm25_idf_command, bm25_tf_command
from lib.constants import BM25_K1, BM25_B
def normalize_to_tokens(text: str) -> list[str]:
translator = str.maketrans("", "", string.punctuation)
stemmer = PorterStemmer()
stopwords = set(load_stopwords())
clean = text.translate(translator).lower()
tokens = [t for t in clean.split() if t]
tokens = [t for t in tokens if t not in stopwords]
tokens = [stemmer.stem(t) for t in tokens]
return tokens
def main() -> None:
parser = argparse.ArgumentParser(description="Keyword Search CLI")
subparsers = parser.add_subparsers(dest="command", help="Available commands")
search_parser = subparsers.add_parser("search", help="Search movies using inverted index")
search_parser.add_argument("query", type=str, help="Search query")
subparsers.add_parser("build", help="Build inverted index")
tf_parser = subparsers.add_parser("tf", help="Get term frequency for a term in a document")
tf_parser.add_argument("doc_id", type=int, help="Document ID")
tf_parser.add_argument("term", type=str, help="Term to search for")
idf_parser = subparsers.add_parser("idf", help="Get inverse document frequency for a term")
idf_parser.add_argument("term", type=str, help="Term to calculate IDF for")
tfidf_parser = subparsers.add_parser("tfidf", help="Get TF-IDF score for a term in a document")
tfidf_parser.add_argument("doc_id", type=int, help="Document ID")
tfidf_parser.add_argument("term", type=str, help="Term to calculate TF-IDF for")
bm25_idf_parser = subparsers.add_parser("bm25idf", help="Get BM25 IDF score for a given term")
bm25_idf_parser.add_argument("term", type=str, help="Term to get BM25 IDF score for")
bm25_tf_parser = subparsers.add_parser("bm25tf", help="Get BM25 TF score for a given document ID and term")
bm25_tf_parser.add_argument("doc_id", type=int, help="Document ID")
bm25_tf_parser.add_argument("term", type=str, help="Term to get BM25 TF score for")
bm25_tf_parser.add_argument("k1", type=float, nargs='?', default=BM25_K1, help="Tunable BM25 K1 parameter")
bm25_tf_parser.add_argument("b", type=float, nargs='?', default=BM25_B, help="Tunable BM25 b parameter")
bm25search_parser = subparsers.add_parser("bm25search", help="Search movies using full BM25 scoring")
bm25search_parser.add_argument("query", type=str, help="Search query")
bm25search_parser.add_argument("--limit", type=int, default=5, help="Number of results to return")
args = parser.parse_args()
match args.command:
case "build":
idx = InvertedIndex()
idx.build()
idx.save()
print("Built and saved inverted index.")
case "search":
print(f"Searching for: {args.query}")
idx = InvertedIndex()
try:
idx.load()
except FileNotFoundError:
print("Error: index not found. Run: uv run cli/keyword_search_cli.py build")
sys.exit(1)
query_tokens = normalize_to_tokens(args.query)
results: list[int] = []
seen = set()
for token in query_tokens:
doc_ids = idx.get_documents(token)
for doc_id in doc_ids:
if doc_id not in seen:
seen.add(doc_id)
results.append(doc_id)
if len(results) >= 5:
break
if len(results) >= 5:
break
for i, doc_id in enumerate(results, 1):
movie = idx.docmap[doc_id]
print(f"{i}. {movie['title']} ({doc_id})")
case "tf":
idx = InvertedIndex()
try:
idx.load()
except FileNotFoundError:
print("Error: index not found. Run: uv run cli/keyword_search_cli.py build")
sys.exit(1)
tf = idx.get_tf(args.doc_id, args.term)
print(tf)
case "idf":
idx = InvertedIndex()
try:
idx.load()
except FileNotFoundError:
print("Error: index not found. Run: uv run cli/keyword_search_cli.py build")
sys.exit(1)
tokens = normalize_to_tokens(args.term)
if len(tokens) == 0:
print(f"Inverse document frequency of '{args.term}': 0.00")
sys.exit(0)
if len(tokens) > 1:
print("Error: idf expects a single token term")
sys.exit(1)
token = tokens[0]
# Calculate IDF: log((N + 1) / (n_t + 1))
N = len(idx.docmap)
doc_ids = idx.get_documents(token)
n_t = len(doc_ids)
idf = math.log((N + 1) / (n_t + 1))
print(f"Inverse document frequency of '{args.term}': {idf:.2f}")
case "tfidf":
idx = InvertedIndex()
try:
idx.load()
except FileNotFoundError:
print("Error: index not found. Run: uv run cli/keyword_search_cli.py build")
sys.exit(1)
tokens = normalize_to_tokens(args.term)
if len(tokens) == 0:
print(f"TF-IDF score of '{args.term}' in document '{args.doc_id}': 0.00")
sys.exit(0)
if len(tokens) > 1:
print("Error: tfidf expects a single token term")
sys.exit(1)
token = tokens[0]
# Calculate TF
tf = idx.get_tf(args.doc_id, token)
# Calculate IDF
N = len(idx.docmap)
doc_ids = idx.get_documents(token)
n_t = len(doc_ids)
idf = math.log((N + 1) / (n_t + 1))
# Calculate TF-IDF
tf_idf = tf * idf
print(f"TF-IDF score of '{args.term}' in document '{args.doc_id}': {tf_idf:.2f}")
case "bm25idf":
try:
bm25idf = bm25_idf_command(args.term)
print(f"BM25 IDF score of '{args.term}': {bm25idf:.2f}")
except FileNotFoundError:
print("Error: index not found. Run: uv run cli/keyword_search_cli.py build")
sys.exit(1)
case "bm25tf":
try:
bm25tf = bm25_tf_command(args.doc_id, args.term, args.k1, args.b)
print(f"BM25 TF score of '{args.term}' in document '{args.doc_id}': {bm25tf:.2f}")
except FileNotFoundError:
print("Error: index not found. Run: uv run cli/keyword_search_cli.py build")
sys.exit(1)
case "bm25search":
try:
idx = InvertedIndex()
idx.load()
limit = args.limit if hasattr(args, 'limit') else 5
results = idx.bm25_search(args.query, limit)
for i, (doc_id, score) in enumerate(results, 1):
movie = idx.docmap[doc_id]
print(f"{i}. ({doc_id}) {movie['title']} - Score: {score:.2f}")
except FileNotFoundError:
print("Error: index not found. Run: uv run cli/keyword_search_cli.py build")
sys.exit(1)
case _:
parser.print_help()
if __name__ == "__main__":
main()
|