Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 logging
  17. from abc import ABC
  18. import pandas as pd
  19. import requests
  20. import re
  21. from agent.component.base import ComponentBase, ComponentParamBase
  22. class BaiduParam(ComponentParamBase):
  23. """
  24. Define the Baidu component parameters.
  25. """
  26. def __init__(self):
  27. super().__init__()
  28. self.top_n = 10
  29. def check(self):
  30. self.check_positive_integer(self.top_n, "Top N")
  31. class Baidu(ComponentBase, ABC):
  32. component_name = "Baidu"
  33. def _run(self, history, **kwargs):
  34. ans = self.get_input()
  35. ans = " - ".join(ans["content"]) if "content" in ans else ""
  36. if not ans:
  37. return Baidu.be_output("")
  38. try:
  39. url = 'https://www.baidu.com/s?wd=' + ans + '&rn=' + str(self._param.top_n)
  40. headers = {
  41. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36'}
  42. response = requests.get(url=url, headers=headers)
  43. url_res = re.findall(r"'url': \\\"(.*?)\\\"}", response.text)
  44. title_res = re.findall(r"'title': \\\"(.*?)\\\",\\n", response.text)
  45. body_res = re.findall(r"\"contentText\":\"(.*?)\"", response.text)
  46. baidu_res = [{"content": re.sub('<em>|</em>', '', '<a href="' + url + '">' + title + '</a> ' + body)} for
  47. url, title, body in zip(url_res, title_res, body_res)]
  48. del body_res, url_res, title_res
  49. except Exception as e:
  50. return Baidu.be_output("**ERROR**: " + str(e))
  51. if not baidu_res:
  52. return Baidu.be_output("")
  53. df = pd.DataFrame(baidu_res)
  54. logging.debug(f"df: {str(df)}")
  55. return df