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.

wikipedia.py 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. import wikipedia
  20. import pandas as pd
  21. from agent.settings import DEBUG
  22. from agent.component.base import ComponentBase, ComponentParamBase
  23. class WikipediaParam(ComponentParamBase):
  24. """
  25. Define the Wikipedia component parameters.
  26. """
  27. def __init__(self):
  28. super().__init__()
  29. self.top_n = 10
  30. self.language = "en"
  31. def check(self):
  32. self.check_positive_integer(self.top_n, "Top N")
  33. self.check_valid_value(self.language, "Wikipedia languages",
  34. ['af', 'pl', 'ar', 'ast', 'az', 'bg', 'nan', 'bn', 'be', 'ca', 'cs', 'cy', 'da', 'de',
  35. 'et', 'el', 'en', 'es', 'eo', 'eu', 'fa', 'fr', 'gl', 'ko', 'hy', 'hi', 'hr', 'id',
  36. 'it', 'he', 'ka', 'lld', 'la', 'lv', 'lt', 'hu', 'mk', 'arz', 'ms', 'min', 'my', 'nl',
  37. 'ja', 'nb', 'nn', 'ce', 'uz', 'pt', 'kk', 'ro', 'ru', 'ceb', 'sk', 'sl', 'sr', 'sh',
  38. 'fi', 'sv', 'ta', 'tt', 'th', 'tg', 'azb', 'tr', 'uk', 'ur', 'vi', 'war', 'zh', 'yue'])
  39. class Wikipedia(ComponentBase, ABC):
  40. component_name = "Wikipedia"
  41. def _run(self, history, **kwargs):
  42. ans = self.get_input()
  43. ans = " - ".join(ans["content"]) if "content" in ans else ""
  44. if not ans:
  45. return Wikipedia.be_output("")
  46. try:
  47. wiki_res = []
  48. wikipedia.set_lang(self._param.language)
  49. wiki_engine = wikipedia
  50. for wiki_key in wiki_engine.search(ans, results=self._param.top_n):
  51. page = wiki_engine.page(title=wiki_key, auto_suggest=False)
  52. wiki_res.append({"content": '<a href="' + page.url + '">' + page.title + '</a> ' + page.summary})
  53. except Exception as e:
  54. return Wikipedia.be_output("**ERROR**: " + str(e))
  55. if not wiki_res:
  56. return Wikipedia.be_output("")
  57. df = pd.DataFrame(wiki_res)
  58. if DEBUG: print(df, ":::::::::::::::::::::::::::::::::")
  59. return df