├── docs ├── narralyzer ├── source │ ├── index.rst │ ├── modules.rst │ ├── narralyzer.rst │ └── conf.py └── Makefile ├── .gitignore ├── out ├── pycallgraph.png ├── vondel_graphviz_.pdf.jpg ├── Hear Me, Pilate!_graphviz_.pdf.jpg ├── Pride and Prejudice_graphviz_.pdf.jpg └── the_adventures_of_sherlock_holmeS_graphviz_.pdf.jpg ├── site ├── static │ ├── img │ │ ├── logo_kb.png │ │ └── logo_ru.png │ ├── js │ │ └── narralyzer.js │ └── css │ │ └── style.css ├── templates │ ├── analyze.html │ ├── main.html │ ├── error.html │ ├── index.html │ └── file_uploaded.html ├── .htaccess └── index.py ├── artwork └── narralyzer_logo_small.png ├── narralyzer ├── __init__.py ├── utils.py ├── visualize_ners.py ├── config.py ├── stanford_ner_wrapper.py └── lang_lib.py ├── requirements.txt ├── .travis.yml ├── run-tests.sh ├── README.md ├── conf └── config.ini ├── README.txt ├── start_stanford.sh ├── install.sh └── licence.txt /docs/narralyzer: -------------------------------------------------------------------------------- 1 | ../narralyzer/ -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | t 2 | ramdisk 3 | *graphviz* 4 | tika 5 | env 6 | *swp 7 | stanford 8 | *pyc 9 | -------------------------------------------------------------------------------- /out/pycallgraph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KBNLresearch/Narralyzer/master/out/pycallgraph.png -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | narralyzer 2 | ========== 3 | 4 | .. toctree:: 5 | :maxdepth: 4 6 | 7 | narralyzer 8 | -------------------------------------------------------------------------------- /docs/source/modules.rst: -------------------------------------------------------------------------------- 1 | narralyzer 2 | ========== 3 | 4 | .. toctree:: 5 | :maxdepth: 4 6 | 7 | narralyzer 8 | -------------------------------------------------------------------------------- /out/vondel_graphviz_.pdf.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KBNLresearch/Narralyzer/master/out/vondel_graphviz_.pdf.jpg -------------------------------------------------------------------------------- /site/static/img/logo_kb.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KBNLresearch/Narralyzer/master/site/static/img/logo_kb.png -------------------------------------------------------------------------------- /site/static/img/logo_ru.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KBNLresearch/Narralyzer/master/site/static/img/logo_ru.png -------------------------------------------------------------------------------- /artwork/narralyzer_logo_small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KBNLresearch/Narralyzer/master/artwork/narralyzer_logo_small.png -------------------------------------------------------------------------------- /out/Hear Me, Pilate!_graphviz_.pdf.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KBNLresearch/Narralyzer/master/out/Hear Me, Pilate!_graphviz_.pdf.jpg -------------------------------------------------------------------------------- /out/Pride and Prejudice_graphviz_.pdf.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KBNLresearch/Narralyzer/master/out/Pride and Prejudice_graphviz_.pdf.jpg -------------------------------------------------------------------------------- /out/the_adventures_of_sherlock_holmeS_graphviz_.pdf.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KBNLresearch/Narralyzer/master/out/the_adventures_of_sherlock_holmeS_graphviz_.pdf.jpg -------------------------------------------------------------------------------- /narralyzer/__init__.py: -------------------------------------------------------------------------------- 1 | __all__ = ['stanford_ner_wrapper', 2 | 'Language', 3 | 'utils'] 4 | 5 | from stanford_ner_wrapper import stanford_ner_wrapper 6 | from lang_lib import Language 7 | import utils 8 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | backports.shutil_get_terminal_size 2 | django 3 | flask 4 | Flask-Mako 5 | graphviz 6 | gutenberg 7 | ipython 8 | langdetect 9 | logger 10 | lxml 11 | mako 12 | numpy 13 | pattern 14 | probablepeople 15 | pycallgraph 16 | python-dateutil 17 | python-magic 18 | requests 19 | segtok 20 | stop-words 21 | -------------------------------------------------------------------------------- /site/templates/analyze.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Narralyzer-3 5 | 6 | 7 | 8 | 9 | 10 |

Analyze results

11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: yes 2 | dist: trusty 3 | language: java 4 | jdk: 5 | - oraclejdk8 6 | notifications: 7 | email: 8 | recipients: 9 | - willemjanfaber@fe2.nl 10 | on_success: change 11 | on_failure: always 12 | before_install: 13 | - sudo apt-get -qq update 14 | - sudo apt-get install -y libxml2-dev libdb-dev python2.7 python-pip python-virtualenv netcat 15 | install: 16 | - bash install.sh 17 | script: 18 | - bash run-tests.sh 19 | -------------------------------------------------------------------------------- /site/static/js/narralyzer.js: -------------------------------------------------------------------------------- 1 | $("[id^=chapter]").click(function () { 2 | var $c=$(this).css("background-color"); 3 | $name=$(this).attr('id').replace('_',''); 4 | 5 | if ($("#" + $name).is(':checked')) { 6 | $(this).css({'background-color' : 'lightgray'}); 7 | $("#" + $name).attr('checked', false) 8 | } else { 9 | $(this).css({'background-color' : 'lightgreen'}); 10 | $name=$(this).attr('id').replace('_',''); 11 | $("#" + $name).attr('checked', true) 12 | } 13 | }); 14 | 15 | 16 | -------------------------------------------------------------------------------- /site/templates/main.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Narralyzer-0 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 |

Narralyzer

16 |

Analyzing narratives with DH-tools.

17 |
18 | {% block body %} 19 | {% endblock %} 20 | 21 | 22 | -------------------------------------------------------------------------------- /site/templates/error.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Narralyzer 5 | 6 | 7 | 8 | 9 |

Narralyzer

10 | 11 |

This tool will help you quickly analyze a narrative.

12 |

By looking at the structure of the text, and the main actors in the text, this tool can help you gain insight in the dialog structure..blah blah enzo :)

13 | 14 |
15 |

{{ val }}

16 |

Select 'Browse' to select a file to upload, next press 'Upload' to commence the uploading.
17 |

18 |

19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /run-tests.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # 4 | # File: run-tests.sh 5 | # 6 | # This file is part of the Narralyzer package. 7 | # see: http://lab.kb.nl/tool/narralyzer 8 | 9 | # Little wrapper to datestamp outgoing messages. 10 | function inform_user() { 11 | msg="$1" 12 | timestamp=`date "+%Y-%m-%d %H:%M"` 13 | echo "$timestamp: Narralyzer start_stanford.sh $msg" 14 | } 15 | 16 | function run_test() { 17 | fname="$1" 18 | inform_user "Running doctests for: $fname" 19 | python2.7 "$fname" test || exit -1 20 | } 21 | 22 | 23 | ( 24 | inform_user "Starting Stanford." 25 | . start_stanford.sh waitforstartup 26 | 27 | inform_user "Crawling into virtualenv." 28 | . env/bin/activate 29 | 30 | run_test "./narralyzer/stanford_ner_wrapper.py" 31 | run_test "./narralyzer/lang_lib.py" 32 | run_test "./narralyzer/utils.py" 33 | ) || exit -1 34 | -------------------------------------------------------------------------------- /docs/source/narralyzer.rst: -------------------------------------------------------------------------------- 1 | narralyzer package 2 | ================== 3 | 4 | Submodules 5 | ---------- 6 | 7 | narralyzer.lang_lib module 8 | -------------------------- 9 | 10 | .. automodule:: narralyzer.lang_lib 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | narralyzer.stanford_ner_wrapper module 16 | -------------------------------------- 17 | 18 | .. automodule:: narralyzer.stanford_ner_wrapper 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | 23 | narralyzer.visualize_ners module 24 | -------------------------------- 25 | 26 | .. automodule:: narralyzer.visualize_ners 27 | :members: 28 | :undoc-members: 29 | :show-inheritance: 30 | 31 | 32 | Module contents 33 | --------------- 34 | 35 | .. automodule:: narralyzer 36 | :members: 37 | :undoc-members: 38 | :show-inheritance: 39 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Narralyzer will help you quickly analyze the occurrence of and relations between Entities in narrative texts, such as novels, short stories and newspaper articles in four languages. The following aspects of narrative texts are included in the analysis: 2 | 3 | - NER (Named Entity Recognition) 4 | - Relations between Entities 5 | - Entity-text extraction (aura of n = 5) 6 | 7 | 8 | ![Example output](https://raw.githubusercontent.com/KBNLresearch/Narralyzer/master/out/Hear%20Me%2C%20Pilate!_graphviz_.pdf.jpg) 9 | 10 | The backend library also does POS tagging and sentiment analysis, however this is not exposed in the frontend. 11 | 12 | - Info: http://lab.kb.nl/tool/narralyzer 13 | - Demo: https://kbresearch.nl/narralyzer/ 14 | - Language models: 15 | - https://github.com/WillemJan/Narralyzer_languagemodel 16 | - https://github.com/WillemJan/Narralyzer_Dutch_languagemodel 17 | -------------------------------------------------------------------------------- /site/templates/index.html: -------------------------------------------------------------------------------- 1 | {% extends "main.html" %} 2 | {% block body %} 3 | 4 |

This tool will help you quickly analyze a narrative.

5 |

By looking at the structure of the text, and the main actors in the text, this tool can help you gain insight in the dialog structure..blah blah enzo :)

6 |

Please note the following guidlines for optimal usage of this tool: 7 |

11 | (Wellicht moet er eerst een intro pagina voordat we meteen beginnen met uploaden..)
12 |
13 |

Select 'Browse' to select a file to upload, next press 'Upload' to commence the uploading.
14 |

15 |

