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.

wikipedia.py 2.6KB

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