search-ai-core 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- search_ai_core-0.1.0/PKG-INFO +18 -0
- search_ai_core-0.1.0/README.md +0 -0
- search_ai_core-0.1.0/pyproject.toml +53 -0
- search_ai_core-0.1.0/search_ai/__init__.py +3 -0
- search_ai_core-0.1.0/search_ai/extractor.py +74 -0
- search_ai_core-0.1.0/search_ai/filters.py +132 -0
- search_ai_core-0.1.0/search_ai/parse.py +44 -0
- search_ai_core-0.1.0/search_ai/proxy.py +24 -0
- search_ai_core-0.1.0/search_ai/search_result.py +207 -0
- search_ai_core-0.1.0/search_ai/searcher.py +189 -0
- search_ai_core-0.1.0/search_ai/utils.py +93 -0
- search_ai_core-0.1.0/search_ai_core.egg-info/PKG-INFO +18 -0
- search_ai_core-0.1.0/search_ai_core.egg-info/SOURCES.txt +18 -0
- search_ai_core-0.1.0/search_ai_core.egg-info/dependency_links.txt +1 -0
- search_ai_core-0.1.0/search_ai_core.egg-info/requires.txt +8 -0
- search_ai_core-0.1.0/search_ai_core.egg-info/top_level.txt +1 -0
- search_ai_core-0.1.0/setup.cfg +4 -0
- search_ai_core-0.1.0/tests/test_filters.py +164 -0
- search_ai_core-0.1.0/tests/test_proxy.py +31 -0
- search_ai_core-0.1.0/tests/test_search_results.py +86 -0
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: search-ai-core
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Google Search & News tool with advanced filters and LLM-friendly output formats!
|
|
5
|
+
Author-email: Jacob Padilla <searchai@jacobpadilla.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/jpjacobpadilla/SearchAI
|
|
8
|
+
Keywords: python,search,markdown,search-engine,data,google,ai,web-crawler,googlesearch,googlenews,llm
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
Requires-Dist: html2text>=2025.4.15
|
|
12
|
+
Requires-Dist: httpx[socks]>=0.28.1
|
|
13
|
+
Requires-Dist: lxml>=5.4.0
|
|
14
|
+
Requires-Dist: nest-asyncio>=1.6.0
|
|
15
|
+
Requires-Dist: playwright>=1.52.0
|
|
16
|
+
Requires-Dist: publicsuffix2>=2.20191221
|
|
17
|
+
Requires-Dist: pydantic>=2.11.5
|
|
18
|
+
Requires-Dist: tenacity>=9.1.2
|
|
File without changes
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "search-ai-core"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Google Search & News tool with advanced filters and LLM-friendly output formats!"
|
|
9
|
+
readme = { file = "README.md", content-type = "text/markdown" }
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
urls = { "Homepage" = "https://github.com/jpjacobpadilla/SearchAI" }
|
|
13
|
+
authors = [
|
|
14
|
+
{ name = "Jacob Padilla", email = "searchai@jacobpadilla.com" }
|
|
15
|
+
]
|
|
16
|
+
keywords = [
|
|
17
|
+
"python", "search", "markdown", "search-engine",
|
|
18
|
+
"data", "google", "ai", "web-crawler", "googlesearch",
|
|
19
|
+
"googlenews", "llm"
|
|
20
|
+
]
|
|
21
|
+
dependencies = [
|
|
22
|
+
"html2text>=2025.4.15",
|
|
23
|
+
"httpx[socks]>=0.28.1",
|
|
24
|
+
"lxml>=5.4.0",
|
|
25
|
+
"nest-asyncio>=1.6.0",
|
|
26
|
+
"playwright>=1.52.0",
|
|
27
|
+
"publicsuffix2>=2.20191221",
|
|
28
|
+
"pydantic>=2.11.5",
|
|
29
|
+
"tenacity>=9.1.2",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
[dependency-groups]
|
|
33
|
+
dev = [
|
|
34
|
+
"notebook>=7.4.2",
|
|
35
|
+
"pytest>=8.3.5",
|
|
36
|
+
"pytest-asyncio>=1.0.0",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
[tool.setuptools.packages.find]
|
|
40
|
+
include = ["search_ai"]
|
|
41
|
+
|
|
42
|
+
[tool.ruff]
|
|
43
|
+
line-length = 120
|
|
44
|
+
|
|
45
|
+
[tool.ruff.lint]
|
|
46
|
+
select = ["I", "TID"]
|
|
47
|
+
|
|
48
|
+
[tool.ruff.format]
|
|
49
|
+
quote-style = "single"
|
|
50
|
+
|
|
51
|
+
[tool.pytest.ini_options]
|
|
52
|
+
testpaths = ["tests"]
|
|
53
|
+
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
from typing import overload
|
|
3
|
+
|
|
4
|
+
from .proxy import Proxy
|
|
5
|
+
from .utils import valid_type
|
|
6
|
+
|
|
7
|
+
from playwright.async_api import async_playwright, Browser as AsyncBrowser
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
PLAYWRIGHT_CONFIG = {
|
|
11
|
+
'user_agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
|
|
12
|
+
'viewport': {'width': 1280, 'height': 720},
|
|
13
|
+
'locale': 'en-US',
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@overload
|
|
18
|
+
def get_page_sync(url: str, proxy: Proxy | None) -> str: ...
|
|
19
|
+
@overload
|
|
20
|
+
def get_page_sync(url: list[str], proxy: Proxy | None) -> list[str]: ...
|
|
21
|
+
@overload
|
|
22
|
+
async def get_page(url: str, proxy: Proxy | None) -> str: ...
|
|
23
|
+
@overload
|
|
24
|
+
async def get_page(url: list[str], proxy: Proxy | None) -> list[str]: ...
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def get_page_sync(url: str | list[str], proxy: Proxy | None) -> str | list[str]:
|
|
28
|
+
try:
|
|
29
|
+
loop = asyncio.get_event_loop()
|
|
30
|
+
if loop.is_running():
|
|
31
|
+
import nest_asyncio
|
|
32
|
+
|
|
33
|
+
nest_asyncio.apply()
|
|
34
|
+
return asyncio.run(get_page(url, proxy))
|
|
35
|
+
else:
|
|
36
|
+
return loop.run_until_complete(get_page(url, proxy))
|
|
37
|
+
except RuntimeError:
|
|
38
|
+
return asyncio.run(get_page(url, proxy))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
async def get_page(url: str | list[str], proxy: Proxy | None) -> str | list[str]:
|
|
42
|
+
semaphore = asyncio.Semaphore(8)
|
|
43
|
+
url_list = url if isinstance(url, list) else [url]
|
|
44
|
+
|
|
45
|
+
async with async_playwright() as playwright:
|
|
46
|
+
browser = await playwright.chromium.launch(headless=True, proxy=proxy.to_playwright_proxy() if proxy else None)
|
|
47
|
+
|
|
48
|
+
tasks = [_get_page_source(url, semaphore, browser) for url in url_list]
|
|
49
|
+
results = await asyncio.gather(*tasks)
|
|
50
|
+
|
|
51
|
+
await browser.close()
|
|
52
|
+
|
|
53
|
+
return results[0] if isinstance(url, str) else results
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
async def _get_page_source(url: str, semaphore: asyncio.Semaphore, browser: AsyncBrowser) -> str:
|
|
57
|
+
if not valid_type(url):
|
|
58
|
+
return ''
|
|
59
|
+
|
|
60
|
+
async with semaphore:
|
|
61
|
+
context = await browser.new_context(**PLAYWRIGHT_CONFIG)
|
|
62
|
+
page = await context.new_page()
|
|
63
|
+
|
|
64
|
+
try:
|
|
65
|
+
await page.goto(url, wait_until='domcontentloaded', timeout=6000)
|
|
66
|
+
await page.wait_for_timeout(2000) # Wait an extra 2s for JS to populate content
|
|
67
|
+
except Exception:
|
|
68
|
+
page_source = ''
|
|
69
|
+
else:
|
|
70
|
+
page_source = await page.content()
|
|
71
|
+
|
|
72
|
+
await page.close()
|
|
73
|
+
await context.close()
|
|
74
|
+
return page_source
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
from datetime import date
|
|
2
|
+
from typing import Annotated
|
|
3
|
+
|
|
4
|
+
from pydantic import BaseModel, Field, AfterValidator
|
|
5
|
+
from pydantic.types import StringConstraints
|
|
6
|
+
from publicsuffix2 import PublicSuffixList
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
FileType = Annotated[str, StringConstraints(pattern=r'^[a-zA-Z0-9]{2,10}$')]
|
|
10
|
+
Keyword = Annotated[str, StringConstraints(pattern=r'^[^\s]+$')]
|
|
11
|
+
|
|
12
|
+
psl = PublicSuffixList()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def to_list(val: str | list[str] | None) -> list[str]:
|
|
16
|
+
if val is None:
|
|
17
|
+
return []
|
|
18
|
+
return val.split(' ') if isinstance(val, str) else val
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def group_includes(values: list[str], op: str | None = None) -> str:
|
|
22
|
+
if not values:
|
|
23
|
+
return ''
|
|
24
|
+
|
|
25
|
+
if len(values) == 1:
|
|
26
|
+
return f'{op}:{values[0]}' if op else f'"{values[0]}"'
|
|
27
|
+
|
|
28
|
+
if op:
|
|
29
|
+
parts = [f'{op}:{v}' for v in values]
|
|
30
|
+
else:
|
|
31
|
+
parts = [f'"{v}"' for v in values]
|
|
32
|
+
|
|
33
|
+
return f'({" | ".join(parts)})'
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def group_excludes(op: str, values: list[str]) -> list[str]:
|
|
37
|
+
return [f'-{op}:{v}' for v in values]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def validate_tld(v: str | list[str] | None):
|
|
41
|
+
# TODO: make type a generic type
|
|
42
|
+
if not v:
|
|
43
|
+
return v
|
|
44
|
+
|
|
45
|
+
tlds = v if isinstance(v, list) else [v]
|
|
46
|
+
for tld in tlds:
|
|
47
|
+
if not psl.get_tld(tld, strict=True):
|
|
48
|
+
raise ValueError(f'{tld!r} is an invalid top-level domain according to https://publicsuffix.org')
|
|
49
|
+
|
|
50
|
+
return v
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class Filters(BaseModel):
|
|
54
|
+
# fmt: off
|
|
55
|
+
sites: str | list[str] | None = Field(None, description='Only show results from specific domains')
|
|
56
|
+
tlds: Annotated[str | list[str] | None, AfterValidator(validate_tld)] = Field(None, description='Only show results from specific top-level domains (e.g., .gov, .edu)')
|
|
57
|
+
filetype: FileType | None = Field(None, description='Only show documents that are a specific file type. Note: Google only supports one filetype per search.')
|
|
58
|
+
https_only: bool = Field(False, description='Only show websites that support HTTPS')
|
|
59
|
+
|
|
60
|
+
exclude_sites: str | list[str] | None = Field(None, description='Exclude results from specific domains')
|
|
61
|
+
exclude_tlds: Annotated[str | list[str] | None, AfterValidator(validate_tld)] = Field(None, description='Exclude results from specific top-level domains')
|
|
62
|
+
exclude_filetypes: FileType | list[FileType] | None = Field(None, description='Exclude documents with specific file types')
|
|
63
|
+
exclude_https: bool = Field(False, description='Exclude HTTPS pages')
|
|
64
|
+
|
|
65
|
+
before: date | None = Field(None, description='Only show results before this date')
|
|
66
|
+
after: date | None = Field(None, description='Only show results after this date')
|
|
67
|
+
|
|
68
|
+
any_keywords: Keyword | list[Keyword] | None = Field(None, description='Require at least one word anywhere in the page')
|
|
69
|
+
all_keywords: Keyword | list[Keyword] | None = Field(None, description='Require specific words anywhere in the page')
|
|
70
|
+
exact_phrases: str | list[str] | None = Field(None, description='Include results with exact phrases')
|
|
71
|
+
|
|
72
|
+
exclude_all_keywords: Keyword | list[Keyword] | None = Field(None, description='Exclude pages containing certain words')
|
|
73
|
+
exclude_exact_phrases: str | list[str] | None = Field(None, description='Exclude results with exact phrases')
|
|
74
|
+
|
|
75
|
+
in_title: str | list[str] | None = Field(None, description='Require specific words in the title')
|
|
76
|
+
in_url: str | list[str] | None = Field(None, description='Require specific words in the URL')
|
|
77
|
+
in_text: str | list[str] | None = Field(None, description='Require specific words in the page text')
|
|
78
|
+
|
|
79
|
+
not_in_title: str | list[str] | None = Field(None, description='Exclude pages with specific words in the title')
|
|
80
|
+
not_in_url: str | list[str] | None = Field(None, description='Exclude pages with specific words in the URL')
|
|
81
|
+
not_in_text: str | list[str] | None = Field(None, description='Exclude pages with specific words in the page text')
|
|
82
|
+
# fmt: on
|
|
83
|
+
|
|
84
|
+
def compile_filters(self) -> str:
|
|
85
|
+
filters = []
|
|
86
|
+
|
|
87
|
+
filters.append(group_includes(to_list(self.sites), 'site'))
|
|
88
|
+
filters.append(group_includes(to_list(self.tlds), 'site'))
|
|
89
|
+
|
|
90
|
+
filters.append(group_includes(to_list(self.filetype), 'filetype'))
|
|
91
|
+
filters.append(group_includes(to_list(self.any_keywords)))
|
|
92
|
+
filters.extend([f'"{w}"' for w in to_list(self.all_keywords)])
|
|
93
|
+
|
|
94
|
+
if self.exact_phrases:
|
|
95
|
+
phrase_list = self.exact_phrases if isinstance(self.exact_phrases, list) else [self.exact_phrases]
|
|
96
|
+
filters.extend([f'"{phrase}"' for phrase in phrase_list])
|
|
97
|
+
|
|
98
|
+
if self.https_only:
|
|
99
|
+
filters.append('inurl:https')
|
|
100
|
+
|
|
101
|
+
filters.extend([f'intitle:{w}' for w in to_list(self.in_title)])
|
|
102
|
+
filters.extend([f'inurl:{w}' for w in to_list(self.in_url)])
|
|
103
|
+
filters.extend([f'intext:{w}' for w in to_list(self.in_text)])
|
|
104
|
+
|
|
105
|
+
if self.before:
|
|
106
|
+
filters.append(f'before:{self.before.isoformat()}')
|
|
107
|
+
if self.after:
|
|
108
|
+
filters.append(f'after:{self.after.isoformat()}')
|
|
109
|
+
|
|
110
|
+
# Negative Filters
|
|
111
|
+
if self.exclude_exact_phrases:
|
|
112
|
+
phrase_list = (
|
|
113
|
+
self.exclude_exact_phrases
|
|
114
|
+
if isinstance(self.exclude_exact_phrases, list)
|
|
115
|
+
else [self.exclude_exact_phrases]
|
|
116
|
+
)
|
|
117
|
+
filters.extend([f'-"{phrase}"' for phrase in phrase_list])
|
|
118
|
+
|
|
119
|
+
filters.extend(group_excludes('site', to_list(self.exclude_sites)))
|
|
120
|
+
filters.extend(group_excludes('site', to_list(self.exclude_tlds)))
|
|
121
|
+
|
|
122
|
+
if self.exclude_https:
|
|
123
|
+
filters.append('-inurl:https')
|
|
124
|
+
|
|
125
|
+
filters.extend(group_excludes('filetype', to_list(self.exclude_filetypes)))
|
|
126
|
+
filters.extend([f'-{w}' for w in to_list(self.exclude_all_keywords)])
|
|
127
|
+
|
|
128
|
+
filters.extend([f'-inurl:{w}' for w in to_list(self.not_in_url)])
|
|
129
|
+
filters.extend([f'-intitle:{w}' for w in to_list(self.not_in_title)])
|
|
130
|
+
filters.extend([f'-intext:{w}' for w in to_list(self.not_in_text)])
|
|
131
|
+
|
|
132
|
+
return ' '.join([f for f in filters if f])
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
from lxml import html
|
|
2
|
+
from urllib.parse import urlparse, parse_qs
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
RESULTS_XPATH = './/div[@class="ezO2md"][descendant::*[contains(@class, "fuLhoc")]]'
|
|
6
|
+
TITLE_XPATH = './/*[contains(@class, "fuLhoc")]'
|
|
7
|
+
SUB_TITLE_XPATH = './span[1]'
|
|
8
|
+
LINK_XPATH = './/a'
|
|
9
|
+
DESCRIPTION_XPATH = './/span[contains(@class, "FrIlee")]//span[@class="fYyStc" and normalize-space()]'
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def parse_search(data):
|
|
13
|
+
result_set = []
|
|
14
|
+
|
|
15
|
+
tree = html.fromstring(data)
|
|
16
|
+
results = tree.xpath(RESULTS_XPATH)
|
|
17
|
+
|
|
18
|
+
for result in results:
|
|
19
|
+
title_elem = result.xpath(TITLE_XPATH)
|
|
20
|
+
if not title_elem:
|
|
21
|
+
continue
|
|
22
|
+
|
|
23
|
+
title_elem = title_elem[0]
|
|
24
|
+
if title := title_elem.xpath(SUB_TITLE_XPATH):
|
|
25
|
+
extracted_title = title[0].text
|
|
26
|
+
else:
|
|
27
|
+
extracted_title = title_elem.text
|
|
28
|
+
|
|
29
|
+
link_elem = result.xpath(LINK_XPATH)[0].attrib['href']
|
|
30
|
+
link = parse_qs(urlparse(link_elem).query).get('q')
|
|
31
|
+
if not link:
|
|
32
|
+
continue
|
|
33
|
+
|
|
34
|
+
extracted_link = link[0].strip()
|
|
35
|
+
|
|
36
|
+
description_elem = result.xpath(DESCRIPTION_XPATH)
|
|
37
|
+
if description_elem:
|
|
38
|
+
extracted_description = description_elem[0].text_content().strip()
|
|
39
|
+
else:
|
|
40
|
+
extracted_description = None
|
|
41
|
+
|
|
42
|
+
result_set.append({'title': extracted_title, 'link': extracted_link, 'description': extracted_description})
|
|
43
|
+
|
|
44
|
+
return result_set
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from typing import Literal, Optional
|
|
2
|
+
from pydantic import BaseModel, Field
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class Proxy(BaseModel):
|
|
6
|
+
protocol: Literal['http', 'https', 'socks4', 'socks5'] = Field(..., description='Proxy protocol')
|
|
7
|
+
host: str = Field(..., description='Proxy server host or IP')
|
|
8
|
+
port: int = Field(..., ge=1, le=65535, description='Proxy server port')
|
|
9
|
+
username: Optional[str] = Field(None, description='Username for proxy auth')
|
|
10
|
+
password: Optional[str] = Field(None, description='Password for proxy auth')
|
|
11
|
+
|
|
12
|
+
def to_httpx_proxy_url(self) -> str:
|
|
13
|
+
auth = f'{self.username}:{self.password}@' if self.username and self.password else ''
|
|
14
|
+
return f'{self.protocol}://{auth}{self.host}:{self.port}'
|
|
15
|
+
|
|
16
|
+
def to_playwright_proxy(self) -> dict:
|
|
17
|
+
proxy = {'server': f'{self.protocol}://{self.host}:{self.port}'}
|
|
18
|
+
|
|
19
|
+
if self.username:
|
|
20
|
+
proxy['username'] = self.username
|
|
21
|
+
if self.password:
|
|
22
|
+
proxy['password'] = self.password
|
|
23
|
+
|
|
24
|
+
return proxy
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
from .proxy import Proxy
|
|
4
|
+
from .utils import extract_metadata, generate_markdown, valid_type
|
|
5
|
+
from .extractor import get_page_sync, get_page
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel, HttpUrl
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class BaseSearchResult(BaseModel):
|
|
11
|
+
title: str
|
|
12
|
+
link: HttpUrl
|
|
13
|
+
description: str | None = None
|
|
14
|
+
_proxy: Proxy | None = None
|
|
15
|
+
|
|
16
|
+
def __str__(self):
|
|
17
|
+
"""
|
|
18
|
+
This is here to hide _proxy, which is more of an implementation detail.
|
|
19
|
+
"""
|
|
20
|
+
return f'{self.__class__.__name__}(title="{self.title}", link="{self.link}", description="{self.description}")'
|
|
21
|
+
|
|
22
|
+
def __repr__(self):
|
|
23
|
+
return self.__str__()
|
|
24
|
+
|
|
25
|
+
def _basic_markdown(self) -> str:
|
|
26
|
+
parts = [f'**Title:** {self.title}', f'**Link:** {self.link}']
|
|
27
|
+
if self.description:
|
|
28
|
+
parts.append(f'**Description:** {self.description}')
|
|
29
|
+
return '\n'.join(parts)
|
|
30
|
+
|
|
31
|
+
def _extended_markdown(
|
|
32
|
+
self,
|
|
33
|
+
page_source: str,
|
|
34
|
+
content_length: int,
|
|
35
|
+
only_page_content: bool = False,
|
|
36
|
+
ignore_links: bool = False,
|
|
37
|
+
ignore_images: bool = True,
|
|
38
|
+
) -> str:
|
|
39
|
+
markdown = generate_markdown(page_source, ignore_links, ignore_images)
|
|
40
|
+
|
|
41
|
+
if only_page_content:
|
|
42
|
+
return markdown[:content_length]
|
|
43
|
+
|
|
44
|
+
metadata = extract_metadata(page_source)
|
|
45
|
+
|
|
46
|
+
parts = [f'**Title:** {metadata.get("title") or self.title}', f'**Link:** {self.link}']
|
|
47
|
+
|
|
48
|
+
if metadata.get('description'):
|
|
49
|
+
parts.append(f'**Description:** {metadata["description"]}')
|
|
50
|
+
elif self.description:
|
|
51
|
+
parts.append(f'**Description:** {self.description}')
|
|
52
|
+
|
|
53
|
+
if metadata.get('author'):
|
|
54
|
+
parts.append(f'**Author:** {metadata["author"]}')
|
|
55
|
+
if metadata.get('twitter'):
|
|
56
|
+
parts.append(f'**Twitter:** {metadata["twitter"]}')
|
|
57
|
+
|
|
58
|
+
if markdown:
|
|
59
|
+
parts.append('') # Extra break between metadata and page data
|
|
60
|
+
parts.append('## Page Preview:\n')
|
|
61
|
+
parts.append(markdown[:content_length].strip())
|
|
62
|
+
|
|
63
|
+
return '\n'.join(parts)
|
|
64
|
+
|
|
65
|
+
def _extended_json(
|
|
66
|
+
self, page_source: str, content_length: int, ignore_links: bool = False, ignore_images: bool = True
|
|
67
|
+
) -> dict:
|
|
68
|
+
metadata = extract_metadata(page_source)
|
|
69
|
+
markdown = generate_markdown(page_source, ignore_links, ignore_images)
|
|
70
|
+
|
|
71
|
+
combined_data = {'title': metadata.get('title') or self.title, 'link': str(self.link)}
|
|
72
|
+
|
|
73
|
+
if metadata.get('description'):
|
|
74
|
+
combined_data['description'] = metadata['description']
|
|
75
|
+
elif self.description:
|
|
76
|
+
combined_data['description'] = self.description
|
|
77
|
+
|
|
78
|
+
if metadata.get('author'):
|
|
79
|
+
combined_data['author'] = metadata['author']
|
|
80
|
+
if metadata.get('twitter'):
|
|
81
|
+
combined_data['twitter'] = metadata['twitter']
|
|
82
|
+
|
|
83
|
+
if markdown:
|
|
84
|
+
combined_data['page_preview'] = markdown[:content_length]
|
|
85
|
+
|
|
86
|
+
return combined_data
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class SearchResult(BaseSearchResult):
|
|
90
|
+
def markdown(
|
|
91
|
+
self,
|
|
92
|
+
extend: bool = False,
|
|
93
|
+
content_length: int = 1_000,
|
|
94
|
+
ignore_links: bool = False,
|
|
95
|
+
ignore_images: bool = True,
|
|
96
|
+
only_page_content: bool = False,
|
|
97
|
+
) -> str:
|
|
98
|
+
if not extend or not valid_type(str(self.link)):
|
|
99
|
+
return self._basic_markdown()
|
|
100
|
+
|
|
101
|
+
page_source = get_page_sync(str(self.link), self._proxy)
|
|
102
|
+
return self._extended_markdown(page_source, content_length, only_page_content, ignore_links, ignore_images)
|
|
103
|
+
|
|
104
|
+
def json(
|
|
105
|
+
self,
|
|
106
|
+
extend: bool = False,
|
|
107
|
+
content_length: int = 1_000,
|
|
108
|
+
ignore_links: bool = False,
|
|
109
|
+
ignore_images: bool = True,
|
|
110
|
+
**kwargs: Any,
|
|
111
|
+
) -> dict:
|
|
112
|
+
if not extend or not valid_type(str(self.link)):
|
|
113
|
+
return super().model_dump(**kwargs)
|
|
114
|
+
|
|
115
|
+
page_source = get_page_sync(str(self.link), self._proxy)
|
|
116
|
+
return self._extended_json(page_source, content_length, ignore_links, ignore_images)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class AsyncSearchResult(BaseSearchResult):
|
|
120
|
+
async def markdown(
|
|
121
|
+
self,
|
|
122
|
+
extend: bool = False,
|
|
123
|
+
content_length: int = 1_000,
|
|
124
|
+
ignore_links: bool = False,
|
|
125
|
+
ignore_images: bool = True,
|
|
126
|
+
only_page_content: bool = False,
|
|
127
|
+
) -> str:
|
|
128
|
+
if not extend or not valid_type(str(self.link)):
|
|
129
|
+
return self._basic_markdown()
|
|
130
|
+
|
|
131
|
+
page_source = await get_page(str(self.link), self._proxy)
|
|
132
|
+
return self._extended_markdown(page_source, content_length, only_page_content, ignore_links, ignore_images)
|
|
133
|
+
|
|
134
|
+
async def json(
|
|
135
|
+
self,
|
|
136
|
+
extend: bool = False,
|
|
137
|
+
content_length: int = 1_000,
|
|
138
|
+
ignore_links: bool = False,
|
|
139
|
+
ignore_images: bool = True,
|
|
140
|
+
**kwargs: Any,
|
|
141
|
+
) -> dict:
|
|
142
|
+
if not extend or not valid_type(str(self.link)):
|
|
143
|
+
return super().model_dump(**kwargs)
|
|
144
|
+
|
|
145
|
+
page_source = await get_page(str(self.link), self._proxy)
|
|
146
|
+
return self._extended_json(page_source, content_length, ignore_links, ignore_images)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
class SearchResults(list):
|
|
150
|
+
def __init__(self, results: list[SearchResult], _proxy: Proxy | None = None):
|
|
151
|
+
super().__init__(results)
|
|
152
|
+
self._proxy = _proxy
|
|
153
|
+
|
|
154
|
+
def markdown(self, extend: bool = False, content_length: int = 400, **kwargs) -> str:
|
|
155
|
+
if not self: # Edge case for no search results
|
|
156
|
+
return ''
|
|
157
|
+
|
|
158
|
+
if not extend:
|
|
159
|
+
content = [result._basic_markdown() for result in self]
|
|
160
|
+
|
|
161
|
+
else:
|
|
162
|
+
page_sources = get_page_sync([str(result.link) for result in self], self._proxy)
|
|
163
|
+
content = [
|
|
164
|
+
result._extended_markdown(page_source=page_source, content_length=content_length, **kwargs)
|
|
165
|
+
for result, page_source in zip(self, page_sources)
|
|
166
|
+
]
|
|
167
|
+
|
|
168
|
+
return '# Search Results\n\n' + '\n----------\n'.join(content)
|
|
169
|
+
|
|
170
|
+
def json(self, extend: bool = False, content_length: int = 400, **kwargs) -> list[dict]:
|
|
171
|
+
if not extend:
|
|
172
|
+
return [result.model_dump() for result in self]
|
|
173
|
+
|
|
174
|
+
page_sources = get_page_sync([str(result.link) for result in self], self._proxy)
|
|
175
|
+
return [
|
|
176
|
+
result._extended_json(page_source=page_source, content_length=content_length, **kwargs)
|
|
177
|
+
for result, page_source in zip(self, page_sources)
|
|
178
|
+
]
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
class AsyncSearchResults(list):
|
|
182
|
+
def __init__(self, results: list[AsyncSearchResult], _proxy: Proxy | None = None):
|
|
183
|
+
super().__init__(results)
|
|
184
|
+
self._proxy = _proxy
|
|
185
|
+
|
|
186
|
+
async def markdown(self, extend: bool = False, content_length: int = 400, **kwargs) -> str:
|
|
187
|
+
if not extend:
|
|
188
|
+
content = [result._basic_markdown() for result in self]
|
|
189
|
+
|
|
190
|
+
else:
|
|
191
|
+
page_sources = await get_page([str(result.link) for result in self], self._proxy)
|
|
192
|
+
content = [
|
|
193
|
+
result._extended_markdown(page_source=page_source, content_length=content_length, **kwargs)
|
|
194
|
+
for result, page_source in zip(self, page_sources)
|
|
195
|
+
]
|
|
196
|
+
|
|
197
|
+
return '# Search Results\n\n' + '\n----------\n'.join(content)
|
|
198
|
+
|
|
199
|
+
async def json(self, extend: bool = False, content_length: int = 400, **kwargs) -> list[dict]:
|
|
200
|
+
if not extend:
|
|
201
|
+
return [result.model_dump() for result in self]
|
|
202
|
+
|
|
203
|
+
page_sources = await get_page([str(result.link) for result in self], self._proxy)
|
|
204
|
+
return [
|
|
205
|
+
result._extended_json(page_source=page_source, content_length=content_length, **kwargs)
|
|
206
|
+
for result, page_source in zip(self, page_sources)
|
|
207
|
+
]
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import time
|
|
2
|
+
import random
|
|
3
|
+
import asyncio
|
|
4
|
+
from typing import Literal
|
|
5
|
+
from functools import partial
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
from tenacity import retry, stop_after_attempt, wait_fixed, retry_if_exception_type
|
|
9
|
+
|
|
10
|
+
from .proxy import Proxy
|
|
11
|
+
from .filters import Filters
|
|
12
|
+
from .parse import parse_search
|
|
13
|
+
from .utils import generate_useragent
|
|
14
|
+
from .search_result import SearchResult, SearchResults, AsyncSearchResult, AsyncSearchResults
|
|
15
|
+
|
|
16
|
+
BASE_URL = 'https://www.google.com/search'
|
|
17
|
+
|
|
18
|
+
retry_httpx = partial(
|
|
19
|
+
retry,
|
|
20
|
+
stop=stop_after_attempt(2),
|
|
21
|
+
wait=wait_fixed(2),
|
|
22
|
+
retry=retry_if_exception_type(httpx.HTTPError),
|
|
23
|
+
reraise=True,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def search(
|
|
28
|
+
query: str = '',
|
|
29
|
+
filters: Filters | None = None,
|
|
30
|
+
mode: Literal['news'] | Literal['search'] = 'search',
|
|
31
|
+
count: int = 10,
|
|
32
|
+
offset: int = 0,
|
|
33
|
+
unique: bool = False,
|
|
34
|
+
safe: bool = True,
|
|
35
|
+
region: str | None = None,
|
|
36
|
+
proxy: Proxy | None = None,
|
|
37
|
+
sleep_time: int = 0.5,
|
|
38
|
+
):
|
|
39
|
+
assert mode in ('news', 'search'), '"mode" must be "news" or "search"'
|
|
40
|
+
|
|
41
|
+
filters = filters.compile_filters() if filters else ''
|
|
42
|
+
compiled_query = f'{query}{" " if filters else ""}{filters}'
|
|
43
|
+
|
|
44
|
+
results = SearchResults(results=[], _proxy=proxy)
|
|
45
|
+
result_set = set()
|
|
46
|
+
|
|
47
|
+
while len(results) < count:
|
|
48
|
+
adjusted_count = (count - len(results)) + 2 # Plus 2 because not all the results are links
|
|
49
|
+
response = _request(compiled_query, mode, adjusted_count, offset, safe, region, proxy)
|
|
50
|
+
|
|
51
|
+
new_results = parse_search(response)
|
|
52
|
+
|
|
53
|
+
if not new_results:
|
|
54
|
+
return results
|
|
55
|
+
|
|
56
|
+
for new_result in new_results:
|
|
57
|
+
if unique:
|
|
58
|
+
if new_result['link'] in result_set:
|
|
59
|
+
continue
|
|
60
|
+
else:
|
|
61
|
+
result_set.add(new_result['link'])
|
|
62
|
+
|
|
63
|
+
results.append(SearchResult(**new_result, _proxy=proxy))
|
|
64
|
+
if len(results) == count:
|
|
65
|
+
return results
|
|
66
|
+
|
|
67
|
+
offset += len(new_results)
|
|
68
|
+
|
|
69
|
+
twenty_percent = sleep_time * 0.10
|
|
70
|
+
time.sleep(random.uniform(sleep_time - twenty_percent, sleep_time + twenty_percent))
|
|
71
|
+
|
|
72
|
+
return results
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
async def async_search(
|
|
76
|
+
query: str = '',
|
|
77
|
+
filters: Filters | None = None,
|
|
78
|
+
mode: Literal['news'] | Literal['search'] = 'search',
|
|
79
|
+
count: int = 10,
|
|
80
|
+
offset: int = 0,
|
|
81
|
+
unique: bool = False,
|
|
82
|
+
safe: bool = True,
|
|
83
|
+
region: str | None = None,
|
|
84
|
+
proxy: Proxy | None = None,
|
|
85
|
+
sleep_time: int = 0.5,
|
|
86
|
+
):
|
|
87
|
+
assert mode in ('news', 'search'), '"mode" must be "news" or "search"'
|
|
88
|
+
|
|
89
|
+
filters = filters.compile_filters() if filters else ''
|
|
90
|
+
compiled_query = f'{query}{" " if filters else ""}{filters}'
|
|
91
|
+
|
|
92
|
+
results = AsyncSearchResults(results=[], _proxy=proxy)
|
|
93
|
+
result_set = set()
|
|
94
|
+
|
|
95
|
+
while len(results) < count:
|
|
96
|
+
adjusted_count = (count - len(results)) + 2 # Plus 2 because not all the results are links
|
|
97
|
+
response = await _async_request(compiled_query, mode, adjusted_count, offset, safe, region, proxy)
|
|
98
|
+
|
|
99
|
+
new_results = parse_search(response)
|
|
100
|
+
|
|
101
|
+
if not new_results:
|
|
102
|
+
return results
|
|
103
|
+
|
|
104
|
+
for new_result in new_results:
|
|
105
|
+
if unique:
|
|
106
|
+
if new_result['link'] in result_set:
|
|
107
|
+
continue
|
|
108
|
+
else:
|
|
109
|
+
result_set.add(new_result['link'])
|
|
110
|
+
|
|
111
|
+
results.append(AsyncSearchResult(**new_result, _proxy=proxy))
|
|
112
|
+
if len(results) == count:
|
|
113
|
+
return results
|
|
114
|
+
|
|
115
|
+
offset += len(new_results)
|
|
116
|
+
|
|
117
|
+
twenty_percent = sleep_time * 0.10
|
|
118
|
+
await asyncio.sleep(random.uniform(sleep_time - twenty_percent, sleep_time + twenty_percent))
|
|
119
|
+
|
|
120
|
+
return results
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def generate_request_params(
|
|
124
|
+
query: str,
|
|
125
|
+
mode: Literal['news'] | Literal['search'],
|
|
126
|
+
number: int,
|
|
127
|
+
offset: int,
|
|
128
|
+
safe: bool,
|
|
129
|
+
region: str | None,
|
|
130
|
+
proxy: Proxy | None,
|
|
131
|
+
) -> tuple[dict, dict, dict, str | None]:
|
|
132
|
+
params = {
|
|
133
|
+
'q': query,
|
|
134
|
+
'num': number,
|
|
135
|
+
'start': offset,
|
|
136
|
+
'safe': 'active' if safe else 'off',
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
if region:
|
|
140
|
+
params['gl'] = region
|
|
141
|
+
if mode == 'news':
|
|
142
|
+
params['tbm'] = 'nws'
|
|
143
|
+
|
|
144
|
+
cookies = {'CONSENT': 'PENDING+987', 'SOCS': 'CAESHAgBEhIaAB'}
|
|
145
|
+
|
|
146
|
+
headers = {
|
|
147
|
+
'Accept': 'text/html, text/plain, text/sgml, text/css, */*;q=0.01',
|
|
148
|
+
'Accept-Encoding': 'gzip, compress, bzip2',
|
|
149
|
+
'Accept-Language': 'en',
|
|
150
|
+
'User-Agent': generate_useragent(),
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
httpx_proxy = proxy.to_httpx_proxy_url() if proxy else None
|
|
154
|
+
|
|
155
|
+
return params, cookies, headers, httpx_proxy
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
@retry_httpx()
|
|
159
|
+
def _request(
|
|
160
|
+
query: str,
|
|
161
|
+
mode: Literal['news'] | Literal['search'],
|
|
162
|
+
number: int,
|
|
163
|
+
offset: int,
|
|
164
|
+
safe: bool,
|
|
165
|
+
region: str | None,
|
|
166
|
+
proxy: Proxy | None,
|
|
167
|
+
) -> str:
|
|
168
|
+
params, cookies, headers, httpx_proxy = generate_request_params(query, mode, number, offset, safe, region, proxy)
|
|
169
|
+
with httpx.Client(proxy=httpx_proxy, headers=headers, cookies=cookies) as client:
|
|
170
|
+
resp = client.get(BASE_URL, params=params)
|
|
171
|
+
resp.raise_for_status()
|
|
172
|
+
return resp.text
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
@retry_httpx()
|
|
176
|
+
async def _async_request(
|
|
177
|
+
query: str,
|
|
178
|
+
mode: Literal['news'] | Literal['search'],
|
|
179
|
+
number: int,
|
|
180
|
+
offset: int,
|
|
181
|
+
safe: bool,
|
|
182
|
+
region: str | None,
|
|
183
|
+
proxy: Proxy | None,
|
|
184
|
+
) -> str:
|
|
185
|
+
params, cookies, headers, httpx_proxy = generate_request_params(query, mode, number, offset, safe, region, proxy)
|
|
186
|
+
async with httpx.AsyncClient(proxy=httpx_proxy, headers=headers, cookies=cookies) as client:
|
|
187
|
+
resp = await client.get(BASE_URL, params=params)
|
|
188
|
+
resp.raise_for_status()
|
|
189
|
+
return resp.text
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import random
|
|
2
|
+
import mimetypes
|
|
3
|
+
|
|
4
|
+
import html2text
|
|
5
|
+
from lxml import html, etree
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def extract_metadata(page_source: str) -> dict:
|
|
9
|
+
try:
|
|
10
|
+
tree = html.fromstring(page_source)
|
|
11
|
+
except Exception:
|
|
12
|
+
return {}
|
|
13
|
+
|
|
14
|
+
page_title = tree.xpath('//head/title/text()')
|
|
15
|
+
page_description = tree.xpath('//head/meta[@name="description"]/@content')
|
|
16
|
+
author = tree.xpath('//head/meta[@name="author"]/@content')
|
|
17
|
+
twitter_handle = tree.xpath('//head/meta[@name="twitter:site"]/@content')
|
|
18
|
+
|
|
19
|
+
result = {}
|
|
20
|
+
|
|
21
|
+
if page_title:
|
|
22
|
+
result['title'] = page_title[0]
|
|
23
|
+
if page_description and valid_description_metadata(page_description[0]):
|
|
24
|
+
result['description'] = page_description[0]
|
|
25
|
+
if author:
|
|
26
|
+
result['author'] = author[0]
|
|
27
|
+
if twitter_handle:
|
|
28
|
+
result['twitter'] = twitter_handle[0]
|
|
29
|
+
|
|
30
|
+
return result
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def valid_description_metadata(desc: str) -> bool:
|
|
34
|
+
try:
|
|
35
|
+
etree.fromstring(desc)
|
|
36
|
+
return False
|
|
37
|
+
except etree.XMLSyntaxError:
|
|
38
|
+
return True
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def generate_markdown(page_source: str, ignore_links: bool, ignore_images: bool) -> str:
|
|
42
|
+
text_maker = html2text.HTML2Text()
|
|
43
|
+
text_maker.ignore_links = ignore_links
|
|
44
|
+
text_maker.ignore_images = ignore_images
|
|
45
|
+
text_maker.body_width = 0 # Prevent automatic wrapping
|
|
46
|
+
return text_maker.handle(page_source).strip()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def valid_type(url: str) -> bool:
|
|
50
|
+
"""
|
|
51
|
+
Currently, only text / html pages are supported for extended data retrival.
|
|
52
|
+
"""
|
|
53
|
+
mime, _ = mimetypes.guess_type(url)
|
|
54
|
+
return mime in ('text/html', 'text/plain', 'application/xhtml+xml', None)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def generate_useragent() -> str:
|
|
58
|
+
"""
|
|
59
|
+
Returns a Lynx browser User Agent string.
|
|
60
|
+
|
|
61
|
+
The idea to use the Lynx browser User Agent was from
|
|
62
|
+
the following GitHub project: https://github.com/Nv7-GitHub/googlesearch
|
|
63
|
+
|
|
64
|
+
Returns:
|
|
65
|
+
str: A User Agent string for the Lynx browser.
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
# Lynx: 2.8.5–2.9.2 or 3.0.0–3.2.0
|
|
69
|
+
major = random.choice([2, 3])
|
|
70
|
+
if major == 2:
|
|
71
|
+
minor = random.randint(8, 9)
|
|
72
|
+
patch = random.randint(0, 2)
|
|
73
|
+
else:
|
|
74
|
+
minor = random.randint(0, 2)
|
|
75
|
+
patch = 0
|
|
76
|
+
lynx_version = f'Lynx/{major}.{minor}.{patch}'
|
|
77
|
+
|
|
78
|
+
# libwww-FM: realistically 2.14 ± small variance
|
|
79
|
+
libwww_version = f'libwww-FM/{random.choice([13, 14, 15])}'
|
|
80
|
+
|
|
81
|
+
# SSL-MM: pin around 1.4.x
|
|
82
|
+
ssl_mm_version = f'SSL-MM/1.{random.randint(4, 5)}.{random.randint(0, 9)}'
|
|
83
|
+
|
|
84
|
+
# OpenSSL: legacy 1.1.x or modern 3.x (3.4–3.5)
|
|
85
|
+
openssl_major = random.choice([1, 3])
|
|
86
|
+
if openssl_major == 1:
|
|
87
|
+
openssl_minor = random.randint(0, 1)
|
|
88
|
+
else:
|
|
89
|
+
openssl_minor = random.randint(4, 5)
|
|
90
|
+
openssl_patch = random.randint(0, 9)
|
|
91
|
+
openssl_version = f'OpenSSL/{openssl_major}.{openssl_minor}.{openssl_patch}'
|
|
92
|
+
|
|
93
|
+
return f'{lynx_version} {libwww_version} {ssl_mm_version} {openssl_version}'
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: search-ai-core
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Google Search & News tool with advanced filters and LLM-friendly output formats!
|
|
5
|
+
Author-email: Jacob Padilla <searchai@jacobpadilla.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/jpjacobpadilla/SearchAI
|
|
8
|
+
Keywords: python,search,markdown,search-engine,data,google,ai,web-crawler,googlesearch,googlenews,llm
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
Requires-Dist: html2text>=2025.4.15
|
|
12
|
+
Requires-Dist: httpx[socks]>=0.28.1
|
|
13
|
+
Requires-Dist: lxml>=5.4.0
|
|
14
|
+
Requires-Dist: nest-asyncio>=1.6.0
|
|
15
|
+
Requires-Dist: playwright>=1.52.0
|
|
16
|
+
Requires-Dist: publicsuffix2>=2.20191221
|
|
17
|
+
Requires-Dist: pydantic>=2.11.5
|
|
18
|
+
Requires-Dist: tenacity>=9.1.2
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
search_ai/__init__.py
|
|
4
|
+
search_ai/extractor.py
|
|
5
|
+
search_ai/filters.py
|
|
6
|
+
search_ai/parse.py
|
|
7
|
+
search_ai/proxy.py
|
|
8
|
+
search_ai/search_result.py
|
|
9
|
+
search_ai/searcher.py
|
|
10
|
+
search_ai/utils.py
|
|
11
|
+
search_ai_core.egg-info/PKG-INFO
|
|
12
|
+
search_ai_core.egg-info/SOURCES.txt
|
|
13
|
+
search_ai_core.egg-info/dependency_links.txt
|
|
14
|
+
search_ai_core.egg-info/requires.txt
|
|
15
|
+
search_ai_core.egg-info/top_level.txt
|
|
16
|
+
tests/test_filters.py
|
|
17
|
+
tests/test_proxy.py
|
|
18
|
+
tests/test_search_results.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
search_ai
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
from datetime import date
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from search_ai import Filters
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@pytest.mark.parametrize(
|
|
9
|
+
'field, value, expected',
|
|
10
|
+
[
|
|
11
|
+
('sites', 'example_a.com', 'site:example_a.com'),
|
|
12
|
+
('sites', ['example_a.com', 'example_b.com'], '(site:example_a.com | site:example_b.com)'),
|
|
13
|
+
('tlds', '.gov', 'site:.gov'),
|
|
14
|
+
('tlds', ['.gov', '.edu'], '(site:.gov | site:.edu)'),
|
|
15
|
+
('filetype', 'pdf', 'filetype:pdf'),
|
|
16
|
+
('https_only', True, 'inurl:https'),
|
|
17
|
+
('before', date(1999, 12, 31), 'before:1999-12-31'),
|
|
18
|
+
('before', date(2023, 6, 15), 'before:2023-06-15'),
|
|
19
|
+
('before', date(2100, 1, 1), 'before:2100-01-01'),
|
|
20
|
+
('after', date(2000, 1, 1), 'after:2000-01-01'),
|
|
21
|
+
('after', date(2022, 11, 30), 'after:2022-11-30'),
|
|
22
|
+
('after', date(2099, 12, 31), 'after:2099-12-31'),
|
|
23
|
+
('all_keywords', 'ai', '"ai"'),
|
|
24
|
+
('all_keywords', ['ai', 'ml'], '"ai" "ml"'),
|
|
25
|
+
('all_keywords', ['ai'], '"ai"'),
|
|
26
|
+
('any_keywords', 'ai', '"ai"'),
|
|
27
|
+
('any_keywords', ['ai', 'ml'], '("ai" | "ml")'),
|
|
28
|
+
('any_keywords', ['ai'], '"ai"'),
|
|
29
|
+
('exact_phrases', 'openai api', '"openai api"'),
|
|
30
|
+
('exact_phrases', ['foo bar', 'baz qux'], '"foo bar" "baz qux"'),
|
|
31
|
+
('in_title', 'research', 'intitle:research'),
|
|
32
|
+
('in_title', ['ai', 'ml'], 'intitle:ai intitle:ml'),
|
|
33
|
+
('in_url', 'docs', 'inurl:docs'),
|
|
34
|
+
('in_url', ['api', 'ref'], 'inurl:api inurl:ref'),
|
|
35
|
+
('in_text', 'hello', 'intext:hello'),
|
|
36
|
+
('in_text', ['world', 'vector'], 'intext:world intext:vector'),
|
|
37
|
+
('exclude_sites', 'spam.com', '-site:spam.com'),
|
|
38
|
+
('exclude_sites', ['a.com', 'b.com'], '-site:a.com -site:b.com'),
|
|
39
|
+
('exclude_tlds', '.biz', '-site:.biz'),
|
|
40
|
+
('exclude_tlds', ['.xyz', '.info'], '-site:.xyz -site:.info'),
|
|
41
|
+
('exclude_filetypes', 'exe', '-filetype:exe'),
|
|
42
|
+
('exclude_filetypes', ['bin', 'dat'], '-filetype:bin -filetype:dat'),
|
|
43
|
+
('exclude_https', True, '-inurl:https'),
|
|
44
|
+
('exclude_all_keywords', 'ads', '-ads'),
|
|
45
|
+
('exclude_all_keywords', ['spam', 'click'], '-spam -click'),
|
|
46
|
+
('exclude_all_keywords', ['ads'], '-ads'),
|
|
47
|
+
('exclude_exact_phrases', 'bad ad', '-"bad ad"'),
|
|
48
|
+
('exclude_exact_phrases', ['fake news', 'scam'], '-"fake news" -"scam"'),
|
|
49
|
+
('not_in_title', 'promo', '-intitle:promo'),
|
|
50
|
+
('not_in_title', ['clickbait', 'ad'], '-intitle:clickbait -intitle:ad'),
|
|
51
|
+
('not_in_url', 'track', '-inurl:track'),
|
|
52
|
+
('not_in_url', ['ref', 'share'], '-inurl:ref -inurl:share'),
|
|
53
|
+
('not_in_text', 'cookie', '-intext:cookie'),
|
|
54
|
+
('not_in_text', ['ads', 'popup'], '-intext:ads -intext:popup'),
|
|
55
|
+
],
|
|
56
|
+
)
|
|
57
|
+
def test_individual_fields(field, value, expected):
|
|
58
|
+
filter_obj = Filters(**{field: value})
|
|
59
|
+
compiled_filters = filter_obj.compile_filters()
|
|
60
|
+
assert compiled_filters == expected
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@pytest.mark.parametrize(
|
|
64
|
+
'field, value',
|
|
65
|
+
[
|
|
66
|
+
('filetype', 'toolongfilename123'),
|
|
67
|
+
('filetype', 'we!rd'),
|
|
68
|
+
('exclude_filetypes', 'we!rd'),
|
|
69
|
+
('exclude_filetypes', ['bad!', '!!']),
|
|
70
|
+
('all_keywords', 'with space'),
|
|
71
|
+
('all_keywords', 'with space'),
|
|
72
|
+
('any_keywords', ['ok', 'bad word']),
|
|
73
|
+
('any_keywords', ['ok', 'bad word']),
|
|
74
|
+
('exclude_all_keywords', 'white space'),
|
|
75
|
+
('exclude_all_keywords', ['fine', 'break this']),
|
|
76
|
+
('tlds', '.invalidtld'),
|
|
77
|
+
('tlds', ['.edu', '.badzone']),
|
|
78
|
+
('exclude_tlds', '.invalidtld'),
|
|
79
|
+
('exclude_tlds', ['.edu', '.badzone']),
|
|
80
|
+
],
|
|
81
|
+
)
|
|
82
|
+
def test_field_validation(field, value):
|
|
83
|
+
with pytest.raises(ValueError, match=r'.*'):
|
|
84
|
+
Filters(**{field: value})
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@pytest.mark.parametrize(
|
|
88
|
+
'kwargs, expected',
|
|
89
|
+
[
|
|
90
|
+
({'sites': 'example.com', 'all_keywords': 'ai'}, 'site:example.com "ai"'),
|
|
91
|
+
({'tlds': '.com', 'all_keywords': ['ai', 'llm']}, 'site:.com "ai" "llm"'),
|
|
92
|
+
({'tlds': '.com', 'any_keywords': ['ai', 'llm']}, 'site:.com ("ai" | "llm")'),
|
|
93
|
+
(
|
|
94
|
+
{
|
|
95
|
+
'sites': ['a.com', 'b.com'],
|
|
96
|
+
'filetype': 'pdf',
|
|
97
|
+
'exact_phrases': ['openai api', 'machine learning'],
|
|
98
|
+
'https_only': True,
|
|
99
|
+
'in_title': ['research', 'ai'],
|
|
100
|
+
},
|
|
101
|
+
'(site:a.com | site:b.com) filetype:pdf "openai api" "machine learning" inurl:https intitle:research intitle:ai',
|
|
102
|
+
),
|
|
103
|
+
(
|
|
104
|
+
{
|
|
105
|
+
'exclude_sites': ['spam.com'],
|
|
106
|
+
'exclude_all_keywords': ['ads', 'clickbait'],
|
|
107
|
+
'not_in_url': 'ref',
|
|
108
|
+
'exclude_https': True,
|
|
109
|
+
},
|
|
110
|
+
'-site:spam.com -inurl:https -ads -clickbait -inurl:ref',
|
|
111
|
+
),
|
|
112
|
+
(
|
|
113
|
+
{
|
|
114
|
+
'tlds': ['.gov', '.edu'],
|
|
115
|
+
'before': date(2020, 1, 1),
|
|
116
|
+
'after': date(2010, 5, 10),
|
|
117
|
+
'in_text': ['compliance', 'report'],
|
|
118
|
+
'exclude_tlds': ['.xyz'],
|
|
119
|
+
},
|
|
120
|
+
'(site:.gov | site:.edu) intext:compliance intext:report before:2020-01-01 after:2010-05-10 -site:.xyz',
|
|
121
|
+
),
|
|
122
|
+
(
|
|
123
|
+
{
|
|
124
|
+
'filetype': 'ppt',
|
|
125
|
+
'exclude_filetypes': ['exe', 'bat'],
|
|
126
|
+
'any_keywords': ['presentation', 'slides'],
|
|
127
|
+
},
|
|
128
|
+
'filetype:ppt ("presentation" | "slides") -filetype:exe -filetype:bat',
|
|
129
|
+
),
|
|
130
|
+
(
|
|
131
|
+
{'in_url': 'docs', 'in_title': 'introduction', 'exclude_exact_phrases': 'outdated info'},
|
|
132
|
+
'intitle:introduction inurl:docs -"outdated info"',
|
|
133
|
+
),
|
|
134
|
+
(
|
|
135
|
+
{'sites': 'example.org', 'in_text': 'summary', 'exclude_all_keywords': 'draft'},
|
|
136
|
+
'site:example.org intext:summary -draft',
|
|
137
|
+
),
|
|
138
|
+
(
|
|
139
|
+
{'sites': 'example.org', 'in_text': 'summary', 'exclude_all_keywords': ['draft', 'ai', 'bot']},
|
|
140
|
+
'site:example.org intext:summary -draft -ai -bot',
|
|
141
|
+
),
|
|
142
|
+
(
|
|
143
|
+
{
|
|
144
|
+
'sites': ['news.com', 'media.com'],
|
|
145
|
+
'in_url': ['breaking', 'live'],
|
|
146
|
+
'not_in_text': ['subscribe', 'cookie'],
|
|
147
|
+
},
|
|
148
|
+
'(site:news.com | site:media.com) inurl:breaking inurl:live -intext:subscribe -intext:cookie',
|
|
149
|
+
),
|
|
150
|
+
(
|
|
151
|
+
{
|
|
152
|
+
'exact_phrases': 'deep learning',
|
|
153
|
+
'exclude_exact_phrases': 'deprecated method',
|
|
154
|
+
'in_title': 'tutorial',
|
|
155
|
+
'not_in_title': 'sponsored',
|
|
156
|
+
},
|
|
157
|
+
'"deep learning" intitle:tutorial -"deprecated method" -intitle:sponsored',
|
|
158
|
+
),
|
|
159
|
+
],
|
|
160
|
+
)
|
|
161
|
+
def test_combined_fields(kwargs, expected):
|
|
162
|
+
filter_obj = Filters(**kwargs)
|
|
163
|
+
compiled_filters = filter_obj.compile_filters()
|
|
164
|
+
assert compiled_filters == expected
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
|
|
3
|
+
from search_ai import Proxy
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@pytest.fixture
|
|
7
|
+
def proxy_with_auth() -> Proxy:
|
|
8
|
+
return Proxy(protocol='http', host='127.0.0.1', port=8080, username='user', password='pass')
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@pytest.fixture
|
|
12
|
+
def proxy_no_auth() -> Proxy:
|
|
13
|
+
return Proxy(protocol='https', host='proxy.io', port=443)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def test_to_httpx_proxy_url_with_auth(proxy_with_auth):
|
|
17
|
+
assert proxy_with_auth.to_httpx_proxy_url() == 'http://user:pass@127.0.0.1:8080'
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def test_to_httpx_proxy_url_no_auth(proxy_no_auth):
|
|
21
|
+
assert proxy_no_auth.to_httpx_proxy_url() == 'https://proxy.io:443'
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def test_to_playwright_proxy_with_auth(proxy_with_auth):
|
|
25
|
+
expected = {'server': 'http://127.0.0.1:8080', 'username': 'user', 'password': 'pass'}
|
|
26
|
+
assert proxy_with_auth.to_playwright_proxy() == expected
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def test_to_playwright_proxy_no_auth(proxy_no_auth):
|
|
30
|
+
expected = {'server': 'https://proxy.io:443'}
|
|
31
|
+
assert proxy_no_auth.to_playwright_proxy() == expected
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
from pydantic import HttpUrl
|
|
3
|
+
from search_ai.search_result import (
|
|
4
|
+
SearchResult,
|
|
5
|
+
AsyncSearchResult,
|
|
6
|
+
SearchResults,
|
|
7
|
+
AsyncSearchResults,
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@pytest.fixture
|
|
12
|
+
def sample_data():
|
|
13
|
+
return {'title': 'Example Title', 'link': 'https://example.com', 'description': 'An example description.'}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def test_search_result(sample_data):
|
|
17
|
+
result = SearchResult(**sample_data)
|
|
18
|
+
|
|
19
|
+
assert result.title == sample_data['title']
|
|
20
|
+
assert result.link == HttpUrl(sample_data['link'])
|
|
21
|
+
assert result.description == sample_data['description']
|
|
22
|
+
|
|
23
|
+
markdown = result.markdown()
|
|
24
|
+
assert '**Title:**' in markdown
|
|
25
|
+
assert '**Link:**' in markdown
|
|
26
|
+
assert '**Description:**' in markdown
|
|
27
|
+
|
|
28
|
+
json_data = result.json()
|
|
29
|
+
for key, val in sample_data.items():
|
|
30
|
+
if key == 'link':
|
|
31
|
+
assert json_data[key] == HttpUrl(val)
|
|
32
|
+
else:
|
|
33
|
+
assert json_data[key] == val
|
|
34
|
+
|
|
35
|
+
assert set(json_data.keys()) == set(sample_data.keys())
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@pytest.mark.asyncio
|
|
39
|
+
async def test_async_search_result(sample_data):
|
|
40
|
+
result = AsyncSearchResult(**sample_data)
|
|
41
|
+
assert result.title == sample_data['title']
|
|
42
|
+
assert result.link == HttpUrl(sample_data['link'])
|
|
43
|
+
assert result.description == sample_data['description']
|
|
44
|
+
|
|
45
|
+
markdown = await result.markdown()
|
|
46
|
+
assert '**Title:**' in markdown
|
|
47
|
+
assert '**Link:**' in markdown
|
|
48
|
+
assert '**Description:**' in markdown
|
|
49
|
+
|
|
50
|
+
json_data = await result.json()
|
|
51
|
+
for key, val in sample_data.items():
|
|
52
|
+
if key == 'link':
|
|
53
|
+
assert json_data[key] == HttpUrl(val)
|
|
54
|
+
else:
|
|
55
|
+
assert json_data[key] == val
|
|
56
|
+
|
|
57
|
+
assert set(json_data.keys()) == set(sample_data.keys())
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_search_results(sample_data):
|
|
61
|
+
r1 = SearchResult(**sample_data)
|
|
62
|
+
r2 = SearchResult(**sample_data)
|
|
63
|
+
results = SearchResults(results=[r1, r2])
|
|
64
|
+
|
|
65
|
+
markdown = results.markdown()
|
|
66
|
+
assert markdown.count('**Title:**') == 2
|
|
67
|
+
assert markdown.startswith('# Search Results')
|
|
68
|
+
|
|
69
|
+
json_data = results.json()
|
|
70
|
+
assert isinstance(json_data, list)
|
|
71
|
+
assert len(json_data) == 2
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@pytest.mark.asyncio
|
|
75
|
+
async def test_async_search_results(sample_data):
|
|
76
|
+
r1 = AsyncSearchResult(**sample_data)
|
|
77
|
+
r2 = AsyncSearchResult(**sample_data)
|
|
78
|
+
results = AsyncSearchResults(results=[r1, r2])
|
|
79
|
+
|
|
80
|
+
markdown = await results.markdown()
|
|
81
|
+
assert markdown.count('**Title:**') == 2
|
|
82
|
+
assert markdown.startswith('# Search Results')
|
|
83
|
+
|
|
84
|
+
json_data = await results.json()
|
|
85
|
+
assert isinstance(json_data, list)
|
|
86
|
+
assert len(json_data) == 2
|