16 | 17 | {% endblock %} 18 | -------------------------------------------------------------------------------- /conf/config.ini: -------------------------------------------------------------------------------- 1 | [main] 2 | stanford_ner_path="language_models/stanford/ner" 3 | stanford_core="http://nlp.stanford.edu/software/stanford-corenlp-full-2015-12-09.zip" 4 | tika="http://apache.cs.uu.nl/tika/tika-app-1.13.jar" 5 | 6 | [lang_de] 7 | port = 9990 8 | stanford_ner="german.dewac_175m_600.crf.ser.gz" 9 | stanford_ner_source="http://nlp.stanford.edu/software/stanford-german-2016-01-19-models.jar" 10 | 11 | [lang_en] 12 | port = 9991 13 | stanford_ner="english.all.3class.distsim.crf.ser.gz" 14 | stanford_ner_source="http://nlp.stanford.edu/software/stanford-english-corenlp-2016-01-10-models.jar" 15 | 16 | [lang_nl] 17 | port = 9992 18 | stanford_ner="dutch.crf.gz" 19 | stanford_ner_source="https://raw.githubusercontent.com/WillemJan/Narralyzer_Dutch_languagemodel/master/dutch.crf.gz" 20 | 21 | [lang_sp] 22 | port = 9993 23 | stanford_ner="spanish.ancora.distsim.s512.crf.ser.gz" 24 | stanford_ner_source="http://nlp.stanford.edu/software/stanford-spanish-corenlp-2015-10-14-models.jar" 25 | -------------------------------------------------------------------------------- /site/static/css/style.css: -------------------------------------------------------------------------------- 1 | * { 2 | margin: 0px 0px 0px 0px; 3 | padding: 0px 0px 0px 0px; 4 | } 5 | 6 | body { 7 | background-color: #FFF; 8 | color: #000; 9 | font-family: Arial,Helvetica,sans-serif,Verdana; 10 | font-size: small; 11 | } 12 | 13 | #uploadform { 14 | border: 1px solid #000; 15 | padding: 20px; 16 | width: 300px; 17 | } 18 | 19 | .chapter { 20 | border: 1px solid #000; 21 | margin: 10px; 22 | height: 200px; 23 | overflow: auto; 24 | padding: 5px; 25 | width: 70%; 26 | } 27 | 28 | h1 { 29 | text-align: left; 30 | margin-left: 40%; 31 | padding-top: 30px; 32 | font-family: 'Source Sans Pro', sans-serif; 33 | font-size: 40px; 34 | } 35 | 36 | h2 { 37 | text-align: left; 38 | margin-left: 35%; 39 | font-family: 'Source Sans Pro', sans-serif; 40 | font-size: 20px; 41 | font-style: italic; 42 | } 43 | 44 | 45 | hr { 46 | color: lightblue; 47 | float: left; 48 | width: 40%; 49 | } 50 | 51 | .header { 52 | background: #CACFCA; 53 | height: 120px; 54 | } 55 | 56 | .chapter_selected p { 57 | background-color: #328832; 58 | margin-top: 20px; 59 | margin-left: 100px; 60 | overflow: auto; 61 | height: 100px; 62 | width: 800px; 63 | } 64 | 65 | #header_logo_ru { 66 | padding-top: 5px; 67 | float: right; 68 | clear: both; 69 | width: 200px; 70 | } 71 | 72 | #header_logo_kb { 73 | padding-top: 20px; 74 | float: right; 75 | width: 200px; 76 | } 77 | 78 | input[type="radio"] { 79 | margin-left: 15px; 80 | } 81 | -------------------------------------------------------------------------------- /site/.htaccess: -------------------------------------------------------------------------------- 1 | 2 | SetHandler wsgi-script 3 | Options +ExecCGI 4 | 5 | 6 | RewriteEngine on 7 | RewriteBase / 8 | RewriteCond %{REQUEST_URI} !^/robots.txt 9 | RewriteCond %{REQUEST_URI} !^/static 10 | RewriteCond %{REQUEST_URI} !^(/.*)+index.py 11 | RewriteRule ^(.*)$ index.py/$1 [PT] 12 | -------------------------------------------------------------------------------- /README.txt: -------------------------------------------------------------------------------- 1 | Welcome to Narralyzer. 2 | Travis-CI status 3 | *Warning this site & code is work in progress* 4 | Intermediate result of parser backendlog.pdf 5 | Intermediate result of character visualization 1, 2, still needs some work :) 6 | What does Narralyzer do? 7 | 8 | Narralyzer will help you quickly analyze the occurrence of and relations between Entities in narrative texts, such as novels, short stories and newspaper articles in four languages. The following aspects of narrative texts are included in the analysis: 9 | 10 | NER (Named Entity Recognition) 11 | Relations between Entities 12 | Entity-text detection (aura of n = x) 13 | 14 | Based on the NER and relation-analysis: 15 | 16 | A visualization (using GraphViz, see www.graphviz.org) of the relations between Entities can be created, per text-part and for the entire text 17 | 18 | Entity-text, per text-part and for the entire text, can be downloaded, so the user can then use it as material for performing more computational analyzes 19 | 20 | What does Narralyzer need from you? 21 | 22 | In order for Narralyzer to run properly, the input text should meet the following requirements: 23 | Texts should be in either:Dutch, English, German or Spanish (Due to available NER-models) 24 | Texts should be in one of the following formats: 25 | 26 | TEI 27 | PDF 28 | Epub 29 | Plain text 30 | 31 | Text-parts (i.e. chapters or other relevant structural text-parts) should be classified as such; 32 | Narralyzer will explicitly ask you to do this. 33 | 34 | Exception: when the text-format is PDF or Epub and provides metadata on text partitions, manual text cutting is not always needed. 35 | 36 | Note: for optimal usage of Narralyzer manual partitioning is, for now, the most reliable option. 37 | 38 | How to cite using Narralyzer 39 | 40 | If you use Narralyzer for your research, educational purposes or in any other way, please cite as follows: Wildschut, P.A., Faber, W-J. (2016) Narralyzer. Analyzing Narratives with DH-tools. [http://www.narralyzer.com/] Hosted by the National Library of the Netherlands (KB) & Radboud University Nijmegen. 41 | Contact 42 | 43 | For questions and remarks, please contact Puck Wildschut (p.wildschut@let.ru.nl) For technical support, contact Willem-Jan Faber ([willemjan.faber@kb.nl]) Further information 44 | 45 | Narralyzer has been created within the context of the Researcher-in-residence programme, funded by the National Library of the Netherlands (KB). Narralyzer is the intellectual property of its authors (sic) and the Radboud University Nijmegen. 46 | 47 | -------------------------------------------------------------------------------- /site/templates/file_uploaded.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Narralyzer-1 5 | 6 | 7 | 8 | 9 | 10 | 11 |

Narralyzer

12 | 13 |

14 | 15 | Revieved and parsed:{{ filename }}
16 | Recieved file at: {{ datetime }}

17 | Recieved file is of type: {{ ftype }}
18 | Original filesize (absolute): {{ filesize }}
19 | 20 | 25 | 26 |
27 | 28 |
29 | The following information was dectected automaticly, this is your last change to change it before we start the final analysis.
30 | (of cource you can re-upload and see what happens if you play arround with the structure of the chapters.) 31 | 32 |
33 |

Author: {{ narrative.author }}

34 |

Title: {{ narrative.title }}

35 | 36 | Language for analysis: 37 | {% if narrative.lang == 'nl' %} 38 | nl
39 | en
40 | {% else %} 41 | nl
42 | en
43 | {% endif %} 44 | 45 | 46 |


47 | Please select the chapters that you want to include in the analysis.
48 | Currently selected (X/{{ narrative.nr_of_chapters }}) chapters.

49 | 50 | 51 | {% for i in range(0,narrative.nr_of_chapters) %} 52 | 53 | 54 |
55 |
56 |

{{ narrative.titles[i] }}

57 |

{{ narrative.chapters[i].replace('\n', '
') | safe }}

58 | 59 | 62 | {% endfor %} 63 |
64 | 65 | 66 |
67 | 68 | 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /narralyzer/utils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2.7 2 | # -*- coding: utf-8 -*- 3 | """ 4 | narralyzer.utils 5 | ~~~~~~~~~~~~~~~~ 6 | Misc utilities to support Narralyzer. 7 | 8 | :copyright: (c) 2016 Koninklijke Bibliotheek, by Willem-Jan Faber. 9 | :license: GPLv3, see licence.txt for more details. 10 | """ 11 | 12 | import sys 13 | reload(sys) 14 | sys.setdefaultencoding('utf-8') 15 | 16 | import codecs 17 | import cPickle 18 | import gzip 19 | import json 20 | import logging 21 | import os 22 | import time 23 | 24 | 25 | # Define how often you want to see messages 26 | DEFAULT_LOGLEVEL = logging.DEBUG 27 | 28 | # Define how pretty the logs look 29 | LOG_FORMAT = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s' 30 | 31 | # Get the package-base-path 32 | BASE_PATH = '' 33 | 34 | # Path to test data 35 | TESTDATA_PATH = os.sep +'test_data' + os.sep 36 | 37 | # Path to output files 38 | OUTPUT_PATH = os.sep + 'out' + os.sep 39 | 40 | def logger(name, loglevel='warning'): 41 | try: 42 | loglevel = getattr(logging, 43 | [l for l in dir(logging) if ( 44 | l.isupper() and l.lower()) == loglevel].pop()) 45 | except: 46 | loglevel = DEFAULT_LOGLEVEL 47 | 48 | logger = logging.getLogger(name) 49 | handler = logging.StreamHandler() 50 | formatter = logging.Formatter(LOG_FORMAT) 51 | handler.setFormatter(formatter) 52 | logger.addHandler(handler) 53 | logger.setLevel(loglevel) 54 | return logger 55 | 56 | def narralyze(input_text, output_name=False, return_json=True, verbose=True): 57 | from lang_lib import Language 58 | 59 | if not input_text: 60 | msg = "Did not recieve any text to work with" 61 | return 62 | 63 | output_name = os.path.join( 64 | BASE_PATH, 65 | OUTPUT_PATH, 66 | output_name) 67 | 68 | ''' 69 | 70 | if not os.path.isfile(output_name): 71 | # Open and read the test-book. 72 | fh = codecs.open(fname_txt, 'r', encoding='utf-8') 73 | book = fh.read().replace('\n', ' ') 74 | fh.close() 75 | 76 | # Tag each sentence. 77 | t = time.time() 78 | lang = Language(book) 79 | lang.parse() 80 | if verbose: 81 | print("Took %s to parse %s bytes" % (str(round(time.time() - t)), 82 | str(len(book)))) 83 | 84 | # Store the result to a compressed pickle file. 85 | fh = gzip.GzipFile(ofname, 'wb') 86 | fh.write(cPickle.dumps(lang.result)) 87 | fh.close() 88 | result = lang.result 89 | else: 90 | if not os.path.isfile(ofname): 91 | ofname = os.path.join("..", OUTPUT, fname.replace('.txt', '.pickle.gz')) 92 | # Load the tagged sentences from a compressed pickle file. 93 | fh = gzip.GzipFile(ofname, 'rb') 94 | raw_data = "" 95 | data = fh.read() 96 | 97 | while data: 98 | raw_data += data 99 | data = fh.read() 100 | 101 | langlib_result = cPickle.loads(raw_data) 102 | fh.close() 103 | result = langlib_result 104 | 105 | if return_json: 106 | return json.dumps(result) 107 | return result 108 | ''' 109 | 110 | if __name__ == "__main__": 111 | print("Relativity theory") 112 | #if len(sys.argv) >= 2 and 'test' in " ".join(sys.argv): 113 | # import doctest 114 | # doctest.testmod(verbose=True) 115 | 116 | #from pprint import pprint 117 | #book = load_test_book('dutch_book_gbid_20060.txt') 118 | #pprint(book) 119 | -------------------------------------------------------------------------------- /narralyzer/visualize_ners.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2.7 2 | # -*- coding: utf-8 -*- 3 | """ 4 | narralyzer.visualize_ners 5 | ~~~~~~~~~~~~~~~~~~~~~~~~~ 6 | Implements a dialog visualisation between person's extracted from text. 7 | 8 | :copyright: (c) 2016 Koninklijke Bibliotheek, by Willem Jan Faber. 9 | :license: GPLv3, see licence.txt for more details. 10 | """ 11 | 12 | import sys 13 | reload(sys) 14 | sys.setdefaultencoding('utf-8') 15 | 16 | import os 17 | import string 18 | import sys 19 | 20 | from django.utils.encoding import smart_text 21 | from graphviz import Digraph 22 | from pprint import pprint 23 | 24 | 25 | def analyze(ner_array, dot, name): 26 | ner = {} 27 | print("Total nr of NER's: %i " % len(ner_array)) 28 | for item in ner_array: 29 | if not item in ner: 30 | ner[item] = 0 31 | else: 32 | ner[item] += 1 33 | 34 | ranks = sorted(ner.items(), key=lambda x: x[1]) 35 | to_remove = [] 36 | 37 | ''' 38 | for item in ranks: 39 | if item[1] < 1: 40 | to_remove.append(item[0]) 41 | ''' 42 | 43 | for item in to_remove: 44 | ner.pop(item) 45 | 46 | person_matrix = {} 47 | 48 | interaction_scale = 0 49 | 50 | prev_item = ner_array[-1] 51 | for item in ner: 52 | person = item 53 | person_matrix[person] = {} 54 | for item in ner_array: 55 | if not item == person and prev_item == person: 56 | if not item in person_matrix[person]: 57 | person_matrix[person][item] = 1 58 | else: 59 | person_matrix[person][item] += 1 60 | if person_matrix[person][item] > interaction_scale: 61 | interaction_scale = person_matrix[person][item] 62 | prev_item = item 63 | 64 | print("SCALE:", interaction_scale) 65 | pprint(person_matrix) 66 | 67 | translate_table = {} 68 | 69 | i = 0 70 | for item in person_matrix: 71 | translate_table[item] = string.letters[i] 72 | dot.node(string.letters[i], item) 73 | print(item, string.letters[i]) 74 | i += 1 75 | 76 | for item in person_matrix: 77 | for person in person_matrix[item]: 78 | if (person_matrix[item][person]): 79 | if item in translate_table and person in translate_table: 80 | print(person_matrix[item][person]) 81 | #print(translate_table[item]) 82 | #print(translate_table[person]) 83 | dot.edge(translate_table[item], translate_table[person], color=color_code(person_matrix[item][person], interaction_scale), bgcolor='red', arrowtail='both', label=str(person_matrix[item][person])) 84 | #print(color_code(person_matrix[item][person], interaction_scale)) 85 | #print([ translate_table[item] , translate_table[person] ]) 86 | dot.render(name + "_graphviz_", view=False) 87 | 88 | def color_code(value, max_value): 89 | per = (value * (max_value / 100.0)) * 100 90 | print(per) 91 | if per < 25.0: 92 | return 'green' 93 | if per < 50.0: 94 | return 'blue' 95 | if per < 75.0: 96 | return 'yellow' 97 | return 'red' 98 | 99 | if __name__ == "__main__": 100 | name = 'vondel' 101 | 102 | dot = Digraph(comment=name) 103 | ner_array = [] 104 | result = stanford_ner_wrapper(data, 9991) 105 | 106 | for ner in result.get('ners'): 107 | if ('per' or 'person') in ner.get('tag'): 108 | ner_array.append(ner.get('string')) 109 | 110 | pprint(ner_array) 111 | analyze(ner_array, dot, name) 112 | -------------------------------------------------------------------------------- /narralyzer/config.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2.7 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | narralyzer.config 5 | ~~~~~~~~~~~~~~~~~ 6 | 7 | Handle misc config variables. 8 | 9 | :copyright: (c) 2016 Koninklijke Bibliotheek, by Willem-Jan Faber. 10 | :license: GPLv3, see licence.txt for more details. 11 | ''' 12 | 13 | import sys 14 | reload(sys) 15 | sys.setdefaultencoding('utf-8') 16 | 17 | from os import path, environ, getenv 18 | from ConfigParser import ConfigParser 19 | 20 | try: 21 | from narralyzer.util import logger as logger 22 | except: 23 | from utils import logger 24 | 25 | class Config(): 26 | """ 27 | Configuration file dict. 28 | 29 | >>> config = Config() 30 | >>> config.get('supported_languages') 31 | 'DE EN NL SP' 32 | """ 33 | 34 | config = { 35 | 'config_file': 'conf/config.ini', 36 | 'models': {}, 37 | 'root': None, 38 | 'supported_languages': [] 39 | } 40 | 41 | 42 | def __init__(self): 43 | if self.config.get('root', None) is None: 44 | root = path.join(path.dirname(path.abspath(__file__))) 45 | root = path.join(root, '..') 46 | self.config['root'] = path.abspath(root) 47 | 48 | root = self.config['root'] 49 | logger("My basepath={0}".format(root)) 50 | config_file = path.join(root, self.config.get('config_file')) 51 | 52 | if not path.isfile(config_file): 53 | print("Could not open config file: {0}".format(path.abspath(config_file))) 54 | sys.exit(-1) 55 | 56 | self.config['config_file'] = config_file 57 | config = ConfigParser() 58 | config.read(config_file) 59 | 60 | for section in config.sections(): 61 | if section.startswith('lang_'): 62 | language = section.replace('lang_', '') 63 | port = config.get(section, 'port') 64 | stanford_ner = config.get(section, 'stanford_ner') 65 | self.config['models'][language] = { 66 | 'port': port, 67 | 'stanford_ner': stanford_ner} 68 | if section == 'main': 69 | stanford_ner_path = config.get(section, 'stanford_ner_path') 70 | 71 | for language in self.config.get('models'): 72 | if not language in self.config["supported_languages"]: 73 | self.config["supported_languages"].append(language) 74 | 75 | def get(self, variable): 76 | result = self.config.get(variable, None) 77 | if isinstance(result, list): 78 | return " ".join(sorted(result)).upper() 79 | return result 80 | 81 | def __repr__(self): 82 | current_config = "root: {0}\n" \ 83 | "\tsupported_languages: {1}\n" \ 84 | "\tconfig_file: {2}\n".format( 85 | self.config.get('root'), 86 | self.get('supported_languages'), 87 | self.config.get('config_file')) 88 | result = "Available config parameters:\n\t{0}\n\t{1}\n\nCurrent config:\n\t{2}".format( 89 | "- supported_languages", 90 | "- root", 91 | current_config.strip() 92 | ) 93 | return result 94 | 95 | if __name__ == "__main__": 96 | config = Config() 97 | if len(sys.argv) >= 2 and not "test" in " ".join(sys.argv): 98 | result = config.get(sys.argv[1]) 99 | if result is None: 100 | msg = "Config key {0} unknown." 101 | logger(msg) 102 | exit(-1) 103 | else: 104 | print(result) 105 | else: 106 | if len(sys.argv) >= 2 and "test" in " ".join(sys.argv): 107 | import doctest 108 | doctest.testmod(verbose=True) 109 | else: 110 | print(config) 111 | -------------------------------------------------------------------------------- /start_stanford.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # 4 | # File: start_stanford.sh 5 | # 6 | # This file is part of the Narralyzer package. 7 | # see: http://lab.kb.nl/tool/narralyzer 8 | # 9 | 10 | # 11 | # This program is free software: you can redistribute it and/or modify 12 | # it under the terms of the GNU General Public License as published by 13 | # the Free Software Foundation, either version 3 of the License, or 14 | # (at your option) any later version. 15 | # 16 | # This program is distributed in the hope that it will be useful, 17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | # GNU General Public License for more details. 20 | # 21 | # You should have received a copy of the GNU General Public License 22 | # along with this program. If not, see . 23 | # 24 | 25 | DE_CLASSIFIER="../models/edu/stanford/nlp/models/ner/german.dewac_175m_600.crf.ser.gz" 26 | DE_PORT=9990 27 | 28 | EN_CLASSIFIER="../models/edu/stanford/nlp/models/ner/english.all.3class.distsim.crf.ser.gz" 29 | EN_PORT=9991 30 | 31 | # FR_CLASSIFIER="../models/edu/stanford/nlp/models/srparser/frenchSR.beam.ser.gz" 32 | # FR_PORT=9992 33 | 34 | NL_CLASSIFIER="../models/dutch.crf.gz" 35 | NL_PORT=9993 36 | 37 | SP_CLASSIFIER="../models//edu/stanford/nlp/models/ner/spanish.ancora.distsim.s512.crf.ser.gz" 38 | SP_PORT=9994 39 | 40 | SUPPORTED_LANG=$(narralyzer/config.py supported_languages) 41 | 42 | # Little wrapper to datestamp outgoing messages. 43 | function inform_user() { 44 | msg="$1" 45 | timestamp=`date "+%Y-%m-%d %H:%M"` 46 | echo "$timestamp: Narralyzer start_stanford.sh $msg" 47 | } 48 | 49 | # Path to Stanford-core lib. 50 | # (Should be installed the by install.sh). 51 | PATH_TO_STANFORD_CORE="stanford/core/" 52 | inform_user "Changing directory to $PATH_TO_STANFORD_CORE" 53 | cd $PATH_TO_STANFORD_CORE 54 | 55 | # Prefix for logfile output name, to turn logging off 56 | # change LOG to "/dev/null". 57 | LOG="stanford_" 58 | 59 | # Use system wide default java. 60 | JAVA=`which java` 61 | # Except if your hostname "fe2" 62 | # So this private litte hack is to be ignored. 63 | if [ $HOSTNAME == "fe2" ]; then 64 | JAVA=/home/aloha/java/bin/java 65 | fi 66 | 67 | java_version=($JAVA -version) 68 | inform_user "Using java version: $java_version" 69 | 70 | # Use a whopping 4g per language. 71 | JAVA_MEM="-mx4g" 72 | 73 | # From the Stanford repo: 74 | OS=`uname` 75 | # Some machines (older OS X, BSD, Windows environments) don't support readlink -e 76 | if hash readlink 2>/dev/null; then 77 | scriptdir=`dirname $0` 78 | else 79 | scriptpath=$(readlink -e "$0") || scriptpath=$0 80 | scriptdir=$(dirname "$scriptpath") 81 | fi 82 | 83 | # Fire several stanford core server. 84 | for lang in $(echo $SUPPORTED_LANG | sort | xargs);do 85 | classifier=$(eval "echo \$${lang}_CLASSIFIER") 86 | port=$(eval "echo \$${lang}_PORT") 87 | is_running=$(ps x | grep "$classifier" | grep -v 'grep' | wc -l) 88 | if [ "$is_running" == "1" ]; then 89 | inform_user "Not starting $lang on port $port for it is allready running." 90 | else 91 | inform_user "Starting Stanford-core for language: $lang on port: $port" 92 | inform_user "$JAVA $JAVA_MEM -Djava.net.preferIPv4Stack=true -cp $scriptdir/\* edu.stanford.nlp.ie.NERServer -port $port -loadClassifier $classifier -outputFormat inlineXML" 93 | # TODO Logging would be nice. 94 | $JAVA $JAVA_MEM -Djava.net.preferIPv4Stack=true -cp $scriptdir/\* edu.stanford.nlp.ie.NERServer -port $port -loadClassifier $classifier -outputFormat inlineXML > "$LOG$lang.log" 2>&1 & 95 | fi 96 | done 97 | 98 | # Wait until the cores are booted and responsive, 99 | # if parameter 'waitforstartup' is given to start_stanford.sh. 100 | for lang in $(echo $SUPPORTED_LANG | sort | xargs);do 101 | port=$(eval "echo \$${lang}_PORT") 102 | if [ "$1" == "waitforstartup" ];then 103 | count=$(lsof -i tcp -n | grep $port | wc -l) 104 | while [ "$count" != "1" ]; do 105 | inform_user "Waiting for Stanford-core: $lang port: $port" 106 | sleep 1 107 | count=$(lsof -i tcp -n | grep $port | wc -l) 108 | done 109 | fi 110 | done 111 | 112 | inform_user "Moving to directory where we started" 113 | cd - 114 | -------------------------------------------------------------------------------- /install.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # 4 | # File: install.sh 5 | # 6 | # This file is part of the Narralyzer package. 7 | # see: http://lab.kb.nl/tool/narralyzer 8 | 9 | # If you run into troubles try this: 10 | # 11 | # sudo apt-get install -y build-essesntials libdb-dev virtualenv python2.7 libxml2-dev libxslt1-dev 12 | 13 | 14 | # Tika will take care of most input document conversion. 15 | TIKA="http://apache.cs.uu.nl/tika/tika-app-1.13.jar" 16 | 17 | # Where Stanford core lives. 18 | STANFORD_CORE="http://nlp.stanford.edu/software/stanford-corenlp-full-2015-12-09.zip" 19 | 20 | # Where the language models live. 21 | STANFORD_DE="http://nlp.stanford.edu/software/stanford-german-2016-01-19-models.jar" 22 | STANFORD_EN="http://nlp.stanford.edu/software/stanford-english-corenlp-2016-01-10-models.jar" 23 | STANFORD_NL="https://raw.githubusercontent.com/WillemJan/Narralyzer_Dutch_languagemodel/master/dutch.crf.gz" 24 | STANFORD_SP="http://nlp.stanford.edu/software/stanford-spanish-corenlp-2015-10-14-models.jar" 25 | 26 | # Little wrapper to datestamp outgoing messages. 27 | function inform_user() { 28 | msg="$1" 29 | timestamp=`date "+%Y-%m-%d %H:%M"` 30 | echo "$timestamp: Narralyzer install.sh $msg" 31 | } 32 | 33 | # Fetch the given URL, and save to disk 34 | # use the 'basename' for storing. 35 | function get_if_not_there () { 36 | URL=$1 37 | if [ ! -f `basename $URL` ]; then 38 | inform_user "Fetching $URL..." 39 | wget_output=$(wget -q "$URL") 40 | if [ $? -ne 0 ]; then 41 | inform_user "Error while fetching $URL, time to exit." 42 | exit -1; 43 | fi 44 | else 45 | inform_user "Not fetching $URL, `basename \"$URL\"` allready there." 46 | fi 47 | 48 | } 49 | 50 | # Fetch and unpack the Stanford core package. 51 | function fetch_stanford_core { 52 | get_if_not_there $STANFORD_CORE 53 | if [ -f `basename $STANFORD_CORE` ]; then 54 | unzip -q -n `basename "$STANFORD_CORE"` 55 | rm `basename "$STANFORD_CORE"` 56 | ln -s `find -name \*full\* -type d` core 57 | fi 58 | } 59 | 60 | # Fetch and unpack the language models. 61 | # (Might move them into this repo for ease later). 62 | function fetch_stanford_lang_models { 63 | get_if_not_there $STANFORD_DE 64 | get_if_not_there $STANFORD_EN 65 | get_if_not_there $STANFORD_FR 66 | get_if_not_there $STANFORD_NL 67 | get_if_not_there $STANFORD_SP 68 | find . -name \*.jar -exec unzip -q -o '{}' ';' 69 | # rm *.jar <- Save some diskspace here. 70 | } 71 | 72 | # Check if Python2.7 is installed on the os, 73 | # we might need that in the near futute. 74 | is_python2_7_avail() { 75 | is_avail=$(which python2.7 | wc -l) 76 | if [ "$is_avail" = "0" ]; then 77 | inform_user "Python 2.7 is not available, helas. sudo apt-get install python2.7?" 78 | exit -1 79 | fi 80 | inform_user "Python 2.7 is available." 81 | } 82 | 83 | # Check if we find (Python) virtualenv. 84 | is_virtualenv_avail() { 85 | is_avail=$(which virtualenv | wc -l) 86 | if [ "$is_avail" = "0" ]; then 87 | inform_user "Virtualenv is not available, helas. sudo-apt-get install virtualenv?" 88 | exit -1 89 | fi 90 | inform_user "Virtualenv is available." 91 | } 92 | 93 | # Now move to install dir for installation of core and models. 94 | if [ ! -d 'stanford' ]; then 95 | mkdir stanford && cd stanford 96 | else 97 | cd stanford 98 | fi 99 | 100 | # If stanford-corenlp-full*.zip is allready there, do nothing. 101 | full=$(find -name \*full\* | wc -l) 102 | if [ "$full" = "0" ];then 103 | # Fetch stanford-core from their site, 104 | # and install it. 105 | fetch_stanford_core 106 | else 107 | inform_user "Not fetching stanford-core, allready there." 108 | fi 109 | 110 | # If the models are allready there, do nothing. 111 | if [ ! -d 'models' ]; then 112 | # Else fetch and unpack models. 113 | mkdir models && cd models 114 | fetch_stanford_lang_models 115 | cd .. 116 | fi 117 | 118 | # Now leave the install dir. 119 | cd .. 120 | 121 | # Check if the virtual env exists, if not, create one and within 122 | # the virtual env install the required packages. 123 | if [ ! -d "env" ]; then 124 | is_python2_7_avail 125 | is_virtualenv_avail 126 | 127 | inform_user "Creating new virtualenv using python2.7 in ./env" 128 | virtualenv -p python2.7 ./env 129 | 130 | inform_user "Entering virtualenv, to leave: deactivate" 131 | source env/bin/activate 132 | 133 | inform_user "Upgrade pip and setuptools to latest version." 134 | pip install --upgrade pip setuptools 135 | 136 | if [ -f ~/requirements.txt ]; then 137 | req="~/requirements.txt" 138 | else 139 | req=`find ~ -name 'requirements.txt' | grep '/Narralyzer/'` 140 | fi 141 | 142 | if [ -f "$req" ]; then 143 | inform_user "Installing the following packages." 144 | cat "$req" 145 | pip install -r "$req" 146 | fi 147 | fi 148 | 149 | #if [ ! -d 'tika' ]; then 150 | # mkdir tika && cd tika 151 | # get_if_not_there $TIKA 152 | # unzip -q -n `basename "$TIKA"` 153 | # rm `basename "$TIKA"` 154 | #fi 155 | -------------------------------------------------------------------------------- /site/index.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2.7 2 | 3 | import os, sys 4 | 5 | sys.path.append(os.path.dirname(__file__)) 6 | VIRT_ENV = "env/bin/activate_this.py" 7 | execfile(VIRT_ENV, dict(__file__=VIRT_ENV)) 8 | 9 | import codecs 10 | import datetime 11 | import magic 12 | import os 13 | import string 14 | import sys 15 | import sys 16 | import xml.etree.ElementTree as etree 17 | 18 | from collections import Counter 19 | from dateutil.tz import tzlocal 20 | from flask import * 21 | from flask_mako import MakoTemplates 22 | from langdetect import detect 23 | from time import gmtime, strftime 24 | from werkzeug import secure_filename 25 | 26 | UPLOAD_FOLDER = 'upload' 27 | 28 | sys.path.append(os.path.dirname(__file__)) 29 | 30 | application = Flask(__name__) 31 | application.debug = True 32 | application.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER 33 | 34 | template_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates') 35 | application.template_folder = template_path 36 | 37 | mako = MakoTemplates(application) 38 | 39 | ALLOWED_EXTENSIONS = set(['pdf', 'xml', 'txt']) 40 | 41 | def tei_to_chapters(fname): 42 | """ Convert a TEI 2 xml into an array of chapters with text, 43 | and return the title. 44 | """ 45 | data = codecs.open(fname,'r', 'utf-8').read().replace(' ', '') 46 | 47 | utf8_parser = etree.XMLParser(encoding='utf-8') 48 | book = etree.fromstring(data.encode('utf-8'), parser=utf8_parser) 49 | 50 | chapters = [] 51 | chap_title = '' 52 | text = '' 53 | title = '' 54 | 55 | for item in book.iter(): 56 | if item.tag == 'author': 57 | author = item.text 58 | if item.tag == 'title' and not title and item.attrib.get('type') and item.attrib.get('type') == 'main': 59 | title = item.text 60 | 61 | if item.tag == 'head': 62 | if item.attrib and item.attrib.get('rend') and \ 63 | item.attrib.get('rend') == 'h2' and not item.text is None: 64 | chap_title = item.text 65 | 66 | if item.tag == 'head': 67 | if item.attrib and item.attrib.get('rend') and \ 68 | item.attrib.get('rend') == 'h3' and not item.text is None: 69 | chap_title += '\n' + item.text 70 | 71 | if item.tag == 'div': 72 | if item.attrib and item.attrib.get('type') and \ 73 | item.attrib.get('type') == 'chapter': 74 | chapters.append([chap_title, text]) 75 | text = '' 76 | chap_title = '' 77 | 78 | if 'rend' in item.attrib and not item.text is None: 79 | text += item.text + "\n" 80 | if item.tag == "p" and not item.text is None: 81 | text += item.text + "\n" 82 | 83 | chapters.append([chap_title, text]) 84 | return author, title, chapters 85 | 86 | def tei_check(path_to_file): 87 | """ Returns true if the file is an TEI-xml 88 | The following part of the header must be found in the first 10 lines of the file. 89 | ' where is one of" 20 | @echo " html to make standalone HTML files" 21 | @echo " dirhtml to make HTML files named index.html in directories" 22 | @echo " singlehtml to make a single large HTML file" 23 | @echo " pickle to make pickle files" 24 | @echo " json to make JSON files" 25 | @echo " htmlhelp to make HTML files and a HTML help project" 26 | @echo " qthelp to make HTML files and a qthelp project" 27 | @echo " applehelp to make an Apple Help Book" 28 | @echo " devhelp to make HTML files and a Devhelp project" 29 | @echo " epub to make an epub" 30 | @echo " epub3 to make an epub3" 31 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 32 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 33 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 34 | @echo " text to make text files" 35 | @echo " man to make manual pages" 36 | @echo " texinfo to make Texinfo files" 37 | @echo " info to make Texinfo files and run them through makeinfo" 38 | @echo " gettext to make PO message catalogs" 39 | @echo " changes to make an overview of all changed/added/deprecated items" 40 | @echo " xml to make Docutils-native XML files" 41 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 42 | @echo " linkcheck to check all external links for integrity" 43 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 44 | @echo " coverage to run coverage check of the documentation (if enabled)" 45 | @echo " dummy to check syntax errors of document sources" 46 | 47 | .PHONY: clean 48 | clean: 49 | rm -rf $(BUILDDIR)/* 50 | 51 | .PHONY: html 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | .PHONY: dirhtml 58 | dirhtml: 59 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 60 | @echo 61 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 62 | 63 | .PHONY: singlehtml 64 | singlehtml: 65 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 66 | @echo 67 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 68 | 69 | .PHONY: pickle 70 | pickle: 71 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 72 | @echo 73 | @echo "Build finished; now you can process the pickle files." 74 | 75 | .PHONY: json 76 | json: 77 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 78 | @echo 79 | @echo "Build finished; now you can process the JSON files." 80 | 81 | .PHONY: htmlhelp 82 | htmlhelp: 83 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 84 | @echo 85 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 86 | ".hhp project file in $(BUILDDIR)/htmlhelp." 87 | 88 | .PHONY: qthelp 89 | qthelp: 90 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 91 | @echo 92 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 93 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 94 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Narralyzer.qhcp" 95 | @echo "To view the help file:" 96 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Narralyzer.qhc" 97 | 98 | .PHONY: applehelp 99 | applehelp: 100 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 101 | @echo 102 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 103 | @echo "N.B. You won't be able to view it unless you put it in" \ 104 | "~/Library/Documentation/Help or install it in your application" \ 105 | "bundle." 106 | 107 | .PHONY: devhelp 108 | devhelp: 109 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 110 | @echo 111 | @echo "Build finished." 112 | @echo "To view the help file:" 113 | @echo "# mkdir -p $$HOME/.local/share/devhelp/Narralyzer" 114 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Narralyzer" 115 | @echo "# devhelp" 116 | 117 | .PHONY: epub 118 | epub: 119 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 120 | @echo 121 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 122 | 123 | .PHONY: epub3 124 | epub3: 125 | $(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3 126 | @echo 127 | @echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3." 128 | 129 | .PHONY: latex 130 | latex: 131 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 132 | @echo 133 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 134 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 135 | "(use \`make latexpdf' here to do that automatically)." 136 | 137 | .PHONY: latexpdf 138 | latexpdf: 139 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 140 | @echo "Running LaTeX files through pdflatex..." 141 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 142 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 143 | 144 | .PHONY: latexpdfja 145 | latexpdfja: 146 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 147 | @echo "Running LaTeX files through platex and dvipdfmx..." 148 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 149 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 150 | 151 | .PHONY: text 152 | text: 153 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 154 | @echo 155 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 156 | 157 | .PHONY: man 158 | man: 159 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 160 | @echo 161 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 162 | 163 | .PHONY: texinfo 164 | texinfo: 165 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 166 | @echo 167 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 168 | @echo "Run \`make' in that directory to run these through makeinfo" \ 169 | "(use \`make info' here to do that automatically)." 170 | 171 | .PHONY: info 172 | info: 173 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 174 | @echo "Running Texinfo files through makeinfo..." 175 | make -C $(BUILDDIR)/texinfo info 176 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 177 | 178 | .PHONY: gettext 179 | gettext: 180 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 181 | @echo 182 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 183 | 184 | .PHONY: changes 185 | changes: 186 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 187 | @echo 188 | @echo "The overview file is in $(BUILDDIR)/changes." 189 | 190 | .PHONY: linkcheck 191 | linkcheck: 192 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 193 | @echo 194 | @echo "Link check complete; look for any errors in the above output " \ 195 | "or in $(BUILDDIR)/linkcheck/output.txt." 196 | 197 | .PHONY: doctest 198 | doctest: 199 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 200 | @echo "Testing of doctests in the sources finished, look at the " \ 201 | "results in $(BUILDDIR)/doctest/output.txt." 202 | 203 | .PHONY: coverage 204 | coverage: 205 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 206 | @echo "Testing of coverage in the sources finished, look at the " \ 207 | "results in $(BUILDDIR)/coverage/python.txt." 208 | 209 | .PHONY: xml 210 | xml: 211 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 212 | @echo 213 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 214 | 215 | .PHONY: pseudoxml 216 | pseudoxml: 217 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 218 | @echo 219 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 220 | 221 | .PHONY: dummy 222 | dummy: 223 | $(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy 224 | @echo 225 | @echo "Build finished. Dummy builder generates no files." 226 | -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Narralyzer documentation build configuration file, created by 4 | # sphinx-quickstart on Sun Jul 31 13:24:34 2016. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | # If extensions (or modules to document with autodoc) are in another directory, 16 | # add these directories to sys.path here. If the directory is relative to the 17 | # documentation root, use os.path.abspath to make it absolute, like shown here. 18 | # 19 | import os 20 | import sys 21 | sys.path.insert(0, os.path.abspath('../')) 22 | 23 | # -- General configuration ------------------------------------------------ 24 | 25 | # If your documentation needs a minimal Sphinx version, state it here. 26 | # 27 | # needs_sphinx = '1.0' 28 | 29 | # Add any Sphinx extension module names here, as strings. They can be 30 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 31 | # ones. 32 | extensions = [ 33 | 'sphinx.ext.autodoc', 34 | 'sphinx.ext.doctest', 35 | 'sphinx.ext.intersphinx', 36 | 'sphinx.ext.todo', 37 | 'sphinx.ext.coverage', 38 | 'sphinx.ext.mathjax', 39 | 'sphinx.ext.ifconfig', 40 | 'sphinx.ext.viewcode', 41 | 'sphinx.ext.githubpages', 42 | ] 43 | 44 | # Add any paths that contain templates here, relative to this directory. 45 | templates_path = ['_templates'] 46 | 47 | # The suffix(es) of source filenames. 48 | # You can specify multiple suffix as a list of string: 49 | # 50 | # source_suffix = ['.rst', '.md'] 51 | source_suffix = '.rst' 52 | 53 | # The encoding of source files. 54 | # 55 | # source_encoding = 'utf-8-sig' 56 | 57 | # The master toctree document. 58 | master_doc = 'narralyzer' 59 | 60 | # General information about the project. 61 | project = u'Narralyzer' 62 | copyright = u'2016, Willem Jan Faber' 63 | author = u'Willem Jan Faber' 64 | 65 | # The version info for the project you're documenting, acts as replacement for 66 | # |version| and |release|, also used in various other places throughout the 67 | # built documents. 68 | # 69 | # The short X.Y version. 70 | version = u'0.1' 71 | # The full version, including alpha/beta/rc tags. 72 | release = u'0.1' 73 | 74 | # The language for content autogenerated by Sphinx. Refer to documentation 75 | # for a list of supported languages. 76 | # 77 | # This is also used if you do content translation via gettext catalogs. 78 | # Usually you set "language" from the command line for these cases. 79 | language = None 80 | 81 | # There are two options for replacing |today|: either, you set today to some 82 | # non-false value, then it is used: 83 | # 84 | # today = '' 85 | # 86 | # Else, today_fmt is used as the format for a strftime call. 87 | # 88 | # today_fmt = '%B %d, %Y' 89 | 90 | # List of patterns, relative to source directory, that match files and 91 | # directories to ignore when looking for source files. 92 | # This patterns also effect to html_static_path and html_extra_path 93 | exclude_patterns = [] 94 | 95 | # The reST default role (used for this markup: `text`) to use for all 96 | # documents. 97 | # 98 | # default_role = None 99 | 100 | # If true, '()' will be appended to :func: etc. cross-reference text. 101 | # 102 | # add_function_parentheses = True 103 | 104 | # If true, the current module name will be prepended to all description 105 | # unit titles (such as .. function::). 106 | # 107 | # add_module_names = True 108 | 109 | # If true, sectionauthor and moduleauthor directives will be shown in the 110 | # output. They are ignored by default. 111 | # 112 | # show_authors = False 113 | 114 | # The name of the Pygments (syntax highlighting) style to use. 115 | pygments_style = 'sphinx' 116 | 117 | # A list of ignored prefixes for module index sorting. 118 | # modindex_common_prefix = [] 119 | 120 | # If true, keep warnings as "system message" paragraphs in the built documents. 121 | # keep_warnings = False 122 | 123 | # If true, `todo` and `todoList` produce output, else they produce nothing. 124 | todo_include_todos = True 125 | 126 | 127 | # -- Options for HTML output ---------------------------------------------- 128 | 129 | # The theme to use for HTML and HTML Help pages. See the documentation for 130 | # a list of builtin themes. 131 | # 132 | html_theme = 'classic' 133 | 134 | # Theme options are theme-specific and customize the look and feel of a theme 135 | # further. For a list of options available for each theme, see the 136 | # documentation. 137 | # 138 | # html_theme_options = {} 139 | 140 | # Add any paths that contain custom themes here, relative to this directory. 141 | # html_theme_path = [] 142 | 143 | # The name for this set of Sphinx documents. 144 | # " v documentation" by default. 145 | # 146 | html_title = u'Narralyzer v0.1' 147 | 148 | # A shorter title for the navigation bar. Default is the same as html_title. 149 | # 150 | # html_short_title = None 151 | 152 | # The name of an image file (relative to this directory) to place at the top 153 | # of the sidebar. 154 | # 155 | # html_logo = None 156 | 157 | # The name of an image file (relative to this directory) to use as a favicon of 158 | # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 159 | # pixels large. 160 | # 161 | # html_favicon = None 162 | 163 | # Add any paths that contain custom static files (such as style sheets) here, 164 | # relative to this directory. They are copied after the builtin static files, 165 | # so a file named "default.css" will overwrite the builtin "default.css". 166 | html_static_path = ['_static'] 167 | 168 | # Add any extra paths that contain custom files (such as robots.txt or 169 | # .htaccess) here, relative to this directory. These files are copied 170 | # directly to the root of the documentation. 171 | # 172 | # html_extra_path = [] 173 | 174 | # If not None, a 'Last updated on:' timestamp is inserted at every page 175 | # bottom, using the given strftime format. 176 | # The empty string is equivalent to '%b %d, %Y'. 177 | # 178 | # html_last_updated_fmt = None 179 | 180 | # If true, SmartyPants will be used to convert quotes and dashes to 181 | # typographically correct entities. 182 | # 183 | # html_use_smartypants = True 184 | 185 | # Custom sidebar templates, maps document names to template names. 186 | # 187 | # html_sidebars = {} 188 | 189 | # Additional templates that should be rendered to pages, maps page names to 190 | # template names. 191 | # 192 | # html_additional_pages = {} 193 | 194 | # If false, no module index is generated. 195 | # 196 | # html_domain_indices = True 197 | 198 | # If false, no index is generated. 199 | # 200 | # html_use_index = True 201 | 202 | # If true, the index is split into individual pages for each letter. 203 | # 204 | # html_split_index = False 205 | 206 | # If true, links to the reST sources are added to the pages. 207 | # 208 | # html_show_sourcelink = True 209 | 210 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 211 | # 212 | # html_show_sphinx = True 213 | 214 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 215 | # 216 | # html_show_copyright = True 217 | 218 | # If true, an OpenSearch description file will be output, and all pages will 219 | # contain a tag referring to it. The value of this option must be the 220 | # base URL from which the finished HTML is served. 221 | # 222 | # html_use_opensearch = '' 223 | 224 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 225 | # html_file_suffix = None 226 | 227 | # Language to be used for generating the HTML full-text search index. 228 | # Sphinx supports the following languages: 229 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' 230 | # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh' 231 | # 232 | # html_search_language = 'en' 233 | 234 | # A dictionary with options for the search language support, empty by default. 235 | # 'ja' uses this config value. 236 | # 'zh' user can custom change `jieba` dictionary path. 237 | # 238 | # html_search_options = {'type': 'default'} 239 | 240 | # The name of a javascript file (relative to the configuration directory) that 241 | # implements a search results scorer. If empty, the default will be used. 242 | # 243 | # html_search_scorer = 'scorer.js' 244 | 245 | # Output file base name for HTML help builder. 246 | htmlhelp_basename = 'Narralyzerdoc' 247 | 248 | # -- Options for LaTeX output --------------------------------------------- 249 | 250 | latex_elements = { 251 | # The paper size ('letterpaper' or 'a4paper'). 252 | # 253 | # 'papersize': 'letterpaper', 254 | 255 | # The font size ('10pt', '11pt' or '12pt'). 256 | # 257 | # 'pointsize': '10pt', 258 | 259 | # Additional stuff for the LaTeX preamble. 260 | # 261 | # 'preamble': '', 262 | 263 | # Latex figure (float) alignment 264 | # 265 | # 'figure_align': 'htbp', 266 | } 267 | 268 | # Grouping the document tree into LaTeX files. List of tuples 269 | # (source start file, target name, title, 270 | # author, documentclass [howto, manual, or own class]). 271 | latex_documents = [ 272 | (master_doc, 'Narralyzer.tex', u'Narralyzer Documentation', 273 | u'Willem Jan Faber', 'manual'), 274 | ] 275 | 276 | # The name of an image file (relative to this directory) to place at the top of 277 | # the title page. 278 | # 279 | # latex_logo = None 280 | 281 | # For "manual" documents, if this is true, then toplevel headings are parts, 282 | # not chapters. 283 | # 284 | # latex_use_parts = False 285 | 286 | # If true, show page references after internal links. 287 | # 288 | # latex_show_pagerefs = False 289 | 290 | # If true, show URL addresses after external links. 291 | # 292 | # latex_show_urls = False 293 | 294 | # Documents to append as an appendix to all manuals. 295 | # 296 | # latex_appendices = [] 297 | 298 | # It false, will not define \strong, \code, itleref, \crossref ... but only 299 | # \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added 300 | # packages. 301 | # 302 | # latex_keep_old_macro_names = True 303 | 304 | # If false, no module index is generated. 305 | # 306 | # latex_domain_indices = True 307 | 308 | 309 | # -- Options for manual page output --------------------------------------- 310 | 311 | # One entry per manual page. List of tuples 312 | # (source start file, name, description, authors, manual section). 313 | man_pages = [ 314 | (master_doc, 'narralyzer', u'Narralyzer Documentation', 315 | [author], 1) 316 | ] 317 | 318 | # If true, show URL addresses after external links. 319 | # 320 | # man_show_urls = False 321 | 322 | 323 | # -- Options for Texinfo output ------------------------------------------- 324 | 325 | # Grouping the document tree into Texinfo files. List of tuples 326 | # (source start file, target name, title, author, 327 | # dir menu entry, description, category) 328 | texinfo_documents = [ 329 | (master_doc, 'Narralyzer', u'Narralyzer Documentation', 330 | author, 'Narralyzer', 'One line description of project.', 331 | 'Miscellaneous'), 332 | ] 333 | 334 | # Documents to append as an appendix to all manuals. 335 | # 336 | # texinfo_appendices = [] 337 | 338 | # If false, no module index is generated. 339 | # 340 | # texinfo_domain_indices = True 341 | 342 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 343 | # 344 | # texinfo_show_urls = 'footnote' 345 | 346 | # If true, do not generate a @detailmenu in the "Top" node's menu. 347 | # 348 | # texinfo_no_detailmenu = False 349 | 350 | 351 | # -- Options for Epub output ---------------------------------------------- 352 | 353 | # Bibliographic Dublin Core info. 354 | epub_title = project 355 | epub_author = author 356 | epub_publisher = author 357 | epub_copyright = copyright 358 | 359 | # The basename for the epub file. It defaults to the project name. 360 | # epub_basename = project 361 | 362 | # The HTML theme for the epub output. Since the default themes are not 363 | # optimized for small screen space, using the same theme for HTML and epub 364 | # output is usually not wise. This defaults to 'epub', a theme designed to save 365 | # visual space. 366 | # 367 | # epub_theme = 'epub' 368 | 369 | # The language of the text. It defaults to the language option 370 | # or 'en' if the language is not set. 371 | # 372 | # epub_language = '' 373 | 374 | # The scheme of the identifier. Typical schemes are ISBN or URL. 375 | # epub_scheme = '' 376 | 377 | # The unique identifier of the text. This can be a ISBN number 378 | # or the project homepage. 379 | # 380 | # epub_identifier = '' 381 | 382 | # A unique identification for the text. 383 | # 384 | # epub_uid = '' 385 | 386 | # A tuple containing the cover image and cover page html template filenames. 387 | # 388 | # epub_cover = () 389 | 390 | # A sequence of (type, uri, title) tuples for the guide element of content.opf. 391 | # 392 | # epub_guide = () 393 | 394 | # HTML files that should be inserted before the pages created by sphinx. 395 | # The format is a list of tuples containing the path and title. 396 | # 397 | # epub_pre_files = [] 398 | 399 | # HTML files that should be inserted after the pages created by sphinx. 400 | # The format is a list of tuples containing the path and title. 401 | # 402 | # epub_post_files = [] 403 | 404 | # A list of files that should not be packed into the epub file. 405 | epub_exclude_files = ['search.html'] 406 | 407 | # The depth of the table of contents in toc.ncx. 408 | # 409 | # epub_tocdepth = 3 410 | 411 | # Allow duplicate toc entries. 412 | # 413 | # epub_tocdup = True 414 | 415 | # Choose between 'default' and 'includehidden'. 416 | # 417 | # epub_tocscope = 'default' 418 | 419 | # Fix unsupported image types using the Pillow. 420 | # 421 | # epub_fix_images = False 422 | 423 | # Scale large images. 424 | # 425 | # epub_max_image_width = 0 426 | 427 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 428 | # 429 | # epub_show_urls = 'inline' 430 | 431 | # If false, no index is generated. 432 | # 433 | # epub_use_index = True 434 | 435 | 436 | # Example configuration for intersphinx: refer to the Python standard library. 437 | intersphinx_mapping = {'https://docs.python.org/': None} 438 | -------------------------------------------------------------------------------- /narralyzer/stanford_ner_wrapper.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2.7 2 | # -*- coding: utf-8 -*- 3 | """ 4 | narralyzer.stanford_ner_wrapper 5 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 6 | Implements tiny wrapper for Stanford CoreNLP NER. 7 | Also invokes the awsome powers of probablepeople! 8 | 9 | Hint's on setting up a high-preformance NER-farm. 10 | http://stanfordnlp.github.io/CoreNLP/corenlp-server.html#dedicated-server 11 | 12 | Docs on probablepeople are found here: 13 | http://probablepeople.readthedocs.io/ 14 | 15 | :copyright: (c) 2016 Koninklijke Bibliotheek, by Willem-Jan Faber. 16 | :license: GPLv3, see licence.txt for more details. 17 | """ 18 | 19 | import sys 20 | reload(sys) 21 | sys.setdefaultencoding('utf-8') 22 | 23 | import logging 24 | import lxml.html 25 | import probablepeople 26 | import socket 27 | import sys 28 | 29 | from contextlib import contextmanager 30 | from django.utils.encoding import smart_text 31 | 32 | log = logging.basicConfig(stream=sys.stdout, level=logging.INFO) 33 | 34 | 35 | @contextmanager 36 | def _tcpip4_socket(host, port): 37 | """Open a TCP/IP4 socket to designated host/port. 38 | This code originates from 'pip install ner', 39 | but the module itself was broken, so took usefull code 40 | and improved on it. 41 | """ 42 | 43 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 44 | sock.settimeout(50) 45 | 46 | try: 47 | sock.connect((host, port)) 48 | yield sock 49 | finally: 50 | try: 51 | sock.shutdown(socket.SHUT_RDWR) 52 | except socket.error: 53 | log.error("Socket error %s %s" % (host, str(port))) 54 | pass 55 | except OSError: 56 | log.error("OSEerror %s %s" % (host, str(port))) 57 | pass 58 | finally: 59 | sock.close() 60 | 61 | 62 | def stanford_ner_wrapper(text, port=False, use_pp=True, host='localhost'): 63 | """ 64 | Standalone function to fetch results from Stanford ner, and appy probablepeople. 65 | 66 | 67 | >>> res = stanford_ner_wrapper("Willem-Alexander (Dutch: [ˈʋɪləm aːlɛkˈsɑndər]; Willem-Alexander Claus George Ferdinand; born 27 April 1967) is the King of the Netherlands.", 9991, True) 68 | >>> from pprint import pprint;pprint(res) 69 | {'ners': [{'string': 'Willem-Alexander', 'tag': 'person'}, 70 | {'string': 'Willem-Alexander Claus George Ferdinand', 71 | 'tag': 'person'}, 72 | {'string': 'Netherlands', 'tag': 'location'}], 73 | 'pp': [{'parse': [('Willem-Alexander', 'GivenName')], 74 | 'tag': {'GivenName': 'Willem-Alexander'}}, 75 | {'parse': [('Willem-Alexander', 'CorporationName'), 76 | ('Claus', 'CorporationName'), 77 | ('George', 'CorporationName'), 78 | ('Ferdinand', 'CorporationName')], 79 | 'tag': {'CorporationName': 'Willem-Alexander Claus George Ferdinand'}}], 80 | 'raw_ners': [{'string': 'Willem-Alexander', 'tag': 'person'}, 81 | {'string': 'Willem-Alexander Claus George Ferdinand', 82 | 'tag': 'person'}, 83 | {'string': 'Netherlands', 'tag': 'location'}], 84 | 'raw_response': u'Willem-Alexander (Dutch: [\u02c8\u028b\u026al\u0259m a\u02d0l\u025bk\u02c8s\u0251nd\u0259r]; Willem-Alexander Claus George Ferdinand; born 27 April 1967) is the King of the Netherlands.'} 85 | >>> res = stanford_ner_wrapper("Prof. Albert Einstein vertoeft op het oogenblik te Londen, en gisteravond was hij in Savoy Hotel eeregast aan een diner, gegeven door de Ort and Oze Societies. De voorzitter van de Engelsche sectie dier Vereeniging is Lord • Rothschild ; de voorzitter van de Duitsche sectie is prof. Einstein. Lord Rothschild presideerde het diner; aan zijn rechterhand zat de beroemdste geleerde van onzen tyd, aan zijn linkerhand de beroemdste dichter, Bernard Shaw. Rechts van Einstein zat Wells. Het was een gastmaal voor het intellect en z|jn dames. Ik wil er geen verslag van geven, maar my bepalen tot enkele aanteekeningen.", 9993, True) 86 | >>> from pprint import pprint;pprint(res) 87 | {'ners': [{'string': 'Albert Einstein', 'tag': 'per'}, 88 | {'string': 'Londen', 'tag': 'loc'}, 89 | {'string': 'Savoy Hotel', 'tag': 'loc'}, 90 | {'string': 'Ort and Oze Societies', 'tag': 'misc'}, 91 | {'string': 'Engelsche', 'tag': 'misc'}, 92 | {'string': 'Vereeniging', 'tag': 'loc'}, 93 | {'string': u'Lord \u2022 Rothschild', 'tag': 'per'}, 94 | {'string': 'Duitsche', 'tag': 'misc'}, 95 | {'string': 'Einstein', 'tag': 'loc'}, 96 | {'string': 'Lord Rothschild', 'tag': 'per'}, 97 | {'string': 'Bernard Shaw', 'tag': 'per'}, 98 | {'string': 'Einstein', 'tag': 'loc'}, 99 | {'string': 'Wells', 'tag': 'per'}], 100 | 'pp': [{'parse': [('Albert', 'GivenName'), ('Einstein', 'Surname')], 101 | 'tag': {'GivenName': 'Albert', 'Surname': 'Einstein'}}, 102 | {'parse': [(u'Lord', 'GivenName'), (u'Rothschild', 'Surname')], 103 | 'tag': {'GivenName': u'Lord', 'Surname': u'Rothschild'}}, 104 | {'parse': [('Lord', 'GivenName'), ('Rothschild', 'Surname')], 105 | 'tag': {'GivenName': 'Lord', 'Surname': 'Rothschild'}}, 106 | {'parse': [('Bernard', 'GivenName'), ('Shaw', 'Surname')], 107 | 'tag': {'GivenName': 'Bernard', 'Surname': 'Shaw'}}, 108 | {'parse': [('Wells', 'Surname')], 'tag': {'Surname': 'Wells'}}], 109 | 'raw_ners': [{'string': 'Albert', 'tag': 'b-per'}, 110 | {'string': 'Einstein', 'tag': 'i-per'}, 111 | {'string': 'Londen', 'tag': 'b-loc'}, 112 | {'string': 'Savoy', 'tag': 'b-loc'}, 113 | {'string': 'Hotel', 'tag': 'i-loc'}, 114 | {'string': 'Ort', 'tag': 'b-misc'}, 115 | {'string': 'and Oze Societies', 'tag': 'i-misc'}, 116 | {'string': 'Engelsche', 'tag': 'b-misc'}, 117 | {'string': 'Vereeniging', 'tag': 'b-loc'}, 118 | {'string': 'Lord', 'tag': 'b-per'}, 119 | {'string': u'\u2022 Rothschild', 'tag': 'i-per'}, 120 | {'string': 'Duitsche', 'tag': 'b-misc'}, 121 | {'string': 'Einstein', 'tag': 'b-loc'}, 122 | {'string': 'Lord', 'tag': 'b-per'}, 123 | {'string': 'Rothschild', 'tag': 'i-per'}, 124 | {'string': 'Bernard', 'tag': 'b-per'}, 125 | {'string': 'Shaw', 'tag': 'i-per'}, 126 | {'string': 'Einstein', 'tag': 'b-loc'}, 127 | {'string': 'Wells', 'tag': 'b-per'}], 128 | 'raw_response': u'Prof. Albert Einstein vertoeft op het oogenblik te Londen, en gisteravond was hij in Savoy Hotel eeregast aan een diner, gegeven door de Ort and Oze Societies. De voorzitter van de Engelsche sectie dier Vereeniging is Lord \u2022 Rothschild ; de voorzitter van de Duitsche sectie is prof. Einstein. Lord Rothschild presideerde het diner; aan zijn rechterhand zat de beroemdste geleerde van onzen tyd, aan zijn linkerhand de beroemdste dichter, Bernard Shaw. Rechts van Einstein zat Wells. Het was een gastmaal voor het intellect en z|jn dames. Ik wil er geen verslag van geven, maar my bepalen tot enkele aanteekeningen.'} 129 | >>> res = stanford_ner_wrapper("Prof. Albert Einstein vertoeft op het oogenblik te Londen, en gisteravond was hij in Savoy Hotel eeregast aan een diner, gegeven door de Ort and Oze Societies. De voorzitter van de Engelsche sectie dier Vereeniging is Lord • Rothschild ; de voorzitter van de Duitsche sectie is prof. Einstein. Lord Rothschild presideerde het diner; aan zijn rechterhand zat de beroemdste geleerde van onzen tyd, aan zijn linkerhand de beroemdste dichter, Bernard Shaw. Rechts van Einstein zat Wells. Het was een gastmaal voor het intellect en z|jn dames. Ik wil er geen verslag van geven, maar my bepalen tot enkele aanteekeningen.", 9993, True) 130 | >>> from pprint import pprint;pprint(res) 131 | {'ners': [{'string': 'Albert Einstein', 'tag': 'per'}, 132 | {'string': 'Londen', 'tag': 'loc'}, 133 | {'string': 'Savoy Hotel', 'tag': 'loc'}, 134 | {'string': 'Ort and Oze Societies', 'tag': 'misc'}, 135 | {'string': 'Engelsche', 'tag': 'misc'}, 136 | {'string': 'Vereeniging', 'tag': 'loc'}, 137 | {'string': u'Lord \u2022 Rothschild', 'tag': 'per'}, 138 | {'string': 'Duitsche', 'tag': 'misc'}, 139 | {'string': 'Einstein', 'tag': 'loc'}, 140 | {'string': 'Lord Rothschild', 'tag': 'per'}, 141 | {'string': 'Bernard Shaw', 'tag': 'per'}, 142 | {'string': 'Einstein', 'tag': 'loc'}, 143 | {'string': 'Wells', 'tag': 'per'}], 144 | 'pp': [{'parse': [('Albert', 'GivenName'), ('Einstein', 'Surname')], 145 | 'tag': {'GivenName': 'Albert', 'Surname': 'Einstein'}}, 146 | {'parse': [(u'Lord', 'GivenName'), (u'Rothschild', 'Surname')], 147 | 'tag': {'GivenName': u'Lord', 'Surname': u'Rothschild'}}, 148 | {'parse': [('Lord', 'GivenName'), ('Rothschild', 'Surname')], 149 | 'tag': {'GivenName': 'Lord', 'Surname': 'Rothschild'}}, 150 | {'parse': [('Bernard', 'GivenName'), ('Shaw', 'Surname')], 151 | 'tag': {'GivenName': 'Bernard', 'Surname': 'Shaw'}}, 152 | {'parse': [('Wells', 'Surname')], 'tag': {'Surname': 'Wells'}}], 153 | 'raw_ners': [{'string': 'Albert', 'tag': 'b-per'}, 154 | {'string': 'Einstein', 'tag': 'i-per'}, 155 | {'string': 'Londen', 'tag': 'b-loc'}, 156 | {'string': 'Savoy', 'tag': 'b-loc'}, 157 | {'string': 'Hotel', 'tag': 'i-loc'}, 158 | {'string': 'Ort', 'tag': 'b-misc'}, 159 | {'string': 'and Oze Societies', 'tag': 'i-misc'}, 160 | {'string': 'Engelsche', 'tag': 'b-misc'}, 161 | {'string': 'Vereeniging', 'tag': 'b-loc'}, 162 | {'string': 'Lord', 'tag': 'b-per'}, 163 | {'string': u'\u2022 Rothschild', 'tag': 'i-per'}, 164 | {'string': 'Duitsche', 'tag': 'b-misc'}, 165 | {'string': 'Einstein', 'tag': 'b-loc'}, 166 | {'string': 'Lord', 'tag': 'b-per'}, 167 | {'string': 'Rothschild', 'tag': 'i-per'}, 168 | {'string': 'Bernard', 'tag': 'b-per'}, 169 | {'string': 'Shaw', 'tag': 'i-per'}, 170 | {'string': 'Einstein', 'tag': 'b-loc'}, 171 | {'string': 'Wells', 'tag': 'b-per'}], 172 | 'raw_response': u'Prof. Albert Einstein vertoeft op het oogenblik te Londen, en gisteravond was hij in Savoy Hotel eeregast aan een diner, gegeven door de Ort and Oze Societies. De voorzitter van de Engelsche sectie dier Vereeniging is Lord \u2022 Rothschild ; de voorzitter van de Duitsche sectie is prof. Einstein. Lord Rothschild presideerde het diner; aan zijn rechterhand zat de beroemdste geleerde van onzen tyd, aan zijn linkerhand de beroemdste dichter, Bernard Shaw. Rechts van Einstein zat Wells. Het was een gastmaal voor het intellect en z|jn dames. Ik wil er geen verslag van geven, maar my bepalen tot enkele aanteekeningen.'} 173 | """ 174 | for s in ("\f", "\n", "\r", "\t", "\v"): # strip whitespaces 175 | text = text.replace(s, '') 176 | text += "\n" # ensure end-of-line 177 | 178 | with _tcpip4_socket(host, port) as s: 179 | if not isinstance(text, bytes): 180 | text = text.encode('utf-8') 181 | s.sendall(text) 182 | 183 | tagged_text = s.recv(10*len(text)) 184 | 185 | result = tagged_text.decode("utf-8") 186 | 187 | ner = {"raw_response": result, 188 | "raw_ners": [], 189 | "ners": []} 190 | 191 | result = "%s" % result 192 | res = lxml.html.fromstring(result) 193 | 194 | for item in res.iter(): 195 | if item.tag == 'xml': 196 | continue 197 | ner["raw_ners"].append({"string": item.text, 198 | "tag": item.tag}) 199 | 200 | counter_ners = 0 201 | ners = [] 202 | for item in ner["raw_ners"]: 203 | if item.get("tag")[0] == 'i': 204 | if counter_ners and len(ners) >= counter_ners - 1: 205 | ners[counter_ners - 1]["string"] += ' ' + item.get("string") 206 | else: 207 | tag = item.get("tag") 208 | if "-" in tag: 209 | tag = tag.split('-')[1] 210 | ners.append({"string": item.get("string"), 211 | "tag": tag}) 212 | counter_ners += 1 213 | ner["ners"] = ners 214 | 215 | # Apply probablepeople / (parse and tag) 216 | if use_pp: 217 | pp = [] 218 | for item in ners: 219 | if "per" in item["tag"].lower(): 220 | result = {} 221 | try: 222 | result["parse"] = probablepeople.parse(item["string"]) 223 | for key, value in probablepeople.tag(item["string"])[0].iteritems(): 224 | if "tag" not in result: 225 | result["tag"] = {} 226 | if key not in result["tag"]: 227 | result["tag"][key] = value 228 | else: 229 | result["tag"][key] += " " + value 230 | except: 231 | if "error" not in result: 232 | result["error"] = 0 233 | else: 234 | result["error"] += 1 235 | pp.append(result) 236 | ner["pp"] = pp 237 | return ner 238 | 239 | 240 | if __name__ == '__main__': 241 | if len(sys.argv) >= 2 and 'test' in " ".join(sys.argv): 242 | import doctest 243 | doctest.testmod(verbose=True) 244 | 245 | if len(sys.argv) >= 2 and 'profile' in " ".join(sys.argv): 246 | from gutenberg.acquire import load_etext 247 | from gutenberg.cleanup import strip_headers 248 | from pycallgraph import PyCallGraph 249 | from pycallgraph.output import GraphvizOutput 250 | 251 | text = smart_text(strip_headers(load_etext(17685)).strip()) 252 | with PyCallGraph(output=GraphvizOutput()): 253 | stanford_ner_wrapper(text, 9992, True) 254 | -------------------------------------------------------------------------------- /narralyzer/lang_lib.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2.7 2 | # -*- coding: utf-8 -*- 3 | """ 4 | narralyzer.lang_lib 5 | ~~~~~~~~~~~~~~~~~~~ 6 | Implements sentence level analyzer for natural language 7 | 8 | :copyright: (c) 2016 Koninklijke Bibliotheek, by Willem Jan Faber. 9 | :license: GPLv3, see licence.txt for more details. 10 | """ 11 | 12 | import sys 13 | reload(sys) 14 | sys.setdefaultencoding('utf-8') 15 | 16 | import importlib 17 | import string 18 | 19 | from langdetect import detect 20 | from numpy import mean 21 | from Queue import Queue 22 | from segtok.segmenter import split_multi 23 | from stanford_ner_wrapper import stanford_ner_wrapper 24 | from threading import Thread 25 | 26 | try: 27 | from narralyzer import config 28 | except: 29 | import config 30 | 31 | try: 32 | from narralyzer import utils 33 | except: 34 | import utils 35 | 36 | # TODO Move this to a seperate config module. 37 | STANFORD_NER_SERVERS = {"de": 9990, 38 | "en": 9991, 39 | "fr": 9992, 40 | "nl": 9993, 41 | "sp": 9994} 42 | 43 | 44 | class Language: 45 | ''' 46 | Intro 47 | ----- 48 | The ``lang_lib.Language`` class is part of the Narralyzer project. 49 | This class takes care of chopping up strings/documents into sentences, 50 | and applies the following: 51 | 52 | - Part-of-speech tagging (Using CLiPS-pattern) 53 | - Sentencte analysis (Using CLiPS-pattern) 54 | - Named entity extraction (Using Stanford CoreNLP) 55 | 56 | About 57 | ----- 58 | The module combines the power of several awesome Python/Java projects, 59 | see overview of most relevant projects below. 60 | 61 | Using ``lang_lib.Language`` 62 | --------------------------- 63 | >>> lang = Language(("Willem-Jan Faber just invoked lang_lib.Language, while wishing he was in West Virginia.")) 64 | Using detected language 'en' to parse input text. 65 | >>> lang.parse() 66 | >>> from pprint import pprint; pprint(lang.result) 67 | {'lang': u'en', 68 | 'sentences': {0: {'count': 0, 69 | 'pos': [{'string': u'Willem-Jan', 'tag': u'NNP'}, 70 | {'string': u'Faber', 'tag': u'NNP'}, 71 | {'string': u'just', 'tag': u'RB'}, 72 | {'string': u'invoked', 'tag': u'VBN'}, 73 | {'string': u'lang_lib.Language', 'tag': u'NN'}, 74 | {'string': u',', 'tag': u','}, 75 | {'string': u'while', 'tag': u'IN'}, 76 | {'string': u'wishing', 'tag': u'VBG'}, 77 | {'string': u'he', 'tag': u'PRP'}, 78 | {'string': u'was', 'tag': u'VBD'}, 79 | {'string': u'in', 'tag': u'IN'}, 80 | {'string': u'West', 'tag': u'NNP'}, 81 | {'string': u'Virginia', 'tag': u'NNP'}, 82 | {'string': u'.', 'tag': u'.'}], 83 | 'sentiment': (0.0, 0.0), 84 | 'stanford': {'ners': [{'string': 'Willem-Jan Faber', 85 | 'tag': 'person'}, 86 | {'string': 'West Virginia', 87 | 'tag': 'location'}], 88 | 'pp': [{'parse': [('Willem-Jan', 89 | 'GivenName'), 90 | ('Faber', 'Surname')], 91 | 'tag': {'GivenName': 'Willem-Jan', 92 | 'Surname': 'Faber'}}], 93 | 'raw_ners': [{'string': 'Willem-Jan Faber', 94 | 'tag': 'person'}, 95 | {'string': 'West Virginia', 96 | 'tag': 'location'}], 97 | 'raw_response': u'Willem-Jan Faber just invoked lang_lib.Language, while wishing he was in West Virginia.'}, 98 | 'stats': {'ascii_lowercase': 71, 99 | 'count': 87, 100 | 'digits': 0, 101 | 'lowercase': 65, 102 | 'printable': 87, 103 | 'unprintable': 0, 104 | 'uppercase': 6}, 105 | 'string': u'Willem-Jan Faber just invoked lang_lib.Language, while wishing he was in West Virginia.'}}, 106 | 'stats': {'avg_length': 87, 'max': 87, 'min': 87}, 107 | 'text': 'Willem-Jan Faber just invoked lang_lib.Language, while wishing he was in West Virginia.'} 108 | 109 | URL + Project / Function within Narralyzer: 110 | ------------------------------------------- 111 | 112 | http://stanfordnlp.github.io/CoreNLP/ 113 | Stanford CoreNLP / Find named entities. 114 | Provide (NER) language models. 115 | 116 | http://www.cnts.ua.ac.be/conll2002/ner/data/ 117 | Conference on Computational Natural Language Learning (CoNLL-2002) / 118 | Provide Dutch language model. 119 | 120 | http://www.clips.ua.ac.be/pattern 121 | CLiPS Pattern / Sentiment analysis. 122 | Part-of-speech tagging. 123 | 124 | http://fnl.es/segtok-a-segmentation-and-tokenization-library.html 125 | Segtok / Sentencte segmentation. 126 | 127 | https://github.com/datamade/probablepeople 128 | probablepeople / Verify & split names. 129 | 130 | 131 | Source code: https://github.com/KBNLresearch/Narralyzer 132 | ''' 133 | sentences = {} 134 | stanford_port = 9990 135 | 136 | use_threads = False 137 | nr_of_threads = 10 138 | 139 | use_stats = True 140 | 141 | sentiment_avail = True 142 | config = config.Config() 143 | 144 | def __init__(self, text=False, lang=False, use_langdetect=True): 145 | if not text: 146 | msg = "Did not get any text to look at." 147 | print(msg) 148 | sys.exit(-1) 149 | 150 | if len(text) < 9: 151 | msg = "Input text is way to small to say someting credible about it." 152 | print(msg) 153 | sys.exit(-1) 154 | 155 | detected_lang = False 156 | if use_langdetect and not lang: 157 | try: 158 | detected_lang = detect(text) 159 | if detected_lang not in STANFORD_NER_SERVERS: 160 | msg = "Detected language (%s) is not (yet) supported.\n" % detected_lang 161 | print(msg) 162 | 163 | msg = "Using detected language '%s' to parse input text." % detected_lang 164 | print(msg) 165 | lang = detected_lang 166 | except: 167 | msg = "Could not automaticly detect language." 168 | print(msg) 169 | elif use_langdetect and lang: 170 | msg = "Skipping language detection, user specified %s as language" % lang 171 | print(msg) 172 | 173 | if not lang or lang not in self.config.get('supported_languages').lower(): 174 | msg = "Did not find suitable language to parse text in." 175 | print(msg, lang) 176 | sys.exit(-1) 177 | 178 | self.stanford_port = STANFORD_NER_SERVERS.get(lang) 179 | 180 | pattern = False 181 | try: 182 | pattern = importlib.import_module('pattern.' + lang) 183 | except: 184 | msg = "Requested language is not (yet) supported, failed to import pattern.%s" % lang 185 | print(msg) 186 | sys.exit(-1) 187 | 188 | self._pattern_parse = pattern.parse 189 | 190 | try: 191 | self._pattern_sentiment = pattern.sentiment 192 | except: 193 | self.sentiment_avail = False 194 | 195 | self._pattern_tag = pattern.tag 196 | 197 | self.result = {"text": text, 198 | "lang": lang, 199 | "sentences": {}, 200 | "stats": {}} 201 | 202 | def parse(self): 203 | for count, sentence in enumerate(split_multi(self.result["text"])): 204 | self.result["sentences"][count] = {"string": sentence, 205 | "pos": [], 206 | "sentiment": [], 207 | "stanford": [], 208 | "count": count} 209 | 210 | if self.use_threads: 211 | self._threaded_parser() 212 | else: 213 | self._parser() 214 | 215 | if self.use_stats: 216 | self.stats_all() 217 | 218 | def _parser(self): 219 | for count, sentence in enumerate(self.result["sentences"].values()): 220 | sentence = sentence.get("string") 221 | result = self._parse_singleton(sentence, count) 222 | for item in result: 223 | self.result["sentences"][count][item] = result[item] 224 | 225 | def _threaded_parser(self): 226 | work_queue = Queue() 227 | result_queue = Queue() 228 | 229 | for count, sentence in enumerate(self.result["sentences"].values()): 230 | work_queue.put({"string": sentence.get("string"), 231 | "count": sentence.get("count")}) 232 | 233 | nr_of_threads = self.nr_of_threads 234 | if len(self.result["sentences"]) <= self.nr_of_threads: 235 | nr_of_threads = len(self.result["sentences"]) 236 | 237 | threads = [] 238 | for worker in range(nr_of_threads): 239 | process = Thread(target=self._parse_queue, 240 | args=(work_queue, result_queue)) 241 | process.daemon = True 242 | process.start() 243 | threads.append(process) 244 | 245 | for thread in threads: 246 | thread.join() 247 | 248 | try: 249 | result = result_queue.get_nowait() 250 | except: 251 | msg = "Thread did not recieve input from queue, bye!" 252 | print(msg) 253 | result = False 254 | 255 | while result: 256 | count = result.get('count') 257 | for item in result: 258 | if item == 'count': 259 | continue 260 | self.result["sentences"][count][item] = result.get(item) 261 | try: 262 | result = result_queue.get_nowait() 263 | except: 264 | result = False 265 | 266 | def _parse_queue(self, work_queue, done_queue): 267 | done = False 268 | while not done: 269 | try: 270 | job = work_queue.get_nowait() 271 | result = self._parse_singleton(job.get('string'), 272 | job.get('count')) 273 | done_queue.put(result) 274 | except: 275 | done = True 276 | 277 | def _parse_singleton(self, sentence, count): 278 | result = {"count": count, 279 | "pos": False, 280 | "sentiment": False, 281 | "stanford": False, 282 | "stats": False} 283 | 284 | if len(sentence) < 2: 285 | return result 286 | 287 | if self.sentiment_avail: 288 | result["sentiment"] = self._pattern_sentiment(sentence) 289 | 290 | result["stanford"] = stanford_ner_wrapper(sentence, 291 | port=self.stanford_port, 292 | use_pp=True) 293 | 294 | pos = [] 295 | for word, pos_tag in self._pattern_tag(sentence): 296 | pos.append({"string": word, "tag": pos_tag}) 297 | 298 | result["pos"] = pos 299 | 300 | return result 301 | 302 | def stats_pos(self): 303 | pass 304 | 305 | def stats_ner(self): 306 | pass 307 | 308 | @staticmethod 309 | def stats_sentence(sentence): 310 | ascii_letters = count = digits = lowercase = \ 311 | printable = uppercase = unprintable = 0 312 | 313 | for count, char in enumerate(sentence): 314 | if char in string.printable: 315 | printable += 1 316 | if char in string.digits: 317 | digits += 1 318 | elif char in string.ascii_letters: 319 | ascii_letters += 1 320 | if char in string.ascii_lowercase: 321 | lowercase += 1 322 | elif char in string.ascii_uppercase: 323 | uppercase += 1 324 | else: 325 | unprintable += 1 326 | 327 | stats = {"ascii_lowercase": ascii_letters, 328 | "count": count + 1, # a='123'; for i in enumerate(a): print(i) 329 | "digits": digits, 330 | "lowercase": lowercase, 331 | "printable": printable, 332 | "uppercase": uppercase, 333 | "unprintable": unprintable} 334 | 335 | return stats 336 | 337 | def stats_all(self): 338 | max_len = min_len = 0 # Min and max sentence length. 339 | avg = [] # Caluclate average sentence length. 340 | for sentence in self.result["sentences"].values(): 341 | # Caluclate the stats per sentence. 342 | sentence_stats = self.stats_sentence(sentence.get("string")) 343 | avg.append(sentence_stats.get("count")) 344 | 345 | if sentence_stats.get("count") > max_len: 346 | max_len = sentence_stats.get("count") 347 | 348 | if sentence_stats.get("count") < min_len: 349 | min_len = sentence_stats.get("count") 350 | 351 | if min_len == 0: 352 | min_len = sentence_stats.get("count") 353 | 354 | self.result["sentences"][sentence.get("count")]["stats"] = sentence_stats 355 | 356 | # Caluclate the total stats. 357 | avg_sentence_length = int(round(mean(avg))) 358 | 359 | stats = {} 360 | stats["avg_length"] = avg_sentence_length 361 | stats["max"] = max_len 362 | stats["min"] = min_len 363 | 364 | self.result["stats"] = stats 365 | 366 | 367 | def _test_NL(): 368 | ''' 369 | >>> lang = Language("Later gaf Christophorus Columbus in een brief aan Ferdinand en Isabella de opdracht de buit te verstoppen en de haven af te branden. Toen Columbus uit de haven van Tunis voer zag hij de soldaten van Isabella naderen.") 370 | Using detected language 'nl' to parse input text. 371 | >>> lang.use_threads = False 372 | >>> lang.parse() 373 | >>> from pprint import pprint 374 | >>> pprint (lang.result) 375 | {'lang': u'nl', 376 | 'sentences': {0: {'count': 0, 377 | 'pos': [{'string': u'Later', 'tag': u'JJR'}, 378 | {'string': u'gaf', 'tag': u'VBD'}, 379 | {'string': u'Christophorus', 'tag': u'NNP'}, 380 | {'string': u'Columbus', 'tag': u'NNP'}, 381 | {'string': u'in', 'tag': u'IN'}, 382 | {'string': u'een', 'tag': u'DT'}, 383 | {'string': u'brief', 'tag': u'NN'}, 384 | {'string': u'aan', 'tag': u'IN'}, 385 | {'string': u'Ferdinand', 'tag': u'NNP'}, 386 | {'string': u'en', 'tag': u'CC'}, 387 | {'string': u'Isabella', 'tag': u'NNP'}, 388 | {'string': u'de', 'tag': u'DT'}, 389 | {'string': u'opdracht', 'tag': u'NN'}, 390 | {'string': u'de', 'tag': u'DT'}, 391 | {'string': u'buit', 'tag': u'NN'}, 392 | {'string': u'te', 'tag': u'TO'}, 393 | {'string': u'verstoppen', 'tag': u'VB'}, 394 | {'string': u'en', 'tag': u'CC'}, 395 | {'string': u'de', 'tag': u'DT'}, 396 | {'string': u'haven', 'tag': u'NN'}, 397 | {'string': u'af', 'tag': u'RP'}, 398 | {'string': u'te', 'tag': u'TO'}, 399 | {'string': u'branden', 'tag': u'VBP'}, 400 | {'string': u'.', 'tag': u'.'}], 401 | 'sentiment': (0.0, 0.1), 402 | 'stanford': {'ners': [{'string': 'Christophorus Columbus', 403 | 'tag': 'per'}, 404 | {'string': 'Ferdinand', 405 | 'tag': 'loc'}, 406 | {'string': 'Isabella', 407 | 'tag': 'per'}], 408 | 'pp': [{'parse': [('Christophorus', 409 | 'CorporationName'), 410 | ('Columbus', 411 | 'CorporationName')], 412 | 'tag': {'CorporationName': 'Christophorus Columbus'}}, 413 | {'parse': [('Isabella', 414 | 'GivenName')], 415 | 'tag': {'GivenName': 'Isabella'}}], 416 | 'raw_ners': [{'string': 'Christophorus', 417 | 'tag': 'b-per'}, 418 | {'string': 'Columbus', 419 | 'tag': 'i-per'}, 420 | {'string': 'Ferdinand', 421 | 'tag': 'b-loc'}, 422 | {'string': 'Isabella', 423 | 'tag': 'b-per'}], 424 | 'raw_response': u'Later gaf Christophorus Columbus in een brief aan Ferdinand en Isabella de opdracht de buit te verstoppen en de haven af te branden.'}, 425 | 'stats': {'ascii_lowercase': 109, 426 | 'count': 132, 427 | 'digits': 0, 428 | 'lowercase': 104, 429 | 'printable': 132, 430 | 'unprintable': 0, 431 | 'uppercase': 5}, 432 | 'string': u'Later gaf Christophorus Columbus in een brief aan Ferdinand en Isabella de opdracht de buit te verstoppen en de haven af te branden.'}, 433 | 1: {'count': 1, 434 | 'pos': [{'string': u'Toen', 'tag': u'CC'}, 435 | {'string': u'Columbus', 'tag': u'NNP'}, 436 | {'string': u'uit', 'tag': u'IN'}, 437 | {'string': u'de', 'tag': u'DT'}, 438 | {'string': u'haven', 'tag': u'NN'}, 439 | {'string': u'van', 'tag': u'IN'}, 440 | {'string': u'Tunis', 'tag': u'NNP'}, 441 | {'string': u'voer', 'tag': u'NN'}, 442 | {'string': u'zag', 'tag': u'VBD'}, 443 | {'string': u'hij', 'tag': u'PRP'}, 444 | {'string': u'de', 'tag': u'DT'}, 445 | {'string': u'soldaten', 'tag': u'NNS'}, 446 | {'string': u'van', 'tag': u'IN'}, 447 | {'string': u'Isabella', 'tag': u'NNP'}, 448 | {'string': u'naderen', 'tag': u'VB'}, 449 | {'string': u'.', 'tag': u'.'}], 450 | 'sentiment': (0.0, 0.0), 451 | 'stanford': {'ners': [{'string': 'Columbus', 452 | 'tag': 'per'}, 453 | {'string': 'Tunis', 'tag': 'loc'}, 454 | {'string': 'Isabella', 455 | 'tag': 'per'}], 456 | 'pp': [{'parse': [('Columbus', 457 | 'GivenName')], 458 | 'tag': {'GivenName': 'Columbus'}}, 459 | {'parse': [('Isabella', 460 | 'GivenName')], 461 | 'tag': {'GivenName': 'Isabella'}}], 462 | 'raw_ners': [{'string': 'Columbus', 463 | 'tag': 'b-per'}, 464 | {'string': 'Tunis', 465 | 'tag': 'b-loc'}, 466 | {'string': 'Isabella', 467 | 'tag': 'b-per'}], 468 | 'raw_response': u'Toen Columbus uit de haven van Tunis voer zag hij de soldaten van Isabella naderen.'}, 469 | 'stats': {'ascii_lowercase': 68, 470 | 'count': 83, 471 | 'digits': 0, 472 | 'lowercase': 64, 473 | 'printable': 83, 474 | 'unprintable': 0, 475 | 'uppercase': 4}, 476 | 'string': u'Toen Columbus uit de haven van Tunis voer zag hij de soldaten van Isabella naderen.'}}, 477 | 'stats': {'avg_length': 108, 'max': 132, 'min': 83}, 478 | 'text': 'Later gaf Christophorus Columbus in een brief aan Ferdinand en Isabella de opdracht de buit te verstoppen en de haven af te branden. Toen Columbus uit de haven van Tunis voer zag hij de soldaten van Isabella naderen.'} 479 | ''' 480 | lang = Language("Later gaf Christophorus Columbus in een brief aan Ferdinand en Isabella de opdracht de buit te verstoppen en de haven af te branden. Toen Columbus uit de haven van Tunis voer zag hij de soldaten van Isabella naderen.", "nl") 481 | lang.use_threads = False 482 | lang.parse() 483 | from pprint import pprint 484 | pprint(lang.result) 485 | 486 | if __name__ == '__main__': 487 | if len(sys.argv) >= 2 and "test" in " ".join(sys.argv): 488 | import doctest 489 | doctest.testmod(verbose=True) 490 | 491 | if len(sys.argv) >= 2 and "time" or "profile" in " ".join(sys.argv): 492 | import time 493 | import json 494 | 495 | from django.utils.encoding import smart_text 496 | from gutenberg.acquire import load_etext 497 | from gutenberg.cleanup import strip_headers 498 | from pycallgraph import PyCallGraph 499 | from pycallgraph.output import GraphvizOutput 500 | 501 | if "time" in " ".join(sys.argv): 502 | print("Timing non-threaded lang_lib") 503 | s = time.time() 504 | lang = Language(text) 505 | lang.use_threads = False 506 | lang.parse() 507 | print("Took %s seconds" % (str(round(s - time.time()) * -1))) 508 | 509 | print("Timing threaded lang_lib") 510 | s = time.time() 511 | lang = Language(text) 512 | lang.use_threads = True 513 | lang.parse() 514 | print("Took %s seconds" % (str(round(s - time.time()) * -1))) 515 | 516 | print("Timing ner-vanilla") 517 | s = time.time() 518 | stanford_ner_wrapper(text, 9992) 519 | print("Took %s seconds" % (str(round(s - time.time()) * -1))) 520 | 521 | outfile = "../out/%s.pos_ner_sentiment.json" % gutenberg_test_id 522 | print("Writing output in json-format to: %s" % outfile) 523 | with open(outfile, "w") as fh: 524 | fh.write(json.dumps(lang.result)) 525 | 526 | with PyCallGraph(output=GraphvizOutput()): 527 | lang = Language(text) 528 | lang.use_threads = True 529 | lang.parse() 530 | -------------------------------------------------------------------------------- /licence.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 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 General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------