wordnet_app.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  1. # Natural Language Toolkit: WordNet Browser Application
  2. #
  3. # Copyright (C) 2001-2020 NLTK Project
  4. # Author: Jussi Salmela <jtsalmela@users.sourceforge.net>
  5. # Paul Bone <pbone@students.csse.unimelb.edu.au>
  6. # URL: <http://nltk.org/>
  7. # For license information, see LICENSE.TXT
  8. """
  9. A WordNet Browser application which launches the default browser
  10. (if it is not already running) and opens a new tab with a connection
  11. to http://localhost:port/ . It also starts an HTTP server on the
  12. specified port and begins serving browser requests. The default
  13. port is 8000. (For command-line help, run "python wordnet -h")
  14. This application requires that the user's web browser supports
  15. Javascript.
  16. BrowServer is a server for browsing the NLTK Wordnet database It first
  17. launches a browser client to be used for browsing and then starts
  18. serving the requests of that and maybe other clients
  19. Usage::
  20. browserver.py -h
  21. browserver.py [-s] [-p <port>]
  22. Options::
  23. -h or --help
  24. Display this help message.
  25. -l <file> or --log-file <file>
  26. Logs messages to the given file, If this option is not specified
  27. messages are silently dropped.
  28. -p <port> or --port <port>
  29. Run the web server on this TCP port, defaults to 8000.
  30. -s or --server-mode
  31. Do not start a web browser, and do not allow a user to
  32. shotdown the server through the web interface.
  33. """
  34. # TODO: throughout this package variable names and docstrings need
  35. # modifying to be compliant with NLTK's coding standards. Tests also
  36. # need to be develop to ensure this continues to work in the face of
  37. # changes to other NLTK packages.
  38. # Allow this program to run inside the NLTK source tree.
  39. from sys import path
  40. import os
  41. import sys
  42. from sys import argv
  43. from collections import defaultdict
  44. import webbrowser
  45. import datetime
  46. import re
  47. import threading
  48. import time
  49. import getopt
  50. import base64
  51. import pickle
  52. import copy
  53. from http.server import HTTPServer, BaseHTTPRequestHandler
  54. from urllib.parse import unquote_plus
  55. from nltk.corpus import wordnet as wn
  56. from nltk.corpus.reader.wordnet import Synset, Lemma
  57. # now included in local file
  58. # from util import html_header, html_trailer, \
  59. # get_static_index_page, get_static_page_by_path, \
  60. # page_from_word, page_from_href
  61. firstClient = True
  62. # True if we're not also running a web browser. The value f server_mode
  63. # gets set by demo().
  64. server_mode = None
  65. # If set this is a file object for writting log messages.
  66. logfile = None
  67. class MyServerHandler(BaseHTTPRequestHandler):
  68. def do_HEAD(self):
  69. self.send_head()
  70. def do_GET(self):
  71. global firstClient
  72. sp = self.path[1:]
  73. if unquote_plus(sp) == "SHUTDOWN THE SERVER":
  74. if server_mode:
  75. page = "Server must be killed with SIGTERM."
  76. type = "text/plain"
  77. else:
  78. print("Server shutting down!")
  79. os._exit(0)
  80. elif sp == "": # First request.
  81. type = "text/html"
  82. if not server_mode and firstClient:
  83. firstClient = False
  84. page = get_static_index_page(True)
  85. else:
  86. page = get_static_index_page(False)
  87. word = "green"
  88. elif sp.endswith(".html"): # Trying to fetch a HTML file TODO:
  89. type = "text/html"
  90. usp = unquote_plus(sp)
  91. if usp == "NLTK Wordnet Browser Database Info.html":
  92. word = "* Database Info *"
  93. if os.path.isfile(usp):
  94. with open(usp, "r") as infile:
  95. page = infile.read()
  96. else:
  97. page = (
  98. (html_header % word) + "<p>The database info file:"
  99. "<p><b>"
  100. + usp
  101. + "</b>"
  102. + "<p>was not found. Run this:"
  103. + "<p><b>python dbinfo_html.py</b>"
  104. + "<p>to produce it."
  105. + html_trailer
  106. )
  107. else:
  108. # Handle files here.
  109. word = sp
  110. page = get_static_page_by_path(usp)
  111. elif sp.startswith("search"):
  112. # This doesn't seem to work with MWEs.
  113. type = "text/html"
  114. parts = (sp.split("?")[1]).split("&")
  115. word = [
  116. p.split("=")[1].replace("+", " ")
  117. for p in parts
  118. if p.startswith("nextWord")
  119. ][0]
  120. page, word = page_from_word(word)
  121. elif sp.startswith("lookup_"):
  122. # TODO add a variation of this that takes a non ecoded word or MWE.
  123. type = "text/html"
  124. sp = sp[len("lookup_") :]
  125. page, word = page_from_href(sp)
  126. elif sp == "start_page":
  127. # if this is the first request we should display help
  128. # information, and possibly set a default word.
  129. type = "text/html"
  130. page, word = page_from_word("wordnet")
  131. else:
  132. type = "text/plain"
  133. page = "Could not parse request: '%s'" % sp
  134. # Send result.
  135. self.send_head(type)
  136. self.wfile.write(page.encode("utf8"))
  137. def send_head(self, type=None):
  138. self.send_response(200)
  139. self.send_header("Content-type", type)
  140. self.end_headers()
  141. def log_message(self, format, *args):
  142. global logfile
  143. if logfile:
  144. logfile.write(
  145. "%s - - [%s] %s\n"
  146. % (self.address_string(), self.log_date_time_string(), format % args)
  147. )
  148. def get_unique_counter_from_url(sp):
  149. """
  150. Extract the unique counter from the URL if it has one. Otherwise return
  151. null.
  152. """
  153. pos = sp.rfind("%23")
  154. if pos != -1:
  155. return int(sp[(pos + 3) :])
  156. else:
  157. return None
  158. def wnb(port=8000, runBrowser=True, logfilename=None):
  159. """
  160. Run NLTK Wordnet Browser Server.
  161. :param port: The port number for the server to listen on, defaults to
  162. 8000
  163. :type port: int
  164. :param runBrowser: True to start a web browser and point it at the web
  165. server.
  166. :type runBrowser: bool
  167. """
  168. # The webbrowser module is unpredictable, typically it blocks if it uses
  169. # a console web browser, and doesn't block if it uses a GUI webbrowser,
  170. # so we need to force it to have a clear correct behaviour.
  171. #
  172. # Normally the server should run for as long as the user wants. they
  173. # should idealy be able to control this from the UI by closing the
  174. # window or tab. Second best would be clicking a button to say
  175. # 'Shutdown' that first shutsdown the server and closes the window or
  176. # tab, or exits the text-mode browser. Both of these are unfreasable.
  177. #
  178. # The next best alternative is to start the server, have it close when
  179. # it receives SIGTERM (default), and run the browser as well. The user
  180. # may have to shutdown both programs.
  181. #
  182. # Since webbrowser may block, and the webserver will block, we must run
  183. # them in separate threads.
  184. #
  185. global server_mode, logfile
  186. server_mode = not runBrowser
  187. # Setup logging.
  188. if logfilename:
  189. try:
  190. logfile = open(logfilename, "a", 1) # 1 means 'line buffering'
  191. except IOError as e:
  192. sys.stderr.write("Couldn't open %s for writing: %s", logfilename, e)
  193. sys.exit(1)
  194. else:
  195. logfile = None
  196. # Compute URL and start web browser
  197. url = "http://localhost:" + str(port)
  198. server_ready = None
  199. browser_thread = None
  200. if runBrowser:
  201. server_ready = threading.Event()
  202. browser_thread = startBrowser(url, server_ready)
  203. # Start the server.
  204. server = HTTPServer(("", port), MyServerHandler)
  205. if logfile:
  206. logfile.write("NLTK Wordnet browser server running serving: %s\n" % url)
  207. if runBrowser:
  208. server_ready.set()
  209. try:
  210. server.serve_forever()
  211. except KeyboardInterrupt:
  212. pass
  213. if runBrowser:
  214. browser_thread.join()
  215. if logfile:
  216. logfile.close()
  217. def startBrowser(url, server_ready):
  218. def run():
  219. server_ready.wait()
  220. time.sleep(1) # Wait a little bit more, there's still the chance of
  221. # a race condition.
  222. webbrowser.open(url, new=2, autoraise=1)
  223. t = threading.Thread(target=run)
  224. t.start()
  225. return t
  226. #####################################################################
  227. # Utilities
  228. #####################################################################
  229. """
  230. WordNet Browser Utilities.
  231. This provides a backend to both wxbrowse and browserver.py.
  232. """
  233. ################################################################################
  234. #
  235. # Main logic for wordnet browser.
  236. #
  237. # This is wrapped inside a function since wn is only available if the
  238. # WordNet corpus is installed.
  239. def _pos_tuples():
  240. return [
  241. (wn.NOUN, "N", "noun"),
  242. (wn.VERB, "V", "verb"),
  243. (wn.ADJ, "J", "adj"),
  244. (wn.ADV, "R", "adv"),
  245. ]
  246. def _pos_match(pos_tuple):
  247. """
  248. This function returns the complete pos tuple for the partial pos
  249. tuple given to it. It attempts to match it against the first
  250. non-null component of the given pos tuple.
  251. """
  252. if pos_tuple[0] == "s":
  253. pos_tuple = ("a", pos_tuple[1], pos_tuple[2])
  254. for n, x in enumerate(pos_tuple):
  255. if x is not None:
  256. break
  257. for pt in _pos_tuples():
  258. if pt[n] == pos_tuple[n]:
  259. return pt
  260. return None
  261. HYPONYM = 0
  262. HYPERNYM = 1
  263. CLASS_REGIONAL = 2
  264. PART_HOLONYM = 3
  265. PART_MERONYM = 4
  266. ATTRIBUTE = 5
  267. SUBSTANCE_HOLONYM = 6
  268. SUBSTANCE_MERONYM = 7
  269. MEMBER_HOLONYM = 8
  270. MEMBER_MERONYM = 9
  271. VERB_GROUP = 10
  272. INSTANCE_HYPONYM = 12
  273. INSTANCE_HYPERNYM = 13
  274. CAUSE = 14
  275. ALSO_SEE = 15
  276. SIMILAR = 16
  277. ENTAILMENT = 17
  278. ANTONYM = 18
  279. FRAMES = 19
  280. PERTAINYM = 20
  281. CLASS_CATEGORY = 21
  282. CLASS_USAGE = 22
  283. CLASS_REGIONAL = 23
  284. CLASS_USAGE = 24
  285. CLASS_CATEGORY = 11
  286. DERIVATIONALLY_RELATED_FORM = 25
  287. INDIRECT_HYPERNYMS = 26
  288. def lemma_property(word, synset, func):
  289. def flattern(l):
  290. if l == []:
  291. return []
  292. else:
  293. return l[0] + flattern(l[1:])
  294. return flattern([func(l) for l in synset.lemmas if l.name == word])
  295. def rebuild_tree(orig_tree):
  296. node = orig_tree[0]
  297. children = orig_tree[1:]
  298. return (node, [rebuild_tree(t) for t in children])
  299. def get_relations_data(word, synset):
  300. """
  301. Get synset relations data for a synset. Note that this doesn't
  302. yet support things such as full hyponym vs direct hyponym.
  303. """
  304. if synset.pos() == wn.NOUN:
  305. return (
  306. (HYPONYM, "Hyponyms", synset.hyponyms()),
  307. (INSTANCE_HYPONYM, "Instance hyponyms", synset.instance_hyponyms()),
  308. (HYPERNYM, "Direct hypernyms", synset.hypernyms()),
  309. (
  310. INDIRECT_HYPERNYMS,
  311. "Indirect hypernyms",
  312. rebuild_tree(synset.tree(lambda x: x.hypernyms()))[1],
  313. ),
  314. # hypernyms', 'Sister terms',
  315. (INSTANCE_HYPERNYM, "Instance hypernyms", synset.instance_hypernyms()),
  316. # (CLASS_REGIONAL, ['domain term region'], ),
  317. (PART_HOLONYM, "Part holonyms", synset.part_holonyms()),
  318. (PART_MERONYM, "Part meronyms", synset.part_meronyms()),
  319. (SUBSTANCE_HOLONYM, "Substance holonyms", synset.substance_holonyms()),
  320. (SUBSTANCE_MERONYM, "Substance meronyms", synset.substance_meronyms()),
  321. (MEMBER_HOLONYM, "Member holonyms", synset.member_holonyms()),
  322. (MEMBER_MERONYM, "Member meronyms", synset.member_meronyms()),
  323. (ATTRIBUTE, "Attributes", synset.attributes()),
  324. (ANTONYM, "Antonyms", lemma_property(word, synset, lambda l: l.antonyms())),
  325. (
  326. DERIVATIONALLY_RELATED_FORM,
  327. "Derivationally related form",
  328. lemma_property(
  329. word, synset, lambda l: l.derivationally_related_forms()
  330. ),
  331. ),
  332. )
  333. elif synset.pos() == wn.VERB:
  334. return (
  335. (ANTONYM, "Antonym", lemma_property(word, synset, lambda l: l.antonyms())),
  336. (HYPONYM, "Hyponym", synset.hyponyms()),
  337. (HYPERNYM, "Direct hypernyms", synset.hypernyms()),
  338. (
  339. INDIRECT_HYPERNYMS,
  340. "Indirect hypernyms",
  341. rebuild_tree(synset.tree(lambda x: x.hypernyms()))[1],
  342. ),
  343. (ENTAILMENT, "Entailments", synset.entailments()),
  344. (CAUSE, "Causes", synset.causes()),
  345. (ALSO_SEE, "Also see", synset.also_sees()),
  346. (VERB_GROUP, "Verb Groups", synset.verb_groups()),
  347. (
  348. DERIVATIONALLY_RELATED_FORM,
  349. "Derivationally related form",
  350. lemma_property(
  351. word, synset, lambda l: l.derivationally_related_forms()
  352. ),
  353. ),
  354. )
  355. elif synset.pos() == wn.ADJ or synset.pos == wn.ADJ_SAT:
  356. return (
  357. (ANTONYM, "Antonym", lemma_property(word, synset, lambda l: l.antonyms())),
  358. (SIMILAR, "Similar to", synset.similar_tos()),
  359. # Participle of verb - not supported by corpus
  360. (
  361. PERTAINYM,
  362. "Pertainyms",
  363. lemma_property(word, synset, lambda l: l.pertainyms()),
  364. ),
  365. (ATTRIBUTE, "Attributes", synset.attributes()),
  366. (ALSO_SEE, "Also see", synset.also_sees()),
  367. )
  368. elif synset.pos() == wn.ADV:
  369. # This is weird. adverbs such as 'quick' and 'fast' don't seem
  370. # to have antonyms returned by the corpus.a
  371. return (
  372. (ANTONYM, "Antonym", lemma_property(word, synset, lambda l: l.antonyms())),
  373. )
  374. # Derived from adjective - not supported by corpus
  375. else:
  376. raise TypeError("Unhandles synset POS type: " + str(synset.pos()))
  377. html_header = """
  378. <!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01//EN'
  379. 'http://www.w3.org/TR/html4/strict.dtd'>
  380. <html>
  381. <head>
  382. <meta name='generator' content=
  383. 'HTML Tidy for Windows (vers 14 February 2006), see www.w3.org'>
  384. <meta http-equiv='Content-Type' content=
  385. 'text/html; charset=us-ascii'>
  386. <title>NLTK Wordnet Browser display of: %s</title></head>
  387. <body bgcolor='#F5F5F5' text='#000000'>
  388. """
  389. html_trailer = """
  390. </body>
  391. </html>
  392. """
  393. explanation = """
  394. <h3>Search Help</h3>
  395. <ul><li>The display below the line is an example of the output the browser
  396. shows you when you enter a search word. The search word was <b>green</b>.</li>
  397. <li>The search result shows for different parts of speech the <b>synsets</b>
  398. i.e. different meanings for the word.</li>
  399. <li>All underlined texts are hypertext links. There are two types of links:
  400. word links and others. Clicking a word link carries out a search for the word
  401. in the Wordnet database.</li>
  402. <li>Clicking a link of the other type opens a display section of data attached
  403. to that link. Clicking that link a second time closes the section again.</li>
  404. <li>Clicking <u>S:</u> opens a section showing the relations for that synset.
  405. </li>
  406. <li>Clicking on a relation name opens a section that displays the associated
  407. synsets.</li>
  408. <li>Type a search word in the <b>Word</b> field and start the search by the
  409. <b>Enter/Return</b> key or click the <b>Search</b> button.</li>
  410. </ul>
  411. <hr width='100%'>
  412. """
  413. # HTML oriented functions
  414. def _bold(txt):
  415. return "<b>%s</b>" % txt
  416. def _center(txt):
  417. return "<center>%s</center>" % txt
  418. def _hlev(n, txt):
  419. return "<h%d>%s</h%d>" % (n, txt, n)
  420. def _italic(txt):
  421. return "<i>%s</i>" % txt
  422. def _li(txt):
  423. return "<li>%s</li>" % txt
  424. def pg(word, body):
  425. """
  426. Return a HTML page of NLTK Browser format constructed from the
  427. word and body
  428. :param word: The word that the body corresponds to
  429. :type word: str
  430. :param body: The HTML body corresponding to the word
  431. :type body: str
  432. :return: a HTML page for the word-body combination
  433. :rtype: str
  434. """
  435. return (html_header % word) + body + html_trailer
  436. def _ul(txt):
  437. return "<ul>" + txt + "</ul>"
  438. def _abbc(txt):
  439. """
  440. abbc = asterisks, breaks, bold, center
  441. """
  442. return _center(_bold("<br>" * 10 + "*" * 10 + " " + txt + " " + "*" * 10))
  443. full_hyponym_cont_text = _ul(_li(_italic("(has full hyponym continuation)"))) + "\n"
  444. def _get_synset(synset_key):
  445. """
  446. The synset key is the unique name of the synset, this can be
  447. retrived via synset.name()
  448. """
  449. return wn.synset(synset_key)
  450. def _collect_one_synset(word, synset, synset_relations):
  451. """
  452. Returns the HTML string for one synset or word
  453. :param word: the current word
  454. :type word: str
  455. :param synset: a synset
  456. :type synset: synset
  457. :param synset_relations: information about which synset relations
  458. to display.
  459. :type synset_relations: dict(synset_key, set(relation_id))
  460. :return: The HTML string built for this synset
  461. :rtype: str
  462. """
  463. if isinstance(synset, tuple): # It's a word
  464. raise NotImplementedError("word not supported by _collect_one_synset")
  465. typ = "S"
  466. pos_tuple = _pos_match((synset.pos(), None, None))
  467. assert pos_tuple is not None, "pos_tuple is null: synset.pos(): %s" % synset.pos()
  468. descr = pos_tuple[2]
  469. ref = copy.deepcopy(Reference(word, synset_relations))
  470. ref.toggle_synset(synset)
  471. synset_label = typ + ";"
  472. if synset.name() in synset_relations:
  473. synset_label = _bold(synset_label)
  474. s = "<li>%s (%s) " % (make_lookup_link(ref, synset_label), descr)
  475. def format_lemma(w):
  476. w = w.replace("_", " ")
  477. if w.lower() == word:
  478. return _bold(w)
  479. else:
  480. ref = Reference(w)
  481. return make_lookup_link(ref, w)
  482. s += ", ".join(format_lemma(l.name()) for l in synset.lemmas())
  483. gl = " (%s) <i>%s</i> " % (
  484. synset.definition(),
  485. "; ".join('"%s"' % e for e in synset.examples()),
  486. )
  487. return s + gl + _synset_relations(word, synset, synset_relations) + "</li>\n"
  488. def _collect_all_synsets(word, pos, synset_relations=dict()):
  489. """
  490. Return a HTML unordered list of synsets for the given word and
  491. part of speech.
  492. """
  493. return "<ul>%s\n</ul>\n" % "".join(
  494. (
  495. _collect_one_synset(word, synset, synset_relations)
  496. for synset in wn.synsets(word, pos)
  497. )
  498. )
  499. def _synset_relations(word, synset, synset_relations):
  500. """
  501. Builds the HTML string for the relations of a synset
  502. :param word: The current word
  503. :type word: str
  504. :param synset: The synset for which we're building the relations.
  505. :type synset: Synset
  506. :param synset_relations: synset keys and relation types for which to display relations.
  507. :type synset_relations: dict(synset_key, set(relation_type))
  508. :return: The HTML for a synset's relations
  509. :rtype: str
  510. """
  511. if not synset.name() in synset_relations:
  512. return ""
  513. ref = Reference(word, synset_relations)
  514. def relation_html(r):
  515. if isinstance(r, Synset):
  516. return make_lookup_link(Reference(r.lemma_names()[0]), r.lemma_names()[0])
  517. elif isinstance(r, Lemma):
  518. return relation_html(r.synset())
  519. elif isinstance(r, tuple):
  520. # It's probably a tuple containing a Synset and a list of
  521. # similar tuples. This forms a tree of synsets.
  522. return "%s\n<ul>%s</ul>\n" % (
  523. relation_html(r[0]),
  524. "".join("<li>%s</li>\n" % relation_html(sr) for sr in r[1]),
  525. )
  526. else:
  527. raise TypeError(
  528. "r must be a synset, lemma or list, it was: type(r) = %s, r = %s"
  529. % (type(r), r)
  530. )
  531. def make_synset_html(db_name, disp_name, rels):
  532. synset_html = "<i>%s</i>\n" % make_lookup_link(
  533. copy.deepcopy(ref).toggle_synset_relation(synset, db_name).encode(),
  534. disp_name,
  535. )
  536. if db_name in ref.synset_relations[synset.name()]:
  537. synset_html += "<ul>%s</ul>\n" % "".join(
  538. "<li>%s</li>\n" % relation_html(r) for r in rels
  539. )
  540. return synset_html
  541. html = (
  542. "<ul>"
  543. + "\n".join(
  544. (
  545. "<li>%s</li>" % make_synset_html(*rel_data)
  546. for rel_data in get_relations_data(word, synset)
  547. if rel_data[2] != []
  548. )
  549. )
  550. + "</ul>"
  551. )
  552. return html
  553. class Reference(object):
  554. """
  555. A reference to a page that may be generated by page_word
  556. """
  557. def __init__(self, word, synset_relations=dict()):
  558. """
  559. Build a reference to a new page.
  560. word is the word or words (separated by commas) for which to
  561. search for synsets of
  562. synset_relations is a dictionary of synset keys to sets of
  563. synset relation identifaiers to unfold a list of synset
  564. relations for.
  565. """
  566. self.word = word
  567. self.synset_relations = synset_relations
  568. def encode(self):
  569. """
  570. Encode this reference into a string to be used in a URL.
  571. """
  572. # This uses a tuple rather than an object since the python
  573. # pickle representation is much smaller and there is no need
  574. # to represent the complete object.
  575. string = pickle.dumps((self.word, self.synset_relations), -1)
  576. return base64.urlsafe_b64encode(string).decode()
  577. @staticmethod
  578. def decode(string):
  579. """
  580. Decode a reference encoded with Reference.encode
  581. """
  582. string = base64.urlsafe_b64decode(string.encode())
  583. word, synset_relations = pickle.loads(string)
  584. return Reference(word, synset_relations)
  585. def toggle_synset_relation(self, synset, relation):
  586. """
  587. Toggle the display of the relations for the given synset and
  588. relation type.
  589. This function will throw a KeyError if the synset is currently
  590. not being displayed.
  591. """
  592. if relation in self.synset_relations[synset.name()]:
  593. self.synset_relations[synset.name()].remove(relation)
  594. else:
  595. self.synset_relations[synset.name()].add(relation)
  596. return self
  597. def toggle_synset(self, synset):
  598. """
  599. Toggle displaying of the relation types for the given synset
  600. """
  601. if synset.name() in self.synset_relations:
  602. del self.synset_relations[synset.name()]
  603. else:
  604. self.synset_relations[synset.name()] = set()
  605. return self
  606. def make_lookup_link(ref, label):
  607. return '<a href="lookup_%s">%s</a>' % (ref.encode(), label)
  608. def page_from_word(word):
  609. """
  610. Return a HTML page for the given word.
  611. :type word: str
  612. :param word: The currently active word
  613. :return: A tuple (page,word), where page is the new current HTML page
  614. to be sent to the browser and
  615. word is the new current word
  616. :rtype: A tuple (str,str)
  617. """
  618. return page_from_reference(Reference(word))
  619. def page_from_href(href):
  620. """
  621. Returns a tuple of the HTML page built and the new current word
  622. :param href: The hypertext reference to be solved
  623. :type href: str
  624. :return: A tuple (page,word), where page is the new current HTML page
  625. to be sent to the browser and
  626. word is the new current word
  627. :rtype: A tuple (str,str)
  628. """
  629. return page_from_reference(Reference.decode(href))
  630. def page_from_reference(href):
  631. """
  632. Returns a tuple of the HTML page built and the new current word
  633. :param href: The hypertext reference to be solved
  634. :type href: str
  635. :return: A tuple (page,word), where page is the new current HTML page
  636. to be sent to the browser and
  637. word is the new current word
  638. :rtype: A tuple (str,str)
  639. """
  640. word = href.word
  641. pos_forms = defaultdict(list)
  642. words = word.split(",")
  643. words = [w for w in [w.strip().lower().replace(" ", "_") for w in words] if w != ""]
  644. if len(words) == 0:
  645. # No words were found.
  646. return "", "Please specify a word to search for."
  647. # This looks up multiple words at once. This is probably not
  648. # necessary and may lead to problems.
  649. for w in words:
  650. for pos in [wn.NOUN, wn.VERB, wn.ADJ, wn.ADV]:
  651. form = wn.morphy(w, pos)
  652. if form and form not in pos_forms[pos]:
  653. pos_forms[pos].append(form)
  654. body = ""
  655. for pos, pos_str, name in _pos_tuples():
  656. if pos in pos_forms:
  657. body += _hlev(3, name) + "\n"
  658. for w in pos_forms[pos]:
  659. # Not all words of exc files are in the database, skip
  660. # to the next word if a KeyError is raised.
  661. try:
  662. body += _collect_all_synsets(w, pos, href.synset_relations)
  663. except KeyError:
  664. pass
  665. if not body:
  666. body = "The word or words '%s' where not found in the dictonary." % word
  667. return body, word
  668. #####################################################################
  669. # Static pages
  670. #####################################################################
  671. def get_static_page_by_path(path):
  672. """
  673. Return a static HTML page from the path given.
  674. """
  675. if path == "index_2.html":
  676. return get_static_index_page(False)
  677. elif path == "index.html":
  678. return get_static_index_page(True)
  679. elif path == "NLTK Wordnet Browser Database Info.html":
  680. return "Display of Wordnet Database Statistics is not supported"
  681. elif path == "upper_2.html":
  682. return get_static_upper_page(False)
  683. elif path == "upper.html":
  684. return get_static_upper_page(True)
  685. elif path == "web_help.html":
  686. return get_static_web_help_page()
  687. elif path == "wx_help.html":
  688. return get_static_wx_help_page()
  689. else:
  690. return "Internal error: Path for static page '%s' is unknown" % path
  691. def get_static_web_help_page():
  692. """
  693. Return the static web help page.
  694. """
  695. return """
  696. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  697. <html>
  698. <!-- Natural Language Toolkit: Wordnet Interface: Graphical Wordnet Browser
  699. Copyright (C) 2001-2020 NLTK Project
  700. Author: Jussi Salmela <jtsalmela@users.sourceforge.net>
  701. URL: <http://nltk.org/>
  702. For license information, see LICENSE.TXT -->
  703. <head>
  704. <meta http-equiv='Content-Type' content='text/html; charset=us-ascii'>
  705. <title>NLTK Wordnet Browser display of: * Help *</title>
  706. </head>
  707. <body bgcolor='#F5F5F5' text='#000000'>
  708. <h2>NLTK Wordnet Browser Help</h2>
  709. <p>The NLTK Wordnet Browser is a tool to use in browsing the Wordnet database. It tries to behave like the Wordnet project's web browser but the difference is that the NLTK Wordnet Browser uses a local Wordnet database.
  710. <p><b>You are using the Javascript client part of the NLTK Wordnet BrowseServer.</b> We assume your browser is in tab sheets enabled mode.</p>
  711. <p>For background information on Wordnet, see the Wordnet project home page: <a href="http://wordnet.princeton.edu/"><b> http://wordnet.princeton.edu/</b></a>. For more information on the NLTK project, see the project home:
  712. <a href="http://nltk.sourceforge.net/"><b>http://nltk.sourceforge.net/</b></a>. To get an idea of what the Wordnet version used by this browser includes choose <b>Show Database Info</b> from the <b>View</b> submenu.</p>
  713. <h3>Word search</h3>
  714. <p>The word to be searched is typed into the <b>New Word</b> field and the search started with Enter or by clicking the <b>Search</b> button. There is no uppercase/lowercase distinction: the search word is transformed to lowercase before the search.</p>
  715. <p>In addition, the word does not have to be in base form. The browser tries to find the possible base form(s) by making certain morphological substitutions. Typing <b>fLIeS</b> as an obscure example gives one <a href="MfLIeS">this</a>. Click the previous link to see what this kind of search looks like and then come back to this page by using the <b>Alt+LeftArrow</b> key combination.</p>
  716. <p>The result of a search is a display of one or more
  717. <b>synsets</b> for every part of speech in which a form of the
  718. search word was found to occur. A synset is a set of words
  719. having the same sense or meaning. Each word in a synset that is
  720. underlined is a hyperlink which can be clicked to trigger an
  721. automatic search for that word.</p>
  722. <p>Every synset has a hyperlink <b>S:</b> at the start of its
  723. display line. Clicking that symbol shows you the name of every
  724. <b>relation</b> that this synset is part of. Every relation name is a hyperlink that opens up a display for that relation. Clicking it another time closes the display again. Clicking another relation name on a line that has an opened relation closes the open relation and opens the clicked relation.</p>
  725. <p>It is also possible to give two or more words or collocations to be searched at the same time separating them with a comma like this <a href="Mcheer up,clear up">cheer up,clear up</a>, for example. Click the previous link to see what this kind of search looks like and then come back to this page by using the <b>Alt+LeftArrow</b> key combination. As you could see the search result includes the synsets found in the same order than the forms were given in the search field.</p>
  726. <p>
  727. There are also word level (lexical) relations recorded in the Wordnet database. Opening this kind of relation displays lines with a hyperlink <b>W:</b> at their beginning. Clicking this link shows more info on the word in question.</p>
  728. <h3>The Buttons</h3>
  729. <p>The <b>Search</b> and <b>Help</b> buttons need no more explanation. </p>
  730. <p>The <b>Show Database Info</b> button shows a collection of Wordnet database statistics.</p>
  731. <p>The <b>Shutdown the Server</b> button is shown for the first client of the BrowServer program i.e. for the client that is automatically launched when the BrowServer is started but not for the succeeding clients in order to protect the server from accidental shutdowns.
  732. </p></body>
  733. </html>
  734. """
  735. def get_static_welcome_message():
  736. """
  737. Get the static welcome page.
  738. """
  739. return """
  740. <h3>Search Help</h3>
  741. <ul><li>The display below the line is an example of the output the browser
  742. shows you when you enter a search word. The search word was <b>green</b>.</li>
  743. <li>The search result shows for different parts of speech the <b>synsets</b>
  744. i.e. different meanings for the word.</li>
  745. <li>All underlined texts are hypertext links. There are two types of links:
  746. word links and others. Clicking a word link carries out a search for the word
  747. in the Wordnet database.</li>
  748. <li>Clicking a link of the other type opens a display section of data attached
  749. to that link. Clicking that link a second time closes the section again.</li>
  750. <li>Clicking <u>S:</u> opens a section showing the relations for that synset.</li>
  751. <li>Clicking on a relation name opens a section that displays the associated
  752. synsets.</li>
  753. <li>Type a search word in the <b>Next Word</b> field and start the search by the
  754. <b>Enter/Return</b> key or click the <b>Search</b> button.</li>
  755. </ul>
  756. """
  757. def get_static_index_page(with_shutdown):
  758. """
  759. Get the static index page.
  760. """
  761. template = """
  762. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
  763. <HTML>
  764. <!-- Natural Language Toolkit: Wordnet Interface: Graphical Wordnet Browser
  765. Copyright (C) 2001-2020 NLTK Project
  766. Author: Jussi Salmela <jtsalmela@users.sourceforge.net>
  767. URL: <http://nltk.org/>
  768. For license information, see LICENSE.TXT -->
  769. <HEAD>
  770. <TITLE>NLTK Wordnet Browser</TITLE>
  771. </HEAD>
  772. <frameset rows="7%%,93%%">
  773. <frame src="%s" name="header">
  774. <frame src="start_page" name="body">
  775. </frameset>
  776. </HTML>
  777. """
  778. if with_shutdown:
  779. upper_link = "upper.html"
  780. else:
  781. upper_link = "upper_2.html"
  782. return template % upper_link
  783. def get_static_upper_page(with_shutdown):
  784. """
  785. Return the upper frame page,
  786. If with_shutdown is True then a 'shutdown' button is also provided
  787. to shutdown the server.
  788. """
  789. template = """
  790. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  791. <html>
  792. <!-- Natural Language Toolkit: Wordnet Interface: Graphical Wordnet Browser
  793. Copyright (C) 2001-2020 NLTK Project
  794. Author: Jussi Salmela <jtsalmela@users.sourceforge.net>
  795. URL: <http://nltk.org/>
  796. For license information, see LICENSE.TXT -->
  797. <head>
  798. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  799. <title>Untitled Document</title>
  800. </head>
  801. <body>
  802. <form method="GET" action="search" target="body">
  803. Current Word:&nbsp;<input type="text" id="currentWord" size="10" disabled>
  804. Next Word:&nbsp;<input type="text" id="nextWord" name="nextWord" size="10">
  805. <input name="searchButton" type="submit" value="Search">
  806. </form>
  807. <a target="body" href="web_help.html">Help</a>
  808. %s
  809. </body>
  810. </html>
  811. """
  812. if with_shutdown:
  813. shutdown_link = '<a href="SHUTDOWN THE SERVER">Shutdown</a>'
  814. else:
  815. shutdown_link = ""
  816. return template % shutdown_link
  817. def usage():
  818. """
  819. Display the command line help message.
  820. """
  821. print(__doc__)
  822. def app():
  823. # Parse and interpret options.
  824. (opts, _) = getopt.getopt(
  825. argv[1:], "l:p:sh", ["logfile=", "port=", "server-mode", "help"]
  826. )
  827. port = 8000
  828. server_mode = False
  829. help_mode = False
  830. logfilename = None
  831. for (opt, value) in opts:
  832. if (opt == "-l") or (opt == "--logfile"):
  833. logfilename = str(value)
  834. elif (opt == "-p") or (opt == "--port"):
  835. port = int(value)
  836. elif (opt == "-s") or (opt == "--server-mode"):
  837. server_mode = True
  838. elif (opt == "-h") or (opt == "--help"):
  839. help_mode = True
  840. if help_mode:
  841. usage()
  842. else:
  843. wnb(port, not server_mode, logfilename)
  844. if __name__ == "__main__":
  845. app()
  846. __all__ = ["app"]