├── .gitignore ├── README.md ├── license ├── nbactions.xml ├── pom.xml └── src ├── main └── java │ └── be │ └── vanoosten │ └── esa │ ├── CachingTokenStream.java │ ├── ConceptSimilarity.java │ ├── EnwikiFactory.java │ ├── Main.java │ ├── TODO.txt │ ├── WikiAnalyzer.java │ ├── WikiFactory.java │ ├── WikiIndexer.java │ ├── brainstorm │ └── Brainstormer.java │ ├── gui │ ├── AbstractViewModel.java │ ├── EsaFrame.form │ ├── EsaFrame.java │ ├── EsaViewModel.java │ └── package-info.java │ └── tools │ ├── ConceptVector.java │ ├── RelatedTokensFinder.java │ ├── SemanticSimilarityTool.java │ └── Vectorizer.java └── test └── java └── be └── vanoosten └── esa └── StringMatchingTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | CL-ESA.pdf 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Wikipedia-based Explicit Semantic Analysis 2 | 3 | ## What is this? 4 | 5 | Semantic analysis is a way to extract meaning from a written text. 6 | The written text may be a single word, a couple of words, a sentence, a paragraph or a whole book. 7 | 8 | Explicit Semantic Analysis is a way to derive meaning based on Wikipedia. 9 | The text is transformed into a vector of Wikipedia articles. 10 | The vectors of two different texts can then be compared to assess the semantic similarity of those texts. 11 | 12 | This implementation was written by Philip van Oosten. 13 | It takes advantage of the mature Lucene project. 14 | 15 | ## License 16 | 17 | This software is provided under the terms of the AGPLv3 license. 18 | If this software seems helpful to you, but you dislike the licensing, don't let it get in your way and contact the author. 19 | We can work something out. 20 | 21 | ## Usage 22 | 23 | ESA can be used as a library. You will need to make some changes to the source code to use ESA and to tweak it. 24 | 25 | To learn how to work with it, I recommend trying a language with a small Wikipedia dump, other than English. 26 | The English wikipedia dump is very large and each step in the process of setting up ESA takes several hours to complete. 27 | A language with a smaller Wikipedia dump may not work as good as English, because there is just less data, but you will 28 | get up and running much faster. 29 | 30 | ### Download a Wikipedia dump 31 | 32 | This takes several hours. 33 | 34 | A list of all available database dumps is available here: . 35 | Choose a download which contains all current articles without history. 36 | For English ([enwiki](https://dumps.wikimedia.org/enwiki/20160801/enwiki-20160801-pages-articles-multistream.xml.bz2)), the download size is 13 GB at the time of writing, for Dutch ([nlwiki](https://dumps.wikimedia.org/nlwiki/20160801/nlwiki-20160801-pages-articles-multistream.xml.bz2)) it is 1.3 GB. 37 | Note that Wikipedia is constantly updated, so old dumps may not contain new concepts that could be interesting for your application. 38 | 39 | The Wikipedia article dump consists of a multi-stream BZipped xml file. 40 | That means that a straightforward way to read the bzip stream ends somewhere near the beginning of the file. 41 | You need to read the whole dump, not just the beginning. 42 | This implementation takes care of that. 43 | 44 | ### Indexing 45 | 46 | This also takes several hours. 47 | 48 | Now that the Wikipedia dump is downloaded, it must be indexed. 49 | Indexing is done with Lucene in two steps. 50 | 51 | First, all articles are indexed to a term-to-document index. 52 | The documents are the concepts in ESA. 53 | 54 | Second, the full-text index is inverted, so that each concept is mapped to all the terms that are important for that concept. 55 | To find that index, the terms in the first index become a document in the second index. 56 | Lucene further handles the indexing. 57 | 58 | The class `be.vanoosten.esa.Main` contains an `indexing` method. 59 | Using that method, you can create a term to concept index (the first index). 60 | 61 | The same class also contains a `createConceptTermIndex()` method, which is a bit more involved. 62 | That method can be used to create the second index, which maps Wikipedia articles to their tokens. 63 | 64 | #### Tweaking the indexing process 65 | 66 | All kinds of tricks from Lucene can be used to tweak the indexing. 67 | Maybe you will want to use a different Lucene Analyzer. 68 | Taking a good look at Lucene documentation and the `be.vanoosten.esa.WikiAnalyzer` class can be a good starting point for that. 69 | 70 | ### Analyzing 71 | 72 | After indexing, you are ready to transform text to vectors. 73 | Creating a concept vector from a text can be done with a Vectorizer, implemented in the class `be.vanoosten.esa.tools.Vectorizer`. 74 | 75 | The vectorizer has a `vectorize(String text)` method, which transforms the text into a concept vector (`be.vanoosten.esa.tools.ConceptVector`). 76 | Basically, the text is tokenized and searched for in the term-to-concept index. 77 | The result is a list of Wikipedia articles, along with their numeric similarity to the vectorized text. 78 | Two concept vectors can be easily compared to each other, using the `dotProduct` method. 79 | The dot product of two concept vectors is a measure for the semantic similarity between the two texts those vectors are created from. 80 | 81 | Calculating the semantic similarity between two texts directly is exactly what the semantic similarity tool (`be.vanoosten.esa.tools.SemanticSimilarityTool`) does. 82 | 83 | ### Automatic brainstorming 84 | 85 | Finally, the automatic brainstormer is why I went through the effort to create an ESA implementation. 86 | Starting from a text or a set of words, the brainstormer searches for words with a similar meaning. 87 | That process can be repeated a couple of times to create a network of words that can be visualized with Graphviz. 88 | 89 | The brainstormer is available in the class `be.vanoosten.esa.brainstorm.Brainstormer`. 90 | 91 | ## Theory 92 | 93 | Wikipedia-based Explicit Semantic Analysis, as described by Gabrilovich and Markovitch. 94 | 95 | ESA is well described in a scientific paper. 96 | 97 | http://en.wikipedia.org/wiki/Explicit_semantic_analysis 98 | 99 | http://www.cs.technion.ac.il/~gabr/resources/code/esa/esa.html 100 | 101 | http://www.cs.technion.ac.il/~gabr/papers/ijcai-2007-sim.pdf 102 | 103 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /nbactions.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | run 5 | 6 | jar 7 | 8 | 9 | process-classes 10 | org.codehaus.mojo:exec-maven-plugin:1.2.1:exec 11 | 12 | 13 | -classpath %classpath be.vanoosten.esa.gui.EsaFrame 14 | java 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | be.vanoosten 5 | esa 6 | 1.0-SNAPSHOT 7 | jar 8 | 9 | UTF-8 10 | 1.8 11 | 1.8 12 | 13 | 14 | 15 | de.tudarmstadt.ukp.wikipedia 16 | de.tudarmstadt.ukp.wikipedia.parser 17 | 0.9.2 18 | 19 | 20 | org.apache.commons 21 | commons-compress 22 | 1.19 23 | 24 | 25 | org.apache.lucene 26 | lucene-analyzers-common 27 | 4.8.1 28 | 29 | 30 | org.apache.lucene 31 | lucene-queryparser 32 | 4.8.1 33 | jar 34 | 35 | 36 | org.jdesktop 37 | beansbinding 38 | 1.2.1 39 | 40 | 41 | com.tinkerpop.blueprints 42 | blueprints-graph-jung 43 | 2.5.0 44 | jar 45 | 46 | 47 | -------------------------------------------------------------------------------- /src/main/java/be/vanoosten/esa/CachingTokenStream.java: -------------------------------------------------------------------------------- 1 | package be.vanoosten.esa; 2 | 3 | import java.io.IOException; 4 | import java.util.ArrayList; 5 | import org.apache.lucene.analysis.Token; 6 | import org.apache.lucene.analysis.TokenStream; 7 | import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; 8 | import org.apache.lucene.analysis.tokenattributes.PayloadAttribute; 9 | 10 | /** 11 | * 12 | * @author Philip van Oosten 13 | */ 14 | class CachingTokenStream extends TokenStream { 15 | 16 | private int i = -1; 17 | private final ArrayList queue; 18 | 19 | private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class); 20 | private final PayloadAttribute payloadAtt = addAttribute(PayloadAttribute.class); 21 | 22 | CachingTokenStream() { 23 | this.queue = new ArrayList<>(); 24 | } 25 | 26 | void produceToken(Token token) { 27 | queue.add(token); 28 | } 29 | 30 | @Override 31 | public boolean incrementToken() throws IOException { 32 | i++; 33 | if (queue.size() <= i) { 34 | return false; 35 | } 36 | final Token token = queue.get(i); 37 | int tokenLength = token.length(); 38 | termAtt.resizeBuffer(Math.max(termAtt.buffer().length, tokenLength)); 39 | termAtt.setLength(tokenLength); 40 | final char[] buffer = termAtt.buffer(); 41 | System.arraycopy(token.buffer(), 0, buffer, 0, token.length()); 42 | payloadAtt.setPayload(token.getPayload()); 43 | return true; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/be/vanoosten/esa/ConceptSimilarity.java: -------------------------------------------------------------------------------- 1 | package be.vanoosten.esa; 2 | 3 | import org.apache.lucene.index.FieldInvertState; 4 | import org.apache.lucene.search.similarities.TFIDFSimilarity; 5 | import org.apache.lucene.store.ByteArrayDataInput; 6 | import org.apache.lucene.util.BytesRef; 7 | 8 | /** 9 | * 10 | * @author Philip van Oosten 11 | */ 12 | public class ConceptSimilarity extends TFIDFSimilarity{ 13 | 14 | public static final float SIMILARITY_FACTOR = 0.00001f; 15 | 16 | private final ByteArrayDataInput dataInput = new ByteArrayDataInput(); 17 | 18 | @Override 19 | public float coord(int overlap, int maxOverlap) { 20 | return 1f/maxOverlap; 21 | } 22 | 23 | @Override 24 | public float queryNorm(float sumOfSquaredWeights) { 25 | return 1f; 26 | } 27 | 28 | @Override 29 | public float tf(float freq) { 30 | return 1f; 31 | } 32 | 33 | @Override 34 | public float idf(long docFreq, long numDocs) { 35 | return (float) Math.log(1.0*numDocs/docFreq); 36 | } 37 | 38 | @Override 39 | public float lengthNorm(FieldInvertState state) { 40 | return 1f; 41 | } 42 | 43 | @Override 44 | public float decodeNormValue(long norm) { 45 | return 1f; 46 | } 47 | 48 | @Override 49 | public long encodeNormValue(float f) { 50 | return 1L; 51 | } 52 | 53 | @Override 54 | public float sloppyFreq(int distance) { 55 | return 0f; 56 | } 57 | 58 | @Override 59 | public float scorePayload(int doc, int start, int end, BytesRef payload) { 60 | synchronized(dataInput){ 61 | dataInput.reset(payload.bytes); 62 | return SIMILARITY_FACTOR* dataInput.readVInt(); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/be/vanoosten/esa/EnwikiFactory.java: -------------------------------------------------------------------------------- 1 | package be.vanoosten.esa; 2 | 3 | import java.io.File; 4 | import org.apache.lucene.analysis.core.StopAnalyzer; 5 | 6 | /** 7 | * 8 | * @author Philip van Oosten 9 | */ 10 | public class EnwikiFactory extends WikiFactory { 11 | 12 | public EnwikiFactory() { 13 | super(indexRootPath(), 14 | new File(indexRootPath(), String.join(File.separator, "dump", "enwiki-20140614-pages-articles-multistream.xml.bz2")), 15 | StopAnalyzer.ENGLISH_STOP_WORDS_SET); 16 | } 17 | 18 | private static File indexRootPath() { 19 | return new File(String.join(File.separator, "D:", "Development", "esa", "enwiki")); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/be/vanoosten/esa/Main.java: -------------------------------------------------------------------------------- 1 | package be.vanoosten.esa; 2 | 3 | import static be.vanoosten.esa.WikiIndexer.TITLE_FIELD; 4 | import java.io.File; 5 | import java.io.IOException; 6 | import java.util.Locale; 7 | import java.util.concurrent.ExecutorService; 8 | import java.util.concurrent.Executors; 9 | import org.apache.lucene.analysis.Analyzer; 10 | import org.apache.lucene.analysis.Token; 11 | import org.apache.lucene.analysis.core.StopAnalyzer; 12 | import org.apache.lucene.analysis.util.CharArraySet; 13 | import org.apache.lucene.document.Document; 14 | import org.apache.lucene.document.Field; 15 | import org.apache.lucene.document.StringField; 16 | import org.apache.lucene.document.TextField; 17 | import org.apache.lucene.index.DirectoryReader; 18 | import org.apache.lucene.index.Fields; 19 | import org.apache.lucene.index.IndexReader; 20 | import org.apache.lucene.index.IndexWriter; 21 | import org.apache.lucene.index.IndexWriterConfig; 22 | import org.apache.lucene.index.MultiFields; 23 | import org.apache.lucene.index.Term; 24 | import org.apache.lucene.index.Terms; 25 | import org.apache.lucene.index.TermsEnum; 26 | import org.apache.lucene.queryparser.classic.ParseException; 27 | import org.apache.lucene.queryparser.classic.QueryParser; 28 | import org.apache.lucene.search.BooleanClause.Occur; 29 | import org.apache.lucene.search.BooleanQuery; 30 | import org.apache.lucene.search.IndexSearcher; 31 | import org.apache.lucene.search.Query; 32 | import org.apache.lucene.search.ScoreDoc; 33 | import org.apache.lucene.search.TermQuery; 34 | import org.apache.lucene.search.TopDocs; 35 | import org.apache.lucene.store.ByteArrayDataOutput; 36 | import org.apache.lucene.store.Directory; 37 | import org.apache.lucene.store.FSDirectory; 38 | import org.apache.lucene.util.AttributeSource; 39 | import org.apache.lucene.util.BytesRef; 40 | import static org.apache.lucene.util.Version.LUCENE_48; 41 | 42 | /** 43 | * 44 | * @author Philip van Oosten 45 | */ 46 | public class Main { 47 | 48 | public static void main(String[] args) throws IOException, ParseException { 49 | /* 50 | String indexPath = String.join(File.separator, "D:", "Development", "esa", "nlwiki"); 51 | File wikipediaDumpFile = new File(String.join(File.separator, "D:", "Downloads", "nlwiki", "nlwiki-20140611-pages-articles-multistream.xml.bz2")); 52 | String startTokens = "geheim anoniem auteur verhalen lezen schrijven wetenschappelijk artikel peer review"; 53 | */ 54 | WikiFactory factory = new EnwikiFactory(); 55 | File indexPath = factory.getIndexRootPath(); 56 | File wikipediaDumpFile = factory.getWikipediaDumpFile(); 57 | String startTokens = "secret anonymous author stories read write scientific article peer review"; 58 | CharArraySet stopWords = factory.getStopWords(); 59 | 60 | File termDocIndexDirectory = factory.getTermDocIndexDirectory(); 61 | File conceptTermIndexDirectory = factory.getConceptTermIndexDirectory(); 62 | 63 | // The following lines are commented, because they can take a looong time. 64 | // indexing(termDocIndexDirectory, wikipediaDumpFile, stopWords); 65 | // createConceptTermIndex(termDocIndexDirectory, conceptTermIndexDirectory); 66 | } 67 | 68 | /** 69 | * Creates a concept-term index from a term-to-concept index (a full text index of a Wikipedia dump). 70 | * @param termDocIndexDirectory The directory that contains the term-to-concept index, which is created by {@code indexing()} or in a similar fashion. 71 | * @param conceptTermIndexDirectory The directory that shall contain the concept-term index. 72 | * @throws IOException 73 | */ 74 | static void createConceptTermIndex(File termDocIndexDirectory, File conceptTermIndexDirectory) throws IOException { 75 | ExecutorService es = Executors.newFixedThreadPool(2); 76 | 77 | final Directory termDocDirectory = FSDirectory.open(termDocIndexDirectory); 78 | final IndexReader termDocReader = IndexReader.open(termDocDirectory); 79 | final IndexSearcher docSearcher = new IndexSearcher(termDocReader); 80 | 81 | Fields fields = MultiFields.getFields(termDocReader); 82 | if (fields != null) { 83 | Terms terms = fields.terms(WikiIndexer.TEXT_FIELD); 84 | TermsEnum termsEnum = terms.iterator(null); 85 | 86 | final IndexWriterConfig conceptIndexWriterConfig = new IndexWriterConfig(LUCENE_48, null); 87 | try (IndexWriter conceptIndexWriter = new IndexWriter(FSDirectory.open(conceptTermIndexDirectory), conceptIndexWriterConfig)) { 88 | int t = 0; 89 | BytesRef bytesRef; 90 | while ((bytesRef = termsEnum.next()) != null) { 91 | String termString = bytesRef.utf8ToString(); 92 | if (termString.matches("^[a-zA-Z]+:/.*$") || termString.matches("^\\d+$")) { 93 | continue; 94 | } 95 | if (termString.charAt(0) >= '0' && termString.charAt(0) <= '9') { 96 | continue; 97 | } 98 | if (termString.contains(".") || termString.contains("_")) { 99 | continue; 100 | } 101 | if (t++ == 1000) { 102 | t = 0; 103 | System.out.println(termString); 104 | } 105 | TopDocs td = SearchTerm(bytesRef, docSearcher); 106 | 107 | // add the concepts to the token stream 108 | byte[] payloadBytes = new byte[5]; 109 | ByteArrayDataOutput dataOutput = new ByteArrayDataOutput(payloadBytes); 110 | CachingTokenStream pcTokenStream = new CachingTokenStream(); 111 | double norm = ConceptSimilarity.SIMILARITY_FACTOR; 112 | int last = 0; 113 | for(ScoreDoc scoreDoc : td.scoreDocs){ 114 | if(scoreDoc.score/norm < ConceptSimilarity.SIMILARITY_FACTOR || 115 | last>= 1.0f / ConceptSimilarity.SIMILARITY_FACTOR) break; 116 | norm += scoreDoc.score * scoreDoc.score; 117 | last++; 118 | } 119 | for (int i=0; i Opbouwen van een graaf. Verwijder alle knopen met graad 1, en opnieuw tot er geen meer zijn. 14 | 15 | implementeer de automatische brainstormer op basis van de RelatedTokensFinder. 16 | Start met startTokens 17 | zoek related tokens voor alle startTokens 18 | zoek verder tot X aantal paden of totaal gewicht W tussen alle startTokens bestaan. 19 | 20 | 21 | Maak van de methode Main.createConceptTermIndex de klasse ConceptVectorIndexer 22 | ============================================================================== 23 | Indexeer willekeurige teksten mbv Vectorizer 24 | Indexeer alle tokens in de wiki-index 25 | ... 26 | Maak een package voor wiki-indexen be.vanoosten.esa.wiki en een voor semantische indexen: be.vanoosten.esa.concepts 27 | 28 | 29 | Tool om teksten te clusteren op semantic relatedness 30 | ---------------------------------------------------- 31 | - indexeer de teksten op concept 32 | - relatedness kan nu realtime bepaald worden ipv telkens biede teksten te zoeken en resultaten te vergelijken met cosinus: 33 | ---> maak query van ene tekst 34 | ---> filter enkel de andere tekst uit zoekresultaten, gebruik search score als relatedness 35 | 36 | Mogelijkheden voor optimalisatie 37 | -------------------------------- 38 | - de term-concept index tot een index van concepten per n-gram of frase (na chunking) 39 | - CLESA 40 | 41 | 42 | -------------------------------------------------------------------------------- /src/main/java/be/vanoosten/esa/WikiAnalyzer.java: -------------------------------------------------------------------------------- 1 | package be.vanoosten.esa; 2 | 3 | import org.apache.lucene.analysis.Analyzer; 4 | import org.apache.lucene.analysis.core.LowerCaseFilter; 5 | import org.apache.lucene.analysis.core.StopFilter; 6 | import org.apache.lucene.analysis.TokenStream; 7 | import org.apache.lucene.analysis.Tokenizer; 8 | import org.apache.lucene.analysis.snowball.SnowballFilter; 9 | import org.apache.lucene.analysis.standard.StandardFilter; 10 | import org.apache.lucene.analysis.standard.StandardTokenizer; 11 | import org.apache.lucene.analysis.util.CharArraySet; 12 | import org.apache.lucene.analysis.util.WordlistLoader; 13 | import org.apache.lucene.util.IOUtils; 14 | import org.apache.lucene.util.Version; 15 | 16 | import java.io.IOException; 17 | import java.io.Reader; 18 | import java.nio.charset.StandardCharsets; 19 | import org.apache.lucene.analysis.wikipedia.WikipediaTokenizer; 20 | 21 | // copied from DutchAnalyzer, changed StandardTokenizer to WikipediaTokenizer 22 | public final class WikiAnalyzer extends Analyzer { 23 | 24 | /** 25 | * Contains the stopwords used with the StopFilter. 26 | */ 27 | private final CharArraySet stoptable; 28 | 29 | // null if on 3.1 or later - only for bw compat 30 | private final Version matchVersion; 31 | 32 | public WikiAnalyzer(Version matchVersion, CharArraySet stopwords) { 33 | this.matchVersion = matchVersion; 34 | this.stoptable = CharArraySet.unmodifiableSet(CharArraySet.copy(matchVersion, stopwords)); 35 | } 36 | 37 | /** 38 | * Returns a (possibly reused) {@link TokenStream} which tokenizes all the 39 | * text in the provided {@link Reader}. 40 | * 41 | * @param aReader 42 | * @return A {@link TokenStream} built from a {@link StandardTokenizer} 43 | * filtered with {@link StandardFilter}, {@link LowerCaseFilter}, 44 | * {@link StopFilter} 45 | */ 46 | @Override 47 | protected Analyzer.TokenStreamComponents createComponents(String fieldName, Reader aReader) { 48 | final Tokenizer source = new WikipediaTokenizer(aReader); 49 | TokenStream result = new StandardFilter(matchVersion, source); 50 | result = new LowerCaseFilter(matchVersion, result); 51 | result = new StopFilter(matchVersion, result, stoptable); 52 | return new Analyzer.TokenStreamComponents(source, result); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/be/vanoosten/esa/WikiFactory.java: -------------------------------------------------------------------------------- 1 | package be.vanoosten.esa; 2 | 3 | import be.vanoosten.esa.tools.RelatedTokensFinder; 4 | import be.vanoosten.esa.tools.Vectorizer; 5 | import java.io.File; 6 | import java.io.IOException; 7 | import java.util.logging.Level; 8 | import java.util.logging.Logger; 9 | import org.apache.lucene.analysis.Analyzer; 10 | import org.apache.lucene.analysis.util.CharArraySet; 11 | import org.apache.lucene.index.DirectoryReader; 12 | import org.apache.lucene.queryparser.classic.QueryParser; 13 | import org.apache.lucene.search.IndexSearcher; 14 | import org.apache.lucene.store.FSDirectory; 15 | import org.apache.lucene.util.Version; 16 | import static org.apache.lucene.util.Version.LUCENE_48; 17 | 18 | /** 19 | * 20 | * @author Philip van Oosten 21 | */ 22 | public abstract class WikiFactory implements AutoCloseable { 23 | 24 | private Vectorizer vectorizer; 25 | private Analyzer analyzer; 26 | private RelatedTokensFinder relatedTokensFinder; 27 | private final File indexRootPath; 28 | private final File dumpFile; 29 | private final CharArraySet stopWords; 30 | private IndexSearcher relatedTermsSearcher; 31 | private FSDirectory relatedTermsIndex; 32 | private DirectoryReader relatedTermsIndexReader; 33 | 34 | protected WikiFactory(File indexRootPath, File dumpFile, CharArraySet stopWords) { 35 | this.indexRootPath = indexRootPath; 36 | this.dumpFile = dumpFile; 37 | this.stopWords = stopWords; 38 | } 39 | 40 | public final File getIndexRootPath() { 41 | return indexRootPath; 42 | } 43 | 44 | public final File getWikipediaDumpFile() { 45 | return dumpFile; 46 | } 47 | 48 | public final CharArraySet getStopWords() { 49 | return stopWords; 50 | } 51 | 52 | public final Analyzer getAnalyzer() { 53 | if (analyzer == null) { 54 | analyzer = new WikiAnalyzer(Version.LUCENE_48, getStopWords()); 55 | } 56 | return analyzer; 57 | } 58 | 59 | public synchronized final Vectorizer getOrCreateVectorizer() { 60 | if (vectorizer == null) { 61 | try { 62 | vectorizer = new Vectorizer(getIndexRootPath(), getAnalyzer()); 63 | } catch (IOException ex) { 64 | Logger.getLogger(EnwikiFactory.class.getName()).log(Level.SEVERE, null, ex); 65 | } 66 | } 67 | return vectorizer; 68 | } 69 | 70 | @Override 71 | public synchronized final void close() throws Exception { 72 | if (vectorizer != null) { 73 | vectorizer.close(); 74 | vectorizer = null; 75 | } 76 | if (relatedTermsSearcher != null) { 77 | relatedTermsIndex.close(); 78 | relatedTermsIndexReader.close(); 79 | relatedTermsSearcher = null; 80 | } 81 | } 82 | 83 | public synchronized final IndexSearcher getOrCreateRelatedTermsSearcher() { 84 | if (relatedTermsSearcher == null) { 85 | try { 86 | relatedTermsIndex = FSDirectory.open(getConceptTermIndexDirectory()); 87 | relatedTermsIndexReader = DirectoryReader.open(relatedTermsIndex); 88 | QueryParser conceptQueryParser = new QueryParser(LUCENE_48, WikiIndexer.TEXT_FIELD, getAnalyzer()); 89 | relatedTermsSearcher = new IndexSearcher(relatedTermsIndexReader); 90 | } catch (IOException ex) { 91 | Logger.getLogger(WikiFactory.class.getName()).log(Level.SEVERE, null, ex); 92 | } 93 | } 94 | return relatedTermsSearcher; 95 | } 96 | 97 | public synchronized RelatedTokensFinder getOrCreateRelatedTokensFinder() { 98 | if (relatedTokensFinder == null) { 99 | IndexSearcher searcher = getOrCreateRelatedTermsSearcher(); 100 | relatedTokensFinder = new RelatedTokensFinder(getOrCreateVectorizer(), relatedTermsIndexReader, relatedTermsSearcher); 101 | } 102 | return relatedTokensFinder; 103 | } 104 | 105 | public final File getConceptTermIndexDirectory() { 106 | return new File(getIndexRootPath(), "conceptterm"); 107 | } 108 | 109 | public final File getTermDocIndexDirectory() { 110 | return new File(getIndexRootPath(), "termdoc"); 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/main/java/be/vanoosten/esa/WikiIndexer.java: -------------------------------------------------------------------------------- 1 | package be.vanoosten.esa; 2 | 3 | import java.io.BufferedInputStream; 4 | import java.io.File; 5 | import java.io.FileInputStream; 6 | import java.io.FileNotFoundException; 7 | import java.io.IOException; 8 | import java.io.InputStream; 9 | import java.util.logging.Level; 10 | import java.util.logging.Logger; 11 | import java.util.regex.Matcher; 12 | import java.util.regex.Pattern; 13 | import javax.xml.parsers.ParserConfigurationException; 14 | import javax.xml.parsers.SAXParser; 15 | import javax.xml.parsers.SAXParserFactory; 16 | import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; 17 | import org.apache.lucene.analysis.Analyzer; 18 | import org.apache.lucene.document.Document; 19 | import org.apache.lucene.document.Field; 20 | import org.apache.lucene.document.StoredField; 21 | import org.apache.lucene.document.TextField; 22 | import org.apache.lucene.index.IndexWriter; 23 | import org.apache.lucene.index.IndexWriterConfig; 24 | import org.apache.lucene.store.Directory; 25 | import org.apache.lucene.util.Version; 26 | import org.xml.sax.Attributes; 27 | import org.xml.sax.SAXException; 28 | import org.xml.sax.helpers.DefaultHandler; 29 | 30 | /** 31 | * 32 | * @author Philip van Oosten 33 | */ 34 | public class WikiIndexer extends DefaultHandler implements AutoCloseable { 35 | 36 | private final SAXParserFactory saxFactory; 37 | private boolean inPage; 38 | private boolean inPageTitle; 39 | private boolean inPageText; 40 | private StringBuilder content = new StringBuilder(); 41 | private String wikiTitle; 42 | private int numIndexed = 0; 43 | private int numTotal = 0; 44 | 45 | public static final String TEXT_FIELD = "text"; 46 | public static final String TITLE_FIELD = "title"; 47 | Pattern pat; 48 | 49 | IndexWriter indexWriter; 50 | 51 | int minimumArticleLength; 52 | 53 | /** 54 | * Gets the minimum length of an article in characters that should be 55 | * indexed. 56 | * 57 | * @return 58 | */ 59 | public int getMinimumArticleLength() { 60 | return minimumArticleLength; 61 | } 62 | 63 | /** 64 | * Sets the minimum length of an article in characters for it to be indexed. 65 | * 66 | * @param minimumArticleLength 67 | */ 68 | public final void setMinimumArticleLength(int minimumArticleLength) { 69 | this.minimumArticleLength = minimumArticleLength; 70 | } 71 | 72 | public WikiIndexer(Analyzer analyzer, Directory directory) throws IOException { 73 | saxFactory = SAXParserFactory.newInstance(); 74 | saxFactory.setNamespaceAware(true); 75 | saxFactory.setValidating(true); 76 | saxFactory.setXIncludeAware(true); 77 | 78 | IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_48, analyzer); 79 | indexWriter = new IndexWriter(directory, indexWriterConfig); 80 | String regex = "^[a-zA-z]+:.*"; 81 | pat = Pattern.compile(regex); 82 | setMinimumArticleLength(2000); 83 | } 84 | 85 | public void parseXmlDump(String path) { 86 | parseXmlDump(new File(path)); 87 | } 88 | 89 | public void parseXmlDump(File file) { 90 | try { 91 | SAXParser saxParser = saxFactory.newSAXParser(); 92 | InputStream wikiInputStream = new FileInputStream(file); 93 | wikiInputStream = new BufferedInputStream(wikiInputStream); 94 | wikiInputStream = new BZip2CompressorInputStream(wikiInputStream, true); 95 | saxParser.parse(wikiInputStream, this); 96 | } catch (ParserConfigurationException | SAXException | FileNotFoundException ex) { 97 | Logger.getLogger(WikiIndexer.class.getName()).log(Level.SEVERE, null, ex); 98 | } catch (IOException ex) { 99 | Logger.getLogger(WikiIndexer.class.getName()).log(Level.SEVERE, null, ex); 100 | } 101 | } 102 | 103 | @Override 104 | public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { 105 | if ("page".equals(localName)) { 106 | inPage = true; 107 | } else if (inPage && "title".equals(localName)) { 108 | inPageTitle = true; 109 | content = new StringBuilder(); 110 | } else if (inPage && "text".equals(localName)) { 111 | inPageText = true; 112 | content = new StringBuilder(); 113 | } 114 | } 115 | 116 | @Override 117 | public void endElement(String uri, String localName, String qName) throws SAXException { 118 | if (inPage && inPageTitle && "title".equals(localName)) { 119 | inPageTitle = false; 120 | wikiTitle = content.toString(); 121 | } else if (inPage && inPageText && "text".equals(localName)) { 122 | inPageText = false; 123 | String wikiText = content.toString(); 124 | try { 125 | numTotal++; 126 | if (index(wikiTitle, wikiText)) { 127 | numIndexed++; 128 | if (numIndexed % 1000 == 0) { 129 | System.out.println("" + numIndexed + "\t/ " + numTotal + "\t" + wikiTitle); 130 | } 131 | } 132 | } catch (IOException ex) { 133 | throw new RuntimeException(ex); 134 | } 135 | } else if (inPage && "page".equals(localName)) { 136 | inPage = false; 137 | } 138 | } 139 | 140 | @Override 141 | public void characters(char[] ch, int start, int length) throws SAXException { 142 | content.append(ch, start, length); 143 | } 144 | 145 | boolean index(String title, String wikiText) throws IOException { 146 | Matcher matcher = pat.matcher(title); 147 | if (matcher.find() || title.startsWith("Lijst van ") || wikiText.length() < getMinimumArticleLength()) { 148 | return false; 149 | } 150 | Document doc = new Document(); 151 | doc.add(new StoredField(TITLE_FIELD, title)); 152 | Analyzer analyzer = indexWriter.getAnalyzer(); 153 | doc.add(new TextField(TEXT_FIELD, wikiText, Field.Store.NO)); 154 | indexWriter.addDocument(doc); 155 | return true; 156 | } 157 | 158 | @Override 159 | public void close() throws IOException { 160 | indexWriter.close(); 161 | } 162 | 163 | } 164 | -------------------------------------------------------------------------------- /src/main/java/be/vanoosten/esa/brainstorm/Brainstormer.java: -------------------------------------------------------------------------------- 1 | package be.vanoosten.esa.brainstorm; 2 | 3 | import be.vanoosten.esa.WikiFactory; 4 | import be.vanoosten.esa.tools.RelatedTokensFinder; 5 | import com.tinkerpop.blueprints.Direction; 6 | import com.tinkerpop.blueprints.Edge; 7 | import com.tinkerpop.blueprints.Graph; 8 | import com.tinkerpop.blueprints.Vertex; 9 | import com.tinkerpop.blueprints.impls.tg.TinkerGraph; 10 | import java.io.IOException; 11 | import java.util.ArrayList; 12 | import java.util.Arrays; 13 | import java.util.List; 14 | import java.util.Map.Entry; 15 | import java.util.logging.Level; 16 | import java.util.logging.Logger; 17 | import org.apache.lucene.queryparser.classic.ParseException; 18 | 19 | /** 20 | * 21 | * @author Philip van Oosten 22 | */ 23 | public class Brainstormer { 24 | 25 | public static final String SCORE_PROPERTY = "score"; 26 | public static final String RELATED_EDGE = "related"; 27 | public static final String ERROR_EDGE = "error"; 28 | public static final String START_VERTEX = "start"; 29 | public static final String TOKEN_PROPERTY = "token"; 30 | 31 | private final Graph g; 32 | private final WikiFactory wikiFactory; 33 | private final Integer[] startTokenVertices; 34 | 35 | private int lastVertexId = 0; 36 | 37 | /** 38 | * 39 | * @param wikiFactory the factory to create all required resources from 40 | * @param breadth the maximum number of related tokens per token 41 | * @param depth the maximum number of tries 42 | * @param startTokens the tokens to start searching from 43 | */ 44 | public Brainstormer(WikiFactory wikiFactory, int breadth, int depth, String... startTokens) { 45 | this.wikiFactory = wikiFactory; 46 | g = new TinkerGraph(); 47 | 48 | startTokenVertices = addStartTokens(startTokens); 49 | 50 | // mark the start token vertices as end points 51 | List endPoints = Arrays.asList(startTokenVertices); 52 | // Until end condition reached, find new tokens 53 | RelatedTokensFinder relatedTokensFinder = wikiFactory.getOrCreateRelatedTokensFinder(); 54 | do { 55 | List newEndPoints = new ArrayList<>(); 56 | for (Integer endPoint : endPoints) { 57 | String endPointToken = g.getVertex(endPoint).getProperty(TOKEN_PROPERTY).toString(); 58 | try { 59 | List> relatedTerms = relatedTokensFinder.findRelatedTerms(endPointToken, breadth); 60 | for (Entry entry : relatedTerms) { 61 | String token = entry.getKey(); 62 | int id = lastVertexId; 63 | Integer newTokenVertex = addTokenVertex(token); 64 | float score = entry.getValue(); 65 | if (id != lastVertexId) { 66 | // the token was added 67 | newEndPoints.add(newTokenVertex); 68 | } 69 | Edge e = addEdge(endPoint, newTokenVertex, RELATED_EDGE); 70 | e.setProperty(SCORE_PROPERTY, score); 71 | } 72 | } catch (ParseException | IOException ex) { 73 | Logger.getLogger(Brainstormer.class.getName()).log(Level.SEVERE, null, ex); 74 | Vertex v = g.getVertex(endPoint); 75 | Edge e = v.addEdge(ERROR_EDGE, getErrorVertex()); 76 | e.setProperty("message", ex.getMessage()); 77 | } 78 | } 79 | endPoints = newEndPoints; 80 | } while (depth-- > 0); 81 | 82 | // Until no more tokens are branched, branch tokens with degree 1 83 | // start with endPoints, which contains all the leaves. 84 | while (!endPoints.isEmpty()) { 85 | Integer endPoint = endPoints.get(0); 86 | Vertex vEnd = g.getVertex(endPoint); 87 | if(vEnd == null){ 88 | endPoints.remove(0); 89 | continue; 90 | } 91 | Counter c = new Counter(); 92 | vEnd.getEdges(Direction.BOTH, RELATED_EDGE).spliterator().forEachRemaining(e -> c.count()); 93 | int degree = c.c; 94 | if (degree == 1) { 95 | Edge edge = vEnd.getEdges(Direction.BOTH, RELATED_EDGE).iterator().next(); 96 | Vertex newEndpoint = edge.getVertex(Direction.IN) == vEnd ? edge.getVertex(Direction.OUT) : edge.getVertex(Direction.IN); 97 | endPoints.add(Integer.parseInt(newEndpoint.getId().toString())); 98 | g.removeEdge(edge); 99 | g.removeVertex(vEnd); 100 | } else if (degree > 1){ 101 | endPoints.remove(0); 102 | } 103 | } 104 | } 105 | 106 | private Edge addEdge(int fromVertexId, int toVertexId, String type) { 107 | return g.getVertex(fromVertexId).addEdge(type, g.getVertex(toVertexId)); 108 | } 109 | 110 | private int addTokenVertex(final String token) { 111 | return addTokenVertex(token, false); 112 | } 113 | 114 | private class Counter{ 115 | int c = 0; 116 | void count(){ 117 | c++; 118 | } 119 | } 120 | 121 | private int addTokenVertex(final String token, final boolean startToken) { 122 | Iterable verts = g.getVertices(TOKEN_PROPERTY, token); 123 | Counter c = new Counter(); 124 | verts.spliterator().forEachRemaining(v -> c.count()); 125 | final int count = c.c; 126 | int vertexId = -1; 127 | if (count <= 0L) { 128 | lastVertexId++; 129 | vertexId = lastVertexId; 130 | Vertex v = g.addVertex(vertexId); 131 | v.setProperty(TOKEN_PROPERTY, token); 132 | v.setProperty(START_VERTEX, startToken); 133 | } else if (count == 1L) { 134 | vertexId = Integer.parseInt(verts.iterator().next().getId().toString()); 135 | } else { 136 | throw new IllegalStateException("There are multiple vertices with the same token"); 137 | } 138 | return vertexId; 139 | } 140 | 141 | private Vertex getErrorVertex() { 142 | Vertex errorVertex = g.getVertex("error"); 143 | if (errorVertex == null) { 144 | errorVertex = g.addVertex("error"); 145 | } 146 | return errorVertex; 147 | } 148 | 149 | private Integer[] addStartTokens(final String[] startTokens) { 150 | // Add start tokens 151 | @SuppressWarnings("LocalVariableHidesMemberVariable") 152 | Integer[] startTokenVertices = new Integer[startTokens.length]; 153 | for (int i = 0; i < startTokens.length; i++) { 154 | startTokenVertices[i] = addTokenVertex(startTokens[i], true); 155 | } 156 | return startTokenVertices; 157 | } 158 | 159 | public String toNeatoScript() { 160 | StringBuilder buf = new StringBuilder(); 161 | buf.append("graph g {\nnode[shape=box];\n"); 162 | writeNeatoVertices(buf, true); 163 | writeNeatoVertices(buf, false); 164 | writeNeatoEdges(buf); 165 | buf.append("}"); 166 | return buf.toString(); 167 | } 168 | 169 | void writeNeatoEdges(StringBuilder buf){ 170 | for(Edge e : g.getEdges()){ 171 | if(RELATED_EDGE.equals(e.getLabel())){ 172 | String from = e.getVertex(Direction.OUT).getId().toString(); 173 | String to = e.getVertex(Direction.IN).getId().toString(); 174 | float score = e.getProperty(Brainstormer.SCORE_PROPERTY); 175 | buf.append(from).append(" -- ").append(to).append(" [label=\"").append(score).append("\"];").append('\n'); 176 | } 177 | } 178 | } 179 | 180 | void writeNeatoVertices(StringBuilder buf, boolean startToken) { 181 | for (Vertex v : g.getVertices(START_VERTEX, startToken)) { 182 | int id = Integer.parseInt(v.getId().toString()); 183 | String token = (String) v.getProperty(TOKEN_PROPERTY); 184 | writeNeatoVertex(buf, id, token, startToken); 185 | } 186 | } 187 | 188 | private void writeNeatoVertex(StringBuilder buf, int id, String token, boolean startToken) { 189 | buf.append(id).append(startToken?"[color=red, label=\"" : "[label=\"").append(token).append("\"];"); 190 | buf.append('\n'); 191 | } 192 | } 193 | -------------------------------------------------------------------------------- /src/main/java/be/vanoosten/esa/gui/AbstractViewModel.java: -------------------------------------------------------------------------------- 1 | package be.vanoosten.esa.gui; 2 | 3 | import java.beans.PropertyChangeEvent; 4 | import java.beans.PropertyChangeListener; 5 | import java.beans.PropertyChangeSupport; 6 | 7 | /** 8 | * 9 | * @author Philip van Oosten 10 | */ 11 | public abstract class AbstractViewModel { 12 | 13 | protected AbstractViewModel() { 14 | } 15 | 16 | private final PropertyChangeSupport support = new PropertyChangeSupport(this); 17 | 18 | public final void addPropertyChangeListener(PropertyChangeListener listener) { 19 | support.addPropertyChangeListener(listener); 20 | } 21 | 22 | public final void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { 23 | support.addPropertyChangeListener(listener); 24 | } 25 | 26 | protected final void firePropertyChange(String propertyName, Object oldValue, Object newValue) { 27 | support.firePropertyChange(propertyName, oldValue, newValue); 28 | } 29 | 30 | protected final void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) { 31 | support.firePropertyChange(propertyName, oldValue, newValue); 32 | } 33 | 34 | protected final void firePropertyChange(String propertyName, int oldValue, int newValue) { 35 | support.firePropertyChange(propertyName, oldValue, newValue); 36 | } 37 | 38 | protected final void fireIndexedPropertyChange(String propertyName, int index, Object oldValue, Object newValue) { 39 | support.fireIndexedPropertyChange(propertyName, index, oldValue, newValue); 40 | } 41 | 42 | protected final void fireIndexedPropertyChange(String propertyName, int index, boolean oldValue, boolean newValue) { 43 | support.fireIndexedPropertyChange(propertyName, index, oldValue, newValue); 44 | } 45 | 46 | protected final void fireIndexedPropertyChange(String propertyName, int index, int oldValue, int newValue) { 47 | support.fireIndexedPropertyChange(propertyName, index, oldValue, newValue); 48 | } 49 | 50 | protected final void firePropertyChange(PropertyChangeEvent event) { 51 | support.firePropertyChange(event); 52 | } 53 | 54 | public final PropertyChangeListener[] getPropertyChangeListeners() { 55 | return support.getPropertyChangeListeners(); 56 | } 57 | 58 | public final PropertyChangeListener[] getPropertyChangeListeners(String propertyName) { 59 | return support.getPropertyChangeListeners(propertyName); 60 | } 61 | 62 | public final boolean hasListeners(String propertyName) { 63 | return support.hasListeners(propertyName); 64 | } 65 | 66 | public final void removePropertyChangeListener(PropertyChangeListener listener) { 67 | support.removePropertyChangeListener(listener); 68 | } 69 | 70 | public final void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { 71 | support.removePropertyChangeListener(propertyName, listener); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/be/vanoosten/esa/gui/EsaFrame.form: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 |
131 | -------------------------------------------------------------------------------- /src/main/java/be/vanoosten/esa/gui/EsaFrame.java: -------------------------------------------------------------------------------- 1 | package be.vanoosten.esa.gui; 2 | 3 | import java.beans.PropertyChangeEvent; 4 | import java.beans.PropertyChangeListener; 5 | 6 | /** 7 | * 8 | * @author Philip van Oosten 9 | */ 10 | public class EsaFrame extends javax.swing.JFrame implements PropertyChangeListener { 11 | 12 | private EsaViewModel configuration; 13 | 14 | public EsaViewModel getConfiguration() { 15 | return configuration; 16 | } 17 | 18 | public final void setConfiguration(EsaViewModel configuration) { 19 | this.configuration = configuration; 20 | configuration.addPropertyChangeListener(this); 21 | } 22 | 23 | /** 24 | * Creates new form EsaFrame 25 | */ 26 | public EsaFrame() { 27 | initComponents(); 28 | setConfiguration(new EsaViewModel()); 29 | } 30 | 31 | /** 32 | * This method is called from within the constructor to initialize the form. 33 | * WARNING: Do NOT modify this code. The content of this method is always 34 | * regenerated by the Form Editor. 35 | */ 36 | @SuppressWarnings("unchecked") 37 | // //GEN-BEGIN:initComponents 38 | private void initComponents() { 39 | bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); 40 | 41 | jScrollPane2 = new javax.swing.JScrollPane(); 42 | jScrollPane1 = new javax.swing.JScrollPane(); 43 | outputText = new javax.swing.JTextArea(); 44 | jLabel1 = new javax.swing.JLabel(); 45 | jLabel2 = new javax.swing.JLabel(); 46 | jScrollPane3 = new javax.swing.JScrollPane(); 47 | inputText = new javax.swing.JTextArea(); 48 | jButton1 = new javax.swing.JButton(); 49 | 50 | setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 51 | setTitle("ESA tools"); 52 | 53 | outputText.setColumns(20); 54 | outputText.setRows(5); 55 | 56 | org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${configuration.outputText}"), outputText, org.jdesktop.beansbinding.BeanProperty.create("text_ON_ACTION_OR_FOCUS_LOST")); 57 | bindingGroup.addBinding(binding); 58 | binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${configuration.foo}"), outputText, org.jdesktop.beansbinding.BeanProperty.create("name")); 59 | bindingGroup.addBinding(binding); 60 | 61 | jScrollPane1.setViewportView(outputText); 62 | 63 | jScrollPane2.setViewportView(jScrollPane1); 64 | 65 | jLabel1.setText("input text"); 66 | 67 | jLabel2.setText("output text"); 68 | 69 | inputText.setColumns(20); 70 | inputText.setRows(5); 71 | 72 | binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${configuration.inputText}"), inputText, org.jdesktop.beansbinding.BeanProperty.create("text_ON_FOCUS_LOST")); 73 | bindingGroup.addBinding(binding); 74 | 75 | jScrollPane3.setViewportView(inputText); 76 | 77 | jButton1.setText("jButton1"); 78 | jButton1.addActionListener(new java.awt.event.ActionListener() { 79 | public void actionPerformed(java.awt.event.ActionEvent evt) { 80 | jButton1ActionPerformed(evt); 81 | } 82 | }); 83 | 84 | javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); 85 | getContentPane().setLayout(layout); 86 | layout.setHorizontalGroup( 87 | layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 88 | .addGroup(layout.createSequentialGroup() 89 | .addContainerGap() 90 | .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 91 | .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING) 92 | .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 802, Short.MAX_VALUE) 93 | .addGroup(layout.createSequentialGroup() 94 | .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 95 | .addComponent(jLabel2) 96 | .addComponent(jLabel1)) 97 | .addGap(0, 0, Short.MAX_VALUE)) 98 | .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() 99 | .addGap(0, 0, Short.MAX_VALUE) 100 | .addComponent(jButton1))) 101 | .addContainerGap()) 102 | ); 103 | layout.setVerticalGroup( 104 | layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 105 | .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() 106 | .addContainerGap(85, Short.MAX_VALUE) 107 | .addComponent(jButton1) 108 | .addGap(18, 18, 18) 109 | .addComponent(jLabel1) 110 | .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) 111 | .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE) 112 | .addGap(18, 18, 18) 113 | .addComponent(jLabel2) 114 | .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) 115 | .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 373, javax.swing.GroupLayout.PREFERRED_SIZE) 116 | .addContainerGap()) 117 | ); 118 | 119 | bindingGroup.bind(); 120 | 121 | pack(); 122 | }// //GEN-END:initComponents 123 | 124 | private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed 125 | getConfiguration().setInputText(getInputText()); 126 | getConfiguration().runSelectedTool(); 127 | }//GEN-LAST:event_jButton1ActionPerformed 128 | 129 | /** 130 | * @param args the command line arguments 131 | */ 132 | public static void main(String args[]) { 133 | /* Set the Nimbus look and feel */ 134 | // 135 | /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. 136 | * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 137 | */ 138 | try { 139 | for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { 140 | if ("Nimbus".equals(info.getName())) { 141 | javax.swing.UIManager.setLookAndFeel(info.getClassName()); 142 | break; 143 | } 144 | } 145 | } catch (ClassNotFoundException ex) { 146 | java.util.logging.Logger.getLogger(EsaFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 147 | } catch (InstantiationException ex) { 148 | java.util.logging.Logger.getLogger(EsaFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 149 | } catch (IllegalAccessException ex) { 150 | java.util.logging.Logger.getLogger(EsaFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 151 | } catch (javax.swing.UnsupportedLookAndFeelException ex) { 152 | java.util.logging.Logger.getLogger(EsaFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 153 | } 154 | // 155 | 156 | /* Create and display the form */ 157 | java.awt.EventQueue.invokeLater(new Runnable() { 158 | public void run() { 159 | new EsaFrame().setVisible(true); 160 | } 161 | }); 162 | } 163 | 164 | // Variables declaration - do not modify//GEN-BEGIN:variables 165 | private javax.swing.JTextArea inputText; 166 | private javax.swing.JButton jButton1; 167 | private javax.swing.JLabel jLabel1; 168 | private javax.swing.JLabel jLabel2; 169 | private javax.swing.JScrollPane jScrollPane1; 170 | private javax.swing.JScrollPane jScrollPane2; 171 | private javax.swing.JScrollPane jScrollPane3; 172 | private javax.swing.JTextArea outputText; 173 | private org.jdesktop.beansbinding.BindingGroup bindingGroup; 174 | // End of variables declaration//GEN-END:variables 175 | 176 | @Override 177 | public void propertyChange(PropertyChangeEvent evt) { 178 | String propertyName = evt.getPropertyName(); 179 | if ("outputText".equals(propertyName) && !configuration.getOutputText().equals(getOutputText())) { 180 | setOutputText(configuration.getOutputText()); 181 | } else if ("inputText".equals(propertyName) && !configuration.getInputText().equals(getInputText())) { 182 | setInputText(configuration.getInputText()); 183 | } 184 | } 185 | 186 | private String getOutputText() { 187 | String value = outputText.getText(); 188 | return value == null ? "" : value; 189 | } 190 | 191 | private void setOutputText(String newValue) { 192 | outputText.setText(newValue); 193 | } 194 | 195 | private void setInputText(String newValue) { 196 | inputText.setText(newValue); 197 | } 198 | 199 | private String getInputText() { 200 | String value = inputText.getText(); 201 | return value == null ? "" : value; 202 | } 203 | } 204 | -------------------------------------------------------------------------------- /src/main/java/be/vanoosten/esa/gui/EsaViewModel.java: -------------------------------------------------------------------------------- 1 | package be.vanoosten.esa.gui; 2 | 3 | import be.vanoosten.esa.EnwikiFactory; 4 | import be.vanoosten.esa.WikiFactory; 5 | import be.vanoosten.esa.brainstorm.Brainstormer; 6 | import be.vanoosten.esa.tools.ConceptVector; 7 | import be.vanoosten.esa.tools.RelatedTokensFinder; 8 | import be.vanoosten.esa.tools.Vectorizer; 9 | import java.io.IOException; 10 | import java.util.Iterator; 11 | import java.util.logging.Level; 12 | import java.util.logging.Logger; 13 | import org.apache.lucene.queryparser.classic.ParseException; 14 | 15 | /** 16 | * 17 | * @author Philip van Oosten 18 | */ 19 | public final class EsaViewModel extends AbstractViewModel { 20 | 21 | private final WikiFactory factory; 22 | 23 | @SuppressWarnings("LeakingThisInConstructor") 24 | public EsaViewModel() { 25 | setInputText("Type the input here..."); 26 | setOutputText("Here comes the output"); 27 | factory = new EnwikiFactory(); 28 | } 29 | 30 | private String inputText; 31 | 32 | public String getInputText() { 33 | return inputText == null ? "" : inputText; 34 | } 35 | 36 | public void setInputText(String inputText) { 37 | if (this.inputText == null ? inputText == null : this.inputText.equals(inputText)) { 38 | return; 39 | } 40 | String old = this.inputText; 41 | this.inputText = inputText; 42 | firePropertyChange("inputText", old, inputText); 43 | } 44 | 45 | private String outputText; 46 | 47 | public String getOutputText() { 48 | return outputText == null ? "" : outputText; 49 | } 50 | 51 | public void setOutputText(String outputText) { 52 | if (this.outputText == null ? outputText == null : this.outputText.equals(outputText)) { 53 | return; 54 | } 55 | String old = this.outputText; 56 | this.outputText = outputText; 57 | firePropertyChange("outputText", old, outputText); 58 | } 59 | 60 | void runSelectedTool() { 61 | // eerst voor enwiki, later andere wikis toevoegen 62 | // Eerst echo, dan andere tools toevoegen, met factory. 63 | 64 | // conceptvector tonen 65 | setOutputText("Even geduld..."); 66 | // showConcepts(); 67 | // showRelatedTokens(); 68 | showBrainstorm(); 69 | } 70 | 71 | private void showRelatedTokens() { 72 | try { 73 | StringBuilder buf = new StringBuilder(); 74 | factory. 75 | getOrCreateRelatedTokensFinder(). 76 | findRelatedTerms(getInputText(), 50). 77 | forEach(t -> buf.append(t.getKey()).append('\n')); 78 | setOutputText(buf.toString()); 79 | } catch (ParseException | IOException ex) { 80 | Logger.getLogger(EsaViewModel.class.getName()).log(Level.SEVERE, null, ex); 81 | setOutputText(ex.toString()); 82 | } 83 | } 84 | 85 | private void showBrainstorm(){ 86 | String[] startTokens = getInputText().split("[\r\n\f]+"); 87 | Brainstormer brainstormer = new Brainstormer(factory, 10, 1, startTokens); 88 | setOutputText(brainstormer.toNeatoScript()); 89 | } 90 | 91 | private void showConcepts() { 92 | try { 93 | Vectorizer vectorizer = factory.getOrCreateVectorizer(); 94 | StringBuilder out = new StringBuilder(); 95 | ConceptVector vector = vectorizer.vectorize(getInputText()); 96 | for (Iterator it = vector.topConcepts(100); it.hasNext();) { 97 | String ccpt = it.next(); 98 | out.append(ccpt).append("\n"); 99 | } 100 | setOutputText(out.toString()); 101 | } catch (ParseException | IOException ex) { 102 | setOutputText(ex.toString()); 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/main/java/be/vanoosten/esa/gui/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * A Swing GUI to use the implemented tools. 3 | */ 4 | package be.vanoosten.esa.gui; -------------------------------------------------------------------------------- /src/main/java/be/vanoosten/esa/tools/ConceptVector.java: -------------------------------------------------------------------------------- 1 | package be.vanoosten.esa.tools; 2 | 3 | import be.vanoosten.esa.WikiIndexer; 4 | import java.io.IOException; 5 | import java.util.HashMap; 6 | import java.util.HashSet; 7 | import java.util.Iterator; 8 | import java.util.Map; 9 | import java.util.Set; 10 | import org.apache.lucene.index.IndexReader; 11 | import org.apache.lucene.index.Term; 12 | import org.apache.lucene.search.BooleanClause; 13 | import org.apache.lucene.search.BooleanQuery; 14 | import org.apache.lucene.search.Query; 15 | import org.apache.lucene.search.ScoreDoc; 16 | import org.apache.lucene.search.TermQuery; 17 | import org.apache.lucene.search.TopDocs; 18 | 19 | /** 20 | * 21 | * @author Philip van Oosten 22 | */ 23 | public class ConceptVector { 24 | 25 | Map conceptWeights; 26 | 27 | ConceptVector(TopDocs td, IndexReader indexReader) throws IOException { 28 | double norm = 0.0; 29 | conceptWeights = new HashMap<>(); 30 | for (ScoreDoc scoreDoc : td.scoreDocs) { 31 | norm += scoreDoc.score * scoreDoc.score; 32 | String concept = indexReader.document(scoreDoc.doc).get(WikiIndexer.TITLE_FIELD); 33 | conceptWeights.put(concept, scoreDoc.score); 34 | } 35 | norm = Math.sqrt(norm); 36 | for (String concept : conceptWeights.keySet()) { 37 | conceptWeights.put(concept, (float) (conceptWeights.get(concept) / norm)); 38 | } 39 | } 40 | 41 | public float dotProduct(ConceptVector other) { 42 | Set commonConcepts = new HashSet<>(other.conceptWeights.keySet()); 43 | commonConcepts.retainAll(conceptWeights.keySet()); 44 | double dotProd = 0.0; 45 | for (String concept : commonConcepts) { 46 | dotProd += conceptWeights.get(concept) * other.conceptWeights.get(concept); 47 | } 48 | return (float) dotProd; 49 | } 50 | 51 | public Iterator topConcepts(int n) { 52 | return conceptWeights.entrySet().stream(). 53 | sorted((Map.Entry e1, Map.Entry e2) -> (int) Math.signum(e1.getValue() - e2.getValue())). 54 | map(e -> e.getKey()). 55 | iterator(); 56 | } 57 | 58 | public Query asQuery() { 59 | BooleanQuery relatedTermsQuery = new BooleanQuery(); 60 | for (Map.Entry entry : conceptWeights.entrySet()) { 61 | String concept = entry.getKey(); 62 | TermQuery conceptAsTermQuery = new TermQuery(new Term("concept", concept)); 63 | conceptAsTermQuery.setBoost(entry.getValue()); 64 | relatedTermsQuery.add(conceptAsTermQuery, BooleanClause.Occur.SHOULD); 65 | } 66 | return relatedTermsQuery; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/be/vanoosten/esa/tools/RelatedTokensFinder.java: -------------------------------------------------------------------------------- 1 | package be.vanoosten.esa.tools; 2 | 3 | import be.vanoosten.esa.WikiIndexer; 4 | import java.io.IOException; 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | import java.util.Map; 8 | import org.apache.lucene.index.IndexReader; 9 | import org.apache.lucene.queryparser.classic.ParseException; 10 | import org.apache.lucene.search.IndexSearcher; 11 | import org.apache.lucene.search.Query; 12 | import org.apache.lucene.search.ScoreDoc; 13 | import org.apache.lucene.search.TopDocs; 14 | 15 | /** 16 | * 17 | * @author Philip van Oosten 18 | */ 19 | public class RelatedTokensFinder { 20 | 21 | private final Vectorizer vectorizer; 22 | private final IndexSearcher relatedTermsSearcher; 23 | private final IndexReader relatedTermsIndexReader; 24 | 25 | public RelatedTokensFinder(final Vectorizer vectorizer, IndexReader relatedTermsIndexReader, IndexSearcher relatedTermsSearcher) { 26 | this.vectorizer = vectorizer; 27 | this.relatedTermsSearcher = relatedTermsSearcher; 28 | this.relatedTermsIndexReader = relatedTermsIndexReader; 29 | } 30 | 31 | public List> findRelatedTerms(String queryText, int n) throws ParseException, IOException { 32 | ConceptVector vec = vectorizer.vectorize(queryText); 33 | Query relatedTermsQuery = vec.asQuery(); 34 | TopDocs topTerms = relatedTermsSearcher.search(relatedTermsQuery, n); 35 | List> tokens = new ArrayList<>(n); 36 | for (ScoreDoc sd : topTerms.scoreDocs) { 37 | String term = relatedTermsIndexReader.document(sd.doc).get(WikiIndexer.TEXT_FIELD); 38 | tokens.add(new Pair(term, sd.score)); 39 | } 40 | return tokens; 41 | } 42 | 43 | static class Pair implements Map.Entry { 44 | 45 | private final String key; 46 | private final float value; 47 | 48 | public Pair(String key, float value) { 49 | this.key = key; 50 | this.value = value; 51 | } 52 | 53 | @Override 54 | public String getKey() { 55 | return key; 56 | } 57 | 58 | @Override 59 | public Float getValue() { 60 | return value; 61 | } 62 | 63 | @Override 64 | public Float setValue(Float value) { 65 | throw new UnsupportedOperationException("Altering values is not supported."); 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/be/vanoosten/esa/tools/SemanticSimilarityTool.java: -------------------------------------------------------------------------------- 1 | package be.vanoosten.esa.tools; 2 | 3 | import java.io.IOException; 4 | import org.apache.lucene.queryparser.classic.ParseException; 5 | 6 | /** 7 | * Calculates a numeric value for the semantic similarity between two texts. 8 | * @author Philip van Oosten 9 | */ 10 | public class SemanticSimilarityTool { 11 | 12 | Vectorizer vectorizer; 13 | 14 | public SemanticSimilarityTool(Vectorizer vectorizer) { 15 | this.vectorizer = vectorizer; 16 | } 17 | 18 | public float findSemanticSimilarity(String formerText, String latterText) throws ParseException, IOException{ 19 | ConceptVector formerVector = vectorizer.vectorize(formerText); 20 | ConceptVector latterVector = vectorizer.vectorize(latterText); 21 | return formerVector.dotProduct(latterVector); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/be/vanoosten/esa/tools/Vectorizer.java: -------------------------------------------------------------------------------- 1 | package be.vanoosten.esa.tools; 2 | 3 | import static be.vanoosten.esa.WikiIndexer.TEXT_FIELD; 4 | import static org.apache.lucene.util.Version.LUCENE_48; 5 | import java.io.File; 6 | import java.io.IOException; 7 | import java.util.logging.Level; 8 | import java.util.logging.Logger; 9 | import org.apache.lucene.analysis.Analyzer; 10 | import org.apache.lucene.index.DirectoryReader; 11 | import org.apache.lucene.index.IndexReader; 12 | import org.apache.lucene.queryparser.classic.ParseException; 13 | import org.apache.lucene.queryparser.classic.QueryParser; 14 | import org.apache.lucene.search.IndexSearcher; 15 | import org.apache.lucene.search.Query; 16 | import org.apache.lucene.search.TopDocs; 17 | import org.apache.lucene.store.Directory; 18 | import org.apache.lucene.store.FSDirectory; 19 | 20 | /** 21 | * Can present text as a vector of weighted concepts. 22 | * 23 | * @author Philip van Oosten 24 | */ 25 | public class Vectorizer implements AutoCloseable { 26 | 27 | Directory termToConceptDirectory; 28 | IndexReader indexReader; 29 | IndexSearcher searcher; 30 | QueryParser queryParser; 31 | int conceptCount; 32 | 33 | /** 34 | * Creates a new Vectorizer 35 | * 36 | * @param indexDirectory The directory where to find the indices 37 | * @param analyzer The analyzer to use to create search queries 38 | * @throws java.io.IOException 39 | */ 40 | public Vectorizer(File indexDirectory, Analyzer analyzer) throws IOException { 41 | File termConceptDirectory = new File(indexDirectory, "termdoc"); 42 | termToConceptDirectory = FSDirectory.open(termConceptDirectory); 43 | indexReader = DirectoryReader.open(termToConceptDirectory); 44 | searcher = new IndexSearcher(indexReader); 45 | queryParser = new QueryParser(LUCENE_48, TEXT_FIELD, analyzer); 46 | conceptCount = 100; 47 | } 48 | 49 | public ConceptVector vectorize(String text) throws ParseException, IOException { 50 | Query query = queryParser.parse(text); 51 | TopDocs td = searcher.search(query, conceptCount); 52 | return new ConceptVector(td, indexReader); 53 | } 54 | 55 | public int getConceptCount() { 56 | return conceptCount; 57 | } 58 | 59 | public void setConceptCount(int conceptCount) { 60 | this.conceptCount = conceptCount; 61 | } 62 | 63 | @Override 64 | public void close() { 65 | try { 66 | indexReader.close(); 67 | termToConceptDirectory.close(); 68 | } catch (IOException ex) { 69 | Logger.getLogger(Vectorizer.class.getName()).log(Level.SEVERE, null, ex); 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/test/java/be/vanoosten/esa/StringMatchingTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package be.vanoosten.esa; 7 | 8 | import java.util.regex.Matcher; 9 | import java.util.regex.Pattern; 10 | import org.junit.After; 11 | import org.junit.AfterClass; 12 | import static org.junit.Assert.*; 13 | import org.junit.Before; 14 | import org.junit.BeforeClass; 15 | import org.junit.Test; 16 | 17 | /** 18 | * 19 | * @author user 20 | */ 21 | public class StringMatchingTest { 22 | 23 | public StringMatchingTest() { 24 | } 25 | 26 | @BeforeClass 27 | public static void setUpClass() { 28 | } 29 | 30 | @AfterClass 31 | public static void tearDownClass() { 32 | } 33 | 34 | @Before 35 | public void setUp() { 36 | } 37 | 38 | @After 39 | public void tearDown() { 40 | } 41 | 42 | private void assertMatchesNamespaceRegex(String title, boolean shouldMatch) { 43 | String regex = "^[a-zA-z]+:.*"; 44 | Pattern pat = Pattern.compile(regex); 45 | Matcher matcher = pat.matcher(title); 46 | assertTrue(String.format("\"%s\" doesn't match /%s/", title, regex), matcher.find() == shouldMatch); 47 | } 48 | 49 | @Test 50 | public void testSplitLines() { 51 | String text = "alpha\n\nbeta\r\ngamma\ndelta\n\n"; 52 | String[] lines = text.split("[\n\r\f]+"); 53 | assertEquals(4, lines.length); 54 | assertEquals("alpha", lines[0]); 55 | assertEquals("beta", lines[1]); 56 | assertEquals("gamma", lines[2]); 57 | assertEquals("delta", lines[3]); 58 | } 59 | 60 | @Test 61 | public void testMatchNamespaceRegex() { 62 | assertMatchesNamespaceRegex("Category: alpha beta gamma\n", true); 63 | assertMatchesNamespaceRegex("Sjabloon:123FooBar", true); 64 | assertMatchesNamespaceRegex("1234Blabla:koolness", false); 65 | } 66 | } 67 | --------------------------------------------------------------------------------