File size: 1,901 Bytes
4cf88e8 |
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 |
from typing import Union
from langchain.docstore.base import Docstore
from langchain.docstore.document import Document
class Wiki(Docstore):
"""
Wrapper around wikipedia API.
"""
def __init__(self) -> None:
"""Check that wikipedia package is installed."""
try:
import wikipedia # noqa: F401
except ImportError:
raise ValueError(
"Could not import wikipedia python package. "
"Please install it with `pip install wikipedia`."
)
@staticmethod
def fetch(searched_page: str) -> Union[str, Document]:
"""
Try to fetch for wiki page.
If page exists, return the page summary, and a PageWithLookups object.
If page does not exist, return similar entries.
"""
import wikipedia
try:
# wikipedia.set_lang("fr")
page_content = wikipedia.page(searched_page).content
url = wikipedia.page(searched_page).url
result: Union[str, Document] = Document(
page_content=page_content, metadata={"page": url}
)
except wikipedia.PageError:
result = f"Could not find [{searched_page}]. Similar: {wikipedia.search(searched_page)}"
except wikipedia.DisambiguationError:
result = f"Could not find [{searched_page}]. Similar: {wikipedia.search(searched_page)}"
return result
def search(searched_context: str) -> [str]:
"""
Finds wiki page title in relation with the given context
"""
import wikipedia
try:
# wikipedia.set_lang("fr")
page_title_list = wikipedia.search(searched_context)
result = page_title_list
except wikipedia.PageError:
result = f"Could not find [{searched_context}]."
return result
|