-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservir.py
More file actions
75 lines (62 loc) · 2.42 KB
/
Copy pathservir.py
File metadata and controls
75 lines (62 loc) · 2.42 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
# Server - Serves search queries
import sqlite3
from typing import List, Dict
import json
from classeur import tokenize_and_stem
def search_pages(query: str, db_path: str = 'clea_db.db', max_results: int = 100) -> List[Dict]:
"""Search indexed pages using a text query."""
query_words = tokenize_and_stem(query)
if not query_words:
return []
conn = sqlite3.connect(db_path)
try:
cursor = conn.cursor()
# get matching webpage IDs for each word
matching_pages = {}
for word in query_words:
cursor.execute('''
SELECT webpage_ids, webpage_frequencies
FROM word_index
WHERE word = ?
''', (word,))
row = cursor.fetchone()
if row:
webpage_ids = json.loads(row[0])
frequencies = json.loads(row[1])
for webpage_id in webpage_ids:
if webpage_id not in matching_pages:
matching_pages[webpage_id] = {
'matching_terms': 0,
'total_frequency': 0
}
matching_pages[webpage_id]['matching_terms'] += 1
matching_pages[webpage_id]['total_frequency'] += frequencies[webpage_id]
# Sort by matching terms and frequency
sorted_pages = sorted(
matching_pages.items(),
key=lambda x: (x[1]['matching_terms'], x[1]['total_frequency']),
reverse=True
)[:max_results]
results = []
for webpage_id, scores in sorted_pages:
cursor.execute('''
SELECT url, title
FROM webpages
WHERE id = ?
''', (webpage_id,))
row = cursor.fetchone()
if row:
url = row[0]
title = row[1]
cursor.execute('SELECT snippet FROM webpages WHERE id = ?', (webpage_id,))
snippet = cursor.fetchone()[0]
results.append({
'url': url,
'title': title,
'snippet': snippet,
'matching_terms': scores['matching_terms'],
'relevance_score': scores['total_frequency']
})
return results
finally:
conn.close()