jisho.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """
  3. Jisho (the Japanese-English dictionary)
  4. """
  5. from urllib.parse import urlencode, urljoin
  6. # about
  7. about = {
  8. "website": 'https://jisho.org',
  9. "wikidata_id": 'Q24568389',
  10. "official_api_documentation": "https://jisho.org/forum/54fefc1f6e73340b1f160000-is-there-any-kind-of-search-api",
  11. "use_official_api": True,
  12. "require_api_key": False,
  13. "results": 'JSON',
  14. "language": 'ja',
  15. }
  16. categories = ['dictionaries']
  17. engine_type = 'online_dictionary'
  18. paging = False
  19. URL = 'https://jisho.org'
  20. BASE_URL = 'https://jisho.org/word/'
  21. SEARCH_URL = URL + '/api/v1/search/words?{query}'
  22. def request(query, params):
  23. query = urlencode({'keyword': query})
  24. params['url'] = SEARCH_URL.format(query=query)
  25. logger.debug(f"query_url --> {params['url']}")
  26. return params
  27. def response(resp):
  28. results = []
  29. infoboxed = False
  30. search_results = resp.json()
  31. pages = search_results.get('data', [])
  32. for page in pages:
  33. # Entries that are purely from Wikipedia are excluded.
  34. if page['senses'][0]['parts_of_speech'] != [] and page['senses'][0]['parts_of_speech'][0] == 'Wikipedia definition':
  35. pass
  36. # Process alternative forms
  37. japanese = page['japanese']
  38. alt_forms = []
  39. for title_raw in japanese:
  40. if 'word' not in title_raw:
  41. alt_forms.append(title_raw['reading'])
  42. else:
  43. title = title_raw['word']
  44. if 'reading' in title_raw:
  45. title += ' (' + title_raw['reading'] + ')'
  46. alt_forms.append(title)
  47. # Process definitions
  48. definitions = []
  49. def_raw = page['senses']
  50. for defn_raw in def_raw:
  51. extra = ''
  52. if not infoboxed:
  53. # Extra data. Since they're not documented, this implementation is based solely by the author's assumptions.
  54. if defn_raw['tags'] != []:
  55. if defn_raw['info'] != []:
  56. extra += defn_raw['tags'][0] + ', ' + defn_raw['info'][0] + '. ' # "usually written as kana: <kana>"
  57. else:
  58. extra += ', '.join(defn_raw['tags']) + '. ' # abbreviation, archaism, etc.
  59. elif defn_raw['info'] != []:
  60. extra += ', '.join(defn_raw['info']).capitalize() + '. ' # inconsistent
  61. if defn_raw['restrictions'] != []:
  62. extra += 'Only applies to: ' + ', '.join(defn_raw['restrictions']) + '. '
  63. extra = extra[:-1]
  64. definitions.append((
  65. ', '.join(defn_raw['parts_of_speech']),
  66. '; '.join(defn_raw['english_definitions']),
  67. extra
  68. ))
  69. content = ''
  70. infobox_content = '''
  71. <small><a href="https://www.edrdg.org/wiki/index.php/JMdict-EDICT_Dictionary_Project">JMdict</a>
  72. and <a href="https://www.edrdg.org/enamdict/enamdict_doc.html">JMnedict</a>
  73. by <a href="https://www.edrdg.org/edrdg/licence.html">EDRDG</a>, CC BY-SA 3.0.</small><ul>
  74. '''
  75. for pos, engdef, extra in definitions:
  76. if pos == 'Wikipedia definition':
  77. infobox_content += '</ul><small>Wikipedia, CC BY-SA 3.0.</small><ul>'
  78. if pos == '':
  79. infobox_content += f"<li>{engdef}"
  80. else:
  81. infobox_content += f"<li><i>{pos}</i>: {engdef}"
  82. if extra != '':
  83. infobox_content += f" ({extra})"
  84. infobox_content += '</li>'
  85. content += f"{engdef}. "
  86. infobox_content += '</ul>'
  87. # For results, we'll return the URL, all alternative forms (as title),
  88. # and all definitions (as description) truncated to 300 characters.
  89. results.append({
  90. 'url': urljoin(BASE_URL, page['slug']),
  91. 'title': ", ".join(alt_forms),
  92. 'content': content[:300] + (content[300:] and '...')
  93. })
  94. # Like Wordnik, we'll return the first result in an infobox too.
  95. if not infoboxed:
  96. infoboxed = True
  97. infobox_urls = []
  98. infobox_urls.append({
  99. 'title': 'Jisho.org',
  100. 'url': urljoin(BASE_URL, page['slug'])
  101. })
  102. infobox = {
  103. 'infobox': alt_forms[0],
  104. 'urls': infobox_urls
  105. }
  106. alt_forms.pop(0)
  107. alt_content = ''
  108. if len(alt_forms) > 0:
  109. alt_content = '<p><i>Other forms:</i> '
  110. alt_content += ", ".join(alt_forms)
  111. alt_content += '</p>'
  112. infobox['content'] = alt_content + infobox_content
  113. results.append(infobox)
  114. return results