選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

duckduckgosearch.py 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import random
  17. from abc import ABC
  18. from functools import partial
  19. from duckduckgo_search import DDGS
  20. import pandas as pd
  21. from graph.component.base import ComponentBase, ComponentParamBase
  22. class DuckDuckGoSearchParam(ComponentParamBase):
  23. """
  24. Define the DuckDuckGoSearch component parameters.
  25. """
  26. def __init__(self):
  27. super().__init__()
  28. self.top_n = 10
  29. self.channel = "text"
  30. def check(self):
  31. self.check_positive_integer(self.top_n, "Top N")
  32. self.check_valid_value(self.channel, "Web Search or News", ["text", "news"])
  33. class DuckDuckGoSearch(ComponentBase, ABC):
  34. component_name = "DuckDuckGoSearch"
  35. def _run(self, history, **kwargs):
  36. ans = self.get_input()
  37. ans = " - ".join(ans["content"]) if "content" in ans else ""
  38. if not ans:
  39. return Baidu.be_output(self._param.no)
  40. if self.channel == "text":
  41. with DDGS() as ddgs:
  42. # {'title': '', 'href': '', 'body': ''}
  43. duck_res = ['<a href="' + i["href"] + '">' + i["title"] + '</a> ' + i["body"] for i in
  44. ddgs.text(ans, max_results=self._param.top_n)]
  45. elif self.channel == "news":
  46. with DDGS() as ddgs:
  47. # {'date': '', 'title': '', 'body': '', 'url': '', 'image': '', 'source': ''}
  48. duck_res = ['<a href="' + i["url"] + '">' + i["title"] + '</a> ' + i["body"] for i in
  49. ddgs.news(ans, max_results=self._param.top_n)]
  50. print(duck_res, ":::::::::::::::::::::::::::::::::")
  51. return DuckDuckGoSearch.be_output(duck_res)