You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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.settings import DEBUG
  22. from graph.component.base import ComponentBase, ComponentParamBase
  23. class DuckDuckGoParam(ComponentParamBase):
  24. """
  25. Define the DuckDuckGo component parameters.
  26. """
  27. def __init__(self):
  28. super().__init__()
  29. self.top_n = 10
  30. self.channel = "text"
  31. def check(self):
  32. self.check_positive_integer(self.top_n, "Top N")
  33. self.check_valid_value(self.channel, "Web Search or News", ["text", "news"])
  34. class DuckDuckGo(ComponentBase, ABC):
  35. component_name = "DuckDuckGo"
  36. def _run(self, history, **kwargs):
  37. ans = self.get_input()
  38. ans = " - ".join(ans["content"]) if "content" in ans else ""
  39. if not ans:
  40. return DuckDuckGo.be_output("")
  41. if self._param.channel == "text":
  42. with DDGS() as ddgs:
  43. # {'title': '', 'href': '', 'body': ''}
  44. duck_res = [{"content": '<a href="' + i["href"] + '">' + i["title"] + '</a> ' + i["body"]} for i in
  45. ddgs.text(ans, max_results=self._param.top_n)]
  46. elif self._param.channel == "news":
  47. with DDGS() as ddgs:
  48. # {'date': '', 'title': '', 'body': '', 'url': '', 'image': '', 'source': ''}
  49. duck_res = [{"content": '<a href="' + i["url"] + '">' + i["title"] + '</a> ' + i["body"]} for i in
  50. ddgs.news(ans, max_results=self._param.top_n)]
  51. if not duck_res:
  52. return DuckDuckGo.be_output("")
  53. df = pd.DataFrame(duck_res)
  54. if DEBUG: print(df, ":::::::::::::::::::::::::::::::::")
  55. return df