|
| 1 | +import base64 |
| 2 | +import io |
| 3 | +import json |
| 4 | +import logging |
| 5 | +import os |
| 6 | +from typing import Optional, List |
| 7 | + |
| 8 | +import requests |
| 9 | + |
| 10 | +from fastapi import Request |
| 11 | + |
| 12 | +from open_webui.retrieval.web.main import SearchResult, get_filtered_results |
| 13 | +from open_webui.utils.headers import include_user_info_headers |
| 14 | + |
| 15 | +from xml.etree import ElementTree as ET |
| 16 | +from xml.etree.ElementTree import Element |
| 17 | + |
| 18 | +log = logging.getLogger(__name__) |
| 19 | + |
| 20 | + |
| 21 | +def xml_element_contents_to_string(element: Element) -> str: |
| 22 | + buffer = [element.text if element.text else ""] |
| 23 | + |
| 24 | + for child in element: |
| 25 | + buffer.append(xml_element_contents_to_string(child)) |
| 26 | + |
| 27 | + buffer.append(element.tail if element.tail else "") |
| 28 | + |
| 29 | + return "".join(buffer) |
| 30 | + |
| 31 | + |
| 32 | +def search_yandex( |
| 33 | + request: Request, |
| 34 | + yandex_search_url: str, |
| 35 | + yandex_search_api_key: str, |
| 36 | + yandex_search_config: str, |
| 37 | + query: str, |
| 38 | + count: int, |
| 39 | + filter_list: Optional[List[str]] = None, |
| 40 | + user=None, |
| 41 | +) -> List[SearchResult]: |
| 42 | + try: |
| 43 | + headers = { |
| 44 | + "User-Agent": "Open WebUI (https://github.com/open-webui/open-webui) RAG Bot", |
| 45 | + "Authorization": f"Api-Key {yandex_search_api_key}", |
| 46 | + } |
| 47 | + |
| 48 | + if user is not None: |
| 49 | + headers = include_user_info_headers(headers, user) |
| 50 | + |
| 51 | + chat_id = getattr(request.state, "chat_id", None) |
| 52 | + if chat_id: |
| 53 | + headers["X-OpenWebUI-Chat-Id"] = str(chat_id) |
| 54 | + |
| 55 | + payload = {} if yandex_search_config == "" else json.loads(yandex_search_config) |
| 56 | + |
| 57 | + if type(payload.get("query", None)) != dict: |
| 58 | + payload["query"] = {} |
| 59 | + |
| 60 | + if "searchType" not in payload["query"]: |
| 61 | + payload["query"]["searchType"] = "SEARCH_TYPE_RU" |
| 62 | + |
| 63 | + payload["query"]["queryText"] = query |
| 64 | + |
| 65 | + if type(payload.get("groupSpec", None)) != dict: |
| 66 | + payload["groupSpec"] = {} |
| 67 | + |
| 68 | + if "groupMode" not in payload["groupSpec"]: |
| 69 | + payload["groupSpec"]["groupMode"] = "GROUP_MODE_DEEP" |
| 70 | + |
| 71 | + payload["groupSpec"]["groupsOnPage"] = count |
| 72 | + payload["groupSpec"]["docsInGroup"] = 1 |
| 73 | + |
| 74 | + response = requests.post( |
| 75 | + "https://searchapi.api.cloud.yandex.net/v2/web/search" if yandex_search_url == "" else yandex_search_url, |
| 76 | + headers=headers, |
| 77 | + json=payload, |
| 78 | + ) |
| 79 | + |
| 80 | + response.raise_for_status() |
| 81 | + |
| 82 | + response_body = response.json() |
| 83 | + if "rawData" not in response_body: |
| 84 | + raise Exception(f"No `rawData` in response body: {response_body}") |
| 85 | + |
| 86 | + search_result_body_bytes = base64.decodebytes(bytes(response_body["rawData"], "utf-8")) |
| 87 | + |
| 88 | + doc_root = ET.parse(io.BytesIO(search_result_body_bytes)) |
| 89 | + |
| 90 | + results = [] |
| 91 | + |
| 92 | + for group in doc_root.findall("response/results/grouping/group"): |
| 93 | + results.append({ |
| 94 | + "url": xml_element_contents_to_string(group.find("doc/url")).strip("\n"), |
| 95 | + "title": xml_element_contents_to_string(group.find("doc/title")).strip("\n"), |
| 96 | + "snippet": xml_element_contents_to_string(group.find("doc/passages/passage")), |
| 97 | + }) |
| 98 | + |
| 99 | + results = get_filtered_results(results, filter_list) |
| 100 | + |
| 101 | + results = [ |
| 102 | + SearchResult( |
| 103 | + link=result.get("url"), |
| 104 | + title=result.get("title"), |
| 105 | + snippet=result.get("snippet"), |
| 106 | + ) |
| 107 | + for result in results[:count] |
| 108 | + ] |
| 109 | + |
| 110 | + log.info(f"Yandex search results: {results}") |
| 111 | + |
| 112 | + return results |
| 113 | + except Exception as e: |
| 114 | + log.error(f"Error in search: {e}") |
| 115 | + |
| 116 | + return [] |
| 117 | + |
| 118 | + |
| 119 | +if __name__ == "__main__": |
| 120 | + from starlette.datastructures import Headers |
| 121 | + from fastapi import FastAPI |
| 122 | + |
| 123 | + result = search_yandex( |
| 124 | + Request( |
| 125 | + { |
| 126 | + "type": "http", |
| 127 | + "asgi.version": "3.0", |
| 128 | + "asgi.spec_version": "2.0", |
| 129 | + "method": "GET", |
| 130 | + "path": "/internal", |
| 131 | + "query_string": b"", |
| 132 | + "headers": Headers({}).raw, |
| 133 | + "client": ("127.0.0.1", 12345), |
| 134 | + "server": ("127.0.0.1", 80), |
| 135 | + "scheme": "http", |
| 136 | + "app": FastAPI(), |
| 137 | + }, |
| 138 | + None, |
| 139 | + ), |
| 140 | + os.environ.get("YANDEX_WEB_SEARCH_URL", ""), |
| 141 | + os.environ.get("YANDEX_WEB_SEARCH_API_KEY", ""), |
| 142 | + os.environ.get("YANDEX_WEB_SEARCH_CONFIG", "{\"query\": {\"searchType\": \"SEARCH_TYPE_COM\"}}"), |
| 143 | + "TOP movies of the past year", |
| 144 | + 3, |
| 145 | + ) |
| 146 | + |
| 147 | + print(result) |
0 commit comments