### Start the Stanza demo server with Flask Source: https://github.com/stanfordnlp/stanza/blob/main/stanza/pipeline/demo/README.md Run these commands from the demo directory to start the Flask server. Requires stanza and flask installed. The server will serve the demo at http://localhost:5000 by default. ```bash export FLASK_APP=demo_server.py flask run ``` -------------------------------- ### install_corenlp(dir=DEFAULT_CORENLP_DIR, url=DEFAULT_CORENLP_URL, logging_level=None, proxies=None, version=None) Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/resources.md Fully automatic installation and setup of the CoreNLP library to use the client functionality. Downloads the CoreNLP zip, unzips it, moves files out of the versioned folder, and cleans up. ```APIDOC ## install_corenlp(dir=DEFAULT_CORENLP_DIR, url=DEFAULT_CORENLP_URL, logging_level=None, proxies=None, version=None) ### Description Fully automatic installation and setup of the CoreNLP library to use the client functionality. Downloads the CoreNLP zip, unzips it, moves files out of the versioned folder, and cleans up. ### Parameters - **dir** (str) - Optional - Installation directory (`$CORENLP_HOME` honored). Default: `DEFAULT_CORENLP_DIR`. - **url** (str) - Optional - Zip URL; needs a `{version}` or `{tag}` placeholder. Default: `DEFAULT_CORENLP_URL`. - **logging_level** (str) - Optional - Temporary logging level. Default: `None`. - **proxies** (dict) - Optional - Requests proxies. Default: `None`. - **version** (str) - Optional - `'4.5.10'`, `'main'`, or `None` for newest release. Default: `None`. ### Behavior Warns and returns early if `dir` already exists non-empty. Downloads `corenlp.zip`, unzips, moves files out of the versioned folder, cleans up, and warns to set `CORENLP_HOME` when a non-default `dir` is used. Download failures are wrapped in `RuntimeError("Downloading CoreNLP {description} failed. Please try manual installation: https://stanfordnlp.github.io/CoreNLP/.")`. ``` -------------------------------- ### RobustService.start() Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/corenlp-client.md Launches the server subprocess using the start command. Optionally binds to a host and port first, raising PermanentlyFailedException if the port is occupied and FileNotFoundError if Java is not installed. ```APIDOC ## RobustService.start() ### Description Launches the server subprocess using the start command. Optionally binds to a host and port first, raising PermanentlyFailedException if the port is occupied and FileNotFoundError if Java is not installed. ### Method Start ### Exceptions - **PermanentlyFailedException** - Raised if the port is occupied (unless ignore_binding_error). - **FileNotFoundError** - Raised if Java is not installed. ``` -------------------------------- ### stanza.download usage examples Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/resources.md Shows basic downloads, processor-specific downloads, and a custom-trained model download using the 'pretrain' processor with the 'gsd' package. ```python import stanza stanza.download('en') stanza.download('zh', processors={'tokenize': 'default', 'ner': 'default'}) # custom-trained model download stanza.download('en', processors='pretrain', package='gsd') ``` -------------------------------- ### Install Stanza from source Source: https://github.com/stanfordnlp/stanza/blob/main/README.md Clones the Stanza git repository and installs it in editable mode for development flexibility. ```bash git clone https://github.com/stanfordnlp/stanza.git cd stanza pip install -e . ``` -------------------------------- ### Install and import Stanza Source: https://github.com/stanfordnlp/stanza/blob/main/demo/Stanza_Beginners_Guide.ipynb Install the stanza package with pip and import it. The '!' prefix is only needed when running in a notebook; omit it in a terminal. Stanza requires Python 3.6 or above. ```python # Install; note that the prefix "!" is not needed if you are running in a terminal !pip install stanza # Import the package import stanza ``` -------------------------------- ### Verify CoreNLP installation by listing files Source: https://github.com/stanfordnlp/stanza/blob/main/demo/Stanza_CoreNLP_Interface.ipynb List the files in the CoreNLP directory to confirm the installation succeeded. You should see a number of .jar files. ```python # Examine the CoreNLP installation folder to make sure the installation is successful !ls $CORENLP_HOME ``` -------------------------------- ### Download and set up Stanford CoreNLP with stanza.install_corenlp Source: https://github.com/stanfordnlp/stanza/blob/main/demo/Stanza_CoreNLP_Interface.ipynb Download the CoreNLP package using Stanza's installation command and set the CORENLP_HOME environment variable to the installation directory. This may take several minutes depending on network speed. ```python # Download the Stanford CoreNLP package with Stanza's installation command # This'll take several minutes, depending on the network speed corenlp_dir = './corenlp' stanza.install_corenlp(dir=corenlp_dir) # Set the CORENLP_HOME environment variable to point to the installation location import os os.environ["CORENLP_HOME"] = corenlp_dir ``` -------------------------------- ### Imports and environment setup for Semgrex visualization Source: https://github.com/stanfordnlp/stanza/blob/main/demo/semgrex visualization.ipynb Sets up the notebook environment for Semgrex visualization. Requires CoreNLP and Java installed, with the CLASSPATH environment variable set to the CoreNLP directory. The %env magic sets the CLASSPATH for the notebook session. ```python import stanza from stanza.server.semgrex import Semgrex from stanza.models.common.constant import is_right_to_left import spacy from spacy import displacy from spacy.tokens import Doc from IPython.display import display, HTML ``` ```python """ IMPORTANT: For the code in this module to run, you must have corenlp and Java installed on your machine. Additionally, set an environment variable CLASSPATH equal to the path of your corenlp directory. Example: CLASSPATH=C:\\Users\\Alex\\PycharmProjects\\pythonProject\\stanford-corenlp-4.5.0\\stanford-corenlp-4.5.0\\* """ %env CLASSPATH=C:\\stanford-corenlp-4.5.2\\stanford-corenlp-4.5.2\\* ``` -------------------------------- ### Install and import Stanza Source: https://github.com/stanfordnlp/stanza/blob/main/demo/Stanza_CoreNLP_Interface.ipynb Install the Stanza library using pip and import it. The '!' prefix is only needed in a notebook environment. ```python # Install stanza; note that the prefix "!" is not needed if you are running in a terminal !pip install stanza # Import stanza import stanza ``` -------------------------------- ### get() usage example Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/document.md Shows how to use the get() method to retrieve 'text' and 'upos' fields from a processed document. The output is a list of lists, e.g., ['Hello', 'world', '.'] for texts. ```python import stanza nlp = stanza.Pipeline('en', processors='tokenize,pos') doc = nlp("Hello world.") texts, upos = doc.get(['text', 'upos']) print(texts) # ['Hello', 'world', '.'] ``` -------------------------------- ### process_pipeline_parameters usage example Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/resources.md Shows how to call process_pipeline_parameters with a language, model directory, package, and processors string. It returns a normalized tuple of (lang, model_dir, package, processors). ```python from stanza.resources.common import process_pipeline_parameters, maintain_processor_list, load_resources_json lang, model_dir, package, processors = process_pipeline_parameters('en', '/data', 'default', 'tokenize,pos') ``` -------------------------------- ### Install CoreNLP for stanza.server tools Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/resources.md Installs CoreNLP machinery needed by stanza.server tools. Uses stanza.install_corenlp with dir='/opt/corenlp' and version='4.5.10', then downloads English models. Catches RuntimeError and prints a failure message. ```python import stanza # install CoreNLP machinery needed by stanza.server tools try: stanza.install_corenlp(dir='/opt/corenlp', version='4.5.10') stanza.download_corenlp_models('english', dir='/opt/corenlp') except RuntimeError as e: print("CoreNLP installation failed:", e) ``` -------------------------------- ### installed_corenlp_version(dir) Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/resources.md Returns the version of the installed CoreNLP distribution from the single `stanford-corenlp-.jar` in the given directory, or `None` if not found. ```APIDOC ## installed_corenlp_version(dir) ### Description Returns the version of the installed CoreNLP distribution from the single `stanford-corenlp-.jar` in the given directory, or `None` if not found. ### Parameters - **dir** (str) - Required - Directory containing the CoreNLP installation. ### Returns - **str or None** - The version string extracted from the jar filename, or `None` if no matching jar is found. ``` -------------------------------- ### process() usage example Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/pipeline.md Shows how to create a pipeline and process a single text, printing the detected entities. ```python import stanza nlp = stanza.Pipeline('en') doc = nlp.process("Barack Obama was born in Hawaii.") print(doc.entities) ``` -------------------------------- ### flatten_processor_list(processor_list) Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/resources.md Returns `[[processor, package], ...]` including deduplicated dependencies. ```APIDOC ## [FUNCTION] flatten_processor_list(processor_list) ### Description Returns `[[processor, package], ...]` including deduplicated dependencies. ### Method Function call ### Parameters #### Parameters - **processor_list** (list) - Required - List of `[processor_name, [ModelSpecification, ...]]` pairs. ### Response #### Success Response Returns a flattened list of `[processor, package]` pairs. ``` -------------------------------- ### Download English and Chinese models with stanza.download Source: https://github.com/stanfordnlp/stanza/blob/main/demo/Stanza_Beginners_Guide.ipynb Download pretrained models using the stanza.download command. Specify the language by full name or short code (e.g., 'en', 'zh'). Models are saved to ~/stanza_resources by default; pass dir=your_path to change the location. Use verbose=False to suppress printed messages. ```python # Download an English model into the default directory print("Downloading English model...") stanza.download('en') # Similarly, download a (simplified) Chinese model # Note that you can use verbose=False to turn off all printed messages print("Downloading Chinese model...") stanza.download('zh', verbose=False) ``` -------------------------------- ### Module constants for CoreNLP installation Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/resources.md Defines default URLs, directory, and available models for CoreNLP installation. Environment variables CORENLP_MODEL_URL, CORENLP_URL, and CORENLP_HOME are honored. ```python DEFAULT_CORENLP_MODEL_URL = os.getenv('CORENLP_MODEL_URL', 'https://huggingface.co/stanfordnlp/corenlp-{model}/resolve/{tag}/stanford-corenlp-models-{model}.jar') BACKUP_CORENLP_MODEL_URL = "http://nlp.stanford.edu/software/stanford-corenlp-{version}-models-{model}.jar" DEFAULT_CORENLP_URL = os.getenv('CORENLP_URL', 'https://huggingface.co/stanfordnlp/CoreNLP/resolve/{tag}/stanford-corenlp-latest.zip') DEFAULT_CORENLP_DIR = os.getenv('CORENLP_HOME', os.path.join(USER_CACHE_DIR, 'corenlp')) AVAILABLE_MODELS = set(['arabic', 'chinese', 'english-extra', 'english-kbp', 'french', 'german', 'hungarian', 'italian', 'spanish']) ``` -------------------------------- ### Visualize Japanese CONLLU file with conll_to_visual Source: https://github.com/stanfordnlp/stanza/blob/main/demo/CONLL_Dependency_Visualizer_Example.ipynb Loads a Japanese CONLLU file and generates dependency visualizations. The file 'japanese_test.conllu.txt' is expected in the demo directory. ```python from stanza.utils.visualization.conll_deprel_visualization import conll_to_visual jp_file = "japanese_test.conllu.txt" conll_to_visual(jp_file, "ja") ``` -------------------------------- ### resolve_corenlp_version(url, requested, proxies=None) Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/resources.md Resolves the CoreNLP version to install based on the requested version and URL. Returns a tuple `(version, tag, description)`. ```APIDOC ## resolve_corenlp_version(url, requested, proxies=None) ### Description Resolves the CoreNLP version to install based on the requested version and URL. Returns a tuple `(version, tag, description)`. ### Parameters - **url** (str) - Required - The URL template for the CoreNLP zip. - **requested** (str) - Required - Version request: `None` for newest release, `'main'` for main branch, or a release number. - **proxies** (dict) - Optional - Requests proxies. Default: `None`. ### Returns - **version** (str) - The resolved version string. - **tag** (str) - The tag to use in the URL. - **description** (str) - Human-readable description of the version. ### Behavior - `requested` `None` → newest release tag from the HF repo. - `'main'` → main branch (description names the matching release, if any). - A release number → `(requested, 'v'+requested, requested)`. - Offline (`HF_HUB_OFFLINE`): newest release in the local HF cache, else `'main'`, else `RuntimeError`. - Non-HF URLs with `requested=None` raise `ValueError`; repo lookups failures raise `RuntimeError`. ``` -------------------------------- ### Install Stanza with pip Source: https://github.com/stanfordnlp/stanza/blob/main/README.md Installs the latest Stanza package via pip. Requires Python 3.6 or later and resolves dependencies such as PyTorch 1.3.0 or above. ```bash pip install stanza ``` -------------------------------- ### Construct and start CoreNLPClient with annotators, memory, endpoint, and be_quiet Source: https://github.com/stanfordnlp/stanza/blob/main/demo/Stanza_CoreNLP_Interface.ipynb Creates a CoreNLPClient with basic annotators (tokenize, ssplit, pos, lemma, ner), 4GB memory, endpoint port 9001, and be_quiet=True to avoid IO issues in Colab. The client.start() call is optional because the server starts automatically on first annotation; a 10-second sleep waits for the background Java server. ```python # Construct a CoreNLPClient with some basic annotators, a memory allocation of 4GB, and port number 9001 client = CoreNLPClient( annotators=['tokenize','ssplit', 'pos', 'lemma', 'ner'], memory='4G', endpoint='http://localhost:9001', be_quiet=True) print(client) # Start the background server and wait for some time # Note that in practice this is totally optional, as by default the server will be started when the first annotation is performed client.start() import time; time.sleep(10) ``` -------------------------------- ### GET / Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/endpoints.md Serves the rendered index page for the demo brat server. Returns the HTML template with version and current date. ```APIDOC ## GET / ### Description Serves the rendered index page for the demo brat server. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **body** (HTML) - The rendered `stanza-brat.html.j2` template with version and current date. #### Response Example ```html ... ``` ``` -------------------------------- ### Visualize Arabic CONLLU file with conll_to_visual Source: https://github.com/stanfordnlp/stanza/blob/main/demo/CONLL_Dependency_Visualizer_Example.ipynb Loads an Arabic CONLLU file and generates dependency visualizations for a right-to-left language. The file 'arabic_test.conllu.txt' is expected in the demo directory. ```python from stanza.utils.visualization.conll_deprel_visualization import conll_to_visual # testing right to left languages ar_file = "arabic_test.conllu.txt" conll_to_visual(ar_file, "ar") ``` -------------------------------- ### Visualize English CONLLU file with conll_to_visual Source: https://github.com/stanfordnlp/stanza/blob/main/demo/CONLL_Dependency_Visualizer_Example.ipynb Loads an English CONLLU file and generates dependency visualizations for the first 2 and 10 sentences. The file 'en_test.conllu.txt' is expected in the demo directory. A commented-out call shows how to display all sentences with display_all=True. ```python from stanza.utils.visualization.conll_deprel_visualization import conll_to_visual # load necessary conllu files - expected to be in the demo directory along with the notebook en_file = "en_test.conllu.txt" # testing left to right languages conll_to_visual(en_file, "en", sent_count=2) conll_to_visual(en_file, "en", sent_count=10) #conll_to_visual(en_file, "en", display_all=True) ``` -------------------------------- ### Use CoreNLPClient with the Python `with` statement Source: https://github.com/stanfordnlp/stanza/blob/main/demo/Stanza_CoreNLP_Interface.ipynb Recommended way to manage the CoreNLP client lifecycle: the `with` statement automatically starts and stops the server, avoiding memory leaks from forgotten `stop()` calls. The example initializes the client with specified annotators, memory, endpoint, and quiet mode, then annotates a sample text and prints entity mentions. ```python print("Starting a server with the Python \"with\" statement...") with CoreNLPClient(annotators=['tokenize','ssplit', 'pos', 'lemma', 'ner'], memory='4G', endpoint='http://localhost:9001', be_quiet=True) as client: text = "Albert Einstein was a German-born theoretical physicist." document = client.annotate(text) print("{:30s}\t{}".format("Mention", "Type")) for sent in document.sentence: for m in sent.mentions: print("{:30s}\t{}".format(m.entityMentionText, m.entityType)) print("\nThe server should be stopped upon exit from the \"with\" statement.") ``` -------------------------------- ### Example usage of loaded_processors Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/pipeline.md Shows how to access the loaded processors of a pipeline and print their provides attributes. ```python import stanza nlp = stanza.Pipeline('en', processors='tokenize,pos') print(nlp.loaded_processors) # [TokenizeProcessor(...), POSProcessor(...)] print([p.provides for p in nlp.loaded_processors]) ``` -------------------------------- ### Download Stanza models for a language Source: https://github.com/stanfordnlp/stanza/blob/main/stanza/pipeline/demo/README.md Use this Python snippet to download the models for a specific language code before submitting requests to the demo server. Replace with the desired language code. ```python import stanza; stanza.download() ``` -------------------------------- ### add_dependencies(resources, lang, processor_list) Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/resources.md Fills each `ModelSpecification.dependencies` (tuples of `(model, package)`), skipping processor variants and the identity lemmatizer. Mutates the list items. ```APIDOC ## [FUNCTION] add_dependencies(resources, lang, processor_list) ### Description Fills each `ModelSpecification.dependencies` (tuples of `(model, package)`), skipping processor variants and the identity lemmatizer. Mutates the list items. ### Method Function call ### Parameters #### Parameters - **resources** (dict) - Required - The resources JSON. - **lang** (str) - Required - Language code. - **processor_list** (list) - Required - List of `[processor_name, [ModelSpecification, ...]]` pairs. ### Response #### Success Response Mutates the processor list items to include dependencies. ``` -------------------------------- ### Install Stanza with conda Source: https://github.com/stanfordnlp/stanza/blob/main/README.md Installs Stanza via Anaconda using the stanfordnlp channel. Note that this method does not currently work for Python 3.10; use pip for Python 3.10. ```bash conda install -c stanfordnlp stanza ``` -------------------------------- ### install_corenlp function signature Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/resources.md Fully automatic installation of CoreNLP. Accepts directory, URL, logging level, proxies, and version. Returns early if directory exists non-empty; wraps download failures in RuntimeError. ```python def install_corenlp(dir=DEFAULT_CORENLP_DIR, url=DEFAULT_CORENLP_URL, logging_level=None, proxies=None, version=None): """ A fully automatic way to install and setting up the CoreNLP library to use the client functionality. """ ``` -------------------------------- ### sort_processors(processor_list) Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/resources.md Sorts the list into `PIPELINE_NAMES` order, appending unknown names at the end. ```APIDOC ## [FUNCTION] sort_processors(processor_list) ### Description Sorts the list into `PIPELINE_NAMES` order, appending unknown names at the end. ### Method Function call ### Parameters #### Parameters - **processor_list** (list) - Required - List of processor names. ### Response #### Success Response Returns the sorted processor list. ``` -------------------------------- ### CoreNLPClient.__init__ Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/corenlp-client.md Constructor for the CoreNLPClient class. Initializes a client to interact with a Stanford CoreNLP server, optionally starting the server with specified configuration. ```APIDOC ## CoreNLPClient.__init__ ### Description Constructor for the CoreNLPClient class. Initializes a client to interact with a Stanford CoreNLP server, optionally starting the server with specified configuration. ### Method Constructor ### Signature ```python def __init__(self, start_server=StartServer.FORCE_START, endpoint=DEFAULT_ENDPOINT, timeout=DEFAULT_TIMEOUT, threads=DEFAULT_THREADS, annotators=None, pretokenized=False, output_format=None, properties=None, stdout=None, stderr=None, memory=DEFAULT_MEMORY, be_quiet=False, max_char_length=DEFAULT_MAX_CHAR_LENGTH, preload=True, classpath=None, **kwargs): ``` ### Parameters - **start_server** (StartServer or bool, deprecated) - Optional - Whether/how to start the server. Default: `StartServer.FORCE_START`. - **endpoint** (str) - Optional - Server URL. When starting a server, host must be `localhost` (asserted) and a port is parsed from the URL. Default: `"http://localhost:9000"`. - **timeout** (int) - Optional - Server timeout in milliseconds (request timeout is `timeout*2/1000` seconds). Default: `60000`. - **threads** (int) - Optional - Server thread count. Default: `5`. - **annotators** (str / list) - Optional - Annotators for the server / requests (comma-joined). Default: `None`. - **pretokenized** (bool) - Optional - Adds `-preTokenized` to the server command. Default: `False`. - **output_format** (str) - Optional - One of the validated formats (see `CORENLP_OUTPUT_VALS`); defaults to `serialized`. Default: `None`. - **properties** (str / dict) - Optional - Server properties: a CoreNLP language name (e.g. `'french'`, `'fr'`), a `.props` file path, or a dict (written to a temp props file, cleaned up at exit). Default: `None`. - **stdout** / **stderr** (file objects) - Optional - Subprocess streams. Default: `None`. - **memory** (str) - Optional - JVM heap (`-Xmx`). Default: `'5G'`. - **be_quiet** (bool) - Optional - `-quiet` flag; when `True` also devnulls subprocess output. Default: `False`. - **max_char_length** (int) - Optional - `-maxCharLength` server flag. Default: `100000`. - **preload** (bool / str / list) - Optional - `-preload` flag: `True` preloads all defaults; a list/str names specific annotators. Default: `True`. - **classpath** (str) - Optional - Java classpath; see `resolve_classpath()`. Default: `None`. - **kwargs** (—) - Optional - Extra server flags: `ssl`, `strict`, `status_port`, `uriContext`, `key`, `username`, `password`, `blockList`, `server_id` (each appended to the start command, with value when appropriate). ### Notes - Validated formats (`validate_corenlp_props`, line 59): `conll, conllu, json, serialized, text, xml, inlinexml` — any other `output_format` raises `ValueError`. ``` -------------------------------- ### list_available_languages(model_dir=DEFAULT_MODEL_DIR, resources_url=DEFAULT_RESOURCES_URL, resources_branch=None, resources_version=DEFAULT_RESOURCES_VERSION, proxies=None) Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/resources.md Downloads the resources JSON and returns a sorted list of non-alias language codes. ```APIDOC ## [FUNCTION] list_available_languages(model_dir=DEFAULT_MODEL_DIR, resources_url=DEFAULT_RESOURCES_URL, resources_branch=None, resources_version=DEFAULT_RESOURCES_VERSION, proxies=None) ### Description Downloads the resources JSON and returns a sorted list of non-alias language codes. ### Method Function call ### Parameters #### Parameters - **model_dir** (str) - Optional - Directory where models are saved. Default: `DEFAULT_MODEL_DIR`. - **resources_url** (str) - Optional - Resources JSON base URL. Default: `DEFAULT_RESOURCES_URL`. - **resources_branch** (str) - Optional - GitHub branch override. Default: `None`. - **resources_version** (str) - Optional - Version used in the filename `resources_{version}.json`. Default: `DEFAULT_RESOURCES_VERSION`. - **proxies** (dict) - Optional - Requests proxies. Default: `None`. ### Response #### Success Response Returns a sorted list of non-alias language codes. ``` -------------------------------- ### RobustService.__init__ Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/corenlp-client.md Initializes a RobustService instance with the given start and stop commands, endpoint, and optional parameters. This is the base service that resuscitates itself when not available. ```APIDOC ## RobustService.__init__ ### Description Initializes a RobustService instance with the given start and stop commands, endpoint, and optional parameters. This is the base service that resuscitates itself when not available. ### Method Constructor ### Signature ```python def __init__(self, start_cmd, stop_cmd, endpoint, stdout=None, stderr=None, be_quiet=False, host=None, port=None, ignore_binding_error=False) ``` ### Parameters - **start_cmd** (str) - Required - Command to start the server. - **stop_cmd** (str) - Required - Command to stop the server. - **endpoint** (str) - Required - Base URL of the server. - **stdout** (file object) - Optional - Where to redirect stdout. - **stderr** (file object) - Optional - Where to redirect stderr. - **be_quiet** (bool) - Optional - Suppress output. - **host** (str) - Optional - Host to bind. - **port** (int) - Optional - Port to bind. - **ignore_binding_error** (bool) - Optional - Ignore binding errors. ### Class Attribute - **CHECK_ALIVE_TIMEOUT** (int) - 120 seconds. ``` -------------------------------- ### download_resources_json(model_dir=DEFAULT_MODEL_DIR, resources_url=DEFAULT_RESOURCES_URL, resources_branch=None, resources_version=DEFAULT_RESOURCES_VERSION, resources_filepath=None, proxies=None) Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/resources.md Downloads the resources JSON file from the specified URL into the model directory. It recognizes short names for the Stanford mirror and sets `raise_for_status=True`. ```APIDOC ## [FUNCTION] download_resources_json(model_dir=DEFAULT_MODEL_DIR, resources_url=DEFAULT_RESOURCES_URL, resources_branch=None, resources_version=DEFAULT_RESOURCES_VERSION, resources_filepath=None, proxies=None) ### Description Downloads the resources JSON file from the specified URL into the model directory. It recognizes short names for the Stanford mirror and sets `raise_for_status=True`. ### Method Function call ### Parameters #### Parameters - **model_dir** (str) - Optional - Directory where models are saved. Default: `DEFAULT_MODEL_DIR`. - **resources_url** (str) - Optional - Resources JSON base URL. Default: `DEFAULT_RESOURCES_URL`. - **resources_branch** (str) - Optional - GitHub branch override. Default: `None`. - **resources_version** (str) - Optional - Version used in the filename `resources_{version}.json`. Default: `DEFAULT_RESOURCES_VERSION`. - **resources_filepath** (str) - Optional - Custom filepath for the downloaded resources JSON. Default: `None`. - **proxies** (dict) - Optional - Requests proxies. Default: `None`. ### Response #### Success Response Downloads the resources JSON to the specified location. ``` -------------------------------- ### conll2doc error handling example Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/conll.md Demonstrates catching a `CoNLLError` when parsing invalid CoNLL input with too few fields. The example passes a string with only two fields and prints the error message. ```python from stanza.utils.conll import CoNLL, CoNLLError try: doc = CoNLL.conll2doc(input_str="1\tbad") # too few fields except CoNLLError as e: print("conll parse failed:", e) ``` -------------------------------- ### conll2doc usage example with reconstruct_text Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/conll.md Shows how to load a CoNLL-U file into a `Document` with `reconstruct_text=True` to add character offsets and rebuild sentence text. The example prints the universal part-of-speech tag of the first word in the first sentence. ```python from stanza.utils.conll import CoNLL doc = CoNLL.conll2doc(input_file="arabic_test.conllu.txt", reconstruct_text=True) print(doc.sentences[0].words[0].upos) ``` -------------------------------- ### RobustService.__enter__ / __exit__ Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/corenlp-client.md Context manager methods that start and stop the service. ```APIDOC ## RobustService.__enter__ / __exit__ ### Description Context manager methods that start and stop the service. ### Usage ```python with RobustService(...) as service: ... ``` ``` -------------------------------- ### from_serialized() usage example Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/document.md Shows how to serialize a document to JSON bytes and then deserialize it back into a Document object using from_serialized(). The example prints the text of the deserialized document. ```python import stanza from stanza import Document nlp = stanza.Pipeline('en', processors='tokenize') doc = nlp("Two sentences. Here.") blob = doc.to_serialized() # JSON bytes doc2 = Document.from_serialized(blob) print(doc2.text) ``` -------------------------------- ### release_tags(tags) Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/resources.md Maps release `Version` objects to tag names, skipping non-`v` and prerelease tags. ```APIDOC ## release_tags(tags) ### Description Maps release `Version` objects to tag names, skipping non-`v` and prerelease tags. ### Parameters - **tags** (dict) - Required - Dictionary mapping tag names to commit hashes. ### Returns - **dict** - Dictionary mapping `Version` objects to tag names, excluding non-`v` and prerelease tags. ``` -------------------------------- ### visualize_strings usage example Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/visualization.md Shows how to import and call visualize_strings with a list of strings, a language code, and a colors dictionary mapping entity types to colors. The function builds a tokenize,ner pipeline for the language code and visualizes each string separated by a delimiting line. ```python from stanza.utils.visualization.ner_visualization import visualize_strings visualize_strings(["Barack Obama was born in Hawaii."], "en", colors={"PERSON": "yellow", "GPE": "blue"}) ``` -------------------------------- ### download_corenlp_models(model, version=None, dir=DEFAULT_CORENLP_DIR, url=DEFAULT_CORENLP_MODEL_URL, logging_level='INFO', proxies=None, force=True) Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/resources.md Downloads a CoreNLP model jar for a specified model. Validates the model name against `AVAILABLE_MODELS` and handles version resolution. ```APIDOC ## download_corenlp_models(model, version=None, dir=DEFAULT_CORENLP_DIR, url=DEFAULT_CORENLP_MODEL_URL, logging_level='INFO', proxies=None, force=True) ### Description Downloads a CoreNLP model jar for a specified model. Validates the model name against `AVAILABLE_MODELS` and handles version resolution. ### Parameters - **model** (str) - Required - One of `AVAILABLE_MODELS` (case-insensitive); empty → `ValueError("The model to download must be specified")`; unknown → `KeyError`. - **version** (str) - Optional - Matches the CoreNLP installed in `dir` when `None`; else a release like `'4.5.10'` or `'main'`. Default: `None`. - **dir** (str) - Optional - Destination dir. Default: `DEFAULT_CORENLP_DIR`. - **url** (str) - Optional - Jar URL template with `{model}` and `{tag}`/`{version}`. Default: `DEFAULT_CORENLP_MODEL_URL`. - **logging_level** (str) - Optional - Logging level during install. Default: `'INFO'`. - **proxies** (dict) - Optional - Requests proxies. Default: `None`. - **force** (bool) - Optional - If `False`, warn and return when the jar already exists. Default: `True`. ### Behavior Download failures raise `RuntimeError` pointing to https://stanfordnlp.github.io/CoreNLP/. ``` -------------------------------- ### load_resources_json(model_dir=DEFAULT_MODEL_DIR, resources_filepath=None) Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/resources.md Parses and returns the resources JSON from the model directory or a custom filepath. Raises `ResourcesFileNotFoundError` if the file is missing. ```APIDOC ## [FUNCTION] load_resources_json(model_dir=DEFAULT_MODEL_DIR, resources_filepath=None) ### Description Parses and returns the resources JSON from the model directory or a custom filepath. Raises `ResourcesFileNotFoundError` if the file is missing. ### Method Function call ### Parameters #### Parameters - **model_dir** (str) - Optional - Directory where models are saved. Default: `DEFAULT_MODEL_DIR`. - **resources_filepath** (str) - Optional - Custom filepath to the resources JSON. Default: `None`. ### Response #### Success Response Returns the parsed resources JSON. #### Error Handling Raises `ResourcesFileNotFoundError` if the file is not found. ``` -------------------------------- ### Upgrade Stanza with pip Source: https://github.com/stanfordnlp/stanza/blob/main/README.md Upgrades an existing Stanza installation to the latest version using pip. ```bash pip install stanza -U ``` -------------------------------- ### Check background Java CoreNLP server process Source: https://github.com/stanfordnlp/stanza/blob/main/demo/Stanza_CoreNLP_Interface.ipynb Runs a shell command to list background processes and verify that a StanfordCoreNLPServer java process is running after starting the client. ```python # Print background processes and look for java # You should be able to see a StanfordCoreNLPServer java process running in the background !ps -o pid,cmd | grep java ``` -------------------------------- ### Visualize Arabic dependency strings with visualize_strings Source: https://github.com/stanfordnlp/stanza/blob/main/demo/Dependency_Visualization_Testing.ipynb Tests the visualize_strings function with Arabic (right-to-left) text. Imports visualize_strings from stanza.utils.visualization.dependency_visualization and passes a list of Arabic sentences with language code 'ar'. ```python from stanza.utils.visualization.dependency_visualization import visualize_strings ar_strings = ['برلين ترفض حصول شركة اميركية على رخصة تصنيع دبابة "ليوبارد" الالمانية', "هل بإمكاني مساعدتك؟", "أراك في مابعد", "لحظة من فضلك"] # Testing with right to left language visualize_strings(ar_strings, "ar") ``` -------------------------------- ### GET / Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/endpoints.md Serves whitelisted static assets for the demo brat server. Returns the requested asset or 403 for disallowed paths. ```APIDOC ## GET / ### Description Serves whitelisted static assets for the demo brat server. ### Method GET ### Endpoint / ### Parameters #### Path Parameters - **path** (string) - Required - Path to the static asset. ### Response #### Success Response (200) - **body** (file) - The requested asset (CSS, JS, images, fonts, or rendered `index.html`). #### Error Response (403) - **body** (string) - `FORBIDDEN` when the path is not whitelisted. ``` -------------------------------- ### Annotate English and Chinese text with a pipeline Source: https://github.com/stanfordnlp/stanza/blob/main/demo/Stanza_Beginners_Guide.ipynb Pass a string to a constructed pipeline to get a Document object containing detailed annotations. The example processes English and Chinese sentences and prints the type of the returned object. ```python # Processing English text en_doc = en_nlp("Barack Obama was born in Hawaii. He was elected president in 2008.") print(type(en_doc)) # Processing Chinese text zh_doc = zh_nlp("达沃斯世界经济论坛是每年全球政商界领袖聚在一起的年度盛事。") print(type(zh_doc)) ``` -------------------------------- ### Visualize Chinese dependency strings with visualize_strings Source: https://github.com/stanfordnlp/stanza/blob/main/demo/Dependency_Visualization_Testing.ipynb Tests the visualize_strings function with Chinese text. Imports visualize_strings from stanza.utils.visualization.dependency_visualization and passes a list of Chinese sentences with language code 'zh'. ```python from stanza.utils.visualization.dependency_visualization import visualize_strings zh_strings = ["中国是一个很有意思的国家。"] # Testing with right to left language visualize_strings(zh_strings, "zh") ``` -------------------------------- ### hf_repo_refs(repo_id, proxies=None) Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/resources.md Fetches branch and tag references for a Hugging Face repository. Returns a tuple of dictionaries mapping names to commit hashes. ```APIDOC ## hf_repo_refs(repo_id, proxies=None) ### Description Fetches branch and tag references for a Hugging Face repository. Returns a tuple of dictionaries mapping names to commit hashes. ### Parameters - **repo_id** (str) - Required - The Hugging Face repository ID. - **proxies** (dict) - Optional - Requests proxies. Default: `None`. ### Returns - **branches** (dict) - Dictionary mapping branch names to commit hashes. - **tags** (dict) - Dictionary mapping tag names to commit hashes. ### Behavior Uses `huggingface_hub` or `requests` (endpoint from `HF_ENDPOINT`, honored with proxies). ``` -------------------------------- ### Visualize English dependency strings with visualize_strings Source: https://github.com/stanfordnlp/stanza/blob/main/demo/Dependency_Visualization_Testing.ipynb Tests the visualize_strings function with English (left-to-right) text. Imports visualize_strings from stanza.utils.visualization.dependency_visualization and passes a list of English sentences with language code 'en'. ```python from stanza.utils.visualization.dependency_visualization import visualize_strings en_strings = ["This is a sentence.", "He is wearing a red shirt", "Barack Obama was born in Hawaii. He was elected President of the United States in 2008."] # Testing with left to right languages visualize_strings(en_strings, "en") ``` -------------------------------- ### maintain_processor_list(resources, lang, package, processors, allow_pretrain=False, maybe_add_mwt=True) Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/resources.md Resolves processor/package requests into a list of `[processor_name, [ModelSpecification, ...]]` pairs. Raises `ValueError` for invalid inputs and `UnknownProcessorError` for unknown processors. ```APIDOC ## [FUNCTION] maintain_processor_list(resources, lang, package, processors, allow_pretrain=False, maybe_add_mwt=True) ### Description Resolves processor/package requests into a list of `[processor_name, [ModelSpecification, ...]]` pairs. Raises `ValueError` for invalid inputs and `UnknownProcessorError` for unknown processors. ### Method Function call ### Parameters #### Parameters - **resources** (dict) - Required - The resources JSON. - **lang** (str) - Required - Language code. - **package** (str) - Required - Package name. - **processors** (dict) - Required - Processor → package (or list of packages) mapping. - **allow_pretrain** (bool) - Optional - Whether to allow pretrain processors. Default: `False`. - **maybe_add_mwt** (bool) - Optional - Whether to add MWT processor if needed. Default: `True`. ### Response #### Success Response Returns a list of `[processor_name, [ModelSpecification, ...]]` pairs. #### Error Handling Raises `ValueError` for non-string processor names or non-string/list values; raises `UnknownProcessorError` for unknown processors (unless `allow_pretrain` and the key is in `PRETRAIN_NAMES`). Unknown processor/package combinations produce a `logger.warning` and are ignored. ``` -------------------------------- ### Iterate over named entity mentions Source: https://github.com/stanfordnlp/stanza/blob/main/demo/Stanza_Beginners_Guide.ipynb Iterates over all extracted named entity mentions in an English Document, printing the mention text, entity type, and character span (start and end). Useful for inspecting NER annotations. ```python print("Mention text\tType\tStart-End") for ent in en_doc.ents: print("{}\t{}\t{}-{}".format(ent.text, ent.type, ent.start_char, ent.end_char)) ``` -------------------------------- ### Basic annotate usage with protobuf Document access Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/corenlp-client.md Creates a CoreNLPClient with specified annotators, memory, and timeout, then annotates a sentence and accesses the protobuf Document's token word. Requires a running CoreNLP server or starts one as a subprocess. ```python from stanza.server import CoreNLPClient with CoreNLPClient(annotators="tokenize,ssplit,pos,lemma,ner", memory="4G", timeout=30000) as client: ann = client.annotate("Barack Obama was born in Hawaii.") print(ann.sentence[0].token[0].word) # protobuf Document access ``` -------------------------------- ### Print a Word object as a dict Source: https://github.com/stanfordnlp/stanza/blob/main/demo/Stanza_Beginners_Guide.ipynb Prints a single Word object from the first sentence of an English Document, displaying all its annotations as a Python dict. Useful for quickly viewing all available word-level annotations. ```python word = en_doc.sentences[0].words[0] print(word) ``` -------------------------------- ### Iterate over English sentences and words Source: https://github.com/stanfordnlp/stanza/blob/main/demo/Stanza_Beginners_Guide.ipynb Iterates over all sentences and words in an English Document, printing word text, lemma, POS tag, head index, and dependency relation for each word. Useful for inspecting token-level annotations. ```python for i, sent in enumerate(en_doc.sentences): print("[Sentence {}]".format(i+1)) for word in sent.words: print("{:12s}\t{:12s}\t{:6s}\t{:d}\t{:12s}".format(\ word.text, word.lemma, word.pos, word.head, word.deprel)) print("") ``` -------------------------------- ### Iterate over Chinese sentences and words Source: https://github.com/stanfordnlp/stanza/blob/main/demo/Stanza_Beginners_Guide.ipynb Iterates over all sentences and words in a Chinese Document, printing word text, lemma, POS tag, head index, and dependency relation for each word. Useful for inspecting token-level annotations in Chinese text. ```python for i, sent in enumerate(zh_doc.sentences): print("[Sentence {}]".format(i+1)) for word in sent.words: print("{:12s}\t{:12s}\t{:6s}\t{:d}\t{:12s}".format(\ word.text, word.lemma, word.pos, word.head, word.deprel)) print("") ``` -------------------------------- ### Run Stanza neural pipeline Source: https://github.com/stanfordnlp/stanza/blob/main/README.md Sets up a default English neural pipeline, processes a sentence, and prints dependency relations. The pipeline can auto-download models if not pre-downloaded. ```python >>> import stanza >>> stanza.download('en') # Optional: pre-download English models (Pipeline can auto-download if needed) >>> nlp = stanza.Pipeline('en') # This sets up a default neural pipeline in English >>> doc = nlp("Barack Obama was born in Hawaii. He was elected president in 2008.") >>> doc.sentences[0].print_dependencies() ``` -------------------------------- ### Build English and Chinese pipelines with stanza.Pipeline Source: https://github.com/stanfordnlp/stanza/blob/main/demo/Stanza_Beginners_Guide.ipynb Construct a language-specific Pipeline. By default all processors are included; use the processors argument to customize. The pipeline is CUDA-aware and uses GPU when available; set use_gpu=False to force CPU. Set verbose=False to suppress logging. ```python # Build an English pipeline, with all processors by default print("Building an English pipeline...") en_nlp = stanza.Pipeline('en') # Build a Chinese pipeline, with customized processor list and no logging, and force it to use CPU print("Building a Chinese pipeline...") zh_nlp = stanza.Pipeline('zh', processors='tokenize,lemma,pos,depparse', verbose=False, use_gpu=False) ``` -------------------------------- ### NERTagger subclass of Annotator with run() Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/endpoints.md Example subclass implementing the required name, requires, provides, and annotate methods. The annotate method sets every token's ner field to "O". Running the script starts the HTTP server on the default host and port 8432, serving /ping/ and /annotate/ endpoints. ```python class NERTagger(Annotator): @property def name(self): return "nertagger" @property def requires(self): return {"tokenize", "ssplit", "pos"} @property def provides(self): return {"ner"} def annotate(self, ann): for sent in ann.sentence: for tok in sent.token: tok.ner = "O" def __init__(self, host="", port=8432): super().__init__(host=host, port=port) if __name__ == '__main__': NERTagger().run() # serves /ping/ and /annotate/ ``` -------------------------------- ### Run Stanza neural pipeline with proxy Source: https://github.com/stanfordnlp/stanza/blob/main/README.md Sets up the same pipeline but uses a proxy for downloading models, useful when encountering requests.exceptions.ConnectionError. ```python >>> import stanza >>> proxies = {'http': 'http://ip:port', 'https': 'http://ip:port'} >>> stanza.download('en', proxies=proxies) # Optional: pre-download English models (Pipeline can auto-download if needed) >>> nlp = stanza.Pipeline('en') # This sets up a default neural pipeline in English >>> doc = nlp("Barack Obama was born in Hawaii. He was elected president in 2008.") >>> doc.sentences[0].print_dependencies() ``` -------------------------------- ### ModelSpecification namedtuple definition Source: https://github.com/stanfordnlp/stanza/blob/main/_autodocs/api-reference/resources.md Defines a namedtuple for model specifications with fields processor, package, and dependencies. Used to describe model packages and their dependencies. ```python ModelSpecification = namedtuple('ModelSpecification', ['processor', 'package', 'dependencies']) # line 64 ```