Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

duckduckgosearch.py 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 duckduckgosearch 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. dr = pd.DataFrame(duck_res, columns=['content'])
  51. print(">>>>>>>>>>>>>>>>>>>>>>>>>>\n", dr)
  52. return dr