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.

pubmed.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 logging
  17. from abc import ABC
  18. from Bio import Entrez
  19. import re
  20. import pandas as pd
  21. import xml.etree.ElementTree as ET
  22. from agent.component.base import ComponentBase, ComponentParamBase
  23. class PubMedParam(ComponentParamBase):
  24. """
  25. Define the PubMed component parameters.
  26. """
  27. def __init__(self):
  28. super().__init__()
  29. self.top_n = 5
  30. self.email = "A.N.Other@example.com"
  31. def check(self):
  32. self.check_positive_integer(self.top_n, "Top N")
  33. class PubMed(ComponentBase, ABC):
  34. component_name = "PubMed"
  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 PubMed.be_output("")
  40. try:
  41. Entrez.email = self._param.email
  42. pubmedids = Entrez.read(Entrez.esearch(db='pubmed', retmax=self._param.top_n, term=ans))['IdList']
  43. pubmedcnt = ET.fromstring(re.sub(r'<(/?)b>|<(/?)i>', '', Entrez.efetch(db='pubmed', id=",".join(pubmedids),
  44. retmode="xml").read().decode(
  45. "utf-8")))
  46. pubmed_res = [{"content": 'Title:' + child.find("MedlineCitation").find("Article").find(
  47. "ArticleTitle").text + '\nUrl:<a href=" https://pubmed.ncbi.nlm.nih.gov/' + child.find(
  48. "MedlineCitation").find("PMID").text + '">' + '</a>\n' + 'Abstract:' + (
  49. child.find("MedlineCitation").find("Article").find("Abstract").find(
  50. "AbstractText").text if child.find("MedlineCitation").find(
  51. "Article").find("Abstract") else "No abstract available")} for child in
  52. pubmedcnt.findall("PubmedArticle")]
  53. except Exception as e:
  54. return PubMed.be_output("**ERROR**: " + str(e))
  55. if not pubmed_res:
  56. return PubMed.be_output("")
  57. df = pd.DataFrame(pubmed_res)
  58. logging.debug(f"df: {df}")
  59. return df